-
Notifications
You must be signed in to change notification settings - Fork 15
/
resource.go
316 lines (282 loc) · 9 KB
/
resource.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
package cke
import (
"bytes"
"context"
"errors"
"fmt"
"sort"
"strconv"
"github.com/cybozu-go/log"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer/yaml"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/dynamic"
)
// Annotations for CKE-managed resources.
const (
AnnotationResourceImage = "cke.cybozu.com/image"
AnnotationResourceRevision = "cke.cybozu.com/revision"
AnnotationResourceInjectCA = "cke.cybozu.com/inject-cacert"
AnnotationResourceIssueCert = "cke.cybozu.com/issue-cert"
)
// kinds
const (
KindDeployment = "Deployment"
KindMutatingWebhookConfiguration = "MutatingWebhookConfiguration"
KindSecret = "Secret"
KindValidatingWebhookConfiguration = "ValidatingWebhookConfiguration"
)
var decUnstructured = yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme)
// ApplyResource creates or updates given resource using server-side-apply.
func ApplyResource(ctx context.Context, dynclient dynamic.Interface, mapper meta.RESTMapper, inf Infrastructure, data []byte, rev int64, forceConflicts bool) error {
obj := &unstructured.Unstructured{}
_, gvk, err := decUnstructured.Decode(data, nil, obj)
if err != nil {
return fmt.Errorf("failed to decode data into *Unstructured: %w", err)
}
ann := obj.GetAnnotations()
if ann == nil {
ann = make(map[string]string)
}
ann[AnnotationResourceRevision] = strconv.FormatInt(rev, 10)
obj.SetAnnotations(ann)
mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return fmt.Errorf("failed to find REST mapping for %s: %w", gvk.String(), err)
}
if gvk.Kind == KindValidatingWebhookConfiguration || gvk.Kind == KindMutatingWebhookConfiguration {
if ann[AnnotationResourceInjectCA] == "true" {
if err := injectCA(ctx, inf.Storage(), obj, gvk); err != nil {
return fmt.Errorf("failed to inject CA certificate: %w", err)
}
}
}
if gvk.Kind == KindSecret {
if svc := ann[AnnotationResourceIssueCert]; svc != "" {
if err := issueCert(ctx, inf, obj, svc); err != nil {
return fmt.Errorf("failed to issue cert for webhook: %w", err)
}
}
}
var dr dynamic.ResourceInterface
if mapping.Scope.Name() == meta.RESTScopeNameNamespace {
dr = dynclient.Resource(mapping.Resource).Namespace(obj.GetNamespace())
} else {
dr = dynclient.Resource(mapping.Resource)
}
buf := &bytes.Buffer{}
if err := unstructured.UnstructuredJSONScheme.Encode(obj, buf); err != nil {
return err
}
if log.Enabled(log.LvDebug) {
log.Debug("resource-apply", map[string]interface{}{
"gvk": gvk.String(),
"gvr": mapping.Resource.String(),
"namespace": obj.GetNamespace(),
"name": obj.GetName(),
"data": buf.String(),
})
}
_, err = dr.Patch(ctx, obj.GetName(), types.ApplyPatchType, buf.Bytes(), metav1.PatchOptions{
FieldManager: "cke",
Force: &forceConflicts,
})
return err
}
func injectCA(ctx context.Context, st Storage, obj *unstructured.Unstructured, gvk *schema.GroupVersionKind) error {
cacert, err := st.GetCACertificate(ctx, CAWebhook)
if err != nil {
return fmt.Errorf("failed to get CA cert for webhook: %w", err)
}
certData := []byte(cacert)
cvt := runtime.DefaultUnstructuredConverter
switch {
case gvk.Version == "v1" && gvk.Kind == KindValidatingWebhookConfiguration:
typed := &admissionregistrationv1.ValidatingWebhookConfiguration{}
if err := cvt.FromUnstructured(obj.UnstructuredContent(), typed); err != nil {
return fmt.Errorf("failed to convert validating webhook %s: %w", obj.GetName(), err)
}
for i := range typed.Webhooks {
typed.Webhooks[i].ClientConfig.CABundle = certData
}
mutated, err := cvt.ToUnstructured(typed)
if err != nil {
return err
}
obj.UnstructuredContent()["webhooks"] = mutated["webhooks"]
return nil
case gvk.Version == "v1" && gvk.Kind == KindMutatingWebhookConfiguration:
typed := &admissionregistrationv1.MutatingWebhookConfiguration{}
if err := cvt.FromUnstructured(obj.UnstructuredContent(), typed); err != nil {
return fmt.Errorf("failed to convert mutating webhook %s: %w", obj.GetName(), err)
}
for i := range typed.Webhooks {
typed.Webhooks[i].ClientConfig.CABundle = certData
}
mutated, err := cvt.ToUnstructured(typed)
if err != nil {
return err
}
obj.UnstructuredContent()["webhooks"] = mutated["webhooks"]
return nil
case gvk.Version == "v1beta1" && gvk.Kind == KindValidatingWebhookConfiguration:
typed := &admissionregistrationv1beta1.ValidatingWebhookConfiguration{}
if err := cvt.FromUnstructured(obj.UnstructuredContent(), typed); err != nil {
return fmt.Errorf("failed to convert validating webhook %s: %w", obj.GetName(), err)
}
for i := range typed.Webhooks {
typed.Webhooks[i].ClientConfig.CABundle = certData
}
mutated, err := cvt.ToUnstructured(typed)
if err != nil {
return err
}
obj.UnstructuredContent()["webhooks"] = mutated["webhooks"]
return nil
case gvk.Version == "v1beta1" && gvk.Kind == KindMutatingWebhookConfiguration:
typed := &admissionregistrationv1beta1.MutatingWebhookConfiguration{}
if err := cvt.FromUnstructured(obj.UnstructuredContent(), typed); err != nil {
return fmt.Errorf("failed to convert mutating webhook %s: %w", obj.GetName(), err)
}
for i := range typed.Webhooks {
typed.Webhooks[i].ClientConfig.CABundle = certData
}
mutated, err := cvt.ToUnstructured(typed)
if err != nil {
return err
}
obj.UnstructuredContent()["webhooks"] = mutated["webhooks"]
return nil
}
panic(gvk)
}
func issueCert(ctx context.Context, inf Infrastructure, obj *unstructured.Unstructured, svcName string) error {
cvt := runtime.DefaultUnstructuredConverter
secret := &corev1.Secret{}
if err := cvt.FromUnstructured(obj.UnstructuredContent(), secret); err != nil {
return fmt.Errorf("failed to convert secret %s/%s: %w", obj.GetNamespace(), obj.GetName(), err)
}
ca := WebhookCA{}
cert, key, err := ca.IssueCertificate(ctx, inf, obj.GetNamespace(), svcName)
if err != nil {
return fmt.Errorf("failed to issue certificate for %s.%s.svc: %w", svcName, obj.GetNamespace(), err)
}
if secret.Data == nil {
secret.Data = make(map[string][]byte)
}
secret.Data[corev1.TLSCertKey] = []byte(cert)
secret.Data[corev1.TLSPrivateKeyKey] = []byte(key)
mutated, err := cvt.ToUnstructured(secret)
if err != nil {
return err
}
obj.UnstructuredContent()["data"] = mutated["data"]
obj.UnstructuredContent()["type"] = corev1.SecretTypeTLS
return nil
}
// ParseResource parses YAML string.
func ParseResource(data []byte) (string, error) {
obj := &unstructured.Unstructured{}
_, _, err := decUnstructured.Decode(data, nil, obj)
if err != nil {
return "", err
}
name := obj.GetName()
if name == "" {
return "", errors.New("no name")
}
if obj.GetAPIVersion() == "" {
return "", errors.New("no apiVersion")
}
if obj.GetNamespace() == "" {
return obj.GetKind() + "/" + name, nil
}
return obj.GetKind() + "/" + obj.GetNamespace() + "/" + name, nil
}
// ResourceDefinition represents a CKE-managed kubernetes resource.
type ResourceDefinition struct {
Key string
Kind string
Namespace string
Name string
Revision int64
Image string // may contains multiple images; we should not use this whole string as an image name.
Definition []byte
}
// String implements fmt.Stringer.
func (d ResourceDefinition) String() string {
return fmt.Sprintf("%s@%d", d.Key, d.Revision)
}
// NeedUpdate returns true if annotations of the current resource
// indicates need for update.
func (d ResourceDefinition) NeedUpdate(rs *ResourceStatus) bool {
if rs == nil {
return true
}
curRev, ok := rs.Annotations[AnnotationResourceRevision]
if !ok {
return true
}
if curRev != strconv.FormatInt(d.Revision, 10) {
return true
}
if d.Image == "" {
return false
}
curImage, ok := rs.Annotations[AnnotationResourceImage]
if !ok {
return true
}
return curImage != d.Image
}
func (d ResourceDefinition) rank() int {
switch d.Kind {
case "Namespace":
return 10
case "ServiceAccount":
return 20
case "CustomResourceDefinition":
return 30
case "ClusterRole":
return 40
case "ClusterRoleBinding":
return 50
// other cluster-scoped resources: 1000
case "Role":
return 2000
case "RoleBinding":
return 2010
case "NetworkPolicy":
return 2020
case "Secret":
return 2030
case "ConfigMap":
return 2040
// other namespace scoped resources: 3000
}
if d.Namespace == "" {
return 1000
}
return 3000
}
// SortResources sort resources as defined order of creation.
func SortResources(res []ResourceDefinition) {
less := func(i, j int) bool {
a := res[i]
b := res[j]
aRank := a.rank()
bRank := b.rank()
if aRank == bRank {
return a.Key < b.Key
}
return aRank < bRank
}
sort.Slice(res, less)
}