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 20 21
/*
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 (
	"io/ioutil"
	"os"
H
Hiroshi Nomura 已提交
22
	"os/exec"
23
	"path"
M
Matt Rickard 已提交
24
	"path/filepath"
25
	"runtime"
M
Matt Rickard 已提交
26
	"strings"
27
	"sync"
T
tstromberg 已提交
28
	"time"
M
Matt Rickard 已提交
29

30
	"github.com/docker/machine/libmachine/state"
31
	"github.com/golang/glog"
32 33
	"github.com/google/go-containerregistry/pkg/authn"
	"github.com/google/go-containerregistry/pkg/name"
34 35
	v1 "github.com/google/go-containerregistry/pkg/v1"
	"github.com/google/go-containerregistry/pkg/v1/daemon"
36
	"github.com/google/go-containerregistry/pkg/v1/remote"
37 38
	"github.com/google/go-containerregistry/pkg/v1/tarball"
	"github.com/pkg/errors"
K
kairen 已提交
39
	"golang.org/x/sync/errgroup"
M
Matt Rickard 已提交
40 41
	"k8s.io/minikube/pkg/minikube/assets"
	"k8s.io/minikube/pkg/minikube/bootstrapper"
42
	"k8s.io/minikube/pkg/minikube/cluster"
43
	"k8s.io/minikube/pkg/minikube/command"
P
Priya Wadhwa 已提交
44
	"k8s.io/minikube/pkg/minikube/config"
M
Matt Rickard 已提交
45
	"k8s.io/minikube/pkg/minikube/constants"
46
	"k8s.io/minikube/pkg/minikube/cruntime"
47
	"k8s.io/minikube/pkg/minikube/vmpath"
M
Matt Rickard 已提交
48 49
)

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

H
Hiroshi Nomura 已提交
53 54
var getWindowsVolumeName = getWindowsVolumeNameCmd

55 56
// loadImageLock is used to serialize image loads to avoid overloading the guest VM
var loadImageLock sync.Mutex
57

58
// CacheImagesForBootstrapper will cache images for a bootstrapper
59 60
func CacheImagesForBootstrapper(imageRepository string, version string, clusterBootstrapper string) error {
	images := bootstrapper.GetCachedImageList(imageRepository, version, clusterBootstrapper)
M
Matt Rickard 已提交
61 62 63 64 65 66 67 68

	if err := CacheImages(images, constants.ImageCacheDir); err != nil {
		return errors.Wrapf(err, "Caching images for %s", clusterBootstrapper)
	}

	return nil
}

M
Matt Rickard 已提交
69 70 71
// CacheImages will cache images on the host
//
// The cache directory currently caches images using the imagename_tag
T
Tim Hockin 已提交
72 73
// For example, k8s.gcr.io/kube-addon-manager:v6.5 would be
// stored at $CACHE_DIR/k8s.gcr.io/kube-addon-manager_v6.5
M
Matt Rickard 已提交
74 75 76 77 78 79 80 81
func CacheImages(images []string, cacheDir string) error {
	var g errgroup.Group
	for _, image := range images {
		image := image
		g.Go(func() error {
			dst := filepath.Join(cacheDir, image)
			dst = sanitizeCacheDir(dst)
			if err := CacheImage(image, dst); err != nil {
T
tstromberg 已提交
82
				glog.Errorf("CacheImage %s -> %s failed: %v", image, dst, err)
M
Matt Rickard 已提交
83 84
				return errors.Wrapf(err, "caching image %s", dst)
			}
T
tstromberg 已提交
85
			glog.Infof("CacheImage %s -> %s succeeded", image, dst)
M
Matt Rickard 已提交
86 87 88 89 90 91 92 93 94 95
			return nil
		})
	}
	if err := g.Wait(); err != nil {
		return errors.Wrap(err, "caching images")
	}
	glog.Infoln("Successfully cached all images.")
	return nil
}

96
// LoadImages loads previously cached images into the container runtime
97
func LoadImages(cc *config.MachineConfig, cmd command.Runner, images []string, cacheDir string) error {
98 99
	glog.Infof("LoadImages start: %s", images)
	defer glog.Infof("LoadImages end")
M
Matt Rickard 已提交
100 101 102 103 104 105
	var g errgroup.Group
	for _, image := range images {
		image := image
		g.Go(func() error {
			src := filepath.Join(cacheDir, image)
			src = sanitizeCacheDir(src)
106
			if err := transferAndLoadImage(cmd, cc.KubernetesConfig, src); err != nil {
107
				glog.Warningf("Failed to load %s: %v", src, err)
M
Matt Rickard 已提交
108 109 110 111 112 113 114 115 116 117 118 119
				return errors.Wrapf(err, "loading image %s", src)
			}
			return nil
		})
	}
	if err := g.Wait(); err != nil {
		return errors.Wrap(err, "loading cached images")
	}
	glog.Infoln("Successfully loaded all cached images.")
	return nil
}

120
// CacheAndLoadImages caches and loads images to all profiles
P
Priya Wadhwa 已提交
121 122 123
func CacheAndLoadImages(images []string) error {
	if err := CacheImages(images, constants.ImageCacheDir); err != nil {
		return err
P
Priya Wadhwa 已提交
124
	}
P
Priya Wadhwa 已提交
125 126 127 128 129
	api, err := NewAPIClient()
	if err != nil {
		return err
	}
	defer api.Close()
130
	profiles, _, err := config.ListProfiles() // need to load image to all profiles
131
	if err != nil {
132
		return errors.Wrap(err, "list profiles")
133
	}
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
	for _, p := range profiles { // adding images to all the profiles
		pName := p.Name // capture the loop variable
		status, err := cluster.GetHostStatus(api, pName)
		if err != nil {
			glog.Warningf("skipping loading cache for profile %s", pName)
			glog.Errorf("error getting status for %s: %v", pName, err)
			continue // try next machine
		}
		if status == state.Running.String() { // the not running hosts will load on next start
			h, err := api.Load(pName)
			if err != nil {
				return err
			}
			cr, err := CommandRunner(h)
			if err != nil {
				return err
			}
151 152 153 154 155
			c, err := config.Load(pName)
			if err != nil {
				return err
			}
			err = LoadImages(c, cr, images, constants.ImageCacheDir)
156 157 158 159
			if err != nil {
				glog.Warningf("Failed to load cached images for profile %s. make sure the profile is running. %v", pName, err)
			}
		}
P
Priya Wadhwa 已提交
160
	}
161
	return err
P
Priya Wadhwa 已提交
162 163
}

M
Matt Rickard 已提交
164 165
// # ParseReference cannot have a : in the directory path
func sanitizeCacheDir(image string) string {
H
Hiroshi Nomura 已提交
166
	if runtime.GOOS == "windows" && hasWindowsDriveLetter(image) {
167
		// not sanitize Windows drive letter.
T
tstromberg 已提交
168 169 170
		s := image[:2] + strings.Replace(image[2:], ":", "_", -1)
		glog.Infof("windows sanitize: %s -> %s", image, s)
		return s
171
	}
M
Matt Rickard 已提交
172 173 174
	return strings.Replace(image, ":", "_", -1)
}

175 176 177 178 179 180
func hasWindowsDriveLetter(s string) bool {
	if len(s) < 3 {
		return false
	}

	drive := s[:3]
M
Mark Gibbons 已提交
181
	for _, b := range "CDEFGHIJKLMNOPQRSTUVWXYZABcdefghijklmnopqrstuvwxyzab" {
182 183 184 185 186 187 188 189
		if d := string(b) + ":"; drive == d+`\` || drive == d+`/` {
			return true
		}
	}

	return false
}

H
Hiroshi Nomura 已提交
190 191 192 193 194 195 196 197 198 199 200 201
// Replace a drive letter to a volume name.
func replaceWinDriveLetterToVolumeName(s string) (string, error) {
	vname, err := getWindowsVolumeName(s[:1])
	if err != nil {
		return "", err
	}
	path := vname + s[3:]

	return path, nil
}

func getWindowsVolumeNameCmd(d string) (string, error) {
H
Hiroshi Nomura 已提交
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
	cmd := exec.Command("wmic", "volume", "where", "DriveLetter = '"+d+":'", "get", "DeviceID")

	stdout, err := cmd.Output()
	if err != nil {
		return "", err
	}

	outs := strings.Split(strings.Replace(string(stdout), "\r", "", -1), "\n")

	var vname string
	for _, l := range outs {
		s := strings.TrimSpace(l)
		if strings.HasPrefix(s, `\\?\Volume{`) && strings.HasSuffix(s, `}\`) {
			vname = s
			break
		}
	}

	if vname == "" {
		return "", errors.New("failed to get a volume GUID")
	}

	return vname, nil
}

227 228
// transferAndLoadImage transfers and loads a single image from the cache
func transferAndLoadImage(cr command.Runner, k8s config.KubernetesConfig, src string) error {
229
	glog.Infof("Loading image from cache: %s", src)
M
Matt Rickard 已提交
230
	filename := filepath.Base(src)
231
	if _, err := os.Stat(src); err != nil {
232
		return err
M
Matt Rickard 已提交
233
	}
234 235
	dst := path.Join(loadRoot, filename)
	f, err := assets.NewFileAsset(src, loadRoot, filename, "0644")
M
Matt Rickard 已提交
236 237 238
	if err != nil {
		return errors.Wrapf(err, "creating copyable file asset: %s", filename)
	}
239
	if err := cr.Copy(f); err != nil {
M
Matt Rickard 已提交
240 241 242
		return errors.Wrap(err, "transferring cached image")
	}

243 244 245
	r, err := cruntime.New(cruntime.Config{Type: k8s.ContainerRuntime, Runner: cr})
	if err != nil {
		return errors.Wrap(err, "runtime")
M
Matt Rickard 已提交
246
	}
247 248
	loadImageLock.Lock()
	defer loadImageLock.Unlock()
M
Matt Rickard 已提交
249

250 251 252
	err = r.LoadImage(dst)
	if err != nil {
		return errors.Wrapf(err, "%s load %s", r.Name(), dst)
253 254
	}

M
Matt Rickard 已提交
255 256 257 258
	glog.Infof("Successfully loaded image %s from cache", src)
	return nil
}

259
// DeleteFromImageCacheDir deletes images from the cache
P
Priya Wadhwa 已提交
260 261 262
func DeleteFromImageCacheDir(images []string) error {
	for _, image := range images {
		path := filepath.Join(constants.ImageCacheDir, image)
K
kairen 已提交
263
		path = sanitizeCacheDir(path)
P
Priya Wadhwa 已提交
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
		glog.Infoln("Deleting image in cache at ", path)
		if err := os.Remove(path); err != nil {
			return err
		}
	}
	return cleanImageCacheDir()
}

func cleanImageCacheDir() error {
	err := filepath.Walk(constants.ImageCacheDir, func(path string, info os.FileInfo, err error) error {
		// If error is not nil, it's because the path was already deleted and doesn't exist
		// Move on to next path
		if err != nil {
			return nil
		}
		// Check if path is directory
		if !info.IsDir() {
			return nil
		}
		// If directory is empty, delete it
		entries, err := ioutil.ReadDir(path)
		if err != nil {
			return err
		}
		if len(entries) == 0 {
			if err = os.Remove(path); err != nil {
				return err
			}
		}
		return nil
	})
	return err
}

T
tstromberg 已提交
298
func getDstPath(dst string) (string, error) {
H
Hiroshi Nomura 已提交
299
	if runtime.GOOS == "windows" && hasWindowsDriveLetter(dst) {
H
Hiroshi Nomura 已提交
300
		// ParseReference does not support a Windows drive letter.
H
Hiroshi Nomura 已提交
301 302 303
		// Therefore, will replace the drive letter to a volume name.
		var err error
		if dst, err = replaceWinDriveLetterToVolumeName(dst); err != nil {
304
			return "", errors.Wrap(err, "parsing docker archive dst ref: replace a Win drive letter to a volume name")
H
Hiroshi Nomura 已提交
305 306
		}
	}
H
Hiroshi Nomura 已提交
307

308
	return dst, nil
M
Matt Rickard 已提交
309 310
}

311
// CacheImage caches an image
M
Matt Rickard 已提交
312
func CacheImage(image, dst string) error {
T
tstromberg 已提交
313 314 315 316 317 318
	start := time.Now()
	glog.Infof("CacheImage: %s -> %s", image, dst)
	defer func() {
		glog.Infof("CacheImage: %s -> %s completed in %s", image, dst, time.Since(start))
	}()

M
Matt Rickard 已提交
319
	if _, err := os.Stat(dst); err == nil {
T
tstromberg 已提交
320
		glog.Infof("%s exists", dst)
M
Matt Rickard 已提交
321 322 323
		return nil
	}

T
tstromberg 已提交
324
	dstPath, err := getDstPath(dst)
M
Matt Rickard 已提交
325
	if err != nil {
326
		return errors.Wrap(err, "getting destination path")
M
Matt Rickard 已提交
327 328
	}

329 330
	if err := os.MkdirAll(filepath.Dir(dstPath), 0777); err != nil {
		return errors.Wrapf(err, "making cache image directory: %s", dst)
M
Matt Rickard 已提交
331 332
	}

333
	ref, err := name.ParseReference(image, name.WeakValidation)
M
Matt Rickard 已提交
334
	if err != nil {
335
		return errors.Wrap(err, "creating docker image name")
M
Matt Rickard 已提交
336 337
	}

338
	img, err := retrieveImage(ref)
M
Matt Rickard 已提交
339
	if err != nil {
340
		return errors.Wrap(err, "fetching image")
M
Matt Rickard 已提交
341 342
	}

343
	glog.Infoln("OPENING: ", dstPath)
344
	f, err := ioutil.TempFile(filepath.Dir(dstPath), filepath.Base(dstPath)+".*.tmp")
345 346 347
	if err != nil {
		return err
	}
M
Medya Gh 已提交
348 349 350 351 352 353
	defer func() { // clean up temp files
		err := os.Remove(f.Name())
		if err != nil {
			glog.Infof("Failed to clean up the temp file %s : %v", f.Name(), err)
		}
	}()
P
Priya Wadhwa 已提交
354 355 356 357 358
	tag, err := name.NewTag(image, name.WeakValidation)
	if err != nil {
		return err
	}
	err = tarball.Write(tag, img, &tarball.WriteOptions{}, f)
359 360 361 362 363 364 365 366 367 368 369
	if err != nil {
		return err
	}
	err = f.Close()
	if err != nil {
		return err
	}
	err = os.Rename(f.Name(), dstPath)
	if err != nil {
		return err
	}
T
tstromberg 已提交
370
	glog.Infof("%s exists", dst)
371
	return nil
M
Matt Rickard 已提交
372
}
373 374

func retrieveImage(ref name.Reference) (v1.Image, error) {
T
tstromberg 已提交
375
	glog.Infof("retrieving image: %+v", ref)
376 377 378 379 380
	img, err := daemon.Image(ref)
	if err == nil {
		glog.Infof("found %s locally; caching", ref.Name())
		return img, err
	}
T
tstromberg 已提交
381 382
	glog.Infof("daemon image for %+v: %v", img, err)
	img, err = remote.Image(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain))
T
tstromberg 已提交
383 384 385 386 387 388 389
	if err == nil {
		return img, err
	}
	glog.Warningf("failed authn download for %+v (trying anon): %+v", ref, err)
	img, err = remote.Image(ref)
	if err != nil {
		glog.Warningf("failed anon download for %+v: %+v", ref, err)
T
tstromberg 已提交
390 391
	}
	return img, err
392
}