// From https://github.com/docker/docker/blob/0d70706b4b6bf9d5a5daf46dd147ca71270d0ab7/api/client/utils.go#L222-L233
424343
func monitorExecTty(client *docker.Client, execID string, terminalFd uintptr) {
	// HACK: For some weird reason on Docker 1.4.1 this resize is being triggered
	//       before the Exec instance is running resulting in an error on the
	//       Docker server. So we wait a little bit before triggering this first
	//       resize
	time.Sleep(50 * time.Millisecond)
	resizeExecTty(client, execID, terminalFd)

	sigchan := make(chan os.Signal, 1)
	gosignal.Notify(sigchan, syscall.SIGWINCH)
	go func() {
		for _ = range sigchan {
			resizeExecTty(client, execID, terminalFd)
		}
	}()
}
1324706
func (c *Cluster) PullImage(opts docker.PullImageOptions, auth docker.AuthConfiguration, nodes ...string) error {
	var w safe.Buffer
	if opts.OutputStream != nil {
		mw := io.MultiWriter(&w, opts.OutputStream)
		opts.OutputStream = mw
	} else {
		opts.OutputStream = &w
	}
	key := imageKey(opts.Repository, opts.Tag)
	_, err := c.runOnNodes(func(n node) (interface{}, error) {
		n.setPersistentClient()
		err := n.PullImage(opts, auth)
		if err != nil {
			return nil, err
		}
		img, err := n.InspectImage(key)
		if err != nil {
			return nil, err
		}
		return nil, c.storage().StoreImage(key, img.ID, n.addr)
	}, docker.ErrNoSuchImage, true, nodes...)
	if err != nil {
		return err
	}
	digest, _ := fix.GetImageDigest(w.String())
	return c.storage().SetImageDigest(key, digest)
}
852922
func (d Docker) GetImage(name string) (builder.Image, error) {
	img, err := d.Daemon.GetImage(name)
	if err != nil {
		return nil, err
	}
	return imgWrap{img}, nil
}
1236036
func (_ *Helper) GetClient() (client *docker.Client, endpoint string, err error) {
	client, err = docker.NewClientFromEnv()
	if len(os.Getenv("DOCKER_HOST")) > 0 {
		endpoint = os.Getenv("DOCKER_HOST")
	} else {
		endpoint = "unix:///var/run/docker.sock"
	}
	return
}
142611
func ShortDockerImageID(image *DockerImage, length int) string {
	id := image.ID
	if s, err := digest.ParseDigest(id); err == nil {
		id = s.Hex()
	}
	if len(id) > length {
		id = id[:length]
	}
	return id
}
56165
func Convert_DockerV1CompatibilityImage_to_DockerImageConfig(in *DockerV1CompatibilityImage, out *DockerImageConfig) error {
	*out = DockerImageConfig{
		ID:              in.ID,
		Parent:          in.Parent,
		Comment:         in.Comment,
		Created:         in.Created,
		Container:       in.Container,
		DockerVersion:   in.DockerVersion,
		Author:          in.Author,
		Architecture:    in.Architecture,
		Size:            in.Size,
		OS:              "linux",
		ContainerConfig: in.ContainerConfig,
	}
	if in.Config != nil {
		out.Config = &DockerConfig{}
		*out.Config = *in.Config
	}
	return nil
}
632956
func (c *container) Push() {
	fmt.Fprintf(c.CommandsOut(), "Pushing image %s ...\n", c.Image())
	args := []string{"push", c.Image()}
	executeCommand("docker", args, c.CommandsOut(), c.CommandsErr())
}
420894
func (client *Client) Wait(cid string) (int, error) {
	uri := fmt.Sprintf("/containers/%s/wait", cid)
	resp, err := client.DoRequest("POST", uri, nil)
	if err != nil {
		return 0, err
	}
	waitResp := struct {
		StatusCode int
	}{-1}
	if err := jsonUnmarshal(resp, &waitResp); err != nil {
		return 0, fmt.Errorf("docker: wait: %v", err)
	}
	return waitResp.StatusCode, nil
}
1177128
func (r *dockerFetcher) getV2URLPaths(ctx context.Context, desc ocispec.Descriptor) ([]string, error) {
	var urls []string

	if len(desc.URLs) > 0 {
		// handle fetch via external urls.
		for _, u := range desc.URLs {
			log.G(ctx).WithField("url", u).Debug("adding alternative url")
			urls = append(urls, u)
		}
	}

	switch desc.MediaType {
	case images.MediaTypeDockerSchema2Manifest, images.MediaTypeDockerSchema2ManifestList,
		images.MediaTypeDockerSchema1Manifest,
		ocispec.MediaTypeImageManifest, ocispec.MediaTypeImageIndex:
		urls = append(urls, r.url(path.Join("manifests", desc.Digest.String())))
	}

	// always fallback to attempting to get the object out of the blobs store.
	urls = append(urls, r.url(path.Join("blobs", desc.Digest.String())))

	return urls, nil
}
871586
func Convert_v1_DockerStrategyOptions_To_build_DockerStrategyOptions(in *v1.DockerStrategyOptions, out *build.DockerStrategyOptions, s conversion.Scope) error {
	return autoConvert_v1_DockerStrategyOptions_To_build_DockerStrategyOptions(in, out, s)
}
399824
func ConvertSavedFile(dockerSavedFile string, config FileConfig) ([]string, error) {
	config.initLogger()

	f, err := os.Open(dockerSavedFile)
	if err != nil {
		return nil, fmt.Errorf("error opening file: %v", err)
	}
	defer f.Close()

	return (&converter{
		backend:   file.NewFileBackend(f, config.Debug, config.Info),
		dockerURL: config.DockerURL,
		config:    config.CommonConfig,
	}).convert()
}
151536
func getDockerClient() (*docker.Client, error) {
	dockerClient, _, err := dockerutil.NewHelper().GetClient()
	if err == nil {
		if err = dockerClient.Ping(); err != nil {
			klog.V(4).Infof("Docker client did not respond to a ping: %v", err)
			return nil, err
		}
		return dockerClient, nil
	}
	klog.V(2).Infof("No local Docker daemon detected: %v", err)
	return nil, err
}
1071987
func ParseDockerURL(arg string) (*ParsedDockerURL, error) {
	r, err := reference.ParseNormalizedNamed(arg)
	if err != nil {
		return nil, err
	}

	var tag, digest string
	switch x := r.(type) {
	case reference.Canonical:
		digest = x.Digest().String()
	case reference.NamedTagged:
		tag = x.Tag()
	default:
		tag = defaultTag
	}

	indexURL, remoteName := docker.SplitReposName(reference.FamiliarName(r))

	return &ParsedDockerURL{
		OriginalName: arg,
		IndexURL:     indexURL,
		ImageName:    remoteName,
		Tag:          tag,
		Digest:       digest,
	}, nil
}
538755
func Convert_public_to_api_DockerConfig(in *public.DockerConfig, out *docker10.DockerConfig) error {
	*out = docker10.DockerConfig{
		Hostname:        in.Hostname,
		Domainname:      in.Domainname,
		User:            in.User,
		Memory:          in.Memory,
		MemorySwap:      in.MemorySwap,
		CPUShares:       in.CPUShares,
		CPUSet:          in.CPUSet,
		AttachStdin:     in.AttachStdin,
		AttachStdout:    in.AttachStdout,
		AttachStderr:    in.AttachStderr,
		PortSpecs:       in.PortSpecs,
		ExposedPorts:    in.ExposedPorts,
		Tty:             in.Tty,
		OpenStdin:       in.OpenStdin,
		StdinOnce:       in.StdinOnce,
		Env:             in.Env,
		Cmd:             in.Cmd,
		DNS:             in.DNS,
		Image:           in.Image,
		Volumes:         in.Volumes,
		VolumesFrom:     in.VolumesFrom,
		WorkingDir:      in.WorkingDir,
		Entrypoint:      in.Entrypoint,
		NetworkDisabled: in.NetworkDisabled,
		SecurityOpts:    in.SecurityOpts,
		OnBuild:         in.OnBuild,
		Labels:          in.Labels,
	}
	return nil
}
840397
func (d *dockerCoordinator) PullImage(image string, authOptions *docker.AuthConfiguration, callerID string, emitFn LogEventFn) (imageID string, err error) {
	// Get the future
	d.imageLock.Lock()
	future, ok := d.pullFutures[image]
	d.registerPullLogger(image, emitFn)
	if !ok {
		// Make the future
		future = newPullFuture()
		d.pullFutures[image] = future
		go d.pullImageImpl(image, authOptions, future)
	}
	d.imageLock.Unlock()

	// We unlock while we wait since this can take a while
	id, err := future.wait().result()

	d.imageLock.Lock()
	defer d.imageLock.Unlock()

	// Delete the future since we don't need it and we don't want to cache an
	// image being there if it has possibly been manually deleted (outside of
	// Nomad).
	if _, ok := d.pullFutures[image]; ok {
		delete(d.pullFutures, image)
	}

	// If we are cleaning up, we increment the reference count on the image
	if err == nil && d.cleanup {
		d.incrementImageReferenceImpl(id, image, callerID)
	}

	return id, err
}
583198
func GenerateManifest(layerData types.DockerImageData, manhash string, dockerURL *common.ParsedDockerURL, debug log.Logger) (*schema.ImageManifest, error) {
	dockerConfig := layerData.Config
	genManifest := &schema.ImageManifest{}

	appURL := ""
	appURL = dockerURL.IndexURL + "/"
	appURL += dockerURL.ImageName + "-" + layerData.ID
	appURL, err := appctypes.SanitizeACIdentifier(appURL)
	if err != nil {
		return nil, err
	}
	name := appctypes.MustACIdentifier(appURL)
	genManifest.Name = *name

	acVersion, err := appctypes.NewSemVer(schema.AppContainerVersion.String())
	if err != nil {
		panic("invalid appc spec version")
	}
	genManifest.ACVersion = *acVersion

	genManifest.ACKind = appctypes.ACKind(schema.ImageManifestKind)

	var annotations appctypes.Annotations

	labels := make(map[appctypes.ACIdentifier]string)
	parentLabels := make(map[appctypes.ACIdentifier]string)

	setLabel(labels, "layer", layerData.ID)
	setLabel(labels, "version", dockerURL.Tag)

	setOSArch(labels, layerData.OS, layerData.Architecture)
	setOSArch(parentLabels, layerData.OS, layerData.Architecture)

	setAnnotation(&annotations, "authors", layerData.Author)
	epoch := time.Unix(0, 0)
	if !layerData.Created.Equal(epoch) {
		setAnnotation(&annotations, "created", layerData.Created.Format(time.RFC3339))
	}
	setAnnotation(&annotations, "docker-comment", layerData.Comment)
	setAnnotation(&annotations, common.AppcDockerOriginalName, dockerURL.OriginalName)
	setAnnotation(&annotations, common.AppcDockerRegistryURL, dockerURL.IndexURL)
	setAnnotation(&annotations, common.AppcDockerRepository, dockerURL.ImageName)
	setAnnotation(&annotations, common.AppcDockerImageID, layerData.ID)
	setAnnotation(&annotations, common.AppcDockerParentImageID, layerData.Parent)
	setAnnotation(&annotations, common.AppcDockerManifestHash, manhash)

	if dockerConfig != nil {
		exec := getExecCommand(dockerConfig.Entrypoint, dockerConfig.Cmd)
		user, group := parseDockerUser(dockerConfig.User)
		var env appctypes.Environment
		for _, v := range dockerConfig.Env {
			parts := strings.SplitN(v, "=", 2)
                        if len(parts) == 2 {
				env.Set(parts[0], parts[1])
                        }
		}
		app := &appctypes.App{
			Exec:             exec,
			User:             user,
			Group:            group,
			Environment:      env,
			WorkingDirectory: dockerConfig.WorkingDir,
		}

		app.UserLabels = dockerConfig.Labels

		app.MountPoints, err = convertVolumesToMPs(dockerConfig.Volumes)
		if err != nil {
			return nil, err
		}

		app.Ports, err = convertPorts(dockerConfig.ExposedPorts, dockerConfig.PortSpecs, debug)
		if err != nil {
			return nil, err
		}

		ep, cmd, err := generateEPCmdAnnotation(dockerConfig.Entrypoint, dockerConfig.Cmd)
		if err != nil {
			return nil, err
		}
		if len(ep) > 0 {
			setAnnotation(&annotations, common.AppcDockerEntrypoint, ep)
		}
		if len(cmd) > 0 {
			setAnnotation(&annotations, common.AppcDockerCmd, cmd)
		}

		genManifest.App = app
	}

	if layerData.Parent != "" {
		indexPrefix := ""
		// omit docker hub index URL in app name
		indexPrefix = dockerURL.IndexURL + "/"
		parentImageNameString := indexPrefix + dockerURL.ImageName + "-" + layerData.Parent
		parentImageNameString, err := appctypes.SanitizeACIdentifier(parentImageNameString)
		if err != nil {
			return nil, err
		}
		parentImageName := appctypes.MustACIdentifier(parentImageNameString)

		plbl, err := appctypes.LabelsFromMap(labels)
		if err != nil {
			return nil, err
		}

		genManifest.Dependencies = append(genManifest.Dependencies, appctypes.Dependency{ImageName: *parentImageName, Labels: plbl})

		setAnnotation(&annotations, common.AppcDockerTag, dockerURL.Tag)
	}

	genManifest.Labels, err = appctypes.LabelsFromMap(labels)
	if err != nil {
		return nil, err
	}
	genManifest.Annotations = annotations

	return genManifest, nil
}
1000754
func (s *Server) PullImage(ctx context.Context, req *pb.PullImageRequest) (resp *pb.PullImageResponse, err error) {
	const operation = "pull_image"
	defer func() {
		recordOperation(operation, time.Now())
		recordError(operation, err)
	}()

	logrus.Debugf("PullImageRequest: %+v", req)
	// TODO: what else do we need here? (Signatures when the story isn't just pulling from docker://)
	image := ""
	img := req.GetImage()
	if img != nil {
		image = img.Image
	}

	var (
		images []string
		pulled string
	)
	images, err = s.StorageImageServer().ResolveNames(image)
	if err != nil {
		return nil, err
	}
	for _, img := range images {
		var (
			username string
			password string
		)
		if req.GetAuth() != nil {
			username = req.GetAuth().Username
			password = req.GetAuth().Password
			if req.GetAuth().Auth != "" {
				username, password, err = decodeDockerAuth(req.GetAuth().Auth)
				if err != nil {
					logrus.Debugf("error decoding authentication for image %s: %v", img, err)
					continue
				}
			}
		}
		options := &copy.Options{
			SourceCtx: &types.SystemContext{
				DockerRegistryUserAgent: useragent.Get(ctx),
				SignaturePolicyPath:     s.ImageContext().SignaturePolicyPath,
			},
		}

		// Specifying a username indicates the user intends to send authentication to the registry.
		if username != "" {
			options.SourceCtx = &types.SystemContext{
				DockerAuthConfig: &types.DockerAuthConfig{
					Username: username,
					Password: password,
				},
			}
		}

		var tmpImg types.Image
		tmpImg, err = s.StorageImageServer().PrepareImage(img, options)
		if err != nil {
			logrus.Debugf("error preparing image %s: %v", img, err)
			continue
		}

		var storedImage *storage.ImageResult
		storedImage, err = s.StorageImageServer().ImageStatus(s.ImageContext(), img)
		if err == nil {
			tmpImgConfigDigest := tmpImg.ConfigInfo().Digest
			if tmpImgConfigDigest.String() == "" {
				// this means we are playing with a schema1 image, in which
				// case, we're going to repull the image in any case
				logrus.Debugf("image config digest is empty, re-pulling image")
			} else if tmpImgConfigDigest.String() == storedImage.ConfigDigest.String() {
				logrus.Debugf("image %s already in store, skipping pull", img)
				pulled = img
				break
			}
			logrus.Debugf("image in store has different ID, re-pulling %s", img)
		}

		_, err = s.StorageImageServer().PullImage(s.ImageContext(), img, options)
		if err != nil {
			logrus.Debugf("error pulling image %s: %v", img, err)
			continue
		}
		pulled = img
		break
	}
	if pulled == "" && err != nil {
		return nil, err
	}
	status, err := s.StorageImageServer().ImageStatus(s.ImageContext(), pulled)
	if err != nil {
		return nil, err
	}
	imageRef := status.ID
	if len(status.RepoDigests) > 0 {
		imageRef = status.RepoDigests[0]
	}
	resp = &pb.PullImageResponse{
		ImageRef: imageRef,
	}
	logrus.Debugf("PullImageResponse: %+v", resp)
	return resp, nil
}