-
Notifications
You must be signed in to change notification settings - Fork 5k
/
argo.go
765 lines (695 loc) · 27.3 KB
/
argo.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
package argo
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/argoproj/gitops-engine/pkg/cache"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
"github.com/r3labs/diff"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned/typed/application/v1alpha1"
applicationsv1 "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1"
"github.com/argoproj/argo-cd/v2/reposerver/apiclient"
"github.com/argoproj/argo-cd/v2/util/db"
"github.com/argoproj/argo-cd/v2/util/io"
"github.com/argoproj/argo-cd/v2/util/settings"
)
const (
errDestinationMissing = "Destination server missing from app spec"
)
// FormatAppConditions returns string representation of give app condition list
func FormatAppConditions(conditions []argoappv1.ApplicationCondition) string {
formattedConditions := make([]string, 0)
for _, condition := range conditions {
formattedConditions = append(formattedConditions, fmt.Sprintf("%s: %s", condition.Type, condition.Message))
}
return strings.Join(formattedConditions, ";")
}
// FilterByProjects returns applications which belongs to the specified project
func FilterByProjects(apps []argoappv1.Application, projects []string) []argoappv1.Application {
if len(projects) == 0 {
return apps
}
projectsMap := make(map[string]bool)
for i := range projects {
projectsMap[projects[i]] = true
}
items := make([]argoappv1.Application, 0)
for i := 0; i < len(apps); i++ {
a := apps[i]
if _, ok := projectsMap[a.Spec.GetProject()]; ok {
items = append(items, a)
}
}
return items
}
// FilterAppSetsByProjects returns applications which belongs to the specified project
func FilterAppSetsByProjects(appsets []argoappv1.ApplicationSet, projects []string) []argoappv1.ApplicationSet {
if len(projects) == 0 {
return appsets
}
projectsMap := make(map[string]bool)
for i := range projects {
projectsMap[projects[i]] = true
}
items := make([]argoappv1.ApplicationSet, 0)
for i := 0; i < len(appsets); i++ {
a := appsets[i]
if _, ok := projectsMap[a.Spec.Template.Spec.GetProject()]; ok {
items = append(items, a)
}
}
return items
}
// FilterByRepo returns an application
func FilterByRepo(apps []argoappv1.Application, repo string) []argoappv1.Application {
if repo == "" {
return apps
}
items := make([]argoappv1.Application, 0)
for i := 0; i < len(apps); i++ {
if apps[i].Spec.Source.RepoURL == repo {
items = append(items, apps[i])
}
}
return items
}
// FilterByCluster returns an application
func FilterByCluster(apps []argoappv1.Application, cluster string) []argoappv1.Application {
if cluster == "" {
return apps
}
items := make([]argoappv1.Application, 0)
for i := 0; i < len(apps); i++ {
if apps[i].Spec.Destination.Server == cluster || apps[i].Spec.Destination.Name == cluster {
items = append(items, apps[i])
}
}
return items
}
// FilterByName returns an application
func FilterByName(apps []argoappv1.Application, name string) ([]argoappv1.Application, error) {
if name == "" {
return apps, nil
}
items := make([]argoappv1.Application, 0)
for i := 0; i < len(apps); i++ {
if apps[i].Name == name {
items = append(items, apps[i])
return items, nil
}
}
return items, status.Errorf(codes.NotFound, "application '%s' not found", name)
}
// RefreshApp updates the refresh annotation of an application to coerce the controller to process it
func RefreshApp(appIf v1alpha1.ApplicationInterface, name string, refreshType argoappv1.RefreshType) (*argoappv1.Application, error) {
metadata := map[string]interface{}{
"metadata": map[string]interface{}{
"annotations": map[string]string{
argoappv1.AnnotationKeyRefresh: string(refreshType),
},
},
}
var err error
patch, err := json.Marshal(metadata)
if err != nil {
return nil, fmt.Errorf("error marshaling metadata: %w", err)
}
for attempt := 0; attempt < 5; attempt++ {
app, err := appIf.Patch(context.Background(), name, types.MergePatchType, patch, metav1.PatchOptions{})
if err != nil {
if !apierr.IsConflict(err) {
return nil, fmt.Errorf("error patching annotations in application %q: %w", name, err)
}
} else {
log.Infof("Requested app '%s' refresh", name)
return app, nil
}
time.Sleep(100 * time.Millisecond)
}
return nil, err
}
func TestRepoWithKnownType(ctx context.Context, repoClient apiclient.RepoServerServiceClient, repo *argoappv1.Repository, isHelm bool, isHelmOci bool) error {
repo = repo.DeepCopy()
if isHelm {
repo.Type = "helm"
} else {
repo.Type = "git"
}
repo.EnableOCI = repo.EnableOCI || isHelmOci
_, err := repoClient.TestRepository(ctx, &apiclient.TestRepositoryRequest{
Repo: repo,
})
if err != nil {
return fmt.Errorf("repo client error while testing repository: %w", err)
}
return nil
}
// ValidateRepo validates the repository specified in application spec. Following is checked:
// * the repository is accessible
// * the path contains valid manifests
// * there are parameters of only one app source type
func ValidateRepo(
ctx context.Context,
app *argoappv1.Application,
repoClientset apiclient.Clientset,
db db.ArgoDB,
kustomizeOptions *argoappv1.KustomizeOptions,
plugins []*argoappv1.ConfigManagementPlugin,
kubectl kube.Kubectl,
proj *argoappv1.AppProject,
settingsMgr *settings.SettingsManager,
) ([]argoappv1.ApplicationCondition, error) {
spec := &app.Spec
conditions := make([]argoappv1.ApplicationCondition, 0)
// Test the repo
conn, repoClient, err := repoClientset.NewRepoServerClient()
if err != nil {
return nil, fmt.Errorf("error instantiating new repo server client: %w", err)
}
defer io.Close(conn)
repo, err := db.GetRepository(ctx, spec.Source.RepoURL)
if err != nil {
return nil, fmt.Errorf("error getting repository: %w", err)
}
repoAccessible := false
err = TestRepoWithKnownType(ctx, repoClient, repo, app.Spec.Source.IsHelm(), app.Spec.Source.IsHelmOci())
if err != nil {
conditions = append(conditions, argoappv1.ApplicationCondition{
Type: argoappv1.ApplicationConditionInvalidSpecError,
Message: fmt.Sprintf("repository not accessible: %v", err),
})
} else {
repoAccessible = true
}
// Verify only one source type is defined
_, err = spec.Source.ExplicitType()
if err != nil {
return nil, fmt.Errorf("error verifying source type: %w", err)
}
// is the repo inaccessible - abort now
if !repoAccessible {
return conditions, nil
}
helmOptions, err := settingsMgr.GetHelmSettings()
if err != nil {
return nil, fmt.Errorf("error getting helm settings: %w", err)
}
helmRepos, err := db.ListHelmRepositories(ctx)
if err != nil {
return nil, fmt.Errorf("error listing helm repos: %w", err)
}
permittedHelmRepos, err := GetPermittedRepos(proj, helmRepos)
if err != nil {
return nil, fmt.Errorf("error getting permitted repos: %w", err)
}
helmRepositoryCredentials, err := db.GetAllHelmRepositoryCredentials(ctx)
if err != nil {
return nil, fmt.Errorf("error getting helm repo creds: %w", err)
}
permittedHelmCredentials, err := GetPermittedReposCredentials(proj, helmRepositoryCredentials)
if err != nil {
return nil, fmt.Errorf("error getting permitted repo creds: %w", err)
}
cluster, err := db.GetCluster(context.Background(), spec.Destination.Server)
if err != nil {
conditions = append(conditions, argoappv1.ApplicationCondition{
Type: argoappv1.ApplicationConditionInvalidSpecError,
Message: fmt.Sprintf("Unable to get cluster: %v", err),
})
return conditions, nil
}
config := cluster.RESTConfig()
cluster.ServerVersion, err = kubectl.GetServerVersion(config)
if err != nil {
return nil, fmt.Errorf("error getting k8s server version: %w", err)
}
apiGroups, err := kubectl.GetAPIResources(config, false, cache.NewNoopSettings())
if err != nil {
return nil, fmt.Errorf("error getting API resources: %w", err)
}
enabledSourceTypes, err := settingsMgr.GetEnabledSourceTypes()
if err != nil {
return nil, fmt.Errorf("error getting enabled source types: %w", err)
}
conditions = append(conditions, verifyGenerateManifests(
ctx,
repo,
permittedHelmRepos,
helmOptions,
app,
repoClient,
kustomizeOptions,
plugins,
cluster.ServerVersion,
APIResourcesToStrings(apiGroups, true),
permittedHelmCredentials,
enabledSourceTypes,
settingsMgr)...)
return conditions, nil
}
// ValidateDestination sets the 'Server' value of the ApplicationDestination, if it is not set.
// NOTE: this function WILL write to the object pointed to by the 'dest' parameter.
//
// If an ApplicationDestination has a Name field, but has an empty Server (URL) field,
// ValidationDestination will look up the cluster by name (to get the server URL), and
// set the corresponding Server field value.
//
// It also checks:
// - If we used both name and server then we return an invalid spec error
func ValidateDestination(ctx context.Context, dest *argoappv1.ApplicationDestination, db db.ArgoDB) error {
if dest.Name != "" {
if dest.Server == "" {
server, err := getDestinationServer(ctx, db, dest.Name)
if err != nil {
return fmt.Errorf("unable to find destination server: %v", err)
}
if server == "" {
return fmt.Errorf("application references destination cluster %s which does not exist", dest.Name)
}
dest.SetInferredServer(server)
} else {
if !dest.IsServerInferred() {
return fmt.Errorf("application destination can't have both name and server defined: %s %s", dest.Name, dest.Server)
}
}
}
return nil
}
// ValidatePermissions ensures that the referenced cluster has been added to Argo CD and the app source repo and destination namespace/cluster are permitted in app project
func ValidatePermissions(ctx context.Context, spec *argoappv1.ApplicationSpec, proj *argoappv1.AppProject, db db.ArgoDB) ([]argoappv1.ApplicationCondition, error) {
conditions := make([]argoappv1.ApplicationCondition, 0)
if spec.Source.RepoURL == "" || (spec.Source.Path == "" && spec.Source.Chart == "") {
conditions = append(conditions, argoappv1.ApplicationCondition{
Type: argoappv1.ApplicationConditionInvalidSpecError,
Message: "spec.source.repoURL and either spec.source.path or spec.source.chart are required",
})
return conditions, nil
}
if spec.Source.Chart != "" && spec.Source.TargetRevision == "" {
conditions = append(conditions, argoappv1.ApplicationCondition{
Type: argoappv1.ApplicationConditionInvalidSpecError,
Message: "spec.source.targetRevision is required if the manifest source is a helm chart",
})
return conditions, nil
}
if !proj.IsSourcePermitted(spec.Source) {
conditions = append(conditions, argoappv1.ApplicationCondition{
Type: argoappv1.ApplicationConditionInvalidSpecError,
Message: fmt.Sprintf("application repo %s is not permitted in project '%s'", spec.Source.RepoURL, spec.Project),
})
}
// ValidateDestination will resolve the destination's server address from its name for us, if possible
if err := ValidateDestination(ctx, &spec.Destination, db); err != nil {
conditions = append(conditions, argoappv1.ApplicationCondition{
Type: argoappv1.ApplicationConditionInvalidSpecError,
Message: err.Error(),
})
return conditions, nil
}
if spec.Destination.Server != "" {
permitted, err := proj.IsDestinationPermitted(spec.Destination, func(project string) ([]*argoappv1.Cluster, error) {
return db.GetProjectClusters(ctx, project)
})
if err != nil {
return nil, err
}
if !permitted {
conditions = append(conditions, argoappv1.ApplicationCondition{
Type: argoappv1.ApplicationConditionInvalidSpecError,
Message: fmt.Sprintf("application destination {%s %s} is not permitted in project '%s'", spec.Destination.Server, spec.Destination.Namespace, spec.Project),
})
}
// Ensure the k8s cluster the app is referencing, is configured in Argo CD
_, err = db.GetCluster(ctx, spec.Destination.Server)
if err != nil {
if errStatus, ok := status.FromError(err); ok && errStatus.Code() == codes.NotFound {
conditions = append(conditions, argoappv1.ApplicationCondition{
Type: argoappv1.ApplicationConditionInvalidSpecError,
Message: fmt.Sprintf("cluster '%s' has not been configured", spec.Destination.Server),
})
} else {
return nil, fmt.Errorf("error getting cluster: %w", err)
}
}
} else if spec.Destination.Server == "" {
conditions = append(conditions, argoappv1.ApplicationCondition{Type: argoappv1.ApplicationConditionInvalidSpecError, Message: errDestinationMissing})
}
return conditions, nil
}
// APIResourcesToStrings converts list of API Resources list into string list
func APIResourcesToStrings(resources []kube.APIResourceInfo, includeKinds bool) []string {
resMap := map[string]bool{}
for _, r := range resources {
groupVersion := r.GroupVersionResource.GroupVersion().String()
resMap[groupVersion] = true
if includeKinds {
resMap[groupVersion+"/"+r.GroupKind.Kind] = true
}
}
var res []string
for k := range resMap {
res = append(res, k)
}
sort.Slice(res, func(i, j int) bool {
return res[i] < res[j]
})
return res
}
// GetAppProjectWithScopedResources returns a project from an application with scoped resources
func GetAppProjectWithScopedResources(name string, projLister applicationsv1.AppProjectLister, ns string, settingsManager *settings.SettingsManager, db db.ArgoDB, ctx context.Context) (*argoappv1.AppProject, argoappv1.Repositories, []*argoappv1.Cluster, error) {
projOrig, err := projLister.AppProjects(ns).Get(name)
if err != nil {
return nil, nil, nil, fmt.Errorf("error getting app project %q: %w", name, err)
}
project, err := GetAppVirtualProject(projOrig, projLister, settingsManager)
if err != nil {
return nil, nil, nil, fmt.Errorf("error getting app virtual project: %w", err)
}
clusters, err := db.GetProjectClusters(ctx, project.Name)
if err != nil {
return nil, nil, nil, fmt.Errorf("error getting project clusters: %w", err)
}
repos, err := db.GetProjectRepositories(ctx, name)
if err != nil {
return nil, nil, nil, fmt.Errorf("error getting project repos: %w", err)
}
return project, repos, clusters, nil
}
// GetAppProjectByName returns a project from an application based on name
func GetAppProjectByName(name string, projLister applicationsv1.AppProjectLister, ns string, settingsManager *settings.SettingsManager, db db.ArgoDB, ctx context.Context) (*argoappv1.AppProject, error) {
projOrig, err := projLister.AppProjects(ns).Get(name)
if err != nil {
return nil, fmt.Errorf("error getting app project %q: %w", name, err)
}
project := projOrig.DeepCopy()
repos, err := db.GetProjectRepositories(ctx, name)
if err != nil {
return nil, fmt.Errorf("error getting project repositories: %w", err)
}
for _, repo := range repos {
project.Spec.SourceRepos = append(project.Spec.SourceRepos, repo.Repo)
}
clusters, err := db.GetProjectClusters(ctx, name)
if err != nil {
return nil, fmt.Errorf("error getting project clusters: %w", err)
}
for _, cluster := range clusters {
if len(cluster.Namespaces) == 0 {
project.Spec.Destinations = append(project.Spec.Destinations, argoappv1.ApplicationDestination{Server: cluster.Server, Namespace: "*"})
} else {
for _, ns := range cluster.Namespaces {
project.Spec.Destinations = append(project.Spec.Destinations, argoappv1.ApplicationDestination{Server: cluster.Server, Namespace: ns})
}
}
}
return GetAppVirtualProject(project, projLister, settingsManager)
}
// GetAppProject returns a project from an application. It will also ensure
// that the application is allowed to use the project.
func GetAppProject(app *argoappv1.Application, projLister applicationsv1.AppProjectLister, ns string, settingsManager *settings.SettingsManager, db db.ArgoDB, ctx context.Context) (*argoappv1.AppProject, error) {
proj, err := GetAppProjectByName(app.Spec.GetProject(), projLister, ns, settingsManager, db, ctx)
if err != nil {
return nil, err
}
if !proj.IsAppNamespacePermitted(app, ns) {
return nil, fmt.Errorf("application '%s' in namespace '%s' is not allowed to use project '%s'",
app.Name, app.Namespace, proj.Name)
}
return proj, nil
}
// verifyGenerateManifests verifies a repo path can generate manifests
func verifyGenerateManifests(ctx context.Context, repoRes *argoappv1.Repository, helmRepos argoappv1.Repositories, helmOptions *argoappv1.HelmOptions, app *argoappv1.Application, repoClient apiclient.RepoServerServiceClient, kustomizeOptions *argoappv1.KustomizeOptions, plugins []*argoappv1.ConfigManagementPlugin, kubeVersion string, apiVersions []string, repositoryCredentials []*argoappv1.RepoCreds, enableGenerateManifests map[string]bool, settingsMgr *settings.SettingsManager) []argoappv1.ApplicationCondition {
spec := &app.Spec
var conditions []argoappv1.ApplicationCondition
if spec.Destination.Server == "" {
conditions = append(conditions, argoappv1.ApplicationCondition{
Type: argoappv1.ApplicationConditionInvalidSpecError,
Message: errDestinationMissing,
})
}
req := apiclient.ManifestRequest{
Repo: &argoappv1.Repository{
Repo: spec.Source.RepoURL,
Type: repoRes.Type,
Name: repoRes.Name,
Proxy: repoRes.Proxy,
},
Repos: helmRepos,
Revision: spec.Source.TargetRevision,
AppName: app.Name,
Namespace: spec.Destination.Namespace,
ApplicationSource: &spec.Source,
Plugins: plugins,
KustomizeOptions: kustomizeOptions,
KubeVersion: kubeVersion,
ApiVersions: apiVersions,
HelmOptions: helmOptions,
HelmRepoCreds: repositoryCredentials,
TrackingMethod: string(GetTrackingMethod(settingsMgr)),
EnabledSourceTypes: enableGenerateManifests,
NoRevisionCache: true,
}
req.Repo.CopyCredentialsFromRepo(repoRes)
req.Repo.CopySettingsFrom(repoRes)
// Only check whether we can access the application's path,
// and not whether it actually contains any manifests.
_, err := repoClient.GenerateManifest(ctx, &req)
if err != nil {
conditions = append(conditions, argoappv1.ApplicationCondition{
Type: argoappv1.ApplicationConditionInvalidSpecError,
Message: fmt.Sprintf("Unable to generate manifests in %s: %v", spec.Source.Path, err),
})
}
return conditions
}
// SetAppOperation updates an application with the specified operation, retrying conflict errors
func SetAppOperation(appIf v1alpha1.ApplicationInterface, appName string, op *argoappv1.Operation) (*argoappv1.Application, error) {
for {
a, err := appIf.Get(context.Background(), appName, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("error getting application %q: %w", appName, err)
}
if a.Operation != nil {
return nil, status.Errorf(codes.FailedPrecondition, "another operation is already in progress")
}
a.Operation = op
a.Status.OperationState = nil
a, err = appIf.Update(context.Background(), a, metav1.UpdateOptions{})
if op.Sync == nil {
return nil, status.Errorf(codes.InvalidArgument, "Operation unspecified")
}
if err == nil {
return a, nil
}
if !apierr.IsConflict(err) {
return nil, fmt.Errorf("error updating application %q: %w", appName, err)
}
log.Warnf("Failed to set operation for app '%s' due to update conflict. Retrying again...", appName)
}
}
// ContainsSyncResource determines if the given resource exists in the provided slice of sync operation resources.
func ContainsSyncResource(name string, namespace string, gvk schema.GroupVersionKind, rr []argoappv1.SyncOperationResource) bool {
for _, r := range rr {
if r.HasIdentity(name, namespace, gvk) {
return true
}
}
return false
}
// NormalizeApplicationSpec will normalize an application spec to a preferred state. This is used
// for migrating application objects which are using deprecated legacy fields into the new fields,
// and defaulting fields in the spec (e.g. spec.project)
func NormalizeApplicationSpec(spec *argoappv1.ApplicationSpec) *argoappv1.ApplicationSpec {
spec = spec.DeepCopy()
if spec.Project == "" {
spec.Project = argoappv1.DefaultAppProjectName
}
// 3. If any app sources are their zero values, then nil out the pointers to the source spec.
// This makes it easier for users to switch between app source types if they are not using
// any of the source-specific parameters.
if spec.Source.Kustomize != nil && spec.Source.Kustomize.IsZero() {
spec.Source.Kustomize = nil
}
if spec.Source.Helm != nil && spec.Source.Helm.IsZero() {
spec.Source.Helm = nil
}
if spec.Source.Directory != nil && spec.Source.Directory.IsZero() {
if spec.Source.Directory.Exclude != "" && spec.Source.Directory.Include != "" {
spec.Source.Directory = &argoappv1.ApplicationSourceDirectory{Exclude: spec.Source.Directory.Exclude, Include: spec.Source.Directory.Include}
} else if spec.Source.Directory.Exclude != "" {
spec.Source.Directory = &argoappv1.ApplicationSourceDirectory{Exclude: spec.Source.Directory.Exclude}
} else if spec.Source.Directory.Include != "" {
spec.Source.Directory = &argoappv1.ApplicationSourceDirectory{Include: spec.Source.Directory.Include}
} else {
spec.Source.Directory = nil
}
}
return spec
}
func GetPermittedReposCredentials(proj *argoappv1.AppProject, repoCreds []*argoappv1.RepoCreds) ([]*argoappv1.RepoCreds, error) {
var permittedRepoCreds []*argoappv1.RepoCreds
for _, v := range repoCreds {
if proj.IsSourcePermitted(argoappv1.ApplicationSource{RepoURL: v.URL}) {
permittedRepoCreds = append(permittedRepoCreds, v)
}
}
return permittedRepoCreds, nil
}
func GetPermittedRepos(proj *argoappv1.AppProject, repos []*argoappv1.Repository) ([]*argoappv1.Repository, error) {
var permittedRepos []*argoappv1.Repository
for _, v := range repos {
if proj.IsSourcePermitted(argoappv1.ApplicationSource{RepoURL: v.Repo}) {
permittedRepos = append(permittedRepos, v)
}
}
return permittedRepos, nil
}
func getDestinationServer(ctx context.Context, db db.ArgoDB, clusterName string) (string, error) {
servers, err := db.GetClusterServersByName(ctx, clusterName)
if err != nil {
return "", fmt.Errorf("error getting cluster server by name %q: %w", clusterName, err)
}
if len(servers) > 1 {
return "", fmt.Errorf("there are %d clusters with the same name: %v", len(servers), servers)
} else if len(servers) == 0 {
return "", fmt.Errorf("there are no clusters with this name: %s", clusterName)
}
return servers[0], nil
}
func GetGlobalProjects(proj *argoappv1.AppProject, projLister applicationsv1.AppProjectLister, settingsManager *settings.SettingsManager) []*argoappv1.AppProject {
gps, err := settingsManager.GetGlobalProjectsSettings()
globalProjects := make([]*argoappv1.AppProject, 0)
if err != nil {
log.Warnf("Failed to get global project settings: %v", err)
return globalProjects
}
for _, gp := range gps {
//The project itself is not its own the global project
if proj.Name == gp.ProjectName {
continue
}
selector, err := metav1.LabelSelectorAsSelector(&gp.LabelSelector)
if err != nil {
break
}
//Get projects which match the label selector, then see if proj is a match
projList, err := projLister.AppProjects(proj.Namespace).List(selector)
if err != nil {
break
}
var matchMe bool
for _, item := range projList {
if item.Name == proj.Name {
matchMe = true
break
}
}
if !matchMe {
continue
}
//If proj is a match for this global project setting, then it is its global project
globalProj, err := projLister.AppProjects(proj.Namespace).Get(gp.ProjectName)
if err != nil {
break
}
globalProjects = append(globalProjects, globalProj)
}
return globalProjects
}
func GetAppVirtualProject(proj *argoappv1.AppProject, projLister applicationsv1.AppProjectLister, settingsManager *settings.SettingsManager) (*argoappv1.AppProject, error) {
virtualProj := proj.DeepCopy()
globalProjects := GetGlobalProjects(proj, projLister, settingsManager)
for _, gp := range globalProjects {
virtualProj = mergeVirtualProject(virtualProj, gp)
}
return virtualProj, nil
}
func mergeVirtualProject(proj *argoappv1.AppProject, globalProj *argoappv1.AppProject) *argoappv1.AppProject {
if globalProj == nil {
return proj
}
proj.Spec.ClusterResourceWhitelist = append(proj.Spec.ClusterResourceWhitelist, globalProj.Spec.ClusterResourceWhitelist...)
proj.Spec.ClusterResourceBlacklist = append(proj.Spec.ClusterResourceBlacklist, globalProj.Spec.ClusterResourceBlacklist...)
proj.Spec.NamespaceResourceWhitelist = append(proj.Spec.NamespaceResourceWhitelist, globalProj.Spec.NamespaceResourceWhitelist...)
proj.Spec.NamespaceResourceBlacklist = append(proj.Spec.NamespaceResourceBlacklist, globalProj.Spec.NamespaceResourceBlacklist...)
proj.Spec.SyncWindows = append(proj.Spec.SyncWindows, globalProj.Spec.SyncWindows...)
proj.Spec.SourceRepos = append(proj.Spec.SourceRepos, globalProj.Spec.SourceRepos...)
proj.Spec.Destinations = append(proj.Spec.Destinations, globalProj.Spec.Destinations...)
return proj
}
func GenerateSpecIsDifferentErrorMessage(entity string, a, b interface{}) string {
basicMsg := fmt.Sprintf("existing %s spec is different; use upsert flag to force update", entity)
difference, _ := GetDifferentPathsBetweenStructs(a, b)
if len(difference) == 0 {
return basicMsg
}
return fmt.Sprintf("%s; difference in keys \"%s\"", basicMsg, strings.Join(difference[:], ","))
}
func GetDifferentPathsBetweenStructs(a, b interface{}) ([]string, error) {
var difference []string
changelog, err := diff.Diff(a, b)
if err != nil {
return nil, fmt.Errorf("error during diff: %w", err)
}
for _, changeItem := range changelog {
difference = append(difference, changeItem.Path...)
}
return difference, nil
}
// parseAppName will
func parseAppName(appName string, defaultNs string, delim string) (string, string) {
var ns string
var name string
t := strings.SplitN(appName, delim, 2)
if len(t) == 2 {
ns = t[0]
name = t[1]
} else {
ns = defaultNs
name = t[0]
}
return name, ns
}
// ParseAppNamespacedName parses a namespaced name in the format namespace/name
// and returns the components. If name wasn't namespaced, defaultNs will be
// returned as namespace component.
func ParseAppQualifiedName(appName string, defaultNs string) (string, string) {
return parseAppName(appName, defaultNs, "/")
}
// ParseAppInstanceName parses a namespaced name in the format namespace_name
// and returns the components. If name wasn't namespaced, defaultNs will be
// returned as namespace component.
func ParseAppInstanceName(appName string, defaultNs string) (string, string) {
return parseAppName(appName, defaultNs, "_")
}
// AppInstanceName returns the value to be used for app instance labels from
// the combination of appName, appNs and defaultNs.
func AppInstanceName(appName, appNs, defaultNs string) string {
if appNs == "" || appNs == defaultNs {
return appName
} else {
return appNs + "_" + appName
}
}
// AppInstanceNameFromQualified returns the value to be used for app
func AppInstanceNameFromQualified(name string, defaultNs string) string {
appName, appNs := ParseAppQualifiedName(name, defaultNs)
return AppInstanceName(appName, appNs, defaultNs)
}
// ErrProjectNotPermitted returns an error to indicate that an application
// identified by appName and appNamespace is not allowed to use the project
// identified by projName.
func ErrProjectNotPermitted(appName, appNamespace, projName string) error {
return fmt.Errorf("application '%s' in namespace '%s' is not permitted to use project '%s'", appName, appNamespace, projName)
}