/
sync.go
424 lines (346 loc) · 12.8 KB
/
sync.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
/*
Copyright 2020 Google LLC
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
https://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 sync contains logic for synchronizing Ingress and ManagedCertificate resources
// with user intent.
package sync
import (
"context"
"fmt"
"sort"
"strings"
"time"
computev1 "google.golang.org/api/compute/v1"
netv1 "k8s.io/api/networking/v1"
"k8s.io/klog"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/apis/networking.gke.io/v1"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/clients/event"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/clients/ingress"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/clients/managedcertificate"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/config"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/controller/certificates"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/controller/metrics"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/controller/sslcertificatemanager"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/controller/state"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/utils/errors"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/utils/patch"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/utils/random"
"github.com/GoogleCloudPlatform/gke-managed-certs/pkg/utils/types"
)
const (
separator = ","
)
// Interface provides operations for synchronizing resources with user intent.
type Interface interface {
// ManagedCertificate synchronizes ManagedCertificate resources
// with user intent.
ManagedCertificate(ctx context.Context, id types.Id) error
// Ingress synchronizes ManagedCertificate resources
// with user intent.
Ingress(ctx context.Context, id types.Id) error
}
type impl struct {
config *config.Config
event event.Interface
ingress ingress.Interface
managedCertificate managedcertificate.Interface
metrics metrics.Interface
random random.Interface
ssl sslcertificatemanager.Interface
state state.Interface
}
func New(config *config.Config, event event.Interface, ingress ingress.Interface,
managedCertificate managedcertificate.Interface, metrics metrics.Interface,
random random.Interface, ssl sslcertificatemanager.Interface,
state state.Interface) Interface {
return impl{
config: config,
event: event,
ingress: ingress,
managedCertificate: managedCertificate,
metrics: metrics,
random: random,
ssl: ssl,
state: state,
}
}
// Splits given comma separated string into a set of non-empty items
func parse(annotation string) map[string]bool {
result := make(map[string]bool, 0)
for _, item := range strings.Split(annotation, separator) {
trimmed := strings.TrimSpace(item)
if trimmed != "" {
result[trimmed] = true
}
}
return result
}
// Returns:
// 1. a set of SslCertificate resources that should be attached to Ingress
// via annotation pre-shared-cert.
// 2. a slice of ManagedCertificate ids that are attached to Ingress
// via annotation managed-certificates.
// 3. an error on failure.
func (s impl) getCertificatesToAttach(ingress *netv1.Ingress) (map[string]bool, []types.Id, error) {
// If a ManagedCertificate attached to Ingress does not exist, add an event to Ingress
// and return an error.
boundManagedCertificates := parse(ingress.Annotations[config.AnnotationManagedCertificatesKey])
for mcrtName := range boundManagedCertificates {
id := types.NewId(ingress.Namespace, mcrtName)
_, err := s.managedCertificate.Get(id)
if err == nil {
continue
}
if errors.IsNotFound(err) {
s.event.MissingCertificate(*ingress, mcrtName)
}
return nil, nil, fmt.Errorf("managedCertificate.Get(%s): %w", id.String(), err)
}
// Take already bound SslCertificate resources.
sslCertificates := make(map[string]bool, 0)
for sslCertificateName := range parse(ingress.Annotations[config.AnnotationPreSharedCertKey]) {
sslCertificates[sslCertificateName] = true
}
// Slice of ManagedCertificate ids that are attached to Ingress via annotation
// managed-certificates.
var managedCertificates []types.Id
for id, entry := range s.state.List() {
if id.Namespace != ingress.Namespace {
continue
}
if entry.SoftDeleted {
delete(sslCertificates, entry.SslCertificateName)
} else if _, e := boundManagedCertificates[id.Name]; e {
sslCertificates[entry.SslCertificateName] = true
managedCertificates = append(managedCertificates, id)
}
}
return sslCertificates, managedCertificates, nil
}
// Builds the value of pre-shared-cert annotation
// out of a set of SslCertificate resources' names.
func buildPreSharedCertAnnotation(sslCertificates map[string]bool) string {
var result []string
for sslCertificate := range sslCertificates {
result = append(result, sslCertificate)
}
sort.Strings(result)
return strings.Join(result, separator)
}
func (s impl) reportManagedCertificatesAttached(ctx context.Context, managedCertificates []types.Id) error {
for _, id := range managedCertificates {
entry, err := s.state.Get(id)
if err != nil {
return err
}
if entry.ExcludedFromSLO {
klog.Infof("Skipping reporting SslCertificate binding metric: %s is marked as excluded from SLO calculations.", id.String())
continue
}
if entry.SslCertificateBindingReported {
klog.Infof("Skipping reporting SslCertificate binding metric: already reported for %s.", id.String())
continue
}
mcrt, err := s.managedCertificate.Get(id)
if err != nil {
return err
}
creationTime, err := time.Parse(time.RFC3339, mcrt.CreationTimestamp.Format(time.RFC3339))
if err != nil {
return err
}
s.metrics.ObserveSslCertificateBindingLatency(creationTime)
if err := s.state.SetSslCertificateBindingReported(ctx, id); err != nil {
return err
}
}
return nil
}
func (s impl) Ingress(ctx context.Context, id types.Id) error {
originalIngress, err := s.ingress.Get(id)
if errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
klog.Infof("Syncing Ingress %s", id.String())
sslCertificates, managedCertificates, err := s.getCertificatesToAttach(originalIngress)
if err != nil {
return fmt.Errorf("getCertificatesToAttach(): %w", err)
}
preSharedCertValue := buildPreSharedCertAnnotation(sslCertificates)
if preSharedCertValue == originalIngress.Annotations[config.AnnotationPreSharedCertKey] {
return nil
}
klog.Infof("Annotation %s on Ingress %s was %s, set to %s",
config.AnnotationPreSharedCertKey, id.String(),
originalIngress.Annotations[config.AnnotationPreSharedCertKey], preSharedCertValue)
modifiedIngress := originalIngress.DeepCopy()
if modifiedIngress.Annotations == nil {
modifiedIngress.Annotations = make(map[string]string, 0)
}
modifiedIngress.Annotations[config.AnnotationPreSharedCertKey] = preSharedCertValue
patchBytes, modified, err := patch.CreateMergePatch(originalIngress, modifiedIngress)
if err != nil {
return fmt.Errorf("patch.CreateMergePatch(): %w", err)
}
if modified {
err = s.ingress.Patch(ctx, id, patchBytes)
if err != nil {
return fmt.Errorf("s.ingress.Patch(): %w", err)
}
}
if err := s.reportManagedCertificatesAttached(ctx, managedCertificates); err != nil {
return fmt.Errorf("reportManagedCertificatesAttached(): %w", err)
}
return nil
}
// createStateEntry creates a new state entry for given ManagedCertificate id with a random
// name for the SslCertificate. Returns existing state entry for that id if it already exists.
func (s impl) createStateEntry(ctx context.Context, id types.Id) (state.Entry, error) {
entry, err := s.state.Get(id)
if err == nil {
return entry, nil
} else if !errors.IsNotFound(err) {
return state.Entry{}, err
}
sslCertificateName, err := s.random.Name()
if err != nil {
return state.Entry{}, err
}
klog.Infof("Add to state SslCertificate name %s for ManagedCertificate %s",
sslCertificateName, id.String())
s.state.Insert(ctx, id, sslCertificateName)
return s.state.Get(id)
}
func (s impl) observeSslCertificateCreationLatency(ctx context.Context, sslCertificateName string,
id types.Id, managedCertificate v1.ManagedCertificate) error {
entry, err := s.state.Get(id)
if err != nil {
return err
}
if entry.ExcludedFromSLO {
klog.Infof(`Skipping reporting SslCertificate creation metric,
because %s is marked as excluded from SLO calculations.`, id.String())
return nil
}
if entry.SslCertificateCreationReported {
klog.Infof(`Skipping reporting SslCertificate creation metric,
already reported for %s.`, id.String())
return nil
}
creationTime, err := time.Parse(time.RFC3339,
managedCertificate.CreationTimestamp.Format(time.RFC3339))
if err != nil {
return err
}
s.metrics.ObserveSslCertificateCreationLatency(creationTime)
if err := s.state.SetSslCertificateCreationReported(ctx, id); err != nil {
return err
}
return nil
}
// deleteSslCertificate marks the state entry for the ManagedCertificate id as
// soft-deleted then deletes the SslCertificate. It does not delete the state entry.
func (s impl) deleteSslCertificate(ctx context.Context,
managedCertificate *v1.ManagedCertificate,
id types.Id, sslCertificateName string) error {
klog.Infof("Mark entry for ManagedCertificate %s as soft deleted", id.String())
if err := s.state.SetSoftDeleted(ctx, id, true); err != nil {
return err
}
klog.Infof("Delete SslCertificate %s for ManagedCertificate %s",
sslCertificateName, id.String())
return errors.IgnoreNotFound(s.ssl.Delete(ctx, sslCertificateName, managedCertificate))
}
// createSslCertificate creates an SslCertificate and returns it. If the same
// SslCertificate already exists (i.e same domains and name), it returns the
// existing one.
// Returns an error if there is no entry for given ManagedCertificate in the state.
func (s impl) createSslCertificate(ctx context.Context, sslCertificateName string,
id types.Id, managedCertificate *v1.ManagedCertificate) (*computev1.SslCertificate, error) {
sslCert, err := s.ssl.Get(sslCertificateName, managedCertificate)
if err != nil && !errors.IsNotFound(err) {
return nil, err
}
if err == nil { // Exists
diff := certificates.Diff(*managedCertificate, *sslCert)
if diff == "" {
klog.Infof(`SslCertificate: %+v already exists, restoring it if it
is soft-deleted`, sslCert)
if err = s.state.SetSoftDeleted(ctx, id, false); err != nil {
return nil, err
}
return sslCert, nil
}
klog.Infof(`Certificates out of sync: certificates.Diff(%s, %s): %s,
ManagedCertificate: %+v, SslCertificate: %+v. Deleting SslCertificate %s
and recreating it.`,
id, sslCert.Name, diff, managedCertificate, sslCert, sslCert.Name)
if err := s.deleteSslCertificate(ctx, managedCertificate, id, sslCertificateName); err != nil {
return nil, err
}
}
if err = s.state.SetSoftDeleted(ctx, id, false); err != nil {
return nil, err
}
if err = s.ssl.Create(ctx, sslCertificateName, *managedCertificate); err != nil {
return nil, err
}
if err = s.observeSslCertificateCreationLatency(ctx, sslCertificateName,
id, *managedCertificate); err != nil {
return nil, err
}
return s.ssl.Get(sslCertificateName, managedCertificate)
}
func (s impl) ManagedCertificate(ctx context.Context, id types.Id) error {
originalMcrt, err := s.managedCertificate.Get(id)
if errors.IsNotFound(err) {
entry, err := s.state.Get(id)
if errors.IsNotFound(err) {
return nil
} else if err != nil {
return err
}
klog.Infof(`ManagedCertificate %s already deleted. Deleting its
SslCertificate %s`, id.String(), entry.SslCertificateName)
if err = s.deleteSslCertificate(ctx, nil, id, entry.SslCertificateName); err != nil {
return err
}
klog.Infof("Remove entry for ManagedCertificate %s from state", id.String())
s.state.Delete(ctx, id)
return nil
} else if err != nil {
return err
}
klog.Infof("Syncing ManagedCertificate %s", id.String())
stateEntry, err := s.createStateEntry(ctx, id)
if err != nil {
return err
}
modifiedMcrt := originalMcrt.DeepCopy()
sslCert, err := s.createSslCertificate(ctx, stateEntry.SslCertificateName, id, modifiedMcrt)
if err != nil {
return err
}
if err := certificates.CopyStatus(*sslCert, modifiedMcrt, s.config); err != nil {
return err
}
patchBytes, modified, err := patch.CreateMergePatch(originalMcrt, modifiedMcrt)
if err != nil {
return fmt.Errorf("patch.CreateMergePatch(): %w", err)
}
if modified {
err = s.managedCertificate.Patch(ctx, id, patchBytes)
}
return err
}