// NewDockerVM returns a new DockerVM instance
355514
func NewDockerVM(peerID, networkID string, buildMetrics *BuildMetrics) *DockerVM {
	return &DockerVM{
		PeerID:       peerID,
		NetworkID:    networkID,
		getClientFnc: getDockerClient,
		BuildMetrics: buildMetrics,
	}
}
613457
func buildDockerEnvironmentVars(env map[string]string) []string {
	var list []string
	for k, v := range env {
		list = append(list, []string{"-e", fmt.Sprintf("%s=%s", k, v)}...)
	}

	return list
}
1343121
func createVM(c context.Context, v *crimson.VM) (*crimson.VM, error) {
	if err := validateVMForCreation(v); err != nil {
		return nil, err
	}
	ip, _ := common.ParseIPv4(v.Ipv4)
	tx, err := database.Begin(c)
	if err != nil {
		return nil, errors.Annotate(err, "failed to begin transaction").Err()
	}
	defer tx.MaybeRollback(c)

	hostnameId, err := model.AssignHostnameAndIP(c, tx, v.Name, ip)
	if err != nil {
		return nil, err
	}

	// vms.hostname_id, vms.physical_host_id, and vms.os_id are NOT NULL as above.
	_, err = tx.ExecContext(c, `
		INSERT INTO vms (hostname_id, physical_host_id, os_id, description, deployment_ticket, state)
		VALUES (
			?,
			(SELECT p.id FROM physical_hosts p, hostnames h WHERE p.hostname_id = h.id AND h.name = ?),
			(SELECT id FROM oses WHERE name = ?),
			?,
			?,
			?
		)
	`, hostnameId, v.Host, v.Os, v.Description, v.DeploymentTicket, v.State)
	if err != nil {
		switch e, ok := err.(*mysql.MySQLError); {
		case !ok:
			// Type assertion failed.
		case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'physical_host_id'"):
			// e.g. "Error 1048: Column 'physical_host_id' cannot be null".
			return nil, status.Errorf(codes.NotFound, "physical host %q does not exist", v.Host)
		case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'os_id'"):
			// e.g. "Error 1048: Column 'os_id' cannot be null".
			return nil, status.Errorf(codes.NotFound, "operating system %q does not exist", v.Os)
		}
		return nil, errors.Annotate(err, "failed to create VM").Err()
	}

	vms, err := listVMs(c, tx, &crimson.ListVMsRequest{
		Names: []string{v.Name},
	})
	if err != nil {
		return nil, errors.Annotate(err, "failed to fetch created VM").Err()
	}

	if err := tx.Commit(); err != nil {
		return nil, errors.Annotate(err, "failed to commit transaction").Err()
	}
	return vms[0], nil
}
235130
func NewV2Repository(ctx context.Context, repoInfo *registry.RepositoryInfo, endpoint registry.APIEndpoint, metaHeaders http.Header, authConfig *types.AuthConfig, actions ...string) (repo distribution.Repository, foundVersion bool, err error) {
	repoName := repoInfo.Name.Name()
	// If endpoint does not support CanonicalName, use the RemoteName instead
	if endpoint.TrimHostname {
		repoName = reference.Path(repoInfo.Name)
	}

	direct := &net.Dialer{
		Timeout:   30 * time.Second,
		KeepAlive: 30 * time.Second,
		DualStack: true,
	}

	// TODO(dmcgowan): Call close idle connections when complete, use keep alive
	base := &http.Transport{
		Proxy:               http.ProxyFromEnvironment,
		Dial:                direct.Dial,
		TLSHandshakeTimeout: 10 * time.Second,
		TLSClientConfig:     endpoint.TLSConfig,
		// TODO(dmcgowan): Call close idle connections when complete and use keep alive
		DisableKeepAlives: true,
	}

	proxyDialer, err := sockets.DialerFromEnvironment(direct)
	if err == nil {
		base.Dial = proxyDialer.Dial
	}

	modifiers := registry.Headers(dockerversion.DockerUserAgent(ctx), metaHeaders)
	authTransport := transport.NewTransport(base, modifiers...)

	challengeManager, foundVersion, err := registry.PingV2Registry(endpoint.URL, authTransport)
	if err != nil {
		transportOK := false
		if responseErr, ok := err.(registry.PingResponseError); ok {
			transportOK = true
			err = responseErr.Err
		}
		return nil, foundVersion, fallbackError{
			err:         err,
			confirmedV2: foundVersion,
			transportOK: transportOK,
		}
	}

	if authConfig.RegistryToken != "" {
		passThruTokenHandler := &existingTokenHandler{token: authConfig.RegistryToken}
		modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, passThruTokenHandler))
	} else {
		scope := auth.RepositoryScope{
			Repository: repoName,
			Actions:    actions,
			Class:      repoInfo.Class,
		}

		creds := registry.NewStaticCredentialStore(authConfig)
		tokenHandlerOptions := auth.TokenHandlerOptions{
			Transport:   authTransport,
			Credentials: creds,
			Scopes:      []auth.Scope{scope},
			ClientID:    registry.AuthClientID,
		}
		tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions)
		basicHandler := auth.NewBasicHandler(creds)
		modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler))
	}
	tr := transport.NewTransport(base, modifiers...)

	repoNameRef, err := reference.WithName(repoName)
	if err != nil {
		return nil, foundVersion, fallbackError{
			err:         err,
			confirmedV2: foundVersion,
			transportOK: true,
		}
	}

	repo, err = client.NewRepository(repoNameRef, endpoint.URL.String(), tr)
	if err != nil {
		err = fallbackError{
			err:         err,
			confirmedV2: foundVersion,
			transportOK: true,
		}
	}
	return
}
382690
func New(client Client, auth api.AuthConfig) Docker {
	return &stiDocker{
		client: client,
		pullAuth: dockertypes.AuthConfig{
			Username:      auth.Username,
			Password:      auth.Password,
			Email:         auth.Email,
			ServerAddress: auth.ServerAddress,
		},
	}
}
1360037
func New(client docker.Client, config *api.Config, fs fs.FileSystem, overrides build.Overrides) (*OnBuild, error) {
	dockerHandler := docker.New(client, config.PullAuthentication)
	builder := &OnBuild{
		docker: dockerHandler,
		git:    git.New(fs, cmd.NewCommandRunner()),
		fs:     fs,
		tar:    tar.New(fs),
	}
	// Use STI Prepare() and download the 'run' script optionally.
	s, err := sti.New(client, config, fs, overrides)
	if err != nil {
		return nil, err
	}
	s.SetScripts([]string{}, []string{constants.Assemble, constants.Run})

	downloader := overrides.Downloader
	if downloader == nil {
		downloader, err = scm.DownloaderForSource(builder.fs, config.Source, config.ForceCopy)
		if err != nil {
			return nil, err
		}
	}

	builder.source = onBuildSourceHandler{
		Downloader: downloader,
		Preparer:   s,
		Ignorer:    &ignore.DockerIgnorer{},
	}

	builder.garbage = build.NewDefaultCleaner(builder.fs, builder.docker)
	return builder, nil
}
59150
func New(c Config) (Manager, error) {
	switch c.Type {
	case "", "docker":
		return &Docker{Socket: c.Socket, Runner: c.Runner}, nil
	case "crio", "cri-o":
		return &CRIO{Socket: c.Socket, Runner: c.Runner}, nil
	case "containerd":
		return &Containerd{Socket: c.Socket, Runner: c.Runner}, nil
	default:
		return nil, fmt.Errorf("unknown runtime type: %q", c.Type)
	}
}
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),
	}
}
456354
func (dh *Client) CreateContainer(options *docker.ContainerConfig, name string) (containerId string, e error) {
	imageId := options.Image

	// Verify image available on host.
	_, e = dh.ImageHistory(imageId)
	if e != nil && e.Error() == "resource not found" {
		if e = dh.PullImage(imageId); e != nil {
			return "", e
		}
	}

	imgDetails, err := dh.ImageDetails(imageId)
	if err != nil {
		return "", err
	}
	options.Env = append(options.Env, "DOCKER_IMAGE="+imgDetails.Id)

	container := &docker.Container{}
	u := dh.Address + "/containers/create"

	if name != "" {
		u += "?name=" + name
	}

	if _, e = dh.postJSON(u, options, container); e != nil {
		return "", fmt.Errorf("failed creating container: %s", e.Error())
	}
	return container.Id, e
}
296317
func getDockerClient(dockerEndpoint string) (*dockerapi.Client, error) {
	if len(dockerEndpoint) > 0 {
		klog.Infof("Connecting to docker on %s", dockerEndpoint)
		return dockerapi.NewClient(dockerEndpoint, "", nil, nil)
	}
	return dockerapi.NewEnvClient()
}
791603
func (a *api) connectDocker() (*dockerclient.Client, error) {
	if a.docker == nil {
		const DockerEndpoint string = "unix:///var/run/docker.sock"
		var err error
		if a.docker, err = dockerclient.NewClient(DockerEndpoint); err != nil {
			return nil, fmt.Errorf("could not create a client to docker: %s", err)
		}
	}
	return a.docker, nil
}
64887
func (s *VPCService) NewCreateVPCOfferingParams(displaytext string, name string, supportedservices []string) *CreateVPCOfferingParams {
	p := &CreateVPCOfferingParams{}
	p.p = make(map[string]interface{})
	p.p["displaytext"] = displaytext
	p.p["name"] = name
	p.p["supportedservices"] = supportedservices
	return p
}
1011950
func newDockerAPI() (*dockerAPI, error) {
	glog.V(4).Infof("docker creating api client")
	c, err := client.NewEnvClient()
	if err != nil {
		return nil, fmt.Errorf("error building docker client: %v", err)
	}

	if c == nil {
		return nil, fmt.Errorf("error building docker client, client returned is nil")
	}

	// Test the client
	ctx := context.Background()
	_, err = c.Info(ctx)
	if err != nil {
		// TODO check if /var/run/docker.sock exists and create a connection using that
		glog.Errorf("Unable to create docker client please set DOCKER_HOST to unix socket or tcp socket")
		glog.Errorf("Standard DOCKER_HOST values can be %q and defaults to %q", "unix:///var/run/docker.sock", client.DefaultDockerHost)
		return nil, fmt.Errorf("error building docker client, unable to make info call: %v", err)
	}

	return &dockerAPI{
		client: c,
	}, nil
}
1035769
func NewDockerClient(host, certPath string) (*docker.Client, error) {
	if certPath != "" {
		cert := certPath + "/cert.pem"
		key := certPath + "/key.pem"
		ca := certPath + "/ca.pem"
		return docker.NewTLSClient(host, cert, key, ca)
	}

	return docker.NewClient(host)
}
269316
func (s *SystemVMService) NewRebootSystemVmParams(id string) *RebootSystemVmParams {
	p := &RebootSystemVmParams{}
	p.p = make(map[string]interface{})
	p.p["id"] = id
	return p
}
501069
func DockerDaemon(c *dockerutil.Client) *DockerDaemonRegistry {
	e := multiExtractor(
		newFileExtractor(c),
		newCMDExtractor(c),
	)
	return &DockerDaemonRegistry{
		docker:    c,
		extractor: e,
	}
}
340786
func NewDockerHelper(client *docker.Client) *DockerHelper {
	return &DockerHelper{
		client:   client,
		errStats: newErrorStats(),
	}
}