// Assumes that the local docker image (imageSpec) exists and has been sync'd
// with the registry.
199223
func getInternalImageIDs(userSpec, imageSpec string) (uid, gid int, err error) {

	userSpecCache.Lock()
	defer userSpecCache.Unlock()

	key := userSpec + "!" + imageSpec
	if val, found := userSpecCache.lookup[key]; found {
		return val.uid, val.gid, nil
	}

	var output string
	// explicitly ignoring errors because of -rm under load
	output, _ = dockerRun(imageSpec, "/bin/sh", "-c",
		fmt.Sprintf(`touch test.txt && chown %s test.txt && ls -ln test.txt | awk '{ print $3, $4 }'`,
			userSpec))

	s := strings.TrimSpace(string(output))
	pattern := regexp.MustCompile(`^\d+ \d+$`)

	if !pattern.MatchString(s) {
		err = fmt.Errorf("unexpected output from getInternalImageIDs: %s", s)
		return
	}
	fields := strings.Fields(s)
	if len(fields) != 2 {
		err = fmt.Errorf("unexpected number of fields from container spec: %s", fields)
		return
	}
	uid, err = strconv.Atoi(fields[0])
	if err != nil {
		return
	}
	gid, err = strconv.Atoi(fields[1])
	if err != nil {
		return
	}
	// cache the results
	userSpecCache.lookup[key] = uidgid{uid: uid, gid: gid}
	time.Sleep(time.Second)
	return
}
1079070
func (ds *dockerService) ImageStatus(_ context.Context, r *runtimeapi.ImageStatusRequest) (*runtimeapi.ImageStatusResponse, error) {
	image := r.GetImage()

	imageInspect, err := ds.client.InspectImageByRef(image.Image)
	if err != nil {
		if libdocker.IsImageNotFoundError(err) {
			return &runtimeapi.ImageStatusResponse{}, nil
		}
		return nil, err
	}

	imageStatus, err := imageInspectToRuntimeAPIImage(imageInspect)
	if err != nil {
		return nil, err
	}

	res := runtimeapi.ImageStatusResponse{Image: imageStatus}
	if r.GetVerbose() {
		res.Info = imageInspect.Config.Labels
	}
	return &res, nil
}
42290
func (d *dockerAPI) findImage(name string) (*types.Image, error) {
	glog.V(4).Infof("docker query for image %q", name)
	options := types.ImageListOptions{
		MatchName: name,
	}
	ctx := context.Background()
	images, err := d.client.ImageList(ctx, options)
	if err != nil {
		return nil, fmt.Errorf("error listing images: %v", err)
	}
	for i := range images {
		for _, repoTag := range images[i].RepoTags {
			if repoTag == name {
				return &images[i], nil
			}
		}
	}
	return nil, nil
}
1108943
func (f *FakeDocker) CheckImage(name string) (*api.Image, error) {
	return nil, nil
}
568023
func (r DockerImageReference) Exact() string {
	name := r.NameString()
	if len(name) == 0 {
		return name
	}
	s := r.Registry
	if len(s) > 0 {
		s += "/"
	}

	if len(r.Namespace) != 0 {
		s += r.Namespace + "/"
	}
	return s + name
}
649485
func PushDockerImageToECR(localImageTag string,
	ecrRepoName string,
	awsSession *session.Session,
	logger *logrus.Logger) (string, error) {

	stsSvc := sts.New(awsSession)
	ecrSvc := ecr.New(awsSession)

	// 1. Get the caller identity s.t. we can get the ECR URL which includes the
	// account name
	stsIdentityOutput, stsIdentityErr := stsSvc.GetCallerIdentity(&sts.GetCallerIdentityInput{})
	if stsIdentityErr != nil {
		return "", errors.Wrapf(stsIdentityErr, "Attempting to get AWS caller identity")
	}

	// 2. Create the URL to which we're going to do the push
	localImageTagParts := strings.Split(localImageTag, ":")
	ecrTagValue := fmt.Sprintf("%s.dkr.ecr.%s.amazonaws.com/%s:%s",
		*stsIdentityOutput.Account,
		*awsSession.Config.Region,
		ecrRepoName,
		localImageTagParts[len(localImageTagParts)-1])

	// 3. Tag the local image with the ECR tag
	dockerTagCmd := exec.Command("docker", "tag", localImageTag, ecrTagValue)
	dockerTagCmdErr := system.RunOSCommand(dockerTagCmd, logger)
	if dockerTagCmdErr != nil {
		return "", errors.Wrapf(dockerTagCmdErr, "Attempting to tag Docker image")
	}

	// 4. Push the image - if that fails attempt to reauthorize with the docker
	// client and try again
	var pushError error
	dockerPushCmd := exec.Command("docker", "push", ecrTagValue)
	pushError = system.RunOSCommand(dockerPushCmd, logger)
	if pushError != nil {
		logger.WithFields(logrus.Fields{
			"Error": pushError,
		}).Info("ECR push failed - reauthorizing")
		ecrAuthTokenResult, ecrAuthTokenResultErr := ecrSvc.GetAuthorizationToken(&ecr.GetAuthorizationTokenInput{})
		if ecrAuthTokenResultErr != nil {
			pushError = ecrAuthTokenResultErr
		} else {
			authData := ecrAuthTokenResult.AuthorizationData[0]
			authToken, authTokenErr := base64.StdEncoding.DecodeString(*authData.AuthorizationToken)
			if authTokenErr != nil {
				pushError = authTokenErr
			} else {
				authTokenString := string(authToken)
				authTokenParts := strings.Split(authTokenString, ":")
				dockerURL := fmt.Sprintf("https://%s.dkr.ecr.%s.amazonaws.com",
					*stsIdentityOutput.Account,
					*awsSession.Config.Region)
				dockerLoginCmd := exec.Command("docker",
					"login",
					"-u",
					authTokenParts[0],
					"--password-stdin",
					dockerURL)
				dockerLoginCmd.Stdout = os.Stdout
				dockerLoginCmd.Stdin = bytes.NewReader([]byte(fmt.Sprintf("%s\n", authTokenParts[1])))
				dockerLoginCmd.Stderr = os.Stderr
				dockerLoginCmdErr := system.RunOSCommand(dockerLoginCmd, logger)
				if dockerLoginCmdErr != nil {
					pushError = dockerLoginCmdErr
				} else {
					// Try it again...
					dockerRetryPushCmd := exec.Command("docker", "push", ecrTagValue)
					dockerRetryPushCmdErr := system.RunOSCommand(dockerRetryPushCmd, logger)
					pushError = dockerRetryPushCmdErr
				}
			}
		}
	}
	if pushError != nil {
		pushError = errors.Wrapf(pushError, "Attempting to push Docker image")
	}
	return ecrTagValue, pushError
}
113506
func IsImageNotFound(err error) bool {
	if err == nil {
		return false
	}
	if err == dockerclient.ErrNoSuchImage {
		return true
	}
	var ok bool
	if _, ok = err.(*ImageNotFound); !ok {
		var checks = []*regexp.Regexp{
			regexp.MustCompile("Tag .* not found in repository .*"),
			regexp.MustCompile("Error: image .* not found"),
		}
		for _, check := range checks {
			if ok = check.MatchString(err.Error()); ok {
				break
			}
		}
	}
	return ok
}
437183
func (_m *APIClient) ContainerInspect(ctx context.Context, _a1 string) (types.ContainerJSON, error) {
	ret := _m.Called(ctx, _a1)

	var r0 types.ContainerJSON
	if rf, ok := ret.Get(0).(func(context.Context, string) types.ContainerJSON); ok {
		r0 = rf(ctx, _a1)
	} else {
		r0 = ret.Get(0).(types.ContainerJSON)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, string) error); ok {
		r1 = rf(ctx, _a1)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
1061397
func (daemon *Daemon) ContainerCreateIgnoreImagesArgsEscaped(params types.ContainerCreateConfig) (containertypes.ContainerCreateCreatedBody, error) {
	return daemon.containerCreate(createOpts{
		params:                  params,
		managed:                 false,
		ignoreImagesArgsEscaped: true})
}
111268
func (dk *BasicDockerKeyring) Lookup(image string) ([]docker.AuthConfiguration, bool) {
	// range over the index as iterating over a map does not provide a predictable ordering
	ret := []docker.AuthConfiguration{}
	for _, k := range dk.index {
		// both k and image are schemeless URLs because even though schemes are allowed
		// in the credential configurations, we remove them in Add.
		if matched, _ := urlsMatchStr(k, image); !matched {
			continue
		}

		ret = append(ret, dk.creds[k]...)
	}

	if len(ret) > 0 {
		return ret, true
	}

	// Use credentials for the default registry if provided, and appropriate
	if isDefaultRegistryMatch(image) {
		if auth, ok := dk.creds[defaultRegistryHost]; ok {
			return auth, true
		}
	}

	return []docker.AuthConfiguration{}, false
}
62043
func IsImageNotFound(err error) bool {
	if err != nil {
		if err == dockerclient.ErrNoSuchImage {
			return true
		}
		var checks = []*regexp.Regexp{
			regexp.MustCompile("(?i)Tag .* not found in repository .*"),
			regexp.MustCompile("(?i)Error: image .* not found"),
			regexp.MustCompile("(?i)could not find image"),
			regexp.MustCompile("(?i)no such id"),
			regexp.MustCompile("(?i)no such image"),
		}
		for _, check := range checks {
			if ok := check.MatchString(err.Error()); ok {
				return true
			}
		}
	}
	return false
}
751783
func ensureSandboxImageExists(client libdocker.Interface, image string) error {
	_, err := client.InspectImageByRef(image)
	if err == nil {
		return nil
	}
	if !libdocker.IsImageNotFoundError(err) {
		return fmt.Errorf("failed to inspect sandbox image %q: %v", image, err)
	}

	repoToPull, _, _, err := parsers.ParseImageName(image)
	if err != nil {
		return err
	}

	keyring := credentialprovider.NewDockerKeyring()
	creds, withCredentials := keyring.Lookup(repoToPull)
	if !withCredentials {
		klog.V(3).Infof("Pulling image %q without credentials", image)

		err := client.PullImage(image, dockertypes.AuthConfig{}, dockertypes.ImagePullOptions{})
		if err != nil {
			return fmt.Errorf("failed pulling image %q: %v", image, err)
		}

		return nil
	}

	var pullErrs []error
	for _, currentCreds := range creds {
		authConfig := dockertypes.AuthConfig(credentialprovider.LazyProvide(currentCreds, repoToPull))
		err := client.PullImage(image, authConfig, dockertypes.ImagePullOptions{})
		// If there was no error, return success
		if err == nil {
			return nil
		}

		pullErrs = append(pullErrs, err)
	}

	return utilerrors.NewAggregate(pullErrs)
}
597853
func ParseDockerImageReference(spec string) (reference.DockerImageReference, error) {
	ref, err := reference.Parse(spec)
	if err != nil {
		return ref, err
	}
	return ref, nil
}
1179168
func (f *FakeDocker) CheckAndPullImage(name string) (*api.Image, error) {
	if f.PullResult {
		return &api.Image{}, nil
	}
	return nil, f.PullError
}
630955
func (m *imageManager) EnsureImageExists(pod *v1.Pod, container *v1.Container, pullSecrets []v1.Secret, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, string, error) {
	logPrefix := fmt.Sprintf("%s/%s", pod.Name, container.Image)
	ref, err := kubecontainer.GenerateContainerRef(pod, container)
	if err != nil {
		klog.Errorf("Couldn't make a ref to pod %v, container %v: '%v'", pod.Name, container.Name, err)
	}

	// If the image contains no tag or digest, a default tag should be applied.
	image, err := applyDefaultImageTag(container.Image)
	if err != nil {
		msg := fmt.Sprintf("Failed to apply default image tag %q: %v", container.Image, err)
		m.logIt(ref, v1.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, klog.Warning)
		return "", msg, ErrInvalidImageName
	}

	spec := kubecontainer.ImageSpec{Image: image}
	imageRef, err := m.imageService.GetImageRef(spec)
	if err != nil {
		msg := fmt.Sprintf("Failed to inspect image %q: %v", container.Image, err)
		m.logIt(ref, v1.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, klog.Warning)
		return "", msg, ErrImageInspect
	}

	present := imageRef != ""
	if !shouldPullImage(container, present) {
		if present {
			msg := fmt.Sprintf("Container image %q already present on machine", container.Image)
			m.logIt(ref, v1.EventTypeNormal, events.PulledImage, logPrefix, msg, klog.Info)
			return imageRef, "", nil
		}
		msg := fmt.Sprintf("Container image %q is not present with pull policy of Never", container.Image)
		m.logIt(ref, v1.EventTypeWarning, events.ErrImageNeverPullPolicy, logPrefix, msg, klog.Warning)
		return "", msg, ErrImageNeverPull
	}

	backOffKey := fmt.Sprintf("%s_%s", pod.UID, container.Image)
	if m.backOff.IsInBackOffSinceUpdate(backOffKey, m.backOff.Clock.Now()) {
		msg := fmt.Sprintf("Back-off pulling image %q", container.Image)
		m.logIt(ref, v1.EventTypeNormal, events.BackOffPullImage, logPrefix, msg, klog.Info)
		return "", msg, ErrImagePullBackOff
	}
	m.logIt(ref, v1.EventTypeNormal, events.PullingImage, logPrefix, fmt.Sprintf("Pulling image %q", container.Image), klog.Info)
	pullChan := make(chan pullResult)
	m.puller.pullImage(spec, pullSecrets, pullChan, podSandboxConfig)
	imagePullResult := <-pullChan
	if imagePullResult.err != nil {
		m.logIt(ref, v1.EventTypeWarning, events.FailedToPullImage, logPrefix, fmt.Sprintf("Failed to pull image %q: %v", container.Image, imagePullResult.err), klog.Warning)
		m.backOff.Next(backOffKey, m.backOff.Clock.Now())
		if imagePullResult.err == ErrRegistryUnavailable {
			msg := fmt.Sprintf("image pull failed for %s because the registry is unavailable.", container.Image)
			return "", msg, imagePullResult.err
		}

		return "", imagePullResult.err.Error(), ErrImagePull
	}
	m.logIt(ref, v1.EventTypeNormal, events.PulledImage, logPrefix, fmt.Sprintf("Successfully pulled image %q", container.Image), klog.Info)
	m.backOff.GC()
	return imagePullResult.imageRef, "", nil
}
965983
func (f *FakeDockerClient) InspectImageByRef(name string) (*dockertypes.ImageInspect, error) {
	f.Lock()
	defer f.Unlock()
	f.appendCalled(CalledDetail{name: "inspect_image"})
	if err := f.popError("inspect_image"); err != nil {
		return nil, err
	}
	if result, ok := f.ImageInspects[name]; ok {
		return result, nil
	}
	return nil, ImageNotFoundError{name}
}
1082529
func (f *FakeDocker) BuildImage(opts BuildImageOptions) error {
	f.BuildImageOpts = opts
	if opts.Stdin != nil {
		_, err := io.Copy(ioutil.Discard, opts.Stdin)
		if err != nil {
			return err
		}
	}
	return f.BuildImageError
}