File: buildcontext.go

package info (click to toggle)
kind 0.30.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,392 kB
  • sloc: sh: 1,900; makefile: 97; javascript: 55; xml: 9
file content (374 lines) | stat: -rw-r--r-- 12,289 bytes parent folder | download | duplicates (2)
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
/*
Copyright 2018 The Kubernetes Authors.

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 nodeimage

import (
	"fmt"
	"math/rand"
	"os"
	"path"
	"strings"
	"time"

	"sigs.k8s.io/kind/pkg/errors"
	"sigs.k8s.io/kind/pkg/exec"
	"sigs.k8s.io/kind/pkg/log"

	"sigs.k8s.io/kind/pkg/build/nodeimage/internal/container/docker"
	"sigs.k8s.io/kind/pkg/build/nodeimage/internal/kube"
	"sigs.k8s.io/kind/pkg/internal/sets"
	"sigs.k8s.io/kind/pkg/internal/version"
)

const (
	// httpProxy is the HTTP_PROXY environment variable key
	httpProxy = "HTTP_PROXY"
	// httpsProxy is the HTTPS_PROXY environment variable key
	httpsProxy = "HTTPS_PROXY"
	// noProxy is the NO_PROXY environment variable key
	noProxy = "NO_PROXY"
)

// buildContext is used to build the kind node image, and contains
// build configuration
type buildContext struct {
	// option fields
	image     string
	baseImage string
	logger    log.Logger
	arch      string
	buildType string
	kubeParam string
	// non-option fields
	builder kube.Builder
}

// Build builds the cluster node image, the source dir must be set on
// the buildContext
func (c *buildContext) Build() (err error) {
	// ensure kubernetes build is up-to-date first
	c.logger.V(0).Info("Starting to build Kubernetes")
	bits, err := c.builder.Build()
	if err != nil {
		c.logger.Errorf("Failed to build Kubernetes: %v", err)
		return errors.Wrap(err, "failed to build kubernetes")
	}
	c.logger.V(0).Info("Finished building Kubernetes")

	// then perform the actual docker image build
	c.logger.V(0).Info("Building node image ...")
	return c.buildImage(bits)
}

func (c *buildContext) buildImage(bits kube.Bits) error {
	// create build container
	// NOTE: we are using docker run + docker commit, so we can install
	// debian packages without permanently copying them into the image.
	// if docker gets proper squash support, we can rm them instead
	// This also allows the KubeBit implementations to programmatically
	// install in the image
	containerID, err := c.createBuildContainer()
	cmder := docker.ContainerCmder(containerID)

	// ensure we will delete it
	if containerID != "" {
		defer func() {
			_ = exec.Command("docker", "rm", "-f", "-v", containerID).Run()
		}()
	}
	if err != nil {
		c.logger.Errorf("Image build Failed! Failed to create build container: %v", err)
		return err
	}

	c.logger.V(0).Info("Building in container: " + containerID)

	// copy artifacts in
	for _, binary := range bits.BinaryPaths() {
		// TODO: probably should be /usr/local/bin, but the existing kubelet
		// service file expects /usr/bin/kubelet
		nodePath := "/usr/bin/" + path.Base(binary)
		if err := exec.Command("docker", "cp", binary, containerID+":"+nodePath).Run(); err != nil {
			return err
		}
		if err := cmder.Command("chmod", "+x", nodePath).Run(); err != nil {
			return err
		}
		if err := cmder.Command("chown", "root:root", nodePath).Run(); err != nil {
			return err
		}
	}

	// write version
	// TODO: support grabbing version from a binary instead?
	// This may or may not be a good idea ...
	rawVersion := bits.Version()
	parsedVersion, err := version.ParseSemantic(rawVersion)
	if err != nil {
		return errors.Wrap(err, "invalid Kubernetes version")
	}
	if err := createFile(cmder, "/kind/version", rawVersion); err != nil {
		return err
	}

	// pre-pull images that were not part of the build and write CNI / storage
	// manifests
	if _, err = c.prePullImagesAndWriteManifests(bits, parsedVersion, containerID); err != nil {
		c.logger.Errorf("Image build Failed! Failed to pull Images: %v", err)
		return err
	}

	// Save the image changes to a new image
	if err = exec.Command(
		"docker", "commit",
		// we need to put this back after changing it when running the image
		"--change", `ENTRYPOINT [ "/usr/local/bin/entrypoint", "/sbin/init" ]`,
		// remove proxy settings since they're for the building process
		// and should not be carried with the built image
		"--change", `ENV HTTP_PROXY="" HTTPS_PROXY="" NO_PROXY=""`,
		containerID, c.image,
	).Run(); err != nil {
		c.logger.Errorf("Image build Failed! Failed to save image: %v", err)
		return err
	}

	c.logger.V(0).Infof("Image %q build completed.", c.image)
	return nil
}

// returns a set of image tags that will be side-loaded
func (c *buildContext) getBuiltImages(bits kube.Bits) (sets.String, error) {
	images := sets.NewString()
	for _, path := range bits.ImagePaths() {
		tags, err := docker.GetArchiveTags(path)
		if err != nil {
			return nil, err
		}
		images.Insert(tags...)
	}
	return images, nil
}

// must be run after kubernetes has been installed on the node
func (c *buildContext) prePullImagesAndWriteManifests(bits kube.Bits, parsedVersion *version.Version, containerID string) ([]string, error) {
	// first get the images we actually built
	builtImages, err := c.getBuiltImages(bits)
	if err != nil {
		c.logger.Errorf("Image build Failed! Failed to get built images: %v", err)
		return nil, err
	}

	// helpers to run things in the build container
	cmder := docker.ContainerCmder(containerID)

	// For kubernetes v1.15+ (actually 1.16 alpha versions) we may need to
	// drop the arch suffix from images to get the expected image
	archSuffix := "-" + c.arch
	fixRepository := func(repository string) string {
		if strings.HasSuffix(repository, archSuffix) {
			fixed := strings.TrimSuffix(repository, archSuffix)
			c.logger.V(1).Info("fixed: " + repository + " -> " + fixed)
			repository = fixed
		}
		return repository
	}

	// Determine accurate built tags using the logic that will be applied
	// when rewriting tags during archive loading
	fixedImages := sets.NewString()
	fixedImagesMap := make(map[string]string, builtImages.Len()) // key: original images, value: fixed images
	for _, image := range builtImages.List() {
		registry, tag, err := docker.SplitImage(image)
		if err != nil {
			return nil, err
		}
		registry = fixRepository(registry)
		fixedImage := registry + ":" + tag
		fixedImages.Insert(fixedImage)
		fixedImagesMap[image] = fixedImage
	}
	builtImages = fixedImages
	c.logger.V(1).Info("Detected built images: " + strings.Join(builtImages.List(), ", "))

	// gets the list of images required by kubeadm
	requiredImages, err := exec.OutputLines(cmder.Command(
		"kubeadm", "config", "images", "list", "--kubernetes-version", bits.Version(),
	))
	if err != nil {
		return nil, err
	}

	// replace pause image with our own
	containerdConfig, err := exec.Output(cmder.Command("cat", containerdConfigPath))
	if err != nil {
		return nil, err
	}
	pauseImage, err := findSandboxImage(string(containerdConfig))
	if err != nil {
		return nil, err
	}
	n := 0
	for _, image := range requiredImages {
		if !strings.Contains(image, "pause") {
			requiredImages[n] = image
			n++
		}
	}
	requiredImages = append(requiredImages[:n], pauseImage)

	if parsedVersion.LessThan(version.MustParseSemantic("v1.24.0")) {
		if err := configureContainerdSystemdCgroupFalse(cmder, string(containerdConfig)); err != nil {
			return nil, err
		}
	}

	// write the default CNI manifest
	if err := createFile(cmder, defaultCNIManifestLocation, defaultCNIManifest); err != nil {
		c.logger.Errorf("Image build Failed! Failed write default CNI Manifest: %v", err)
		return nil, err
	}
	// all builds should install the default CNI images from the above manifest currently
	requiredImages = append(requiredImages, defaultCNIImages...)

	// write the default Storage manifest
	if err := createFile(cmder, defaultStorageManifestLocation, defaultStorageManifest); err != nil {
		c.logger.Errorf("Image build Failed! Failed write default Storage Manifest: %v", err)
		return nil, err
	}
	// all builds should install the default storage driver images currently
	requiredImages = append(requiredImages, defaultStorageImages...)

	// setup image importer
	importer := newContainerdImporter(cmder)
	if err := importer.Prepare(); err != nil {
		c.logger.Errorf("Image build Failed! Failed to prepare containerd to load images %v", err)
		return nil, err
	}

	// TODO: return this error?
	defer func() {
		if err := importer.End(); err != nil {
			c.logger.Errorf("Image build Failed! Failed to tear down containerd after loading images %v", err)
		}
	}()

	fns := []func() error{}
	osArch := dockerBuildOsAndArch(c.arch)
	for _, image := range requiredImages {
		image := image // https://golang.org/doc/faq#closures_and_goroutines
		if !builtImages.Has(image) {
			fns = append(fns, func() error {
				if err = importer.Pull(image, osArch); err != nil {
					c.logger.Warnf("Failed to pull %s with error: %v", image, err)
					runE := exec.RunErrorForError(err)
					c.logger.Warn(string(runE.Output))
					c.logger.Warnf("Retrying %s pull after 1s ...", image)
					time.Sleep(time.Second)
					return importer.Pull(image, osArch)
				}
				return nil
			})
		}
	}
	// Wait for containerd socket to be ready, which may take 1s when running under emulation
	if err := importer.WaitForReady(); err != nil {
		c.logger.Errorf("Image build failed, containerd did not become ready %v", err)
		return nil, err
	}
	if err := errors.AggregateConcurrent(fns); err != nil {
		return nil, err
	}

	// create a plan of image loading
	loadFns := []func() error{}
	for _, image := range bits.ImagePaths() {
		image := image // capture loop var
		loadFns = append(loadFns, func() error {
			f, err := os.Open(image)
			if err != nil {
				return err
			}
			defer f.Close()
			return importer.LoadCommand().SetStdout(os.Stdout).SetStderr(os.Stderr).SetStdin(f).Run()
			// we will rewrite / correct the tags in tagFns below
		})
	}

	// run all image loading concurrently until one fails or all succeed
	if err := errors.UntilErrorConcurrent(loadFns); err != nil {
		c.logger.Errorf("Image build Failed! Failed to load images %v", err)
		return nil, err
	}

	// create a plan of image re-tagging
	tagFns := []func() error{}
	for unfixed, fixed := range fixedImagesMap {
		unfixed, fixed := unfixed, fixed // capture loop var
		if unfixed != fixed {
			tagFns = append(tagFns, func() error {
				return importer.Tag(unfixed, fixed)
			})
		}
	}

	// run all image re-tagging concurrently until one fails or all succeed
	if err := errors.UntilErrorConcurrent(tagFns); err != nil {
		c.logger.Errorf("Image build Failed! Failed to re-tag images %v", err)
		return nil, err
	}

	return importer.ListImported()
}

func (c *buildContext) createBuildContainer() (id string, err error) {
	// attempt to explicitly pull the image if it doesn't exist locally
	// errors here are non-critical; we'll proceed with execution, which includes a pull operation
	_ = docker.Pull(c.logger, c.baseImage, dockerBuildOsAndArch(c.arch), 4)
	// this should be good enough: a specific prefix, the current unix time,
	// and a little random bits in case we have multiple builds simultaneously
	random := rand.New(rand.NewSource(time.Now().UnixNano())).Int31()
	id = fmt.Sprintf("kind-build-%d-%d", time.Now().UTC().Unix(), random)
	runArgs := []string{
		"-d",                 // make the client exit while the container continues to run
		"--entrypoint=sleep", // the container should hang forever, so we can exec in it
		"--name=" + id,
		"--platform=" + dockerBuildOsAndArch(c.arch),
		"--security-opt", "seccomp=unconfined",
	}
	// pass proxy settings from environment variables to the building container
	// to make them work during the building process
	for _, name := range []string{httpProxy, httpsProxy, noProxy} {
		val := os.Getenv(name)
		if val == "" {
			val = os.Getenv(strings.ToLower(name))
		}
		if val != "" {
			runArgs = append(runArgs, "--env", name+"="+val)
		}
	}
	err = docker.Run(
		c.baseImage,
		runArgs,
		[]string{
			"infinity", // sleep infinitely to keep container running indefinitely
		},
	)
	if err != nil {
		return id, errors.Wrap(err, "failed to create build container")
	}
	return id, nil
}