-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
client.go
500 lines (433 loc) · 15 KB
/
client.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
package helm
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"time"
executil "github.com/argoproj/argo-cd/v2/util/exec"
"github.com/argoproj/pkg/sync"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"oras.land/oras-go/v2/registry/remote"
"oras.land/oras-go/v2/registry/remote/auth"
"oras.land/oras-go/v2/registry/remote/credentials"
"github.com/argoproj/argo-cd/v2/util/cache"
argoio "github.com/argoproj/argo-cd/v2/util/io"
"github.com/argoproj/argo-cd/v2/util/io/files"
"github.com/argoproj/argo-cd/v2/util/proxy"
)
var (
globalLock = sync.NewKeyLock()
indexLock = sync.NewKeyLock()
OCINotEnabledErr = errors.New("could not perform the action when oci is not enabled")
)
type Creds struct {
Username string
Password string
CAPath string
CertData []byte
KeyData []byte
InsecureSkipVerify bool
}
type indexCache interface {
SetHelmIndex(repo string, indexData []byte) error
GetHelmIndex(repo string, indexData *[]byte) error
}
type Client interface {
CleanChartCache(chart string, version string, project string) error
ExtractChart(chart string, version string, project string, passCredentials bool, manifestMaxExtractedSize int64, disableManifestMaxExtractedSize bool) (string, argoio.Closer, error)
GetIndex(noCache bool, maxIndexSize int64) (*Index, error)
GetTags(chart string, noCache bool) (*TagsList, error)
TestHelmOCI() (bool, error)
}
type ClientOpts func(c *nativeHelmChart)
func WithIndexCache(indexCache indexCache) ClientOpts {
return func(c *nativeHelmChart) {
c.indexCache = indexCache
}
}
func WithChartPaths(chartPaths argoio.TempPaths) ClientOpts {
return func(c *nativeHelmChart) {
c.chartCachePaths = chartPaths
}
}
func NewClient(repoURL string, creds Creds, enableOci bool, proxy string, noProxy string, opts ...ClientOpts) Client {
return NewClientWithLock(repoURL, creds, globalLock, enableOci, proxy, noProxy, opts...)
}
func NewClientWithLock(repoURL string, creds Creds, repoLock sync.KeyLock, enableOci bool, proxy string, noProxy string, opts ...ClientOpts) Client {
c := &nativeHelmChart{
repoURL: repoURL,
creds: creds,
repoLock: repoLock,
enableOci: enableOci,
proxy: proxy,
noProxy: noProxy,
chartCachePaths: argoio.NewRandomizedTempPaths(os.TempDir()),
}
for i := range opts {
opts[i](c)
}
return c
}
var _ Client = &nativeHelmChart{}
type nativeHelmChart struct {
chartCachePaths argoio.TempPaths
repoURL string
creds Creds
repoLock sync.KeyLock
enableOci bool
indexCache indexCache
proxy string
noProxy string
}
func fileExist(filePath string) (bool, error) {
if _, err := os.Stat(filePath); err != nil {
if os.IsNotExist(err) {
return false, nil
} else {
return false, fmt.Errorf("error checking file existence for %s: %w", filePath, err)
}
}
return true, nil
}
func (c *nativeHelmChart) CleanChartCache(chart string, version string, project string) error {
cachePath, err := c.getCachedChartPath(chart, version, project)
if err != nil {
return fmt.Errorf("error getting cached chart path: %w", err)
}
if err := os.RemoveAll(cachePath); err != nil {
return fmt.Errorf("error removing chart cache at %s: %w", cachePath, err)
}
return nil
}
func untarChart(tempDir string, cachedChartPath string, manifestMaxExtractedSize int64, disableManifestMaxExtractedSize bool) error {
if disableManifestMaxExtractedSize {
cmd := exec.Command("tar", "-zxvf", cachedChartPath)
cmd.Dir = tempDir
_, err := executil.Run(cmd)
if err != nil {
return fmt.Errorf("error executing tar command: %w", err)
}
return nil
}
reader, err := os.Open(cachedChartPath)
if err != nil {
return fmt.Errorf("error opening cached chart path %s: %w", cachedChartPath, err)
}
return files.Untgz(tempDir, reader, manifestMaxExtractedSize, false)
}
func (c *nativeHelmChart) ExtractChart(chart string, version string, project string, passCredentials bool, manifestMaxExtractedSize int64, disableManifestMaxExtractedSize bool) (string, argoio.Closer, error) {
// always use Helm V3 since we don't have chart content to determine correct Helm version
helmCmd, err := NewCmdWithVersion("", c.enableOci, c.proxy, c.noProxy)
if err != nil {
return "", nil, fmt.Errorf("error creating Helm command: %w", err)
}
defer helmCmd.Close()
// throw away temp directory that stores extracted chart and should be deleted as soon as no longer needed by returned closer
tempDir, err := files.CreateTempDir(os.TempDir())
if err != nil {
return "", nil, fmt.Errorf("error creating temporary directory: %w", err)
}
cachedChartPath, err := c.getCachedChartPath(chart, version, project)
if err != nil {
_ = os.RemoveAll(tempDir)
return "", nil, fmt.Errorf("error getting cached chart path: %w", err)
}
c.repoLock.Lock(cachedChartPath)
defer c.repoLock.Unlock(cachedChartPath)
// check if chart tar is already downloaded
exists, err := fileExist(cachedChartPath)
if err != nil {
_ = os.RemoveAll(tempDir)
return "", nil, fmt.Errorf("error checking existence of cached chart path: %w", err)
}
if !exists {
// create empty temp directory to extract chart from the registry
tempDest, err := files.CreateTempDir(os.TempDir())
if err != nil {
_ = os.RemoveAll(tempDir)
return "", nil, fmt.Errorf("error creating temporary destination directory: %w", err)
}
defer func() { _ = os.RemoveAll(tempDest) }()
if c.enableOci {
if c.creds.Password != "" && c.creds.Username != "" {
_, err = helmCmd.RegistryLogin(c.repoURL, c.creds)
if err != nil {
_ = os.RemoveAll(tempDir)
return "", nil, fmt.Errorf("error logging into OCI registry: %w", err)
}
defer func() {
_, _ = helmCmd.RegistryLogout(c.repoURL, c.creds)
}()
}
// 'helm pull' ensures that chart is downloaded into temp directory
_, err = helmCmd.PullOCI(c.repoURL, chart, version, tempDest, c.creds)
if err != nil {
_ = os.RemoveAll(tempDir)
return "", nil, fmt.Errorf("error pulling OCI chart: %w", err)
}
} else {
_, err = helmCmd.Fetch(c.repoURL, chart, version, tempDest, c.creds, passCredentials)
if err != nil {
_ = os.RemoveAll(tempDir)
return "", nil, fmt.Errorf("error fetching chart: %w", err)
}
}
// 'helm pull/fetch' file downloads chart into the tgz file and we move that to where we want it
infos, err := os.ReadDir(tempDest)
if err != nil {
return "", nil, fmt.Errorf("error reading directory %s: %w", tempDest, err)
}
if len(infos) != 1 {
return "", nil, fmt.Errorf("expected 1 file, found %v", len(infos))
}
chartFilePath := filepath.Join(tempDest, infos[0].Name())
err = os.Rename(chartFilePath, cachedChartPath)
if err != nil {
return "", nil, fmt.Errorf("error renaming file from %s to %s: %w", chartFilePath, cachedChartPath, err)
}
}
err = untarChart(tempDir, cachedChartPath, manifestMaxExtractedSize, disableManifestMaxExtractedSize)
if err != nil {
_ = os.RemoveAll(tempDir)
return "", nil, fmt.Errorf("error untarring chart: %w", err)
}
return path.Join(tempDir, normalizeChartName(chart)), argoio.NewCloser(func() error {
return os.RemoveAll(tempDir)
}), nil
}
func (c *nativeHelmChart) GetIndex(noCache bool, maxIndexSize int64) (*Index, error) {
indexLock.Lock(c.repoURL)
defer indexLock.Unlock(c.repoURL)
var data []byte
if !noCache && c.indexCache != nil {
if err := c.indexCache.GetHelmIndex(c.repoURL, &data); err != nil && !errors.Is(err, cache.ErrCacheMiss) {
log.Warnf("Failed to load index cache for repo: %s: %v", c.repoURL, err)
}
}
if len(data) == 0 {
start := time.Now()
var err error
data, err = c.loadRepoIndex(maxIndexSize)
if err != nil {
return nil, fmt.Errorf("error loading repo index: %w", err)
}
log.WithFields(log.Fields{"seconds": time.Since(start).Seconds()}).Info("took to get index")
if c.indexCache != nil {
if err := c.indexCache.SetHelmIndex(c.repoURL, data); err != nil {
log.Warnf("Failed to store index cache for repo: %s: %v", c.repoURL, err)
}
}
}
index := &Index{}
err := yaml.NewDecoder(bytes.NewBuffer(data)).Decode(index)
if err != nil {
return nil, fmt.Errorf("error decoding index: %w", err)
}
return index, nil
}
func (c *nativeHelmChart) TestHelmOCI() (bool, error) {
start := time.Now()
tmpDir, err := os.MkdirTemp("", "helm")
if err != nil {
return false, fmt.Errorf("error creating temporary directory: %w", err)
}
defer func() { _ = os.RemoveAll(tmpDir) }()
helmCmd, err := NewCmdWithVersion(tmpDir, c.enableOci, c.proxy, c.noProxy)
if err != nil {
return false, fmt.Errorf("error creating Helm command: %w", err)
}
defer helmCmd.Close()
// Looks like there is no good way to test access to OCI repo if credentials are not provided
// just assume it is accessible
if c.creds.Username != "" && c.creds.Password != "" {
_, err = helmCmd.RegistryLogin(c.repoURL, c.creds)
if err != nil {
return false, fmt.Errorf("error logging into OCI registry: %w", err)
}
defer func() {
_, _ = helmCmd.RegistryLogout(c.repoURL, c.creds)
}()
log.WithFields(log.Fields{"seconds": time.Since(start).Seconds()}).Info("took to test helm oci repository")
}
return true, nil
}
func (c *nativeHelmChart) loadRepoIndex(maxIndexSize int64) ([]byte, error) {
indexURL, err := getIndexURL(c.repoURL)
if err != nil {
return nil, fmt.Errorf("error getting index URL: %w", err)
}
req, err := http.NewRequest(http.MethodGet, indexURL, nil)
if err != nil {
return nil, fmt.Errorf("error creating HTTP request: %w", err)
}
if c.creds.Username != "" || c.creds.Password != "" {
// only basic supported
req.SetBasicAuth(c.creds.Username, c.creds.Password)
}
tlsConf, err := newTLSConfig(c.creds)
if err != nil {
return nil, fmt.Errorf("error creating TLS config: %w", err)
}
tr := &http.Transport{
Proxy: proxy.GetCallback(c.proxy, c.noProxy),
TLSClientConfig: tlsConf,
DisableKeepAlives: true,
}
client := http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("error making HTTP request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, errors.New("failed to get index: " + resp.Status)
}
return io.ReadAll(io.LimitReader(resp.Body, maxIndexSize))
}
func newTLSConfig(creds Creds) (*tls.Config, error) {
tlsConfig := &tls.Config{InsecureSkipVerify: creds.InsecureSkipVerify}
if creds.CAPath != "" {
caData, err := os.ReadFile(creds.CAPath)
if err != nil {
return nil, fmt.Errorf("error reading CA file %s: %w", creds.CAPath, err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caData)
tlsConfig.RootCAs = caCertPool
}
// If a client cert & key is provided then configure TLS config accordingly.
if len(creds.CertData) > 0 && len(creds.KeyData) > 0 {
cert, err := tls.X509KeyPair(creds.CertData, creds.KeyData)
if err != nil {
return nil, fmt.Errorf("error creating X509 key pair: %w", err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
// nolint:staticcheck
tlsConfig.BuildNameToCertificate()
return tlsConfig, nil
}
// Normalize a chart name for file system use, that is, if chart name is foo/bar/baz, returns the last component as chart name.
func normalizeChartName(chart string) string {
strings.Join(strings.Split(chart, "/"), "_")
_, nc := path.Split(chart)
// We do not want to return the empty string or something else related to filesystem access
// Instead, return original string
if nc == "" || nc == "." || nc == ".." {
return chart
}
return nc
}
func (c *nativeHelmChart) getCachedChartPath(chart string, version string, project string) (string, error) {
keyData, err := json.Marshal(map[string]string{"url": c.repoURL, "chart": chart, "version": version, "project": project})
if err != nil {
return "", fmt.Errorf("error marshaling cache key data: %w", err)
}
return c.chartCachePaths.GetPath(string(keyData))
}
// Ensures that given OCI registries URL does not have protocol
func IsHelmOciRepo(repoURL string) bool {
if repoURL == "" {
return false
}
parsed, err := url.Parse(repoURL)
// the URL parser treat hostname as either path or opaque if scheme is not specified, so hostname must be empty
return err == nil && parsed.Host == ""
}
func getIndexURL(rawURL string) (string, error) {
indexFile := "index.yaml"
repoURL, err := url.Parse(rawURL)
if err != nil {
return "", fmt.Errorf("error parsing repository URL: %w", err)
}
repoURL.Path = path.Join(repoURL.Path, indexFile)
repoURL.RawPath = path.Join(repoURL.RawPath, indexFile)
return repoURL.String(), nil
}
func (c *nativeHelmChart) GetTags(chart string, noCache bool) (*TagsList, error) {
if !c.enableOci {
return nil, OCINotEnabledErr
}
tagsURL := strings.Replace(fmt.Sprintf("%s/%s", c.repoURL, chart), "https://", "", 1)
indexLock.Lock(tagsURL)
defer indexLock.Unlock(tagsURL)
var data []byte
if !noCache && c.indexCache != nil {
if err := c.indexCache.GetHelmIndex(tagsURL, &data); err != nil && !errors.Is(err, cache.ErrCacheMiss) {
log.Warnf("Failed to load index cache for repo: %s: %v", tagsURL, err)
}
}
tags := &TagsList{}
if len(data) == 0 {
start := time.Now()
repo, err := remote.NewRepository(tagsURL)
if err != nil {
return nil, fmt.Errorf("failed to initialize repository: %w", err)
}
tlsConf, err := newTLSConfig(c.creds)
if err != nil {
return nil, fmt.Errorf("failed setup tlsConfig: %w", err)
}
client := &http.Client{Transport: &http.Transport{
Proxy: proxy.GetCallback(c.proxy, c.noProxy),
TLSClientConfig: tlsConf,
DisableKeepAlives: true,
}}
repoHost, _, _ := strings.Cut(tagsURL, "/")
credential := auth.StaticCredential(repoHost, auth.Credential{
Username: c.creds.Username,
Password: c.creds.Password,
})
// Try to fallback to the environment config, but we shouldn't error if the file is not set
if c.creds.Username == "" && c.creds.Password == "" {
store, _ := credentials.NewStoreFromDocker(credentials.StoreOptions{})
if store != nil {
credential = credentials.Credential(store)
}
}
repo.Client = &auth.Client{
Client: client,
Cache: nil,
Credential: credential,
}
ctx := context.Background()
err = repo.Tags(ctx, "", func(tagsResult []string) error {
for _, tag := range tagsResult {
// By convention: Change underscore (_) back to plus (+) to get valid SemVer
convertedTag := strings.ReplaceAll(tag, "_", "+")
tags.Tags = append(tags.Tags, convertedTag)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("failed to get tags: %w", err)
}
log.WithFields(
log.Fields{"seconds": time.Since(start).Seconds(), "chart": chart, "repo": c.repoURL},
).Info("took to get tags")
if c.indexCache != nil {
if err := c.indexCache.SetHelmIndex(tagsURL, data); err != nil {
log.Warnf("Failed to store tags list cache for repo: %s: %v", tagsURL, err)
}
}
} else {
err := json.Unmarshal(data, tags)
if err != nil {
return nil, fmt.Errorf("failed to decode tags: %w", err)
}
}
return tags, nil
}