-
Notifications
You must be signed in to change notification settings - Fork 19
/
pod.go
74 lines (61 loc) · 2.32 KB
/
pod.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package sidecar contains operations related to sidecar manipulation (Add, update, remove).
package sidecar
import (
"fmt"
"github.com/go-logr/logr"
corev1 "k8s.io/api/core/v1"
"github.com/aws/amazon-cloudwatch-agent-operator/apis/v1alpha1"
"github.com/aws/amazon-cloudwatch-agent-operator/internal/config"
"github.com/aws/amazon-cloudwatch-agent-operator/internal/manifests/collector"
"github.com/aws/amazon-cloudwatch-agent-operator/internal/naming"
)
const (
injectedLabel = "sidecar.opentelemetry.io/injected"
confEnvVar = "OTEL_CONFIG"
)
// add a new sidecar container to the given pod, based on the given AmazonCloudWatchAgent.
func add(cfg config.Config, logger logr.Logger, otelcol v1alpha1.AmazonCloudWatchAgent, pod corev1.Pod, attributes []corev1.EnvVar) (corev1.Pod, error) {
otelColCfg, err := collector.ReplaceConfig(otelcol)
if err != nil {
return pod, err
}
container := collector.Container(cfg, logger, otelcol, false)
container.Args = append(container.Args, fmt.Sprintf("--config=env:%s", confEnvVar))
container.Env = append(container.Env, corev1.EnvVar{Name: confEnvVar, Value: otelColCfg})
if !hasResourceAttributeEnvVar(container.Env) {
container.Env = append(container.Env, attributes...)
}
pod.Spec.InitContainers = append(pod.Spec.InitContainers, otelcol.Spec.InitContainers...)
pod.Spec.Containers = append(pod.Spec.Containers, container)
pod.Spec.Volumes = append(pod.Spec.Volumes, otelcol.Spec.Volumes...)
if pod.Labels == nil {
pod.Labels = map[string]string{}
}
pod.Labels[injectedLabel] = naming.Truncate("%s.%s", 63, otelcol.Namespace, otelcol.Name)
return pod, nil
}
// remove the sidecar container from the given pod.
func remove(pod corev1.Pod) (corev1.Pod, error) {
if !existsIn(pod) {
return pod, nil
}
var containers []corev1.Container
for _, container := range pod.Spec.Containers {
if container.Name != naming.Container() {
containers = append(containers, container)
}
}
pod.Spec.Containers = containers
return pod, nil
}
// existsIn checks whether a sidecar container exists in the given pod.
func existsIn(pod corev1.Pod) bool {
for _, container := range pod.Spec.Containers {
if container.Name == naming.Container() {
return true
}
}
return false
}