-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
repository.go
1539 lines (1368 loc) · 50.1 KB
/
repository.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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package repository
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/Masterminds/semver"
"github.com/TomOnTime/utfutil"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
textutils "github.com/argoproj/gitops-engine/pkg/utils/text"
"github.com/argoproj/pkg/sync"
jsonpatch "github.com/evanphx/json-patch"
"github.com/ghodss/yaml"
"github.com/google/go-jsonnet"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/semaphore"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"github.com/argoproj/argo-cd/v2/common"
"github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/argoproj/argo-cd/v2/reposerver/apiclient"
"github.com/argoproj/argo-cd/v2/reposerver/cache"
reposervercache "github.com/argoproj/argo-cd/v2/reposerver/cache"
"github.com/argoproj/argo-cd/v2/reposerver/metrics"
"github.com/argoproj/argo-cd/v2/util/app/discovery"
argopath "github.com/argoproj/argo-cd/v2/util/app/path"
executil "github.com/argoproj/argo-cd/v2/util/exec"
"github.com/argoproj/argo-cd/v2/util/git"
"github.com/argoproj/argo-cd/v2/util/glob"
"github.com/argoproj/argo-cd/v2/util/gpg"
"github.com/argoproj/argo-cd/v2/util/helm"
"github.com/argoproj/argo-cd/v2/util/io"
pathutil "github.com/argoproj/argo-cd/v2/util/io/path"
"github.com/argoproj/argo-cd/v2/util/ksonnet"
argokube "github.com/argoproj/argo-cd/v2/util/kube"
"github.com/argoproj/argo-cd/v2/util/kustomize"
"github.com/argoproj/argo-cd/v2/util/text"
)
const (
cachedManifestGenerationPrefix = "Manifest generation error (cached)"
helmDepUpMarkerFile = ".argocd-helm-dep-up"
allowConcurrencyFile = ".argocd-allow-concurrency"
repoSourceFile = ".argocd-source.yaml"
appSourceFile = ".argocd-source-%s.yaml"
ociPrefix = "oci://"
)
// Service implements ManifestService interface
type Service struct {
repoLock *repositoryLock
cache *reposervercache.Cache
parallelismLimitSemaphore *semaphore.Weighted
metricsServer *metrics.MetricsServer
newGitClient func(rawRepoURL string, creds git.Creds, insecure bool, enableLfs bool, proxy string, opts ...git.ClientOpts) (git.Client, error)
newHelmClient func(repoURL string, creds helm.Creds, enableOci bool, proxy string, opts ...helm.ClientOpts) helm.Client
initConstants RepoServerInitConstants
// now is usually just time.Now, but may be replaced by unit tests for testing purposes
now func() time.Time
}
type RepoServerInitConstants struct {
ParallelismLimit int64
PauseGenerationAfterFailedGenerationAttempts int
PauseGenerationOnFailureForMinutes int
PauseGenerationOnFailureForRequests int
}
// NewService returns a new instance of the Manifest service
func NewService(metricsServer *metrics.MetricsServer, cache *reposervercache.Cache, initConstants RepoServerInitConstants) *Service {
var parallelismLimitSemaphore *semaphore.Weighted
if initConstants.ParallelismLimit > 0 {
parallelismLimitSemaphore = semaphore.NewWeighted(initConstants.ParallelismLimit)
}
repoLock := NewRepositoryLock()
return &Service{
parallelismLimitSemaphore: parallelismLimitSemaphore,
repoLock: repoLock,
cache: cache,
metricsServer: metricsServer,
newGitClient: git.NewClient,
newHelmClient: func(repoURL string, creds helm.Creds, enableOci bool, proxy string, opts ...helm.ClientOpts) helm.Client {
return helm.NewClientWithLock(repoURL, creds, sync.NewKeyLock(), enableOci, proxy, opts...)
},
initConstants: initConstants,
now: time.Now,
}
}
// List a subset of the refs (currently, branches and tags) of a git repo
func (s *Service) ListRefs(ctx context.Context, q *apiclient.ListRefsRequest) (*apiclient.Refs, error) {
gitClient, err := s.newClient(q.Repo)
if err != nil {
return nil, err
}
s.metricsServer.IncPendingRepoRequest(q.Repo.Repo)
defer s.metricsServer.DecPendingRepoRequest(q.Repo.Repo)
refs, err := gitClient.LsRefs()
if err != nil {
return nil, err
}
res := apiclient.Refs{
Branches: refs.Branches,
Tags: refs.Tags,
}
return &res, nil
}
// ListApps lists the contents of a GitHub repo
func (s *Service) ListApps(ctx context.Context, q *apiclient.ListAppsRequest) (*apiclient.AppList, error) {
gitClient, commitSHA, err := s.newClientResolveRevision(q.Repo, q.Revision)
if err != nil {
return nil, err
}
if apps, err := s.cache.ListApps(q.Repo.Repo, commitSHA); err == nil {
log.Infof("cache hit: %s/%s", q.Repo.Repo, q.Revision)
return &apiclient.AppList{Apps: apps}, nil
}
s.metricsServer.IncPendingRepoRequest(q.Repo.Repo)
defer s.metricsServer.DecPendingRepoRequest(q.Repo.Repo)
closer, err := s.repoLock.Lock(gitClient.Root(), commitSHA, true, func() error {
return checkoutRevision(gitClient, commitSHA)
})
if err != nil {
return nil, err
}
defer io.Close(closer)
apps, err := discovery.Discover(gitClient.Root())
if err != nil {
return nil, err
}
err = s.cache.SetApps(q.Repo.Repo, commitSHA, apps)
if err != nil {
log.Warnf("cache set error %s/%s: %v", q.Repo.Repo, commitSHA, err)
}
res := apiclient.AppList{Apps: apps}
return &res, nil
}
type operationSettings struct {
sem *semaphore.Weighted
noCache bool
noRevisionCache bool
allowConcurrent bool
}
// operationContext contains request values which are generated by runRepoOperation (on demand) by a call to the
// provided operationContextSrc function.
type operationContext struct {
// application path or helm chart path
appPath string
// output of 'git verify-(tag/commit)', if signature verification is enabled (otherwise "")
verificationResult string
}
// The 'operation' function parameter of 'runRepoOperation' may call this function to retrieve
// the appPath or GPG verificationResult.
// Failure to generate either of these values will return an error which may be cached by
// the calling function (for example, 'runManifestGen')
type operationContextSrc = func() (*operationContext, error)
// runRepoOperation downloads either git folder or helm chart and executes specified operation
// - Returns a value from the cache if present (by calling getCached(...)); if no value is present, the
// provide operation(...) is called. The specific return type of this function is determined by the
// calling function, via the provided getCached(...) and operation(...) function.
func (s *Service) runRepoOperation(
ctx context.Context,
revision string,
repo *v1alpha1.Repository,
source *v1alpha1.ApplicationSource,
verifyCommit bool,
cacheFn func(cacheKey string, firstInvocation bool) (bool, error),
operation func(repoRoot, commitSHA, cacheKey string, ctxSrc operationContextSrc) error,
settings operationSettings) error {
var gitClient git.Client
var helmClient helm.Client
var err error
revision = textutils.FirstNonEmpty(revision, source.TargetRevision)
if source.IsHelm() {
helmClient, revision, err = s.newHelmClientResolveRevision(repo, revision, source.Chart, settings.noCache || settings.noRevisionCache)
if err != nil {
return err
}
} else {
gitClient, revision, err = s.newClientResolveRevision(repo, revision, git.WithCache(s.cache, !settings.noRevisionCache && !settings.noCache))
if err != nil {
return err
}
}
if !settings.noCache {
if ok, err := cacheFn(revision, true); ok {
return err
}
}
s.metricsServer.IncPendingRepoRequest(repo.Repo)
defer s.metricsServer.DecPendingRepoRequest(repo.Repo)
if settings.sem != nil {
err = settings.sem.Acquire(ctx, 1)
if err != nil {
return err
}
defer settings.sem.Release(1)
}
if source.IsHelm() {
if settings.noCache {
err = helmClient.CleanChartCache(source.Chart, revision)
if err != nil {
return err
}
}
chartPath, closer, err := helmClient.ExtractChart(source.Chart, revision)
if err != nil {
return err
}
defer io.Close(closer)
return operation(chartPath, revision, revision, func() (*operationContext, error) {
return &operationContext{chartPath, ""}, nil
})
} else {
closer, err := s.repoLock.Lock(gitClient.Root(), revision, settings.allowConcurrent, func() error {
return checkoutRevision(gitClient, revision)
})
if err != nil {
return err
}
defer io.Close(closer)
commitSHA, err := gitClient.CommitSHA()
if err != nil {
return err
}
// double-check locking
if !settings.noCache {
if ok, err := cacheFn(revision, false); ok {
return err
}
}
// Here commitSHA refers to the SHA of the actual commit, whereas revision refers to the branch/tag name etc
// We use the commitSHA to generate manifests and store them in cache, and revision to retrieve them from cache
return operation(gitClient.Root(), commitSHA, revision, func() (*operationContext, error) {
var signature string
if verifyCommit {
signature, err = gitClient.VerifyCommitSignature(revision)
if err != nil {
return nil, err
}
}
appPath, err := argopath.Path(gitClient.Root(), source.Path)
if err != nil {
return nil, err
}
return &operationContext{appPath, signature}, nil
})
}
}
func (s *Service) GenerateManifest(ctx context.Context, q *apiclient.ManifestRequest) (*apiclient.ManifestResponse, error) {
var res *apiclient.ManifestResponse
var err error
cacheFn := func(cacheKey string, firstInvocation bool) (bool, error) {
ok, resp, err := s.getManifestCacheEntry(cacheKey, q, firstInvocation)
res = resp
return ok, err
}
operation := func(repoRoot, commitSHA, cacheKey string, ctxSrc operationContextSrc) error {
res, err = s.runManifestGen(repoRoot, commitSHA, cacheKey, ctxSrc, q)
return err
}
settings := operationSettings{sem: s.parallelismLimitSemaphore, noCache: q.NoCache, noRevisionCache: q.NoRevisionCache, allowConcurrent: q.ApplicationSource.AllowsConcurrentProcessing()}
err = s.runRepoOperation(ctx, q.Revision, q.Repo, q.ApplicationSource, q.VerifySignature, cacheFn, operation, settings)
return res, err
}
// runManifestGen will be called by runRepoOperation if:
// - the cache does not contain a value for this key
// - or, the cache does contain a value for this key, but it is an expired manifest generation entry
// - or, NoCache is true
// Returns a ManifestResponse, or an error, but not both
func (s *Service) runManifestGen(repoRoot, commitSHA, cacheKey string, ctxSrc operationContextSrc, q *apiclient.ManifestRequest) (*apiclient.ManifestResponse, error) {
var manifestGenResult *apiclient.ManifestResponse
ctx, err := ctxSrc()
if err == nil {
manifestGenResult, err = GenerateManifests(ctx.appPath, repoRoot, commitSHA, q, false)
}
if err != nil {
// If manifest generation error caching is enabled
if s.initConstants.PauseGenerationAfterFailedGenerationAttempts > 0 {
// Retrieve a new copy (if available) of the cached response: this ensures we are updating the latest copy of the cache,
// rather than a copy of the cache that occurred before (a potentially lengthy) manifest generation.
innerRes := &cache.CachedManifestResponse{}
cacheErr := s.cache.GetManifests(cacheKey, q.ApplicationSource, q, q.Namespace, q.AppLabelKey, q.AppName, innerRes)
if cacheErr != nil && cacheErr != reposervercache.ErrCacheMiss {
log.Warnf("manifest cache set error %s: %v", q.ApplicationSource.String(), cacheErr)
return nil, cacheErr
}
// If this is the first error we have seen, store the time (we only use the first failure, as this
// value is used for PauseGenerationOnFailureForMinutes)
if innerRes.FirstFailureTimestamp == 0 {
innerRes.FirstFailureTimestamp = s.now().Unix()
}
// Update the cache to include failure information
innerRes.NumberOfConsecutiveFailures++
innerRes.MostRecentError = err.Error()
cacheErr = s.cache.SetManifests(cacheKey, q.ApplicationSource, q, q.Namespace, q.AppLabelKey, q.AppName, innerRes)
if cacheErr != nil {
log.Warnf("manifest cache set error %s: %v", q.ApplicationSource.String(), cacheErr)
return nil, cacheErr
}
}
return nil, err
}
// Otherwise, no error occurred, so ensure the manifest generation error data in the cache entry is reset before we cache the value
manifestGenCacheEntry := cache.CachedManifestResponse{
ManifestResponse: manifestGenResult,
NumberOfCachedResponsesReturned: 0,
NumberOfConsecutiveFailures: 0,
FirstFailureTimestamp: 0,
MostRecentError: "",
}
manifestGenResult.Revision = commitSHA
manifestGenResult.VerifyResult = ctx.verificationResult
err = s.cache.SetManifests(cacheKey, q.ApplicationSource, q, q.Namespace, q.AppLabelKey, q.AppName, &manifestGenCacheEntry)
if err != nil {
log.Warnf("manifest cache set error %s/%s: %v", q.ApplicationSource.String(), cacheKey, err)
}
return manifestGenCacheEntry.ManifestResponse, nil
}
// getManifestCacheEntry returns false if the 'generate manifests' operation should be run by runRepoOperation, e.g.:
// - If the cache result is empty for the requested key
// - If the cache is not empty, but the cached value is a manifest generation error AND we have not yet met the failure threshold (e.g. res.NumberOfConsecutiveFailures > 0 && res.NumberOfConsecutiveFailures < s.initConstants.PauseGenerationAfterFailedGenerationAttempts)
// - If the cache is not empty, but the cache value is an error AND that generation error has expired
// and returns true otherwise.
// If true is returned, either the second or third parameter (but not both) will contain a value from the cache (a ManifestResponse, or error, respectively)
func (s *Service) getManifestCacheEntry(cacheKey string, q *apiclient.ManifestRequest, firstInvocation bool) (bool, *apiclient.ManifestResponse, error) {
res := cache.CachedManifestResponse{}
err := s.cache.GetManifests(cacheKey, q.ApplicationSource, q, q.Namespace, q.AppLabelKey, q.AppName, &res)
if err == nil {
// The cache contains an existing value
// If caching of manifest generation errors is enabled, and res is a cached manifest generation error...
if s.initConstants.PauseGenerationAfterFailedGenerationAttempts > 0 && res.FirstFailureTimestamp > 0 {
// If we are already in the 'manifest generation caching' state, due to too many consecutive failures...
if res.NumberOfConsecutiveFailures >= s.initConstants.PauseGenerationAfterFailedGenerationAttempts {
// Check if enough time has passed to try generation again (e.g. to exit the 'manifest generation caching' state)
if s.initConstants.PauseGenerationOnFailureForMinutes > 0 {
elapsedTimeInMinutes := int((s.now().Unix() - res.FirstFailureTimestamp) / 60)
// After X minutes, reset the cache and retry the operation (e.g. perhaps the error is ephemeral and has passed)
if elapsedTimeInMinutes >= s.initConstants.PauseGenerationOnFailureForMinutes {
// We can now try again, so reset the cache state and run the operation below
err = s.cache.DeleteManifests(cacheKey, q.ApplicationSource, q, q.Namespace, q.AppLabelKey, q.AppName)
if err != nil {
log.Warnf("manifest cache set error %s/%s: %v", q.ApplicationSource.String(), cacheKey, err)
}
log.Infof("manifest error cache hit and reset: %s/%s", q.ApplicationSource.String(), cacheKey)
return false, nil, nil
}
}
// Check if enough cached responses have been returned to try generation again (e.g. to exit the 'manifest generation caching' state)
if s.initConstants.PauseGenerationOnFailureForRequests > 0 && res.NumberOfCachedResponsesReturned > 0 {
if res.NumberOfCachedResponsesReturned >= s.initConstants.PauseGenerationOnFailureForRequests {
// We can now try again, so reset the error cache state and run the operation below
err = s.cache.DeleteManifests(cacheKey, q.ApplicationSource, q, q.Namespace, q.AppLabelKey, q.AppName)
if err != nil {
log.Warnf("manifest cache set error %s/%s: %v", q.ApplicationSource.String(), cacheKey, err)
}
log.Infof("manifest error cache hit and reset: %s/%s", q.ApplicationSource.String(), cacheKey)
return false, nil, nil
}
}
// Otherwise, manifest generation is still paused
log.Infof("manifest error cache hit: %s/%s", q.ApplicationSource.String(), cacheKey)
cachedErrorResponse := fmt.Errorf(cachedManifestGenerationPrefix+": %s", res.MostRecentError)
if firstInvocation {
// Increment the number of returned cached responses and push that new value to the cache
// (if we have not already done so previously in this function)
res.NumberOfCachedResponsesReturned++
err = s.cache.SetManifests(cacheKey, q.ApplicationSource, q, q.Namespace, q.AppLabelKey, q.AppName, &res)
if err != nil {
log.Warnf("manifest cache set error %s/%s: %v", q.ApplicationSource.String(), cacheKey, err)
}
}
return true, nil, cachedErrorResponse
}
// Otherwise we are not yet in the manifest generation error state, and not enough consecutive errors have
// yet occurred to put us in that state.
log.Infof("manifest error cache miss: %s/%s", q.ApplicationSource.String(), cacheKey)
return false, res.ManifestResponse, nil
}
log.Infof("manifest cache hit: %s/%s", q.ApplicationSource.String(), cacheKey)
return true, res.ManifestResponse, nil
}
if err != reposervercache.ErrCacheMiss {
log.Warnf("manifest cache error %s: %v", q.ApplicationSource.String(), err)
} else {
log.Infof("manifest cache miss: %s/%s", q.ApplicationSource.String(), cacheKey)
}
return false, nil, nil
}
func getHelmRepos(repositories []*v1alpha1.Repository) []helm.HelmRepository {
repos := make([]helm.HelmRepository, 0)
for _, repo := range repositories {
repos = append(repos, helm.HelmRepository{Name: repo.Name, Repo: repo.Repo, Creds: repo.GetHelmCreds(), EnableOci: repo.EnableOCI})
}
return repos
}
type dependencies struct {
Dependencies []repositories `yaml:"dependencies"`
}
type repositories struct {
Repository string `yaml:"repository"`
}
func getHelmDependencyRepos(appPath string) ([]*v1alpha1.Repository, error) {
repos := make([]*v1alpha1.Repository, 0)
f, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", appPath, "Chart.yaml"))
if err != nil {
return nil, err
}
d := &dependencies{}
if err = yaml.Unmarshal(f, d); err != nil {
return nil, err
}
for _, r := range d.Dependencies {
if u, err := url.Parse(r.Repository); err == nil && (u.Scheme == "https" || u.Scheme == "oci") {
repo := &v1alpha1.Repository{
Repo: r.Repository,
Name: r.Repository,
EnableOCI: u.Scheme == "oci",
}
repos = append(repos, repo)
}
}
return repos, nil
}
func repoExists(repo string, repos []*v1alpha1.Repository) bool {
for _, r := range repos {
if strings.TrimPrefix(repo, ociPrefix) == strings.TrimPrefix(r.Repo, ociPrefix) {
return true
}
}
return false
}
func isConcurrencyAllowed(appPath string) bool {
if _, err := os.Stat(path.Join(appPath, allowConcurrencyFile)); err == nil {
return true
}
return false
}
var manifestGenerateLock = sync.NewKeyLock()
// runHelmBuild executes `helm dependency build` in a given path and ensures that it is executed only once
// if multiple threads are trying to run it.
// Multiple goroutines might process same helm app in one repo concurrently when repo server process multiple
// manifest generation requests of the same commit.
func runHelmBuild(appPath string, h helm.Helm) error {
manifestGenerateLock.Lock(appPath)
defer manifestGenerateLock.Unlock(appPath)
// the `helm dependency build` is potentially time consuming 1~2 seconds
// marker file is used to check if command already run to avoid running it again unnecessary
// file is removed when repository re-initialized (e.g. when another commit is processed)
markerFile := path.Join(appPath, helmDepUpMarkerFile)
_, err := os.Stat(markerFile)
if err == nil {
return nil
} else if !os.IsNotExist(err) {
return err
}
err = h.DependencyBuild()
if err != nil {
return err
}
return ioutil.WriteFile(markerFile, []byte("marker"), 0644)
}
func helmTemplate(appPath string, repoRoot string, env *v1alpha1.Env, q *apiclient.ManifestRequest, isLocal bool) ([]*unstructured.Unstructured, error) {
concurrencyAllowed := isConcurrencyAllowed(appPath)
if !concurrencyAllowed {
manifestGenerateLock.Lock(appPath)
defer manifestGenerateLock.Unlock(appPath)
}
templateOpts := &helm.TemplateOpts{
Name: q.AppName,
Namespace: q.Namespace,
KubeVersion: text.SemVer(q.KubeVersion),
APIVersions: q.ApiVersions,
Set: map[string]string{},
SetString: map[string]string{},
SetFile: map[string]pathutil.ResolvedFilePath{},
}
appHelm := q.ApplicationSource.Helm
var version string
if appHelm != nil {
if appHelm.Version != "" {
version = appHelm.Version
}
if appHelm.ReleaseName != "" {
templateOpts.Name = appHelm.ReleaseName
}
for _, val := range appHelm.ValueFiles {
// This will resolve val to an absolute path (or an URL)
path, _, err := pathutil.ResolveFilePath(appPath, repoRoot, val, q.GetValuesFileSchemes())
if err != nil {
return nil, err
}
templateOpts.Values = append(templateOpts.Values, path)
}
if appHelm.Values != "" {
rand, err := uuid.NewRandom()
if err != nil {
return nil, err
}
p := path.Join(os.TempDir(), rand.String())
defer func() { _ = os.RemoveAll(p) }()
err = ioutil.WriteFile(p, []byte(appHelm.Values), 0644)
if err != nil {
return nil, err
}
templateOpts.Values = append(templateOpts.Values, pathutil.ResolvedFilePath(p))
}
for _, p := range appHelm.Parameters {
if p.ForceString {
templateOpts.SetString[p.Name] = p.Value
} else {
templateOpts.Set[p.Name] = p.Value
}
}
for _, p := range appHelm.FileParameters {
resolvedPath, _, err := pathutil.ResolveFilePath(appPath, repoRoot, env.Envsubst(p.Path), q.GetValuesFileSchemes())
if err != nil {
return nil, err
}
templateOpts.SetFile[p.Name] = resolvedPath
}
}
if templateOpts.Name == "" {
templateOpts.Name = q.AppName
}
for i, j := range templateOpts.Set {
templateOpts.Set[i] = env.Envsubst(j)
}
for i, j := range templateOpts.SetString {
templateOpts.SetString[i] = env.Envsubst(j)
}
repos, err := getHelmDependencyRepos(appPath)
if err != nil {
return nil, err
}
for _, r := range repos {
if !repoExists(r.Repo, q.Repos) {
repositoryCredential := getRepoCredential(q.HelmRepoCreds, r.Repo)
if repositoryCredential != nil {
r.EnableOCI = repositoryCredential.EnableOCI
r.Password = repositoryCredential.Password
r.Username = repositoryCredential.Username
r.SSHPrivateKey = repositoryCredential.SSHPrivateKey
r.TLSClientCertData = repositoryCredential.TLSClientCertData
r.TLSClientCertKey = repositoryCredential.TLSClientCertKey
}
q.Repos = append(q.Repos, r)
}
}
var proxy string
if q.Repo != nil {
proxy = q.Repo.Proxy
}
h, err := helm.NewHelmApp(appPath, getHelmRepos(q.Repos), isLocal, version, proxy)
if err != nil {
return nil, err
}
defer h.Dispose()
err = h.Init()
if err != nil {
return nil, err
}
out, err := h.Template(templateOpts)
if err != nil {
if !helm.IsMissingDependencyErr(err) {
return nil, err
}
if concurrencyAllowed {
err = runHelmBuild(appPath, h)
} else {
err = h.DependencyBuild()
}
if err != nil {
return nil, err
}
out, err = h.Template(templateOpts)
if err != nil {
return nil, err
}
}
return kube.SplitYAML([]byte(out))
}
func getRepoCredential(repoCredentials []*v1alpha1.RepoCreds, repoURL string) *v1alpha1.RepoCreds {
for _, cred := range repoCredentials {
url := strings.TrimPrefix(repoURL, ociPrefix)
if strings.HasPrefix(url, cred.URL) {
return cred
}
}
return nil
}
// GenerateManifests generates manifests from a path
func GenerateManifests(appPath, repoRoot, revision string, q *apiclient.ManifestRequest, isLocal bool) (*apiclient.ManifestResponse, error) {
var targetObjs []*unstructured.Unstructured
var dest *v1alpha1.ApplicationDestination
appSourceType, err := GetAppSourceType(q.ApplicationSource, appPath, q.AppName)
if err != nil {
return nil, err
}
repoURL := ""
if q.Repo != nil {
repoURL = q.Repo.Repo
}
env := newEnv(q, revision)
switch appSourceType {
case v1alpha1.ApplicationSourceTypeKsonnet:
targetObjs, dest, err = ksShow(q.AppLabelKey, appPath, q.ApplicationSource.Ksonnet)
case v1alpha1.ApplicationSourceTypeHelm:
targetObjs, err = helmTemplate(appPath, repoRoot, env, q, isLocal)
case v1alpha1.ApplicationSourceTypeKustomize:
kustomizeBinary := ""
if q.KustomizeOptions != nil {
kustomizeBinary = q.KustomizeOptions.BinaryPath
}
k := kustomize.NewKustomizeApp(appPath, q.Repo.GetGitCreds(), repoURL, kustomizeBinary)
targetObjs, _, err = k.Build(q.ApplicationSource.Kustomize, q.KustomizeOptions)
case v1alpha1.ApplicationSourceTypePlugin:
targetObjs, err = runConfigManagementPlugin(appPath, env, q, q.Repo.GetGitCreds())
case v1alpha1.ApplicationSourceTypeDirectory:
var directory *v1alpha1.ApplicationSourceDirectory
if directory = q.ApplicationSource.Directory; directory == nil {
directory = &v1alpha1.ApplicationSourceDirectory{}
}
targetObjs, err = findManifests(appPath, repoRoot, env, *directory)
}
if err != nil {
return nil, err
}
manifests := make([]string, 0)
for _, obj := range targetObjs {
var targets []*unstructured.Unstructured
if obj.IsList() {
err = obj.EachListItem(func(object runtime.Object) error {
unstructuredObj, ok := object.(*unstructured.Unstructured)
if ok {
targets = append(targets, unstructuredObj)
return nil
}
return fmt.Errorf("resource list item has unexpected type")
})
if err != nil {
return nil, err
}
} else if isNullList(obj) {
// noop
} else {
targets = []*unstructured.Unstructured{obj}
}
for _, target := range targets {
if q.AppLabelKey != "" && q.AppName != "" && !kube.IsCRD(target) {
err = argokube.SetAppInstanceLabel(target, q.AppLabelKey, q.AppName)
if err != nil {
return nil, err
}
}
manifestStr, err := json.Marshal(target.Object)
if err != nil {
return nil, err
}
manifests = append(manifests, string(manifestStr))
}
}
res := apiclient.ManifestResponse{
Manifests: manifests,
SourceType: string(appSourceType),
}
if dest != nil {
res.Namespace = dest.Namespace
res.Server = dest.Server
}
return &res, nil
}
func newEnv(q *apiclient.ManifestRequest, revision string) *v1alpha1.Env {
return &v1alpha1.Env{
&v1alpha1.EnvEntry{Name: "ARGOCD_APP_NAME", Value: q.AppName},
&v1alpha1.EnvEntry{Name: "ARGOCD_APP_NAMESPACE", Value: q.Namespace},
&v1alpha1.EnvEntry{Name: "ARGOCD_APP_REVISION", Value: revision},
&v1alpha1.EnvEntry{Name: "ARGOCD_APP_SOURCE_REPO_URL", Value: q.Repo.Repo},
&v1alpha1.EnvEntry{Name: "ARGOCD_APP_SOURCE_PATH", Value: q.ApplicationSource.Path},
&v1alpha1.EnvEntry{Name: "ARGOCD_APP_SOURCE_TARGET_REVISION", Value: q.ApplicationSource.TargetRevision},
}
}
// mergeSourceParameters merges parameter overrides from one or more files in
// the Git repo into the given ApplicationSource objects.
//
// If .argocd-source.yaml exists at application's path in repository, it will
// be read and merged. If appName is not the empty string, and a file named
// .argocd-source-<appName>.yaml exists, it will also be read and merged.
func mergeSourceParameters(source *v1alpha1.ApplicationSource, path, appName string) error {
repoFilePath := filepath.Join(path, repoSourceFile)
overrides := []string{repoFilePath}
if appName != "" {
overrides = append(overrides, filepath.Join(path, fmt.Sprintf(appSourceFile, appName)))
}
var merged v1alpha1.ApplicationSource = *source.DeepCopy()
for _, filename := range overrides {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
continue
} else if info != nil && info.IsDir() {
continue
} else if err != nil {
// filename should be part of error message here
return err
}
data, err := json.Marshal(merged)
if err != nil {
return fmt.Errorf("%s: %v", filename, err)
}
patch, err := ioutil.ReadFile(filename)
if err != nil {
return fmt.Errorf("%s: %v", filename, err)
}
patch, err = yaml.YAMLToJSON(patch)
if err != nil {
return fmt.Errorf("%s: %v", filename, err)
}
data, err = jsonpatch.MergePatch(data, patch)
if err != nil {
return fmt.Errorf("%s: %v", filename, err)
}
err = json.Unmarshal(data, &merged)
if err != nil {
return fmt.Errorf("%s: %v", filename, err)
}
}
// make sure only config management tools related properties are used and ignore everything else
merged.Chart = source.Chart
merged.Path = source.Path
merged.RepoURL = source.RepoURL
merged.TargetRevision = source.TargetRevision
*source = merged
return nil
}
// GetAppSourceType returns explicit application source type or examines a directory and determines its application source type
func GetAppSourceType(source *v1alpha1.ApplicationSource, path, appName string) (v1alpha1.ApplicationSourceType, error) {
err := mergeSourceParameters(source, path, appName)
if err != nil {
return "", fmt.Errorf("error while parsing source parameters: %v", err)
}
appSourceType, err := source.ExplicitType()
if err != nil {
return "", err
}
if appSourceType != nil {
return *appSourceType, nil
}
appType, err := discovery.AppType(path)
if err != nil {
return "", err
}
return v1alpha1.ApplicationSourceType(appType), nil
}
// isNullList checks if the object is a "List" type where items is null instead of an empty list.
// Handles a corner case where obj.IsList() returns false when a manifest is like:
// ---
// apiVersion: v1
// items: null
// kind: ConfigMapList
func isNullList(obj *unstructured.Unstructured) bool {
if _, ok := obj.Object["spec"]; ok {
return false
}
if _, ok := obj.Object["status"]; ok {
return false
}
field, ok := obj.Object["items"]
if !ok {
return false
}
return field == nil
}
// ksShow runs `ks show` in an app directory after setting any component parameter overrides
func ksShow(appLabelKey, appPath string, ksonnetOpts *v1alpha1.ApplicationSourceKsonnet) ([]*unstructured.Unstructured, *v1alpha1.ApplicationDestination, error) {
ksApp, err := ksonnet.NewKsonnetApp(appPath)
if err != nil {
return nil, nil, status.Errorf(codes.FailedPrecondition, "unable to load application from %s: %v", appPath, err)
}
if ksonnetOpts == nil {
return nil, nil, status.Errorf(codes.InvalidArgument, "Ksonnet environment not set")
}
for _, override := range ksonnetOpts.Parameters {
err = ksApp.SetComponentParams(ksonnetOpts.Environment, override.Component, override.Name, override.Value)
if err != nil {
return nil, nil, err
}
}
dest, err := ksApp.Destination(ksonnetOpts.Environment)
if err != nil {
return nil, nil, status.Errorf(codes.InvalidArgument, err.Error())
}
targetObjs, err := ksApp.Show(ksonnetOpts.Environment)
if err == nil && appLabelKey == common.LabelKeyLegacyApplicationName {
// Address https://github.com/ksonnet/ksonnet/issues/707
for _, d := range targetObjs {
kube.UnsetLabel(d, "ksonnet.io/component")
}
}
if err != nil {
return nil, nil, err
}
return targetObjs, dest, nil
}
var manifestFile = regexp.MustCompile(`^.*\.(yaml|yml|json|jsonnet)$`)
// findManifests looks at all yaml files in a directory and unmarshals them into a list of unstructured objects
func findManifests(appPath string, repoRoot string, env *v1alpha1.Env, directory v1alpha1.ApplicationSourceDirectory) ([]*unstructured.Unstructured, error) {
var objs []*unstructured.Unstructured
err := filepath.Walk(appPath, func(path string, f os.FileInfo, err error) error {
if err != nil {
return err
}
if f.IsDir() {
if path != appPath && !directory.Recurse {
return filepath.SkipDir
} else {
return nil
}
}
if !manifestFile.MatchString(f.Name()) {
return nil
}
relPath, err := filepath.Rel(appPath, path)
if err != nil {
return err
}
if directory.Exclude != "" && glob.Match(directory.Exclude, relPath) {
return nil
}
if directory.Include != "" && !glob.Match(directory.Include, relPath) {
return nil
}
if strings.HasSuffix(f.Name(), ".jsonnet") {
vm, err := makeJsonnetVm(appPath, repoRoot, directory.Jsonnet, env)
if err != nil {
return err
}
jsonStr, err := vm.EvaluateFile(path)
if err != nil {
return status.Errorf(codes.FailedPrecondition, "Failed to evaluate jsonnet %q: %v", f.Name(), err)
}
// attempt to unmarshal either array or single object
var jsonObjs []*unstructured.Unstructured
err = json.Unmarshal([]byte(jsonStr), &jsonObjs)
if err == nil {
objs = append(objs, jsonObjs...)
} else {
var jsonObj unstructured.Unstructured
err = json.Unmarshal([]byte(jsonStr), &jsonObj)
if err != nil {
return status.Errorf(codes.FailedPrecondition, "Failed to unmarshal generated json %q: %v", f.Name(), err)
}
objs = append(objs, &jsonObj)
}
} else {
out, err := utfutil.ReadFile(path, utfutil.UTF8)
if err != nil {
return err
}
if strings.HasSuffix(f.Name(), ".json") {
var obj unstructured.Unstructured
err = json.Unmarshal(out, &obj)
if err != nil {
return status.Errorf(codes.FailedPrecondition, "Failed to unmarshal %q: %v", f.Name(), err)
}
objs = append(objs, &obj)
} else {
yamlObjs, err := kube.SplitYAML(out)
if err != nil {
if len(yamlObjs) > 0 {
// If we get here, we had a multiple objects in a single YAML file which had some
// valid k8s objects, but errors parsing others (within the same file). It's very
// likely the user messed up a portion of the YAML, so report on that.
return status.Errorf(codes.FailedPrecondition, "Failed to unmarshal %q: %v", f.Name(), err)
}