-
Notifications
You must be signed in to change notification settings - Fork 719
/
util.go
1376 lines (1173 loc) · 42.9 KB
/
util.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
// Copyright 2019 ArgoCD Operator Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package argocd
import (
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"os"
"reflect"
"sort"
"strconv"
"strings"
"text/template"
"sigs.k8s.io/controller-runtime/pkg/builder"
"gopkg.in/yaml.v2"
argoproj "github.com/argoproj-labs/argocd-operator/api/v1alpha1"
argoprojv1a1 "github.com/argoproj-labs/argocd-operator/api/v1alpha1"
"github.com/argoproj-labs/argocd-operator/common"
"github.com/argoproj-labs/argocd-operator/controllers/argoutil"
monitoringv1 "github.com/coreos/prometheus-operator/pkg/apis/monitoring/v1"
oappsv1 "github.com/openshift/api/apps/v1"
routev1 "github.com/openshift/api/route/v1"
configv1client "github.com/openshift/client-go/config/clientset/versioned/typed/config/v1"
"github.com/sethvargo/go-password/password"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
v1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/source"
)
// DexConnector represents an authentication connector for Dex.
type DexConnector struct {
Config map[string]interface{} `yaml:"config,omitempty"`
ID string `yaml:"id"`
Name string `yaml:"name"`
Type string `yaml:"type"`
}
// generateArgoAdminPassword will generate and return the admin password for Argo CD.
func generateArgoAdminPassword() ([]byte, error) {
pass, err := password.Generate(
common.ArgoCDDefaultAdminPasswordLength,
common.ArgoCDDefaultAdminPasswordNumDigits,
common.ArgoCDDefaultAdminPasswordNumSymbols,
false, false)
return []byte(pass), err
}
// generateArgoServerKey will generate and return the server signature key for session validation.
func generateArgoServerSessionKey() ([]byte, error) {
pass, err := password.Generate(
common.ArgoCDDefaultServerSessionKeyLength,
common.ArgoCDDefaultServerSessionKeyNumDigits,
common.ArgoCDDefaultServerSessionKeyNumSymbols,
false, false)
return []byte(pass), err
}
// getArgoApplicationControllerResources will return the ResourceRequirements for the Argo CD application controller container.
func getArgoApplicationControllerResources(cr *argoprojv1a1.ArgoCD) corev1.ResourceRequirements {
resources := corev1.ResourceRequirements{}
// Allow override of resource requirements from CR
if cr.Spec.Controller.Resources != nil {
resources = *cr.Spec.Controller.Resources
}
return resources
}
// getArgoApplicationControllerCommand will return the command for the ArgoCD Application Controller component.
func getArgoApplicationControllerCommand(cr *argoprojv1a1.ArgoCD) []string {
cmd := []string{
"argocd-application-controller",
"--operation-processors", fmt.Sprint(getArgoServerOperationProcessors(cr)),
"--redis", getRedisServerAddress(cr),
"--repo-server", getRepoServerAddress(cr),
"--status-processors", fmt.Sprint(getArgoServerStatusProcessors(cr)),
"--kubectl-parallelism-limit", fmt.Sprint(getArgoControllerParellismLimit(cr)),
}
if cr.Spec.Controller.AppSync != nil {
cmd = append(cmd, "--app-resync", strconv.FormatInt(int64(cr.Spec.Controller.AppSync.Seconds()), 10))
}
cmd = append(cmd, "--loglevel")
cmd = append(cmd, getLogLevel(cr.Spec.Controller.LogLevel))
cmd = append(cmd, "--logformat")
cmd = append(cmd, getLogFormat(cr.Spec.Controller.LogFormat))
return cmd
}
// getArgoContainerImage will return the container image for ArgoCD.
func getArgoContainerImage(cr *argoprojv1a1.ArgoCD) string {
defaultTag, defaultImg := false, false
img := cr.Spec.Image
if img == "" {
img = common.ArgoCDDefaultArgoImage
defaultImg = true
}
tag := cr.Spec.Version
if tag == "" {
tag = common.ArgoCDDefaultArgoVersion
defaultTag = true
}
if e := os.Getenv(common.ArgoCDImageEnvName); e != "" && (defaultTag && defaultImg) {
return e
}
return argoutil.CombineImageTag(img, tag)
}
// getRepoServerContainerImage will return the container image for the Repo server.
//
// There are three possible options for configuring the image, and this is the
// order of preference.
//
// 1. from the Spec, the spec.repo field has an image and version to use for
// generating an image reference.
// 2. from the Environment, this looks for the `ARGOCD_REPOSERVER_IMAGE` field and uses
// that if the spec is not configured.
// 3. the default is configured in common.ArgoCDDefaultRepoServerVersion and
// common.ArgoCDDefaultRepoServerImage.
func getRepoServerContainerImage(cr *argoprojv1a1.ArgoCD) string {
defaultImg, defaultTag := false, false
img := cr.Spec.Repo.Image
if img == "" {
img = common.ArgoCDDefaultArgoImage
defaultImg = true
}
tag := cr.Spec.Repo.Version
if tag == "" {
tag = common.ArgoCDDefaultArgoVersion
defaultTag = true
}
if e := os.Getenv(common.ArgoCDImageEnvName); e != "" && (defaultTag && defaultImg) {
return e
}
return argoutil.CombineImageTag(img, tag)
}
// getArgoRepoResources will return the ResourceRequirements for the Argo CD Repo server container.
func getArgoRepoResources(cr *argoprojv1a1.ArgoCD) corev1.ResourceRequirements {
resources := corev1.ResourceRequirements{}
// Allow override of resource requirements from CR
if cr.Spec.Repo.Resources != nil {
resources = *cr.Spec.Repo.Resources
}
return resources
}
// getArgoServerInsecure returns the insecure value for the ArgoCD Server component.
func getArgoServerInsecure(cr *argoprojv1a1.ArgoCD) bool {
return cr.Spec.Server.Insecure
}
func isRepoServerTLSVerificationRequested(cr *argoprojv1a1.ArgoCD) bool {
return cr.Spec.Repo.VerifyTLS
}
// getArgoServerGRPCHost will return the GRPC host for the given ArgoCD.
func getArgoServerGRPCHost(cr *argoprojv1a1.ArgoCD) string {
host := nameWithSuffix("grpc", cr)
if len(cr.Spec.Server.GRPC.Host) > 0 {
host = cr.Spec.Server.GRPC.Host
}
return host
}
// getArgoServerHost will return the host for the given ArgoCD.
func getArgoServerHost(cr *argoprojv1a1.ArgoCD) string {
host := cr.Name
if len(cr.Spec.Server.Host) > 0 {
host = cr.Spec.Server.Host
}
return host
}
// getArgoServerResources will return the ResourceRequirements for the Argo CD server container.
func getArgoServerResources(cr *argoprojv1a1.ArgoCD) corev1.ResourceRequirements {
resources := corev1.ResourceRequirements{}
if cr.Spec.Server.Autoscale.Enabled {
resources = corev1.ResourceRequirements{
Limits: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse(common.ArgoCDDefaultServerResourceLimitCPU),
corev1.ResourceMemory: resource.MustParse(common.ArgoCDDefaultServerResourceLimitMemory),
},
Requests: corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse(common.ArgoCDDefaultServerResourceRequestCPU),
corev1.ResourceMemory: resource.MustParse(common.ArgoCDDefaultServerResourceRequestMemory),
},
}
}
// Allow override of resource requirements from CR
if cr.Spec.Server.Resources != nil {
resources = *cr.Spec.Server.Resources
}
return resources
}
// getArgoServerURI will return the URI for the ArgoCD server.
// The hostname for argocd-server is from the route, ingress, an external hostname or service name in that order.
func (r *ReconcileArgoCD) getArgoServerURI(cr *argoprojv1a1.ArgoCD) string {
host := nameWithSuffix("server", cr) // Default to service name
// Use the external hostname provided by the user
if cr.Spec.Server.Host != "" {
host = cr.Spec.Server.Host
}
// Use Ingress host if enabled
if cr.Spec.Server.Ingress.Enabled {
ing := newIngressWithSuffix("server", cr)
if argoutil.IsObjectFound(r.Client, cr.Namespace, ing.Name, ing) {
host = ing.Spec.Rules[0].Host
}
}
// Use Route host if available, override Ingress if both exist
if IsRouteAPIAvailable() {
route := newRouteWithSuffix("server", cr)
if argoutil.IsObjectFound(r.Client, cr.Namespace, route.Name, route) {
host = route.Spec.Host
}
}
return fmt.Sprintf("https://%s", host) // TODO: Safe to assume HTTPS here?
}
// getArgoServerOperationProcessors will return the numeric Operation Processors value for the ArgoCD Server.
func getArgoServerOperationProcessors(cr *argoprojv1a1.ArgoCD) int32 {
op := common.ArgoCDDefaultServerOperationProcessors
if cr.Spec.Controller.Processors.Operation > op {
op = cr.Spec.Controller.Processors.Operation
}
return op
}
// getArgoServerStatusProcessors will return the numeric Status Processors value for the ArgoCD Server.
func getArgoServerStatusProcessors(cr *argoprojv1a1.ArgoCD) int32 {
sp := common.ArgoCDDefaultServerStatusProcessors
if cr.Spec.Controller.Processors.Status > sp {
sp = cr.Spec.Controller.Processors.Status
}
return sp
}
// getArgoControllerParellismLimit returns the parallelism limit for the application controller
func getArgoControllerParellismLimit(cr *argoprojv1a1.ArgoCD) int32 {
pl := common.ArgoCDDefaultControllerParallelismLimit
if cr.Spec.Controller.ParallelismLimit > 0 {
pl = cr.Spec.Controller.ParallelismLimit
}
return pl
}
// getDexContainerImage will return the container image for the Dex server.
//
// There are three possible options for configuring the image, and this is the
// order of preference.
//
// 1. from the Spec, the spec.dex field has an image and version to use for
// generating an image reference.
// 2. from the Environment, this looks for the `ARGOCD_DEX_IMAGE` field and uses
// that if the spec is not configured.
// 3. the default is configured in common.ArgoCDDefaultDexVersion and
// common.ArgoCDDefaultDexImage.
func getDexContainerImage(cr *argoprojv1a1.ArgoCD) string {
defaultImg, defaultTag := false, false
img := cr.Spec.Dex.Image
if img == "" {
img = common.ArgoCDDefaultDexImage
defaultImg = true
}
tag := cr.Spec.Dex.Version
if tag == "" {
tag = common.ArgoCDDefaultDexVersion
defaultTag = true
}
if e := os.Getenv(common.ArgoCDDexImageEnvName); e != "" && (defaultTag && defaultImg) {
return e
}
return argoutil.CombineImageTag(img, tag)
}
// getDexOAuthClientID will return the OAuth client ID for the given ArgoCD.
func getDexOAuthClientID(cr *argoprojv1a1.ArgoCD) string {
return fmt.Sprintf("system:serviceaccount:%s:%s", cr.Namespace, fmt.Sprintf("%s-%s", cr.Name, common.ArgoCDDefaultDexServiceAccountName))
}
// getDexOAuthClientSecret will return the OAuth client secret for the given ArgoCD.
func (r *ReconcileArgoCD) getDexOAuthClientSecret(cr *argoprojv1a1.ArgoCD) (*string, error) {
sa := newServiceAccountWithName(common.ArgoCDDefaultDexServiceAccountName, cr)
if err := argoutil.FetchObject(r.Client, cr.Namespace, sa.Name, sa); err != nil {
return nil, err
}
// Find the token secret
var tokenSecret *corev1.ObjectReference
for _, saSecret := range sa.Secrets {
if strings.Contains(saSecret.Name, "token") {
tokenSecret = &saSecret
break
}
}
if tokenSecret == nil {
return nil, errors.New("unable to locate ServiceAccount token for OAuth client secret")
}
// Fetch the secret to obtain the token
secret := argoutil.NewSecretWithName(cr, tokenSecret.Name)
if err := argoutil.FetchObject(r.Client, cr.Namespace, secret.Name, secret); err != nil {
return nil, err
}
token := string(secret.Data["token"])
return &token, nil
}
// getDexResources will return the ResourceRequirements for the Dex container.
func getDexResources(cr *argoprojv1a1.ArgoCD) corev1.ResourceRequirements {
resources := corev1.ResourceRequirements{}
// Allow override of resource requirements from CR
if cr.Spec.Dex.Resources != nil {
resources = *cr.Spec.Dex.Resources
}
return resources
}
// getGrafanaContainerImage will return the container image for the Grafana server.
func getGrafanaContainerImage(cr *argoprojv1a1.ArgoCD) string {
defaultTag, defaultImg := false, false
img := cr.Spec.Grafana.Image
if img == "" {
img = common.ArgoCDDefaultGrafanaImage
defaultImg = true
}
tag := cr.Spec.Grafana.Version
if tag == "" {
tag = common.ArgoCDDefaultGrafanaVersion
defaultTag = true
}
if e := os.Getenv(common.ArgoCDGrafanaImageEnvName); e != "" && (defaultTag && defaultImg) {
return e
}
return argoutil.CombineImageTag(img, tag)
}
// getGrafanaResources will return the ResourceRequirements for the Grafana container.
func getGrafanaResources(cr *argoprojv1a1.ArgoCD) corev1.ResourceRequirements {
resources := corev1.ResourceRequirements{}
// Allow override of resource requirements from CR
if cr.Spec.Grafana.Resources != nil {
resources = *cr.Spec.Grafana.Resources
}
return resources
}
// getOpenShiftDexConfig will return the configuration for the Dex server running on OpenShift.
func (r *ReconcileArgoCD) getOpenShiftDexConfig(cr *argoprojv1a1.ArgoCD) (string, error) {
clientSecret, err := r.getDexOAuthClientSecret(cr)
if err != nil {
return "", err
}
connector := DexConnector{
Type: "openshift",
ID: "openshift",
Name: "OpenShift",
Config: map[string]interface{}{
"issuer": "https://kubernetes.default.svc", // TODO: Should this be hard-coded?
"clientID": getDexOAuthClientID(cr),
"clientSecret": *clientSecret,
"redirectURI": r.getDexOAuthRedirectURI(cr),
"insecureCA": true, // TODO: Configure for openshift CA,
"groups": cr.Spec.Dex.Groups,
},
}
connectors := make([]DexConnector, 0)
connectors = append(connectors, connector)
dex := make(map[string]interface{})
dex["connectors"] = connectors
bytes, err := yaml.Marshal(dex)
return string(bytes), err
}
// getRedisConfigPath will return the path for the Redis configuration templates.
func getRedisConfigPath() string {
path := os.Getenv("REDIS_CONFIG_PATH")
if len(path) > 0 {
return path
}
return common.ArgoCDDefaultRedisConfigPath
}
// getRedisInitScript will load the redis configuration from a template on disk for the given ArgoCD.
// If an error occurs, an empty string value will be returned.
func getRedisConf() string {
path := fmt.Sprintf("%s/redis.conf.tpl", getRedisConfigPath())
conf, err := loadTemplateFile(path, map[string]string{})
if err != nil {
log.Error(err, "unable to load redis configuration")
return ""
}
return conf
}
// getRedisContainerImage will return the container image for the Redis server.
func getRedisContainerImage(cr *argoprojv1a1.ArgoCD) string {
defaultImg, defaultTag := false, false
img := cr.Spec.Redis.Image
if img == "" {
img = common.ArgoCDDefaultRedisImage
defaultImg = true
}
tag := cr.Spec.Redis.Version
if tag == "" {
tag = common.ArgoCDDefaultRedisVersion
defaultTag = true
}
if e := os.Getenv(common.ArgoCDRedisImageEnvName); e != "" && (defaultTag && defaultImg) {
return e
}
return argoutil.CombineImageTag(img, tag)
}
// getRedisHAContainerImage will return the container image for the Redis server in HA mode.
func getRedisHAContainerImage(cr *argoprojv1a1.ArgoCD) string {
defaultImg, defaultTag := false, false
img := cr.Spec.Redis.Image
if img == "" {
img = common.ArgoCDDefaultRedisImage
defaultImg = true
}
tag := cr.Spec.Redis.Version
if tag == "" {
tag = common.ArgoCDDefaultRedisVersionHA
defaultTag = true
}
if e := os.Getenv(common.ArgoCDRedisHAImageEnvName); e != "" && (defaultTag && defaultImg) {
return e
}
return argoutil.CombineImageTag(img, tag)
}
// getRedisHAProxyAddress will return the Redis HA Proxy service address for the given ArgoCD.
func getRedisHAProxyAddress(cr *argoprojv1a1.ArgoCD) string {
return fqdnServiceRef("redis-ha-haproxy", common.ArgoCDDefaultRedisPort, cr)
}
// getRedisHAProxyContainerImage will return the container image for the Redis HA Proxy.
func getRedisHAProxyContainerImage(cr *argoprojv1a1.ArgoCD) string {
defaultImg, defaultTag := false, false
img := cr.Spec.HA.RedisProxyImage
if len(img) <= 0 {
img = common.ArgoCDDefaultRedisHAProxyImage
defaultImg = true
}
tag := cr.Spec.HA.RedisProxyVersion
if len(tag) <= 0 {
tag = common.ArgoCDDefaultRedisHAProxyVersion
defaultTag = true
}
if e := os.Getenv(common.ArgoCDRedisHAProxyImageEnvName); e != "" && (defaultTag && defaultImg) {
return e
}
return argoutil.CombineImageTag(img, tag)
}
// getRedisInitScript will load the redis init script from a template on disk for the given ArgoCD.
// If an error occurs, an empty string value will be returned.
func getRedisInitScript(cr *argoprojv1a1.ArgoCD) string {
path := fmt.Sprintf("%s/init.sh.tpl", getRedisConfigPath())
vars := map[string]string{
"ServiceName": nameWithSuffix("redis-ha", cr),
}
script, err := loadTemplateFile(path, vars)
if err != nil {
log.Error(err, "unable to load redis init-script")
return ""
}
return script
}
// getRedisHAProxySConfig will load the Redis HA Proxy configuration from a template on disk for the given ArgoCD.
// If an error occurs, an empty string value will be returned.
func getRedisHAProxyConfig(cr *argoprojv1a1.ArgoCD) string {
path := fmt.Sprintf("%s/haproxy.cfg.tpl", getRedisConfigPath())
vars := map[string]string{
"ServiceName": nameWithSuffix("redis-ha", cr),
}
script, err := loadTemplateFile(path, vars)
if err != nil {
log.Error(err, "unable to load redis haproxy configuration")
return ""
}
return script
}
// getRedisHAProxyScript will load the Redis HA Proxy init script from a template on disk for the given ArgoCD.
// If an error occurs, an empty string value will be returned.
func getRedisHAProxyScript(cr *argoprojv1a1.ArgoCD) string {
path := fmt.Sprintf("%s/haproxy_init.sh.tpl", getRedisConfigPath())
vars := map[string]string{
"ServiceName": nameWithSuffix("redis-ha", cr),
}
script, err := loadTemplateFile(path, vars)
if err != nil {
log.Error(err, "unable to load redis haproxy init script")
return ""
}
return script
}
// getRedisResources will return the ResourceRequirements for the Redis container.
func getRedisResources(cr *argoprojv1a1.ArgoCD) corev1.ResourceRequirements {
resources := corev1.ResourceRequirements{}
// Allow override of resource requirements from CR
if cr.Spec.Redis.Resources != nil {
resources = *cr.Spec.Redis.Resources
}
return resources
}
// getRedisHAProxyResources will return the ResourceRequirements for the Redis HA Proxy.
func getRedisHAProxyResources(cr *argoprojv1a1.ArgoCD) corev1.ResourceRequirements {
resources := corev1.ResourceRequirements{}
// Allow override of resource requirements from CR
if cr.Spec.HA.Resources != nil {
resources = *cr.Spec.HA.Resources
}
return resources
}
// getRedisSentinelConf will load the redis sentinel configuration from a template on disk for the given ArgoCD.
// If an error occurs, an empty string value will be returned.
func getRedisSentinelConf() string {
path := fmt.Sprintf("%s/sentinel.conf.tpl", getRedisConfigPath())
conf, err := loadTemplateFile(path, map[string]string{})
if err != nil {
log.Error(err, "unable to load redis sentinel configuration")
return ""
}
return conf
}
// getRedisLivenessScript will load the redis liveness script from a template on disk for the given ArgoCD.
// If an error occurs, an empty string value will be returned.
func getRedisLivenessScript() string {
path := fmt.Sprintf("%s/redis_liveness.sh.tpl", getRedisConfigPath())
conf, err := loadTemplateFile(path, map[string]string{})
if err != nil {
log.Error(err, "unable to load redis liveness script")
return ""
}
return conf
}
// getRedisReadinessScript will load the redis readiness script from a template on disk for the given ArgoCD.
// If an error occurs, an empty string value will be returned.
func getRedisReadinessScript() string {
path := fmt.Sprintf("%s/redis_readiness.sh.tpl", getRedisConfigPath())
conf, err := loadTemplateFile(path, map[string]string{})
if err != nil {
log.Error(err, "unable to load redis readiness script")
return ""
}
return conf
}
// getSentinelLivenessScript will load the redis liveness script from a template on disk for the given ArgoCD.
// If an error occurs, an empty string value will be returned.
func getSentinelLivenessScript() string {
path := fmt.Sprintf("%s/sentinel_liveness.sh.tpl", getRedisConfigPath())
conf, err := loadTemplateFile(path, map[string]string{})
if err != nil {
log.Error(err, "unable to load sentinel liveness script")
return ""
}
return conf
}
// getRedisServerAddress will return the Redis service address for the given ArgoCD.
func getRedisServerAddress(cr *argoprojv1a1.ArgoCD) string {
if cr.Spec.HA.Enabled {
return getRedisHAProxyAddress(cr)
}
return fqdnServiceRef(common.ArgoCDDefaultRedisSuffix, common.ArgoCDDefaultRedisPort, cr)
}
// loadTemplateFile will parse a template with the given path and execute it with the given params.
func loadTemplateFile(path string, params map[string]string) (string, error) {
tmpl, err := template.ParseFiles(path)
if err != nil {
log.Error(err, "unable to parse template")
return "", err
}
buf := new(bytes.Buffer)
err = tmpl.Execute(buf, params)
if err != nil {
log.Error(err, "unable to execute template")
return "", err
}
return buf.String(), nil
}
// nameWithSuffix will return a name based on the given ArgoCD. The given suffix is appended to the generated name.
// Example: Given an ArgoCD with the name "example-argocd", providing the suffix "foo" would result in the value of
// "example-argocd-foo" being returned.
func nameWithSuffix(suffix string, cr *argoprojv1a1.ArgoCD) string {
return fmt.Sprintf("%s-%s", cr.Name, suffix)
}
// fqdnServiceRef will return the FQDN referencing a specific service name, as set up by the operator, with the
// given port.
func fqdnServiceRef(service string, port int, cr *argoprojv1a1.ArgoCD) string {
return fmt.Sprintf("%s.%s.svc.cluster.local:%d", nameWithSuffix(service, cr), cr.Namespace, port)
}
// InspectCluster will verify the availability of extra features available to the cluster, such as Prometheus and
// OpenShift Routes.
func InspectCluster() error {
if err := verifyPrometheusAPI(); err != nil {
return err
}
if err := verifyRouteAPI(); err != nil {
return err
}
if err := verifyTemplateAPI(); err != nil {
return err
}
return nil
}
// reconcileCertificateAuthority will reconcile all Certificate Authority resources.
func (r *ReconcileArgoCD) reconcileCertificateAuthority(cr *argoprojv1a1.ArgoCD) error {
log.Info("reconciling CA secret")
if err := r.reconcileClusterCASecret(cr); err != nil {
return err
}
log.Info("reconciling CA config map")
if err := r.reconcileCAConfigMap(cr); err != nil {
return err
}
return nil
}
// reconcileResources will reconcile common ArgoCD resources.
func (r *ReconcileArgoCD) reconcileResources(cr *argoprojv1a1.ArgoCD) error {
log.Info("reconciling status")
if err := r.reconcileStatus(cr); err != nil {
return err
}
log.Info("reconciling roles")
if err := r.reconcileRoles(cr); err != nil {
return err
}
log.Info("reconciling rolebindings")
if err := r.reconcileRoleBindings(cr); err != nil {
return err
}
log.Info("reconciling service accounts")
if err := r.reconcileServiceAccounts(cr); err != nil {
return err
}
log.Info("reconciling certificate authority")
if err := r.reconcileCertificateAuthority(cr); err != nil {
return err
}
log.Info("reconciling secrets")
if err := r.reconcileSecrets(cr); err != nil {
return err
}
log.Info("reconciling config maps")
if err := r.reconcileConfigMaps(cr); err != nil {
return err
}
log.Info("reconciling services")
if err := r.reconcileServices(cr); err != nil {
return err
}
log.Info("reconciling deployments")
if err := r.reconcileDeployments(cr); err != nil {
return err
}
log.Info("reconciling statefulsets")
if err := r.reconcileStatefulSets(cr); err != nil {
return err
}
log.Info("reconciling autoscalers")
if err := r.reconcileAutoscalers(cr); err != nil {
return err
}
log.Info("reconciling ingresses")
if err := r.reconcileIngresses(cr); err != nil {
return err
}
if IsRouteAPIAvailable() {
log.Info("reconciling routes")
if err := r.reconcileRoutes(cr); err != nil {
return err
}
}
if IsPrometheusAPIAvailable() {
log.Info("reconciling prometheus")
if err := r.reconcilePrometheus(cr); err != nil {
return err
}
if err := r.reconcileMetricsServiceMonitor(cr); err != nil {
return err
}
if err := r.reconcileRepoServerServiceMonitor(cr); err != nil {
return err
}
if err := r.reconcileServerMetricsServiceMonitor(cr); err != nil {
return err
}
}
if cr.Spec.ApplicationSet != nil {
log.Info("reconciling ApplicationSet controller")
if err := r.reconcileApplicationSetController(cr); err != nil {
return err
}
}
if err := r.reconcileRepoServerTLSSecret(cr); err != nil {
return err
}
if cr.Spec.SSO != nil {
log.Info("reconciling SSO")
if err := r.reconcileSSO(cr); err != nil {
return err
}
}
return nil
}
func (r *ReconcileArgoCD) deleteClusterResources(cr *argoprojv1a1.ArgoCD) error {
selector, err := argocdInstanceSelector(cr.Name)
if err != nil {
return err
}
clusterRoleList := &v1.ClusterRoleList{}
if err := filterObjectsBySelector(r.Client, clusterRoleList, selector); err != nil {
return fmt.Errorf("failed to filter ClusterRoles for %s: %w", cr.Name, err)
}
if err := deleteClusterRoles(r.Client, clusterRoleList); err != nil {
return err
}
clusterBindingsList := &v1.ClusterRoleBindingList{}
if err := filterObjectsBySelector(r.Client, clusterBindingsList, selector); err != nil {
return fmt.Errorf("failed to filter ClusterRoleBindings for %s: %w", cr.Name, err)
}
if err := deleteClusterRoleBindings(r.Client, clusterBindingsList); err != nil {
return err
}
return nil
}
func (r *ReconcileArgoCD) removeManagedByLabelFromNamespaces(namespace string) error {
nsList := &corev1.NamespaceList{}
listOption := client.MatchingLabels{
common.ArgoCDManagedByLabel: namespace,
}
if err := r.Client.List(context.TODO(), nsList, listOption); err != nil {
return err
}
nsList.Items = append(nsList.Items, corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}})
for _, n := range nsList.Items {
ns := &corev1.Namespace{}
if err := r.Client.Get(context.TODO(), types.NamespacedName{Name: n.Name}, ns); err != nil {
return err
}
if ns.Labels == nil {
continue
}
if n, ok := ns.Labels[common.ArgoCDManagedByLabel]; !ok || n != namespace {
continue
}
delete(ns.Labels, common.ArgoCDManagedByLabel)
if err := r.Client.Update(context.TODO(), ns); err != nil {
log.Error(err, fmt.Sprintf("failed to remove label from namespace [%s]", ns.Name))
}
}
return nil
}
func filterObjectsBySelector(c client.Client, objectList client.ObjectList, selector labels.Selector) error {
return c.List(context.TODO(), objectList, client.MatchingLabelsSelector{Selector: selector})
}
func argocdInstanceSelector(name string) (labels.Selector, error) {
selector := labels.NewSelector()
requirement, err := labels.NewRequirement(common.ArgoCDKeyManagedBy, selection.Equals, []string{name})
if err != nil {
return nil, fmt.Errorf("failed to create a requirement for %w", err)
}
return selector.Add(*requirement), nil
}
func (r *ReconcileArgoCD) removeDeletionFinalizer(argocd *argoprojv1a1.ArgoCD) error {
argocd.Finalizers = removeString(argocd.GetFinalizers(), common.ArgoCDDeletionFinalizer)
if err := r.Client.Update(context.TODO(), argocd); err != nil {
return fmt.Errorf("failed to remove deletion finalizer from %s: %w", argocd.Name, err)
}
return nil
}
func (r *ReconcileArgoCD) addDeletionFinalizer(argocd *argoprojv1a1.ArgoCD) error {
argocd.Finalizers = append(argocd.Finalizers, common.ArgoCDDeletionFinalizer)
if err := r.Client.Update(context.TODO(), argocd); err != nil {
return fmt.Errorf("failed to add deletion finalizer for %s: %w", argocd.Name, err)
}
return nil
}
func removeString(slice []string, s string) []string {
var result []string
for _, item := range slice {
if item == s {
continue
}
result = append(result, item)
}
return result
}
// setResourceWatches will register Watches for each of the supported Resources.
func setResourceWatches(bldr *builder.Builder, clusterResourceMapper, tlsSecretMapper, namespaceResourceMapper handler.MapFunc) *builder.Builder {
deploymentConfigPred := predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
// Ignore updates to CR status in which case metadata.Generation does not change
var count int32 = 1
newDC, ok := e.ObjectNew.(*oappsv1.DeploymentConfig)
if !ok {
return false
}
oldDC, ok := e.ObjectOld.(*oappsv1.DeploymentConfig)
if !ok {
return false
}
if newDC.Name == defaultKeycloakIdentifier {
if newDC.Status.AvailableReplicas == count {
return true
}
if newDC.Status.AvailableReplicas == int32(0) &&
!reflect.DeepEqual(oldDC.Status.AvailableReplicas, newDC.Status.AvailableReplicas) {
// Handle the deletion of keycloak pod.
log.Info(fmt.Sprintf("Handle the pod deletion event for keycloak deployment config %s in namespace %s",
newDC.Name, newDC.Namespace))
err := handleKeycloakPodDeletion(newDC)
if err != nil {
log.Error(err, fmt.Sprintf("Failed to update Deployment Config %s for keycloak pod deletion in namespace %s",
newDC.Name, newDC.Namespace))
}
}
}
return false
},
}
deleteSSOPred := predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
newCR, ok := e.ObjectNew.(*argoprojv1a1.ArgoCD)
if !ok {
return false
}
oldCR, ok := e.ObjectOld.(*argoprojv1a1.ArgoCD)
if !ok {
return false
}
if !reflect.DeepEqual(oldCR.Spec.SSO, newCR.Spec.SSO) && newCR.Spec.SSO == nil {
err := deleteSSOConfiguration(newCR)
if err != nil {
log.Error(err, fmt.Sprintf("Failed to delete SSO Configuration for ArgoCD %s in namespace %s",
newCR.Name, newCR.Namespace))
}
}
return true
},
}
// Watch for changes to primary resource ArgoCD
bldr.For(&argoprojv1a1.ArgoCD{}, builder.WithPredicates(deleteSSOPred))
// Watch for changes to ConfigMap sub-resources owned by ArgoCD instances.
bldr.Owns(&corev1.ConfigMap{})
// Watch for changes to Secret sub-resources owned by ArgoCD instances.
bldr.Owns(&corev1.Secret{})
// Watch for changes to Service sub-resources owned by ArgoCD instances.
bldr.Owns(&corev1.Service{})
// Watch for changes to Deployment sub-resources owned by ArgoCD instances.
bldr.Owns(&appsv1.Deployment{})
// Watch for changes to Ingress sub-resources owned by ArgoCD instances.
bldr.Owns(&networkingv1.Ingress{})
bldr.Owns(&v1.Role{})
bldr.Owns(&v1.RoleBinding{})
clusterResourceHandler := handler.EnqueueRequestsFromMapFunc(clusterResourceMapper)