-
Notifications
You must be signed in to change notification settings - Fork 239
/
configmap_writer.go
277 lines (245 loc) · 8.55 KB
/
configmap_writer.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
package configmap
import (
"context"
"fmt"
"os"
"regexp"
"github.com/sirupsen/logrus"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"sigs.k8s.io/yaml"
"github.com/operator-framework/operator-registry/pkg/client"
"github.com/operator-framework/operator-registry/pkg/lib/bundle"
"github.com/operator-framework/operator-registry/pkg/lib/encoding"
)
// configmap keys can contain underscores, but configmap names can not
var unallowedKeyChars = regexp.MustCompile("[^-A-Za-z0-9_.]")
const (
EnvContainerImage = "CONTAINER_IMAGE"
ConfigMapImageAnnotationKey = "olm.sourceImage"
ConfigMapEncodingAnnotationKey = "olm.contentEncoding"
ConfigMapEncodingAnnotationGzip = "gzip+base64"
)
type AnnotationsFile struct {
Annotations struct {
Resources string `json:"operators.operatorframework.io.bundle.manifests.v1"`
MediaType string `json:"operators.operatorframework.io.bundle.mediatype.v1"`
Metadata string `json:"operators.operatorframework.io.bundle.metadata.v1"`
Package string `json:"operators.operatorframework.io.bundle.package.v1"`
Channels string `json:"operators.operatorframework.io.bundle.channels.v1"`
ChannelDefault string `json:"operators.operatorframework.io.bundle.channel.default.v1"`
} `json:"annotations"`
}
type ConfigMapWriter struct {
clientset kubernetes.Interface
manifestsDir string
configMapName string
namespace string
gzip bool
}
func NewConfigMapLoader(configMapName, namespace, manifestsDir string, gzip bool, kubeconfig string) *ConfigMapWriter {
clientset, err := client.NewKubeClient(kubeconfig, logrus.StandardLogger())
if err != nil {
logrus.Fatalf("cluster config failed: %v", err)
}
return NewConfigMapLoaderWithClient(configMapName, namespace, manifestsDir, gzip, clientset)
}
func NewConfigMapLoaderWithClient(configMapName, namespace, manifestsDir string, gzip bool, clientset kubernetes.Interface) *ConfigMapWriter {
return &ConfigMapWriter{
clientset: clientset,
manifestsDir: manifestsDir,
configMapName: configMapName,
namespace: namespace,
gzip: gzip,
}
}
func TranslateInvalidChars(input string) string {
validConfigMapKey := unallowedKeyChars.ReplaceAllString(input, "~")
return validConfigMapKey
}
func (c *ConfigMapWriter) Populate(maxDataSizeLimit uint64) error {
subDirs := []string{"manifests/", "metadata/"}
configMapPopulate, err := c.clientset.CoreV1().ConfigMaps(c.namespace).Get(context.TODO(), c.configMapName, metav1.GetOptions{})
if err != nil {
return err
}
configMapPopulate.Data = map[string]string{}
configMapPopulate.BinaryData = map[string][]byte{}
var totalSize uint64
for _, dir := range subDirs {
completePath := c.manifestsDir + dir
files, err := os.ReadDir(completePath)
if err != nil {
logrus.Errorf("read dir failed: %v", err)
return err
}
for _, file := range files {
log := logrus.WithField("file", completePath+file.Name())
log.Info("Reading file")
content, err := os.ReadFile(completePath + file.Name())
if err != nil {
log.Errorf("read failed: %v", err)
return err
}
if file.Name() == bundle.AnnotationsFile {
var annotationsFile AnnotationsFile
err := yaml.Unmarshal(content, &annotationsFile)
if err != nil {
return err
}
configMapPopulate.SetAnnotations(map[string]string{
bundle.ManifestsLabel: annotationsFile.Annotations.Resources,
bundle.MediatypeLabel: annotationsFile.Annotations.MediaType,
bundle.MetadataLabel: annotationsFile.Annotations.Metadata,
bundle.PackageLabel: annotationsFile.Annotations.Package,
bundle.ChannelsLabel: annotationsFile.Annotations.Channels,
bundle.ChannelDefaultLabel: annotationsFile.Annotations.ChannelDefault,
})
// annotations aren't accounted for the ConfigMap data size
// limit, and rather have their own limit of 262144 bytes.
continue
}
if c.gzip {
content, err = encoding.GzipBase64Encode(content)
if err != nil {
log.Errorf("failed to gzip encode file %v: %v", file.Name(), err)
return err
}
}
totalSize += uint64(len(content))
if totalSize > maxDataSizeLimit {
log.Errorf("Bundle files exceeded %v bytes limit", maxDataSizeLimit)
return fmt.Errorf("bundle files exceeded %v bytes limit", maxDataSizeLimit)
}
validConfigMapKey := TranslateInvalidChars(file.Name())
if validConfigMapKey != file.Name() {
logrus.WithFields(logrus.Fields{
"file.Name": file.Name(),
"validConfigMapKey": validConfigMapKey,
}).Info("translated filename for configmap comptability")
}
if c.gzip {
configMapPopulate.BinaryData[validConfigMapKey] = content
} else {
configMapPopulate.Data[validConfigMapKey] = string(content)
}
}
}
if sourceImage := os.Getenv(EnvContainerImage); sourceImage != "" {
annotations := initAndGetAnnotations(configMapPopulate)
annotations[ConfigMapImageAnnotationKey] = sourceImage
}
if c.gzip {
setGzipEncodingAnnotation(configMapPopulate)
}
_, err = c.clientset.CoreV1().ConfigMaps(c.namespace).Update(context.TODO(), configMapPopulate, metav1.UpdateOptions{})
if err != nil {
return err
}
return nil
}
// LaunchBundleImage will launch a bundle image and also create a configmap for
// storing the data that will be updated to contain the bundle image data. It is
// the responsibility of the caller to delete the job, the pod, and the configmap
// when done. This function is intended to be called from OLM, but is put here
// for locality.
func LaunchBundleImage(kubeclient kubernetes.Interface, bundleImage, initImage, namespace string, gzip bool) (*corev1.ConfigMap, *batchv1.Job, error) {
// create configmap for bundle image data to write to (will be returned)
newConfigMap, err := kubeclient.CoreV1().ConfigMaps(namespace).Create(context.TODO(), &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "bundle-image-",
},
}, metav1.CreateOptions{})
if err != nil {
return nil, nil, err
}
opmCommand := []string{"/injected/opm", "alpha", "bundle", "extract", "-n", namespace, "-c", newConfigMap.GetName()}
if gzip {
opmCommand = append(opmCommand, "--gzip")
}
launchJob := batchv1.Job{
ObjectMeta: metav1.ObjectMeta{
GenerateName: "deploy-bundle-image-",
},
Spec: batchv1.JobSpec{
//ttlSecondsAfterFinished: 0 // can use in the future to not have to clean up job
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Name: "bundle-image",
},
Spec: corev1.PodSpec{
RestartPolicy: corev1.RestartPolicyOnFailure,
Containers: []corev1.Container{
{
Name: "bundle-image",
Image: bundleImage,
Command: opmCommand,
Env: []corev1.EnvVar{
{
Name: EnvContainerImage,
Value: bundleImage,
},
},
VolumeMounts: []corev1.VolumeMount{
{
Name: "copydir",
MountPath: "/injected",
},
},
},
},
InitContainers: []corev1.Container{
{
Name: "copy-binary",
Image: initImage,
Command: []string{"/bin/cp", "/bin/opm", "/copy-dest"},
VolumeMounts: []corev1.VolumeMount{
{
Name: "copydir",
MountPath: "/copy-dest",
},
},
},
},
Volumes: []corev1.Volume{
{
Name: "copydir",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
},
},
},
},
},
}
launchedJob, err := kubeclient.BatchV1().Jobs(namespace).Create(context.TODO(), &launchJob, metav1.CreateOptions{})
if err != nil {
err := kubeclient.CoreV1().ConfigMaps(namespace).Delete(context.TODO(), newConfigMap.GetName(), metav1.DeleteOptions{})
if err != nil {
// already in an error, so just report it
logrus.Errorf("failed to remove configmap: %v", err)
}
return nil, nil, err
}
return newConfigMap, launchedJob, nil
}
func setGzipEncodingAnnotation(cm *corev1.ConfigMap) {
annotations := initAndGetAnnotations(cm)
annotations[ConfigMapEncodingAnnotationKey] = ConfigMapEncodingAnnotationGzip
}
func hasGzipEncodingAnnotation(cm *corev1.ConfigMap) bool {
annotations := cm.GetAnnotations()
encoding, ok := annotations[ConfigMapEncodingAnnotationKey]
return ok && encoding == ConfigMapEncodingAnnotationGzip
}
func initAndGetAnnotations(cm *corev1.ConfigMap) map[string]string {
annotations := cm.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
cm.SetAnnotations(annotations)
}
return annotations
}