// BuildImage builds a docker image.
//
// Essentially, this executes:
// 	docker build -t TAG PATH
//
// Params:
// 	- path (string): The path to the image. REQUIRED
// 	- tag (string): The tag to build.
770291
func BuildImage(c cookoo.Context, p *cookoo.Params) (interface{}, cookoo.Interrupt) {
	path := p.Get("path", "").(string)
	tag := p.Get("tag", "").(string)

	log.Infof(c, "Building docker image %s (tag: %s)", path, tag)

	return buildImg(c, path, tag)
}
115748
func (cli *Client) ImageCreate(ctx context.Context, parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) {
	ref, err := reference.ParseNormalizedNamed(parentReference)
	if err != nil {
		return nil, err
	}

	query := url.Values{}
	query.Set("fromImage", reference.FamiliarName(ref))
	query.Set("tag", getAPITagFromNamedRef(ref))
	if options.Platform != "" {
		query.Set("platform", strings.ToLower(options.Platform))
	}
	resp, err := cli.tryImageCreate(ctx, query, options.RegistryAuth)
	if err != nil {
		return nil, err
	}
	return resp.body, nil
}
587965
func (s *BuildStrategyRef) BuildStrategy(env Environment, dockerStrategyOptions *buildv1.DockerStrategyOptions) (*buildv1.BuildStrategy, []buildv1.BuildTriggerPolicy) {
	switch s.Strategy {
	case newapp.StrategyPipeline:
		return &buildv1.BuildStrategy{
			JenkinsPipelineStrategy: &buildv1.JenkinsPipelineBuildStrategy{
				Env: env.List(),
			},
			Type: buildv1.JenkinsPipelineBuildStrategyType,
		}, s.Base.BuildTriggers()

	case newapp.StrategyDocker:
		var triggers []buildv1.BuildTriggerPolicy
		strategy := &buildv1.DockerBuildStrategy{
			Env: env.List(),
		}
		if dockerStrategyOptions != nil {
			strategy.BuildArgs = dockerStrategyOptions.BuildArgs
		}
		if s.Base != nil {
			ref := s.Base.ObjectReference()
			strategy.From = &ref
			triggers = s.Base.BuildTriggers()
		}
		return &buildv1.BuildStrategy{
			DockerStrategy: strategy,
			Type:           buildv1.DockerBuildStrategyType,
		}, triggers

	case newapp.StrategySource:
		return &buildv1.BuildStrategy{
			SourceStrategy: &buildv1.SourceBuildStrategy{
				From: s.Base.ObjectReference(),
				Env:  env.List(),
			},
			Type: buildv1.SourceBuildStrategyType,
		}, s.Base.BuildTriggers()
	}

	klog.Error("BuildStrategy called with unknown strategy")
	return nil, nil
}
138993
func (r *Docker) LoadImage(path string) error {
	glog.Infof("Loading image: %s", path)
	return r.Runner.Run(fmt.Sprintf("docker load -i %s", path))
}
181452
func (r *REST) imageFor(ctx context.Context, tag string, imageStream *imageapi.ImageStream) (*imageapi.Image, error) {
	event := imageapi.LatestTaggedImage(imageStream, tag)
	if event == nil || len(event.Image) == 0 {
		return nil, kapierrors.NewNotFound(imagegroup.Resource("imagestreamtags"), imageapi.JoinImageStreamTag(imageStream.Name, tag))
	}

	return r.imageRegistry.GetImage(ctx, event.Image, &metav1.GetOptions{})
}
181692
func (c *Client) BuildImage(opts BuildImageOptions) error {
	if opts.OutputStream == nil {
		return ErrMissingOutputStream
	}
	headers, err := headersWithAuth(opts.Auth, c.versionedAuthConfigs(opts.AuthConfigs))
	if err != nil {
		return err
	}

	if opts.Remote != "" && opts.Name == "" {
		opts.Name = opts.Remote
	}
	if opts.InputStream != nil || opts.ContextDir != "" {
		headers["Content-Type"] = "application/tar"
	} else if opts.Remote == "" {
		return ErrMissingRepo
	}
	if opts.ContextDir != "" {
		if opts.InputStream != nil {
			return ErrMultipleContexts
		}
		var err error
		if opts.InputStream, err = createTarStream(opts.ContextDir, opts.Dockerfile); err != nil {
			return err
		}
	}
	qs := queryString(&opts)

	if c.serverAPIVersion.GreaterThanOrEqualTo(apiVersion125) && len(opts.CacheFrom) > 0 {
		if b, err := json.Marshal(opts.CacheFrom); err == nil {
			item := url.Values(map[string][]string{})
			item.Add("cachefrom", string(b))
			qs = fmt.Sprintf("%s&%s", qs, item.Encode())
		}
	}

	if len(opts.Ulimits) > 0 {
		if b, err := json.Marshal(opts.Ulimits); err == nil {
			item := url.Values(map[string][]string{})
			item.Add("ulimits", string(b))
			qs = fmt.Sprintf("%s&%s", qs, item.Encode())
		}
	}

	if len(opts.BuildArgs) > 0 {
		v := make(map[string]string)
		for _, arg := range opts.BuildArgs {
			v[arg.Name] = arg.Value
		}
		if b, err := json.Marshal(v); err == nil {
			item := url.Values(map[string][]string{})
			item.Add("buildargs", string(b))
			qs = fmt.Sprintf("%s&%s", qs, item.Encode())
		}
	}

	return c.stream("POST", fmt.Sprintf("/build?%s", qs), streamOptions{
		setRawTerminal:    true,
		rawJSONStream:     opts.RawJSONStream,
		headers:           headers,
		in:                opts.InputStream,
		stdout:            opts.OutputStream,
		stderr:            opts.ErrorStream,
		inactivityTimeout: opts.InactivityTimeout,
		context:           opts.Context,
	})
}
617722
func Image(component string, clusterSpec *kops.ClusterSpec, assetsBuilder *assets.AssetBuilder) (string, error) {
	if assetsBuilder == nil {
		return "", fmt.Errorf("unable to parse assets as assetBuilder is not defined")
	}
	// TODO remove this, as it is an addon now
	if component == "kube-dns" {
		// TODO: Once we are shipping different versions, start to use them
		return "k8s.gcr.io/kubedns-amd64:1.3", nil
	}

	kubernetesVersion, err := k8sversion.Parse(clusterSpec.KubernetesVersion)
	if err != nil {
		return "", err
	}

	if !IsBaseURL(clusterSpec.KubernetesVersion) {
		image := "k8s.gcr.io/" + component + ":" + "v" + kubernetesVersion.String()

		image, err := assetsBuilder.RemapImage(image)
		if err != nil {
			return "", fmt.Errorf("unable to remap container %q: %v", image, err)
		}
		return image, nil
	}

	baseURL := clusterSpec.KubernetesVersion
	baseURL = strings.TrimSuffix(baseURL, "/")

	// TODO path.Join here?
	tagURL := baseURL + "/bin/linux/amd64/" + component + ".docker_tag"
	glog.V(2).Infof("Downloading docker tag for %s from: %s", component, tagURL)

	b, err := vfs.Context.ReadFile(tagURL)
	if err != nil {
		return "", fmt.Errorf("error reading tag file %q: %v", tagURL, err)
	}
	tag := strings.TrimSpace(string(b))
	glog.V(2).Infof("Found tag %q for %q", tag, component)

	image := "k8s.gcr.io/" + component + ":" + tag

	// When we're using a docker load-ed image, we are likely a CI build.
	// But the k8s.gcr.io prefix is an alias, and we only double-tagged from 1.10 onwards.
	// For versions prior to 1.10, remap k8s.gcr.io to the old name.
	// This also means that we won't start using the aliased names on existing clusters,
	// which could otherwise be surprising to users.
	if !kubernetesVersion.IsGTE("1.10") {
		image = "gcr.io/google_containers/" + strings.TrimPrefix(image, "k8s.gcr.io/")
	}

	return image, nil
}
1041070
func (_m *APIClient) ImageBuild(ctx context.Context, _a1 io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) {
	ret := _m.Called(ctx, _a1, options)

	var r0 types.ImageBuildResponse
	if rf, ok := ret.Get(0).(func(context.Context, io.Reader, types.ImageBuildOptions) types.ImageBuildResponse); ok {
		r0 = rf(ctx, _a1, options)
	} else {
		r0 = ret.Get(0).(types.ImageBuildResponse)
	}

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

	return r0, r1
}
590292
func NewImage(conf *Config) (*Image, error) {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: conf.InsecureTLS},
		Proxy:           http.ProxyFromEnvironment,
	}
	client := http.Client{
		Transport: tr,
		Timeout:   conf.Timeout,
	}
	registry := dockerHub
	tag := "latest"
	token := ""
	os := "linux"
	arch := "amd64"
	var nameParts, tagParts []string
	var name, port string
	state := stateInitial
	start := 0
	for i, c := range conf.ImageName {
		if c == ':' || c == '/' || c == '@' || i == len(conf.ImageName)-1 {
			if i == len(conf.ImageName)-1 {
				// ignore a separator, include the last symbol
				i += 1
			}
			part := conf.ImageName[start:i]
			start = i + 1
			switch state {
			case stateInitial:
				if part == "localhost" || strings.Contains(part, ".") {
					// it's registry, let's check what's next =port of image name
					registry = part
					if c == ':' {
						state = statePort
					} else {
						state = stateName
					}
				} else {
					// it's an image name, if separator is /
					// next part is also part of the name
					// othrewise it's an offcial image
					if c == '/' {
						// we got just a part of name, till next time
						start = 0
						state = stateName
					} else {
						state = stateTag
						name = fmt.Sprintf("library/%s", part)
					}
				}
			case stateTag:
				tag = ""
				tagParts = append(tagParts, part)
			case statePort:
				state = stateName
				port = part
			case stateName:
				if c == ':' || c == '@' {
					state = stateTag
				}
				nameParts = append(nameParts, part)
			}
		}
	}

	if port != "" {
		registry = fmt.Sprintf("%s:%s", registry, port)
	}
	if name == "" {
		name = strings.Join(nameParts, "/")
	}
	if tag == "" {
		tag = strings.Join(tagParts, ":")
	}
	if conf.InsecureRegistry {
		registry = fmt.Sprintf("http://%s/v2", registry)
	} else {
		registry = fmt.Sprintf("https://%s/v2", registry)
	}
	if conf.Token != "" {
		token = "Basic " + conf.Token
	}
	if conf.PlatformOS != "" {
		os = conf.PlatformOS
	}
	if conf.PlatformArch != "" {
		arch = conf.PlatformArch
	}

	return &Image{
		Registry: registry,
		Name:     name,
		Tag:      tag,
		user:     conf.User,
		password: conf.Password,
		Token:    token,
		client:   client,
		os:       os,
		arch:     arch,
	}, nil
}
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)
}
141014
func (runtime *DockerRuntime) PullImage(image string) error {
	out, err := runtime.exec.Command("docker", "pull", image).CombinedOutput()
	if err != nil {
		return errors.Wrapf(err, "output: %s, error", string(out))
	}
	return nil
}
10837
func Convert_v1_ImageLabel_To_build_ImageLabel(in *v1.ImageLabel, out *build.ImageLabel, s conversion.Scope) error {
	return autoConvert_v1_ImageLabel_To_build_ImageLabel(in, out, s)
}
417310
func PushImage(repotag string) error {
	iid, err := commons.ParseImageID(repotag)
	if err != nil {
		return err
	}

	return pushImage(iid.BaseName(), iid.Registry(), iid.Tag)
}
940281
func Convert_v1_ImageSource_To_build_ImageSource(in *v1.ImageSource, out *build.ImageSource, s conversion.Scope) error {
	return autoConvert_v1_ImageSource_To_build_ImageSource(in, out, s)
}
84209
func (dh *Client) BuildDockerfile(dockerfile string, opts *BuildImageOptions) (imageId string, e error) {
	r, e := dh.createDockerfileArchive(dockerfile)
	if e != nil {
		return "", e
	}
	return dh.Build(r, opts)

}
467547
func (builder *OnBuild) Build(config *api.Config) (*api.Result, error) {
	buildResult := &api.Result{}

	if config.BlockOnBuild {
		buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason(
			utilstatus.ReasonOnBuildForbidden,
			utilstatus.ReasonMessageOnBuildForbidden,
		)
		return buildResult, fmt.Errorf("builder image uses ONBUILD instructions but ONBUILD is not allowed")
	}
	glog.V(2).Info("Preparing the source code for build")
	// Change the installation directory for this config to store scripts inside
	// the application root directory.
	if err := builder.source.Prepare(config); err != nil {
		return buildResult, err
	}

	// If necessary, copy the STI scripts into application root directory
	builder.copySTIScripts(config)

	glog.V(2).Info("Creating application Dockerfile")
	if err := builder.CreateDockerfile(config); err != nil {
		buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason(
			utilstatus.ReasonDockerfileCreateFailed,
			utilstatus.ReasonMessageDockerfileCreateFailed,
		)
		return buildResult, err
	}

	glog.V(2).Info("Creating application source code image")
	tarStream := builder.tar.CreateTarStreamReader(filepath.Join(config.WorkingDir, "upload", "src"), false)
	defer tarStream.Close()

	outReader, outWriter := io.Pipe()
	go io.Copy(os.Stdout, outReader)

	opts := docker.BuildImageOptions{
		Name:         config.Tag,
		Stdin:        tarStream,
		Stdout:       outWriter,
		CGroupLimits: config.CGroupLimits,
	}

	glog.V(2).Info("Building the application source")
	if err := builder.docker.BuildImage(opts); err != nil {
		buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason(
			utilstatus.ReasonDockerImageBuildFailed,
			utilstatus.ReasonMessageDockerImageBuildFailed,
		)
		return buildResult, err
	}

	glog.V(2).Info("Cleaning up temporary containers")
	builder.garbage.Cleanup(config)

	var imageID string
	var err error
	if len(opts.Name) > 0 {
		if imageID, err = builder.docker.GetImageID(opts.Name); err != nil {
			buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason(
				utilstatus.ReasonGenericS2IBuildFailed,
				utilstatus.ReasonMessageGenericS2iBuildFailed,
			)
			return buildResult, err
		}
	}

	return &api.Result{
		Success:    true,
		WorkingDir: config.WorkingDir,
		ImageID:    imageID,
	}, nil
}
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
}