-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathapplication.go
2605 lines (2343 loc) · 94.5 KB
/
application.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 application
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"reflect"
"sort"
"strconv"
"strings"
"time"
kubecache "github.com/argoproj/gitops-engine/pkg/cache"
"github.com/argoproj/gitops-engine/pkg/diff"
"github.com/argoproj/gitops-engine/pkg/sync/common"
"github.com/argoproj/gitops-engine/pkg/utils/kube"
"github.com/argoproj/gitops-engine/pkg/utils/text"
"github.com/argoproj/pkg/sync"
jsonpatch "github.com/evanphx/json-patch"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
v1 "k8s.io/api/core/v1"
apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/utils/ptr"
argocommon "github.com/argoproj/argo-cd/v2/common"
"github.com/argoproj/argo-cd/v2/pkg/apiclient/application"
appv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
appclientset "github.com/argoproj/argo-cd/v2/pkg/client/clientset/versioned"
applisters "github.com/argoproj/argo-cd/v2/pkg/client/listers/application/v1alpha1"
"github.com/argoproj/argo-cd/v2/reposerver/apiclient"
servercache "github.com/argoproj/argo-cd/v2/server/cache"
"github.com/argoproj/argo-cd/v2/server/deeplinks"
"github.com/argoproj/argo-cd/v2/server/rbacpolicy"
"github.com/argoproj/argo-cd/v2/util/argo"
argoutil "github.com/argoproj/argo-cd/v2/util/argo"
"github.com/argoproj/argo-cd/v2/util/collections"
"github.com/argoproj/argo-cd/v2/util/db"
"github.com/argoproj/argo-cd/v2/util/env"
"github.com/argoproj/argo-cd/v2/util/git"
ioutil "github.com/argoproj/argo-cd/v2/util/io"
"github.com/argoproj/argo-cd/v2/util/lua"
"github.com/argoproj/argo-cd/v2/util/manifeststream"
"github.com/argoproj/argo-cd/v2/util/rbac"
"github.com/argoproj/argo-cd/v2/util/security"
"github.com/argoproj/argo-cd/v2/util/session"
"github.com/argoproj/argo-cd/v2/util/settings"
applicationType "github.com/argoproj/argo-cd/v2/pkg/apis/application"
)
type AppResourceTreeFn func(ctx context.Context, app *appv1.Application) (*appv1.ApplicationTree, error)
const (
backgroundPropagationPolicy string = "background"
foregroundPropagationPolicy string = "foreground"
)
var (
watchAPIBufferSize = env.ParseNumFromEnv(argocommon.EnvWatchAPIBufferSize, 1000, 0, math.MaxInt32)
permissionDeniedErr = status.Error(codes.PermissionDenied, "permission denied")
)
// Server provides an Application service
type Server struct {
ns string
kubeclientset kubernetes.Interface
appclientset appclientset.Interface
appLister applisters.ApplicationLister
appInformer cache.SharedIndexInformer
appBroadcaster Broadcaster
repoClientset apiclient.Clientset
kubectl kube.Kubectl
db db.ArgoDB
enf *rbac.Enforcer
projectLock sync.KeyLock
auditLogger *argo.AuditLogger
settingsMgr *settings.SettingsManager
cache *servercache.Cache
projInformer cache.SharedIndexInformer
enabledNamespaces []string
}
// NewServer returns a new instance of the Application service
func NewServer(
namespace string,
kubeclientset kubernetes.Interface,
appclientset appclientset.Interface,
appLister applisters.ApplicationLister,
appInformer cache.SharedIndexInformer,
appBroadcaster Broadcaster,
repoClientset apiclient.Clientset,
cache *servercache.Cache,
kubectl kube.Kubectl,
db db.ArgoDB,
enf *rbac.Enforcer,
projectLock sync.KeyLock,
settingsMgr *settings.SettingsManager,
projInformer cache.SharedIndexInformer,
enabledNamespaces []string,
) (application.ApplicationServiceServer, AppResourceTreeFn) {
if appBroadcaster == nil {
appBroadcaster = &broadcasterHandler{}
}
_, err := appInformer.AddEventHandler(appBroadcaster)
if err != nil {
log.Error(err)
}
s := &Server{
ns: namespace,
appclientset: appclientset,
appLister: appLister,
appInformer: appInformer,
appBroadcaster: appBroadcaster,
kubeclientset: kubeclientset,
cache: cache,
db: db,
repoClientset: repoClientset,
kubectl: kubectl,
enf: enf,
projectLock: projectLock,
auditLogger: argo.NewAuditLogger(namespace, kubeclientset, "argocd-server"),
settingsMgr: settingsMgr,
projInformer: projInformer,
enabledNamespaces: enabledNamespaces,
}
return s, s.getAppResources
}
// getAppEnforceRBAC gets the Application with the given name in the given namespace. If no namespace is
// specified, the Application is fetched from the default namespace (the one in which the API server is running).
//
// If the user does not provide a "project," then we have to be very careful how we respond. If an app with the given
// name exists, and the user has access to that app in the app's project, we return the app. If the app exists but the
// user does not have access, we return "permission denied." If the app does not exist, we return "permission denied" -
// if we responded with a 404, then the user could infer that the app exists when they get "permission denied."
//
// If the user does provide a "project," we can respond more specifically. If the user does not have access to the given
// app name in the given project, we return "permission denied." If the app exists, but the project is different from
func (s *Server) getAppEnforceRBAC(ctx context.Context, action, project, namespace, name string, getApp func() (*appv1.Application, error)) (*appv1.Application, *appv1.AppProject, error) {
user := session.Username(ctx)
if user == "" {
user = "Unknown user"
}
logCtx := log.WithFields(map[string]interface{}{
"user": user,
"application": name,
"namespace": namespace,
})
if project != "" {
// The user has provided everything we need to perform an initial RBAC check.
givenRBACName := security.RBACName(s.ns, project, namespace, name)
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceApplications, action, givenRBACName); err != nil {
logCtx.WithFields(map[string]interface{}{
"project": project,
argocommon.SecurityField: argocommon.SecurityMedium,
}).Warnf("user tried to %s application which they do not have access to: %s", action, err)
// Do a GET on the app. This ensures that the timing of a "no access" response is the same as a "yes access,
// but the app is in a different project" response. We don't want the user inferring the existence of the
// app from response time.
_, _ = getApp()
return nil, nil, permissionDeniedErr
}
}
a, err := getApp()
if err != nil {
if apierr.IsNotFound(err) {
if project != "" {
// We know that the user was allowed to get the Application, but the Application does not exist. Return 404.
return nil, nil, status.Errorf(codes.NotFound, apierr.NewNotFound(schema.GroupResource{Group: "argoproj.io", Resource: "applications"}, name).Error())
}
// We don't know if the user was allowed to get the Application, and we don't want to leak information about
// the Application's existence. Return 403.
logCtx.Warn("application does not exist")
return nil, nil, permissionDeniedErr
}
logCtx.Errorf("failed to get application: %s", err)
return nil, nil, permissionDeniedErr
}
// Even if we performed an initial RBAC check (because the request was fully parameterized), we still need to
// perform a second RBAC check to ensure that the user has access to the actual Application's project (not just the
// project they specified in the request).
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceApplications, action, a.RBACName(s.ns)); err != nil {
logCtx.WithFields(map[string]interface{}{
"project": a.Spec.Project,
argocommon.SecurityField: argocommon.SecurityMedium,
}).Warnf("user tried to %s application which they do not have access to: %s", action, err)
if project != "" {
// The user specified a project. We would have returned a 404 if the user had access to the app, but the app
// did not exist. So we have to return a 404 when the app does exist, but the user does not have access.
// Otherwise, they could infer that the app exists based on the error code.
return nil, nil, status.Errorf(codes.NotFound, apierr.NewNotFound(schema.GroupResource{Group: "argoproj.io", Resource: "applications"}, name).Error())
}
// The user didn't specify a project. We always return permission denied for both lack of access and lack of
// existence.
return nil, nil, permissionDeniedErr
}
effectiveProject := "default"
if a.Spec.Project != "" {
effectiveProject = a.Spec.Project
}
if project != "" && effectiveProject != project {
logCtx.WithFields(map[string]interface{}{
"project": a.Spec.Project,
argocommon.SecurityField: argocommon.SecurityMedium,
}).Warnf("user tried to %s application in project %s, but the application is in project %s", action, project, effectiveProject)
// The user has access to the app, but the app is in a different project. Return 404, meaning "app doesn't
// exist in that project".
return nil, nil, status.Errorf(codes.NotFound, apierr.NewNotFound(schema.GroupResource{Group: "argoproj.io", Resource: "applications"}, name).Error())
}
// Get the app's associated project, and make sure all project restrictions are enforced.
proj, err := s.getAppProject(ctx, a, logCtx)
if err != nil {
return a, nil, err
}
return a, proj, nil
}
// getApplicationEnforceRBACInformer uses an informer to get an Application. If the app does not exist, permission is
// denied, or any other error occurs when getting the app, we return a permission denied error to obscure any sensitive
// information.
func (s *Server) getApplicationEnforceRBACInformer(ctx context.Context, action, project, namespace, name string) (*appv1.Application, *appv1.AppProject, error) {
namespaceOrDefault := s.appNamespaceOrDefault(namespace)
return s.getAppEnforceRBAC(ctx, action, project, namespaceOrDefault, name, func() (*appv1.Application, error) {
return s.appLister.Applications(namespaceOrDefault).Get(name)
})
}
// getApplicationEnforceRBACClient uses a client to get an Application. If the app does not exist, permission is denied,
// or any other error occurs when getting the app, we return a permission denied error to obscure any sensitive
// information.
func (s *Server) getApplicationEnforceRBACClient(ctx context.Context, action, project, namespace, name, resourceVersion string) (*appv1.Application, *appv1.AppProject, error) {
namespaceOrDefault := s.appNamespaceOrDefault(namespace)
return s.getAppEnforceRBAC(ctx, action, project, namespaceOrDefault, name, func() (*appv1.Application, error) {
if !s.isNamespaceEnabled(namespaceOrDefault) {
return nil, security.NamespaceNotPermittedError(namespaceOrDefault)
}
return s.appclientset.ArgoprojV1alpha1().Applications(namespaceOrDefault).Get(ctx, name, metav1.GetOptions{
ResourceVersion: resourceVersion,
})
})
}
// List returns list of applications
func (s *Server) List(ctx context.Context, q *application.ApplicationQuery) (*appv1.ApplicationList, error) {
selector, err := labels.Parse(q.GetSelector())
if err != nil {
return nil, fmt.Errorf("error parsing the selector: %w", err)
}
var apps []*appv1.Application
if q.GetAppNamespace() == "" {
apps, err = s.appLister.List(selector)
} else {
apps, err = s.appLister.Applications(q.GetAppNamespace()).List(selector)
}
if err != nil {
return nil, fmt.Errorf("error listing apps with selectors: %w", err)
}
filteredApps := apps
// Filter applications by name
if q.Name != nil {
filteredApps = argoutil.FilterByNameP(filteredApps, *q.Name)
}
// Filter applications by projects
filteredApps = argoutil.FilterByProjectsP(filteredApps, getProjectsFromApplicationQuery(*q))
// Filter applications by source repo URL
filteredApps = argoutil.FilterByRepoP(filteredApps, q.GetRepo())
newItems := make([]appv1.Application, 0)
for _, a := range filteredApps {
// Skip any application that is neither in the control plane's namespace
// nor in the list of enabled namespaces.
if !s.isNamespaceEnabled(a.Namespace) {
continue
}
if s.enf.Enforce(ctx.Value("claims"), rbacpolicy.ResourceApplications, rbacpolicy.ActionGet, a.RBACName(s.ns)) {
newItems = append(newItems, *a)
}
}
// Sort found applications by name
sort.Slice(newItems, func(i, j int) bool {
return newItems[i].Name < newItems[j].Name
})
appList := appv1.ApplicationList{
ListMeta: metav1.ListMeta{
ResourceVersion: s.appInformer.LastSyncResourceVersion(),
},
Items: newItems,
}
return &appList, nil
}
// Create creates an application
func (s *Server) Create(ctx context.Context, q *application.ApplicationCreateRequest) (*appv1.Application, error) {
if q.GetApplication() == nil {
return nil, fmt.Errorf("error creating application: application is nil in request")
}
a := q.GetApplication()
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceApplications, rbacpolicy.ActionCreate, a.RBACName(s.ns)); err != nil {
return nil, err
}
s.projectLock.RLock(a.Spec.GetProject())
defer s.projectLock.RUnlock(a.Spec.GetProject())
validate := true
if q.Validate != nil {
validate = *q.Validate
}
proj, err := s.getAppProject(ctx, a, log.WithField("application", a.Name))
if err != nil {
return nil, err
}
err = s.validateAndNormalizeApp(ctx, a, proj, validate)
if err != nil {
return nil, fmt.Errorf("error while validating and normalizing app: %w", err)
}
appNs := s.appNamespaceOrDefault(a.Namespace)
if !s.isNamespaceEnabled(appNs) {
return nil, security.NamespaceNotPermittedError(appNs)
}
// Don't let the app creator set the operation explicitly. Those requests should always go through the Sync API.
if a.Operation != nil {
log.WithFields(log.Fields{
"application": a.Name,
argocommon.SecurityField: argocommon.SecurityLow,
}).Warn("User attempted to set operation on application creation. This could have allowed them to bypass branch protection rules by setting manifests directly. Ignoring the set operation.")
a.Operation = nil
}
created, err := s.appclientset.ArgoprojV1alpha1().Applications(appNs).Create(ctx, a, metav1.CreateOptions{})
if err == nil {
s.logAppEvent(created, ctx, argo.EventReasonResourceCreated, "created application")
s.waitSync(created)
return created, nil
}
if !apierr.IsAlreadyExists(err) {
return nil, fmt.Errorf("error creating application: %w", err)
}
// act idempotent if existing spec matches new spec
existing, err := s.appLister.Applications(appNs).Get(a.Name)
if err != nil {
return nil, status.Errorf(codes.Internal, "unable to check existing application details (%s): %v", appNs, err)
}
equalSpecs := reflect.DeepEqual(existing.Spec, a.Spec) &&
reflect.DeepEqual(existing.Labels, a.Labels) &&
reflect.DeepEqual(existing.Annotations, a.Annotations) &&
reflect.DeepEqual(existing.Finalizers, a.Finalizers)
if equalSpecs {
return existing, nil
}
if q.Upsert == nil || !*q.Upsert {
return nil, status.Errorf(codes.InvalidArgument, "existing application spec is different, use upsert flag to force update")
}
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceApplications, rbacpolicy.ActionUpdate, a.RBACName(s.ns)); err != nil {
return nil, err
}
updated, err := s.updateApp(existing, a, ctx, true)
if err != nil {
return nil, fmt.Errorf("error updating application: %w", err)
}
return updated, nil
}
func (s *Server) queryRepoServer(ctx context.Context, proj *appv1.AppProject, action func(
client apiclient.RepoServerServiceClient,
helmRepos []*appv1.Repository,
helmCreds []*appv1.RepoCreds,
helmOptions *appv1.HelmOptions,
enabledSourceTypes map[string]bool,
) error) error {
closer, client, err := s.repoClientset.NewRepoServerClient()
if err != nil {
return fmt.Errorf("error creating repo server client: %w", err)
}
defer ioutil.Close(closer)
helmRepos, err := s.db.ListHelmRepositories(ctx)
if err != nil {
return fmt.Errorf("error listing helm repositories: %w", err)
}
permittedHelmRepos, err := argo.GetPermittedRepos(proj, helmRepos)
if err != nil {
return fmt.Errorf("error retrieving permitted repos: %w", err)
}
helmRepositoryCredentials, err := s.db.GetAllHelmRepositoryCredentials(ctx)
if err != nil {
return fmt.Errorf("error getting helm repository credentials: %w", err)
}
helmOptions, err := s.settingsMgr.GetHelmSettings()
if err != nil {
return fmt.Errorf("error getting helm settings: %w", err)
}
permittedHelmCredentials, err := argo.GetPermittedReposCredentials(proj, helmRepositoryCredentials)
if err != nil {
return fmt.Errorf("error getting permitted repos credentials: %w", err)
}
enabledSourceTypes, err := s.settingsMgr.GetEnabledSourceTypes()
if err != nil {
return fmt.Errorf("error getting settings enabled source types: %w", err)
}
return action(client, permittedHelmRepos, permittedHelmCredentials, helmOptions, enabledSourceTypes)
}
// GetManifests returns application manifests
func (s *Server) GetManifests(ctx context.Context, q *application.ApplicationManifestQuery) (*apiclient.ManifestResponse, error) {
if q.Name == nil || *q.Name == "" {
return nil, fmt.Errorf("invalid request: application name is missing")
}
a, proj, err := s.getApplicationEnforceRBACInformer(ctx, rbacpolicy.ActionGet, q.GetProject(), q.GetAppNamespace(), q.GetName())
if err != nil {
return nil, err
}
if !s.isNamespaceEnabled(a.Namespace) {
return nil, security.NamespaceNotPermittedError(a.Namespace)
}
manifestInfos := make([]*apiclient.ManifestResponse, 0)
err = s.queryRepoServer(ctx, proj, func(
client apiclient.RepoServerServiceClient, helmRepos []*appv1.Repository, helmCreds []*appv1.RepoCreds, helmOptions *appv1.HelmOptions, enableGenerateManifests map[string]bool) error {
appInstanceLabelKey, err := s.settingsMgr.GetAppInstanceLabelKey()
if err != nil {
return fmt.Errorf("error getting app instance label key from settings: %w", err)
}
config, err := s.getApplicationClusterConfig(ctx, a)
if err != nil {
return fmt.Errorf("error getting application cluster config: %w", err)
}
serverVersion, err := s.kubectl.GetServerVersion(config)
if err != nil {
return fmt.Errorf("error getting server version: %w", err)
}
apiResources, err := s.kubectl.GetAPIResources(config, false, kubecache.NewNoopSettings())
if err != nil {
return fmt.Errorf("error getting API resources: %w", err)
}
sources := make([]appv1.ApplicationSource, 0)
if a.Spec.HasMultipleSources() {
numOfSources := int64(len(a.Spec.GetSources()))
for i, pos := range q.SourcePositions {
if pos <= 0 || pos > numOfSources {
return fmt.Errorf("source position is out of range")
}
a.Spec.Sources[pos-1].TargetRevision = q.Revisions[i]
}
sources = a.Spec.GetSources()
} else {
source := a.Spec.GetSource()
if q.GetRevision() != "" {
source.TargetRevision = q.GetRevision()
}
sources = append(sources, source)
}
// Store the map of all sources having ref field into a map for applications with sources field
refSources, err := argo.GetRefSources(context.Background(), a.Spec, s.db)
if err != nil {
return fmt.Errorf("failed to get ref sources: %v", err)
}
for _, source := range sources {
repo, err := s.db.GetRepository(ctx, source.RepoURL)
if err != nil {
return fmt.Errorf("error getting repository: %w", err)
}
kustomizeSettings, err := s.settingsMgr.GetKustomizeSettings()
if err != nil {
return fmt.Errorf("error getting kustomize settings: %w", err)
}
kustomizeOptions, err := kustomizeSettings.GetOptions(source)
if err != nil {
return fmt.Errorf("error getting kustomize settings options: %w", err)
}
manifestInfo, err := client.GenerateManifest(ctx, &apiclient.ManifestRequest{
Repo: repo,
Revision: source.TargetRevision,
AppLabelKey: appInstanceLabelKey,
AppName: a.InstanceName(s.ns),
Namespace: a.Spec.Destination.Namespace,
ApplicationSource: &source,
Repos: helmRepos,
KustomizeOptions: kustomizeOptions,
KubeVersion: serverVersion,
ApiVersions: argo.APIResourcesToStrings(apiResources, true),
HelmRepoCreds: helmCreds,
HelmOptions: helmOptions,
TrackingMethod: string(argoutil.GetTrackingMethod(s.settingsMgr)),
EnabledSourceTypes: enableGenerateManifests,
ProjectName: proj.Name,
ProjectSourceRepos: proj.Spec.SourceRepos,
HasMultipleSources: a.Spec.HasMultipleSources(),
RefSources: refSources,
})
if err != nil {
return fmt.Errorf("error generating manifests: %w", err)
}
manifestInfos = append(manifestInfos, manifestInfo)
}
return nil
})
if err != nil {
return nil, err
}
manifests := &apiclient.ManifestResponse{}
for _, manifestInfo := range manifestInfos {
for i, manifest := range manifestInfo.Manifests {
obj := &unstructured.Unstructured{}
err = json.Unmarshal([]byte(manifest), obj)
if err != nil {
return nil, fmt.Errorf("error unmarshaling manifest into unstructured: %w", err)
}
if obj.GetKind() == kube.SecretKind && obj.GroupVersionKind().Group == "" {
obj, _, err = diff.HideSecretData(obj, nil)
if err != nil {
return nil, fmt.Errorf("error hiding secret data: %w", err)
}
data, err := json.Marshal(obj)
if err != nil {
return nil, fmt.Errorf("error marshaling manifest: %w", err)
}
manifestInfo.Manifests[i] = string(data)
}
}
manifests.Manifests = manifestInfo.Manifests
}
return manifests, nil
}
func (s *Server) GetManifestsWithFiles(stream application.ApplicationService_GetManifestsWithFilesServer) error {
ctx := stream.Context()
query, err := manifeststream.ReceiveApplicationManifestQueryWithFiles(stream)
if err != nil {
return fmt.Errorf("error getting query: %w", err)
}
if query.Name == nil || *query.Name == "" {
return fmt.Errorf("invalid request: application name is missing")
}
a, proj, err := s.getApplicationEnforceRBACInformer(ctx, rbacpolicy.ActionGet, query.GetProject(), query.GetAppNamespace(), query.GetName())
if err != nil {
return err
}
var manifestInfo *apiclient.ManifestResponse
err = s.queryRepoServer(ctx, proj, func(
client apiclient.RepoServerServiceClient, helmRepos []*appv1.Repository, helmCreds []*appv1.RepoCreds, helmOptions *appv1.HelmOptions, enableGenerateManifests map[string]bool) error {
appInstanceLabelKey, err := s.settingsMgr.GetAppInstanceLabelKey()
if err != nil {
return fmt.Errorf("error getting app instance label key from settings: %w", err)
}
config, err := s.getApplicationClusterConfig(ctx, a)
if err != nil {
return fmt.Errorf("error getting application cluster config: %w", err)
}
serverVersion, err := s.kubectl.GetServerVersion(config)
if err != nil {
return fmt.Errorf("error getting server version: %w", err)
}
apiResources, err := s.kubectl.GetAPIResources(config, false, kubecache.NewNoopSettings())
if err != nil {
return fmt.Errorf("error getting API resources: %w", err)
}
source := a.Spec.GetSource()
proj, err := argo.GetAppProject(a, applisters.NewAppProjectLister(s.projInformer.GetIndexer()), s.ns, s.settingsMgr, s.db, ctx)
if err != nil {
return fmt.Errorf("error getting app project: %w", err)
}
repo, err := s.db.GetRepository(ctx, a.Spec.GetSource().RepoURL)
if err != nil {
return fmt.Errorf("error getting repository: %w", err)
}
kustomizeSettings, err := s.settingsMgr.GetKustomizeSettings()
if err != nil {
return fmt.Errorf("error getting kustomize settings: %w", err)
}
kustomizeOptions, err := kustomizeSettings.GetOptions(a.Spec.GetSource())
if err != nil {
return fmt.Errorf("error getting kustomize settings options: %w", err)
}
req := &apiclient.ManifestRequest{
Repo: repo,
Revision: source.TargetRevision,
AppLabelKey: appInstanceLabelKey,
AppName: a.Name,
Namespace: a.Spec.Destination.Namespace,
ApplicationSource: &source,
Repos: helmRepos,
KustomizeOptions: kustomizeOptions,
KubeVersion: serverVersion,
ApiVersions: argo.APIResourcesToStrings(apiResources, true),
HelmRepoCreds: helmCreds,
HelmOptions: helmOptions,
TrackingMethod: string(argoutil.GetTrackingMethod(s.settingsMgr)),
EnabledSourceTypes: enableGenerateManifests,
ProjectName: proj.Name,
ProjectSourceRepos: proj.Spec.SourceRepos,
}
repoStreamClient, err := client.GenerateManifestWithFiles(stream.Context())
if err != nil {
return fmt.Errorf("error opening stream: %w", err)
}
err = manifeststream.SendRepoStream(repoStreamClient, stream, req, *query.Checksum)
if err != nil {
return fmt.Errorf("error sending repo stream: %w", err)
}
resp, err := repoStreamClient.CloseAndRecv()
if err != nil {
return fmt.Errorf("error generating manifests: %w", err)
}
manifestInfo = resp
return nil
})
if err != nil {
return err
}
for i, manifest := range manifestInfo.Manifests {
obj := &unstructured.Unstructured{}
err = json.Unmarshal([]byte(manifest), obj)
if err != nil {
return fmt.Errorf("error unmarshaling manifest into unstructured: %w", err)
}
if obj.GetKind() == kube.SecretKind && obj.GroupVersionKind().Group == "" {
obj, _, err = diff.HideSecretData(obj, nil)
if err != nil {
return fmt.Errorf("error hiding secret data: %w", err)
}
data, err := json.Marshal(obj)
if err != nil {
return fmt.Errorf("error marshaling manifest: %w", err)
}
manifestInfo.Manifests[i] = string(data)
}
}
stream.SendAndClose(manifestInfo)
return nil
}
// Get returns an application by name
func (s *Server) Get(ctx context.Context, q *application.ApplicationQuery) (*appv1.Application, error) {
appName := q.GetName()
appNs := s.appNamespaceOrDefault(q.GetAppNamespace())
project := ""
projects := getProjectsFromApplicationQuery(*q)
if len(projects) == 1 {
project = projects[0]
} else if len(projects) > 1 {
return nil, status.Errorf(codes.InvalidArgument, "multiple projects specified - the get endpoint accepts either zero or one project")
}
// We must use a client Get instead of an informer Get, because it's common to call Get immediately
// following a Watch (which is not yet powered by an informer), and the Get must reflect what was
// previously seen by the client.
a, proj, err := s.getApplicationEnforceRBACClient(ctx, rbacpolicy.ActionGet, project, appNs, appName, q.GetResourceVersion())
if err != nil {
return nil, err
}
s.inferResourcesStatusHealth(a)
if q.Refresh == nil {
return a, nil
}
refreshType := appv1.RefreshTypeNormal
if *q.Refresh == string(appv1.RefreshTypeHard) {
refreshType = appv1.RefreshTypeHard
}
appIf := s.appclientset.ArgoprojV1alpha1().Applications(appNs)
// subscribe early with buffered channel to ensure we don't miss events
events := make(chan *appv1.ApplicationWatchEvent, watchAPIBufferSize)
unsubscribe := s.appBroadcaster.Subscribe(events, func(event *appv1.ApplicationWatchEvent) bool {
return event.Application.Name == appName && event.Application.Namespace == appNs
})
defer unsubscribe()
app, err := argoutil.RefreshApp(appIf, appName, refreshType)
if err != nil {
return nil, fmt.Errorf("error refreshing the app: %w", err)
}
if refreshType == appv1.RefreshTypeHard {
// force refresh cached application details
if err := s.queryRepoServer(ctx, proj, func(
client apiclient.RepoServerServiceClient,
helmRepos []*appv1.Repository,
_ []*appv1.RepoCreds,
helmOptions *appv1.HelmOptions,
enabledSourceTypes map[string]bool,
) error {
source := app.Spec.GetSource()
repo, err := s.db.GetRepository(ctx, a.Spec.GetSource().RepoURL)
if err != nil {
return fmt.Errorf("error getting repository: %w", err)
}
kustomizeSettings, err := s.settingsMgr.GetKustomizeSettings()
if err != nil {
return fmt.Errorf("error getting kustomize settings: %w", err)
}
kustomizeOptions, err := kustomizeSettings.GetOptions(a.Spec.GetSource())
if err != nil {
return fmt.Errorf("error getting kustomize settings options: %w", err)
}
_, err = client.GetAppDetails(ctx, &apiclient.RepoServerAppDetailsQuery{
Repo: repo,
Source: &source,
AppName: appName,
KustomizeOptions: kustomizeOptions,
Repos: helmRepos,
NoCache: true,
TrackingMethod: string(argoutil.GetTrackingMethod(s.settingsMgr)),
EnabledSourceTypes: enabledSourceTypes,
HelmOptions: helmOptions,
})
return err
}); err != nil {
log.Warnf("Failed to force refresh application details: %v", err)
}
}
minVersion := 0
if minVersion, err = strconv.Atoi(app.ResourceVersion); err != nil {
minVersion = 0
}
for {
select {
case <-ctx.Done():
return nil, fmt.Errorf("application refresh deadline exceeded")
case event := <-events:
if appVersion, err := strconv.Atoi(event.Application.ResourceVersion); err == nil && appVersion > minVersion {
annotations := event.Application.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
if _, ok := annotations[appv1.AnnotationKeyRefresh]; !ok {
return &event.Application, nil
}
}
}
}
}
// ListResourceEvents returns a list of event resources
func (s *Server) ListResourceEvents(ctx context.Context, q *application.ApplicationResourceEventsQuery) (*v1.EventList, error) {
a, _, err := s.getApplicationEnforceRBACInformer(ctx, rbacpolicy.ActionGet, q.GetProject(), q.GetAppNamespace(), q.GetName())
if err != nil {
return nil, err
}
var (
kubeClientset kubernetes.Interface
fieldSelector string
namespace string
)
// There are two places where we get events. If we are getting application events, we query
// our own cluster. If it is events on a resource on an external cluster, then we query the
// external cluster using its rest.Config
if q.GetResourceName() == "" && q.GetResourceUID() == "" {
kubeClientset = s.kubeclientset
namespace = a.Namespace
fieldSelector = fields.SelectorFromSet(map[string]string{
"involvedObject.name": a.Name,
"involvedObject.uid": string(a.UID),
"involvedObject.namespace": a.Namespace,
}).String()
} else {
tree, err := s.getAppResources(ctx, a)
if err != nil {
return nil, fmt.Errorf("error getting app resources: %w", err)
}
found := false
for _, n := range append(tree.Nodes, tree.OrphanedNodes...) {
if n.ResourceRef.UID == q.GetResourceUID() && n.ResourceRef.Name == q.GetResourceName() && n.ResourceRef.Namespace == q.GetResourceNamespace() {
found = true
break
}
}
if !found {
return nil, status.Errorf(codes.InvalidArgument, "%s not found as part of application %s", q.GetResourceName(), q.GetName())
}
namespace = q.GetResourceNamespace()
var config *rest.Config
config, err = s.getApplicationClusterConfig(ctx, a)
if err != nil {
return nil, fmt.Errorf("error getting application cluster config: %w", err)
}
kubeClientset, err = kubernetes.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("error creating kube client: %w", err)
}
fieldSelector = fields.SelectorFromSet(map[string]string{
"involvedObject.name": q.GetResourceName(),
"involvedObject.uid": q.GetResourceUID(),
"involvedObject.namespace": namespace,
}).String()
}
log.Infof("Querying for resource events with field selector: %s", fieldSelector)
opts := metav1.ListOptions{FieldSelector: fieldSelector}
list, err := kubeClientset.CoreV1().Events(namespace).List(ctx, opts)
if err != nil {
return nil, fmt.Errorf("error listing resource events: %w", err)
}
return list, nil
}
// validateAndUpdateApp validates and updates the application. currentProject is the name of the project the app
// currently is under. If not specified, we assume that the app is under the project specified in the app spec.
func (s *Server) validateAndUpdateApp(ctx context.Context, newApp *appv1.Application, merge bool, validate bool, action string, currentProject string) (*appv1.Application, error) {
s.projectLock.RLock(newApp.Spec.GetProject())
defer s.projectLock.RUnlock(newApp.Spec.GetProject())
app, proj, err := s.getApplicationEnforceRBACClient(ctx, action, currentProject, newApp.Namespace, newApp.Name, "")
if err != nil {
return nil, err
}
err = s.validateAndNormalizeApp(ctx, newApp, proj, validate)
if err != nil {
return nil, fmt.Errorf("error validating and normalizing app: %w", err)
}
a, err := s.updateApp(app, newApp, ctx, merge)
if err != nil {
return nil, fmt.Errorf("error updating application: %w", err)
}
return a, nil
}
var informerSyncTimeout = 2 * time.Second
// waitSync is a helper to wait until the application informer cache is synced after create/update.
// It waits until the app in the informer, has a resource version greater than the version in the
// supplied app, or after 2 seconds, whichever comes first. Returns true if synced.
// We use an informer cache for read operations (Get, List). Since the cache is only
// eventually consistent, it is possible that it doesn't reflect an application change immediately
// after a mutating API call (create/update). This function should be called after a creates &
// update to give a probable (but not guaranteed) chance of being up-to-date after the create/update.
func (s *Server) waitSync(app *appv1.Application) {
logCtx := log.WithField("application", app.Name)
deadline := time.Now().Add(informerSyncTimeout)
minVersion, err := strconv.Atoi(app.ResourceVersion)
if err != nil {
logCtx.Warnf("waitSync failed: could not parse resource version %s", app.ResourceVersion)
time.Sleep(50 * time.Millisecond) // sleep anyway
return
}
for {
if currApp, err := s.appLister.Applications(app.Namespace).Get(app.Name); err == nil {
currVersion, err := strconv.Atoi(currApp.ResourceVersion)
if err == nil && currVersion >= minVersion {
return
}
}
if time.Now().After(deadline) {
break
}
time.Sleep(20 * time.Millisecond)
}
logCtx.Warnf("waitSync failed: timed out")
}
func (s *Server) updateApp(app *appv1.Application, newApp *appv1.Application, ctx context.Context, merge bool) (*appv1.Application, error) {
for i := 0; i < 10; i++ {
app.Spec = newApp.Spec
if merge {
app.Labels = collections.MergeStringMaps(app.Labels, newApp.Labels)
app.Annotations = collections.MergeStringMaps(app.Annotations, newApp.Annotations)
} else {
app.Labels = newApp.Labels
app.Annotations = newApp.Annotations
}
app.Finalizers = newApp.Finalizers
res, err := s.appclientset.ArgoprojV1alpha1().Applications(app.Namespace).Update(ctx, app, metav1.UpdateOptions{})
if err == nil {
s.logAppEvent(app, ctx, argo.EventReasonResourceUpdated, "updated application spec")
s.waitSync(res)
return res, nil
}
if !apierr.IsConflict(err) {
return nil, err
}
app, err = s.appclientset.ArgoprojV1alpha1().Applications(app.Namespace).Get(ctx, newApp.Name, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("error getting application: %w", err)
}
s.inferResourcesStatusHealth(app)
}
return nil, status.Errorf(codes.Internal, "Failed to update application. Too many conflicts")
}
// Update updates an application
func (s *Server) Update(ctx context.Context, q *application.ApplicationUpdateRequest) (*appv1.Application, error) {
if q.GetApplication() == nil {
return nil, fmt.Errorf("error updating application: application is nil in request")
}
a := q.GetApplication()
if err := s.enf.EnforceErr(ctx.Value("claims"), rbacpolicy.ResourceApplications, rbacpolicy.ActionUpdate, a.RBACName(s.ns)); err != nil {
return nil, err
}
validate := true
if q.Validate != nil {
validate = *q.Validate
}
return s.validateAndUpdateApp(ctx, q.Application, false, validate, rbacpolicy.ActionUpdate, q.GetProject())
}
// UpdateSpec updates an application spec and filters out any invalid parameter overrides
func (s *Server) UpdateSpec(ctx context.Context, q *application.ApplicationUpdateSpecRequest) (*appv1.ApplicationSpec, error) {
if q.GetSpec() == nil {
return nil, fmt.Errorf("error updating application spec: spec is nil in request")
}
a, _, err := s.getApplicationEnforceRBACClient(ctx, rbacpolicy.ActionUpdate, q.GetProject(), q.GetAppNamespace(), q.GetName(), "")
if err != nil {
return nil, err
}
a.Spec = *q.GetSpec()
validate := true
if q.Validate != nil {
validate = *q.Validate
}
a, err = s.validateAndUpdateApp(ctx, a, false, validate, rbacpolicy.ActionUpdate, q.GetProject())
if err != nil {
return nil, fmt.Errorf("error validating and updating app: %w", err)
}
return &a.Spec, nil
}
// Patch patches an application
func (s *Server) Patch(ctx context.Context, q *application.ApplicationPatchRequest) (*appv1.Application, error) {
app, _, err := s.getApplicationEnforceRBACClient(ctx, rbacpolicy.ActionGet, q.GetProject(), q.GetAppNamespace(), q.GetName(), "")
if err != nil {
return nil, err
}