/
controller.go
179 lines (161 loc) · 6.32 KB
/
controller.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
package blueprintcontroller
import (
"context"
"path/filepath"
"github.com/ccremer/clustercode/pkg/api/v1alpha1"
"github.com/ccremer/clustercode/pkg/internal/pipe"
internaltypes "github.com/ccremer/clustercode/pkg/internal/types"
pipeline "github.com/ccremer/go-command-pipeline"
"github.com/go-logr/logr"
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/utils/pointer"
"k8s.io/utils/strings"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
var ScanRoleName = "clustercode-edit"
var ScanRoleKind = "ClusterRole"
var DefaultClusterCodeContainerImage string
// BlueprintProvisioner reconciles Blueprint objects
type BlueprintProvisioner struct {
client client.Client
Log logr.Logger
}
// BlueprintContext holds the parameters of a single reconciliation
type BlueprintContext struct {
context.Context
blueprint *v1alpha1.Blueprint
}
func (r *BlueprintProvisioner) NewObject() *v1alpha1.Blueprint {
return &v1alpha1.Blueprint{}
}
func (r *BlueprintProvisioner) Provision(ctx context.Context, obj *v1alpha1.Blueprint) (reconcile.Result, error) {
pctx := &BlueprintContext{
blueprint: obj,
Context: ctx,
}
p := pipeline.NewPipeline[*BlueprintContext]().WithBeforeHooks(pipe.DebugLogger[*BlueprintContext](r.Log))
p.WithSteps(
p.NewStep("ensure service account", r.ensureServiceAccount),
p.NewStep("ensure role binding", r.ensureRoleBinding),
p.NewStep("ensure cron job", r.ensureCronJob),
).WithFinalizer(r.setFailureCondition)
return reconcile.Result{}, p.RunWithContext(pctx)
}
func (r *BlueprintProvisioner) Deprovision(_ context.Context, _ *v1alpha1.Blueprint) (reconcile.Result, error) {
return reconcile.Result{}, nil
}
func (r *BlueprintProvisioner) setFailureCondition(ctx *BlueprintContext, err error) error {
if updateErr := pipe.UpdateFailedCondition(ctx, r.client, &ctx.blueprint.Status.Conditions, ctx.blueprint, err); updateErr != nil {
r.Log.Error(updateErr, "could not update Failed status condition")
}
return err
}
func (r *BlueprintProvisioner) ensureServiceAccount(ctx *BlueprintContext) error {
sa := &corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{
Name: ctx.blueprint.GetServiceAccountName(),
Namespace: ctx.blueprint.Namespace,
}}
_, err := controllerutil.CreateOrUpdate(ctx, r.client, sa, func() error {
sa.Labels = labels.Merge(sa.Labels, internaltypes.ClusterCodeLabels)
return controllerutil.SetOwnerReference(ctx.blueprint, sa, r.client.Scheme())
})
return err
}
func (r *BlueprintProvisioner) ensureRoleBinding(ctx *BlueprintContext) error {
saName := ctx.blueprint.GetServiceAccountName()
roleBinding := &rbacv1.RoleBinding{ObjectMeta: metav1.ObjectMeta{
Name: strings.ShortenString(saName, 51) + "-rolebinding",
Namespace: ctx.blueprint.Namespace,
}}
_, err := controllerutil.CreateOrUpdate(ctx, r.client, roleBinding, func() error {
roleBinding.Labels = labels.Merge(roleBinding.Labels, internaltypes.ClusterCodeLabels)
roleBinding.Subjects = []rbacv1.Subject{{
Kind: "ServiceAccount",
Namespace: ctx.blueprint.Namespace,
Name: saName,
}}
// Don't change existing kind or role name if already existing
kind := roleBinding.RoleRef.Kind
if kind == "" {
kind = ScanRoleKind
}
roleName := roleBinding.RoleRef.Name
if roleName == "" {
roleName = ScanRoleName
}
roleBinding.RoleRef = rbacv1.RoleRef{Kind: kind, Name: roleName, APIGroup: rbacv1.GroupName}
return controllerutil.SetOwnerReference(ctx.blueprint, roleBinding, r.client.Scheme())
})
return err
}
func (r *BlueprintProvisioner) ensureCronJob(ctx *BlueprintContext) error {
cronJob := &batchv1.CronJob{
ObjectMeta: metav1.ObjectMeta{
Name: ctx.blueprint.Name + "-scan-job",
Namespace: ctx.blueprint.Namespace,
},
}
_, err := controllerutil.CreateOrUpdate(ctx, r.client, cronJob, func() error {
cronJob.Labels = labels.Merge(cronJob.Labels, internaltypes.ClusterCodeLabels)
cronJob.Spec.Suspend = pointer.Bool(ctx.blueprint.Spec.Suspend)
cronJob.Spec.Schedule = ctx.blueprint.Spec.Scan.Schedule
cronJob.Spec.ConcurrencyPolicy = batchv1.ForbidConcurrent
cronJob.Spec.SuccessfulJobsHistoryLimit = pointer.Int32(1)
cronJob.Spec.FailedJobsHistoryLimit = pointer.Int32(1)
cronJob.Spec.JobTemplate.Spec.BackoffLimit = pointer.Int32(0)
cronJob.Spec.JobTemplate.Spec.Template.Labels = internaltypes.JobTypeScan.AsLabels()
cronJob.Spec.JobTemplate.Spec.Template.Spec.ServiceAccountName = ctx.blueprint.GetServiceAccountName()
cronJob.Spec.JobTemplate.Spec.Template.Spec.RestartPolicy = corev1.RestartPolicyNever
if len(cronJob.Spec.JobTemplate.Spec.Template.Spec.Containers) == 0 {
cronJob.Spec.JobTemplate.Spec.Template.Spec.Containers = []corev1.Container{{
Name: "scanner",
Env: []corev1.EnvVar{
{
Name: "CC_LOG_DEBUG",
Value: "true",
},
},
Args: []string{
"scan",
"--namespace=" + ctx.blueprint.Namespace,
"--blueprint-name=" + ctx.blueprint.Name,
},
Image: DefaultClusterCodeContainerImage,
ImagePullPolicy: corev1.PullIfNotPresent,
VolumeMounts: []corev1.VolumeMount{
{
Name: internaltypes.SourceSubMountPath,
MountPath: filepath.Join("/clustercode", internaltypes.SourceSubMountPath),
SubPath: ctx.blueprint.Spec.Storage.SourcePvc.SubPath},
{
Name: internaltypes.IntermediateSubMountPath,
MountPath: filepath.Join("/clustercode", internaltypes.IntermediateSubMountPath),
SubPath: ctx.blueprint.Spec.Storage.IntermediatePvc.SubPath,
},
},
}}
cronJob.Spec.JobTemplate.Spec.Template.Spec.Volumes = []corev1.Volume{
{
Name: internaltypes.SourceSubMountPath,
VolumeSource: corev1.VolumeSource{
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: ctx.blueprint.Spec.Storage.SourcePvc.ClaimName}},
},
{
Name: internaltypes.IntermediateSubMountPath,
VolumeSource: corev1.VolumeSource{
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: ctx.blueprint.Spec.Storage.IntermediatePvc.ClaimName}},
},
}
}
return controllerutil.SetOwnerReference(ctx.blueprint, cronJob, r.client.Scheme())
})
return err
}