// Start the container with the given identifier. The hostConfig can safely be set to nil to use the defaults.
196665
func (dh *Client) StartContainer(containerId string, hostConfig *docker.HostConfig) (e error) {
	if hostConfig == nil {
		hostConfig = &docker.HostConfig{}
	}
	_, e = dh.postJSON(dh.Address+"/containers/"+containerId+"/start", hostConfig, nil)
	return e
}
439393
func (_m *APIClient) ContainerExecStart(ctx context.Context, execID string, config types.ExecStartCheck) error {
	ret := _m.Called(ctx, execID, config)

	var r0 error
	if rf, ok := ret.Get(0).(func(context.Context, string, types.ExecStartCheck) error); ok {
		r0 = rf(ctx, execID, config)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
706003
func (daemon *Daemon) ContainerStart(name string, hostConfig *containertypes.HostConfig, checkpoint string, checkpointDir string) error {
	if checkpoint != "" && !daemon.HasExperimental() {
		return errdefs.InvalidParameter(errors.New("checkpoint is only supported in experimental mode"))
	}

	container, err := daemon.GetContainer(name)
	if err != nil {
		return err
	}

	validateState := func() error {
		container.Lock()
		defer container.Unlock()

		if container.Paused {
			return errdefs.Conflict(errors.New("cannot start a paused container, try unpause instead"))
		}

		if container.Running {
			return containerNotModifiedError{running: true}
		}

		if container.RemovalInProgress || container.Dead {
			return errdefs.Conflict(errors.New("container is marked for removal and cannot be started"))
		}
		return nil
	}

	if err := validateState(); err != nil {
		return err
	}

	// Windows does not have the backwards compatibility issue here.
	if runtime.GOOS != "windows" {
		// This is kept for backward compatibility - hostconfig should be passed when
		// creating a container, not during start.
		if hostConfig != nil {
			logrus.Warn("DEPRECATED: Setting host configuration options when the container starts is deprecated and has been removed in Docker 1.12")
			oldNetworkMode := container.HostConfig.NetworkMode
			if err := daemon.setSecurityOptions(container, hostConfig); err != nil {
				return errdefs.InvalidParameter(err)
			}
			if err := daemon.mergeAndVerifyLogConfig(&hostConfig.LogConfig); err != nil {
				return errdefs.InvalidParameter(err)
			}
			if err := daemon.setHostConfig(container, hostConfig); err != nil {
				return errdefs.InvalidParameter(err)
			}
			newNetworkMode := container.HostConfig.NetworkMode
			if string(oldNetworkMode) != string(newNetworkMode) {
				// if user has change the network mode on starting, clean up the
				// old networks. It is a deprecated feature and has been removed in Docker 1.12
				container.NetworkSettings.Networks = nil
				if err := container.CheckpointTo(daemon.containersReplica); err != nil {
					return errdefs.System(err)
				}
			}
			container.InitDNSHostConfig()
		}
	} else {
		if hostConfig != nil {
			return errdefs.InvalidParameter(errors.New("Supplying a hostconfig on start is not supported. It should be supplied on create"))
		}
	}

	// check if hostConfig is in line with the current system settings.
	// It may happen cgroups are umounted or the like.
	if _, err = daemon.verifyContainerSettings(container.OS, container.HostConfig, nil, false); err != nil {
		return errdefs.InvalidParameter(err)
	}
	// Adapt for old containers in case we have updates in this function and
	// old containers never have chance to call the new function in create stage.
	if hostConfig != nil {
		if err := daemon.adaptContainerSettings(container.HostConfig, false); err != nil {
			return errdefs.InvalidParameter(err)
		}
	}
	return daemon.containerStart(container, checkpoint, checkpointDir, true)
}
360714
func (config ManifoldConfig) start(context dependency.Context) (worker.Worker, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Trace(err)
	}

	var stTracker workerstate.StateTracker
	if err := context.Get(config.StateName, &stTracker); err != nil {
		return nil, errors.Trace(err)
	}
	statePool, err := stTracker.Use()
	if err != nil {
		return nil, errors.Trace(err)
	}

	w, err := config.NewWorker(Config{
		ModelWatcher:   statePool.SystemState(),
		ModelGetter:    StatePoolModelGetter{statePool},
		NewModelWorker: config.NewModelWorker,
		ErrorDelay:     jworker.RestartDelay,
	})
	if err != nil {
		stTracker.Done()
		return nil, errors.Trace(err)
	}
	return common.NewCleanupWorker(w, func() { stTracker.Done() }), nil
}
185651
func (vm *VM) Start() error {
	vmclient, err := vm.getVMClient()
	if err != nil {
		return fmt.Errorf(errGetClient, err)
	}

	reqID, err := vmclient.StartRole(vm.ServiceName, vm.Name, vm.Name)
	if err != nil {
		return err
	}

	// Wait for the shutdown
	if err := client.WaitForOperation(reqID, nil); err != nil {
		return fmt.Errorf("Error waiting for instance %s to be starting the hosted service %s: %s",
			vm.Name, vm.Name, err)
	}
	return nil
}
929167
func (c *Container) Start(ctx context.Context) error {
	if c.Engine == nil {
		return ErrNilEngine
	}
	startCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()
	return c.Engine.VirtualizationStart(startCtx, c.ID)
}
279502
func (config ManifoldConfig) start(context dependency.Context) (worker.Worker, error) {
	if err := config.Validate(); err != nil {
		return nil, errors.Trace(err)
	}

	var clock clock.Clock
	if err := context.Get(config.ClockName, &clock); err != nil {
		return nil, errors.Trace(err)
	}

	if config.RaftName != "" {
		// We don't need anything from raft directly, but if it's set
		// ensure it's running before continuing.
		if err := context.Get(config.RaftName, nil); err != nil {
			return nil, errors.Trace(err)
		}
	}

	cleanup := func() error { return nil }
	var updaterFunc func() (globalclock.Updater, error)
	if config.StateName != "" {
		var stTracker workerstate.StateTracker
		if err := context.Get(config.StateName, &stTracker); err != nil {
			return nil, errors.Trace(err)
		}
		statePool, err := stTracker.Use()
		if err != nil {
			return nil, errors.Trace(err)
		}
		cleanup = stTracker.Done
		updaterFunc = statePool.SystemState().GlobalClockUpdater
	} else {

		var updater globalclock.Updater
		if err := context.Get(config.LeaseManagerName, &updater); err != nil {
			return nil, errors.Trace(err)
		}
		updaterFunc = func() (globalclock.Updater, error) {
			return updater, nil
		}
	}

	worker, err := config.NewWorker(Config{
		NewUpdater:     updaterFunc,
		LocalClock:     clock,
		UpdateInterval: config.UpdateInterval,
		BackoffDelay:   config.BackoffDelay,
		Logger:         config.Logger,
	})
	if err != nil {
		cleanup()
		return nil, errors.Trace(err)
	}

	go func() {
		worker.Wait()
		cleanup()
	}()
	return worker, nil
}
813305
func (a *HostAgent) StartContainer(cancel <-chan interface{}, serviceID string, instanceID int) (*zkservice.ServiceState, <-chan time.Time, error) {
	logger := plog.WithFields(log.Fields{
		"serviceid":  serviceID,
		"instanceid": instanceID,
	})

	a.serviceCache.Invalidate(serviceID, instanceID)
	evaluatedService, tenantID, _, err := a.serviceCache.GetEvaluatedService(serviceID, instanceID)
	if err != nil {
		logger.WithError(err).Error("Failed to get service")
		return nil, nil, err
	}

	// pull the service image
	a.setInstanceState(serviceID, instanceID, service.StatePulling)
	imageUUID, imageName, err := a.pullImage(logger, cancel, evaluatedService.ImageID)
	if err != nil {
		logger.WithError(err).Debug("Could not pull the service image")
		return nil, nil, err
	}
	// Update the service with the complete image name
	evaluatedService.ImageID = imageName

	// get the container configs
	ctr, state, err := a.setupContainer(tenantID, evaluatedService, instanceID, imageUUID)
	if err != nil {
		logger.WithError(err).Debug("Could not setup container")
		return nil, nil, err
	}

	// start the container
	a.setInstanceState(serviceID, instanceID, service.StateStarting)
	ev := a.monitorContainer(logger, ctr)

	if err := ctr.Start(); err != nil {
		logger.WithError(err).Debug("Could not start container")
		ctr.CancelOnEvent(docker.Die)
		return nil, nil, err
	}
	logger.Debug("Started container")

	dctr, err := ctr.Inspect()
	if err != nil {
		logger.WithError(err).Debug("Could not inspect container")
		ctr.CancelOnEvent(docker.Die)
		return nil, nil, err
	}

	state.HostIP = a.ipaddress
	state.PrivateIP = ctr.NetworkSettings.IPAddress
	state.Started = dctr.State.StartedAt

	go a.exposeAssignedIPs(state, ctr)
	a.setInstanceState(serviceID, instanceID, service.StateRunning)
	return state, ev, nil
}
833573
func (i *InformerHolder) Start(stopCh <-chan struct{}) {
	i.kubernetesInformers.Start(stopCh)
	i.authorizationInformers.Start(stopCh)
	i.imageInformers.Start(stopCh)
	i.oauthInformers.Start(stopCh)
	i.quotaInformers.Start(stopCh)
	i.routeInformers.Start(stopCh)
	i.securityInformers.Start(stopCh)
	i.userInformers.Start(stopCh)
}
699009
func (c *cniProcessor) Start(ctx context.Context, eventInfo *common.EventInfo) error {
	contextID, err := generateContextID(eventInfo)
	if err != nil {
		return err
	}

	runtimeInfo, err := c.metadataExtractor(eventInfo)
	if err != nil {
		return err
	}

	if err := c.config.Policy.HandlePUEvent(ctx, contextID, common.EventCreate, runtimeInfo); err != nil {
		return err
	}

	if err := c.config.Policy.HandlePUEvent(ctx, contextID, common.EventStart, runtimeInfo); err != nil {
		return err
	}

	c.config.Collector.CollectContainerEvent(&collector.ContainerRecord{
		ContextID: contextID,
		IPAddress: runtimeInfo.IPAddresses(),
		Tags:      runtimeInfo.Tags(),
		Event:     collector.ContainerStart,
	})

	return nil
}
804440
func (s *DockerServer) Start() error {
	// Start the internal service.
	if err := s.service.Start(); err != nil {
		klog.Errorf("Unable to start docker service")
		return err
	}

	klog.V(2).Infof("Start dockershim grpc server")
	l, err := util.CreateListener(s.endpoint)
	if err != nil {
		return fmt.Errorf("failed to listen on %q: %v", s.endpoint, err)
	}
	// Create the grpc server and register runtime and image services.
	s.server = grpc.NewServer(
		grpc.MaxRecvMsgSize(maxMsgSize),
		grpc.MaxSendMsgSize(maxMsgSize),
	)
	runtimeapi.RegisterRuntimeServiceServer(s.server, s.service)
	runtimeapi.RegisterImageServiceServer(s.server, s.service)
	go func() {
		if err := s.server.Serve(l); err != nil {
			klog.Fatalf("Failed to serve connections: %v", err)
		}
	}()
	return nil
}
850293
func (c *dockerLoggerClient) Start(opts *StartOpts) error {
	req := &proto.StartRequest{
		Endpoint:    opts.Endpoint,
		ContainerId: opts.ContainerID,
		StdoutFifo:  opts.Stdout,
		StderrFifo:  opts.Stderr,
		Tty:         opts.TTY,

		TlsCert: opts.TLSCert,
		TlsKey:  opts.TLSKey,
		TlsCa:   opts.TLSCA,
	}
	_, err := c.client.Start(context.Background(), req)
	return err
}
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
}
27387
func (e *Engine) VirtualizationStart(ctx context.Context, ID string) error {
	return e.client.ContainerStart(ctx, ID, dockertypes.ContainerStartOptions{})
}
273269
func (s *serviceConfigWatch) Start() error {
	s.ctx, s.cancelFunc = context.WithCancel(context.Background())
	if err := s.ensureConfigWatch(); err != nil {
		return err
	}
	go s.runWatch()

	return nil
}
52205
func (broker *kvmBroker) StartInstance(ctx context.ProviderCallContext, args environs.StartInstanceParams) (*environs.StartInstanceResult, error) {
	// TODO: refactor common code out of the container brokers.
	containerMachineID := args.InstanceConfig.MachineId
	kvmLogger.Infof("starting kvm container for containerMachineID: %s", containerMachineID)

	// TODO: Default to using the host network until we can configure.  Yes,
	// this is using the LxcBridge value, we should put it in the api call for
	// container config.
	bridgeDevice := broker.agentConfig.Value(agent.LxcBridge)
	if bridgeDevice == "" {
		bridgeDevice = network.DefaultKVMBridge
	}

	config, err := broker.api.ContainerConfig()
	if err != nil {
		kvmLogger.Errorf("failed to get container config: %v", err)
		return nil, err
	}

	err = broker.prepareHost(names.NewMachineTag(containerMachineID), kvmLogger, args.Abort)
	if err != nil {
		return nil, errors.Trace(err)
	}

	preparedInfo, err := prepareOrGetContainerInterfaceInfo(
		broker.api,
		containerMachineID,
		true, // allocate if possible, do not maintain existing.
		kvmLogger,
	)
	if err != nil {
		return nil, errors.Trace(err)
	}

	// Something to fallback to if there are no devices given in args.NetworkInfo
	// TODO(jam): 2017-02-07, this feels like something that should never need
	// to be invoked, because either StartInstance or
	// prepareOrGetContainerInterfaceInfo should always return a value. The
	// test suite currently doesn't think so, and I'm hesitant to munge it too
	// much.
	interfaces, err := finishNetworkConfig(bridgeDevice, preparedInfo)
	if err != nil {
		return nil, errors.Trace(err)
	}
	network := container.BridgeNetworkConfig(bridgeDevice, 0, interfaces)

	// The provisioner worker will provide all tools it knows about
	// (after applying explicitly specified constraints), which may
	// include tools for architectures other than the host's.
	//
	// container/kvm only allows running container==host arch, so
	// we constrain the tools to host arch here regardless of the
	// constraints specified.
	archTools, err := matchHostArchTools(args.Tools)
	if err != nil {
		return nil, errors.Trace(err)
	}

	series := archTools.OneSeries()
	args.InstanceConfig.MachineContainerType = instance.KVM
	if err := args.InstanceConfig.SetTools(archTools); err != nil {
		return nil, errors.Trace(err)
	}

	cloudInitUserData, err := combinedCloudInitData(
		config.CloudInitUserData,
		config.ContainerInheritProperties,
		series, kvmLogger)
	if err != nil {
		return nil, errors.Trace(err)
	}

	if err := instancecfg.PopulateInstanceConfig(
		args.InstanceConfig,
		config.ProviderType,
		config.AuthorizedKeys,
		config.SSLHostnameVerification,
		config.LegacyProxy,
		config.JujuProxy,
		config.AptProxy,
		config.AptMirror,
		config.EnableOSRefreshUpdate,
		config.EnableOSUpgrade,
		cloudInitUserData,
		nil,
	); err != nil {
		kvmLogger.Errorf("failed to populate machine config: %v", err)
		return nil, err
	}

	storageConfig := &container.StorageConfig{
		AllowMount: true,
	}
	inst, hardware, err := broker.manager.CreateContainer(
		args.InstanceConfig, args.Constraints,
		series, network, storageConfig, args.StatusCallback,
	)
	if err != nil {
		kvmLogger.Errorf("failed to start container: %v", err)
		return nil, err
	}
	kvmLogger.Infof("started kvm container for containerMachineID: %s, %s, %s", containerMachineID, inst.Id(), hardware.String())
	return &environs.StartInstanceResult{
		Instance:    inst,
		Hardware:    hardware,
		NetworkInfo: interfaces,
	}, nil
}
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
}