-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
kubernetes.go
215 lines (171 loc) · 5.9 KB
/
kubernetes.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
package kubernetes
import (
"context"
"fmt"
"github.com/sirupsen/logrus"
"github.com/spf13/viper"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"github.com/ckotzbauer/sbom-operator/internal"
)
type ContainerImage struct {
Image string
ImageID string
Auth []byte
LegacyAuth bool
Pods []corev1.Pod
}
type KubeClient struct {
Client *kubernetes.Clientset
ignoreAnnotations bool
}
var (
annotationTemplate = "ckotzbauer.sbom-operator.io/%s"
)
func NewClient() *KubeClient {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{})
config, err := kubeConfig.ClientConfig()
if err != nil {
logrus.WithError(err).Fatal("kubeconfig file could not be found!")
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
logrus.WithError(err).Fatal("Could not create Kubernetes client from config!")
}
return &KubeClient{Client: client, ignoreAnnotations: viper.GetBool(internal.ConfigKeyIgnoreAnnotations)}
}
func prepareLabelSelector(selector string) meta.ListOptions {
listOptions := meta.ListOptions{}
if len(selector) > 0 {
listOptions.LabelSelector = internal.Unescape(selector)
logrus.Tracef("Applied labelSelector %v", listOptions.LabelSelector)
}
return listOptions
}
func (client *KubeClient) ListNamespaces(labelSelector string) []corev1.Namespace {
list, err := client.Client.CoreV1().Namespaces().List(context.Background(), prepareLabelSelector(labelSelector))
if err != nil {
logrus.WithError(err).Error("ListNamespaces errored!")
return []corev1.Namespace{}
}
return list.Items
}
func (client *KubeClient) listPods(namespace, labelSelector string) []corev1.Pod {
list, err := client.Client.CoreV1().Pods(namespace).List(context.Background(), prepareLabelSelector(labelSelector))
if err != nil {
logrus.WithError(err).Error("ListPods errored!")
return []corev1.Pod{}
}
return list.Items
}
func (client *KubeClient) LoadImageInfos(namespaces []corev1.Namespace, podLabelSelector string) (map[string]ContainerImage, []ContainerImage) {
images := map[string]ContainerImage{}
allImages := []ContainerImage{}
for _, ns := range namespaces {
pods := client.listPods(ns.Name, podLabelSelector)
for _, pod := range pods {
annotations := pod.Annotations
statuses := []corev1.ContainerStatus{}
statuses = append(statuses, pod.Status.ContainerStatuses...)
statuses = append(statuses, pod.Status.InitContainerStatuses...)
statuses = append(statuses, pod.Status.EphemeralContainerStatuses...)
pullSecrets, legacy, err := client.loadSecrets(pod.Namespace, pod.Spec.ImagePullSecrets)
if err != nil {
logrus.WithError(err).Errorf("PullSecrets could not be retrieved for pod %s/%s", ns.Name, pod.Name)
continue
}
for _, c := range statuses {
if c.ImageID != "" {
if !client.hasAnnotation(annotations, c) {
img, ok := images[c.ImageID]
if !ok {
img = ContainerImage{
Image: c.Image,
ImageID: c.ImageID,
Auth: pullSecrets,
LegacyAuth: legacy,
Pods: []corev1.Pod{},
}
}
img.Pods = append(img.Pods, pod)
images[c.ImageID] = img
allImages = append(allImages, img)
} else {
logrus.Debugf("Skip image %s", c.ImageID)
allImages = append(allImages, ContainerImage{
Image: c.Image,
ImageID: c.ImageID,
Auth: pullSecrets,
LegacyAuth: legacy,
Pods: []corev1.Pod{},
})
}
}
}
}
}
return images, allImages
}
func (client *KubeClient) UpdatePodAnnotation(pod corev1.Pod) {
newPod, err := client.Client.CoreV1().Pods(pod.Namespace).Get(context.Background(), pod.Name, meta.GetOptions{})
if err != nil {
if !errors.IsNotFound(err) {
logrus.WithError(err).Errorf("Pod %s/%s could not be fetched!", pod.Namespace, pod.Name)
}
return
}
ann := newPod.Annotations
if ann == nil {
ann = make(map[string]string)
}
for _, c := range pod.Status.ContainerStatuses {
ann[fmt.Sprintf(annotationTemplate, c.Name)] = c.ImageID
}
for _, c := range pod.Status.InitContainerStatuses {
ann[fmt.Sprintf(annotationTemplate, c.Name)] = c.ImageID
}
for _, c := range pod.Status.EphemeralContainerStatuses {
ann[fmt.Sprintf(annotationTemplate, c.Name)] = c.ImageID
}
newPod.Annotations = ann
_, err = client.Client.CoreV1().Pods(newPod.Namespace).Update(context.Background(), newPod, meta.UpdateOptions{})
if err != nil {
logrus.WithError(err).Errorf("Pod %s/%s could not be updated!", pod.Namespace, pod.Name)
}
}
func (client *KubeClient) hasAnnotation(annotations map[string]string, status corev1.ContainerStatus) bool {
if annotations == nil || client.ignoreAnnotations {
return false
}
if val, ok := annotations[fmt.Sprintf(annotationTemplate, status.Name)]; ok {
return val == status.ImageID
}
return false
}
func (client *KubeClient) loadSecrets(namespace string, secrets []corev1.LocalObjectReference) ([]byte, bool, error) {
// TODO: Support all secrets which are referenced as imagePullSecrets instead of only the first one.
for _, s := range secrets {
secret, err := client.Client.CoreV1().Secrets(namespace).Get(context.Background(), s.Name, meta.GetOptions{})
if err != nil {
return nil, false, err
}
var creds []byte
legacy := false
if secret.Type == corev1.SecretTypeDockerConfigJson {
creds = secret.Data[corev1.DockerConfigJsonKey]
} else if secret.Type == corev1.SecretTypeDockercfg {
creds = secret.Data[corev1.DockerConfigKey]
legacy = true
} else {
return nil, false, fmt.Errorf("invalid secret-type %s for pullSecret %s/%s", secret.Type, secret.Namespace, secret.Name)
}
if len(creds) > 0 {
return creds, legacy, nil
}
}
return nil, false, nil
}