/
controller.go
209 lines (175 loc) · 7.01 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
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
/*
Copyright 2020 The Kubermatic Kubernetes Platform contributors.
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 constraintsyncer
import (
"context"
"encoding/json"
"fmt"
"go.uber.org/zap"
kubermaticv1 "k8c.io/kubermatic/v2/pkg/apis/kubermatic/v1"
userclustercontrollermanager "k8c.io/kubermatic/v2/pkg/controller/user-cluster-controller-manager"
"k8c.io/kubermatic/v2/pkg/controller/util/predicate"
constrainthandler "k8c.io/kubermatic/v2/pkg/handler/v2/constraint"
"k8c.io/kubermatic/v2/pkg/resources/reconciling"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/tools/record"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
const (
controllerName = "kkp-constraint-synchronizer"
constraintAPIVersion = "constraints.gatekeeper.sh/v1beta1"
spec = "spec"
parametersField = "parameters"
matchField = "match"
rawJsonField = "rawJSON"
)
type reconciler struct {
log *zap.SugaredLogger
seedClient ctrlruntimeclient.Client
userClient ctrlruntimeclient.Client
recorder record.EventRecorder
clusterIsPaused userclustercontrollermanager.IsPausedChecker
}
func Add(ctx context.Context, log *zap.SugaredLogger, seedMgr, userMgr manager.Manager, namespace string, clusterIsPaused userclustercontrollermanager.IsPausedChecker) error {
log = log.Named(controllerName)
r := &reconciler{
log: log,
seedClient: seedMgr.GetClient(),
userClient: userMgr.GetClient(),
recorder: userMgr.GetEventRecorderFor(controllerName),
clusterIsPaused: clusterIsPaused,
}
c, err := controller.New(controllerName, seedMgr, controller.Options{
Reconciler: r,
})
if err != nil {
return fmt.Errorf("failed to create controller: %w", err)
}
// Watch for changes to Constraints
if err = c.Watch(
&source.Kind{Type: &kubermaticv1.Constraint{}}, &handler.EnqueueRequestForObject{}, predicate.ByNamespace(namespace)); err != nil {
return fmt.Errorf("failed to establish watch for the Constraints: %w", err)
}
return nil
}
func (r *reconciler) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
log := r.log.With("constraint", request)
log.Debug("Reconciling")
paused, err := r.clusterIsPaused(ctx)
if err != nil {
return reconcile.Result{}, fmt.Errorf("failed to check cluster pause status: %w", err)
}
if paused {
return reconcile.Result{}, nil
}
constraint := &kubermaticv1.Constraint{}
if err := r.seedClient.Get(ctx, request.NamespacedName, constraint); err != nil {
if apierrors.IsNotFound(err) {
log.Debug("constraint not found, returning")
return reconcile.Result{}, nil
}
return reconcile.Result{}, fmt.Errorf("failed to get constraint: %w", err)
}
err = r.reconcile(ctx, constraint, log)
if err != nil {
log.Errorw("Reconciling failed", zap.Error(err))
r.recorder.Event(constraint, corev1.EventTypeWarning, "ConstraintReconcileFailed", err.Error())
}
return reconcile.Result{}, err
}
func (r *reconciler) createConstraint(ctx context.Context, constraint *kubermaticv1.Constraint, log *zap.SugaredLogger) error {
constraintCreatorGetters := []reconciling.NamedUnstructuredCreatorGetter{
constraintCreatorGetter(constraint),
}
if err := reconciling.ReconcileUnstructureds(ctx, constraintCreatorGetters, "", r.userClient); err != nil {
return fmt.Errorf("failed to reconcile constraint: %w", err)
}
return nil
}
func (r *reconciler) cleanupConstraint(ctx context.Context, constraint *kubermaticv1.Constraint, log *zap.SugaredLogger) error {
toDelete := &unstructured.Unstructured{}
toDelete.SetGroupVersionKind(schema.GroupVersionKind{
Group: constrainthandler.ConstraintsGroup,
Version: constrainthandler.ConstraintsVersion,
Kind: constraint.Spec.ConstraintType,
})
toDelete.SetName(constraint.Name)
log.Info("Deleting Constraint")
if err := r.userClient.Delete(ctx, toDelete); ctrlruntimeclient.IgnoreNotFound(err) != nil {
return fmt.Errorf("failed to delete constraint: %w", err)
}
return nil
}
// constraintCreatorGetter returns the unstructured gatekeeper Constraint object.
func constraintCreatorGetter(constraint *kubermaticv1.Constraint) reconciling.NamedUnstructuredCreatorGetter {
return func() (string, string, string, reconciling.UnstructuredCreator) {
return constraint.Name, constraint.Spec.ConstraintType, constraintAPIVersion, func(u *unstructured.Unstructured) (*unstructured.Unstructured, error) {
if len(constraint.Spec.Parameters) > 0 {
var params map[string]interface{}
rawParams, err := json.Marshal(constraint.Spec.Parameters)
if err != nil {
return nil, fmt.Errorf("error marshalling constraint parameters: %w", err)
}
if err := json.Unmarshal(rawParams, ¶ms); err != nil {
return nil, fmt.Errorf("error unmarshalling constraint parameters: %w", err)
}
// To keep backwards compatibility for Constraints that still use rawJSON. Support for this should be removed for 2.19
if rawJson, ok := params[rawJsonField]; ok {
var rawJsonParams map[string]interface{}
rawJson, ok := rawJson.(string)
if !ok {
return nil, fmt.Errorf("error converting raw json parameters")
}
err := json.Unmarshal([]byte(rawJson), &rawJsonParams)
if err != nil {
return nil, fmt.Errorf("error unmarshalling raw json parameters: %w", err)
}
params = rawJsonParams
}
if err := unstructured.SetNestedField(u.Object, params, spec, parametersField); err != nil {
return nil, fmt.Errorf("error setting constraint nested parameters: %w", err)
}
}
// set Match
matchMap, err := unmarshallToJSONMap(&constraint.Spec.Match)
if err != nil {
return nil, err
}
err = unstructured.SetNestedField(u.Object, matchMap, spec, matchField)
if err != nil {
return nil, fmt.Errorf("error setting constraint nested spec: %w", err)
}
return u, nil
}
}
}
func unmarshallToJSONMap(object interface{}) (map[string]interface{}, error) {
raw, err := json.Marshal(object)
if err != nil {
return nil, fmt.Errorf("error marshalling: %w", err)
}
result := make(map[string]interface{})
err = json.Unmarshal(raw, &result)
if err != nil {
return nil, fmt.Errorf("error unmarshalling: %w", err)
}
return result, nil
}