// StartDocker - Start a docker container
343636
func StartDocker(cfg *ProcessConfig, masterAddress, workerAddress, dockerRegistry, controller string) (*exec.Cmd, error) {
	logger := plog.WithFields(log.Fields{
		"masteraddress":   masterAddress,
		"delegateaddress": workerAddress,
		"serviceid":       cfg.ServiceID,
	})

	// look up the service on the master
	masterClient, err := master.NewClient(masterAddress)
	if err != nil {
		logger.WithError(err).Error("Could not connect to the master server")
		return nil, err
	}
	defer masterClient.Close()
	logger.Info("Connected to master")

	svc, err := masterClient.GetService(cfg.ServiceID)
	if err != nil {
		logger.WithError(err).Error("Could not get services")
		return nil, err
	}

	logger = logger.WithField("servicename", svc.Name)

	// can we create a shell for this service?
	if svc.DisableShell {
		logger.Warning("Shell commands are disabled for service")
		return nil, ErrShellDisabled
	} else if svc.ImageID == "" {
		logger.Warning("No image is configured for service")
		return nil, ErrShellDisabled
	}

	// lets make sure the image exists locally and is the latest
	workerClient, err := worker.NewClient(workerAddress)
	if err != nil {
		logger.WithError(err).Error("Could not connect to the delegate server")
		return nil, err
	}
	defer workerClient.Close()

	logger = logger.WithField("imageid", svc.ImageID)

	logger.Info("Connected to delegate; pulling image")
	image, err := workerClient.PullImage(dockerRegistry, svc.ImageID, time.Minute)
	if err != nil {
		logger.WithError(err).Error("Could not pull image")
		return nil, err
	}
	logger.Info("Pulled image, setting up shell")

	// get the docker start command
	docker, err := exec.LookPath("docker")
	if err != nil {
		logger.WithError(err).Error("Docker not found")
		return nil, err
	}

	argv := buildDockerArgs(osWrapImpl{}, svc, cfg, controller, docker, image)
	logger.Debugf("command: docker %+v", argv)
	logger.Info("Shell initialized for service, starting")
	return exec.Command(docker, argv...), nil
}
463182
func (c *client) Start(ctx context.Context, id, checkpointDir string, withStdin bool, attachStdio libcontainerdtypes.StdioCallback) (int, error) {
	ctr, err := c.getContainer(ctx, id)
	if err != nil {
		return -1, err
	}
	var (
		cp             *types.Descriptor
		t              containerd.Task
		rio            cio.IO
		stdinCloseSync = make(chan struct{})
	)

	if checkpointDir != "" {
		// write checkpoint to the content store
		tar := archive.Diff(ctx, "", checkpointDir)
		cp, err = c.writeContent(ctx, images.MediaTypeContainerd1Checkpoint, checkpointDir, tar)
		// remove the checkpoint when we're done
		defer func() {
			if cp != nil {
				err := c.client.ContentStore().Delete(context.Background(), cp.Digest)
				if err != nil {
					c.logger.WithError(err).WithFields(logrus.Fields{
						"ref":    checkpointDir,
						"digest": cp.Digest,
					}).Warnf("failed to delete temporary checkpoint entry")
				}
			}
		}()
		if err := tar.Close(); err != nil {
			return -1, errors.Wrap(err, "failed to close checkpoint tar stream")
		}
		if err != nil {
			return -1, errors.Wrapf(err, "failed to upload checkpoint to containerd")
		}
	}

	spec, err := ctr.Spec(ctx)
	if err != nil {
		return -1, errors.Wrap(err, "failed to retrieve spec")
	}
	labels, err := ctr.Labels(ctx)
	if err != nil {
		return -1, errors.Wrap(err, "failed to retreive labels")
	}
	bundle := labels[DockerContainerBundlePath]
	uid, gid := getSpecUser(spec)
	t, err = ctr.NewTask(ctx,
		func(id string) (cio.IO, error) {
			fifos := newFIFOSet(bundle, libcontainerdtypes.InitProcessName, withStdin, spec.Process.Terminal)

			rio, err = c.createIO(fifos, id, libcontainerdtypes.InitProcessName, stdinCloseSync, attachStdio)
			return rio, err
		},
		func(_ context.Context, _ *containerd.Client, info *containerd.TaskInfo) error {
			info.Checkpoint = cp
			if runtime.GOOS != "windows" {
				info.Options = &runctypes.CreateOptions{
					IoUid:       uint32(uid),
					IoGid:       uint32(gid),
					NoPivotRoot: os.Getenv("DOCKER_RAMDISK") != "",
				}
			} else {
				// Make sure we set the runhcs options to debug if we are at debug level.
				if c.logger.Level == logrus.DebugLevel {
					info.Options = &options.Options{Debug: true}
				}
			}
			return nil
		})
	if err != nil {
		close(stdinCloseSync)
		if rio != nil {
			rio.Cancel()
			rio.Close()
		}
		return -1, wrapError(err)
	}

	// Signal c.createIO that it can call CloseIO
	close(stdinCloseSync)

	if err := t.Start(ctx); err != nil {
		if _, err := t.Delete(ctx); err != nil {
			c.logger.WithError(err).WithField("container", id).
				Error("failed to delete task after fail start")
		}
		return -1, wrapError(err)
	}

	return int(t.Pid()), nil
}
234052
func (ds *dockerService) Start() error {
	ds.initCleanup()

	// Initialize the legacy cleanup flag.
	if ds.startLocalStreamingServer {
		go func() {
			if err := ds.streamingServer.Start(true); err != nil {
				klog.Fatalf("Streaming server stopped unexpectedly: %v", err)
			}
		}()
	}
	return ds.containerManager.Start()
}
525385
func (m *MockContainerAPIClient) ContainerStart(ctx context.Context, container string, options types.ContainerStartOptions) error {
	ret := m.ctrl.Call(m, "ContainerStart", ctx, container, options)
	ret0, _ := ret[0].(error)
	return ret0
}
1244524
func (vm *DockerVM) Start(ccid ccintf.CCID, args, env []string, filesToUpload map[string][]byte, builder container.Builder) error {
	imageName, err := vm.GetVMNameForDocker(ccid)
	if err != nil {
		return err
	}

	attachStdout := viper.GetBool("vm.docker.attachStdout")
	containerName := vm.GetVMName(ccid)
	logger := dockerLogger.With("imageName", imageName, "containerName", containerName)

	client, err := vm.getClientFnc()
	if err != nil {
		logger.Debugf("failed to get docker client", "error", err)
		return err
	}

	vm.stopInternal(client, containerName, 0, false, false)

	err = vm.createContainer(client, imageName, containerName, args, env, attachStdout)
	if err == docker.ErrNoSuchImage {
		reader, err := builder.Build()
		if err != nil {
			return errors.Wrapf(err, "failed to generate Dockerfile to build %s", containerName)
		}

		err = vm.deployImage(client, ccid, reader)
		if err != nil {
			return err
		}

		err = vm.createContainer(client, imageName, containerName, args, env, attachStdout)
		if err != nil {
			logger.Errorf("failed to create container: %s", err)
			return err
		}
	} else if err != nil {
		logger.Errorf("create container failed: %s", err)
		return err
	}

	// stream stdout and stderr to chaincode logger
	if attachStdout {
		containerLogger := flogging.MustGetLogger("peer.chaincode." + containerName)
		streamOutput(dockerLogger, client, containerName, containerLogger)
	}

	// upload specified files to the container before starting it
	// this can be used for configurations such as TLS key and certs
	if len(filesToUpload) != 0 {
		// the docker upload API takes a tar file, so we need to first
		// consolidate the file entries to a tar
		payload := bytes.NewBuffer(nil)
		gw := gzip.NewWriter(payload)
		tw := tar.NewWriter(gw)

		for path, fileToUpload := range filesToUpload {
			cutil.WriteBytesToPackage(path, fileToUpload, tw)
		}

		// Write the tar file out
		if err := tw.Close(); err != nil {
			return fmt.Errorf("Error writing files to upload to Docker instance into a temporary tar blob: %s", err)
		}

		gw.Close()

		err := client.UploadToContainer(containerName, docker.UploadToContainerOptions{
			InputStream:          bytes.NewReader(payload.Bytes()),
			Path:                 "/",
			NoOverwriteDirNonDir: false,
		})
		if err != nil {
			return fmt.Errorf("Error uploading files to the container instance %s: %s", containerName, err)
		}
	}

	// start container with HostConfig was deprecated since v1.10 and removed in v1.2
	err = client.StartContainer(containerName, nil)
	if err != nil {
		dockerLogger.Errorf("start-could not start container: %s", err)
		return err
	}

	dockerLogger.Debugf("Started container %s", containerName)
	return nil
}
629849
func (d *dockerLogger) Start(opts *StartOpts) error {
	client, err := d.getDockerClient(opts)
	if err != nil {
		return fmt.Errorf("failed to open docker client: %v", err)
	}

	ctx, cancel := context.WithCancel(context.Background())
	d.cancelCtx = cancel

	go func() {
		defer close(d.doneCh)

		stdout, stderr, err := d.openStreams(ctx, opts)
		if err != nil {
			d.logger.Error("log streaming ended with terminal error", "error", err)
			return
		}

		sinceTime := time.Unix(opts.StartTime, 0)
		backoff := 0.0

		for {
			logOpts := docker.LogsOptions{
				Context:      ctx,
				Container:    opts.ContainerID,
				OutputStream: stdout,
				ErrorStream:  stderr,
				Since:        sinceTime.Unix(),
				Follow:       true,
				Stdout:       true,
				Stderr:       true,
				RawTerminal:  opts.TTY,
			}

			err := client.Logs(logOpts)
			if ctx.Err() != nil {
				// If context is terminated then we can safely break the loop
				return
			} else if err == nil {
				backoff = 0.0
			} else if isLoggingTerminalError(err) {
				d.logger.Error("log streaming ended with terminal error", "error", err)
				return
			} else if err != nil {
				backoff = nextBackoff(backoff)
				d.logger.Error("log streaming ended with error", "error", err, "retry_in", backoff)

				time.Sleep(time.Duration(backoff) * time.Second)
			}

			sinceTime = time.Now()

			container, err := client.InspectContainer(opts.ContainerID)
			if err != nil {
				_, notFoundOk := err.(*docker.NoSuchContainer)
				if !notFoundOk {
					return
				}
			} else if !container.State.Running {
				return
			}
		}
	}()
	return nil

}
155594
func (p *XPod) Start() error {

	if p.IsStopped() {
		if err := p.createSandbox(p.globalSpec); err != nil {
			p.Log(ERROR, "failed to create sandbox for the stopped pod: %v", err)
			return err
		}

		if err := p.prepareResources(); err != nil {
			return err
		}

		if err := p.addResourcesToSandbox(); err != nil {
			return err
		}
	}

	err := p.waitPodRun("start pod")
	if err != nil {
		p.Log(ERROR, "wait running failed, cannot start pod")
		return err
	}
	if err := p.startAll(); err != nil {
		return err
	}

	return p.saveSandbox()
}
773011
func Start(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
	// Allow insecure Docker registries on all private network ranges in RFC 1918 and RFC 6598.
	dargs := []string{
		"-d",
		"--bip=172.19.42.1/16",
		"--insecure-registry",
		"10.0.0.0/8",
		"--insecure-registry",
		"172.16.0.0/12",
		"--insecure-registry",
		"192.168.0.0/16",
		"--insecure-registry",
		"100.64.0.0/10",
		"--exec-opt",
		"native.cgroupdriver=cgroupfs",
	}

	// For overlay-ish filesystems, force the overlay to kick in if it exists.
	// Then we can check the fstype.
	if err := os.MkdirAll("/", 0700); err == nil {

		cmd := exec.Command("findmnt", "--noheadings", "--output", "FSTYPE", "--target", "/")

		if out, err := cmd.Output(); err == nil && strings.TrimSpace(string(out)) == "overlay" {
			dargs = append(dargs, "--storage-driver=overlay")
		} else {
			log.Infof(c, "File system type: '%s' (%v)", out, err)
		}
	}

	log.Infof(c, "Starting docker with %s", strings.Join(dargs, " "))
	cmd := exec.Command("docker", dargs...)
	if err := cmd.Start(); err != nil {
		log.Errf(c, "Failed to start Docker. %s", err)
		return -1, err
	}
	// Get the PID and return it.
	return cmd.Process.Pid, nil
}
27387
func (e *Engine) VirtualizationStart(ctx context.Context, ID string) error {
	return e.client.ContainerStart(ctx, ID, dockertypes.ContainerStartOptions{})
}
357005
func (loader *PluginLoader) Start(iface coreiface.CoreAPI) error {
	for i, pl := range loader.plugins {
		if pl, ok := pl.(plugin.PluginDaemon); ok {
			err := pl.Start(iface)
			if err != nil {
				closePlugins(loader.plugins[i:])
				return err
			}
		}
	}
	return nil
}
941155
func (m *MCP23017Driver) Start() (err error) {
	bus := m.GetBusOrDefault(m.connector.GetDefaultBus())
	address := m.GetAddressOrDefault(mcp23017Address)

	m.connection, err = m.connector.GetConnection(address, bus)
	if err != nil {
		return err
	}
	// Set IOCON register with MCP23017 configuration.
	ioconReg := m.getPort("A").IOCON // IOCON address is the same for Port A or B.
	ioconVal := m.MCPConf.getUint8Value()
	if _, err := m.connection.Write([]uint8{ioconReg, ioconVal}); err != nil {
		return err
	}
	return
}
537142
func (r *RemoteRuntimeService) StartContainer(containerID string) error {
	ctx, cancel := getContextWithTimeout(r.timeout)
	defer cancel()

	_, err := r.runtimeClient.StartContainer(ctx, &runtimeapi.StartContainerRequest{
		ContainerId: containerID,
	})
	if err != nil {
		klog.Errorf("StartContainer %q from runtime service failed: %v", containerID, err)
		return err
	}

	return nil
}
246582
func Start() {
	connect()
	go startBatcher(commonBatchStream)

	for i := range registry {
		debug("starting", registry[i])
		go registry[i].StartLoop()
	}
}
895571
func LaunchDockerLogger(logger hclog.Logger) (DockerLogger, *plugin.Client, error) {
	logger = logger.Named(PluginName)
	bin, err := discover.NomadExecutable()
	if err != nil {
		return nil, nil, err
	}

	client := plugin.NewClient(&plugin.ClientConfig{
		HandshakeConfig: base.Handshake,
		Plugins: map[string]plugin.Plugin{
			PluginName: &Plugin{impl: NewDockerLogger(logger)},
		},
		Cmd: exec.Command(bin, PluginName),
		AllowedProtocols: []plugin.Protocol{
			plugin.ProtocolGRPC,
		},
		Logger: logger,
	})

	rpcClient, err := client.Client()
	if err != nil {
		return nil, nil, err
	}

	raw, err := rpcClient.Dispense(PluginName)
	if err != nil {
		return nil, nil, err
	}

	l := raw.(DockerLogger)
	return l, client, nil

}
100238
func runStart(dockerCli command.Cli, opts *startOptions) error {
	ctx, cancelFun := context.WithCancel(context.Background())
	defer cancelFun()

	if opts.attach || opts.openStdin {
		// We're going to attach to a container.
		// 1. Ensure we only have one container.
		if len(opts.containers) > 1 {
			return errors.New("you cannot start and attach multiple containers at once")
		}

		// 2. Attach to the container.
		container := opts.containers[0]
		c, err := dockerCli.Client().ContainerInspect(ctx, container)
		if err != nil {
			return err
		}

		// We always use c.ID instead of container to maintain consistency during `docker start`
		if !c.Config.Tty {
			sigc := ForwardAllSignals(ctx, dockerCli, c.ID)
			defer signal.StopCatch(sigc)
		}

		if opts.detachKeys != "" {
			dockerCli.ConfigFile().DetachKeys = opts.detachKeys
		}

		options := types.ContainerAttachOptions{
			Stream:     true,
			Stdin:      opts.openStdin && c.Config.OpenStdin,
			Stdout:     true,
			Stderr:     true,
			DetachKeys: dockerCli.ConfigFile().DetachKeys,
		}

		var in io.ReadCloser

		if options.Stdin {
			in = dockerCli.In()
		}

		resp, errAttach := dockerCli.Client().ContainerAttach(ctx, c.ID, options)
		if errAttach != nil && errAttach != httputil.ErrPersistEOF {
			// ContainerAttach return an ErrPersistEOF (connection closed)
			// means server met an error and already put it in Hijacked connection,
			// we would keep the error and read the detailed error message from hijacked connection
			return errAttach
		}
		defer resp.Close()

		cErr := make(chan error, 1)

		go func() {
			cErr <- func() error {
				streamer := hijackedIOStreamer{
					streams:      dockerCli,
					inputStream:  in,
					outputStream: dockerCli.Out(),
					errorStream:  dockerCli.Err(),
					resp:         resp,
					tty:          c.Config.Tty,
					detachKeys:   options.DetachKeys,
				}

				errHijack := streamer.stream(ctx)
				if errHijack == nil {
					return errAttach
				}
				return errHijack
			}()
		}()

		// 3. We should open a channel for receiving status code of the container
		// no matter it's detached, removed on daemon side(--rm) or exit normally.
		statusChan := waitExitOrRemoved(ctx, dockerCli, c.ID, c.HostConfig.AutoRemove)
		startOptions := types.ContainerStartOptions{
			CheckpointID:  opts.checkpoint,
			CheckpointDir: opts.checkpointDir,
		}

		// 4. Start the container.
		if err := dockerCli.Client().ContainerStart(ctx, c.ID, startOptions); err != nil {
			cancelFun()
			<-cErr
			if c.HostConfig.AutoRemove {
				// wait container to be removed
				<-statusChan
			}
			return err
		}

		// 5. Wait for attachment to break.
		if c.Config.Tty && dockerCli.Out().IsTerminal() {
			if err := MonitorTtySize(ctx, dockerCli, c.ID, false); err != nil {
				fmt.Fprintln(dockerCli.Err(), "Error monitoring TTY size:", err)
			}
		}
		if attachErr := <-cErr; attachErr != nil {
			if _, ok := err.(term.EscapeError); ok {
				// The user entered the detach escape sequence.
				return nil
			}
			return attachErr
		}

		if status := <-statusChan; status != 0 {
			return cli.StatusError{StatusCode: status}
		}
	} else if opts.checkpoint != "" {
		if len(opts.containers) > 1 {
			return errors.New("you cannot restore multiple containers at once")
		}
		container := opts.containers[0]
		startOptions := types.ContainerStartOptions{
			CheckpointID:  opts.checkpoint,
			CheckpointDir: opts.checkpointDir,
		}
		return dockerCli.Client().ContainerStart(ctx, container, startOptions)

	} else {
		// We're not going to attach to anything.
		// Start as many containers as we want.
		return startContainersWithoutAttachments(ctx, dockerCli, opts.containers)
	}

	return nil
}
528997
func StartDriver() {
	cert.SetCertGenerator(&CertGenerator{})
	check.DefaultConnChecker = &ConnChecker{}
	if os.Getenv(localbinary.PluginEnvKey) == localbinary.PluginEnvVal {
		registerDriver(os.Getenv(localbinary.PluginEnvDriverName))
	}

	localbinary.CurrentBinaryIsDockerMachine = true
}
917796
func (b *DockerBuilder) buildDockerGroup() *nodetasks.GroupTask {
	return &nodetasks.GroupTask{
		Name:   "docker",
		System: true,
	}
}