-
Notifications
You must be signed in to change notification settings - Fork 202
/
annotator.go
519 lines (484 loc) · 17 KB
/
annotator.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package kubernetes
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"strings"
jsonpatch "github.com/evanphx/json-patch"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
batchv1beta1 "k8s.io/api/batch/v1beta1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
yamlDecoder "k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/yaml"
"github.com/dapr/dapr/pkg/injector/sidecar"
)
const (
// Dapr annotation keys.
daprEnabledKey = "dapr.io/enabled"
daprAppPortKey = "dapr.io/app-port"
daprConfigKey = "dapr.io/config"
daprAppProtocolKey = "dapr.io/app-protocol"
daprAppIDKey = "dapr.io/app-id"
daprEnableProfilingKey = "dapr.io/enable-profiling"
daprLogLevelKey = "dapr.io/log-level"
daprAPITokenSecretKey = "dapr.io/api-token-secret" /* #nosec */
daprAppTokenSecretKey = "dapr.io/app-token-secret" /* #nosec */
daprLogAsJSONKey = "dapr.io/log-as-json"
daprAppMaxConcurrencyKey = "dapr.io/app-max-concurrency"
daprEnableMetricsKey = "dapr.io/enable-metrics"
daprMetricsPortKey = "dapr.io/metrics-port"
daprEnableDebugKey = "dapr.io/enable-debug"
daprDebugPortKey = "dapr.io/debug-port"
daprEnvKey = "dapr.io/env"
daprCPULimitKey = "dapr.io/sidecar-cpu-limit"
daprMemoryLimitKey = "dapr.io/sidecar-memory-limit"
daprCPURequestKey = "dapr.io/sidecar-cpu-request"
daprMemoryRequestKey = "dapr.io/sidecar-memory-request"
daprListenAddressesKey = "dapr.io/sidecar-listen-addresses"
daprLivenessProbeDelayKey = "dapr.io/sidecar-liveness-probe-delay-seconds"
daprLivenessProbeTimeoutKey = "dapr.io/sidecar-liveness-probe-timeout-seconds"
daprLivenessProbePeriodKey = "dapr.io/sidecar-liveness-probe-period-seconds"
daprLivenessProbeThresholdKey = "dapr.io/sidecar-liveness-probe-threshold"
daprReadinessProbeDelayKey = "dapr.io/sidecar-readiness-probe-delay-seconds"
daprReadinessProbeTimeoutKey = "dapr.io/sidecar-readiness-probe-timeout-seconds"
daprReadinessProbePeriodKey = "dapr.io/sidecar-readiness-probe-period-seconds"
daprReadinessProbeThresholdKey = "dapr.io/sidecar-readiness-probe-threshold"
daprImageKey = "dapr.io/sidecar-image"
daprAppSSLKey = "dapr.io/app-ssl"
daprMaxRequestBodySizeKey = "dapr.io/http-max-request-size"
daprReadBufferSizeKey = "dapr.io/http-read-buffer-size"
daprHTTPStreamRequestBodyKey = "dapr.io/http-stream-request-body"
daprGracefulShutdownSecondsKey = "dapr.io/graceful-shutdown-seconds"
daprEnableAPILoggingKey = "dapr.io/enable-api-logging"
daprUnixDomainSocketPathKey = "dapr.io/unix-domain-socket-path"
daprVolumeMountsReadOnlyKey = "dapr.io/volume-mounts"
daprVolumeMountsReadWriteKey = "dapr.io/volume-mounts-rw"
daprDisableBuiltinK8sSecretStoreKey = "dapr.io/disable-builtin-k8s-secret-store" /* #nosec */
daprPlacementHostAddressKey = "dapr.io/placement-host-address"
// K8s kinds.
pod = "pod"
deployment = "deployment"
replicaset = "replicaset"
daemonset = "daemonset"
statefulset = "statefulset"
cronjob = "cronjob"
job = "job"
list = "list"
cronjobAnnotationsPath = "/spec/jobTemplate/spec/template/metadata/annotations"
podAnnotationsPath = "/metadata/annotations"
templateAnnotationsPath = "/spec/template/metadata/annotations"
)
type Annotator interface {
Annotate(io.Reader, io.Writer) error
}
type K8sAnnotator struct {
config K8sAnnotatorConfig
annotated bool
}
type K8sAnnotatorConfig struct {
// If TargetResource is set, we will search for it and then inject
// annotations on that target resource. If it is not set, we will
// update the first appropriate resource we find.
TargetResource *string
// If TargetNamespace is set, we will search for the target resource
// in the provided target namespace. If it is not set, we will
// just search for the first occurrence of the target resource.
TargetNamespace *string
}
func NewK8sAnnotator(config K8sAnnotatorConfig) *K8sAnnotator {
return &K8sAnnotator{
config: config,
annotated: false,
}
}
// Annotate injects dapr annotations into the kubernetes resource.
func (p *K8sAnnotator) Annotate(inputs []io.Reader, out io.Writer, opts AnnotateOptions) error {
for _, input := range inputs {
err := p.processInput(input, out, opts)
if err != nil {
return err
}
}
return nil
}
func (p *K8sAnnotator) processInput(input io.Reader, out io.Writer, opts AnnotateOptions) error {
reader := yamlDecoder.NewYAMLReader(bufio.NewReaderSize(input, 4096))
var result []byte
iterations := 0
// Read from input and process until EOF or error.
for {
bytes, err := reader.Read()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return err
}
// Check if the input is a list as
// these requires additional processing.
var metaType metav1.TypeMeta
if err = yaml.Unmarshal(bytes, &metaType); err != nil {
return err
}
kind := strings.ToLower(metaType.Kind)
if kind == list {
var sourceList corev1.List
if err = yaml.Unmarshal(bytes, &sourceList); err != nil {
return err
}
items := []runtime.RawExtension{}
for _, item := range sourceList.Items {
var processedYAML []byte
processedYAML, err = p.processYAML(item.Raw, opts)
if err != nil {
return err
}
var annotatedJSON []byte
annotatedJSON, err = yaml.YAMLToJSON(processedYAML)
if err != nil {
return err
}
items = append(items, runtime.RawExtension{Raw: annotatedJSON}) //nolint:exhaustivestruct
}
sourceList.Items = items
result, err = yaml.Marshal(sourceList)
if err != nil {
return err
}
} else {
var processedYAML []byte
processedYAML, err = p.processYAML(bytes, opts)
if err != nil {
return err
}
result = processedYAML
}
// Insert separator between documents.
if iterations > 0 {
out.Write([]byte("---\n"))
}
// Write result from processing into the writer.
_, err = out.Write(result)
if err != nil {
return err
}
iterations++
}
return nil
}
func (p *K8sAnnotator) processYAML(yamlBytes []byte, opts AnnotateOptions) ([]byte, error) {
var err error
var processedYAML []byte
if p.annotated {
// We can only inject dapr into a single resource per execution as the configuration
// options are scoped to a single resource e.g. app-id, port, etc. are specific to a
// dapr enabled resource. Instead we expect multiple runs to be piped together.
processedYAML = yamlBytes
} else {
var annotated bool
processedYAML, annotated, err = p.annotateYAML(yamlBytes, opts)
if err != nil {
return nil, err
}
if annotated {
// Record that we have injected into a document.
p.annotated = annotated
}
}
return processedYAML, nil
}
func (p *K8sAnnotator) annotateYAML(input []byte, config AnnotateOptions) ([]byte, bool, error) {
// We read the metadata again here so this method is encapsulated.
var metaType metav1.TypeMeta
if err := yaml.Unmarshal(input, &metaType); err != nil {
return nil, false, err
}
// If the input resource is a 'kind' that
// we want to inject dapr into, then we
// Unmarshal the input into the appropriate
// type and set the required fields to build
// a patch (path, value, op).
var path string
var annotations map[string]string
var name string
var ns string
kind := strings.ToLower(metaType.Kind)
switch kind {
case pod:
pod := &corev1.Pod{} //nolint:exhaustivestruct
if err := yaml.Unmarshal(input, pod); err != nil {
return nil, false, err
}
name = pod.Name
annotations = pod.Annotations
path = podAnnotationsPath
ns = getNamespaceOrDefault(pod)
case cronjob:
cronjob := &batchv1beta1.CronJob{} //nolint:exhaustivestruct
if err := yaml.Unmarshal(input, cronjob); err != nil {
return nil, false, err
}
name = cronjob.Name
annotations = cronjob.Spec.JobTemplate.Spec.Template.Annotations
path = cronjobAnnotationsPath
ns = getNamespaceOrDefault(cronjob)
case deployment:
deployment := &appsv1.Deployment{} //nolint:exhaustivestruct
if err := yaml.Unmarshal(input, deployment); err != nil {
return nil, false, err
}
name = deployment.Name
annotations = deployment.Spec.Template.Annotations
path = templateAnnotationsPath
ns = getNamespaceOrDefault(deployment)
case replicaset:
replicaset := &appsv1.ReplicaSet{} //nolint:exhaustivestruct
if err := yaml.Unmarshal(input, replicaset); err != nil {
return nil, false, err
}
name = replicaset.Name
annotations = replicaset.Spec.Template.Annotations
path = templateAnnotationsPath
ns = getNamespaceOrDefault(replicaset)
case job:
job := &batchv1.Job{} //nolint:exhaustivestruct
if err := yaml.Unmarshal(input, job); err != nil {
return nil, false, err
}
name = job.Name
annotations = job.Spec.Template.Annotations
path = templateAnnotationsPath
ns = getNamespaceOrDefault(job)
case statefulset:
statefulset := &appsv1.StatefulSet{} //nolint:exhaustivestruct
if err := yaml.Unmarshal(input, statefulset); err != nil {
return nil, false, err
}
name = statefulset.Name
annotations = statefulset.Spec.Template.Annotations
path = templateAnnotationsPath
ns = getNamespaceOrDefault(statefulset)
case daemonset:
daemonset := &appsv1.DaemonSet{} //nolint:exhaustivestruct
if err := yaml.Unmarshal(input, daemonset); err != nil {
return nil, false, err
}
name = daemonset.Name
annotations = daemonset.Spec.Template.Annotations
path = templateAnnotationsPath
ns = getNamespaceOrDefault(daemonset)
default:
// No annotation needed for this kind.
return input, false, nil
}
// TODO: Currently this is where we decide not to
// annotate dapr on this resource as it isn't the
// target we are looking for. This is a bit late
// so it would be good to find a earlier place to
// do this.
if p.config.TargetResource != nil && *p.config.TargetResource != "" {
if !strings.EqualFold(*p.config.TargetResource, name) {
// Not the resource name we're annotating.
return input, false, nil
}
if p.config.TargetNamespace != nil && *p.config.TargetNamespace != "" {
if !strings.EqualFold(*p.config.TargetNamespace, ns) {
// Not the namespace we're annotating.
return input, false, nil
}
}
}
// Get the dapr annotations and set them on the
// resources existing annotation map. This will
// override any existing conflicting annotations.
if annotations == nil {
annotations = make(map[string]string)
}
daprAnnotations := getDaprAnnotations(&config)
for k, v := range daprAnnotations {
// TODO: Should we log when we are overwriting?
// if _, exists := annotations[k]; exists {}.
annotations[k] = v
}
// Check if the app id has been set, if not, we'll
// use the resource metadata namespace, kind and name.
// For example: namespace-kind-name.
if _, appIDSet := annotations[daprAppIDKey]; !appIDSet {
annotations[daprAppIDKey] = fmt.Sprintf("%s-%s-%s", ns, kind, name)
}
// Create a patch operation for the annotations.
patchOps := []sidecar.PatchOperation{}
patchOps = append(patchOps, sidecar.PatchOperation{
Op: "add",
Path: path,
Value: annotations,
})
patchBytes, err := json.Marshal(patchOps)
if err != nil {
return nil, false, err
}
if len(patchBytes) == 0 {
return input, false, nil
}
patch, err := jsonpatch.DecodePatch(patchBytes)
if err != nil {
return nil, false, err
}
// As we are applying the patch as a json patch,
// we have to convert the current YAML resource to
// JSON, apply the patch and then convert back.
inputAsJSON, err := yaml.YAMLToJSON(input)
if err != nil {
return nil, false, err
}
annotatedAsJSON, err := patch.Apply(inputAsJSON)
if err != nil {
return nil, false, err
}
annotatedAsYAML, err := yaml.JSONToYAML(annotatedAsJSON)
if err != nil {
return nil, false, err
}
return annotatedAsYAML, true, nil
}
type NamespacedObject interface {
GetNamespace() string
}
func getNamespaceOrDefault(obj NamespacedObject) string {
ns := obj.GetNamespace()
if ns == "" {
return "default"
}
return ns
}
func getDaprAnnotations(config *AnnotateOptions) map[string]string {
annotations := make(map[string]string)
annotations[daprEnabledKey] = "true"
if config.appID != nil {
annotations[daprAppIDKey] = *config.appID
}
if config.metricsEnabled != nil {
annotations[daprEnableMetricsKey] = strconv.FormatBool(*config.metricsEnabled)
}
if config.metricsPort != nil {
annotations[daprMetricsPortKey] = strconv.FormatInt(int64(*config.metricsPort), 10)
}
if config.appPort != nil {
annotations[daprAppPortKey] = strconv.FormatInt(int64(*config.appPort), 10)
}
if config.config != nil {
annotations[daprConfigKey] = *config.config
}
if config.appProtocol != nil {
annotations[daprAppProtocolKey] = *config.appProtocol
}
if config.profileEnabled != nil {
annotations[daprEnableProfilingKey] = strconv.FormatBool(*config.profileEnabled)
}
if config.logLevel != nil {
annotations[daprLogLevelKey] = *config.logLevel
}
if config.logAsJSON != nil {
annotations[daprLogAsJSONKey] = strconv.FormatBool(*config.logAsJSON)
}
if config.apiTokenSecret != nil {
annotations[daprAPITokenSecretKey] = *config.apiTokenSecret
}
if config.appTokenSecret != nil {
annotations[daprAppTokenSecretKey] = *config.appTokenSecret
}
if config.appMaxConcurrency != nil {
annotations[daprAppMaxConcurrencyKey] = strconv.FormatInt(int64(*config.appMaxConcurrency), 10)
}
if config.debugEnabled != nil {
annotations[daprEnableDebugKey] = strconv.FormatBool(*config.debugEnabled)
}
if config.debugPort != nil {
annotations[daprDebugPortKey] = strconv.FormatInt(int64(*config.debugPort), 10)
}
if config.env != nil {
annotations[daprEnvKey] = *config.env
}
if config.cpuLimit != nil {
annotations[daprCPULimitKey] = *config.cpuLimit
}
if config.memoryLimit != nil {
annotations[daprMemoryLimitKey] = *config.memoryLimit
}
if config.cpuRequest != nil {
annotations[daprCPURequestKey] = *config.cpuRequest
}
if config.memoryRequest != nil {
annotations[daprMemoryRequestKey] = *config.memoryRequest
}
if config.listenAddresses != nil {
annotations[daprListenAddressesKey] = *config.listenAddresses
}
if config.livenessProbeDelay != nil {
annotations[daprLivenessProbeDelayKey] = strconv.FormatInt(int64(*config.livenessProbeDelay), 10)
}
if config.livenessProbeTimeout != nil {
annotations[daprLivenessProbeTimeoutKey] = strconv.FormatInt(int64(*config.livenessProbeTimeout), 10)
}
if config.livenessProbePeriod != nil {
annotations[daprLivenessProbePeriodKey] = strconv.FormatInt(int64(*config.livenessProbePeriod), 10)
}
if config.livenessProbeThreshold != nil {
annotations[daprLivenessProbeThresholdKey] = strconv.FormatInt(int64(*config.livenessProbeThreshold), 10)
}
if config.readinessProbeDelay != nil {
annotations[daprReadinessProbeDelayKey] = strconv.FormatInt(int64(*config.readinessProbeDelay), 10)
}
if config.readinessProbeTimeout != nil {
annotations[daprReadinessProbeTimeoutKey] = strconv.FormatInt(int64(*config.readinessProbeTimeout), 10)
}
if config.readinessProbePeriod != nil {
annotations[daprReadinessProbePeriodKey] = strconv.FormatInt(int64(*config.readinessProbePeriod), 10)
}
if config.readinessProbeThreshold != nil {
annotations[daprReadinessProbeThresholdKey] = strconv.FormatInt(int64(*config.readinessProbeThreshold), 10)
}
if config.image != nil {
annotations[daprImageKey] = *config.image
}
if config.appSSL != nil {
annotations[daprAppSSLKey] = strconv.FormatBool(*config.appSSL)
}
if config.maxRequestBodySize != nil {
annotations[daprMaxRequestBodySizeKey] = strconv.FormatInt(int64(*config.maxRequestBodySize), 10)
}
if config.readBufferSize != nil {
annotations[daprReadBufferSizeKey] = strconv.FormatInt(int64(*config.readBufferSize), 10)
}
if config.httpStreamRequestBody != nil {
annotations[daprHTTPStreamRequestBodyKey] = strconv.FormatBool(*config.httpStreamRequestBody)
}
if config.gracefulShutdownSeconds != nil {
annotations[daprGracefulShutdownSecondsKey] = strconv.FormatInt(int64(*config.gracefulShutdownSeconds), 10)
}
if config.enableAPILogging != nil {
annotations[daprEnableAPILoggingKey] = strconv.FormatBool(*config.enableAPILogging)
}
if config.unixDomainSocketPath != nil {
annotations[daprUnixDomainSocketPathKey] = *config.unixDomainSocketPath
}
if config.volumeMountsReadOnly != nil {
annotations[daprVolumeMountsReadOnlyKey] = *config.volumeMountsReadOnly
}
if config.volumeMountsReadWrite != nil {
annotations[daprVolumeMountsReadWriteKey] = *config.volumeMountsReadWrite
}
if config.disableBuiltinK8sSecretStore != nil {
annotations[daprDisableBuiltinK8sSecretStoreKey] = strconv.FormatBool(*config.disableBuiltinK8sSecretStore)
}
if config.placementHostAddress != nil {
annotations[daprPlacementHostAddressKey] = *config.placementHostAddress
}
return annotations
}