oci.go 20.4 KB
Newer Older
M
Medya Gh 已提交
1 2
/*
Copyright 2019 The Kubernetes Authors All rights reserved.
M
Medya Gh 已提交
3

M
Medya Gh 已提交
4 5 6
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
M
Medya Gh 已提交
7

M
Medya Gh 已提交
8
    http://www.apache.org/licenses/LICENSE-2.0
M
Medya Gh 已提交
9

M
Medya Gh 已提交
10 11 12 13 14 15 16 17 18 19
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 oci

import (
20
	"context"
M
Medya Gh 已提交
21
	"os"
M
Medya Gh 已提交
22
	"time"
M
Medya Gh 已提交
23 24 25 26

	"bufio"
	"bytes"

M
Medya Gh 已提交
27
	"github.com/docker/machine/libmachine/state"
M
Medya Gh 已提交
28
	"github.com/golang/glog"
M
Medya Gh 已提交
29
	"github.com/pkg/errors"
M
Medya Gh 已提交
30
	"k8s.io/minikube/pkg/minikube/constants"
31
	"k8s.io/minikube/pkg/minikube/out"
32
	"k8s.io/minikube/pkg/util/retry"
M
Medya Gh 已提交
33 34 35

	"fmt"
	"os/exec"
36
	"runtime"
37
	"strconv"
38
	"strings"
M
Medya Gh 已提交
39 40
)

M
Medya Gh 已提交
41
// DeleteContainersByLabel deletes all containers that have a specific label
42
// if there no containers found with the given 	label, it will return nil
43
func DeleteContainersByLabel(ociBin string, label string) []error {
44
	var deleteErrs []error
45

46
	cs, err := ListContainersByLabel(ociBin, label)
47
	if err != nil {
M
Medya Gh 已提交
48
		return []error{fmt.Errorf("listing containers by label %q", label)}
49
	}
50

M
Medya Gh 已提交
51 52 53
	if len(cs) == 0 {
		return nil
	}
54

M
lint  
Medya Gh 已提交
55
	for _, c := range cs {
56
		_, err := ContainerStatus(ociBin, c)
M
Medya Gh 已提交
57
		// only try to delete if docker/podman inspect returns
M
Medya Gh 已提交
58
		// if it doesn't it means docker daemon is stuck and needs restart
M
Medya Gh 已提交
59
		if err != nil {
M
Medya Gh 已提交
60
			deleteErrs = append(deleteErrs, errors.Wrapf(err, "delete container %s: %s daemon is stuck. please try again!", c, ociBin))
M
Medya Gh 已提交
61
			glog.Errorf("%s daemon seems to be stuck. Please try restarting your %s. :%v", ociBin, ociBin, err)
M
Medya Gh 已提交
62 63
			continue
		}
64
		if err := ShutDown(ociBin, c); err != nil {
M
lint  
Medya Gh 已提交
65
			glog.Infof("couldn't shut down %s (might be okay): %v ", c, err)
M
Medya Gh 已提交
66
		}
M
Medya Gh 已提交
67

68
		if _, err := runCmd(exec.Command(ociBin, "rm", "-f", "-v", c)); err != nil {
M
Medya Gh 已提交
69
			deleteErrs = append(deleteErrs, errors.Wrapf(err, "delete container %s: output %s", c, err))
70
		}
M
Medya Gh 已提交
71

72 73 74 75
	}
	return deleteErrs
}

M
Medya Gh 已提交
76
// DeleteContainer deletes a container by ID or Name
77 78
func DeleteContainer(ociBin string, name string) error {
	_, err := ContainerStatus(ociBin, name)
79
	if err == context.DeadlineExceeded {
P
Priya Wadhwa 已提交
80
		out.WarningT("{{.ocibin}} is taking an unsually long time to respond, consider restarting {{.ocibin}}", out.V{"ociBin": ociBin})
81 82
	} else if err != nil {
		glog.Warningf("error getting container status, will try to delete anyways: %v", err)
M
Medya Gh 已提交
83 84
	}
	// try to delete anyways
85
	if err := ShutDown(ociBin, name); err != nil {
M
lint  
Medya Gh 已提交
86
		glog.Infof("couldn't shut down %s (might be okay): %v ", name, err)
M
Medya Gh 已提交
87
	}
M
Medya Gh 已提交
88

P
compile  
Priya Wadhwa 已提交
89
	if err := removeNetwork(name); err != nil {
P
cleanup  
Priya Wadhwa 已提交
90 91 92
		glog.Warningf("error deleting network: %v", err)
	}

93
	if _, err := runCmd(exec.Command(ociBin, "rm", "-f", "-v", name)); err != nil {
M
Medya Gh 已提交
94
		return errors.Wrapf(err, "delete %s", name)
M
Medya Gh 已提交
95 96 97 98
	}
	return nil
}

P
Priya Wadhwa 已提交
99
// PrepareContainerNode sets up the container node before CreateContainerNode is called.
100
// For the container runtime, it creates a volume which will be mounted into kic
P
Priya Wadhwa 已提交
101
func PrepareContainerNode(p CreateParams) error {
102
	if err := createVolume(p.OCIBinary, p.Name, p.Name); err != nil {
103 104
		return errors.Wrapf(err, "creating volume for %s container", p.Name)
	}
105
	glog.Infof("Successfully created a %s volume %s", p.OCIBinary, p.Name)
106 107 108 109
	if err := prepareVolume(p.OCIBinary, p.Image, p.Name); err != nil {
		return errors.Wrapf(err, "preparing volume for %s container", p.Name)
	}
	glog.Infof("Successfully prepared a %s volume %s", p.OCIBinary, p.Name)
110 111 112
	return nil
}

M
Medya Gh 已提交
113 114
// CreateContainerNode creates a new container node
func CreateContainerNode(p CreateParams) error {
115 116 117 118 119 120 121
	// on windows os, if docker desktop is using Windows Containers. Exit early with error
	if p.OCIBinary == Docker && runtime.GOOS == "windows" {
		info, err := DaemonInfo(p.OCIBinary)
		if info.OSType == "windows" {
			return ErrWindowsContainers
		}
		if err != nil {
M
Medya Gh 已提交
122 123
			glog.Warningf("error getting dameon info: %v", err)
			return errors.Wrap(err, "daemon info")
124 125 126
		}
	}

M
Medya Gh 已提交
127 128 129 130 131 132 133 134 135
	runArgs := []string{
		"-d", // run the container detached
		"-t", // allocate a tty for entrypoint logs
		// running containers in a container requires privileged
		// NOTE: we could try to replicate this with --cap-add, and use less
		// privileges, but this flag also changes some mounts that are necessary
		// including some ones docker would otherwise do by default.
		// for now this is what we want. in the future we may revisit this.
		"--privileged",
M
Medya Gh 已提交
136
		"--security-opt", "seccomp=unconfined", //  ignore seccomp
M
Medya Gh 已提交
137 138 139 140 141 142 143
		"--tmpfs", "/tmp", // various things depend on working /tmp
		"--tmpfs", "/run", // systemd wants a writable /run
		// logs,pods be stroed on  filesystem vs inside container,
		// some k8s things want /lib/modules
		"-v", "/lib/modules:/lib/modules:ro",
		"--hostname", p.Name, // make hostname match container name
		"--name", p.Name, // ... and set the container name
144
		"--label", fmt.Sprintf("%s=%s", CreatedByLabelKey, "true"),
M
Medya Gh 已提交
145 146 147
		// label the node with the cluster ID
		"--label", p.ClusterLabel,
		// label the node with the role ID
148
		"--label", fmt.Sprintf("%s=%s", nodeRoleLabelKey, p.Role),
S
Sharif Elgamal 已提交
149 150
		// label th enode wuth the node ID
		"--label", p.NodeLabel,
M
Medya Ghazizadeh 已提交
151 152 153 154
	}

	if p.OCIBinary == Podman { // enable execing in /var
		// podman mounts var/lib with no-exec by default  https://github.com/containers/libpod/issues/5103
155
		runArgs = append(runArgs, "--volume", fmt.Sprintf("%s:/var:exec", p.Name))
M
Medya Ghazizadeh 已提交
156 157
	}
	if p.OCIBinary == Docker {
158 159 160 161 162 163
		// on linux, we can provide a static IP for docker
		if runtime.GOOS == "linux" && p.Network != "" && p.IP != "" {
			runArgs = append(runArgs, "--network", p.Network)
			runArgs = append(runArgs, "--ip", p.IP)
		}

164
		runArgs = append(runArgs, "--volume", fmt.Sprintf("%s:/var", p.Name))
165 166
		// ignore apparmore github actions docker: https://github.com/kubernetes/minikube/issues/7624
		runArgs = append(runArgs, "--security-opt", "apparmor=unconfined")
M
Medya Ghazizadeh 已提交
167 168
	}

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
	runArgs = append(runArgs, fmt.Sprintf("--cpus=%s", p.CPUs))

	memcgSwap := true
	if runtime.GOOS == "linux" {
		if _, err := os.Stat("/sys/fs/cgroup/memory/memsw.limit_in_bytes"); os.IsNotExist(err) {
			// requires CONFIG_MEMCG_SWAP_ENABLED or cgroup_enable=memory in grub
			glog.Warning("Your kernel does not support swap limit capabilities or the cgroup is not mounted.")
			memcgSwap = false
		}
	}

	if p.OCIBinary == Podman && memcgSwap { // swap is required for memory
		runArgs = append(runArgs, fmt.Sprintf("--memory=%s", p.Memory))
	}
	if p.OCIBinary == Docker { // swap is only required for --memory-swap
		runArgs = append(runArgs, fmt.Sprintf("--memory=%s", p.Memory))
	}
186

187 188 189 190 191 192 193 194 195 196
	// https://www.freedesktop.org/wiki/Software/systemd/ContainerInterface/
	var virtualization string
	if p.OCIBinary == Podman {
		virtualization = "podman" // VIRTUALIZATION_PODMAN
	}
	if p.OCIBinary == Docker {
		virtualization = "docker" // VIRTUALIZATION_DOCKER
	}
	runArgs = append(runArgs, "-e", fmt.Sprintf("%s=%s", "container", virtualization))

M
Medya Gh 已提交
197 198 199 200 201 202 203
	for key, val := range p.Envs {
		runArgs = append(runArgs, "-e", fmt.Sprintf("%s=%s", key, val))
	}

	// adds node specific args
	runArgs = append(runArgs, p.ExtraArgs...)

204
	if enabled := isUsernsRemapEnabled(p.OCIBinary); enabled {
M
Medya Gh 已提交
205 206 207 208 209
		// We need this argument in order to make this command work
		// in systems that have userns-remap enabled on the docker daemon
		runArgs = append(runArgs, "--userns=host")
	}

210
	if err := createContainer(p.OCIBinary, p.Image, withRunArgs(runArgs...), withMounts(p.Mounts), withPortMappings(p.PortMappings)); err != nil {
T
Thomas Stromberg 已提交
211
		return errors.Wrap(err, "create container")
M
Medya Gh 已提交
212
	}
213 214

	checkRunning := func() error {
215
		r, err := ContainerRunning(p.OCIBinary, p.Name)
216 217 218 219 220 221
		if err != nil {
			return fmt.Errorf("temporary error checking running for %q : %v", p.Name, err)
		}
		if !r {
			return fmt.Errorf("temporary error created container %q is not running yet", p.Name)
		}
222
		s, err := ContainerStatus(p.OCIBinary, p.Name)
223 224 225
		if err != nil {
			return fmt.Errorf("temporary error checking status for %q : %v", p.Name, err)
		}
M
Medya Gh 已提交
226
		if s != state.Running {
227 228
			return fmt.Errorf("temporary error created container %q is not running yet", p.Name)
		}
229 230 231
		if !iptablesFileExists(p.OCIBinary, p.Name) {
			return fmt.Errorf("iptables file doesn't exist, see #8179")
		}
M
Medya Ghazizadeh 已提交
232
		glog.Infof("the created container %q has a running status.", p.Name)
233 234 235
		return nil
	}

236
	if err := retry.Expo(checkRunning, 15*time.Millisecond, 25*time.Second); err != nil {
237
		excerpt := LogContainerDebug(p.OCIBinary, p.Name)
M
Medya Gh 已提交
238 239 240 241
		_, err := DaemonInfo(p.OCIBinary)
		if err != nil {
			return errors.Wrapf(ErrDaemonInfo, "container name %q", p.Name)
		}
242 243

		return errors.Wrapf(ErrExitedUnexpectedly, "container name %q: log: %s", p.Name, excerpt)
244 245
	}

M
Medya Gh 已提交
246 247 248 249
	return nil
}

// CreateContainer creates a container with "docker/podman run"
250
func createContainer(ociBin string, image string, opts ...createOpt) error {
M
Medya Gh 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263
	o := &createOpts{}
	for _, opt := range opts {
		o = opt(o)
	}
	// convert mounts to container run args
	runArgs := o.RunArgs
	for _, mount := range o.Mounts {
		runArgs = append(runArgs, generateMountBindings(mount)...)
	}
	for _, portMapping := range o.PortMappings {
		runArgs = append(runArgs, generatePortMappings(portMapping)...)
	}
	// construct the actual docker run argv
264
	args := []string{"run"}
265

M
Medya Ghazizadeh 已提交
266
	// to run nested container from privileged container in podman https://bugzilla.redhat.com/show_bug.cgi?id=1687713
267
	// only add when running locally (linux), when running remotely it needs to be configured on server in libpod.conf
268
	if ociBin == Podman && runtime.GOOS == "linux" {
M
Medya Ghazizadeh 已提交
269 270
		args = append(args, "--cgroup-manager", "cgroupfs")
	}
271

M
Medya Gh 已提交
272 273 274 275
	args = append(args, runArgs...)
	args = append(args, image)
	args = append(args, o.ContainerArgs...)

276 277 278 279 280
	if rr, err := runCmd(exec.Command(ociBin, args...)); err != nil {
		// full error: docker: Error response from daemon: Range of CPUs is from 0.01 to 8.00, as there are only 8 CPUs available.
		if strings.Contains(rr.Output(), "Range of CPUs is from") && strings.Contains(rr.Output(), "CPUs available") { // CPUs available
			return ErrCPUCountLimit
		}
281
		return err
M
Medya Gh 已提交
282
	}
283

T
Thomas Stromberg 已提交
284
	return nil
M
Medya Gh 已提交
285 286
}

287 288 289 290 291 292
// StartContainer starts a container with "docker/podman start"
func StartContainer(ociBin string, container string) error {
	// construct the actual docker start argv
	args := []string{"start"}

	// to run nested container from privileged container in podman https://bugzilla.redhat.com/show_bug.cgi?id=1687713
293
	// only add when running locally (linux), when running remotely it needs to be configured on server in libpod.conf
294
	if ociBin == Podman && runtime.GOOS == "linux" {
295 296 297 298 299
		args = append(args, "--cgroup-manager", "cgroupfs")
	}

	args = append(args, container)

300
	if _, err := runCmd(exec.Command(ociBin, args...)); err != nil {
301
		return err
M
Medya Gh 已提交
302
	}
303

T
Thomas Stromberg 已提交
304
	return nil
M
Medya Gh 已提交
305 306
}

M
Medya Gh 已提交
307
// ContainerID returns id of a container name
308
func ContainerID(ociBin string, nameOrID string) (string, error) {
309
	rr, err := runCmd(exec.Command(ociBin, "container", "inspect", "-f", "{{.Id}}", nameOrID))
M
Medya Gh 已提交
310
	if err != nil { // don't return error if not found, only return empty string
311 312 313 314 315 316
		if strings.Contains(rr.Stdout.String(), "Error: No such object:") ||
			strings.Contains(rr.Stdout.String(), "Error: No such container:") ||
			strings.Contains(rr.Stdout.String(), "unable to find") ||
			strings.Contains(rr.Stdout.String(), "Error: error inspecting object") ||
			strings.Contains(rr.Stdout.String(), "Error: error looking up container") ||
			strings.Contains(rr.Stdout.String(), "no such container") {
M
Medya Gh 已提交
317 318
			err = nil
		}
M
Medya Gh 已提交
319
		return "", err
M
Medya Gh 已提交
320
	}
M
Medya Gh 已提交
321
	return rr.Stdout.String(), nil
322
}
323

324
// ContainerExists checks if container name exists (either running or exited)
325
func ContainerExists(ociBin string, name string, warnSlow ...bool) (bool, error) {
M
Medya Gh 已提交
326
	rr, err := runCmd(exec.Command(ociBin, "ps", "-a", "--format", "{{.Names}}"), warnSlow...)
M
Medya Gh 已提交
327
	if err != nil {
M
Medya Gh 已提交
328
		return false, err
M
Medya Gh 已提交
329
	}
330

M
Medya Gh 已提交
331
	containers := strings.Split(rr.Stdout.String(), "\n")
M
Medya Gh 已提交
332 333 334 335 336
	for _, c := range containers {
		if strings.TrimSpace(c) == name {
			return true, nil
		}
	}
337

M
Medya Gh 已提交
338 339 340
	return false, nil
}

M
Medya Gh 已提交
341 342
// IsCreatedByMinikube returns true if the container was created by minikube
// with default assumption that it is not created by minikube when we don't know for sure
343
func IsCreatedByMinikube(ociBin string, nameOrID string) bool {
344
	rr, err := runCmd(exec.Command(ociBin, "container", "inspect", nameOrID, "--format", "{{.Config.Labels}}"))
M
Medya Gh 已提交
345
	if err != nil {
M
Medya Gh 已提交
346 347
		return false
	}
348

M
Medya Gh 已提交
349
	if strings.Contains(rr.Stdout.String(), fmt.Sprintf("%s:true", CreatedByLabelKey)) {
M
Medya Gh 已提交
350
		return true
M
Medya Gh 已提交
351
	}
352

M
Medya Gh 已提交
353
	return false
M
Medya Gh 已提交
354 355
}

356 357 358
// ListOwnedContainers lists all the containres that kic driver created on user's machine using a label
func ListOwnedContainers(ociBin string) ([]string, error) {
	return ListContainersByLabel(ociBin, ProfileLabelKey)
M
Medya Gh 已提交
359 360 361
}

// inspect return low-level information on containers
362
func inspect(ociBin string, containerNameOrID, format string) ([]string, error) {
363
	cmd := exec.Command(ociBin, "container", "inspect",
M
Medya Gh 已提交
364 365 366 367 368
		"-f", format,
		containerNameOrID) // ... against the "node" container
	var buff bytes.Buffer
	cmd.Stdout = &buff
	cmd.Stderr = &buff
M
Medya Gh 已提交
369
	_, err := runCmd(cmd)
M
Medya Gh 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
	scanner := bufio.NewScanner(&buff)
	var lines []string
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	return lines, err
}

/*
This is adapated from:
https://github.com/kubernetes/kubernetes/blob/07a5488b2a8f67add543da72e8819407d8314204/pkg/kubelet/dockershim/helpers.go#L115-L155
*/
// generateMountBindings converts the mount list to a list of strings that
// can be understood by docker
// '<HostPath>:<ContainerPath>[:options]', where 'options'
// is a comma-separated list of the following strings:
// 'ro', if the path is read only
// 'Z', if the volume requires SELinux relabeling
M
Medya Gh 已提交
388
func generateMountBindings(mounts ...Mount) []string {
M
Medya Gh 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
	result := make([]string, 0, len(mounts))
	for _, m := range mounts {
		bind := fmt.Sprintf("%s:%s", m.HostPath, m.ContainerPath)
		var attrs []string
		if m.Readonly {
			attrs = append(attrs, "ro")
		}
		// Only request relabeling if the pod provides an SELinux context. If the pod
		// does not provide an SELinux context relabeling will label the volume with
		// the container's randomly allocated MCS label. This would restrict access
		// to the volume to the container which mounts it first.
		if m.SelinuxRelabel {
			attrs = append(attrs, "Z")
		}
		switch m.Propagation {
M
Medya Gh 已提交
404
		case MountPropagationNone:
M
Medya Gh 已提交
405
			// noop, private is default
M
Medya Gh 已提交
406
		case MountPropagationBidirectional:
M
Medya Gh 已提交
407
			attrs = append(attrs, "rshared")
M
Medya Gh 已提交
408
		case MountPropagationHostToContainer:
M
Medya Gh 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
			attrs = append(attrs, "rslave")
		default:
			// Falls back to "private"
		}

		if len(attrs) > 0 {
			bind = fmt.Sprintf("%s:%s", bind, strings.Join(attrs, ","))
		}
		// our specific modification is the following line: make this a docker flag
		bind = fmt.Sprintf("--volume=%s", bind)
		result = append(result, bind)
	}
	return result
}

M
Medya Gh 已提交
424
// isUsernsRemapEnabled checks if userns-remap is enabled in docker
425 426
func isUsernsRemapEnabled(ociBin string) bool {
	cmd := exec.Command(ociBin, "info", "--format", "'{{json .SecurityOptions}}'")
M
Medya Gh 已提交
427 428 429
	var buff bytes.Buffer
	cmd.Stdout = &buff
	cmd.Stderr = &buff
M
Medya Gh 已提交
430

M
Medya Gh 已提交
431
	if _, err := runCmd(cmd); err != nil {
T
Thomas Stromberg 已提交
432
		return false
433 434
	}

M
Medya Gh 已提交
435 436
	scanner := bufio.NewScanner(&buff)
	var lines []string
437

M
Medya Gh 已提交
438 439 440
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
441

M
Medya Gh 已提交
442 443
	if len(lines) > 0 {
		if strings.Contains(lines[0], "name=userns") {
T
Thomas Stromberg 已提交
444
			return true
M
Medya Gh 已提交
445 446
		}
	}
447

T
Thomas Stromberg 已提交
448
	return false
M
Medya Gh 已提交
449 450
}

M
Medya Gh 已提交
451
func generatePortMappings(portMappings ...PortMapping) []string {
M
Medya Gh 已提交
452 453
	result := make([]string, 0, len(portMappings))
	for _, pm := range portMappings {
454 455 456
		// let docker pick a host port by leaving it as ::
		// example --publish=127.0.0.17::8443 will get a random host port for 8443
		publish := fmt.Sprintf("--publish=%s::%d", pm.ListenAddress, pm.ContainerPort)
M
Medya Gh 已提交
457 458 459 460 461
		result = append(result, publish)
	}
	return result
}

M
Medya Gh 已提交
462
// withRunArgs sets the args for docker run
M
Medya Gh 已提交
463
// as in the args portion of `docker run args... image containerArgs...`
M
Medya Gh 已提交
464
func withRunArgs(args ...string) createOpt {
M
Medya Gh 已提交
465 466 467 468 469 470
	return func(r *createOpts) *createOpts {
		r.RunArgs = args
		return r
	}
}

M
Medya Gh 已提交
471 472
// withMounts sets the container mounts
func withMounts(mounts []Mount) createOpt {
M
Medya Gh 已提交
473 474 475 476 477 478
	return func(r *createOpts) *createOpts {
		r.Mounts = mounts
		return r
	}
}

M
Medya Gh 已提交
479 480
// withPortMappings sets the container port mappings to the host
func withPortMappings(portMappings []PortMapping) createOpt {
M
Medya Gh 已提交
481 482 483 484 485 486
	return func(r *createOpts) *createOpts {
		r.PortMappings = portMappings
		return r
	}
}

M
Medya Gh 已提交
487
// ListContainersByLabel returns all the container names with a specified label
488 489
func ListContainersByLabel(ociBin string, label string, warnSlow ...bool) ([]string, error) {
	rr, err := runCmd(exec.Command(ociBin, "ps", "-a", "--filter", fmt.Sprintf("label=%s", label), "--format", "{{.Names}}"), warnSlow...)
490 491 492
	if err != nil {
		return nil, err
	}
M
Medya Gh 已提交
493
	s := bufio.NewScanner(bytes.NewReader(rr.Stdout.Bytes()))
494
	var names []string
495 496 497 498
	for s.Scan() {
		n := strings.TrimSpace(s.Text())
		if n != "" {
			names = append(names, n)
M
Medya Gh 已提交
499
		}
M
Medya Gh 已提交
500
	}
501
	return names, err
M
Medya Gh 已提交
502
}
M
Medya Gh 已提交
503 504 505 506 507 508

// PointToHostDockerDaemon will unset env variables that point to docker inside minikube
// to make sure it points to the docker daemon installed by user.
func PointToHostDockerDaemon() error {
	p := os.Getenv(constants.MinikubeActiveDockerdEnv)
	if p != "" {
M
Medya Gh 已提交
509
		glog.Infof("shell is pointing to dockerd inside minikube. will unset to use host")
M
Medya Gh 已提交
510 511 512 513 514 515 516 517 518 519 520 521
	}

	for i := range constants.DockerDaemonEnvs {
		e := constants.DockerDaemonEnvs[i]
		err := os.Setenv(e, "")
		if err != nil {
			return errors.Wrapf(err, "resetting %s env", e)
		}

	}
	return nil
}
M
Medya Gh 已提交
522

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
// PointToHostPodman will unset env variables that point to podman inside minikube
func PointToHostPodman() error {
	p := os.Getenv(constants.MinikubeActivePodmanEnv)
	if p != "" {
		glog.Infof("shell is pointing to podman inside minikube. will unset to use host")
	}

	for i := range constants.PodmanRemoteEnvs {
		e := constants.PodmanRemoteEnvs[i]
		err := os.Setenv(e, "")
		if err != nil {
			return errors.Wrapf(err, "resetting %s env", e)
		}

	}
	return nil
}

541
// ContainerRunning returns running state of a container
542
func ContainerRunning(ociBin string, name string, warnSlow ...bool) (bool, error) {
543
	rr, err := runCmd(exec.Command(ociBin, "container", "inspect", name, "--format={{.State.Running}}"), warnSlow...)
544 545 546
	if err != nil {
		return false, err
	}
547
	return strconv.ParseBool(strings.TrimSpace(rr.Stdout.String()))
548 549
}

M
Medya Gh 已提交
550
// ContainerStatus returns status of a container running,exited,...
551
func ContainerStatus(ociBin string, name string, warnSlow ...bool) (state.State, error) {
552
	cmd := exec.Command(ociBin, "container", "inspect", name, "--format={{.State.Status}}")
M
Medya Gh 已提交
553
	rr, err := runCmd(cmd, warnSlow...)
M
Medya Gh 已提交
554
	o := strings.TrimSpace(rr.Stdout.String())
M
Medya Gh 已提交
555
	switch o {
556 557
	case "configured":
		return state.Stopped, nil
M
Medya Gh 已提交
558 559 560 561 562 563 564 565 566 567 568 569 570
	case "running":
		return state.Running, nil
	case "exited":
		return state.Stopped, nil
	case "paused":
		return state.Paused, nil
	case "restarting":
		return state.Starting, nil
	case "dead":
		return state.Error, nil
	default:
		return state.None, errors.Wrapf(err, "unknown state %q", name)
	}
M
Medya Gh 已提交
571
}
M
Medya Gh 已提交
572

M
Medya Gh 已提交
573
// ShutDown will run command to shut down the container
M
Medya Gh 已提交
574 575
// to ensure the containers process and networking bindings are all closed
// to avoid containers getting stuck before delete https://github.com/kubernetes/minikube/issues/7657
576 577
func ShutDown(ociBin string, name string) error {
	if _, err := runCmd(exec.Command(ociBin, "exec", "--privileged", "-t", name, "/bin/bash", "-c", "sudo init 0")); err != nil {
M
Medya Gh 已提交
578
		glog.Infof("error shutdown %s: %v", name, err)
M
Medya Gh 已提交
579
	}
M
Medya Gh 已提交
580 581
	// helps with allowing docker realize the container is exited and report its status correctly.
	time.Sleep(time.Second * 1)
M
lint  
Medya Gh 已提交
582 583
	// wait till it is stoped
	stopped := func() error {
584
		st, err := ContainerStatus(ociBin, name)
M
Medya Gh 已提交
585
		if st == state.Stopped {
M
Medya Gh 已提交
586
			glog.Infof("container %s status is %s", name, st)
M
lint  
Medya Gh 已提交
587 588 589 590 591 592 593 594 595 596 597 598
			return nil
		}
		if err != nil {
			glog.Infof("temporary error verifying shutdown: %v", err)
		}
		glog.Infof("temporary error: container %s status is %s but expect it to be exited", name, st)
		return errors.Wrap(err, "couldn't verify cointainer is exited. %v")
	}
	if err := retry.Expo(stopped, time.Millisecond*500, time.Second*20); err != nil {
		return errors.Wrap(err, "verify shutdown")
	}
	glog.Infof("Successfully shutdown container %s", name)
M
Medya Gh 已提交
599 600
	return nil
}
601 602 603

// iptablesFileExists checks if /var/lib/dpkg/alternatives/iptables exists in minikube
// this file is necessary for the entrypoint script to pass
P
Priya Wadhwa 已提交
604
// TODO: https://github.com/kubernetes/minikube/issues/8179
605 606 607 608 609 610 611 612 613
func iptablesFileExists(ociBin string, nameOrID string) bool {
	file := "/var/lib/dpkg/alternatives/iptables"
	_, err := runCmd(exec.Command(ociBin, "exec", nameOrID, "stat", file), false)
	if err != nil {
		glog.Warningf("error checking if %s exists: %v", file, err)
		return false
	}
	return true
}