cache_images.go 10.8 KB
Newer Older
M
Matt Rickard 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
Copyright 2016 The Kubernetes Authors All rights reserved.

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 machine

import (
20
	"fmt"
M
Matt Rickard 已提交
21
	"os"
22
	"path"
M
Matt Rickard 已提交
23
	"path/filepath"
24
	"strings"
25
	"sync"
26
	"time"
M
Matt Rickard 已提交
27

28
	"github.com/docker/docker/client"
29
	"github.com/docker/machine/libmachine/state"
30
	"github.com/pkg/errors"
K
kairen 已提交
31
	"golang.org/x/sync/errgroup"
32
	"k8s.io/klog/v2"
M
Matt Rickard 已提交
33 34
	"k8s.io/minikube/pkg/minikube/assets"
	"k8s.io/minikube/pkg/minikube/bootstrapper"
35
	"k8s.io/minikube/pkg/minikube/command"
P
Priya Wadhwa 已提交
36
	"k8s.io/minikube/pkg/minikube/config"
M
Matt Rickard 已提交
37
	"k8s.io/minikube/pkg/minikube/constants"
38
	"k8s.io/minikube/pkg/minikube/cruntime"
39 40
	"k8s.io/minikube/pkg/minikube/image"
	"k8s.io/minikube/pkg/minikube/localpath"
41
	"k8s.io/minikube/pkg/minikube/vmpath"
M
Matt Rickard 已提交
42 43
)

44
// loadRoot is where images should be loaded from within the guest VM
45
var loadRoot = path.Join(vmpath.GuestPersistentDir, "images")
M
Matt Rickard 已提交
46

47 48
// loadImageLock is used to serialize image loads to avoid overloading the guest VM
var loadImageLock sync.Mutex
49

50
// CacheImagesForBootstrapper will cache images for a bootstrapper
51
func CacheImagesForBootstrapper(imageRepository string, version string, clusterBootstrapper string) error {
52 53 54 55
	images, err := bootstrapper.GetCachedImageList(imageRepository, version, clusterBootstrapper)
	if err != nil {
		return errors.Wrap(err, "cached images list")
	}
M
Matt Rickard 已提交
56

M
Medya Gh 已提交
57
	if err := image.SaveToDir(images, constants.ImageCacheDir); err != nil {
M
Matt Rickard 已提交
58 59 60
		return errors.Wrapf(err, "Caching images for %s", clusterBootstrapper)
	}

61 62 63
	return nil
}

64 65
// LoadCachedImages loads previously cached images into the container runtime
func LoadCachedImages(cc *config.ClusterConfig, runner command.Runner, images []string, cacheDir string) error {
66 67 68 69 70
	cr, err := cruntime.New(cruntime.Config{Type: cc.KubernetesConfig.ContainerRuntime, Runner: runner})
	if err != nil {
		return errors.Wrap(err, "runtime")
	}

M
Medya Gh 已提交
71
	// Skip loading images if images already exist
72
	if cr.ImagesPreloaded(images) {
73
		klog.Infof("Images are preloaded, skipping loading")
M
Medya Gh 已提交
74
		return nil
75
	}
76

77
	klog.Infof("LoadImages start: %s", images)
78 79 80
	start := time.Now()

	defer func() {
81
		klog.Infof("LoadImages completed in %s", time.Since(start))
82 83
	}()

M
Matt Rickard 已提交
84
	var g errgroup.Group
85

86 87 88 89
	var imgClient *client.Client
	if cr.Name() == "Docker" {
		imgClient, err = client.NewClientWithOpts(client.FromEnv) // image client
		if err != nil {
90
			klog.Infof("couldn't get a local image daemon which might be ok: %v", err)
91
		}
92 93
	}

M
Matt Rickard 已提交
94 95 96
	for _, image := range images {
		image := image
		g.Go(func() error {
97 98 99 100 101
			// Put a ten second limit on deciding if an image needs transfer
			// because it takes much less than that time to just transfer the image.
			// This is needed because if running in offline mode, we can spend minutes here
			// waiting for i/o timeout.
			err := timedNeedsTransfer(imgClient, image, cr, 10*time.Second)
102
			if err == nil {
M
lint  
Medya Gh 已提交
103
				return nil
M
Medya Gh 已提交
104
			}
105
			klog.Infof("%q needs transfer: %v", image, err)
106
			return transferAndLoadCachedImage(runner, cc.KubernetesConfig, image, cacheDir)
M
Matt Rickard 已提交
107 108 109 110 111
		})
	}
	if err := g.Wait(); err != nil {
		return errors.Wrap(err, "loading cached images")
	}
112
	klog.Infoln("Successfully loaded all cached images")
113 114 115
	return nil
}

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
func timedNeedsTransfer(imgClient *client.Client, imgName string, cr cruntime.Manager, t time.Duration) error {
	timeout := make(chan bool, 1)
	go func() {
		time.Sleep(t)
		timeout <- true
	}()

	transferFinished := make(chan bool, 1)
	var err error
	go func() {
		err = needsTransfer(imgClient, imgName, cr)
		transferFinished <- true
	}()

	select {
	case <-transferFinished:
		return err
	case <-timeout:
		return fmt.Errorf("needs transfer timed out in %f seconds", t.Seconds())
	}
}

138
// needsTransfer returns an error if an image needs to be retransfered
139
func needsTransfer(imgClient *client.Client, imgName string, cr cruntime.Manager) error {
140
	imgDgst := ""         // for instance sha256:7c92a2c6bbcb6b6beff92d0a940779769c2477b807c202954c537e2e0deb9bed
141
	if imgClient != nil { // if possible try to get img digest from Client lib which is 4s faster.
M
Medya Gh 已提交
142
		imgDgst = image.DigestByDockerLib(imgClient, imgName)
143 144 145
		if imgDgst != "" {
			if !cr.ImageExists(imgName, imgDgst) {
				return fmt.Errorf("%q does not exist at hash %q in container runtime", imgName, imgDgst)
146 147 148 149 150
			}
			return nil
		}
	}
	// if not found with method above try go-container lib (which is 4s slower)
M
Medya Gh 已提交
151
	imgDgst = image.DigestByGoLib(imgName)
152 153
	if imgDgst == "" {
		return fmt.Errorf("got empty img digest %q for %s", imgDgst, imgName)
154
	}
155 156
	if !cr.ImageExists(imgName, imgDgst) {
		return fmt.Errorf("%q does not exist at hash %q in container runtime", imgName, imgDgst)
157 158 159 160
	}
	return nil
}

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
// LoadLocalImages loads images into the container runtime
func LoadLocalImages(cc *config.ClusterConfig, runner command.Runner, images []string) error {
	var g errgroup.Group
	for _, image := range images {
		image := image
		g.Go(func() error {
			return transferAndLoadImage(runner, cc.KubernetesConfig, image)
		})
	}
	if err := g.Wait(); err != nil {
		return errors.Wrap(err, "loading images")
	}
	klog.Infoln("Successfully loaded all images")
	return nil
}

177
// CacheAndLoadImages caches and loads images to all profiles
P
Priya Wadhwa 已提交
178
func CacheAndLoadImages(images []string, profiles []*config.Profile) error {
179 180 181 182
	if len(images) == 0 {
		return nil
	}

183
	// This is the most important thing
M
Medya Gh 已提交
184
	if err := image.SaveToDir(images, constants.ImageCacheDir); err != nil {
185
		return errors.Wrap(err, "save to dir")
P
Priya Wadhwa 已提交
186
	}
187

188 189 190 191 192
	return DoLoadImages(images, profiles, constants.ImageCacheDir)
}

// DoLoadImages loads images to all profiles
func DoLoadImages(images []string, profiles []*config.Profile, cacheDir string) error {
P
Priya Wadhwa 已提交
193 194
	api, err := NewAPIClient()
	if err != nil {
195
		return errors.Wrap(err, "api")
P
Priya Wadhwa 已提交
196 197
	}
	defer api.Close()
198 199 200 201

	succeeded := []string{}
	failed := []string{}

M
Medya Gh 已提交
202
	for _, p := range profiles { // loading images to all running profiles
203
		pName := p.Name // capture the loop variable
204

S
Sharif Elgamal 已提交
205
		c, err := config.Load(pName)
206
		if err != nil {
207
			// Non-fatal because it may race with profile deletion
208
			klog.Errorf("Failed to load profile %q: %v", pName, err)
209 210
			failed = append(failed, pName)
			continue
211
		}
212

S
Sharif Elgamal 已提交
213
		for _, n := range c.Nodes {
D
Daehyeok Mun 已提交
214
			m := config.MachineName(*c, n)
215

216
			status, err := Status(api, m)
217
			if err != nil {
218
				klog.Warningf("error getting status for %s: %v", m, err)
S
Sharif Elgamal 已提交
219
				failed = append(failed, m)
220
				continue
221
			}
222

S
Sharif Elgamal 已提交
223 224 225
			if status == state.Running.String() { // the not running hosts will load on next start
				h, err := api.Load(m)
				if err != nil {
226
					klog.Warningf("Failed to load machine %q: %v", m, err)
S
Sharif Elgamal 已提交
227
					failed = append(failed, m)
228
					continue
S
Sharif Elgamal 已提交
229 230 231 232 233
				}
				cr, err := CommandRunner(h)
				if err != nil {
					return err
				}
234 235 236 237 238 239 240
				if cacheDir != "" {
					// loading image names, from cache
					err = LoadCachedImages(c, cr, images, cacheDir)
				} else {
					// loading image files
					err = LoadLocalImages(c, cr, images)
				}
S
Sharif Elgamal 已提交
241
				if err != nil {
S
Sharif Elgamal 已提交
242
					failed = append(failed, m)
243
					klog.Warningf("Failed to load cached images for profile %s. make sure the profile is running. %v", pName, err)
244
					continue
S
Sharif Elgamal 已提交
245
				}
S
Sharif Elgamal 已提交
246
				succeeded = append(succeeded, m)
247 248
			}
		}
P
Priya Wadhwa 已提交
249
	}
250

251 252
	klog.Infof("succeeded pushing to: %s", strings.Join(succeeded, " "))
	klog.Infof("failed pushing to: %s", strings.Join(failed, " "))
253 254
	// Live pushes are not considered a failure
	return nil
P
Priya Wadhwa 已提交
255 256
}

257 258 259 260 261 262 263 264 265
// transferAndLoadCachedImage transfers and loads a single image from the cache
func transferAndLoadCachedImage(cr command.Runner, k8s config.KubernetesConfig, imgName string, cacheDir string) error {
	src := filepath.Join(cacheDir, imgName)
	src = localpath.SanitizeCacheDir(src)
	return transferAndLoadImage(cr, k8s, src)
}

// transferAndLoadImage transfers and loads a single image
func transferAndLoadImage(cr command.Runner, k8s config.KubernetesConfig, src string) error {
266 267 268 269
	r, err := cruntime.New(cruntime.Config{Type: k8s.ContainerRuntime, Runner: cr})
	if err != nil {
		return errors.Wrap(err, "runtime")
	}
270
	klog.Infof("Loading image from: %s", src)
M
Matt Rickard 已提交
271
	filename := filepath.Base(src)
272
	if _, err := os.Stat(src); err != nil {
273
		return err
M
Matt Rickard 已提交
274
	}
275 276
	dst := path.Join(loadRoot, filename)
	f, err := assets.NewFileAsset(src, loadRoot, filename, "0644")
M
Matt Rickard 已提交
277 278 279
	if err != nil {
		return errors.Wrapf(err, "creating copyable file asset: %s", filename)
	}
280
	if err := cr.Copy(f); err != nil {
M
Matt Rickard 已提交
281 282 283
		return errors.Wrap(err, "transferring cached image")
	}

284 285
	loadImageLock.Lock()
	defer loadImageLock.Unlock()
M
Matt Rickard 已提交
286

287 288 289
	err = r.LoadImage(dst)
	if err != nil {
		return errors.Wrapf(err, "%s load %s", r.Name(), dst)
290 291
	}

292
	klog.Infof("Transferred and loaded %s from cache", src)
M
Matt Rickard 已提交
293 294
	return nil
}
T
Tharun 已提交
295 296

// removeImages removes images from the container run time
297
func removeImages(cruntime cruntime.Manager, images []string) error {
T
Tharun 已提交
298 299 300 301 302 303 304 305 306 307 308 309
	klog.Infof("RemovingImages start: %s", images)
	start := time.Now()

	defer func() {
		klog.Infof("RemovingImages completed in %s", time.Since(start))
	}()

	var g errgroup.Group

	for _, image := range images {
		image := image
		g.Go(func() error {
310
			return cruntime.RemoveImage(image)
T
Tharun 已提交
311 312 313
		})
	}
	if err := g.Wait(); err != nil {
314
		return errors.Wrap(err, "error removing images")
T
Tharun 已提交
315 316 317 318 319
	}
	klog.Infoln("Successfully removed images")
	return nil
}

320
func RemoveImages(images []string, profile *config.Profile) error {
T
Tharun 已提交
321 322
	api, err := NewAPIClient()
	if err != nil {
323
		return errors.Wrap(err, "error creating api client")
T
Tharun 已提交
324 325 326 327 328 329
	}
	defer api.Close()

	succeeded := []string{}
	failed := []string{}

330
	pName := profile.Name
T
Tharun 已提交
331

332 333 334 335 336 337 338 339 340 341
	c, err := config.Load(pName)
	if err != nil {
		klog.Errorf("Failed to load profile %q: %v", pName, err)
		return errors.Wrapf(err, "error loading config for profile :%v", pName)
	}

	for _, n := range c.Nodes {
		m := config.MachineName(*c, n)

		status, err := Status(api, m)
T
Tharun 已提交
342
		if err != nil {
343
			klog.Warningf("error getting status for %s: %v", m, err)
T
Tharun 已提交
344 345 346
			continue
		}

347 348
		if status == state.Running.String() {
			h, err := api.Load(m)
T
Tharun 已提交
349
			if err != nil {
350
				klog.Warningf("Failed to load machine %q: %v", m, err)
T
Tharun 已提交
351 352
				continue
			}
353 354 355 356 357 358 359 360 361 362 363 364 365
			runner, err := CommandRunner(h)
			if err != nil {
				return err
			}
			cruntime, err := cruntime.New(cruntime.Config{Type: c.KubernetesConfig.ContainerRuntime, Runner: runner})
			if err != nil {
				return errors.Wrap(err, "error creating container runtime")
			}
			err = removeImages(cruntime, images)
			if err != nil {
				failed = append(failed, m)
				klog.Warningf("Failed to remove images for profile %s %v", pName, err.Error())
				continue
T
Tharun 已提交
366
			}
367
			succeeded = append(succeeded, m)
T
Tharun 已提交
368 369 370
		}
	}

T
Tharun 已提交
371 372
	klog.Infof("succeeded removing from: %s", strings.Join(succeeded, " "))
	klog.Infof("failed removing from: %s", strings.Join(failed, " "))
T
Tharun 已提交
373 374
	return nil
}