-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
308 lines (286 loc) · 7.06 KB
/
main.go
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
"github.com/google/go-github/v45/github"
"github.com/wandera/helm-github/helm"
"golang.org/x/oauth2"
"sigs.k8s.io/yaml"
)
const (
protocol = "github"
githubHost = "github.com"
indexFilename = "index.yaml"
annotationDownloaded = "wandera.com/helm-github/downloaded"
indexCacheDuration = 60 * time.Second
timeout = 30 * time.Second
)
var (
client *github.Client
cacheDirBase string
chartsCacheDir string
)
func init() {
if env, ok := os.LookupEnv("HELMGITHUB_DEBUG_LOG"); ok {
t, err := os.OpenFile(env, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
log.Panic(err)
}
log.SetOutput(t)
}
token, err := loadGithubToken()
if err != nil {
log.Panic(err)
}
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(context.Background(), ts)
client = github.NewClient(tc)
cacheDirBase = getCacheDirBase()
chartsCacheDir = getChartCacheDir()
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if len(os.Args) == 5 {
uri := strings.TrimPrefix(os.Args[4], protocol+"://")
if strings.HasSuffix(uri, indexFilename) {
file, ok := getCachedIndexFile(uri)
if ok && file.Annotations != nil {
parsed, err := time.Parse(time.RFC3339, file.Annotations[annotationDownloaded])
if err == nil && time.Since(parsed) < indexCacheDuration {
bytes, err := yaml.Marshal(&file)
if err != nil {
log.Panic(err)
}
fmt.Println(string(bytes))
return
}
}
file, err := fetchIndexFile(ctx, uri)
if err != nil {
log.Panic(err)
}
file = switchProtocolToGithub(file)
file.SortEntries()
if file.Annotations == nil {
file.Annotations = make(map[string]string)
}
file.Annotations[annotationDownloaded] = time.Now().Format(time.RFC3339)
bytes, err := yaml.Marshal(&file)
if err != nil {
log.Panic(err)
}
fmt.Println(string(bytes))
} else {
cacheFile, err := openCacheFile(uri)
if err != nil {
log.Panic(err)
}
defer cacheFile.Close()
if validateDigest(getArchiveDigest(uri), cacheFile.Name()) {
_, err := io.Copy(os.Stdout, cacheFile)
if err != nil {
log.Panic(err)
}
} else {
cacheFile.Truncate(0)
cacheFile.Seek(0, 0)
resp, err := fetchArchive(ctx, uri)
if err != nil {
_ = os.Remove(cacheFile.Name())
log.Panic(err)
}
defer resp.Close()
_, err = io.Copy(io.MultiWriter(os.Stdout, cacheFile), resp)
if err != nil {
_ = os.Remove(cacheFile.Name())
log.Panic(err)
}
}
}
}
}
func getArchiveDigest(uri string) string {
idx, ok := getCachedIndexFile(uri)
if !ok {
return ""
}
for _, versions := range idx.Entries {
for _, version := range versions {
for _, u := range version.URLs {
if strings.HasSuffix(u, uri) {
return version.Digest
}
}
}
}
return ""
}
func getCachedIndexFile(uri string) (helm.IndexFile, bool) {
_, r := parseOwnerRepository(uri)
bytes, err := os.ReadFile(path.Join(cacheDirBase, r+"-index.yaml"))
if err != nil {
return helm.IndexFile{}, false
}
idx := helm.IndexFile{}
if err := yaml.Unmarshal(bytes, &idx); err != nil {
return helm.IndexFile{}, false
}
return idx, true
}
func validateDigest(digest string, fileName string) bool {
df, err := helm.DigestFile(fileName)
if err != nil {
log.Panic(err)
}
return digest == df
}
func loadGithubToken() (string, error) {
if env, ok := os.LookupEnv("GITHUB_TOKEN"); ok {
return env, nil
}
if env, ok := os.LookupEnv("GIT_ASKPASS"); ok {
f, err := os.Open(env)
if err != nil {
return "", err
}
bytes, err := io.ReadAll(f)
if err != nil {
return "", err
}
return string(bytes), nil
}
return "", fmt.Errorf("github token not found")
}
func getIndexBranch() string {
if env, ok := os.LookupEnv("HELMGITHUB_INDEX_BRANCH"); ok {
return env
}
return "gh-pages"
}
func getChartCacheDir() string {
dir := getCacheDirBase()
dir = path.Join(dir, "github", "chart")
if err := os.MkdirAll(dir, 0o777); err != nil {
log.Panic(err)
}
return dir
}
func getCacheDirBase() string {
var dir string
if env, ok := os.LookupEnv("HELM_REPOSITORY_CACHE"); ok {
dir = env
} else {
ucd, err := os.UserCacheDir()
if err != nil {
log.Panic(err)
}
dir = ucd
}
return dir
}
func fetchIndexFile(ctx context.Context, uri string) (helm.IndexFile, error) {
owner, repository := parseOwnerRepository(uri)
contents, _, _, err := client.Repositories.GetContents(ctx, owner, repository, indexFilename, &github.RepositoryContentGetOptions{Ref: getIndexBranch()})
if err != nil {
return helm.IndexFile{}, err
}
decoded, err := contents.GetContent()
if err != nil {
return helm.IndexFile{}, err
}
file := helm.IndexFile{}
err = yaml.UnmarshalStrict([]byte(decoded), &file)
if err != nil {
return helm.IndexFile{}, err
}
return file, nil
}
func openCacheFile(uri string) (*os.File, error) {
artifactName := parseArtifactName(uri)
chartPath := path.Join(chartsCacheDir, artifactName+".tgz")
_, err := os.Stat(chartPath)
if err != nil {
create, err := os.Create(chartPath)
if err != nil {
return nil, err
}
return create, nil
}
open, err := os.OpenFile(chartPath, os.O_RDWR, 0o666)
if err != nil {
return nil, err
}
return open, nil
}
func fetchArchive(ctx context.Context, uri string) (io.ReadCloser, error) {
owner, repository := parseOwnerRepository(uri)
tag := parseArtifactName(uri)
release, _, err := client.Repositories.GetReleaseByTag(ctx, owner, repository, tag)
if err != nil {
return nil, err
}
for _, asset := range release.Assets {
if strings.HasSuffix(asset.GetBrowserDownloadURL(), uri) {
rc, _, err := client.Repositories.DownloadReleaseAsset(ctx, owner, repository, asset.GetID(), http.DefaultClient)
if err != nil {
return nil, err
}
return rc, nil
}
}
return nil, fmt.Errorf("asset '%s' not found", uri)
}
func switchProtocolToGithub(file helm.IndexFile) helm.IndexFile {
for name, versions := range file.Entries {
file.Entries[name] = mapFunc(versions, func(chart helm.ChartVersion) helm.ChartVersion {
chart.URLs = mapFunc(chart.URLs, mapGithubURL)
return chart
})
}
return file
}
func parseOwnerRepository(uri string) (string, string) {
uri = strings.TrimPrefix(uri, githubHost)
uri = strings.TrimLeft(uri, "/")
parsed, err := url.Parse(uri)
if err != nil {
return "", ""
}
seps := strings.Split(parsed.Path, "/")
if len(seps) >= 2 {
return seps[0], seps[1]
}
return "", ""
}
func parseArtifactName(uri string) string {
return uri[strings.LastIndex(uri, "/")+1 : strings.LastIndex(uri, ".")]
}
func mapGithubURL(urlString string) string {
parse, err := url.Parse(urlString)
if err != nil {
panic(err)
}
if (parse.Scheme == "https" || parse.Scheme == "http") && parse.Host == githubHost {
parse.Scheme = protocol
return parse.String()
}
return urlString
}
func mapFunc[T any, R any](in []T, f func(T) R) []R {
ret := make([]R, len(in))
for i, t := range in {
ret[i] = f(t)
}
return ret
}