-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
settings.go
1254 lines (1133 loc) · 39.8 KB
/
settings.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 settings
import (
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"net/url"
"os"
"path"
"reflect"
"strings"
"sync"
"time"
"github.com/argoproj/gitops-engine/pkg/diff"
"github.com/ghodss/yaml"
log "github.com/sirupsen/logrus"
apiv1 "k8s.io/api/core/v1"
apierr "k8s.io/apimachinery/pkg/api/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
v1 "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
v1listers "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"github.com/argoproj/argo-cd/common"
"github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1"
"github.com/argoproj/argo-cd/server/settings/oidc"
"github.com/argoproj/argo-cd/util"
"github.com/argoproj/argo-cd/util/password"
tlsutil "github.com/argoproj/argo-cd/util/tls"
)
// ArgoCDSettings holds in-memory runtime configuration options.
type ArgoCDSettings struct {
// URL is the externally facing URL users will visit to reach Argo CD.
// The value here is used when configuring SSO. Omitting this value will disable SSO.
URL string `json:"url,omitempty"`
// Indicates if status badge is enabled or not.
StatusBadgeEnabled bool `json:"statusBadgeEnable"`
// DexConfig contains portions of a dex config yaml
DexConfig string `json:"dexConfig,omitempty"`
// OIDCConfigRAW holds OIDC configuration as a raw string
OIDCConfigRAW string `json:"oidcConfig,omitempty"`
// ServerSignature holds the key used to generate JWT tokens.
ServerSignature []byte `json:"serverSignature,omitempty"`
// Certificate holds the certificate/private key for the Argo CD API server.
// If nil, will run insecure without TLS.
Certificate *tls.Certificate `json:"-"`
// WebhookGitLabSecret holds the shared secret for authenticating GitHub webhook events
WebhookGitHubSecret string `json:"webhookGitHubSecret,omitempty"`
// WebhookGitLabSecret holds the shared secret for authenticating GitLab webhook events
WebhookGitLabSecret string `json:"webhookGitLabSecret,omitempty"`
// WebhookBitbucketUUID holds the UUID for authenticating Bitbucket webhook events
WebhookBitbucketUUID string `json:"webhookBitbucketUUID,omitempty"`
// WebhookBitbucketServerSecret holds the shared secret for authenticating BitbucketServer webhook events
WebhookBitbucketServerSecret string `json:"webhookBitbucketServerSecret,omitempty"`
// WebhookGogsSecret holds the shared secret for authenticating Gogs webhook events
WebhookGogsSecret string `json:"webhookGogsSecret,omitempty"`
// Secrets holds all secrets in argocd-secret as a map[string]string
Secrets map[string]string `json:"secrets,omitempty"`
// KustomizeBuildOptions is a string of kustomize build parameters
KustomizeBuildOptions string `json:"kustomizeBuildOptions,omitempty"`
// Indicates if anonymous user is enabled or not
AnonymousUserEnabled bool `json:"anonymousUserEnabled,omitempty"`
// UiCssURL local or remote path to user-defined CSS to customize ArgoCD UI
UiCssURL string `json:"uiCssURL,omitempty"`
}
type GoogleAnalytics struct {
TrackingID string `json:"trackingID,omitempty"`
AnonymizeUsers bool `json:"anonymizeUsers,omitempty"`
}
// Help settings
type Help struct {
// the URL for getting chat help, this will typically be your Slack channel for support
ChatURL string `json:"chatUrl,omitempty"`
// the text for getting chat help, defaults to "Chat now!"
ChatText string `json:"chatText,omitempty"`
}
type OIDCConfig struct {
Name string `json:"name,omitempty"`
Issuer string `json:"issuer,omitempty"`
ClientID string `json:"clientID,omitempty"`
ClientSecret string `json:"clientSecret,omitempty"`
CLIClientID string `json:"cliClientID,omitempty"`
RequestedScopes []string `json:"requestedScopes,omitempty"`
RequestedIDTokenClaims map[string]*oidc.Claim `json:"requestedIDTokenClaims,omitempty"`
}
// DEPRECATED. Helm repository credentials are now managed using RepoCredentials
type HelmRepoCredentials struct {
URL string `json:"url,omitempty"`
Name string `json:"name,omitempty"`
UsernameSecret *apiv1.SecretKeySelector `json:"usernameSecret,omitempty"`
PasswordSecret *apiv1.SecretKeySelector `json:"passwordSecret,omitempty"`
CertSecret *apiv1.SecretKeySelector `json:"certSecret,omitempty"`
KeySecret *apiv1.SecretKeySelector `json:"keySecret,omitempty"`
}
// KustomizeVersion holds information about additional Kustomize version
type KustomizeVersion struct {
// Name holds Kustomize version name
Name string
// Name holds corresponding binary path
Path string
}
// KustomizeSettings holds kustomize settings
type KustomizeSettings struct {
BuildOptions string
Versions []KustomizeVersion
}
func (ks *KustomizeSettings) GetOptions(source v1alpha1.ApplicationSource) (*v1alpha1.KustomizeOptions, error) {
binaryPath := ""
if source.Kustomize != nil && source.Kustomize.Version != "" {
for _, ver := range ks.Versions {
if ver.Name == source.Kustomize.Version {
binaryPath = ver.Path
break
}
}
if binaryPath == "" {
return nil, fmt.Errorf("kustomize version %s is not registered", source.Kustomize.Version)
}
}
return &v1alpha1.KustomizeOptions{
BuildOptions: ks.BuildOptions,
BinaryPath: binaryPath,
}, nil
}
// Credentials for accessing a Git repository
type Repository struct {
// The URL to the repository
URL string `json:"url,omitempty"`
// the type of the repo, "git" or "helm", assumed to be "git" if empty or absent
Type string `json:"type,omitempty"`
// helm only
Name string `json:"name,omitempty"`
// Name of the secret storing the username used to access the repo
UsernameSecret *apiv1.SecretKeySelector `json:"usernameSecret,omitempty"`
// Name of the secret storing the password used to access the repo
PasswordSecret *apiv1.SecretKeySelector `json:"passwordSecret,omitempty"`
// Name of the secret storing the SSH private key used to access the repo. Git only
SSHPrivateKeySecret *apiv1.SecretKeySelector `json:"sshPrivateKeySecret,omitempty"`
// Whether to connect the repository in an insecure way (deprecated)
InsecureIgnoreHostKey bool `json:"insecureIgnoreHostKey,omitempty"`
// Whether to connect the repository in an insecure way
Insecure bool `json:"insecure,omitempty"`
// Whether the repo is git-lfs enabled. Git only.
EnableLFS bool `json:"enableLfs,omitempty"`
// Name of the secret storing the TLS client cert data
TLSClientCertDataSecret *apiv1.SecretKeySelector `json:"tlsClientCertDataSecret,omitempty"`
// Name of the secret storing the TLS client cert's key data
TLSClientCertKeySecret *apiv1.SecretKeySelector `json:"tlsClientCertKeySecret,omitempty"`
}
// Credential template for accessing repositories
type RepositoryCredentials struct {
// The URL pattern the repository URL has to match
URL string `json:"url,omitempty"`
// Name of the secret storing the username used to access the repo
UsernameSecret *apiv1.SecretKeySelector `json:"usernameSecret,omitempty"`
// Name of the secret storing the password used to access the repo
PasswordSecret *apiv1.SecretKeySelector `json:"passwordSecret,omitempty"`
// Name of the secret storing the SSH private key used to access the repo. Git only
SSHPrivateKeySecret *apiv1.SecretKeySelector `json:"sshPrivateKeySecret,omitempty"`
// Name of the secret storing the TLS client cert data
TLSClientCertDataSecret *apiv1.SecretKeySelector `json:"tlsClientCertDataSecret,omitempty"`
// Name of the secret storing the TLS client cert's key data
TLSClientCertKeySecret *apiv1.SecretKeySelector `json:"tlsClientCertKeySecret,omitempty"`
}
const (
// settingServerSignatureKey designates the key for a server secret key inside a Kubernetes secret.
settingServerSignatureKey = "server.secretkey"
// gaTrackingID holds Google Analytics tracking id
gaTrackingID = "ga.trackingid"
// the URL for getting chat help, this will typically be your Slack channel for support
helpChatURL = "help.chatUrl"
// the text for getting chat help, defaults to "Chat now!"
helpChatText = "help.chatText"
// gaAnonymizeUsers specifies if user ids should be anonymized (hashed) before sending to Google Analytics. True unless value is set to 'false'
gaAnonymizeUsers = "ga.anonymizeusers"
// settingServerCertificate designates the key for the public cert used in TLS
settingServerCertificate = "tls.crt"
// settingServerPrivateKey designates the key for the private key used in TLS
settingServerPrivateKey = "tls.key"
// settingURLKey designates the key where Argo CD's external URL is set
settingURLKey = "url"
// repositoriesKey designates the key where ArgoCDs repositories list is set
repositoriesKey = "repositories"
// repositoryCredentialsKey designates the key where ArgoCDs repositories credentials list is set
repositoryCredentialsKey = "repository.credentials"
// helmRepositoriesKey designates the key where list of helm repositories is set
helmRepositoriesKey = "helm.repositories"
// settingDexConfigKey designates the key for the dex config
settingDexConfigKey = "dex.config"
// settingsOIDCConfigKey designates the key for OIDC config
settingsOIDCConfigKey = "oidc.config"
// statusBadgeEnabledKey holds the key which enables of disables status badge feature
statusBadgeEnabledKey = "statusbadge.enabled"
// settingsWebhookGitHubSecret is the key for the GitHub shared webhook secret
settingsWebhookGitHubSecretKey = "webhook.github.secret"
// settingsWebhookGitLabSecret is the key for the GitLab shared webhook secret
settingsWebhookGitLabSecretKey = "webhook.gitlab.secret"
// settingsWebhookBitbucketUUID is the key for Bitbucket webhook UUID
settingsWebhookBitbucketUUIDKey = "webhook.bitbucket.uuid"
// settingsWebhookBitbucketServerSecret is the key for BitbucketServer webhook secret
settingsWebhookBitbucketServerSecretKey = "webhook.bitbucketserver.secret"
// settingsWebhookGogsSecret is the key for Gogs webhook secret
settingsWebhookGogsSecretKey = "webhook.gogs.secret"
// settingsApplicationInstanceLabelKey is the key to configure injected app instance label key
settingsApplicationInstanceLabelKey = "application.instanceLabelKey"
// resourcesCustomizationsKey is the key to the map of resource overrides
resourceCustomizationsKey = "resource.customizations"
// resourceExclusions is the key to the list of excluded resources
resourceExclusionsKey = "resource.exclusions"
// resourceInclusions is the key to the list of explicitly watched resources
resourceInclusionsKey = "resource.inclusions"
// configManagementPluginsKey is the key to the list of config management plugins
configManagementPluginsKey = "configManagementPlugins"
// kustomizeBuildOptionsKey is a string of kustomize build parameters
kustomizeBuildOptionsKey = "kustomize.buildOptions"
// kustomizeVersionKeyPrefix is a kustomize version key prefix
kustomizeVersionKeyPrefix = "kustomize.version"
// anonymousUserEnabledKey is the key which enables or disables anonymous user
anonymousUserEnabledKey = "users.anonymous.enabled"
// diffOptions is the key where diff options are configured
resourceCompareOptionsKey = "resource.compareoptions"
// settingUiCssURLKey designates the key for user-defined CSS URL for UI customization
settingUiCssURLKey = "ui.cssurl"
)
// SettingsManager holds config info for a new manager with which to access Kubernetes ConfigMaps.
type SettingsManager struct {
ctx context.Context
clientset kubernetes.Interface
secrets v1listers.SecretLister
configmaps v1listers.ConfigMapLister
namespace string
// subscribers is a list of subscribers to settings updates
subscribers []chan<- *ArgoCDSettings
// mutex protects concurrency sensitive parts of settings manager: access to subscribers list and initialization flag
mutex *sync.Mutex
initContextCancel func()
reposCache []Repository
repoCredsCache []RepositoryCredentials
}
type incompleteSettingsError struct {
message string
}
type IgnoreStatus string
const (
// IgnoreResourceStatusInCRD ignores status changes for all CRDs
IgnoreResourceStatusInCRD IgnoreStatus = "crd"
// IgnoreResourceStatusInAll ignores status changes for all resources
IgnoreResourceStatusInAll IgnoreStatus = "all"
// IgnoreResourceStatusInNone ignores status changes for no resources
IgnoreResourceStatusInNone IgnoreStatus = "off"
)
type ArgoCDDiffOptions struct {
diff.DiffOptions
// If set to true then differences caused by status are ignored.
IgnoreResourceStatusField IgnoreStatus `json:"ignoreResourceStatusField,omitempty"`
}
func (e *incompleteSettingsError) Error() string {
return e.message
}
func (mgr *SettingsManager) GetSecretsLister() (v1listers.SecretLister, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
return mgr.secrets, nil
}
func (mgr *SettingsManager) updateSecret(callback func(*apiv1.Secret) error) error {
err := mgr.ensureSynced(false)
if err != nil {
return err
}
argoCDSecret, err := mgr.secrets.Secrets(mgr.namespace).Get(common.ArgoCDSecretName)
createSecret := false
if err != nil {
if !apierr.IsNotFound(err) {
return err
}
argoCDSecret = &apiv1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: common.ArgoCDSecretName,
},
Data: make(map[string][]byte),
}
createSecret = true
}
if argoCDSecret.Data == nil {
argoCDSecret.Data = make(map[string][]byte)
}
updatedSecret := argoCDSecret.DeepCopy()
err = callback(updatedSecret)
if err != nil {
return err
}
if !createSecret && reflect.DeepEqual(argoCDSecret, updatedSecret) {
return nil
}
if createSecret {
_, err = mgr.clientset.CoreV1().Secrets(mgr.namespace).Create(context.Background(), updatedSecret, metav1.CreateOptions{})
} else {
_, err = mgr.clientset.CoreV1().Secrets(mgr.namespace).Update(context.Background(), updatedSecret, metav1.UpdateOptions{})
}
if err != nil {
return err
}
return mgr.ResyncInformers()
}
func (mgr *SettingsManager) updateConfigMap(callback func(*apiv1.ConfigMap) error) error {
argoCDCM, err := mgr.getConfigMap()
createCM := false
if err != nil {
if !apierr.IsNotFound(err) {
return err
}
argoCDCM = &apiv1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: common.ArgoCDConfigMapName,
},
}
createCM = true
}
if argoCDCM.Data == nil {
argoCDCM.Data = make(map[string]string)
}
err = callback(argoCDCM)
if err != nil {
return err
}
if createCM {
_, err = mgr.clientset.CoreV1().ConfigMaps(mgr.namespace).Create(context.Background(), argoCDCM, metav1.CreateOptions{})
} else {
_, err = mgr.clientset.CoreV1().ConfigMaps(mgr.namespace).Update(context.Background(), argoCDCM, metav1.UpdateOptions{})
}
if err != nil {
return err
}
mgr.invalidateCache()
return mgr.ResyncInformers()
}
func (mgr *SettingsManager) getConfigMap() (*apiv1.ConfigMap, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
if err != nil {
return nil, err
}
if argoCDCM.Data == nil {
argoCDCM.Data = make(map[string]string)
}
return argoCDCM, err
}
// Returns the ConfigMap with the given name from the cluster.
// The ConfigMap must be labeled with "app.kubernetes.io/part-of: argocd" in
// order to be retrievable.
func (mgr *SettingsManager) GetConfigMapByName(configMapName string) (*apiv1.ConfigMap, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
configMap, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(configMapName)
if err != nil {
return nil, err
}
return configMap, err
}
func (mgr *SettingsManager) GetResourcesFilter() (*ResourcesFilter, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
rf := &ResourcesFilter{}
if value, ok := argoCDCM.Data[resourceInclusionsKey]; ok {
includedResources := make([]FilteredResource, 0)
err := yaml.Unmarshal([]byte(value), &includedResources)
if err != nil {
return nil, err
}
rf.ResourceInclusions = includedResources
}
if value, ok := argoCDCM.Data[resourceExclusionsKey]; ok {
excludedResources := make([]FilteredResource, 0)
err := yaml.Unmarshal([]byte(value), &excludedResources)
if err != nil {
return nil, err
}
rf.ResourceExclusions = excludedResources
}
return rf, nil
}
func (mgr *SettingsManager) GetAppInstanceLabelKey() (string, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return "", err
}
label := argoCDCM.Data[settingsApplicationInstanceLabelKey]
if label == "" {
return common.LabelKeyAppInstance, nil
}
return label, nil
}
func (mgr *SettingsManager) GetConfigManagementPlugins() ([]v1alpha1.ConfigManagementPlugin, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
plugins := make([]v1alpha1.ConfigManagementPlugin, 0)
if value, ok := argoCDCM.Data[configManagementPluginsKey]; ok {
err := yaml.Unmarshal([]byte(value), &plugins)
if err != nil {
return nil, err
}
}
return plugins, nil
}
// GetResourceOverrides loads Resource Overrides from argocd-cm ConfigMap
func (mgr *SettingsManager) GetResourceOverrides() (map[string]v1alpha1.ResourceOverride, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
resourceOverrides := map[string]v1alpha1.ResourceOverride{}
if value, ok := argoCDCM.Data[resourceCustomizationsKey]; ok {
err := yaml.Unmarshal([]byte(value), &resourceOverrides)
if err != nil {
return nil, err
}
}
var diffOptions ArgoCDDiffOptions
if value, ok := argoCDCM.Data[resourceCompareOptionsKey]; ok {
err := yaml.Unmarshal([]byte(value), &diffOptions)
if err != nil {
return nil, err
}
}
crdGK := "apiextensions.k8s.io/CustomResourceDefinition"
switch diffOptions.IgnoreResourceStatusField {
case "", "crd":
addStatusOverrideToGK(resourceOverrides, crdGK)
log.Info("Ignore status for CustomResourceDefinitions")
case "all":
addStatusOverrideToGK(resourceOverrides, "*/*")
log.Info("Ignore status for all objects")
case "off", "false":
log.Info("Not ignoring status for any object")
default:
addStatusOverrideToGK(resourceOverrides, crdGK)
log.Warnf("Unrecognized value for ignoreResourceStatusField - %s, ignore status for CustomResourceDefinitions", diffOptions.IgnoreResourceStatusField)
}
return resourceOverrides, nil
}
func addStatusOverrideToGK(resourceOverrides map[string]v1alpha1.ResourceOverride, groupKind string) {
if val, ok := resourceOverrides[groupKind]; ok {
val.IgnoreDifferences.JSONPointers = append(val.IgnoreDifferences.JSONPointers, "/status")
resourceOverrides[groupKind] = val
} else {
resourceOverrides[groupKind] = v1alpha1.ResourceOverride{
IgnoreDifferences: v1alpha1.OverrideIgnoreDiff{JSONPointers: []string{"/status"}},
}
}
}
// GetResourceCompareOptions loads the resource compare options settings from the ConfigMap
func (mgr *SettingsManager) GetResourceCompareOptions() (diff.DiffOptions, error) {
// We have a sane set of default diff options
diffOptions := diff.GetDefaultDiffOptions()
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return diffOptions, err
}
if value, ok := argoCDCM.Data[resourceCompareOptionsKey]; ok {
err := yaml.Unmarshal([]byte(value), &diffOptions)
if err != nil {
return diffOptions, err
}
}
return diffOptions, nil
}
// GetKustomizeSettings loads the kustomize settings from argocd-cm ConfigMap
func (mgr *SettingsManager) GetKustomizeSettings() (*KustomizeSettings, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
settings := &KustomizeSettings{}
if value, ok := argoCDCM.Data[kustomizeBuildOptionsKey]; ok {
settings.BuildOptions = value
}
for k, v := range argoCDCM.Data {
if !strings.HasPrefix(k, kustomizeVersionKeyPrefix) {
continue
}
settings.Versions = append(settings.Versions, KustomizeVersion{
Name: k[len(kustomizeVersionKeyPrefix)+1:],
Path: v,
})
}
return settings, nil
}
// DEPRECATED. Helm repository credentials are now managed using RepoCredentials
func (mgr *SettingsManager) GetHelmRepositories() ([]HelmRepoCredentials, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
helmRepositories := make([]HelmRepoCredentials, 0)
helmRepositoriesStr := argoCDCM.Data[helmRepositoriesKey]
if helmRepositoriesStr != "" {
err := yaml.Unmarshal([]byte(helmRepositoriesStr), &helmRepositories)
if err != nil {
return nil, err
}
}
return helmRepositories, nil
}
func (mgr *SettingsManager) GetRepositories() ([]Repository, error) {
if mgr.reposCache == nil {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
mgr.mutex.Lock()
defer mgr.mutex.Unlock()
repositories := make([]Repository, 0)
repositoriesStr := argoCDCM.Data[repositoriesKey]
if repositoriesStr != "" {
err := yaml.Unmarshal([]byte(repositoriesStr), &repositories)
if err != nil {
return nil, err
}
}
mgr.reposCache = repositories
}
return mgr.reposCache, nil
}
func (mgr *SettingsManager) SaveRepositories(repos []Repository) error {
return mgr.updateConfigMap(func(argoCDCM *apiv1.ConfigMap) error {
if len(repos) > 0 {
yamlStr, err := yaml.Marshal(repos)
if err != nil {
return err
}
argoCDCM.Data[repositoriesKey] = string(yamlStr)
} else {
delete(argoCDCM.Data, repositoriesKey)
}
return nil
})
}
func (mgr *SettingsManager) SaveRepositoryCredentials(creds []RepositoryCredentials) error {
return mgr.updateConfigMap(func(argoCDCM *apiv1.ConfigMap) error {
if len(creds) > 0 {
yamlStr, err := yaml.Marshal(creds)
if err != nil {
return err
}
argoCDCM.Data[repositoryCredentialsKey] = string(yamlStr)
} else {
delete(argoCDCM.Data, repositoryCredentialsKey)
}
return nil
})
}
func (mgr *SettingsManager) GetRepositoryCredentials() ([]RepositoryCredentials, error) {
if mgr.repoCredsCache == nil {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
mgr.mutex.Lock()
defer mgr.mutex.Unlock()
creds := make([]RepositoryCredentials, 0)
credsStr := argoCDCM.Data[repositoryCredentialsKey]
if credsStr != "" {
err := yaml.Unmarshal([]byte(credsStr), &creds)
if err != nil {
return nil, err
}
}
mgr.repoCredsCache = creds
}
return mgr.repoCredsCache, nil
}
func (mgr *SettingsManager) GetGoogleAnalytics() (*GoogleAnalytics, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
return &GoogleAnalytics{
TrackingID: argoCDCM.Data[gaTrackingID],
AnonymizeUsers: argoCDCM.Data[gaAnonymizeUsers] != "false",
}, nil
}
func (mgr *SettingsManager) GetHelp() (*Help, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
chatText, ok := argoCDCM.Data[helpChatText]
if !ok {
chatText = "Chat now!"
}
return &Help{
ChatURL: argoCDCM.Data[helpChatURL],
ChatText: chatText,
}, nil
}
// GetSettings retrieves settings from the ArgoCDConfigMap and secret.
func (mgr *SettingsManager) GetSettings() (*ArgoCDSettings, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
if err != nil {
return nil, err
}
argoCDSecret, err := mgr.secrets.Secrets(mgr.namespace).Get(common.ArgoCDSecretName)
if err != nil {
return nil, err
}
var settings ArgoCDSettings
var errs []error
updateSettingsFromConfigMap(&settings, argoCDCM)
if err := updateSettingsFromSecret(&settings, argoCDSecret); err != nil {
errs = append(errs, err)
}
if len(errs) > 0 {
return &settings, errs[0]
}
return &settings, nil
}
// Clears cached settings on configmap/secret change
func (mgr *SettingsManager) invalidateCache() {
mgr.mutex.Lock()
defer mgr.mutex.Unlock()
mgr.reposCache = nil
mgr.repoCredsCache = nil
}
func (mgr *SettingsManager) initialize(ctx context.Context) error {
tweakConfigMap := func(options *metav1.ListOptions) {
cmLabelSelector := fields.ParseSelectorOrDie("app.kubernetes.io/part-of=argocd")
options.LabelSelector = cmLabelSelector.String()
}
eventHandler := cache.ResourceEventHandlerFuncs{
UpdateFunc: func(oldObj, newObj interface{}) {
mgr.invalidateCache()
},
}
indexers := cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}
cmInformer := v1.NewFilteredConfigMapInformer(mgr.clientset, mgr.namespace, 3*time.Minute, indexers, tweakConfigMap)
secretsInformer := v1.NewSecretInformer(mgr.clientset, mgr.namespace, 3*time.Minute, indexers)
cmInformer.AddEventHandler(eventHandler)
secretsInformer.AddEventHandler(eventHandler)
log.Info("Starting configmap/secret informers")
go func() {
cmInformer.Run(ctx.Done())
log.Info("configmap informer cancelled")
}()
go func() {
secretsInformer.Run(ctx.Done())
log.Info("secrets informer cancelled")
}()
if !cache.WaitForCacheSync(ctx.Done(), cmInformer.HasSynced, secretsInformer.HasSynced) {
return fmt.Errorf("Timed out waiting for settings cache to sync")
}
log.Info("Configmap/secret informer synced")
tryNotify := func() {
newSettings, err := mgr.GetSettings()
if err != nil {
log.Warnf("Unable to parse updated settings: %v", err)
} else {
mgr.notifySubscribers(newSettings)
}
}
now := time.Now()
handler := cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
if metaObj, ok := obj.(metav1.Object); ok {
if metaObj.GetCreationTimestamp().After(now) {
tryNotify()
}
}
},
UpdateFunc: func(oldObj, newObj interface{}) {
oldMeta, oldOk := oldObj.(metav1.Common)
newMeta, newOk := newObj.(metav1.Common)
if oldOk && newOk && oldMeta.GetResourceVersion() != newMeta.GetResourceVersion() {
tryNotify()
}
},
}
secretsInformer.AddEventHandler(handler)
cmInformer.AddEventHandler(handler)
mgr.secrets = v1listers.NewSecretLister(secretsInformer.GetIndexer())
mgr.configmaps = v1listers.NewConfigMapLister(cmInformer.GetIndexer())
return nil
}
func (mgr *SettingsManager) ensureSynced(forceResync bool) error {
mgr.mutex.Lock()
defer mgr.mutex.Unlock()
if !forceResync && mgr.secrets != nil && mgr.configmaps != nil {
return nil
}
if !forceResync && mgr.secrets != nil && mgr.configmaps != nil {
return nil
}
if mgr.initContextCancel != nil {
mgr.initContextCancel()
}
ctx, cancel := context.WithCancel(mgr.ctx)
mgr.initContextCancel = cancel
return mgr.initialize(ctx)
}
func updateSettingsFromConfigMap(settings *ArgoCDSettings, argoCDCM *apiv1.ConfigMap) {
settings.DexConfig = argoCDCM.Data[settingDexConfigKey]
settings.OIDCConfigRAW = argoCDCM.Data[settingsOIDCConfigKey]
settings.URL = argoCDCM.Data[settingURLKey]
settings.KustomizeBuildOptions = argoCDCM.Data[kustomizeBuildOptionsKey]
settings.StatusBadgeEnabled = argoCDCM.Data[statusBadgeEnabledKey] == "true"
settings.AnonymousUserEnabled = argoCDCM.Data[anonymousUserEnabledKey] == "true"
settings.UiCssURL = argoCDCM.Data[settingUiCssURLKey]
}
// updateSettingsFromSecret transfers settings from a Kubernetes secret into an ArgoCDSettings struct.
func updateSettingsFromSecret(settings *ArgoCDSettings, argoCDSecret *apiv1.Secret) error {
var errs []error
secretKey, ok := argoCDSecret.Data[settingServerSignatureKey]
if ok {
settings.ServerSignature = secretKey
} else {
errs = append(errs, &incompleteSettingsError{message: "server.secretkey is missing"})
}
if githubWebhookSecret := argoCDSecret.Data[settingsWebhookGitHubSecretKey]; len(githubWebhookSecret) > 0 {
settings.WebhookGitHubSecret = string(githubWebhookSecret)
}
if gitlabWebhookSecret := argoCDSecret.Data[settingsWebhookGitLabSecretKey]; len(gitlabWebhookSecret) > 0 {
settings.WebhookGitLabSecret = string(gitlabWebhookSecret)
}
if bitbucketWebhookUUID := argoCDSecret.Data[settingsWebhookBitbucketUUIDKey]; len(bitbucketWebhookUUID) > 0 {
settings.WebhookBitbucketUUID = string(bitbucketWebhookUUID)
}
if bitbucketserverWebhookSecret := argoCDSecret.Data[settingsWebhookBitbucketServerSecretKey]; len(bitbucketserverWebhookSecret) > 0 {
settings.WebhookBitbucketServerSecret = string(bitbucketserverWebhookSecret)
}
if gogsWebhookSecret := argoCDSecret.Data[settingsWebhookGogsSecretKey]; len(gogsWebhookSecret) > 0 {
settings.WebhookGogsSecret = string(gogsWebhookSecret)
}
serverCert, certOk := argoCDSecret.Data[settingServerCertificate]
serverKey, keyOk := argoCDSecret.Data[settingServerPrivateKey]
if certOk && keyOk {
cert, err := tls.X509KeyPair(serverCert, serverKey)
if err != nil {
errs = append(errs, &incompleteSettingsError{message: fmt.Sprintf("invalid x509 key pair %s/%s in secret: %s", settingServerCertificate, settingServerPrivateKey, err)})
} else {
settings.Certificate = &cert
}
}
secretValues := make(map[string]string, len(argoCDSecret.Data))
for k, v := range argoCDSecret.Data {
secretValues[k] = string(v)
}
settings.Secrets = secretValues
if len(errs) > 0 {
return errs[0]
}
return nil
}
// SaveSettings serializes ArgoCDSettings and upserts it into K8s secret/configmap
func (mgr *SettingsManager) SaveSettings(settings *ArgoCDSettings) error {
err := mgr.updateConfigMap(func(argoCDCM *apiv1.ConfigMap) error {
if settings.URL != "" {
argoCDCM.Data[settingURLKey] = settings.URL
} else {
delete(argoCDCM.Data, settingURLKey)
}
if settings.DexConfig != "" {
argoCDCM.Data[settingDexConfigKey] = settings.DexConfig
} else {
delete(argoCDCM.Data, settings.DexConfig)
}
if settings.OIDCConfigRAW != "" {
argoCDCM.Data[settingsOIDCConfigKey] = settings.OIDCConfigRAW
} else {
delete(argoCDCM.Data, settingsOIDCConfigKey)
}
if settings.UiCssURL != "" {
argoCDCM.Data[settingUiCssURLKey] = settings.UiCssURL
}
return nil
})
if err != nil {
return err
}
err = mgr.updateSecret(func(argoCDSecret *apiv1.Secret) error {
argoCDSecret.Data[settingServerSignatureKey] = settings.ServerSignature
if settings.WebhookGitHubSecret != "" {
argoCDSecret.Data[settingsWebhookGitHubSecretKey] = []byte(settings.WebhookGitHubSecret)
}
if settings.WebhookGitLabSecret != "" {
argoCDSecret.Data[settingsWebhookGitLabSecretKey] = []byte(settings.WebhookGitLabSecret)
}
if settings.WebhookBitbucketUUID != "" {
argoCDSecret.Data[settingsWebhookBitbucketUUIDKey] = []byte(settings.WebhookBitbucketUUID)
}
if settings.WebhookBitbucketServerSecret != "" {
argoCDSecret.Data[settingsWebhookBitbucketServerSecretKey] = []byte(settings.WebhookBitbucketServerSecret)
}
if settings.WebhookGogsSecret != "" {
argoCDSecret.Data[settingsWebhookGogsSecretKey] = []byte(settings.WebhookGogsSecret)
}
if settings.Certificate != nil {
cert, key := tlsutil.EncodeX509KeyPair(*settings.Certificate)
argoCDSecret.Data[settingServerCertificate] = cert
argoCDSecret.Data[settingServerPrivateKey] = key
} else {
delete(argoCDSecret.Data, settingServerCertificate)
delete(argoCDSecret.Data, settingServerPrivateKey)
}
return nil
})
if err != nil {
return err
}
return mgr.ResyncInformers()
}
// Save the SSH known host data into the corresponding ConfigMap
func (mgr *SettingsManager) SaveSSHKnownHostsData(ctx context.Context, knownHostsList []string) error {
err := mgr.ensureSynced(false)
if err != nil {
return err
}
certCM, err := mgr.GetConfigMapByName(common.ArgoCDKnownHostsConfigMapName)
if err != nil {
return err
}
if certCM.Data == nil {
certCM.Data = make(map[string]string)
}
sshKnownHostsData := strings.Join(knownHostsList, "\n") + "\n"
certCM.Data["ssh_known_hosts"] = sshKnownHostsData
_, err = mgr.clientset.CoreV1().ConfigMaps(mgr.namespace).Update(ctx, certCM, metav1.UpdateOptions{})
if err != nil {
return err
}
return mgr.ResyncInformers()
}
func (mgr *SettingsManager) SaveTLSCertificateData(ctx context.Context, tlsCertificates map[string]string) error {
err := mgr.ensureSynced(false)
if err != nil {
return err
}
certCM, err := mgr.GetConfigMapByName(common.ArgoCDTLSCertsConfigMapName)
if err != nil {
return err
}
certCM.Data = tlsCertificates
_, err = mgr.clientset.CoreV1().ConfigMaps(mgr.namespace).Update(ctx, certCM, metav1.UpdateOptions{})
if err != nil {
return err
}
return mgr.ResyncInformers()
}
func (mgr *SettingsManager) SaveGPGPublicKeyData(ctx context.Context, gpgPublicKeys map[string]string) error {
err := mgr.ensureSynced(false)
if err != nil {
return err
}
keysCM, err := mgr.GetConfigMapByName(common.ArgoCDGPGKeysConfigMapName)
if err != nil {
return err
}
keysCM.Data = gpgPublicKeys
_, err = mgr.clientset.CoreV1().ConfigMaps(mgr.namespace).Update(ctx, keysCM, metav1.UpdateOptions{})
if err != nil {
return err
}
return mgr.ResyncInformers()
}
// NewSettingsManager generates a new SettingsManager pointer and returns it
func NewSettingsManager(ctx context.Context, clientset kubernetes.Interface, namespace string) *SettingsManager {
mgr := &SettingsManager{
ctx: ctx,
clientset: clientset,
namespace: namespace,
mutex: &sync.Mutex{},
}
return mgr
}
func (mgr *SettingsManager) ResyncInformers() error {
return mgr.ensureSynced(true)
}
// IsSSOConfigured returns whether or not single-sign-on is configured
func (a *ArgoCDSettings) IsSSOConfigured() bool {
if a.IsDexConfigured() {
return true
}