-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
repository.go
2918 lines (2595 loc) · 111 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"
goio "io"
"io/fs"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/Masterminds/semver/v3"
"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"
gogit "github.com/go-git/go-git/v5"
"github.com/golang/protobuf/ptypes/empty"
"github.com/google/go-jsonnet"
"github.com/google/uuid"
grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/retry"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/semaphore"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
kubeyaml "k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/yaml"
pluginclient "github.com/argoproj/argo-cd/v2/cmpserver/apiclient"
"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"
"github.com/argoproj/argo-cd/v2/reposerver/metrics"
"github.com/argoproj/argo-cd/v2/util/app/discovery"
apppathutil "github.com/argoproj/argo-cd/v2/util/app/path"
argopath "github.com/argoproj/argo-cd/v2/util/app/path"
"github.com/argoproj/argo-cd/v2/util/argo"
"github.com/argoproj/argo-cd/v2/util/cmp"
"github.com/argoproj/argo-cd/v2/util/env"
"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/grpc"
"github.com/argoproj/argo-cd/v2/util/helm"
"github.com/argoproj/argo-cd/v2/util/io"
"github.com/argoproj/argo-cd/v2/util/io/files"
pathutil "github.com/argoproj/argo-cd/v2/util/io/path"
"github.com/argoproj/argo-cd/v2/util/kustomize"
"github.com/argoproj/argo-cd/v2/util/manifeststream"
"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://"
)
var (
ErrExceededMaxCombinedManifestFileSize = errors.New("exceeded max combined manifest file size")
// helmConcurrencyDefault if true then helm concurrent manifest generation is enabled
// TODO: remove env variable and usage of .argocd-allow-concurrency once we are sure that it is safe to enable it by default
helmConcurrencyDefault = env.ParseBoolFromEnv("ARGOCD_HELM_ALLOW_CONCURRENCY", false)
)
// Service implements ManifestService interface
type Service struct {
gitCredsStore git.CredsStore
rootDir string
gitRepoPaths io.TempPaths
chartPaths io.TempPaths
gitRepoInitializer func(rootPath string) goio.Closer
repoLock *repositoryLock
cache *cache.Cache
parallelismLimitSemaphore *semaphore.Weighted
metricsServer *metrics.MetricsServer
resourceTracking argo.ResourceTracking
newGitClient func(rawRepoURL string, root string, creds git.Creds, insecure bool, enableLfs bool, proxy string, noProxy string, opts ...git.ClientOpts) (git.Client, error)
newHelmClient func(repoURL string, creds helm.Creds, enableOci bool, proxy string, noProxy 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
SubmoduleEnabled bool
MaxCombinedDirectoryManifestsSize resource.Quantity
CMPTarExcludedGlobs []string
AllowOutOfBoundsSymlinks bool
StreamedManifestMaxExtractedSize int64
StreamedManifestMaxTarSize int64
HelmManifestMaxExtractedSize int64
HelmRegistryMaxIndexSize int64
DisableHelmManifestMaxExtractedSize bool
IncludeHiddenDirectories bool
CMPUseManifestGeneratePaths bool
}
// NewService returns a new instance of the Manifest service
func NewService(metricsServer *metrics.MetricsServer, cache *cache.Cache, initConstants RepoServerInitConstants, resourceTracking argo.ResourceTracking, gitCredsStore git.CredsStore, rootDir string) *Service {
var parallelismLimitSemaphore *semaphore.Weighted
if initConstants.ParallelismLimit > 0 {
parallelismLimitSemaphore = semaphore.NewWeighted(initConstants.ParallelismLimit)
}
repoLock := NewRepositoryLock()
gitRandomizedPaths := io.NewRandomizedTempPaths(rootDir)
helmRandomizedPaths := io.NewRandomizedTempPaths(rootDir)
return &Service{
parallelismLimitSemaphore: parallelismLimitSemaphore,
repoLock: repoLock,
cache: cache,
metricsServer: metricsServer,
newGitClient: git.NewClientExt,
resourceTracking: resourceTracking,
newHelmClient: func(repoURL string, creds helm.Creds, enableOci bool, proxy string, noProxy string, opts ...helm.ClientOpts) helm.Client {
return helm.NewClientWithLock(repoURL, creds, sync.NewKeyLock(), enableOci, proxy, noProxy, opts...)
},
initConstants: initConstants,
now: time.Now,
gitCredsStore: gitCredsStore,
gitRepoPaths: gitRandomizedPaths,
chartPaths: helmRandomizedPaths,
gitRepoInitializer: directoryPermissionInitializer,
rootDir: rootDir,
}
}
func (s *Service) Init() error {
_, err := os.Stat(s.rootDir)
if os.IsNotExist(err) {
return os.MkdirAll(s.rootDir, 0o300)
}
if err == nil {
// give itself read permissions to list previously written directories
err = os.Chmod(s.rootDir, 0o700)
}
var dirEntries []fs.DirEntry
if err == nil {
dirEntries, err = os.ReadDir(s.rootDir)
}
if err != nil {
log.Warnf("Failed to restore cloned repositories paths: %v", err)
return nil
}
for _, file := range dirEntries {
if !file.IsDir() {
continue
}
fullPath := filepath.Join(s.rootDir, file.Name())
closer := s.gitRepoInitializer(fullPath)
if repo, err := gogit.PlainOpen(fullPath); err == nil {
if remotes, err := repo.Remotes(); err == nil && len(remotes) > 0 && len(remotes[0].Config().URLs) > 0 {
s.gitRepoPaths.Add(git.NormalizeGitURL(remotes[0].Config().URLs[0]), fullPath)
}
}
io.Close(closer)
}
// remove read permissions since no-one should be able to list the directories
return os.Chmod(s.rootDir, 0o300)
}
// ListRefs 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, fmt.Errorf("error creating git client: %w", 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, fmt.Errorf("error setting up git client and resolving given revision: %w", 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() (goio.Closer, error) {
return s.checkoutRevision(gitClient, commitSHA, s.initConstants.SubmoduleEnabled)
})
if err != nil {
return nil, fmt.Errorf("error acquiring repository lock: %w", err)
}
defer io.Close(closer)
apps, err := discovery.Discover(ctx, gitClient.Root(), gitClient.Root(), q.EnabledSourceTypes, s.initConstants.CMPTarExcludedGlobs, []string{})
if err != nil {
return nil, fmt.Errorf("error discovering applications: %w", 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
}
// ListPlugins lists the contents of a GitHub repo
func (s *Service) ListPlugins(ctx context.Context, _ *empty.Empty) (*apiclient.PluginList, error) {
pluginSockFilePath := common.GetPluginSockFilePath()
sockFiles, err := os.ReadDir(pluginSockFilePath)
if err != nil {
return nil, fmt.Errorf("failed to get plugins from dir %v, error=%w", pluginSockFilePath, err)
}
var plugins []*apiclient.PluginInfo
for _, file := range sockFiles {
if file.Type() == os.ModeSocket {
plugins = append(plugins, &apiclient.PluginInfo{Name: strings.TrimSuffix(file.Name(), ".sock")})
}
}
res := apiclient.PluginList{Items: plugins}
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, refSourceCommitSHAs cache.ResolvedRevisions, firstInvocation bool) (bool, error),
operation func(repoRoot, commitSHA, cacheKey string, ctxSrc operationContextSrc) error,
settings operationSettings,
hasMultipleSources bool,
refSources map[string]*v1alpha1.RefTarget,
) error {
if sanitizer, ok := grpc.SanitizerFromContext(ctx); ok {
// make sure a randomized path replaced with '.' in the error message
sanitizer.AddRegexReplacement(getRepoSanitizerRegex(s.rootDir), "<path to cached source>")
}
var gitClient git.Client
var helmClient helm.Client
var err error
gitClientOpts := git.WithCache(s.cache, !settings.noRevisionCache && !settings.noCache)
revision = textutils.FirstNonEmpty(revision, source.TargetRevision)
unresolvedRevision := revision
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, gitClientOpts)
if err != nil {
return err
}
}
repoRefs, err := resolveReferencedSources(hasMultipleSources, source.Helm, refSources, s.newClientResolveRevision, gitClientOpts)
if err != nil {
return err
}
if !settings.noCache {
if ok, err := cacheFn(revision, repoRefs, 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, repo.Project)
if err != nil {
return err
}
}
helmPassCredentials := false
if source.Helm != nil {
helmPassCredentials = source.Helm.PassCredentials
}
chartPath, closer, err := helmClient.ExtractChart(source.Chart, revision, repo.Project, helmPassCredentials, s.initConstants.HelmManifestMaxExtractedSize, s.initConstants.DisableHelmManifestMaxExtractedSize)
if err != nil {
return err
}
defer io.Close(closer)
if !s.initConstants.AllowOutOfBoundsSymlinks {
err := argopath.CheckOutOfBoundsSymlinks(chartPath)
if err != nil {
oobError := &argopath.OutOfBoundsSymlinkError{}
if errors.As(err, &oobError) {
log.WithFields(log.Fields{
common.SecurityField: common.SecurityHigh,
"chart": source.Chart,
"revision": revision,
"file": oobError.File,
}).Warn("chart contains out-of-bounds symlink")
return fmt.Errorf("chart contains out-of-bounds symlinks. file: %s", oobError.File)
} else {
return err
}
}
}
return operation(chartPath, revision, revision, func() (*operationContext, error) {
return &operationContext{chartPath, ""}, nil
})
} else {
closer, err := s.repoLock.Lock(gitClient.Root(), revision, settings.allowConcurrent, func() (goio.Closer, error) {
return s.checkoutRevision(gitClient, revision, s.initConstants.SubmoduleEnabled)
})
if err != nil {
return err
}
defer io.Close(closer)
if !s.initConstants.AllowOutOfBoundsSymlinks {
err := argopath.CheckOutOfBoundsSymlinks(gitClient.Root())
if err != nil {
oobError := &argopath.OutOfBoundsSymlinkError{}
if errors.As(err, &oobError) {
log.WithFields(log.Fields{
common.SecurityField: common.SecurityHigh,
"repo": repo.Repo,
"revision": revision,
"file": oobError.File,
}).Warn("repository contains out-of-bounds symlink")
return fmt.Errorf("repository contains out-of-bounds symlinks. file: %s", oobError.File)
} else {
return err
}
}
}
var commitSHA string
if hasMultipleSources {
commitSHA = revision
} else {
commit, err := gitClient.CommitSHA()
if err != nil {
return fmt.Errorf("failed to get commit SHA: %w", err)
}
commitSHA = commit
}
// double-check locking
if !settings.noCache {
if ok, err := cacheFn(revision, repoRefs, 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 {
// When the revision is an annotated tag, we need to pass the unresolved revision (i.e. the tag name)
// to the verification routine. For everything else, we work with the SHA that the target revision is
// pointing to (i.e. the resolved revision).
var rev string
if gitClient.IsAnnotatedTag(revision) {
rev = unresolvedRevision
} else {
rev = revision
}
signature, err = gitClient.VerifyCommitSignature(rev)
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 getRepoSanitizerRegex(rootDir string) *regexp.Regexp {
// This regex assumes that the sensitive part of the path (the component immediately after "rootDir") contains no
// spaces. This assumption allows us to avoid sanitizing "more info" in "/tmp/_argocd-repo/SENSITIVE more info".
//
// The no-spaces assumption holds for our actual use case, which is "/tmp/_argocd-repo/{random UUID}". The UUID will
// only ever contain digits and hyphens.
return regexp.MustCompile(regexp.QuoteMeta(rootDir) + `/[^ /]*`)
}
type gitClientGetter func(repo *v1alpha1.Repository, revision string, opts ...git.ClientOpts) (git.Client, string, error)
// resolveReferencedSources resolves the revisions for the given referenced sources. This lets us invalidate the cached
// when one or more referenced sources change.
//
// Much of this logic is duplicated in runManifestGenAsync. If making changes here, check whether runManifestGenAsync
// should be updated.
func resolveReferencedSources(hasMultipleSources bool, source *v1alpha1.ApplicationSourceHelm, refSources map[string]*v1alpha1.RefTarget, newClientResolveRevision gitClientGetter, gitClientOpts git.ClientOpts) (map[string]string, error) {
repoRefs := make(map[string]string)
if !hasMultipleSources || source == nil {
return repoRefs, nil
}
refFileParams := make([]string, 0)
for _, fileParam := range source.FileParameters {
refFileParams = append(refFileParams, fileParam.Path)
}
refCandidates := append(source.ValueFiles, refFileParams...)
for _, valueFile := range refCandidates {
if strings.HasPrefix(valueFile, "$") {
refVar := strings.Split(valueFile, "/")[0]
refSourceMapping, ok := refSources[refVar]
if !ok {
if len(refSources) == 0 {
return nil, fmt.Errorf("source referenced %q, but no source has a 'ref' field defined", refVar)
}
refKeys := make([]string, 0)
for refKey := range refSources {
refKeys = append(refKeys, refKey)
}
return nil, fmt.Errorf("source referenced %q, which is not one of the available sources (%s)", refVar, strings.Join(refKeys, ", "))
}
if refSourceMapping.Chart != "" {
return nil, errors.New("source has a 'chart' field defined, but Helm charts are not yet not supported for 'ref' sources")
}
normalizedRepoURL := git.NormalizeGitURL(refSourceMapping.Repo.Repo)
_, ok = repoRefs[normalizedRepoURL]
if !ok {
_, referencedCommitSHA, err := newClientResolveRevision(&refSourceMapping.Repo, refSourceMapping.TargetRevision, gitClientOpts)
if err != nil {
log.Errorf("Failed to get git client for repo %s: %v", refSourceMapping.Repo.Repo, err)
return nil, fmt.Errorf("failed to get git client for repo %s", refSourceMapping.Repo.Repo)
}
repoRefs[normalizedRepoURL] = referencedCommitSHA
}
}
}
return repoRefs, nil
}
func (s *Service) GenerateManifest(ctx context.Context, q *apiclient.ManifestRequest) (*apiclient.ManifestResponse, error) {
var res *apiclient.ManifestResponse
var err error
// Skip this path for ref only sources
if q.HasMultipleSources && q.ApplicationSource.Path == "" && !q.ApplicationSource.IsHelm() && q.ApplicationSource.IsRef() {
log.Debugf("Skipping manifest generation for ref only source for application: %s and ref %s", q.AppName, q.ApplicationSource.Ref)
_, revision, err := s.newClientResolveRevision(q.Repo, q.Revision, git.WithCache(s.cache, !q.NoRevisionCache && !q.NoCache))
res = &apiclient.ManifestResponse{
Revision: revision,
}
return res, err
}
cacheFn := func(cacheKey string, refSourceCommitSHAs cache.ResolvedRevisions, firstInvocation bool) (bool, error) {
ok, resp, err := s.getManifestCacheEntry(cacheKey, q, refSourceCommitSHAs, firstInvocation)
res = resp
return ok, err
}
tarConcluded := false
var promise *ManifestResponsePromise
operation := func(repoRoot, commitSHA, cacheKey string, ctxSrc operationContextSrc) error {
// do not generate manifests if Path and Chart fields are not set for a source in Multiple Sources
if q.HasMultipleSources && q.ApplicationSource.Path == "" && q.ApplicationSource.Chart == "" {
log.WithFields(map[string]interface{}{
"source": q.ApplicationSource,
}).Debugf("not generating manifests as path and chart fields are empty")
res = &apiclient.ManifestResponse{
Revision: commitSHA,
}
return nil
}
promise = s.runManifestGen(ctx, repoRoot, commitSHA, cacheKey, ctxSrc, q)
// The fist channel to send the message will resume this operation.
// The main purpose for using channels here is to be able to unlock
// the repository as soon as the lock in not required anymore. In
// case of CMP the repo is compressed (tgz) and sent to the cmp-server
// for manifest generation.
select {
case err := <-promise.errCh:
return err
case resp := <-promise.responseCh:
res = resp
case tarDone := <-promise.tarDoneCh:
tarConcluded = tarDone
}
return nil
}
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, q.HasMultipleSources, q.RefSources)
// if the tarDoneCh message is sent it means that the manifest
// generation is being managed by the cmp-server. In this case
// we have to wait for the responseCh to send the manifest
// response.
if tarConcluded && res == nil {
select {
case resp := <-promise.responseCh:
res = resp
case err := <-promise.errCh:
return nil, err
}
}
return res, err
}
func (s *Service) GenerateManifestWithFiles(stream apiclient.RepoServerService_GenerateManifestWithFilesServer) error {
workDir, err := files.CreateTempDir("")
if err != nil {
return fmt.Errorf("error creating temp dir: %w", err)
}
defer func() {
if err := os.RemoveAll(workDir); err != nil {
// we panic here as the workDir may contain sensitive information
log.WithField(common.SecurityField, common.SecurityCritical).Errorf("error removing generate manifest workdir: %v", err)
panic(fmt.Sprintf("error removing generate manifest workdir: %s", err))
}
}()
req, metadata, err := manifeststream.ReceiveManifestFileStream(stream.Context(), stream, workDir, s.initConstants.StreamedManifestMaxTarSize, s.initConstants.StreamedManifestMaxExtractedSize)
if err != nil {
return fmt.Errorf("error receiving manifest file stream: %w", err)
}
if !s.initConstants.AllowOutOfBoundsSymlinks {
err := argopath.CheckOutOfBoundsSymlinks(workDir)
if err != nil {
oobError := &argopath.OutOfBoundsSymlinkError{}
if errors.As(err, &oobError) {
log.WithFields(log.Fields{
common.SecurityField: common.SecurityHigh,
"file": oobError.File,
}).Warn("streamed files contains out-of-bounds symlink")
return fmt.Errorf("streamed files contains out-of-bounds symlinks. file: %s", oobError.File)
} else {
return err
}
}
}
promise := s.runManifestGen(stream.Context(), workDir, "streamed", metadata.Checksum, func() (*operationContext, error) {
appPath, err := argopath.Path(workDir, req.ApplicationSource.Path)
if err != nil {
return nil, fmt.Errorf("failed to get app path: %w", err)
}
return &operationContext{appPath, ""}, nil
}, req)
var res *apiclient.ManifestResponse
tarConcluded := false
select {
case err := <-promise.errCh:
return err
case tarDone := <-promise.tarDoneCh:
tarConcluded = tarDone
case resp := <-promise.responseCh:
res = resp
}
if tarConcluded && res == nil {
select {
case resp := <-promise.responseCh:
res = resp
case err := <-promise.errCh:
return err
}
}
err = stream.SendAndClose(res)
return err
}
type ManifestResponsePromise struct {
responseCh <-chan *apiclient.ManifestResponse
tarDoneCh <-chan bool
errCh <-chan error
}
func NewManifestResponsePromise(responseCh <-chan *apiclient.ManifestResponse, tarDoneCh <-chan bool, errCh chan error) *ManifestResponsePromise {
return &ManifestResponsePromise{
responseCh: responseCh,
tarDoneCh: tarDoneCh,
errCh: errCh,
}
}
type generateManifestCh struct {
responseCh chan<- *apiclient.ManifestResponse
tarDoneCh chan<- bool
errCh chan<- error
}
// 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(ctx context.Context, repoRoot, commitSHA, cacheKey string, opContextSrc operationContextSrc, q *apiclient.ManifestRequest) *ManifestResponsePromise {
responseCh := make(chan *apiclient.ManifestResponse)
tarDoneCh := make(chan bool)
errCh := make(chan error)
responsePromise := NewManifestResponsePromise(responseCh, tarDoneCh, errCh)
channels := &generateManifestCh{
responseCh: responseCh,
tarDoneCh: tarDoneCh,
errCh: errCh,
}
go s.runManifestGenAsync(ctx, repoRoot, commitSHA, cacheKey, opContextSrc, q, channels)
return responsePromise
}
type repoRef struct {
// revision is the git revision - can be any valid revision like a branch, tag, or commit SHA.
revision string
// commitSHA is the actual commit to which revision refers.
commitSHA string
// key is the name of the key which was used to reference this repo.
key string
}
func (s *Service) runManifestGenAsync(ctx context.Context, repoRoot, commitSHA, cacheKey string, opContextSrc operationContextSrc, q *apiclient.ManifestRequest, ch *generateManifestCh) {
defer func() {
close(ch.errCh)
close(ch.responseCh)
}()
// GenerateManifests mutates the source (applies overrides). Those overrides shouldn't be reflected in the cache
// key. Overrides will break the cache anyway, because changes to overrides will change the revision.
appSourceCopy := q.ApplicationSource.DeepCopy()
repoRefs := make(map[string]repoRef)
var manifestGenResult *apiclient.ManifestResponse
opContext, err := opContextSrc()
if err == nil {
// Much of the multi-source handling logic is duplicated in resolveReferencedSources. If making changes here,
// check whether they should be replicated in resolveReferencedSources.
if q.HasMultipleSources {
if q.ApplicationSource.Helm != nil {
refFileParams := make([]string, 0)
for _, fileParam := range q.ApplicationSource.Helm.FileParameters {
refFileParams = append(refFileParams, fileParam.Path)
}
refCandidates := append(q.ApplicationSource.Helm.ValueFiles, refFileParams...)
// Checkout every one of the referenced sources to the target revision before generating Manifests
for _, valueFile := range refCandidates {
if strings.HasPrefix(valueFile, "$") {
refVar := strings.Split(valueFile, "/")[0]
refSourceMapping, ok := q.RefSources[refVar]
if !ok {
if len(q.RefSources) == 0 {
ch.errCh <- fmt.Errorf("source referenced %q, but no source has a 'ref' field defined", refVar)
}
refKeys := make([]string, 0)
for refKey := range q.RefSources {
refKeys = append(refKeys, refKey)
}
ch.errCh <- fmt.Errorf("source referenced %q, which is not one of the available sources (%s)", refVar, strings.Join(refKeys, ", "))
return
}
if refSourceMapping.Chart != "" {
ch.errCh <- errors.New("source has a 'chart' field defined, but Helm charts are not yet not supported for 'ref' sources")
return
}
normalizedRepoURL := git.NormalizeGitURL(refSourceMapping.Repo.Repo)
closer, ok := repoRefs[normalizedRepoURL]
if ok {
if closer.revision != refSourceMapping.TargetRevision {
ch.errCh <- fmt.Errorf("cannot reference multiple revisions for the same repository (%s references %q while %s references %q)", refVar, refSourceMapping.TargetRevision, closer.key, closer.revision)
return
}
} else {
gitClient, referencedCommitSHA, err := s.newClientResolveRevision(&refSourceMapping.Repo, refSourceMapping.TargetRevision, git.WithCache(s.cache, !q.NoRevisionCache && !q.NoCache))
if err != nil {
log.Errorf("Failed to get git client for repo %s: %v", refSourceMapping.Repo.Repo, err)
ch.errCh <- fmt.Errorf("failed to get git client for repo %s", refSourceMapping.Repo.Repo)
return
}
if git.NormalizeGitURL(q.ApplicationSource.RepoURL) == normalizedRepoURL && commitSHA != referencedCommitSHA {
ch.errCh <- fmt.Errorf("cannot reference a different revision of the same repository (%s references %q which resolves to %q while the application references %q which resolves to %q)", refVar, refSourceMapping.TargetRevision, referencedCommitSHA, q.Revision, commitSHA)
return
}
closer, err := s.repoLock.Lock(gitClient.Root(), referencedCommitSHA, true, func() (goio.Closer, error) {
return s.checkoutRevision(gitClient, referencedCommitSHA, s.initConstants.SubmoduleEnabled)
})
if err != nil {
log.Errorf("failed to acquire lock for referenced source %s", normalizedRepoURL)
ch.errCh <- err
return
}
defer func(closer goio.Closer) {
err := closer.Close()
if err != nil {
log.Errorf("Failed to release repo lock: %v", err)
}
}(closer)
// Symlink check must happen after acquiring lock.
if !s.initConstants.AllowOutOfBoundsSymlinks {
err := argopath.CheckOutOfBoundsSymlinks(gitClient.Root())
if err != nil {
oobError := &argopath.OutOfBoundsSymlinkError{}
if errors.As(err, &oobError) {
log.WithFields(log.Fields{
common.SecurityField: common.SecurityHigh,
"repo": refSourceMapping.Repo,
"revision": refSourceMapping.TargetRevision,
"file": oobError.File,
}).Warn("repository contains out-of-bounds symlink")
ch.errCh <- fmt.Errorf("repository contains out-of-bounds symlinks. file: %s", oobError.File)
return
} else {
ch.errCh <- err
return
}
}
}
repoRefs[normalizedRepoURL] = repoRef{revision: refSourceMapping.TargetRevision, commitSHA: referencedCommitSHA, key: refVar}
}
}
}
}
}
manifestGenResult, err = GenerateManifests(ctx, opContext.appPath, repoRoot, commitSHA, q, false, s.gitCredsStore, s.initConstants.MaxCombinedDirectoryManifestsSize, s.gitRepoPaths, WithCMPTarDoneChannel(ch.tarDoneCh), WithCMPTarExcludedGlobs(s.initConstants.CMPTarExcludedGlobs), WithCMPUseManifestGeneratePaths(s.initConstants.CMPUseManifestGeneratePaths))
}
refSourceCommitSHAs := make(map[string]string)
if len(repoRefs) > 0 {
for normalizedURL, repoRef := range repoRefs {
refSourceCommitSHAs[normalizedURL] = repoRef.commitSHA
}
}
if err != nil {
logCtx := log.WithFields(log.Fields{
"application": q.AppName,
"appNamespace": q.Namespace,
})
// If manifest generation error caching is enabled
if s.initConstants.PauseGenerationAfterFailedGenerationAttempts > 0 {
cache.LogDebugManifestCacheKeyFields("getting manifests cache", "GenerateManifests error", cacheKey, q.ApplicationSource, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, refSourceCommitSHAs)
// 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, appSourceCopy, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, innerRes, refSourceCommitSHAs, q.InstallationID)
if cacheErr != nil && !errors.Is(cacheErr, cache.ErrCacheMiss) {
logCtx.Warnf("manifest cache get error %s: %v", appSourceCopy.String(), cacheErr)
ch.errCh <- cacheErr
return
}
// 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()
}
cache.LogDebugManifestCacheKeyFields("setting manifests cache", "GenerateManifests error", cacheKey, q.ApplicationSource, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, refSourceCommitSHAs)
// Update the cache to include failure information
innerRes.NumberOfConsecutiveFailures++
innerRes.MostRecentError = err.Error()
cacheErr = s.cache.SetManifests(cacheKey, appSourceCopy, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, innerRes, refSourceCommitSHAs, q.InstallationID)
if cacheErr != nil {
logCtx.Warnf("manifest cache set error %s: %v", appSourceCopy.String(), cacheErr)
ch.errCh <- cacheErr
return
}
}
ch.errCh <- err
return
}
cache.LogDebugManifestCacheKeyFields("setting manifests cache", "fresh GenerateManifests response", cacheKey, q.ApplicationSource, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, refSourceCommitSHAs)
// 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 = opContext.verificationResult
err = s.cache.SetManifests(cacheKey, appSourceCopy, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, &manifestGenCacheEntry, refSourceCommitSHAs, q.InstallationID)
if err != nil {
log.Warnf("manifest cache set error %s/%s: %v", appSourceCopy.String(), cacheKey, err)
}
ch.responseCh <- manifestGenCacheEntry.ManifestResponse
}
// 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, refSourceCommitSHAs cache.ResolvedRevisions, firstInvocation bool) (bool, *apiclient.ManifestResponse, error) {
cache.LogDebugManifestCacheKeyFields("getting manifests cache", "GenerateManifest API call", cacheKey, q.ApplicationSource, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, refSourceCommitSHAs)
res := cache.CachedManifestResponse{}
err := s.cache.GetManifests(cacheKey, q.ApplicationSource, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, &res, refSourceCommitSHAs, q.InstallationID)
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 {
cache.LogDebugManifestCacheKeyFields("deleting manifests cache", "manifest hash did not match or cached response is empty", cacheKey, q.ApplicationSource, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, refSourceCommitSHAs)
// We can now try again, so reset the cache state and run the operation below
err = s.cache.DeleteManifests(cacheKey, q.ApplicationSource, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, refSourceCommitSHAs, q.InstallationID)
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 {
cache.LogDebugManifestCacheKeyFields("deleting manifests cache", "reset after paused generation count", cacheKey, q.ApplicationSource, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, refSourceCommitSHAs)
// We can now try again, so reset the error cache state and run the operation below
err = s.cache.DeleteManifests(cacheKey, q.ApplicationSource, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, refSourceCommitSHAs, q.InstallationID)
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 {
cache.LogDebugManifestCacheKeyFields("setting manifests cache", "update error count", cacheKey, q.ApplicationSource, q.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, refSourceCommitSHAs)
// 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.RefSources, q, q.Namespace, q.TrackingMethod, q.AppLabelKey, q.AppName, &res, refSourceCommitSHAs, q.InstallationID)
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 !errors.Is(err, cache.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(appPath string, repositories []*v1alpha1.Repository, helmRepoCreds []*v1alpha1.RepoCreds) ([]helm.HelmRepository, error) {
dependencies, err := getHelmDependencyRepos(appPath)
if err != nil {
return nil, fmt.Errorf("error retrieving helm dependency repos: %w", err)
}
reposByName := make(map[string]*v1alpha1.Repository)
reposByUrl := make(map[string]*v1alpha1.Repository)
for _, repo := range repositories {
reposByUrl[repo.Repo] = repo
if repo.Name != "" {
reposByName[repo.Name] = repo
}
}
repos := make([]helm.HelmRepository, 0)
for _, dep := range dependencies {
// find matching repo credentials by URL or name
repo, ok := reposByUrl[dep.Repo]
if !ok && dep.Name != "" {
repo, ok = reposByName[dep.Name]
}
if !ok {
// if no matching repo credentials found, use the repo creds from the credential list
repo = &v1alpha1.Repository{Repo: dep.Repo, Name: dep.Name, EnableOCI: dep.EnableOCI}
if repositoryCredential := getRepoCredential(helmRepoCreds, dep.Repo); repositoryCredential != nil {
repo.EnableOCI = repositoryCredential.EnableOCI
repo.Password = repositoryCredential.Password
repo.Username = repositoryCredential.Username
repo.SSHPrivateKey = repositoryCredential.SSHPrivateKey
repo.TLSClientCertData = repositoryCredential.TLSClientCertData