-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
memcached_with_customization.go
1441 lines (1209 loc) · 48.6 KB
/
memcached_with_customization.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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The Operator-SDK 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 v3
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
log "github.com/sirupsen/logrus"
kbutil "sigs.k8s.io/kubebuilder/v3/pkg/plugin/util"
"github.com/operator-framework/operator-sdk/hack/generate/samples/internal/pkg"
)
// Memcached defines the Memcached Sample in GO using webhooks and monitoring code
type Memcached struct {
ctx *pkg.SampleContext
}
var generateWithMonitoring bool
var goFilesHeader string
var prometheusAPIVersion = "v0.59.0"
// GenerateSample will call all actions to create the directory and generate the sample
// Note that it should NOT be called in the e2e tests.
func GenerateSample(binaryPath, samplesPath string) {
log.Infof("starting to generate Go memcached sample with webhooks and metrics documentation")
ctx, err := pkg.NewSampleContext(binaryPath, filepath.Join(samplesPath, "memcached-operator"), "GO111MODULE=on")
pkg.CheckError("generating Go memcached with webhooks and metrics documentation context", err)
generateWithMonitoring = false
if strings.HasSuffix(samplesPath, "monitoring") {
generateWithMonitoring = true
}
memcached := Memcached{&ctx}
memcached.Prepare()
memcached.Run()
}
// Prepare the Context for the Memcached with webhooks and metrics documentation Go Sample
// Note that sample directory will be re-created and the context data for the sample
// will be set such as the domain and GVK.
func (mh *Memcached) Prepare() {
log.Infof("destroying directory for Memcached with webhooks and metrics documentation Go samples")
mh.ctx.Destroy()
log.Infof("creating directory")
err := mh.ctx.Prepare()
pkg.CheckError("creating directory for Go Sample", err)
log.Infof("setting domain and GVK")
mh.ctx.Domain = "example.com"
mh.ctx.Version = "v1alpha1"
mh.ctx.Group = "cache"
mh.ctx.Kind = "Memcached"
}
// Run the steps to create the Memcached with metrics and webhooks Go Sample
func (mh *Memcached) Run() {
if strings.Contains(mh.ctx.Dir, "v4-alpha") {
log.Infof("creating the v4-alpha project")
err := mh.ctx.Init(
"--plugins", "go/v4-alpha",
"--project-version", "3",
"--repo", "github.com/example/memcached-operator",
"--domain", mh.ctx.Domain)
pkg.CheckError("creating the project", err)
} else {
log.Infof("creating the go/v3 project")
err := mh.ctx.Init(
"--plugins", "go/v3",
"--project-version", "3",
"--repo", "github.com/example/memcached-operator",
"--domain", mh.ctx.Domain)
pkg.CheckError("creating the project", err)
}
err := mh.ctx.CreateAPI(
"--group", mh.ctx.Group,
"--version", mh.ctx.Version,
"--kind", mh.ctx.Kind,
"--plugins", "deploy-image/v1-alpha",
"--image", "memcached:1.4.36-alpine",
"--image-container-command", "memcached,-m=64,-o,modern,-v",
"--image-container-port", "11211",
"--run-as-user", "1001",
"--make=false",
"--manifests=false")
pkg.CheckError("scaffolding apis", err)
err = mh.ctx.UncommentRestrictivePodStandards()
pkg.CheckError("creating the bundle", err)
log.Infof("implementing the API markers")
mh.implementingAPIMarkers()
log.Infof("implementing the Controller")
mh.implementingController()
if generateWithMonitoring {
goGetcmd := exec.Command("go", "get", fmt.Sprintf("%s@%s", "github.com/prometheus-operator/prometheus-operator", prometheusAPIVersion))
goGetcmd.Dir = mh.ctx.Dir
if _, err := mh.ctx.Run(goGetcmd); err != nil {
pkg.CheckError("error getting prometheus dependency", err)
}
log.Infof("implementing Monitoring")
mh.implementingMonitoring()
}
log.Infof("scaffolding webhook")
err = mh.ctx.CreateWebhook(
"--group", mh.ctx.Group,
"--version", mh.ctx.Version,
"--kind", mh.ctx.Kind,
"--defaulting",
"--defaulting")
pkg.CheckError("scaffolding webhook", err)
mh.implementingWebhooks()
if strings.Contains(mh.ctx.Dir, "v4-alpha") {
mh.uncommentDefaultKustomizationV4()
mh.uncommentManifestsKustomizationv4()
} else {
mh.uncommentDefaultKustomizationV3()
mh.uncommentManifestsKustomizationv3()
}
mh.implementingE2ETests()
cmd := exec.Command("go", "mod", "tidy")
cmd.Dir = mh.ctx.Dir
_, err = mh.ctx.Run(cmd)
pkg.CheckError("Running go mod tidy", err)
if generateWithMonitoring {
cmd := exec.Command("make", "generate-metricsdocs")
cmd.Dir = mh.ctx.Dir
_, err = mh.ctx.Run(cmd)
pkg.CheckError("Running make generate-metricsdocs", err)
}
log.Infof("creating the bundle")
err = mh.ctx.GenerateBundle()
pkg.CheckError("creating the bundle", err)
log.Infof("setting createdAt annotation")
csv := filepath.Join(mh.ctx.Dir, "bundle", "manifests", mh.ctx.ProjectName+".clusterserviceversion.yaml")
err = kbutil.ReplaceRegexInFile(csv, "createdAt:.*", createdAt)
pkg.CheckError("setting createdAt annotation", err)
log.Infof("striping bundle annotations")
err = mh.ctx.StripBundleAnnotations()
pkg.CheckError("striping bundle annotations", err)
pkg.CheckError("formatting project", mh.ctx.Make("fmt"))
// Clean up built binaries, if any.
pkg.CheckError("cleaning up", os.RemoveAll(filepath.Join(mh.ctx.Dir, "bin")))
}
// uncommentDefaultKustomizationV3 will uncomment code in config/default/kustomization.yaml
func (mh *Memcached) uncommentDefaultKustomizationV3() {
var err error
kustomization := filepath.Join(mh.ctx.Dir, "config", "default", "kustomization.yaml")
log.Info("uncommenting config/default/kustomization.yaml to enable webhooks and ca injection")
err = kbutil.UncommentCode(kustomization, "#- ../webhook", "#")
pkg.CheckError("uncomment webhook", err)
err = kbutil.UncommentCode(kustomization, "#- ../certmanager", "#")
pkg.CheckError("uncomment certmanager", err)
err = kbutil.UncommentCode(kustomization, "#- ../prometheus", "#")
pkg.CheckError("uncomment prometheus", err)
err = kbutil.UncommentCode(kustomization, "#- manager_webhook_patch.yaml", "#")
pkg.CheckError("uncomment manager_webhook_patch.yaml", err)
err = kbutil.UncommentCode(kustomization, "#- webhookcainjection_patch.yaml", "#")
pkg.CheckError("uncomment webhookcainjection_patch.yaml", err)
err = kbutil.UncommentCode(kustomization,
`#- name: CERTIFICATE_NAMESPACE # namespace of the certificate CR
# objref:
# kind: Certificate
# group: cert-manager.io
# version: v1
# name: serving-cert # this name should match the one in certificate.yaml
# fieldref:
# fieldpath: metadata.namespace
#- name: CERTIFICATE_NAME
# objref:
# kind: Certificate
# group: cert-manager.io
# version: v1
# name: serving-cert # this name should match the one in certificate.yaml
#- name: SERVICE_NAMESPACE # namespace of the service
# objref:
# kind: Service
# version: v1
# name: webhook-service
# fieldref:
# fieldpath: metadata.namespace
#- name: SERVICE_NAME
# objref:
# kind: Service
# version: v1
# name: webhook-service`, "#")
pkg.CheckError("uncommented certificate CR", err)
}
// uncommentDefaultKustomizationV3 will uncomment code in config/default/kustomization.yaml
func (mh *Memcached) uncommentDefaultKustomizationV4() {
var err error
kustomization := filepath.Join(mh.ctx.Dir, "config", "default", "kustomization.yaml")
log.Info("uncommenting config/default/kustomization.yaml to enable webhooks and ca injection")
err = kbutil.UncommentCode(kustomization, "#- ../webhook", "#")
pkg.CheckError("uncomment webhook", err)
err = kbutil.UncommentCode(kustomization, "#- ../certmanager", "#")
pkg.CheckError("uncomment certmanager", err)
err = kbutil.UncommentCode(kustomization, "#- ../prometheus", "#")
pkg.CheckError("uncomment prometheus", err)
err = kbutil.UncommentCode(kustomization, "#- manager_webhook_patch.yaml", "#")
pkg.CheckError("uncomment manager_webhook_patch.yaml", err)
err = kbutil.UncommentCode(kustomization, "#- webhookcainjection_patch.yaml", "#")
pkg.CheckError("uncomment webhookcainjection_patch.yaml", err)
err = kbutil.UncommentCode(kustomization,
`#replacements:
# - source: # Add cert-manager annotation to ValidatingWebhookConfiguration, MutatingWebhookConfiguration and CRDs
# kind: Certificate
# group: cert-manager.io
# version: v1
# name: serving-cert # this name should match the one in certificate.yaml
# fieldPath: .metadata.namespace # namespace of the certificate CR
# targets:
# - select:
# kind: ValidatingWebhookConfiguration
# fieldPaths:
# - .metadata.annotations.[cert-manager.io/inject-ca-from]
# options:
# delimiter: '/'
# index: 0
# create: true
# - select:
# kind: MutatingWebhookConfiguration
# fieldPaths:
# - .metadata.annotations.[cert-manager.io/inject-ca-from]
# options:
# delimiter: '/'
# index: 0
# create: true
# - select:
# kind: CustomResourceDefinition
# fieldPaths:
# - .metadata.annotations.[cert-manager.io/inject-ca-from]
# options:
# delimiter: '/'
# index: 0
# create: true
# - source:
# kind: Certificate
# group: cert-manager.io
# version: v1
# name: serving-cert # this name should match the one in certificate.yaml
# fieldPath: .metadata.name
# targets:
# - select:
# kind: ValidatingWebhookConfiguration
# fieldPaths:
# - .metadata.annotations.[cert-manager.io/inject-ca-from]
# options:
# delimiter: '/'
# index: 1
# create: true
# - select:
# kind: MutatingWebhookConfiguration
# fieldPaths:
# - .metadata.annotations.[cert-manager.io/inject-ca-from]
# options:
# delimiter: '/'
# index: 1
# create: true
# - select:
# kind: CustomResourceDefinition
# fieldPaths:
# - .metadata.annotations.[cert-manager.io/inject-ca-from]
# options:
# delimiter: '/'
# index: 1
# create: true
# - source: # Add cert-manager annotation to the webhook Service
# kind: Service
# version: v1
# name: webhook-service
# fieldPath: .metadata.name # namespace of the service
# targets:
# - select:
# kind: Certificate
# group: cert-manager.io
# version: v1
# fieldPaths:
# - .spec.dnsNames.0
# - .spec.dnsNames.1
# options:
# delimiter: '.'
# index: 0
# create: true
# - source:
# kind: Service
# version: v1
# name: webhook-service
# fieldPath: .metadata.namespace # namespace of the service
# targets:
# - select:
# kind: Certificate
# group: cert-manager.io
# version: v1
# fieldPaths:
# - .spec.dnsNames.0
# - .spec.dnsNames.1
# options:
# delimiter: '.'
# index: 1
# create: true`, "#")
pkg.CheckError("uncommented certificate CR", err)
}
// uncommentManifestsKustomization will uncomment code in config/manifests/kustomization.yaml
func (mh *Memcached) uncommentManifestsKustomizationv3() {
var err error
kustomization := filepath.Join(mh.ctx.Dir, "config", "manifests", "kustomization.yaml")
log.Info("uncommenting config/manifests/kustomization.yaml to enable webhooks in OLM")
err = kbutil.UncommentCode(kustomization,
`#patchesJson6902:
#- target:
# group: apps
# version: v1
# kind: Deployment
# name: controller-manager
# namespace: system
# patch: |-
# # Remove the manager container's "cert" volumeMount, since OLM will create and mount a set of certs.
# # Update the indices in this path if adding or removing containers/volumeMounts in the manager's Deployment.
# - op: remove
# path: /spec/template/spec/containers/1/volumeMounts/0
# # Remove the "cert" volume, since OLM will create and mount a set of certs.
# # Update the indices in this path if adding or removing volumes in the manager's Deployment.
# - op: remove
# path: /spec/template/spec/volumes/0`, "#")
pkg.CheckError("uncommented webhook volume removal patch", err)
}
// uncommentManifestsKustomization will uncomment code in config/manifests/kustomization.yaml
func (mh *Memcached) uncommentManifestsKustomizationv4() {
var err error
kustomization := filepath.Join(mh.ctx.Dir, "config", "manifests", "kustomization.yaml")
log.Info("uncommenting config/manifests/kustomization.yaml to enable webhooks in OLM")
err = kbutil.UncommentCode(kustomization,
`#patchesJson6902:
#- target:
# group: apps
# version: v1
# kind: Deployment
# name: controller-manager
# namespace: system
# patch: |-
# # Remove the manager container's "cert" volumeMount, since OLM will create and mount a set of certs.
# # Update the indices in this path if adding or removing containers/volumeMounts in the manager's Deployment.
# - op: remove
# path: /spec/template/spec/containers/0/volumeMounts/0
# # Remove the "cert" volume, since OLM will create and mount a set of certs.
# # Update the indices in this path if adding or removing volumes in the manager's Deployment.
# - op: remove
# path: /spec/template/spec/volumes/0`, "#")
pkg.CheckError("uncommented webhook volume removal patch", err)
}
// implementingWebhooks will customize the kind wekbhok file
func (mh *Memcached) implementingWebhooks() {
log.Infof("implementing webhooks")
webhookPath := filepath.Join(mh.ctx.Dir, "api", mh.ctx.Version, fmt.Sprintf("%s_webhook.go",
strings.ToLower(mh.ctx.Kind)))
// Add webhook methods
err := kbutil.InsertCode(webhookPath,
"// TODO(user): fill in your defaulting logic.\n}",
webhooksFragment)
pkg.CheckError("replacing webhook validate implementation", err)
err = kbutil.ReplaceInFile(webhookPath,
"// TODO(user): fill in your defaulting logic.", "if r.Spec.Size == 0 {\n\t\tr.Spec.Size = 3\n\t}")
pkg.CheckError("replacing webhook default implementation", err)
// Add imports
err = kbutil.InsertCode(webhookPath,
"import (",
// TODO(estroz): remove runtime dep when --programmatic-validation is added to `ccreate webhook` above.
"\"errors\"\n\n\"k8s.io/apimachinery/pkg/runtime\"")
pkg.CheckError("adding imports", err)
}
// implementingController will customize the Controller
func (mh *Memcached) implementingController() {
controllerPath := filepath.Join(mh.ctx.Dir, "controllers", fmt.Sprintf("%s_controller.go",
strings.ToLower(mh.ctx.Kind)))
err := kbutil.InsertCode(controllerPath,
` SecurityContext: &corev1.SecurityContext{`, userIDWarningFragment)
pkg.CheckError("adding warning comment for UserID", err)
err = kbutil.InsertCode(controllerPath,
` RunAsNonRoot: &[]bool{true}[0],`, runAsUserCommentFragment)
pkg.CheckError("adding comment regarding RunAsUser field in Security Context", err)
}
// implementingMonitoring will customize monitoring
func (mh *Memcached) implementingMonitoring() {
err := os.Mkdir(filepath.Join(mh.ctx.Dir, "monitoring"), os.ModePerm)
pkg.CheckError("creating monitoring directory", err)
header, err := os.ReadFile((filepath.Join(mh.ctx.Dir, "hack", "boilerplate.go.txt")))
goFilesHeader = string(header)
pkg.CheckError("reading go files header", err)
log.Infof("implementing metrics")
mh.implementingMetrics()
log.Infof("implementing alerts")
mh.implementingAlerts()
log.Infof("implementing prom-rule-ci")
mh.implementingPromRuleCi()
log.Infof("implementing runbooks")
mh.implementingRunbooks()
log.Infof("implementing prometheus RBAC")
mh.implementingPrometheusRBAC()
log.Infof("customizing the Controller")
mh.customizingController()
log.Infof("customizing Main")
mh.customizingMain()
log.Infof("customizing Dockerfile")
mh.customizingDockerfile()
log.Infof("customizing Makefile")
mh.customizingMakefile()
}
// nolint:gosec
// implementingAPI will customize the API
func (mh *Memcached) implementingAPIMarkers() {
err := kbutil.InsertCode(
filepath.Join(mh.ctx.Dir, "api", mh.ctx.Version, fmt.Sprintf("%s_types.go", strings.ToLower(mh.ctx.Kind))),
"// Port defines the port that will be used to init the container with the image",
`
// +operator-sdk:csv:customresourcedefinitions:type=spec`)
pkg.CheckError("inserting Port spec marker", err)
err = kbutil.InsertCode(
filepath.Join(mh.ctx.Dir, "api", mh.ctx.Version, fmt.Sprintf("%s_types.go", strings.ToLower(mh.ctx.Kind))),
"// +kubebuilder:validation:ExclusiveMaximum=false",
`
// +operator-sdk:csv:customresourcedefinitions:type=spec`)
pkg.CheckError("inserting spec Status", err)
log.Infof("implementing MemcachedStatus marker")
err = kbutil.ReplaceInFile(
filepath.Join(mh.ctx.Dir, "api", mh.ctx.Version, fmt.Sprintf("%s_types.go", strings.ToLower(mh.ctx.Kind))),
` // For further information see: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#typical-status-properties
`,
` // For further information see: https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#typical-status-properties
// Conditions store the status conditions of the Memcached instances
// +operator-sdk:csv:customresourcedefinitions:type=status`,
)
pkg.CheckError("inserting Status marker", err)
err = kbutil.ReplaceInFile(
filepath.Join(mh.ctx.Dir, "api", mh.ctx.Version, fmt.Sprintf("%s_types.go", strings.ToLower(mh.ctx.Kind))),
`
// Size defines the number of Memcached instances
// The following markers will use OpenAPI v3 schema to validate the value
// More info: https://book.kubebuilder.io/reference/markers/crd-validation.html
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=3
// +kubebuilder:validation:ExclusiveMaximum=false
// +operator-sdk:csv:customresourcedefinitions:type=spec`,
`
// The following markers will use OpenAPI v3 schema to validate the value
// More info: https://book.kubebuilder.io/reference/markers/crd-validation.html
// +kubebuilder:validation:Minimum=1
// +kubebuilder:validation:Maximum=3
// +kubebuilder:validation:ExclusiveMaximum=false
// Size defines the number of Memcached instances
// +operator-sdk:csv:customresourcedefinitions:type=spec`,
)
pkg.CheckError("updating Size spec marker", err)
// Add CSV marker that shows CRD owned resources
err = kbutil.InsertCode(
filepath.Join(mh.ctx.Dir, "api", mh.ctx.Version, fmt.Sprintf("%s_types.go", strings.ToLower(mh.ctx.Kind))),
`//+kubebuilder:subresource:status`,
`
// +operator-sdk:csv:customresourcedefinitions:resources={{Deployment,v1,memcached-deployment}}`)
pkg.CheckError("inserting CRD owned resources CSV marker", err)
}
func (mh *Memcached) implementingMetrics() {
// Create metrics file
metricsPath := filepath.Join(mh.ctx.Dir, "monitoring/metrics.go")
_, err := os.Create(metricsPath)
pkg.CheckError("creating metrics file", err)
// Add go files header
err = kbutil.InsertCode(metricsPath,
"",
goFilesHeader)
pkg.CheckError("adding go files header", err)
// Add metrics implementation
err = kbutil.InsertCode(metricsPath,
goFilesHeader,
metricsFragment)
pkg.CheckError("adding metrics content", err)
// Add metricsdocs directory
err = os.Mkdir(filepath.Join(mh.ctx.Dir, "monitoring/metricsdocs"), os.ModePerm)
pkg.CheckError("creating metricsdocs directory", err)
// Create metricsdocs file
metricsdocsPath := filepath.Join(mh.ctx.Dir, "monitoring/metricsdocs/metricsdocs.go")
_, err = os.Create(metricsdocsPath)
pkg.CheckError("creating metricsdocs file", err)
// Add go files header
err = kbutil.InsertCode(metricsdocsPath,
"",
goFilesHeader)
pkg.CheckError("adding go files header", err)
// Create metricsdocs generator tool
err = kbutil.InsertCode(metricsdocsPath,
goFilesHeader,
metricsdocsFragment)
pkg.CheckError("creating metricsdocs generator tool", err)
// Create docs directory
err = os.Mkdir(filepath.Join(mh.ctx.Dir, "docs"), os.ModePerm)
pkg.CheckError("creating docs directory", err)
// Create monitoring directory
err = os.Mkdir(filepath.Join(mh.ctx.Dir, "docs/monitoring"), os.ModePerm)
pkg.CheckError("creating monitoring directory", err)
}
func (mh *Memcached) implementingAlerts() {
// Create alerts file
alertsPath := filepath.Join(mh.ctx.Dir, "monitoring/alerts.go")
_, err := os.Create(alertsPath)
pkg.CheckError("creating alerts file", err)
// Add go files header
err = kbutil.InsertCode(alertsPath,
"",
goFilesHeader)
pkg.CheckError("adding go files header", err)
// Add alerts implementation
err = kbutil.InsertCode(alertsPath,
goFilesHeader,
alertsFragment)
pkg.CheckError("adding alerts content", err)
}
func (mh *Memcached) implementingPromRuleCi() {
// Create prom-rule-ci directory
err := os.Mkdir(filepath.Join(mh.ctx.Dir, "monitoring/prom-rule-ci"), os.ModePerm)
pkg.CheckError("creating prom-rule-ci directory", err)
// Create prom-rules-tests file
promRuleTestsPath := filepath.Join(mh.ctx.Dir, "monitoring/prom-rule-ci/prom-rules-tests.yaml")
_, err = os.Create(promRuleTestsPath)
pkg.CheckError("creating prom-rules-tests file", err)
// Add prom-rules-tests implementation
err = kbutil.InsertCode(promRuleTestsPath,
"",
promRuleTestsFragment)
pkg.CheckError("adding prom-rules-tests content", err)
// Create rule-spec-dumper file
ruleSpecDumperPath := filepath.Join(mh.ctx.Dir, "monitoring/prom-rule-ci/rule-spec-dumper.go")
_, err = os.Create(ruleSpecDumperPath)
pkg.CheckError("creating rule-spec-dumper file", err)
// Add go files header to rule-spec-dumper
err = kbutil.InsertCode(ruleSpecDumperPath,
"",
goFilesHeader)
pkg.CheckError("adding go files header", err)
// Add rule-spec-dumper implementation
err = kbutil.InsertCode(ruleSpecDumperPath,
goFilesHeader,
ruleSpecDumperFragment)
pkg.CheckError("adding rule-spec-dumper content", err)
// Create verify-rules file
verifyRulesPath := filepath.Join(mh.ctx.Dir, "monitoring/prom-rule-ci/verify-rules.sh")
_, err = os.Create(verifyRulesPath)
pkg.CheckError("creating verify-rules file", err)
err = os.Chmod(filepath.Join(mh.ctx.Dir, "monitoring/prom-rule-ci/verify-rules.sh"), 0777)
pkg.CheckError("changing verify-rules file permissions ", err)
// Add verify-rules implementation
err = kbutil.InsertCode(verifyRulesPath,
"",
verifyRulesFragment)
pkg.CheckError("adding verify-rules content", err)
}
func (mh *Memcached) implementingRunbooks() {
runbooksPath := "docs/monitoring/runbooks/"
// Create runbooks directory
err := os.Mkdir(filepath.Join(mh.ctx.Dir, runbooksPath), os.ModePerm)
pkg.CheckError("creating runbooks directory", err)
// Create MemcachedDeploymentSizeUndesired runbook file
memcachedDeploymentSizeUndesiredRunbookPath := filepath.Join(mh.ctx.Dir, runbooksPath, "memcachedDeploymentSizeUndesired.md")
_, err = os.Create(memcachedDeploymentSizeUndesiredRunbookPath)
pkg.CheckError("creating MemcachedDeploymentSizeUndesired runbook file", err)
// Add MemcachedDeploymentSizeUndesired runbook content
err = kbutil.InsertCode(memcachedDeploymentSizeUndesiredRunbookPath,
"",
memcachedDeploymentSizeUndesiredRunbookFragment)
pkg.CheckError("adding MemcachedDeploymentSizeUndesired runbook content", err)
// Create MemcachedOperatorDown runbook file
memcachedOperatorDownRunbookPath := filepath.Join(mh.ctx.Dir, runbooksPath, "memcachedOperatorDown.md")
_, err = os.Create(memcachedOperatorDownRunbookPath)
pkg.CheckError("creating MemcachedOperatorDown runbook file", err)
// Add MemcachedOperatorDown runbook content
err = kbutil.InsertCode(memcachedOperatorDownRunbookPath,
"",
memcachedOperatorDownRunbookFragment)
pkg.CheckError("adding MemcachedDeploymentSizeUndesired runbook content", err)
}
func (mh *Memcached) implementingPrometheusRBAC() {
// Create prometheus role file
prometheusRolePath := filepath.Join(mh.ctx.Dir, "config/rbac/prometheus_role.yaml")
_, err := os.Create(prometheusRolePath)
pkg.CheckError("creating prometheus role file", err)
// Add prometheus role content
err = kbutil.InsertCode(prometheusRolePath,
"",
prometheusRoleFragment)
pkg.CheckError("adding prometheus role content", err)
// Create prometheus role binding file
prometheusRoleBindingPath := filepath.Join(mh.ctx.Dir, "config/rbac/prometheus_role_binding.yaml")
_, err = os.Create(prometheusRoleBindingPath)
pkg.CheckError("creating prometheus role binding file", err)
// Add prometheus role binding content
err = kbutil.InsertCode(prometheusRoleBindingPath,
"",
prometheusRoleBindingFragment)
pkg.CheckError("adding prometheus role binding content", err)
// Add prometheus rbac files to kustomization
kustomizationPath := filepath.Join(mh.ctx.Dir, "config/rbac/kustomization.yaml")
err = kbutil.InsertCode(kustomizationPath,
`- leader_election_role.yaml
- leader_election_role_binding.yaml`,
`
- prometheus_role.yaml
- prometheus_role_binding.yaml`)
pkg.CheckError("adding prometheus role binding content", err)
}
// customizingController will customize the Controller to include monitoring
func (mh *Memcached) customizingController() {
controllerPath := filepath.Join(mh.ctx.Dir, "controllers", fmt.Sprintf("%s_controller.go",
strings.ToLower(mh.ctx.Kind)))
// Add monitoring imports
err := kbutil.InsertCode(controllerPath,
`"os"`,
`
"reflect"`)
pkg.CheckError("adding reflect import", err)
err = kbutil.InsertCode(controllerPath,
`"sigs.k8s.io/controller-runtime/pkg/log"`,
monitoringv1ImportFragment)
pkg.CheckError("adding monitoringv1 import", err)
err = kbutil.InsertCode(controllerPath,
`cachev1alpha1 "github.com/example/memcached-operator/api/v1alpha1"`,
monitoringImportFragment)
pkg.CheckError("adding monitoring import", err)
// Add monitoring parts
err = kbutil.InsertCode(controllerPath,
`const memcachedFinalizer = "cache.example.com/finalizer"`,
`
const ruleName = "memcached-operator-rules"
const namespace = "memcached-operator-system"`)
pkg.CheckError("adding monitoring constants", err)
err = kbutil.InsertCode(controllerPath,
`//+kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch`,
`
//+kubebuilder:rbac:groups=monitoring.coreos.com,resources=prometheusrules,verbs=get;list;watch;create;update;delete`)
pkg.CheckError("adding monitoring.coreos.com rbac", err)
err = kbutil.ReplaceInFile(controllerPath,
controllerMemcachedInstanceFragment,
controllerPrometheusRuleFragment)
pkg.CheckError("adding prometheus rule reconciliation", err)
err = kbutil.InsertCode(controllerPath,
` if *found.Spec.Replicas != size {`,
`
// Increment MemcachedDeploymentSizeUndesiredCountTotal metric by 1
monitoring.MemcachedDeploymentSizeUndesiredCountTotal.Inc()`)
pkg.CheckError("adding metric incrementation", err)
}
// customizingMain will customize main.go to register metrics
func (mh *Memcached) customizingMain() {
mainPath := filepath.Join(mh.ctx.Dir, "main.go")
// Add monitoring imports
err := kbutil.InsertCode(mainPath,
`"sigs.k8s.io/controller-runtime/pkg/log/zap"`,
monitoringv1ImportFragment)
pkg.CheckError("adding monitoringv1 import", err)
err = kbutil.InsertCode(mainPath,
`"github.com/example/memcached-operator/controllers"`,
monitoringImportFragment)
pkg.CheckError("adding monitoring import", err)
// Add monitoring parts
err = kbutil.InsertCode(mainPath,
"utilruntime.Must(cachev1alpha1.AddToScheme(scheme))",
mainMonitoringFragment)
pkg.CheckError("adding monitoring parts", err)
}
// customizingDockerfile will customize the Dockerfile to include monitoring
func (mh *Memcached) customizingDockerfile() {
dockerfilePath := filepath.Join(mh.ctx.Dir, "Dockerfile")
// Copy monitoring
err := kbutil.InsertCode(dockerfilePath,
"COPY controllers/ controllers/",
"\nCOPY monitoring/ monitoring/")
pkg.CheckError("adding COPY monitoring/", err)
}
const createdAt = `createdAt: "2022-11-08T17:26:37Z"`
// customizingMakefile will customize the Makefile to include monitoring
func (mh *Memcached) customizingMakefile() {
makefilePath := filepath.Join(mh.ctx.Dir, "Makefile")
// Add prom-rule-ci target to the makefile
err := kbutil.InsertCode(makefilePath,
`$(KUSTOMIZE) build config/default | kubectl delete --ignore-not-found=$(ignore-not-found) -f -`,
makefileFragment)
pkg.CheckError("adding prom-rule-ci target to the makefile", err)
// Add metrics documentation
err = kbutil.InsertCode(makefilePath,
`$(MAKE) docker-push IMG=$(CATALOG_IMG)`,
metricsdocsMakefileFragment)
pkg.CheckError("adding metrics documentation", err)
}
const metricsFragment = `
package monitoring
import (
"github.com/prometheus/client_golang/prometheus"
"sigs.k8s.io/controller-runtime/pkg/metrics"
)
// MetricDescription is an exported struct that defines the metric description (Name, Help)
// as a new type named MetricDescription.
type MetricDescription struct {
Name string
Help string
Type string
}
// metricsDescription is a map of string keys (metrics) to MetricDescription values (Name, Help).
var metricDescription = map[string]MetricDescription{
"MemcachedDeploymentSizeUndesiredCountTotal": {
Name: "memcached_deployment_size_undesired_count_total",
Help: "Total number of times the deployment size was not as desired.",
Type: "Counter",
},
}
var (
// MemcachedDeploymentSizeUndesiredCountTotal will count how many times was required
// to perform the operation to ensure that the number of replicas on the cluster
// is the same as the quantity desired and specified via the custom resource size spec.
MemcachedDeploymentSizeUndesiredCountTotal = prometheus.NewCounter(
prometheus.CounterOpts{
Name: metricDescription["MemcachedDeploymentSizeUndesiredCountTotal"].Name,
Help: metricDescription["MemcachedDeploymentSizeUndesiredCountTotal"].Help,
},
)
)
// RegisterMetrics will register metrics with the global prometheus registry
func RegisterMetrics() {
metrics.Registry.MustRegister(MemcachedDeploymentSizeUndesiredCountTotal)
}
// ListMetrics will create a slice with the metrics available in metricDescription
func ListMetrics() []MetricDescription {
v := make([]MetricDescription, 0, len(metricDescription))
// Insert value (Name, Help) for each metric
for _, value := range metricDescription {
v = append(v, value)
}
return v
}
`
const metricsdocsFragment = `
package main
import (
"fmt"
"sort"
"github.com/example/memcached-operator/monitoring"
)
// please run "make generate-metricsdocs" to run this tool and update metrics documentation
const (
title = "# Operator Metrics\n"
background = "This document aims to help users that are not familiar with metrics exposed by this operator.\n" +
"The metrics documentation is auto-generated by the utility tool \"monitoring/metricsdocs\" and reflects all of the metrics that are exposed by the operator.\n\n"
KVSpecificMetrics = "## Operator Metrics List\n"
opening = title +
background +
KVSpecificMetrics
// footer
footerHeading = "## Developing new metrics\n"
footerContent = "After developing new metrics or changing old ones, please run \"make generate-metricsdocs\" to regenerate this document.\n\n" +
"If you feel that the new metric doesn't follow these rules, please change \"monitoring/metricsdocs\" according to your needs.\n"
footer = footerHeading + footerContent
)
// TODO: scaffolding these helpers with operator-lib: https://github.com/operator-framework/operator-lib.
// metricList contains the name, description, and type for each metric.
func main() {
metricList := metricDescriptionListToMetricList(monitoring.ListMetrics())
sort.Sort(metricList)
writeToStdOut(metricList)
}
// writeToStdOut receives a list of metrics and prints them to STDOUT.
func writeToStdOut(metricsList metricList) {
fmt.Print(opening)
metricsList.writeOut()
fmt.Print(footer)
}
// Metric is an exported struct that defines the metric
// name, description, and type as a new type named Metric.
type Metric struct {
name string
description string
metricType string
}
func metricDescriptionToMetric(md monitoring.MetricDescription) Metric {
return Metric{
name: md.Name,
description: md.Help,
metricType: md.Type,
}
}
// writeOut receives a metric of type metric and prints
// the metric name, description, and type.
func (m Metric) writeOut() {
fmt.Println("###", m.name)
fmt.Println(m.description, "Type: "+m.metricType+".")
}
// metricList is an array that contain metrics from type metric,
// as a new type named metricList.
type metricList []Metric
// metricDescriptionListToMetricList collects the metrics exposed by the
// operator, and inserts them into the metricList array.
func metricDescriptionListToMetricList(mdl []monitoring.MetricDescription) metricList {
res := make([]Metric, len(mdl))
for i, md := range mdl {
res[i] = metricDescriptionToMetric(md)
}
return res
}
// Len implements sort.Interface.Len
func (m metricList) Len() int {
return len(m)
}
// Less implements sort.Interface.Less
func (m metricList) Less(i, j int) bool {
return m[i].name < m[j].name
}
// Swap implements sort.Interface.Swap
func (m metricList) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
func (m metricList) writeOut() {
for _, met := range m {
met.writeOut()
}
}
`
const alertsFragment = `
package monitoring
import (
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
)
const (
ruleName = "memcached-operator-rules"
alertRuleGroup = "memcached.rules"
deploymentSizeUndesiredAlert = "MemcachedDeploymentSizeUndesired"
operatorDownAlert = "MemcachedOperatorDown"
operatorUpTotalRecordingRule = "memcached_operator_up_total"
runbookURLBasePath = "https://github.com/operator-framework/operator-sdk/tree/master/testdata/go/v4-alpha/monitoring/memcached-operator/docs/monitoring/runbooks/"
)