-
Notifications
You must be signed in to change notification settings - Fork 216
/
git.go
783 lines (696 loc) · 22.5 KB
/
git.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
// Package git implements a controller that watches for GitRepo objects. (fleetcontrollers)
//
// It manages the lifecycle of GitJob resources for GitRepos. It cleans up orphaned bundles and image scans. Also updates the GitRepo and bundle status.
package git
import (
"context"
"encoding/json"
"fmt"
"regexp"
"sort"
"time"
"github.com/sirupsen/logrus"
"github.com/rancher/fleet/internal/cmd/controller/controllers/clusterregistration"
"github.com/rancher/fleet/internal/cmd/controller/display"
"github.com/rancher/fleet/internal/cmd/controller/summary"
"github.com/rancher/fleet/internal/config"
fleet "github.com/rancher/fleet/pkg/apis/fleet.cattle.io/v1alpha1"
fleetcontrollers "github.com/rancher/fleet/pkg/generated/controllers/fleet.cattle.io/v1alpha1"
gitjob "github.com/rancher/gitjob/pkg/apis/gitjob.cattle.io/v1"
v1 "github.com/rancher/gitjob/pkg/generated/controllers/gitjob.cattle.io/v1"
"github.com/rancher/wrangler/pkg/apply"
corev1controller "github.com/rancher/wrangler/pkg/generated/controllers/core/v1"
"github.com/rancher/wrangler/pkg/genericcondition"
"github.com/rancher/wrangler/pkg/kv"
"github.com/rancher/wrangler/pkg/name"
"github.com/rancher/wrangler/pkg/relatedresource"
"github.com/rancher/wrangler/pkg/yaml"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
)
var (
two = int32(2)
)
func Register(ctx context.Context,
apply apply.Apply,
gitJobs v1.GitJobController,
bundleDeployments fleetcontrollers.BundleDeploymentController,
gitRepoRestrictions fleetcontrollers.GitRepoRestrictionCache,
bundles fleetcontrollers.BundleController,
images fleetcontrollers.ImageScanController,
gitRepos fleetcontrollers.GitRepoController,
secrets corev1controller.SecretCache) {
h := &handler{
gitjobCache: gitJobs.Cache(),
bundleCache: bundles.Cache(),
bundles: bundles,
images: images,
bundleDeployments: bundleDeployments.Cache(),
gitRepoRestrictions: gitRepoRestrictions,
display: display.NewFactory(bundles.Cache()),
secrets: secrets,
}
gitRepos.OnChange(ctx, "gitjob-purge", h.DeleteOnChange)
// this will update the lastUpdateTime of the Accepted condition
fleetcontrollers.RegisterGitRepoGeneratingHandler(ctx, gitRepos, apply, "Accepted", "gitjobs", h.OnChange, nil)
// enqueue gitrepo when gitjob changes
relatedresource.Watch(ctx, "gitjobs",
relatedresource.OwnerResolver(true, fleet.SchemeGroupVersion.String(), "GitRepo"), gitRepos, gitJobs)
relatedresource.Watch(ctx, "gitjobs", resolveGitRepo, gitRepos, bundles)
}
// resolveGitRepo enqueues a GitRepo event for a bundle change
func resolveGitRepo(namespace, name string, obj runtime.Object) ([]relatedresource.Key, error) {
if bundle, ok := obj.(*fleet.Bundle); ok {
repo := bundle.Labels[fleet.RepoLabel]
if repo != "" {
return []relatedresource.Key{{
Namespace: bundle.Namespace,
Name: repo,
}}, nil
}
}
return nil, nil
}
type handler struct {
gitjobCache v1.GitJobCache
secrets corev1controller.SecretCache
bundleCache fleetcontrollers.BundleCache
bundles fleetcontrollers.BundleClient
images fleetcontrollers.ImageScanController
gitRepoRestrictions fleetcontrollers.GitRepoRestrictionCache
bundleDeployments fleetcontrollers.BundleDeploymentCache
display *display.Factory
}
func targetsOrDefault(targets []fleet.GitTarget) []fleet.GitTarget {
if len(targets) == 0 {
return []fleet.GitTarget{
{
Name: "default",
ClusterGroup: "default",
},
}
}
return targets
}
// getConfig builds a config map, containing the GitTarget cluster matchers, converted to BundleTargets.
// The BundleTargets are duplicated into TargetRestrictions. TargetRestrictions is a whilelist. A BundleDeployment
// will be created for a Target just if it is inside a TargetRestrictions. If it is not inside TargetRestrictions a Target
// is a TargetCustomization.
func (h *handler) getConfig(repo *fleet.GitRepo) (*corev1.ConfigMap, error) {
spec := &fleet.BundleSpec{}
for _, target := range targetsOrDefault(repo.Spec.Targets) {
spec.Targets = append(spec.Targets, fleet.BundleTarget{
Name: target.Name,
ClusterName: target.ClusterName,
ClusterSelector: target.ClusterSelector,
ClusterGroup: target.ClusterGroup,
ClusterGroupSelector: target.ClusterGroupSelector,
})
spec.TargetRestrictions = append(spec.TargetRestrictions, fleet.BundleTargetRestriction(target))
}
data, err := json.Marshal(spec)
if err != nil {
return nil, err
}
hash := clusterregistration.KeyHash(string(data))
return &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: name.SafeConcatName(repo.Name, "config", hash),
Namespace: repo.Namespace,
},
BinaryData: map[string][]byte{
"targets.yaml": data,
},
}, nil
}
func (h *handler) authorizeAndAssignDefaults(gitrepo *fleet.GitRepo) (*fleet.GitRepo, error) {
restrictions, err := h.gitRepoRestrictions.List(gitrepo.Namespace, labels.Everything())
if err != nil {
return nil, err
}
if len(restrictions) == 0 {
return gitrepo, nil
}
restriction := aggregate(restrictions)
gitrepo = gitrepo.DeepCopy()
if len(restriction.AllowedTargetNamespaces) > 0 && gitrepo.Spec.TargetNamespace == "" {
return nil, fmt.Errorf("empty targetNamespace denied, because allowedTargetNamespaces restriction is present")
}
gitrepo.Spec.TargetNamespace, err = isAllowed(gitrepo.Spec.TargetNamespace, "", restriction.AllowedTargetNamespaces)
if err != nil {
return nil, fmt.Errorf("disallowed targetNamespace %s: %w", gitrepo.Spec.TargetNamespace, err)
}
gitrepo.Spec.ServiceAccount, err = isAllowed(gitrepo.Spec.ServiceAccount,
restriction.DefaultServiceAccount,
restriction.AllowedServiceAccounts)
if err != nil {
return nil, fmt.Errorf("disallowed serviceAccount %s: %w", gitrepo.Spec.ServiceAccount, err)
}
gitrepo.Spec.Repo, err = isAllowedByRegex(gitrepo.Spec.Repo, "", restriction.AllowedRepoPatterns)
if err != nil {
return nil, fmt.Errorf("disallowed repo %s: %w", gitrepo.Spec.ServiceAccount, err)
}
gitrepo.Spec.ClientSecretName, err = isAllowed(gitrepo.Spec.ClientSecretName,
restriction.DefaultClientSecretName,
restriction.AllowedClientSecretNames)
if err != nil {
return nil, fmt.Errorf("disallowed clientSecretName %s: %w", gitrepo.Spec.ServiceAccount, err)
}
return gitrepo, nil
}
func isAllowed(currentValue, defaultValue string, allowedValues []string) (string, error) {
if currentValue == "" {
return defaultValue, nil
}
if len(allowedValues) == 0 {
return currentValue, nil
}
for _, allowedValue := range allowedValues {
if allowedValue == currentValue {
return currentValue, nil
}
}
return currentValue, fmt.Errorf("%s not in allowed set %v", currentValue, allowedValues)
}
func isAllowedByRegex(currentValue, defaultValue string, patterns []string) (string, error) {
if currentValue == "" {
return defaultValue, nil
}
if len(patterns) == 0 {
return currentValue, nil
}
for _, pattern := range patterns {
// for compatibility with previous versions, the patterns can match verbatim
if pattern == currentValue {
return currentValue, nil
}
p, err := regexp.Compile(pattern)
if err != nil {
logrus.Infof("GitRepoRestriction failed to compile regex '%s'", pattern)
return currentValue, err
}
if p.MatchString(currentValue) {
return currentValue, nil
}
}
return currentValue, fmt.Errorf("%s not in allowed set %v", currentValue, patterns)
}
func aggregate(restrictions []*fleet.GitRepoRestriction) (result fleet.GitRepoRestriction) {
sort.Slice(restrictions, func(i, j int) bool {
return restrictions[i].Name < restrictions[j].Name
})
for _, restriction := range restrictions {
if result.DefaultServiceAccount == "" {
result.DefaultServiceAccount = restriction.DefaultServiceAccount
}
if result.DefaultClientSecretName == "" {
result.DefaultClientSecretName = restriction.DefaultClientSecretName
}
result.AllowedServiceAccounts = append(result.AllowedServiceAccounts, restriction.AllowedServiceAccounts...)
result.AllowedClientSecretNames = append(result.AllowedClientSecretNames, restriction.AllowedClientSecretNames...)
result.AllowedRepoPatterns = append(result.AllowedRepoPatterns, restriction.AllowedRepoPatterns...)
result.AllowedTargetNamespaces = append(result.AllowedTargetNamespaces, restriction.AllowedTargetNamespaces...)
}
return
}
func (h *handler) DeleteOnChange(key string, gitrepo *fleet.GitRepo) (*fleet.GitRepo, error) {
if gitrepo != nil {
return gitrepo, nil
}
logrus.Debugf("GitRepo '%s' deleted, deleting bundle, image scane", key)
ns, name := kv.Split(key, "/")
bundles, err := h.bundleCache.List(ns, labels.SelectorFromSet(labels.Set{
fleet.RepoLabel: name,
}))
if err != nil {
return nil, err
}
for _, bundle := range bundles {
err := h.bundles.Delete(bundle.Namespace, bundle.Name, nil)
if err != nil {
return nil, err
}
}
images, err := h.images.Cache().List(ns, labels.Everything())
if err != nil {
return nil, err
}
for _, image := range images {
if image.Spec.GitRepoName == name {
err := h.images.Delete(image.Namespace, image.Name, nil)
if err != nil {
return nil, err
}
}
}
return nil, nil
}
func mergeConditions(existing, next []genericcondition.GenericCondition) []genericcondition.GenericCondition {
result := make([]genericcondition.GenericCondition, 0, len(existing)+len(next))
names := map[string]int{}
for i, existing := range existing {
result = append(result, existing)
names[existing.Type] = i
}
for _, next := range next {
if i, ok := names[next.Type]; ok {
result[i] = next
} else {
result = append(result, next)
}
}
return result
}
func acceptedLastUpdate(conds []genericcondition.GenericCondition) string {
for _, cond := range conds {
if cond.Type == "Accepted" {
return cond.LastUpdateTime
}
}
return ""
}
func (h *handler) OnChange(gitrepo *fleet.GitRepo, status fleet.GitRepoStatus) ([]runtime.Object, fleet.GitRepoStatus, error) {
logrus.Debugf("OnChange GitRepo %s/%s for commit %s last accepted at %s", gitrepo.Namespace, gitrepo.Name, gitrepo.Status.Commit, acceptedLastUpdate(gitrepo.Status.Conditions))
status.ObservedGeneration = gitrepo.Generation
if gitrepo.Spec.Repo == "" {
return nil, status, nil
}
if gitrepo.Spec.HelmSecretNameForPaths != "" {
if _, err := h.secrets.Get(gitrepo.Namespace, gitrepo.Spec.HelmSecretNameForPaths); err != nil {
return nil, status, fmt.Errorf("failed to look up HelmSecretNameForPaths, error: %v", err)
}
} else if gitrepo.Spec.HelmSecretName != "" {
if _, err := h.secrets.Get(gitrepo.Namespace, gitrepo.Spec.HelmSecretName); err != nil {
return nil, status, fmt.Errorf("failed to look up helmSecretName, error: %v", err)
}
}
gitrepo, err := h.authorizeAndAssignDefaults(gitrepo)
if err != nil {
return nil, status, err
}
status, err = h.setBundleStatus(gitrepo, status)
if err != nil {
return nil, status, err
}
paths := gitrepo.Spec.Paths
if len(paths) == 0 {
paths = []string{"."}
}
gitJob, err := h.gitjobCache.Get(gitrepo.Namespace, gitrepo.Name)
if err == nil {
status.Commit = gitJob.Status.Commit
status.Conditions = mergeConditions(status.Conditions, gitJob.Status.Conditions)
status.GitJobStatus = gitJob.Status.JobStatus
} else {
status.Commit = ""
}
if status.GitJobStatus != "Current" {
status.Display.State = "GitUpdating"
}
branch, rev := gitrepo.Spec.Branch, gitrepo.Spec.Revision
if branch == "" && rev == "" {
branch = "master"
}
configMap, err := h.getConfig(gitrepo)
if err != nil {
return nil, status, err
}
syncSeconds := 0
if gitrepo.Spec.PollingInterval != nil {
syncSeconds = int(gitrepo.Spec.PollingInterval.Duration / time.Second)
}
saName := name.SafeConcatName("git", gitrepo.Name)
bundleErrorState := ""
if status.Summary.WaitApplied > 0 {
bundleErrorState = "WaitApplied"
}
if status.Summary.ErrApplied > 0 {
bundleErrorState = "ErrApplied"
}
status.Resources, status.ResourceErrors = h.display.Render(gitrepo.Namespace, gitrepo.Name, bundleErrorState)
status = countResources(status)
volumes, volumeMounts := volumes(h.secrets, gitrepo, configMap)
args, envs := argsAndEnvs(gitrepo)
return []runtime.Object{
configMap,
&corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: saName,
Namespace: gitrepo.Namespace,
},
},
&rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{
Name: saName,
Namespace: gitrepo.Namespace,
},
Rules: []rbacv1.PolicyRule{
{
Verbs: []string{"get", "create", "update", "list", "delete"},
APIGroups: []string{"fleet.cattle.io"},
Resources: []string{"bundles", "imagescans"},
},
{
Verbs: []string{"get"},
APIGroups: []string{"fleet.cattle.io"},
Resources: []string{"gitrepos"},
},
},
},
&rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: saName,
Namespace: gitrepo.Namespace,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: saName,
Namespace: gitrepo.Namespace,
},
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "Role",
Name: saName,
},
},
&gitjob.GitJob{
ObjectMeta: metav1.ObjectMeta{
Labels: yaml.CleanAnnotationsForExport(gitrepo.Labels),
Annotations: yaml.CleanAnnotationsForExport(gitrepo.Annotations),
Name: gitrepo.Name,
Namespace: gitrepo.Namespace,
},
Spec: gitjob.GitJobSpec{
SyncInterval: syncSeconds,
ForceUpdateGeneration: gitrepo.Spec.ForceSyncGeneration,
Git: gitjob.GitInfo{
Credential: gitjob.Credential{
ClientSecretName: gitrepo.Spec.ClientSecretName,
CABundle: gitrepo.Spec.CABundle,
InsecureSkipTLSverify: gitrepo.Spec.InsecureSkipTLSverify,
},
Provider: "polling",
Repo: gitrepo.Spec.Repo,
Revision: rev,
Branch: branch,
},
JobSpec: batchv1.JobSpec{
BackoffLimit: &two,
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
CreationTimestamp: metav1.Time{Time: time.Unix(0, 0)},
},
Spec: corev1.PodSpec{
Volumes: volumes,
SecurityContext: &corev1.PodSecurityContext{
RunAsUser: &[]int64{1000}[0],
},
ServiceAccountName: saName,
RestartPolicy: corev1.RestartPolicyNever,
Containers: []corev1.Container{
{
Name: "fleet",
Image: config.Get().AgentImage,
ImagePullPolicy: corev1.PullPolicy(config.Get().AgentImagePullPolicy),
Command: []string{"log.sh"},
Args: append(args, paths...),
WorkingDir: "/workspace/source",
VolumeMounts: volumeMounts,
Env: envs,
},
},
NodeSelector: map[string]string{"kubernetes.io/os": "linux"},
Tolerations: []corev1.Toleration{{
Key: "cattle.io/os",
Operator: "Equal",
Value: "linux",
Effect: "NoSchedule",
}},
},
},
},
},
},
}, status, nil
}
func countResources(status fleet.GitRepoStatus) fleet.GitRepoStatus {
status.ResourceCounts = fleet.GitRepoResourceCounts{}
for _, resource := range status.Resources {
status.ResourceCounts.DesiredReady++
switch resource.State {
case "Ready":
status.ResourceCounts.Ready++
case "WaitApplied":
status.ResourceCounts.WaitApplied++
case "Modified":
status.ResourceCounts.Modified++
case "Orphan":
status.ResourceCounts.Orphaned++
case "Missing":
status.ResourceCounts.Missing++
case "Unknown":
status.ResourceCounts.Unknown++
default:
status.ResourceCounts.NotReady++
}
}
return status
}
func (h *handler) setBundleStatus(gitrepo *fleet.GitRepo, status fleet.GitRepoStatus) (fleet.GitRepoStatus, error) {
if gitrepo.DeletionTimestamp != nil {
return status, nil
}
bundleDeployments, err := h.bundleDeployments.List("", labels.SelectorFromSet(labels.Set{
fleet.RepoLabel: gitrepo.Name,
fleet.BundleNamespaceLabel: gitrepo.Namespace,
}))
if err != nil {
return status, err
}
status.Summary = fleet.BundleSummary{}
sort.Slice(bundleDeployments, func(i, j int) bool {
return bundleDeployments[i].UID < bundleDeployments[j].UID
})
var (
maxState fleet.BundleState
message string
)
for _, app := range bundleDeployments {
state := summary.GetDeploymentState(app)
summary.IncrementState(&status.Summary, app.Name, state, summary.MessageFromDeployment(app), app.Status.ModifiedStatus, app.Status.NonReadyStatus)
status.Summary.DesiredReady++
if fleet.StateRank[state] > fleet.StateRank[maxState] {
maxState = state
message = summary.MessageFromDeployment(app)
}
}
if maxState == fleet.Ready {
maxState = ""
message = ""
}
bundles, err := h.bundleCache.List(gitrepo.Namespace, labels.SelectorFromSet(labels.Set{
fleet.RepoLabel: gitrepo.Name,
}))
if err != nil {
return status, err
}
sort.Slice(bundles, func(i, j int) bool {
return bundles[i].Name < bundles[j].Name
})
var (
clustersDesiredReady int
clustersReady = -1
)
for _, bundle := range bundles {
if bundle.Status.Summary.DesiredReady > 0 {
clustersDesiredReady = bundle.Status.Summary.DesiredReady
if clustersReady < 0 || bundle.Status.Summary.Ready < clustersReady {
clustersReady = bundle.Status.Summary.Ready
}
}
}
if clustersReady < 0 {
clustersReady = 0
}
status.Display.State = string(maxState)
status.Display.Message = message
status.Display.Error = len(message) > 0
status.DesiredReadyClusters = clustersDesiredReady
status.ReadyClusters = clustersReady
summary.SetReadyConditions(&status, "Bundle", status.Summary)
return status, nil
}
// volumes builds sets of volumes and their volume mounts based on configuration and secrets.
func volumes(
secrets corev1controller.SecretCache,
gitrepo *fleet.GitRepo,
configMap *corev1.ConfigMap,
) ([]corev1.Volume, []corev1.VolumeMount) {
volumes := []corev1.Volume{
{
Name: "config",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: configMap.Name,
},
},
},
},
}
volumeMounts := []corev1.VolumeMount{
{
Name: "config",
MountPath: "/run/config",
},
}
if gitrepo.Spec.HelmSecretNameForPaths != "" {
vols, volMnts := volumesFromSecret(
secrets,
gitrepo.Namespace,
gitrepo.Spec.HelmSecretNameForPaths,
"helm-secret-by-path",
)
volumes = append(volumes, vols...)
volumeMounts = append(volumeMounts, volMnts...)
} else if gitrepo.Spec.HelmSecretName != "" {
vols, volMnts := volumesFromSecret(secrets, gitrepo.Namespace, gitrepo.Spec.HelmSecretName, "helm-secret")
volumes = append(volumes, vols...)
volumeMounts = append(volumeMounts, volMnts...)
}
return volumes, volumeMounts
}
// volumesFromSecret generates volumes and volume mounts from a Helm secret, assuming that that secret exists.
func volumesFromSecret(
secrets corev1controller.SecretCache,
namespace string,
secretName, volumeName string,
) ([]corev1.Volume, []corev1.VolumeMount) {
volumes := []corev1.Volume{
{
Name: volumeName,
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: secretName,
},
},
},
}
volumeMounts := []corev1.VolumeMount{
{
Name: volumeName,
MountPath: "/etc/fleet/helm",
},
}
// Mount a CA certificate, if specified in the secret. This is necessary to support Helm registries with
// self-signed certificates.
secret, _ := secrets.Get(namespace, secretName)
if _, ok := secret.Data["cacerts"]; ok {
certVolumeName := fmt.Sprintf("%s-cert", volumeName)
volumes = append(volumes, corev1.Volume{
Name: certVolumeName,
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: secretName,
Items: []corev1.KeyToPath{
{
Key: "cacerts",
Path: "cacert.crt",
},
},
},
},
})
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: certVolumeName,
MountPath: "/etc/ssl/certs",
})
}
return volumes, volumeMounts
}
func argsAndEnvs(gitrepo *fleet.GitRepo) ([]string, []corev1.EnvVar) {
args := []string{
"fleet",
"apply",
}
if logrus.IsLevelEnabled(logrus.DebugLevel) {
args = append(args, "--debug", "--debug-level", "9")
}
bundleLabels := labels.Merge(gitrepo.Labels, map[string]string{
fleet.RepoLabel: gitrepo.Name,
})
args = append(args,
"--targets-file=/run/config/targets.yaml",
"--label="+bundleLabels.String(),
"--namespace", gitrepo.Namespace,
"--service-account", gitrepo.Spec.ServiceAccount,
fmt.Sprintf("--sync-generation=%d", gitrepo.Spec.ForceSyncGeneration),
fmt.Sprintf("--paused=%v", gitrepo.Spec.Paused),
"--target-namespace", gitrepo.Spec.TargetNamespace,
)
if gitrepo.Spec.KeepResources {
args = append(args, "--keep-resources")
}
if gitrepo.Spec.CorrectDrift.Enabled {
args = append(args, "--correct-drift")
if gitrepo.Spec.CorrectDrift.Force {
args = append(args, "--correct-drift-force")
}
if gitrepo.Spec.CorrectDrift.KeepFailHistory {
args = append(args, "--correct-drift-keep-fail-history")
}
}
var env []corev1.EnvVar
if gitrepo.Spec.HelmSecretNameForPaths != "" {
helmArgs := []string{
"--helm-credentials-by-path-file",
"/etc/fleet/helm/secrets-path.yaml",
}
args = append(args, helmArgs...)
env = append(env,
// for ssh go-getter, make sure we always accept new host key
corev1.EnvVar{
Name: "GIT_SSH_COMMAND",
Value: "ssh -o stricthostkeychecking=accept-new",
},
)
} else if gitrepo.Spec.HelmSecretName != "" {
helmArgs := []string{
"--password-file",
"/etc/fleet/helm/password",
"--cacerts-file",
"/etc/fleet/helm/cacerts",
"--ssh-privatekey-file",
"/etc/fleet/helm/ssh-privatekey",
}
if gitrepo.Spec.HelmRepoURLRegex != "" {
helmArgs = append(helmArgs, "--helm-repo-url-regex", gitrepo.Spec.HelmRepoURLRegex)
}
args = append(args, helmArgs...)
env = append(env,
// for ssh go-getter, make sure we always accept new host key
corev1.EnvVar{
Name: "GIT_SSH_COMMAND",
Value: "ssh -o stricthostkeychecking=accept-new",
},
corev1.EnvVar{
Name: "HELM_USERNAME",
ValueFrom: &corev1.EnvVarSource{
SecretKeyRef: &corev1.SecretKeySelector{
Optional: &[]bool{true}[0],
Key: "username",
LocalObjectReference: corev1.LocalObjectReference{
Name: gitrepo.Spec.HelmSecretName,
},
},
},
})
}
return append(args, "--", gitrepo.Name), env
}