-
Notifications
You must be signed in to change notification settings - Fork 24
/
utils.go
815 lines (709 loc) · 23 KB
/
utils.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
/*
Copyright 2022.
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 controllers
import (
"bytes"
"context"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"time"
cryptorand "crypto/rand"
agentv1alpha1 "github.com/fluxninja/aperture/operator/api/agent/v1alpha1"
"github.com/fluxninja/aperture/operator/api/common"
controllerv1alpha1 "github.com/fluxninja/aperture/operator/api/controller/v1alpha1"
"github.com/imdario/mergo"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// ContainerSecurityContext prepares SecurityContext for containers based on the provided parameter.
func ContainerSecurityContext(containerSecurityContext common.ContainerSecurityContext) *corev1.SecurityContext {
var securityContext *corev1.SecurityContext
if containerSecurityContext.Enabled {
securityContext = &corev1.SecurityContext{
RunAsUser: pointer.Int64(containerSecurityContext.RunAsUser),
RunAsNonRoot: pointer.Bool(containerSecurityContext.RunAsNonRootUser),
ReadOnlyRootFilesystem: pointer.Bool(containerSecurityContext.ReadOnlyRootFilesystem),
}
} else {
securityContext = &corev1.SecurityContext{}
}
return securityContext
}
// PodSecurityContext prepares SecurityContext for Pods based on the provided parameter.
func PodSecurityContext(podSecurityContext common.PodSecurityContext) *corev1.PodSecurityContext {
var securityContext *corev1.PodSecurityContext
if podSecurityContext.Enabled {
securityContext = &corev1.PodSecurityContext{
FSGroup: pointer.Int64(podSecurityContext.FsGroup),
}
} else {
securityContext = &corev1.PodSecurityContext{}
}
return securityContext
}
// ImageString prepares image string from the provided Image struct.
func ImageString(image common.Image, repository string) string {
var imageStr string
if image.Registry != "" {
imageStr = fmt.Sprintf("%s/%s:%s", image.Registry, repository, image.Tag)
} else {
imageStr = fmt.Sprintf("%s:%s", repository, image.Tag)
}
return imageStr
}
// ImagePullSecrets prepares ImagePullSecrets string slice from the provided Image struct.
func ImagePullSecrets(image common.Image) []corev1.LocalObjectReference {
imagePullSecrets := []corev1.LocalObjectReference{}
for _, secret := range image.PullSecrets {
imagePullSecrets = append(imagePullSecrets, corev1.LocalObjectReference{
Name: secret,
})
}
return imagePullSecrets
}
// ContainerEnvFrom prepares EnvFrom resource for Agent and Controllers' container.
func ContainerEnvFrom(controllerSpec common.CommonSpec) []corev1.EnvFromSource {
envFrom := []corev1.EnvFromSource{}
if controllerSpec.ExtraEnvVarsCM != "" {
envFrom = append(envFrom, corev1.EnvFromSource{
ConfigMapRef: &corev1.ConfigMapEnvSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: controllerSpec.ExtraEnvVarsCM,
},
},
})
}
if controllerSpec.ExtraEnvVarsSecret != "" {
envFrom = append(envFrom, corev1.EnvFromSource{
SecretRef: &corev1.SecretEnvSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: controllerSpec.ExtraEnvVarsSecret,
},
},
})
}
return envFrom
}
// ContainerProbes prepares livenessProbe and readinessProbe based on the provided parameters.
func ContainerProbes(spec common.CommonSpec, scheme corev1.URIScheme) (*corev1.Probe, *corev1.Probe) {
var livenessProbe *corev1.Probe
var readinessProbe *corev1.Probe
if spec.LivenessProbe.Enabled {
livenessProbe = &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: "/v1/status/liveness",
Port: intstr.FromString(Server),
Scheme: scheme,
},
},
InitialDelaySeconds: spec.LivenessProbe.InitialDelaySeconds,
TimeoutSeconds: spec.LivenessProbe.TimeoutSeconds,
PeriodSeconds: spec.LivenessProbe.PeriodSeconds,
FailureThreshold: spec.LivenessProbe.FailureThreshold,
SuccessThreshold: spec.LivenessProbe.SuccessThreshold,
}
} else if spec.CustomLivenessProbe != nil {
livenessProbe = spec.CustomLivenessProbe
}
if spec.ReadinessProbe.Enabled {
readinessProbe = &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: "/v1/status/readiness",
Port: intstr.FromString(Server),
Scheme: scheme,
},
},
InitialDelaySeconds: spec.ReadinessProbe.InitialDelaySeconds,
TimeoutSeconds: spec.ReadinessProbe.TimeoutSeconds,
PeriodSeconds: spec.ReadinessProbe.PeriodSeconds,
FailureThreshold: spec.ReadinessProbe.FailureThreshold,
SuccessThreshold: spec.ReadinessProbe.SuccessThreshold,
}
} else if spec.CustomReadinessProbe != nil {
readinessProbe = spec.CustomReadinessProbe
}
return livenessProbe, readinessProbe
}
// AgentEnv prepares env resources for Agents' container.
func AgentEnv(instance *agentv1alpha1.Agent, agentGroup string) []corev1.EnvVar {
spec := instance.Spec
envs := []corev1.EnvVar{
{
Name: "NODE_NAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
APIVersion: V1Version,
FieldPath: "spec.nodeName",
},
},
},
}
if agentGroup == "" && spec.ConfigSpec.AgentInfo.AgentGroup != "" {
agentGroup = spec.ConfigSpec.AgentInfo.AgentGroup
}
if agentGroup != "" {
envs = append(envs, corev1.EnvVar{
Name: "APERTURE_AGENT_AGENT_INFO_AGENT_GROUP",
Value: agentGroup,
})
}
if spec.Sidecar.Enabled {
envs = append(envs, corev1.EnvVar{
Name: "APERTURE_AGENT_SERVICE_DISCOVERY_KUBERNETES_POD_NAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
APIVersion: V1Version,
FieldPath: "metadata.name",
},
},
})
envs = append(envs, corev1.EnvVar{
Name: "APERTURE_AGENT_SERVICE_DISCOVERY_KUBERNETES_DISCOVERY_ENABLED",
Value: "false",
})
} else {
envs = append(envs, corev1.EnvVar{
Name: "APERTURE_AGENT_SERVICE_DISCOVERY_KUBERNETES_NODE_NAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
APIVersion: V1Version,
FieldPath: "spec.nodeName",
},
},
})
envs = append(envs, corev1.EnvVar{
Name: "APERTURE_AGENT_SERVICE_DISCOVERY_KUBERNETES_DISCOVERY_ENABLED",
Value: "true",
})
}
if instance.Spec.Secrets.FluxNinjaPlugin.Create || instance.Spec.Secrets.FluxNinjaPlugin.SecretKeyRef.Name != "" {
envs = append(envs, corev1.EnvVar{
Name: "APERTURE_AGENT_FLUXNINJA_PLUGIN_API_KEY",
ValueFrom: &corev1.EnvVarSource{
SecretKeyRef: &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{
Name: SecretName(instance.GetName(), "agent", &instance.Spec.Secrets.FluxNinjaPlugin),
},
Key: SecretDataKey(&instance.Spec.Secrets.FluxNinjaPlugin.SecretKeyRef),
Optional: pointer.Bool(false),
},
},
})
}
return MergeEnvVars(envs, spec.ExtraEnvVars)
}
// AgentVolumeMounts prepares volumeMounts for Agents' container.
func AgentVolumeMounts(agentSpec agentv1alpha1.AgentSpec) []corev1.VolumeMount {
volumeMounts := []corev1.VolumeMount{
{
Name: "aperture-agent-config",
MountPath: "/etc/aperture/aperture-agent/config",
},
}
return MergeVolumeMounts(volumeMounts, agentSpec.ExtraVolumeMounts)
}
// AgentVolumes prepares volumes for Agent.
func AgentVolumes(agentSpec agentv1alpha1.AgentSpec) []corev1.Volume {
volumes := []corev1.Volume{
{
Name: "aperture-agent-config",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
DefaultMode: pointer.Int32(420),
LocalObjectReference: corev1.LocalObjectReference{
Name: AgentServiceName,
},
},
},
},
}
return MergeVolumes(volumes, agentSpec.ExtraVolumes)
}
// ControllerEnv prepares env resources for Controller' container.
func ControllerEnv(instance *controllerv1alpha1.Controller) []corev1.EnvVar {
spec := instance.Spec
envs := []corev1.EnvVar{
{
Name: "APERTURE_CONTROLLER_SERVICE_DISCOVERY_KUBERNETES_NODE_NAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{
APIVersion: V1Version,
FieldPath: "spec.nodeName",
},
},
},
{
Name: "APERTURE_CONTROLLER_NAMESPACE",
Value: instance.GetNamespace(),
},
}
if spec.Secrets.FluxNinjaPlugin.Create || instance.Spec.Secrets.FluxNinjaPlugin.SecretKeyRef.Name != "" {
envs = append(envs, corev1.EnvVar{
Name: "APERTURE_CONTROLLER_FLUXNINJA_PLUGIN_API_KEY",
ValueFrom: &corev1.EnvVarSource{
SecretKeyRef: &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{
Name: SecretName(instance.GetName(), "controller", &instance.Spec.Secrets.FluxNinjaPlugin),
},
Key: SecretDataKey(&instance.Spec.Secrets.FluxNinjaPlugin.SecretKeyRef),
Optional: pointer.Bool(false),
},
},
})
}
return MergeEnvVars(envs, spec.ExtraEnvVars)
}
// ControllerVolumeMounts prepares volumeMounts for Controllers' container.
func ControllerVolumeMounts(controllerSpec common.CommonSpec) []corev1.VolumeMount {
volumeMounts := []corev1.VolumeMount{
{
Name: "aperture-controller-config",
MountPath: "/etc/aperture/aperture-controller/config",
},
{
Name: "etc-aperture-policies",
MountPath: PolicyFilePath,
ReadOnly: true,
},
{
Name: "etc-aperture-classification",
MountPath: "/etc/aperture/aperture-controller/classifiers",
ReadOnly: true,
},
{
Name: "server-cert",
MountPath: "/etc/aperture/aperture-controller/certs",
ReadOnly: true,
},
}
return MergeVolumeMounts(volumeMounts, controllerSpec.ExtraVolumeMounts)
}
// ControllerVolumes prepares volumes for Controller.
func ControllerVolumes(instance *controllerv1alpha1.Controller) []corev1.Volume {
volumes := []corev1.Volume{
{
Name: "aperture-controller-config",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
DefaultMode: pointer.Int32(420),
LocalObjectReference: corev1.LocalObjectReference{
Name: ControllerServiceName,
},
},
},
},
{
Name: "etc-aperture-policies",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
},
{
Name: "etc-aperture-classification",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
DefaultMode: pointer.Int32(420),
LocalObjectReference: corev1.LocalObjectReference{
Name: "classification",
},
Optional: pointer.Bool(true),
},
},
},
{
Name: "server-cert",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
DefaultMode: pointer.Int32(420),
SecretName: fmt.Sprintf("%s-controller-cert", instance.GetName()),
},
},
},
}
return MergeVolumes(volumes, instance.Spec.ExtraVolumes)
}
// CommonLabels prepares common labels used by all resources.
func CommonLabels(commonLabels map[string]string, instanceName, component string) map[string]string {
labels := map[string]string{
"app.kubernetes.io/name": AppName,
"app.kubernetes.io/instance": instanceName,
"app.kubernetes.io/managed-by": OperatorName,
"app.kubernetes.io/component": component,
}
if commonLabels != nil {
if err := mergo.Map(&labels, commonLabels, mergo.WithOverride); err != nil {
return labels
}
}
return labels
}
// SelectorLabels prepares the labels used for Selector.
func SelectorLabels(instance, component string) map[string]string {
return map[string]string{
"app.kubernetes.io/name": AppName,
"app.kubernetes.io/instance": instance,
"app.kubernetes.io/managed-by": OperatorName,
"app.kubernetes.io/component": component,
}
}
// ControllerAnnotationsWithOwnerRef prepares the map for Annotation with reference to the creator instance.
func ControllerAnnotationsWithOwnerRef(instance *controllerv1alpha1.Controller) map[string]string {
annotations := instance.Spec.Annotations
if annotations == nil {
annotations = map[string]string{}
}
annotations["fluxninja.com/primary-resource"] = fmt.Sprintf("%s/%s", instance.GetNamespace(), instance.GetName())
annotations["fluxninja.com/primary-resource-type"] = fmt.Sprintf("%s.%s",
instance.GetObjectKind().GroupVersionKind().GroupKind().Kind, instance.GetObjectKind().GroupVersionKind().GroupKind().Group)
return annotations
}
// AgentAnnotationsWithOwnerRef prepares the map for Annotation with reference to the creator instance.
func AgentAnnotationsWithOwnerRef(instance *agentv1alpha1.Agent) map[string]string {
annotations := instance.Spec.Annotations
if annotations == nil {
annotations = map[string]string{}
}
annotations["fluxninja.com/primary-resource"] = fmt.Sprintf("%s/%s", instance.GetNamespace(), instance.GetName())
annotations["fluxninja.com/primary-resource-type"] = fmt.Sprintf("%s.%s",
instance.GetObjectKind().GroupVersionKind().GroupKind().Kind, instance.GetObjectKind().GroupVersionKind().GroupKind().Group)
return annotations
}
// SecretName fetches name for ApiKey secret from config or generates the name if not present in config.
func SecretName(instance, component string, spec *common.APIKeySecret) string {
name := spec.SecretKeyRef.Name
if name != "" {
return name
}
return fmt.Sprintf("%s-%s-apikey", instance, component)
}
// SecretDataKey fetches Key for ApiKey secret from config or generates the Key if not present in config.
func SecretDataKey(spec *common.SecretKeyRef) string {
key := spec.Key
if key != "" {
return key
}
return SecretKey
}
// CheckCertificate checks if existing certificates are available.
func CheckCertificate() bool {
certDir := strings.TrimRight(os.Getenv("APERTURE_OPERATOR_CERT_DIR"), "/")
if certDir == "" {
certDir = filepath.Join(os.TempDir(), "k8s-webhook-server", "serving-certs")
os.Setenv("APERTURE_OPERATOR_CERT_DIR", certDir)
}
certName := os.Getenv("APERTURE_OPERATOR_CERT_NAME")
if certName == "" {
certName = "tls.crt"
os.Setenv("APERTURE_OPERATOR_CERT_NAME", certName)
}
keyName := os.Getenv("APERTURE_OPERATOR_KEY_NAME")
if keyName == "" {
keyName = "tls.key"
os.Setenv("APERTURE_OPERATOR_KEY_NAME", keyName)
}
_, err := tls.LoadX509KeyPair(fmt.Sprintf("%s/%s", os.Getenv("APERTURE_OPERATOR_CERT_DIR"), os.Getenv("APERTURE_OPERATOR_CERT_NAME")),
fmt.Sprintf("%s/%s", os.Getenv("APERTURE_OPERATOR_CERT_DIR"), os.Getenv("APERTURE_OPERATOR_KEY_NAME")))
return err == nil
}
// GenerateCertificate generates certificate and stores it in the desired location.
func GenerateCertificate(dnsPrefix, namespace string) (*bytes.Buffer, *bytes.Buffer, *bytes.Buffer, error) {
var caPEM, serverCertPEM, serverPrivKeyPEM *bytes.Buffer
ca := &x509.Certificate{
SerialNumber: big.NewInt(2022),
Subject: pkix.Name{
Organization: []string{"fluxninja.com"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),
IsCA: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}
// CA private key
caPrivKey, err := rsa.GenerateKey(cryptorand.Reader, 4096)
if err != nil {
return nil, nil, nil, err
}
// Self signed CA certificate
caBytes, err := x509.CreateCertificate(cryptorand.Reader, ca, ca, &caPrivKey.PublicKey, caPrivKey)
if err != nil {
return nil, nil, nil, err
}
// PEM encode CA cert
caPEM = new(bytes.Buffer)
_ = pem.Encode(caPEM, &pem.Block{
Type: "CERTIFICATE",
Bytes: caBytes,
})
dnsNames := []string{
dnsPrefix,
fmt.Sprintf("%s.%s", dnsPrefix, namespace),
fmt.Sprintf("%s.%s.svc", dnsPrefix, namespace),
fmt.Sprintf("%s.%s.svc.cluster.local", dnsPrefix, namespace),
}
commonName := fmt.Sprintf("%s.%s.svc", dnsPrefix, namespace)
// server cert config
cert := &x509.Certificate{
DNSNames: dnsNames,
SerialNumber: big.NewInt(1658),
Subject: pkix.Name{
CommonName: commonName,
Organization: []string{"fluxninja.com"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),
SubjectKeyId: []byte{1, 2, 3, 4, 6},
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature,
}
// server private key
serverPrivKey, err := rsa.GenerateKey(cryptorand.Reader, 4096)
if err != nil {
return nil, nil, nil, err
}
// sign the server cert
serverCertBytes, err := x509.CreateCertificate(cryptorand.Reader, cert, ca, &serverPrivKey.PublicKey, caPrivKey)
if err != nil {
return nil, nil, nil, err
}
// PEM encode the server cert and key
serverCertPEM = new(bytes.Buffer)
_ = pem.Encode(serverCertPEM, &pem.Block{
Type: "CERTIFICATE",
Bytes: serverCertBytes,
})
serverPrivKeyPEM = new(bytes.Buffer)
_ = pem.Encode(serverPrivKeyPEM, &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(serverPrivKey),
})
return serverCertPEM, serverPrivKeyPEM, caPEM, nil
}
// WriteFile writes data in the file at the given path.
func WriteFile(filepath string, sCert *bytes.Buffer) error {
f, err := os.Create(filepath)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write(sCert.Bytes())
if err != nil {
return err
}
return nil
}
// CheckAndGenerateCertForOperator checks if existing certificates are present and creates new if not present.
func CheckAndGenerateCertForOperator() error {
if CheckCertificate() {
return nil
}
namespace := os.Getenv("APERTURE_OPERATOR_NAMESPACE")
if namespace == "" {
namespace = "default"
}
serviceName := os.Getenv("APERTURE_OPERATOR_SERVICE_NAME")
if serviceName == "" {
return fmt.Errorf("the value for environment variable 'APERTURE_OPERATOR_SERVICE_NAME' is not configured")
}
serverCertPEM, serverPrivKeyPEM, caPEM, err := GenerateCertificate(serviceName, namespace)
if err != nil {
return err
}
err = os.MkdirAll(os.Getenv("APERTURE_OPERATOR_CERT_DIR"), 0o777)
if err != nil {
return err
}
err = WriteFile(fmt.Sprintf("%s/%s", os.Getenv("APERTURE_OPERATOR_CERT_DIR"), os.Getenv("APERTURE_OPERATOR_CERT_NAME")), serverCertPEM)
if err != nil {
return err
}
err = WriteFile(fmt.Sprintf("%s/%s", os.Getenv("APERTURE_OPERATOR_CERT_DIR"), os.Getenv("APERTURE_OPERATOR_KEY_NAME")), serverPrivKeyPEM)
if err != nil {
return err
}
err = WriteFile(fmt.Sprintf("%s/%s", os.Getenv("APERTURE_OPERATOR_CERT_DIR"), WebhookClientCertName), caPEM)
if err != nil {
return err
}
return nil
}
// MergeEnvVars merges common and provided extra Environment variables of Kubernetes container.
func MergeEnvVars(common, extra []corev1.EnvVar) []corev1.EnvVar {
if extra == nil {
return common
}
keys := map[string]bool{}
for _, env := range extra {
keys[env.Name] = true
}
for _, env := range common {
if _, ok := keys[env.Name]; !ok {
extra = append(extra, env)
keys[env.Name] = true
}
}
return extra
}
// MergeEnvFromSources merges common and provided extra Environment From of Kubernetes container.
func MergeEnvFromSources(common, extra []corev1.EnvFromSource) []corev1.EnvFromSource {
if extra == nil {
return common
}
keys := map[string]bool{}
for _, env := range extra {
if env.ConfigMapRef != nil {
keys[fmt.Sprintf("configmap_%s", env.ConfigMapRef.LocalObjectReference.Name)] = true
}
if env.SecretRef != nil {
keys[fmt.Sprintf("secret_%s", env.SecretRef.LocalObjectReference.Name)] = true
}
}
for _, env := range common {
envFrom := corev1.EnvFromSource{}
if env.ConfigMapRef != nil {
if _, ok := keys[fmt.Sprintf("configmap_%s", env.ConfigMapRef.LocalObjectReference.Name)]; !ok {
envFrom.ConfigMapRef = env.ConfigMapRef
keys[fmt.Sprintf("configmap_%s", env.ConfigMapRef.LocalObjectReference.Name)] = true
}
}
if env.SecretRef != nil {
if _, ok := keys[fmt.Sprintf("secret_%s", env.SecretRef.LocalObjectReference.Name)]; !ok {
envFrom.SecretRef = env.SecretRef
keys[fmt.Sprintf("secret_%s", env.SecretRef.LocalObjectReference.Name)] = true
}
}
if envFrom.ConfigMapRef != nil || envFrom.SecretRef != nil {
extra = append(extra, envFrom)
}
}
return extra
}
// MergeVolumeMounts merges common and provided extra Volume mounts of Kubernetes container.
func MergeVolumeMounts(common, extra []corev1.VolumeMount) []corev1.VolumeMount {
if extra == nil {
return common
}
keys := map[string]bool{}
for _, env := range extra {
keys[env.Name] = true
}
for _, env := range common {
if _, ok := keys[env.Name]; !ok {
extra = append(extra, env)
keys[env.Name] = true
}
}
return extra
}
// MergeVolumes merges common and provided extra Volume of Kubernetes Pod.
func MergeVolumes(common, extra []corev1.Volume) []corev1.Volume {
if extra == nil {
return common
}
keys := map[string]bool{}
for _, env := range extra {
keys[env.Name] = true
}
for _, env := range common {
if _, ok := keys[env.Name]; !ok {
extra = append(extra, env)
keys[env.Name] = true
}
}
return extra
}
// MergeContainers merges common and provided Container/Init Container of Kubernetes container.
func MergeContainers(common, extra []corev1.Container) []corev1.Container {
if extra == nil {
return common
}
keys := map[string]bool{}
for _, env := range extra {
keys[env.Name] = true
}
for _, env := range common {
if _, ok := keys[env.Name]; !ok {
extra = append(extra, env)
keys[env.Name] = true
}
}
return extra
}
// MergeImagePullSecrets merges common and provided Image Pull Secrets of Kubernetes.
func MergeImagePullSecrets(common, extra []corev1.LocalObjectReference) []corev1.LocalObjectReference {
if extra == nil {
return common
}
keys := map[string]bool{}
for _, env := range extra {
keys[env.Name] = true
}
for _, env := range common {
if _, ok := keys[env.Name]; !ok {
extra = append(extra, env)
keys[env.Name] = true
}
}
return extra
}
// UpdateResource updates the Aperture resource in Kubernetes.
func UpdateResource(client client.Client, ctx context.Context, instance client.Object) error {
attempt := 5
for attempt > 0 {
attempt -= 1
if err := client.Update(ctx, instance); err != nil {
if errors.IsConflict(err) {
namespacesName := types.NamespacedName{
Namespace: instance.GetNamespace(),
Name: instance.GetName(),
}
if err = client.Get(ctx, namespacesName, instance); err != nil {
return err
}
continue
}
return err
}
}
return nil
}
// GetPort parses port value from the Address string.
func GetPort(addr string) (int32, error) {
_, portStr, err := net.SplitHostPort(addr)
if err != nil {
return 0, err
}
// read 32 bit integer from string
port, err := strconv.ParseInt(portStr, 10, 32)
if err != nil {
return 0, err
}
return int32(port), nil
}