-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathpackage.go
More file actions
269 lines (239 loc) · 7.5 KB
/
package.go
File metadata and controls
269 lines (239 loc) · 7.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package artifacthub
import (
"encoding/json"
"fmt"
"github.com/meshery/meshkit/utils"
"github.com/meshery/meshkit/utils/component"
"github.com/meshery/meshkit/utils/manifests"
"github.com/meshery/schemas/models/v1beta1/category"
_component "github.com/meshery/schemas/models/v1beta1/component"
"github.com/meshery/schemas/models/v1beta1/model"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"net/http"
"strings"
"time"
)
const ArtifactHubAPIEndpoint = "https://artifacthub.io/api/v1"
const ArtifactHubChartUrlFieldName = "content_url"
const AhHelmExporterEndpoint = ArtifactHubAPIEndpoint + "/helm-exporter"
// internal representation of artifacthub package
// it contains information we need to identify a package using ArtifactHub API
type AhPackage struct {
Name string `yaml:"name"`
Repository string `yaml:"repository"`
Organization string `yaml:"organization"`
RepoUrl string `yaml:"repo_url"`
ChartUrl string `yaml:"chart_url"`
Official bool `yaml:"official"`
VerifiedPublisher bool `yaml:"verified_publisher"`
CNCF bool `yaml:"cncf"`
Version string `yaml:"version"`
}
func (pkg AhPackage) GetVersion() string {
return pkg.Version
}
func (pkg AhPackage) GetSourceURL() string {
return pkg.ChartUrl
}
func (pkg AhPackage) GetName() string {
return pkg.Name
}
func (pkg AhPackage) GenerateComponents(group string) ([]_component.ComponentDefinition, error) {
components := make([]_component.ComponentDefinition, 0)
// TODO: Move this to the configuration
if pkg.ChartUrl == "" {
fmt.Printf("WARN: Skipping package %q due to empty chart URL\n", pkg.Name)
return components, nil
}
if strings.HasPrefix(pkg.ChartUrl, "oci://") {
// Skip OCI charts for now - return empty components
// TODO: Implement OCI chart support
return components, nil
}
crds, err := manifests.GetCrdsFromHelm(pkg.ChartUrl)
if err != nil {
return components, ErrComponentGenerate(err)
}
for _, crd := range crds {
comp, err := component.Generate(crd)
if err != nil {
continue
}
if comp.Model == nil {
comp.Model = &model.ModelDefinition{}
}
if comp.Model.Metadata == nil {
comp.Model.Metadata = &model.ModelDefinition_Metadata{}
}
if comp.Model.Metadata.AdditionalProperties == nil {
comp.Model.Metadata.AdditionalProperties = make(map[string]interface{})
}
comp.Model.Metadata.AdditionalProperties["source_uri"] = pkg.ChartUrl
comp.Model.Version = pkg.Version
comp.Model.Name = pkg.Name
comp.Model.Category = category.CategoryDefinition{
Name: "",
}
comp.Model.DisplayName = manifests.FormatToReadableString(comp.Model.Name)
components = append(components, comp)
}
return components, nil
}
// function that will take the AhPackage as input and give the helm chart url for that package
func (pkg *AhPackage) UpdatePackageData() error {
if pkg.ChartUrl != "" {
return nil
}
urlSuffix := "/index.yaml"
if strings.HasSuffix(pkg.RepoUrl, "/") {
urlSuffix = "index.yaml"
}
charts, err := utils.ReadRemoteFile(pkg.RepoUrl + urlSuffix)
if err != nil {
return ErrGetChartUrl(err)
}
var out map[string]interface{}
err = yaml.Unmarshal([]byte(charts), &out)
if err != nil {
return ErrGetChartUrl(err)
}
entries, ok := out["entries"].(map[interface{}]interface{})
if entries == nil || !ok {
return ErrGetChartUrl(fmt.Errorf("Cannot extract chartUrl from repository helm index"))
}
pkgEntry, ok := entries[pkg.Name]
if pkgEntry == nil || !ok {
return ErrGetChartUrl(fmt.Errorf("Cannot extract chartUrl from repository helm index"))
}
urls, ok := pkgEntry.([]interface{})[0].(map[interface{}]interface{})["urls"]
if urls == nil || !ok {
return ErrGetChartUrl(fmt.Errorf("Cannot extract chartUrl from repository helm index"))
}
chartUrl, ok := urls.([]interface{})[0].(string)
if !ok || chartUrl == "" {
return ErrGetChartUrl(fmt.Errorf("Cannot extract chartUrl from repository helm index"))
}
if strings.HasPrefix(chartUrl, "http") || strings.HasPrefix(chartUrl, "oci://") {
// URL is already complete (HTTP/HTTPS or OCI)
pkg.ChartUrl = chartUrl
} else {
// Relative URL, prepend the repository URL
if !strings.HasSuffix(pkg.RepoUrl, "/") {
pkg.RepoUrl = pkg.RepoUrl + "/"
}
pkg.ChartUrl = fmt.Sprintf("%s%s", pkg.RepoUrl, chartUrl)
}
pkg.ChartUrl = chartUrl
return nil
}
func (pkg *AhPackage) Validator() {
}
// GetAllAhHelmPackages returns a list of all AhPackages, using exponential backoff to handle rate limits.
func GetAllAhHelmPackages() ([]AhPackage, error) {
pkgs := make([]AhPackage, 0)
resp, err := http.Get(AhHelmExporterEndpoint)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
err = fmt.Errorf("status code %d for %s", resp.StatusCode, AhHelmExporterEndpoint)
return nil, ErrGetAllHelmPackages(err)
}
defer resp.Body.Close()
var res []map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&res)
if err != nil {
return nil, err
}
const maxRetries = 5
for _, p := range res {
name, ok := p["name"].(string)
if !ok {
logrus.WithFields(logrus.Fields{"package_data": p}).Warn("Skipping package due to missing or invalid name")
continue
}
repoMap, ok := p["repository"].(map[string]interface{})
if !ok {
logrus.WithFields(logrus.Fields{"package_data": p}).Warn("Skipping package due to missing or invalid repository")
continue
}
repo, ok := repoMap["name"].(string)
if !ok {
logrus.WithFields(logrus.Fields{"package_data": p}).Warn("Skipping package due to missing or invalid repository name")
continue
}
url := fmt.Sprintf("https://artifacthub.io/api/v1/packages/helm/%s/%s", repo, name)
var resp *http.Response
var err error
for i := 0; i < maxRetries; i++ {
resp, err = http.Get(url)
if err != nil {
break
}
if resp.StatusCode == 429 {
resp.Body.Close()
time.Sleep(time.Duration(1<<i) * time.Second)
continue
}
break
}
if err != nil {
logrus.WithError(err).WithField("url", url).Error("Failed to fetch package")
continue
}
if resp.StatusCode != 200 {
err = fmt.Errorf("status code %d for %s", resp.StatusCode, url)
logrus.WithError(err).WithField("url", url).Error("Failed to fetch package")
resp.Body.Close()
continue
}
var pkgRes map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&pkgRes)
resp.Body.Close()
if err != nil {
logrus.WithError(err).WithField("url", url).Error("Failed to decode package response")
continue
}
parsedPkg := parseArtifacthubResponse(pkgRes)
if parsedPkg != nil {
pkgs = append(pkgs, *parsedPkg)
}
}
return pkgs, nil
}
func parseArtifacthubResponse(response map[string]interface{}) *AhPackage {
verified := false
cncf := false
official := false
name, _ := response["name"].(string)
version, _ := response["version"].(string)
repository, ok := response["repository"].(map[string]interface{})
var repoName, repoURL string
if ok {
if repository["name"] != nil {
repoName = repository["name"].(string)
}
if repository["verified_publisher"] != nil {
verified = repository["verified_publisher"].(bool)
}
if repository["official"] != nil {
official = repository["official"].(bool)
}
if repository["cncf"] != nil {
cncf = response["repository"].(map[string]interface{})["cncf"].(bool)
}
if repository["url"] != nil {
repoURL = repository["url"].(string)
}
}
return &AhPackage{
Name: name,
Version: version,
Repository: repoName,
RepoUrl: repoURL,
VerifiedPublisher: verified,
CNCF: cncf,
Official: official,
}
}