// WithDockerfile creates / returns a CmdOperator to set the Dockerfile for a build operation
8531
func WithDockerfile(dockerfile string) func(*icmd.Cmd) func() {
	return func(cmd *icmd.Cmd) func() {
		cmd.Command = append(cmd.Command, "-")
		cmd.Stdin = strings.NewReader(dockerfile)
		return nil
	}
}
170729
func (rco RunContainerOptions) asDockerCreateContainerOptions() dockertypes.ContainerCreateConfig {
	config := rco.asDockerConfig()
	hostConfig := rco.asDockerHostConfig()
	return dockertypes.ContainerCreateConfig{
		Name:       containerName(rco.Image),
		Config:     &config,
		HostConfig: &hostConfig,
	}
}
1096398
func WithNotaryServer(notaryURL string) func(*icmd.Cmd) {
	return func(cmd *icmd.Cmd) {
		env := append(os.Environ(),
			"DOCKER_CONTENT_TRUST_SERVER="+notaryURL,
		)
		cmd.Env = append(cmd.Env, env...)
	}
}
647168
func (builder *UpdateGSetCommandBuilder) WithBucket(bucket string) *UpdateGSetCommandBuilder {
	builder.protobuf.Bucket = []byte(bucket)
	return builder
}
340786
func NewDockerHelper(client *docker.Client) *DockerHelper {
	return &DockerHelper{
		client:   client,
		errStats: newErrorStats(),
	}
}
275838
func buildDockerImage(imageDir, imageName string) {
	if dockDir == "" {
		panic("dockDir should be set before calling buildDockerImage")
	}
	cmd := exec.Command("docker", "build", "-t", imageName, ".")
	cmd.Dir = filepath.Join(dockDir, imageDir)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		log.Fatalf("Error building docker image %v: %v", imageName, err)
	}
}
1132163
func NewDockerCli(ops ...DockerCliOption) (*DockerCli, error) {
	cli := &DockerCli{}
	defaultOps := []DockerCliOption{
		WithContentTrustFromEnv(),
		WithContainerizedClient(containerizedengine.NewClient),
	}
	cli.contextStoreConfig = defaultContextStoreConfig()
	ops = append(defaultOps, ops...)
	if err := cli.Apply(ops...); err != nil {
		return nil, err
	}
	if cli.out == nil || cli.in == nil || cli.err == nil {
		stdin, stdout, stderr := term.StdStreams()
		if cli.in == nil {
			cli.in = streams.NewIn(stdin)
		}
		if cli.out == nil {
			cli.out = streams.NewOut(stdout)
		}
		if cli.err == nil {
			cli.err = stderr
		}
	}
	return cli, nil
}
929057
func (b *KubeletBuilder) buildSystemdEnvironmentFile(kubeletConfig *kops.KubeletConfigSpec) (*nodetasks.File, error) {
	// @step: ensure the masters do not get a bootstrap configuration
	if b.UseBootstrapTokens() && b.IsMaster {
		kubeletConfig.BootstrapKubeconfig = ""
	}

	if kubeletConfig.ExperimentalAllowedUnsafeSysctls != nil {
		// The ExperimentalAllowedUnsafeSysctls flag was renamed in k/k #63717
		if b.IsKubernetesGTE("1.11") {
			glog.V(1).Info("ExperimentalAllowedUnsafeSysctls was renamed in k8s 1.11+, please use AllowedUnsafeSysctls instead.")
			kubeletConfig.AllowedUnsafeSysctls = append(kubeletConfig.ExperimentalAllowedUnsafeSysctls, kubeletConfig.AllowedUnsafeSysctls...)
			kubeletConfig.ExperimentalAllowedUnsafeSysctls = nil
		}
	}

	// TODO: Dump the separate file for flags - just complexity!
	flags, err := flagbuilder.BuildFlags(kubeletConfig)
	if err != nil {
		return nil, fmt.Errorf("error building kubelet flags: %v", err)
	}

	// Add cloud config file if needed
	// We build this flag differently because it depends on CloudConfig, and to expose it directly
	// would be a degree of freedom we don't have (we'd have to write the config to different files)
	// We can always add this later if it is needed.
	if b.Cluster.Spec.CloudConfig != nil {
		flags += " --cloud-config=" + CloudConfigFilePath
	}

	if b.UsesCNI() {
		flags += " --cni-bin-dir=" + b.CNIBinDir()
		flags += " --cni-conf-dir=" + b.CNIConfDir()
	}

	if b.UsesSecondaryIP() {
		sess := session.Must(session.NewSession())
		metadata := ec2metadata.New(sess)
		localIpv4, err := metadata.GetMetadata("local-ipv4")
		if err != nil {
			return nil, fmt.Errorf("error fetching the local-ipv4 address from the ec2 meta-data: %v", err)
		}
		flags += " --node-ip=" + localIpv4
	}

	if b.Cluster.Spec.Networking != nil && b.Cluster.Spec.Networking.Kubenet != nil {
		// Kubenet is neither CNI nor not-CNI, so we need to pass it `--cni-bin-dir` also
		if b.IsKubernetesGTE("1.9") {
			// Flag renamed in #53564
			flags += " --cni-bin-dir=" + b.CNIBinDir()
		} else {
			flags += " --network-plugin-dir=" + b.CNIBinDir()
		}
	}

	if b.usesContainerizedMounter() {
		// We don't want to expose this in the model while it is experimental, but it is needed on COS
		flags += " --experimental-mounter-path=" + path.Join(containerizedMounterHome, "mounter")
	}

	sysconfig := "DAEMON_ARGS=\"" + flags + "\"\n"
	// Makes kubelet read /root/.docker/config.json properly
	sysconfig = sysconfig + "HOME=\"/root" + "\"\n"

	t := &nodetasks.File{
		Path:     "/etc/sysconfig/kubelet",
		Contents: fi.NewStringResource(sysconfig),
		Type:     nodetasks.FileType_File,
	}

	return t, nil
}
153501
func (builder *FetchMapCommandBuilder) WithBucket(bucket string) *FetchMapCommandBuilder {
	builder.protobuf.Bucket = []byte(bucket)
	return builder
}
334768
func NewDockerContainer() *Container {
	container := &Container{}
	container.Type = "DOCKER"
	container.Docker = &Docker{}

	return container
}
225140
func (builder *FetchValueCommandBuilder) WithBucket(bucket string) *FetchValueCommandBuilder {
	builder.protobuf.Bucket = []byte(bucket)
	return builder
}
1078714
func (o *PetUploadImageParams) WithFile(file runtime.NamedReadCloser) *PetUploadImageParams {
	o.SetFile(file)
	return o
}
45250
func SimpleDockerRef(p *d2acommon.ParsedDockerURL) string {
	var sds string
	if p.IndexURL != defaultIndexURL {
		sds += p.IndexURL
	}

	imageName := p.ImageName
	if p.IndexURL == defaultIndexURL && strings.HasPrefix(p.ImageName, defaultRepoPrefix) {
		imageName = strings.TrimPrefix(p.ImageName, defaultRepoPrefix)
	}

	if sds == "" {
		sds = imageName
	} else {
		sds = path.Join(sds, imageName)
	}

	digest := p.Digest
	tag := p.Tag
	if digest != "" {
		sds += "@" + digest
	} else {
		if tag != defaultTag {
			sds += ":" + tag
		}
	}

	return sds
}
1142809
func (rco RunContainerOptions) asDockerConfig() dockercontainer.Config {
	return dockercontainer.Config{
		Image:        getImageName(rco.Image),
		User:         rco.User,
		Env:          rco.Env,
		Entrypoint:   rco.Entrypoint,
		OpenStdin:    rco.Stdin != nil,
		StdinOnce:    rco.Stdin != nil,
		AttachStdout: rco.Stdout != nil,
	}
}
1242445
func BuildDockerImageWithFlags(serviceName string,
	dockerFilepath string,
	dockerTags map[string]string,
	buildTags string,
	linkFlags string,
	logger *logrus.Logger) error {

	// BEGIN DOCKER PRECONDITIONS
	// Ensure that serviceName and tags are lowercase to make Docker happy
	var dockerErrors []string
	for eachKey, eachValue := range dockerTags {
		if eachKey != strings.ToLower(eachKey) ||
			eachValue != strings.ToLower(eachValue) {
			dockerErrors = append(dockerErrors, fmt.Sprintf("--tag %s:%s MUST be lower case", eachKey, eachValue))
		}
	}

	if len(dockerErrors) > 0 {
		return errors.Errorf("Docker build errors: %s", strings.Join(dockerErrors[:], ", "))
	}
	// BEGIN Informational - output the docker version...
	dockerVersionCmd := exec.Command("docker", "-v")
	dockerVersionCmdErr := system.RunOSCommand(dockerVersionCmd, logger)
	if dockerVersionCmdErr != nil {
		return errors.Wrapf(dockerVersionCmdErr, "Attempting to get docker version")
	}
	// END Informational - output the docker version...

	// END DOCKER PRECONDITIONS

	// Compile this binary for minimal Docker size
	// https://blog.codeship.com/building-minimal-docker-containers-for-go-applications/
	currentTime := time.Now().UnixNano()
	executableOutput := fmt.Sprintf("%s-%d-docker.lambda.amd64", serviceName, currentTime)
	buildErr := system.BuildGoBinary(serviceName,
		executableOutput,
		false,
		fmt.Sprintf("%d", currentTime),
		buildTags,
		linkFlags,
		false,
		logger)
	if buildErr != nil {
		return errors.Wrapf(buildErr, "Attempting to build Docker binary")
	}
	defer func() {
		removeErr := os.Remove(executableOutput)
		if removeErr != nil {
			logger.WithFields(logrus.Fields{
				"Path":  executableOutput,
				"Error": removeErr,
			}).Warn("Failed to delete temporary Docker binary")
		}
	}()

	// ARG SPARTA_DOCKER_BINARY reference s.t. we can supply the binary
	// name to the build..
	// We need to build the static binary s.t. we can add it to the Docker container...
	// Build the image...
	dockerArgs := []string{
		"build",
		"--build-arg",
		fmt.Sprintf("%s=%s", BinaryNameArgument, executableOutput),
	}

	if dockerFilepath != "" {
		dockerArgs = append(dockerArgs, "--file", dockerFilepath)
	}
	// Add the latest tag
	// dockerArgs = append(dockerArgs, "--tag", fmt.Sprintf("sparta/%s:latest", serviceName))
	logger.WithFields(logrus.Fields{
		"Tags": dockerTags,
	}).Info("Creating Docker image")

	for eachKey, eachValue := range dockerTags {
		dockerArgs = append(dockerArgs, "--tag", fmt.Sprintf("%s:%s",
			strings.ToLower(eachKey),
			strings.ToLower(eachValue)))
	}

	dockerArgs = append(dockerArgs, ".")
	dockerCmd := exec.Command("docker", dockerArgs...)
	return system.RunOSCommand(dockerCmd, logger)
}
355758
func makeDockerClientWithTLS(config types.Config, ca, cert, key *os.File, endpoint, apiversion string) (engine.API, error) {
	return docker.MakeRawClientWithTLS(config, ca, cert, key, endpoint, apiversion)
}
1231734
func (c *ServicedCli) initDocker() {
	c.app.Commands = append(c.app.Commands, cli.Command{
		Name:        "docker",
		Usage:       "Docker administration commands",
		Description: "",
		Subcommands: []cli.Command{
			{
				Name:        "sync",
				Usage:       "serviced docker sync",
				Description: "sync pushes all images to local registry - allows single host to easily be made master for multi-host",
				Action:      c.cmdRegistrySync,
			}, {
				Name:        "reset-registry",
				Usage:       "serviced docker reset-registry",
				Description: "Pulls images from the docker registry and updates the index",
				Action:      c.cmdResetRegistry,
			}, {
				Name:        "migrate-registry",
				Usage:       "serviced docker migrate-registry",
				Description: "Upgrades the docker registry from an older or remote registry",
				Action:      c.cmdMigrateRegistry,
				Flags: []cli.Flag{
					cli.StringFlag{
						Name:  "registry",
						Value: "",
						Usage: "host:port where the registry is running",
					},
					cli.BoolFlag{
						Name:  "override, f",
						Usage: "overrides all existing image records",
					},
				},
			}, {
				Name:        "override",
				Usage:       "Replace an image in the registry with a new image",
				Description: "serviced docker override OLDIMAGE NEWIMAGE",
				Action:      c.cmdDockerOverride,
			},
		},
	})
}