forked from knative/pkg
/
psbinding.go
366 lines (321 loc) · 11 KB
/
psbinding.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
/*
Copyright 2019 The Knative Authors
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 psbinding
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
"github.com/gobuffalo/flect"
"go.uber.org/zap"
admissionv1 "k8s.io/api/admission/v1"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
"k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/kubernetes"
admissionlisters "k8s.io/client-go/listers/admissionregistration/v1"
corelisters "k8s.io/client-go/listers/core/v1"
"knative.dev/pkg/apis/duck"
duckv1 "knative.dev/pkg/apis/duck/v1"
"knative.dev/pkg/controller"
"knative.dev/pkg/logging"
"knative.dev/pkg/ptr"
pkgreconciler "knative.dev/pkg/reconciler"
"knative.dev/pkg/system"
"knative.dev/pkg/webhook"
certresources "knative.dev/pkg/webhook/certificates/resources"
)
// ReconcilerOption is a function to modify the Reconciler.
type ReconcilerOption func(*Reconciler)
// WithSelector specifies the selector for the webhook.
func WithSelector(s metav1.LabelSelector) ReconcilerOption {
return func(r *Reconciler) {
r.selector = s
}
}
func NewReconciler(
name, path, secretName string,
client kubernetes.Interface,
mwhLister admissionlisters.MutatingWebhookConfigurationLister,
secretLister corelisters.SecretLister,
withContext BindableContext,
options ...ReconcilerOption,
) *Reconciler {
r := &Reconciler{
Name: name,
HandlerPath: path,
SecretName: secretName,
// This is the user-provided context-decorator, which allows
// them to infuse the context passed to Do/Undo.
WithContext: withContext,
Client: client,
MWHLister: mwhLister,
SecretLister: secretLister,
selector: ExclusionSelector, // Use ExclusionSelector by default.
}
// Apply options.
for _, opt := range options {
opt(r)
}
return r
}
// Reconciler implements an AdmissionController for altering PodSpecable
// resources that are the subject of a particular type of Binding.
// The two key methods are:
// 1. reconcileMutatingWebhook: which enumerates all of the Bindings and
// compiles a list of resource types that should be intercepted by our
// webhook. It also builds an index that can be used to efficiently
// handle Admit requests.
// 2. Admit: which leverages the index built by the Reconciler to apply
// mutations to resources.
type Reconciler struct {
pkgreconciler.LeaderAwareFuncs
Name string
HandlerPath string
SecretName string
Client kubernetes.Interface
MWHLister admissionlisters.MutatingWebhookConfigurationLister
SecretLister corelisters.SecretLister
ListAll ListAll
// WithContext is a callback that infuses the context supplied to
// Do/Undo with additional context to enable them to complete their
// respective tasks.
WithContext BindableContext
selector metav1.LabelSelector
index index
}
var _ controller.Reconciler = (*Reconciler)(nil)
var _ pkgreconciler.LeaderAware = (*Reconciler)(nil)
var _ webhook.AdmissionController = (*Reconciler)(nil)
// We need to specifically exclude our deployment(s) from consideration, but this provides a way
// of excluding other things as well.
var (
ExclusionSelector = metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{{
Key: duck.BindingExcludeLabel,
Operator: metav1.LabelSelectorOpNotIn,
Values: []string{"true"},
}},
// TODO(mattmoor): Consider also having a GVR-based one, e.g.
// foobindings.blah.knative.dev/exclude: "true"
}
InclusionSelector = metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{{
Key: duck.BindingIncludeLabel,
Operator: metav1.LabelSelectorOpIn,
Values: []string{"true"},
}},
// TODO(mattmoor): Consider also having a GVR-based one, e.g.
// foobindings.blah.knative.dev/include: "true"
}
)
// Reconcile implements controller.Reconciler
func (ac *Reconciler) Reconcile(ctx context.Context, key string) error {
// Look up the webhook secret, and fetch the CA cert bundle.
secret, err := ac.SecretLister.Secrets(system.Namespace()).Get(ac.SecretName)
if err != nil {
logging.FromContext(ctx).Errorw("Error fetching secret", zap.Error(err))
return err
}
caCert, ok := secret.Data[certresources.CACert]
if !ok {
return fmt.Errorf("secret %q is missing %q key", ac.SecretName, certresources.CACert)
}
// Reconcile the webhook configuration.
return ac.reconcileMutatingWebhook(ctx, caCert)
}
// Path implements AdmissionController
func (ac *Reconciler) Path() string {
return ac.HandlerPath
}
// Admit implements AdmissionController
func (ac *Reconciler) Admit(ctx context.Context, request *admissionv1.AdmissionRequest) *admissionv1.AdmissionResponse {
switch request.Operation {
case admissionv1.Create, admissionv1.Update:
default:
logging.FromContext(ctx).Info("Unhandled webhook operation, letting it through ", request.Operation)
return &admissionv1.AdmissionResponse{Allowed: true}
}
orig := &duckv1.WithPod{}
if err := json.Unmarshal(request.Object.Raw, orig); err != nil {
return webhook.MakeErrorStatus("unable to decode object: %v", err)
}
// Look up the Bindables for this resource.
fbs := ac.index.lookUp(exactKey{
Group: request.Kind.Group,
Kind: request.Kind.Kind,
Namespace: request.Namespace,
Name: orig.Name},
labels.Set(orig.Labels))
if len(fbs) == 0 {
// This doesn't apply!
return &admissionv1.AdmissionResponse{Allowed: true}
}
// Copy the subject state.
mutated := orig.DeepCopy()
// Apply the Bindables to the copy of the subject state. If conflicts occur, for example because multiple Bindables
// make incompatible changes, the reconciler will attempt to correct the state later.
for _, fb := range fbs {
var bindingContext context.Context
// Callback into the user's code to setup the context with additional
// information needed to perform the mutation.
if ac.WithContext != nil {
var err error
bindingContext, err = ac.WithContext(ctx, fb)
if err != nil {
return webhook.MakeErrorStatus("unable to setup binding context: %v", err)
}
} else {
bindingContext = ctx
}
// Mutate the copy of the subject state according to the deletion state of the Bindable.
if fb.GetDeletionTimestamp() != nil {
fb.Undo(bindingContext, mutated)
} else {
fb.Do(bindingContext, mutated)
}
}
// Synthesize a patch from the changes and return it in our AdmissionResponse
patchBytes, err := duck.CreateBytePatch(orig, mutated)
if err != nil {
return webhook.MakeErrorStatus("unable to create patch with binding: %v", err)
}
return &admissionv1.AdmissionResponse{
Patch: patchBytes,
Allowed: true,
PatchType: func() *admissionv1.PatchType {
pt := admissionv1.PatchTypeJSONPatch
return &pt
}(),
}
}
func (ac *Reconciler) reconcileMutatingWebhook(ctx context.Context, caCert []byte) error {
// Build a deduplicated list of all of the GVKs we see.
gks := map[schema.GroupKind]sets.String{}
// When reconciling the webhook, enumerate all of the bindings, so that
// we can index them to efficiently respond to webhook requests.
fbs, err := ac.ListAll()
if err != nil {
return err
}
ib := newIndexBuilder()
for _, fb := range fbs {
ref := fb.GetSubject()
gv, err := schema.ParseGroupVersion(ref.APIVersion)
if err != nil {
return err
}
gk := schema.GroupKind{
Group: gv.Group,
Kind: ref.Kind,
}
set := gks[gk]
if set == nil {
set = make(sets.String, 1)
}
set.Insert(gv.Version)
gks[gk] = set
if ref.Name != "" {
ib.associate(exactKey{
Group: gk.Group,
Kind: gk.Kind,
Namespace: ref.Namespace,
Name: ref.Name},
fb)
} else {
selector, err := metav1.LabelSelectorAsSelector(ref.Selector)
if err != nil {
return err
}
ib.associateSelection(inexactKey{
Group: gk.Group,
Kind: gk.Kind,
Namespace: ref.Namespace},
selector, fb)
}
}
// Update the index.
ib.build(&ac.index)
// After we've updated our indices, bail out unless we are the leader.
// Only the leader should be mutating the webhook.
if !ac.IsLeaderFor(sentinel) {
// We don't use controller.NewSkipKey here because we did do
// some amount of processing and the timing information may be
// useful.
return nil
}
rules := make([]admissionregistrationv1.RuleWithOperations, 0, len(gks))
for gk, versions := range gks {
plural := strings.ToLower(flect.Pluralize(gk.Kind))
rules = append(rules, admissionregistrationv1.RuleWithOperations{
Operations: []admissionregistrationv1.OperationType{
admissionregistrationv1.Create,
admissionregistrationv1.Update,
},
Rule: admissionregistrationv1.Rule{
APIGroups: []string{gk.Group},
APIVersions: versions.List(),
Resources: []string{plural + "/*"},
},
})
}
// Sort the rules by Group, Version, Kind so that things are deterministically ordered.
sort.Slice(rules, func(i, j int) bool {
lhs, rhs := rules[i], rules[j]
if lhs.APIGroups[0] != rhs.APIGroups[0] {
return lhs.APIGroups[0] < rhs.APIGroups[0]
}
if lhs.APIVersions[0] != rhs.APIVersions[0] {
return lhs.APIVersions[0] < rhs.APIVersions[0]
}
return lhs.Resources[0] < rhs.Resources[0]
})
configuredWebhook, err := ac.MWHLister.Get(ac.Name)
if err != nil {
return fmt.Errorf("error retrieving webhook: %w", err)
}
current := configuredWebhook.DeepCopy()
// Use the "Equivalent" match policy so that we don't need to enumerate versions for same-types.
// This is only supported by 1.15+ clusters.
matchPolicy := admissionregistrationv1.Equivalent
for i, wh := range current.Webhooks {
if wh.Name != current.Name {
continue
}
cur := ¤t.Webhooks[i]
selector := webhook.EnsureLabelSelectorExpressions(cur.NamespaceSelector, &ac.selector)
cur.MatchPolicy = &matchPolicy
cur.Rules = rules
cur.NamespaceSelector = selector
cur.ObjectSelector = selector // 1.15+ only
cur.ClientConfig.CABundle = caCert
if cur.ClientConfig.Service == nil {
return fmt.Errorf("missing service reference for webhook: %s", wh.Name)
}
cur.ClientConfig.Service.Path = ptr.String(ac.Path())
}
if ok := equality.Semantic.DeepEqual(configuredWebhook, current); !ok {
logging.FromContext(ctx).Info("Updating webhook")
mwhclient := ac.Client.AdmissionregistrationV1().MutatingWebhookConfigurations()
if _, err := mwhclient.Update(ctx, current, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("failed to update webhook: %w", err)
}
} else {
logging.FromContext(ctx).Info("Webhook is valid")
}
return nil
}