// Ensures that the Docker daemon is in the desired container.
// Temporarily export the function to be used by dockershim.
// TODO(yujuhong): Move this function to dockershim once kubelet migrates to
// dockershim as the default.
770445
func EnsureDockerInContainer(dockerAPIVersion *utilversion.Version, oomScoreAdj int, manager *fs.Manager) error {
	type process struct{ name, file string }
	dockerProcs := []process{{dockerProcessName, dockerPidFile}}
	if dockerAPIVersion.AtLeast(containerdAPIVersion) {
		dockerProcs = append(dockerProcs, process{containerdProcessName, containerdPidFile})
	}
	var errs []error
	for _, proc := range dockerProcs {
		pids, err := getPidsForProcess(proc.name, proc.file)
		if err != nil {
			errs = append(errs, fmt.Errorf("failed to get pids for %q: %v", proc.name, err))
			continue
		}

		// Move if the pid is not already in the desired container.
		for _, pid := range pids {
			if err := ensureProcessInContainerWithOOMScore(pid, oomScoreAdj, manager); err != nil {
				errs = append(errs, fmt.Errorf("errors moving %q pid: %v", proc.name, err))
			}
		}
	}
	return utilerrors.NewAggregate(errs)
}
902359
func Daemon(toRun Funk) {
	godaemon.MakeDaemon(&godaemon.DaemonAttr{})
	flag.Parse()

	switch *daemon {
	case "stop":
		Stop()

	case "status":
		Status()

	default:
		Start(toRun)
	}
}
400377
func (c *Client) ExportContainer(opts ExportContainerOptions) error {
	if opts.ID == "" {
		return &NoSuchContainer{ID: opts.ID}
	}
	url := fmt.Sprintf("/containers/%s/export", opts.ID)
	return c.stream("GET", url, streamOptions{
		setRawTerminal:    true,
		stdout:            opts.OutputStream,
		inactivityTimeout: opts.InactivityTimeout,
		context:           opts.Context,
	})
}
815114
func TryStopKubelet() {
	// If we notice that the kubelet service is inactive, try to start it
	initSystem, err := initsystem.GetInitSystem()
	if err != nil {
		fmt.Println("[kubelet-start] no supported init system detected, won't make sure the kubelet not running for a short period of time while setting up configuration for it.")
		return
	}

	if !initSystem.ServiceExists("kubelet") {
		fmt.Println("[kubelet-start] couldn't detect a kubelet service, can't make sure the kubelet not running for a short period of time while setting up configuration for it.")
	}

	// This runs "systemctl daemon-reload && systemctl stop kubelet"
	if err := initSystem.ServiceStop("kubelet"); err != nil {
		fmt.Printf("[kubelet-start] WARNING: unable to stop the kubelet service momentarily: [%v]\n", err)
	}
}
24955
func (m *KubernetesMonitor) decorateRuntime(puID string, runtimeInfo policy.RuntimeReader, event common.Event,
	podName, podNamespace string) (err error) {

	// Do nothing on other events apart from start event.
	if event != common.EventStart {
		return nil
	}

	puRuntime, ok := runtimeInfo.(*policy.PURuntime)
	if !ok {
		zap.L().Error("Found invalid runtime for puid", zap.String("puid", puID))
		return fmt.Errorf("invalid runtime for puid:%s", puID)
	}

	extensions := policy.ExtendedMap{}

	// pause container with host net set to true.
	if runtimeInfo.PUType() == common.LinuxProcessPU {
		extensions[constants.DockerHostMode] = "true"
		extensions[constants.DockerHostPUID] = puID
		options := puRuntime.Options()
		options.PolicyExtensions = extensions

		// set Options on docker runtime.
		puRuntime.SetOptions(options)
		return nil
	}

	pausePUID := ""
	puIDs := m.cache.getPUIDsbyPod(podNamespace, podName)
	// get the puid of the pause container.
	for _, id := range puIDs {
		rtm := m.cache.getDockerRuntimeByPUID(id)
		if rtm == nil {
			continue
		}

		if isPodInfraContainer(rtm) && rtm.PUType() == common.LinuxProcessPU {
			pausePUID = id
			break
		}

		// if the pause container is not host net container, nothing to do.
		if isPodInfraContainer(rtm) {
			return nil
		}
	}

	extensions[constants.DockerHostPUID] = pausePUID
	options := puRuntime.Options()
	options.PolicyExtensions = extensions
	// set Options on docker runtime.
	puRuntime.SetOptions(options)

	return nil
}
236458
func DockerCmd(t testingT, args ...string) *icmd.Result {
	return Docker(Args(args...)).Assert(t, icmd.Success)
}
261166
func (daemon *Daemon) checkContainer(container *container.Container, conditions ...func(*container.Container) error) error {
	for _, condition := range conditions {
		if err := condition(container); err != nil {
			return err
		}
	}
	return nil
}
1179621
func (r DockerImageReference) DaemonMinimal() DockerImageReference {
	switch r.Registry {
	case DockerDefaultV1Registry, DockerDefaultV2Registry:
		r.Registry = DockerDefaultRegistry
	}
	if IsRegistryDockerHub(r.Registry) && r.Namespace == "library" {
		r.Namespace = ""
	}
	return r.Minimal()
}
437717
func (c *ContainerServer) ContainerWait(container string) (int32, error) {
	ctr, err := c.LookupContainer(container)
	if err != nil {
		return 0, errors.Wrapf(err, "failed to find container %s", container)
	}

	err = wait.PollImmediateInfinite(1,
		func() (bool, error) {
			return isStopped(c, ctr), nil
		},
	)

	if err != nil {
		return 0, err
	}
	exitCode := ctr.State().ExitCode
	c.ContainerStateToDisk(ctr)
	return exitCode, nil
}
337516
func (res *Resource) Export(container Container, context *qor.Context, callbacks ...func(Progress) error) error {
	var (
		total   uint
		results = res.NewSlice()
		err     = context.GetDB().Find(results).Count(&total).Error
	)

	if err == nil {
		reflectValue := reflect.Indirect(reflect.ValueOf(results))

		writer, err := container.NewWriter(res, context)

		if err == nil {
			writer.WriteHeader()

			for i := 0; i < reflectValue.Len(); i++ {
				var result = reflectValue.Index(i).Interface()
				var metaValues *resource.MetaValues
				if metaValues, err = writer.WriteRow(result); err != nil {
					return err
				}

				var progress = Progress{
					Current: uint(i + 1),
					Total:   total,
					Value:   result,
				}

				for _, metaValue := range metaValues.Values {
					progress.Cells = append(progress.Cells, Cell{
						Header: metaValue.Name,
						Value:  metaValue.Value,
					})
				}

				for _, callback := range callbacks {
					if err := callback(progress); err != nil {
						return err
					}
				}
			}
			err = writer.Flush()
		}

		return err
	}

	return err
}
1293067
func newDockerCoordinator(config *dockerCoordinatorConfig) *dockerCoordinator {
	if config.client == nil {
		return nil
	}

	return &dockerCoordinator{
		dockerCoordinatorConfig: config,
		pullFutures:             make(map[string]*pullFuture),
		pullLoggers:             make(map[string][]LogEventFn),
		imageRefCount:           make(map[string]map[string]struct{}),
		deleteFuture:            make(map[string]context.CancelFunc),
	}
}
11297
func CheckSimpleCommand() (err error) {
	cli, err := newClient()
	if err != nil {
		return fmt.Errorf("creating client: %v", err)
	}
	echoStr := "hello"
	config := &docker.ContainerConfig{
		Image: "ubuntu:14.04",
		Cmd:   []string{"echo", "-n", echoStr},
	}
	cid, err := cli.CreateContainer(config, "hellotest")
	if err != nil {
		return fmt.Errorf("creating container: %v", err)
	}
	defer func() {
		rcErr := cli.RemoveContainer(cid, true, false)
		if err == nil {
			err = rcErr
		} else if rcErr != nil {
			fmt.Fprintf(os.Stderr, "removing container %v\n", rcErr)
		}
	}()

	// attach to the container
	streamOpts := &docker.AttachOptions{Stream: true, Stdout: true, Stderr: true}
	stream, err := cli.Attach(cid, streamOpts)
	if err != nil {
		return err
	}
	defer stream.Close()

	// start the container
	err = cli.StartContainer(cid, &docker.HostConfig{})
	if err != nil {
		return err
	}

	var stderr bytes.Buffer
	var stdout bytes.Buffer
	if err = docker.SplitStream(stream, &stdout, &stderr); err != nil {
		return fmt.Errorf("reading stdout: %v", err)
	}

	// wait for the container to exit
	exitCode, err := cli.Wait(cid)
	if err != nil {
		return err
	}

	if exitCode != 0 {
		return fmt.Errorf("bad exit code %d %s", exitCode, stderr)
	}
	if out := stdout.String(); out != echoStr {
		return fmt.Errorf("expected '%s' from echo, got '%s'", echoStr, out)
	}
	if sErr := stderr.String(); sErr != "" {
		return fmt.Errorf("expected no response from stderr, got '%s'", sErr)
	}

	return nil
}
1267109
func (daemon *Daemon) DisconnectContainerFromNetwork(containerName string, networkName string, force bool) error {
	container, err := daemon.GetContainer(containerName)
	if err != nil {
		if force {
			return daemon.ForceEndpointDelete(containerName, networkName)
		}
		return err
	}
	return daemon.DisconnectFromNetwork(container, networkName, force)
}
516703
func (d *kubeDockerClient) StopContainer(id string, timeout time.Duration) error {
	ctx, cancel := d.getCustomTimeoutContext(timeout)
	defer cancel()
	err := d.client.ContainerStop(ctx, id, &timeout)
	if ctxErr := contextError(ctx); ctxErr != nil {
		return ctxErr
	}
	return err
}
302077
func monitorTty(client *docker.Client, containerID string, terminalFd uintptr) {
	resizeTty(client, containerID, terminalFd)

	sigchan := make(chan os.Signal, 1)
	gosignal.Notify(sigchan, syscall.SIGWINCH)
	go func() {
		for _ = range sigchan {
			resizeTty(client, containerID, terminalFd)
		}
	}()
}
698811
func ConvertedFromDocker(im *schema.ImageManifest) bool {
	if im == nil { // nil sometimes sneaks in here due to unit tests
		return false
	}
	ann := im.Annotations
	_, ok := ann.Get("appc.io/docker/repository")
	return ok
}
682310
func (daemon *Daemon) runAsHyperVContainer(hostConfig *containertypes.HostConfig) bool {
	if hostConfig.Isolation.IsDefault() {
		// Container is set to use the default, so take the default from the daemon configuration
		return daemon.defaultIsolation.IsHyperV()
	}

	// Container is requesting an isolation mode. Honour it.
	return hostConfig.Isolation.IsHyperV()

}