-
Notifications
You must be signed in to change notification settings - Fork 157
/
injector.go
500 lines (406 loc) · 15.2 KB
/
injector.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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2021-Present The Zarf Authors
// Package cluster contains Zarf-specific cluster management functions.
package cluster
import (
"fmt"
"net/http"
"os"
"path/filepath"
"regexp"
"time"
"github.com/defenseunicorns/pkg/helpers"
"github.com/defenseunicorns/zarf/src/config"
"github.com/defenseunicorns/zarf/src/pkg/k8s"
"github.com/defenseunicorns/zarf/src/pkg/layout"
"github.com/defenseunicorns/zarf/src/pkg/message"
"github.com/defenseunicorns/zarf/src/pkg/transform"
"github.com/defenseunicorns/zarf/src/pkg/utils"
"github.com/google/go-containerregistry/pkg/crane"
"github.com/mholt/archiver/v3"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/intstr"
)
// The chunk size for the tarball chunks.
var payloadChunkSize = 1024 * 768
var (
injectorRequestedCPU = resource.MustParse(".5")
injectorRequestedMemory = resource.MustParse("64Mi")
injectorLimitCPU = resource.MustParse("1")
injectorLimitMemory = resource.MustParse("256Mi")
)
// imageNodeMap is a map of image/node pairs.
type imageNodeMap map[string][]string
// StartInjectionMadness initializes a Zarf injection into the cluster.
func (c *Cluster) StartInjectionMadness(tmpDir string, imagesDir string, injectorSeedSrcs []string) {
spinner := message.NewProgressSpinner("Attempting to bootstrap the seed image into the cluster")
defer spinner.Stop()
tmp := layout.InjectionMadnessPaths{
SeedImagesDir: filepath.Join(tmpDir, "seed-images"),
// should already exist
InjectionBinary: filepath.Join(tmpDir, "zarf-injector"),
// gets created here
InjectorPayloadTarGz: filepath.Join(tmpDir, "payload.tar.gz"),
}
if err := helpers.CreateDirectory(tmp.SeedImagesDir, helpers.ReadWriteExecuteUser); err != nil {
spinner.Fatalf(err, "Unable to create the seed images directory")
}
var err error
var images imageNodeMap
var payloadConfigmaps []string
var sha256sum string
var seedImages []transform.Image
// Get all the images from the cluster
timeout := 5 * time.Minute
spinner.Updatef("Getting the list of existing cluster images (%s timeout)", timeout.String())
if images, err = c.getImagesAndNodesForInjection(timeout); err != nil {
spinner.Fatalf(err, "Unable to generate a list of candidate images to perform the registry injection")
}
spinner.Updatef("Creating the injector configmap")
if err = c.createInjectorConfigmap(tmp.InjectionBinary); err != nil {
spinner.Fatalf(err, "Unable to create the injector configmap")
}
spinner.Updatef("Creating the injector service")
if service, err := c.createService(); err != nil {
spinner.Fatalf(err, "Unable to create the injector service")
} else {
config.ZarfSeedPort = fmt.Sprintf("%d", service.Spec.Ports[0].NodePort)
}
spinner.Updatef("Loading the seed image from the package")
if seedImages, err = c.loadSeedImages(imagesDir, tmp.SeedImagesDir, injectorSeedSrcs, spinner); err != nil {
spinner.Fatalf(err, "Unable to load the injector seed image from the package")
}
spinner.Updatef("Loading the seed registry configmaps")
if payloadConfigmaps, sha256sum, err = c.createPayloadConfigmaps(tmp.SeedImagesDir, tmp.InjectorPayloadTarGz, spinner); err != nil {
spinner.Fatalf(err, "Unable to generate the injector payload configmaps")
}
// https://regex101.com/r/eLS3at/1
zarfImageRegex := regexp.MustCompile(`(?m)^127\.0\.0\.1:`)
// Try to create an injector pod using an existing image in the cluster
for image, node := range images {
// Don't try to run against the seed image if this is a secondary zarf init run
if zarfImageRegex.MatchString(image) {
continue
}
spinner.Updatef("Attempting to bootstrap with the %s/%s", node, image)
// Make sure the pod is not there first
_ = c.DeletePod(ZarfNamespaceName, "injector")
// Update the podspec image path and use the first node found
pod, err := c.buildInjectionPod(node[0], image, payloadConfigmaps, sha256sum)
if err != nil {
// Just debug log the output because failures just result in trying the next image
message.Debug(err)
continue
}
// Create the pod in the cluster
pod, err = c.CreatePod(pod)
if err != nil {
// Just debug log the output because failures just result in trying the next image
message.Debug(pod, err)
continue
}
// if no error, try and wait for a seed image to be present, return if successful
if c.injectorIsReady(seedImages, spinner) {
spinner.Success()
return
}
// Otherwise just continue to try next image
}
// All images were exhausted and still no happiness
spinner.Fatalf(nil, "Unable to perform the injection")
}
// StopInjectionMadness handles cleanup once the seed registry is up.
func (c *Cluster) StopInjectionMadness() error {
// Try to kill the injector pod now
if err := c.DeletePod(ZarfNamespaceName, "injector"); err != nil {
return err
}
// Remove the configmaps
labelMatch := map[string]string{"zarf-injector": "payload"}
if err := c.DeleteConfigMapsByLabel(ZarfNamespaceName, labelMatch); err != nil {
return err
}
// Remove the injector service
return c.DeleteService(ZarfNamespaceName, "zarf-injector")
}
func (c *Cluster) loadSeedImages(imagesDir, seedImagesDir string, injectorSeedSrcs []string, spinner *message.Spinner) ([]transform.Image, error) {
seedImages := []transform.Image{}
localReferenceToDigest := make(map[string]string)
// Load the injector-specific images and save them as seed-images
for _, src := range injectorSeedSrcs {
spinner.Updatef("Loading the seed image '%s' from the package", src)
ref, err := transform.ParseImageRef(src)
if err != nil {
return seedImages, fmt.Errorf("failed to create ref for image %s: %w", src, err)
}
img, err := utils.LoadOCIImage(imagesDir, ref)
if err != nil {
return seedImages, err
}
crane.SaveOCI(img, seedImagesDir)
seedImages = append(seedImages, ref)
// Get the image digest so we can set an annotation in the image.json later
imgDigest, err := img.Digest()
if err != nil {
return seedImages, err
}
// This is done _without_ the domain (different from pull.go) since the injector only handles local images
localReferenceToDigest[ref.Path+ref.TagOrDigest] = imgDigest.String()
}
if err := utils.AddImageNameAnnotation(seedImagesDir, localReferenceToDigest); err != nil {
return seedImages, fmt.Errorf("unable to format OCI layout: %w", err)
}
return seedImages, nil
}
func (c *Cluster) createPayloadConfigmaps(seedImagesDir, tarPath string, spinner *message.Spinner) ([]string, string, error) {
var configMaps []string
// Chunk size has to accommodate base64 encoding & etcd 1MB limit
tarFileList, err := filepath.Glob(filepath.Join(seedImagesDir, "*"))
if err != nil {
return configMaps, "", err
}
spinner.Updatef("Creating the seed registry archive to send to the cluster")
// Create a tar archive of the injector payload
if err := archiver.Archive(tarFileList, tarPath); err != nil {
return configMaps, "", err
}
chunks, sha256sum, err := helpers.ReadFileByChunks(tarPath, payloadChunkSize)
if err != nil {
return configMaps, "", err
}
spinner.Updatef("Splitting the archive into binary configmaps")
chunkCount := len(chunks)
// Loop over all chunks and generate configmaps
for idx, data := range chunks {
// Create a cat-friendly filename
fileName := fmt.Sprintf("zarf-payload-%03d", idx)
// Store the binary data
configData := map[string][]byte{
fileName: data,
}
spinner.Updatef("Adding archive binary configmap %d of %d to the cluster", idx+1, chunkCount)
// Attempt to create the configmap in the cluster
if _, err = c.ReplaceConfigmap(ZarfNamespaceName, fileName, configData); err != nil {
return configMaps, "", err
}
// Add the configmap to the configmaps slice for later usage in the pod
configMaps = append(configMaps, fileName)
// Give the control plane a 250ms buffer between each configmap
time.Sleep(250 * time.Millisecond)
}
return configMaps, sha256sum, nil
}
// Test for pod readiness and seed image presence.
func (c *Cluster) injectorIsReady(seedImages []transform.Image, spinner *message.Spinner) bool {
tunnel, err := c.NewTunnel(ZarfNamespaceName, k8s.SvcResource, ZarfInjectorName, "", 0, ZarfInjectorPort)
if err != nil {
return false
}
_, err = tunnel.Connect()
if err != nil {
return false
}
defer tunnel.Close()
spinner.Updatef("Testing the injector for seed image availability")
for _, seedImage := range seedImages {
seedRegistry := fmt.Sprintf("%s/v2/%s/manifests/%s", tunnel.HTTPEndpoint(), seedImage.Path, seedImage.Tag)
var resp *http.Response
var err error
err = tunnel.Wrap(func() error {
resp, err = http.Get(seedRegistry)
return err
})
if err != nil || resp.StatusCode != 200 {
// Just debug log the output because failures just result in trying the next image
message.Debug(resp, err)
return false
}
}
spinner.Updatef("Seed image found, injector is ready")
return true
}
func (c *Cluster) createInjectorConfigmap(binaryPath string) error {
var err error
configData := make(map[string][]byte)
// Add the injector binary data to the configmap
if configData["zarf-injector"], err = os.ReadFile(binaryPath); err != nil {
return err
}
// Try to delete configmap silently
_ = c.DeleteConfigmap(ZarfNamespaceName, "rust-binary")
// Attempt to create the configmap in the cluster
if _, err = c.CreateConfigmap(ZarfNamespaceName, "rust-binary", configData); err != nil {
return err
}
return nil
}
func (c *Cluster) createService() (*corev1.Service, error) {
service := c.GenerateService(ZarfNamespaceName, "zarf-injector")
service.Spec.Type = corev1.ServiceTypeNodePort
service.Spec.Ports = append(service.Spec.Ports, corev1.ServicePort{
Port: int32(5000),
})
service.Spec.Selector = map[string]string{
"app": "zarf-injector",
}
// Attempt to purse the service silently
_ = c.DeleteService(ZarfNamespaceName, "zarf-injector")
return c.CreateService(service)
}
// buildInjectionPod return a pod for injection with the appropriate containers to perform the injection.
func (c *Cluster) buildInjectionPod(node, image string, payloadConfigmaps []string, payloadShasum string) (*corev1.Pod, error) {
pod := c.GeneratePod("injector", ZarfNamespaceName)
executeMode := int32(0777)
pod.Labels["app"] = "zarf-injector"
// Ensure zarf agent doesn't break the injector on future runs
pod.Labels[agentLabel] = "ignore"
// Bind the pod to the node the image was found on
pod.Spec.NodeName = node
// Do not try to restart the pod as it will be deleted/re-created instead
pod.Spec.RestartPolicy = corev1.RestartPolicyNever
pod.Spec.Containers = []corev1.Container{
{
Name: "injector",
// An existing image already present on the cluster
Image: image,
// PullIfNotPresent because some distros provide a way (even in airgap) to pull images from local or direct-connected registries
ImagePullPolicy: corev1.PullIfNotPresent,
// This directory's contents come from the init container output
WorkingDir: "/zarf-init",
// Call the injector with shasum of the tarball
Command: []string{"/zarf-init/zarf-injector", payloadShasum},
// Shared mount between the init and regular containers
VolumeMounts: []corev1.VolumeMount{
{
Name: "init",
MountPath: "/zarf-init/zarf-injector",
SubPath: "zarf-injector",
},
{
Name: "seed",
MountPath: "/zarf-seed",
},
},
// Readiness probe to optimize the pod startup time
ReadinessProbe: &corev1.Probe{
PeriodSeconds: 2,
SuccessThreshold: 1,
FailureThreshold: 10,
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: "/v2/", // path to health check
Port: intstr.FromInt(5000), // port to health check
},
},
},
// Keep resources as light as possible as we aren't actually running the container's other binaries
Resources: corev1.ResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceCPU: injectorRequestedCPU,
corev1.ResourceMemory: injectorRequestedMemory,
},
Limits: corev1.ResourceList{
corev1.ResourceCPU: injectorLimitCPU,
corev1.ResourceMemory: injectorLimitMemory,
},
},
},
}
pod.Spec.Volumes = []corev1.Volume{
// Contains the rust binary and collection of configmaps from the tarball (seed image).
{
Name: "init",
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: "rust-binary",
},
DefaultMode: &executeMode,
},
},
},
// Empty directory to hold the seed image (new dir to avoid permission issues)
{
Name: "seed",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
},
}
// Iterate over all the payload configmaps and add their mounts.
for _, filename := range payloadConfigmaps {
// Create the configmap volume from the given filename.
pod.Spec.Volumes = append(pod.Spec.Volumes, corev1.Volume{
Name: filename,
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: filename,
},
},
},
})
// Create the volume mount to place the new volume in the working directory
pod.Spec.Containers[0].VolumeMounts = append(pod.Spec.Containers[0].VolumeMounts, corev1.VolumeMount{
Name: filename,
MountPath: fmt.Sprintf("/zarf-init/%s", filename),
SubPath: filename,
})
}
return pod, nil
}
// GetImagesFromAvailableNodes checks for images on schedulable nodes within a cluster and returns
func (c *Cluster) getImagesAndNodesForInjection(timeoutDuration time.Duration) (imageNodeMap, error) {
timeout := time.After(timeoutDuration)
result := make(imageNodeMap)
for {
select {
// On timeout abort
case <-timeout:
return nil, fmt.Errorf("get image list timed-out")
// After delay, try running
default:
pods, err := c.GetPods(corev1.NamespaceAll)
if err != nil {
return nil, fmt.Errorf("unable to get the list of pods in the cluster")
}
findImages:
for _, pod := range pods.Items {
nodeName := pod.Spec.NodeName
// If this pod doesn't have a node (i.e. is Pending), skip it
if nodeName == "" {
continue
}
nodeDetails, err := c.GetNode(nodeName)
if err != nil {
return nil, fmt.Errorf("unable to get the node %s", pod.Spec.NodeName)
}
if nodeDetails.Status.Allocatable.Cpu().Cmp(injectorRequestedCPU) < 0 ||
nodeDetails.Status.Allocatable.Memory().Cmp(injectorRequestedMemory) < 0 {
continue findImages
}
for _, taint := range nodeDetails.Spec.Taints {
if taint.Effect == corev1.TaintEffectNoSchedule || taint.Effect == corev1.TaintEffectNoExecute {
continue findImages
}
}
for _, container := range pod.Spec.InitContainers {
result[container.Image] = append(result[container.Image], nodeName)
}
for _, container := range pod.Spec.Containers {
result[container.Image] = append(result[container.Image], nodeName)
}
for _, container := range pod.Spec.EphemeralContainers {
result[container.Image] = append(result[container.Image], nodeName)
}
}
}
if len(result) < 1 {
c.Log("no images found: %w")
time.Sleep(2 * time.Second)
} else {
return result, nil
}
}
}