// BuildImage builds an image from a tarball's url or a Dockerfile in the input
// stream.
//
// See https://goo.gl/4nYHwV for more details.
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,
	})
}
1298813
func (r *ImageRef) BuildOutput() (*buildv1.BuildOutput, error) {
	if r == nil {
		return &buildv1.BuildOutput{}, nil
	}
	if !r.AsImageStream {
		return &buildv1.BuildOutput{
			To: &corev1.ObjectReference{
				Kind: "DockerImage",
				Name: r.Reference.String(),
			},
		}, nil
	}
	imageRepo, err := r.ImageStream()
	if err != nil {
		return nil, err
	}
	return &buildv1.BuildOutput{
		To: &corev1.ObjectReference{
			Kind: "ImageStreamTag",
			Name: imageapi.JoinImageStreamTag(imageRepo.Name, r.Reference.Tag),
		},
	}, nil
}
979331
func (s *IndicesRolloverService) buildURL() (string, url.Values, error) {
	// Build URL
	var err error
	var path string
	if s.newIndex != "" {
		path, err = uritemplates.Expand("/{alias}/_rollover/{new_index}", map[string]string{
			"alias":     s.alias,
			"new_index": s.newIndex,
		})
	} else {
		path, err = uritemplates.Expand("/{alias}/_rollover", map[string]string{
			"alias": s.alias,
		})
	}
	if err != nil {
		return "", url.Values{}, err
	}

	// Add query string parameters
	params := url.Values{}
	if s.pretty {
		params.Set("pretty", "true")
	}
	if s.dryRun {
		params.Set("dry_run", "true")
	}
	if s.masterTimeout != "" {
		params.Set("master_timeout", s.masterTimeout)
	}
	if s.timeout != "" {
		params.Set("timeout", s.timeout)
	}
	if s.waitForActiveShards != "" {
		params.Set("wait_for_active_shards", s.waitForActiveShards)
	}
	return path, params, nil
}
255635
func (client *Client) CopyImage(args *CopyImageArgs) (string, error) {
	response := &CopyImageResponse{}
	err := client.Invoke("CopyImage", args, &response)
	if err != nil {
		return "", err
	}
	return response.ImageId, 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
}
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)
}
887648
func (ds *dockerService) PullImage(_ context.Context, r *runtimeapi.PullImageRequest) (*runtimeapi.PullImageResponse, error) {
	image := r.GetImage()
	auth := r.GetAuth()
	authConfig := dockertypes.AuthConfig{}

	if auth != nil {
		authConfig.Username = auth.Username
		authConfig.Password = auth.Password
		authConfig.ServerAddress = auth.ServerAddress
		authConfig.IdentityToken = auth.IdentityToken
		authConfig.RegistryToken = auth.RegistryToken
	}
	err := ds.client.PullImage(image.Image,
		authConfig,
		dockertypes.ImagePullOptions{},
	)
	if err != nil {
		return nil, filterHTTPError(err, image.Image)
	}

	imageRef, err := getImageRef(ds.client, image.Image)
	if err != nil {
		return nil, err
	}

	return &runtimeapi.PullImageResponse{ImageRef: imageRef}, 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
}
1189238
func (b *Builder) build(source builder.Source, dockerfile *parser.Result) (*builder.Result, error) {
	defer b.imageSources.Unmount()

	stages, metaArgs, err := instructions.Parse(dockerfile.AST)
	if err != nil {
		if instructions.IsUnknownInstruction(err) {
			buildsFailed.WithValues(metricsUnknownInstructionError).Inc()
		}
		return nil, errdefs.InvalidParameter(err)
	}
	if b.options.Target != "" {
		targetIx, found := instructions.HasStage(stages, b.options.Target)
		if !found {
			buildsFailed.WithValues(metricsBuildTargetNotReachableError).Inc()
			return nil, errdefs.InvalidParameter(errors.Errorf("failed to reach build target %s in Dockerfile", b.options.Target))
		}
		stages = stages[:targetIx+1]
	}

	// Add 'LABEL' command specified by '--label' option to the last stage
	buildLabelOptions(b.options.Labels, stages)

	dockerfile.PrintWarnings(b.Stderr)
	dispatchState, err := b.dispatchDockerfileWithCancellation(stages, metaArgs, dockerfile.EscapeToken, source)
	if err != nil {
		return nil, err
	}
	if dispatchState.imageID == "" {
		buildsFailed.WithValues(metricsDockerfileEmptyError).Inc()
		return nil, errors.New("No image was generated. Is your Dockerfile empty?")
	}
	return &builder.Result{ImageID: dispatchState.imageID, FromImage: dispatchState.baseImage}, nil
}
629652
func Convert_v1_ImageSourcePath_To_build_ImageSourcePath(in *v1.ImageSourcePath, out *build.ImageSourcePath, s conversion.Scope) error {
	return autoConvert_v1_ImageSourcePath_To_build_ImageSourcePath(in, out, s)
}
66972
func (c *Calcium) BuildImage(ctx context.Context, opts *enginetypes.BuildOptions) (chan *types.BuildImageMessage, error) {
	// Disable build API if scm not set
	if c.source == nil {
		return nil, types.ErrSCMNotSet
	}
	// select nodes
	node, err := c.selectBuildNode(ctx)
	if err != nil {
		return nil, err
	}
	log.Infof("[BuildImage] Building image at pod %s node %s", node.Podname, node.Name)
	// get refs
	refs := node.Engine.BuildRefs(ctx, opts.Name, opts.Tags)
	// support raw build
	buildContent := opts.Tar
	if opts.Builds != nil {
		buildContent, err = node.Engine.BuildContent(ctx, c.source, opts)
		if err != nil {
			return nil, err
		}
	}

	return c.doBuildImage(ctx, buildContent, node, refs)
}
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)

}
1277533
func (c *container) buildImage(nocache bool) {
	executeHook(c.Hooks().PreBuild(), c.ActualName(false))
	fmt.Fprintf(c.CommandsOut(), "Building image %s ...\n", c.Image())
	args := []string{"build"}
	if nocache {
		args = append(args, "--no-cache")
	}
	args = append(args, "--rm", "--tag="+c.Image())
	if len(c.BuildParams().File()) > 0 {
		args = append(args, "--file="+filepath.FromSlash(c.BuildParams().Context()+"/"+c.BuildParams().File()))
	}
	for _, arg := range c.BuildParams().BuildArgs() {
		args = append(args, "--build-arg", arg)
	}

	args = append(args, c.BuildParams().Context())
	executeCommand("docker", args, c.CommandsOut(), c.CommandsErr())
	executeHook(c.Hooks().PostBuild(), c.ActualName(false))
}
671384
func (b *Builder) Build(images []*Image) error {
	builds := make(map[string]*Build, len(images))
	for _, image := range images {
		builds[image.ID] = NewBuild(image)
	}

	addDependency := func(build *Build, dependsOn string) error {
		dep, ok := builds[dependsOn]
		if !ok {
			return fmt.Errorf("unknown image dependency: %s -> %s", build.Image.ID, dependsOn)
		}
		build.AddDependency(dep)
		dep.AddDependent(build)
		return nil
	}

	for _, build := range builds {
		image := build.Image

		// determine build dependencies
		// TODO: check for circular dependencies
		if image.Base != "" {
			addDependency(build, image.Base)
		}
		for _, l := range image.Layers {
			// build Go binaries using the Go image
			if l.BuildWith == "" && (len(l.GoBuild) > 0 || len(l.CGoBuild) > 0) {
				l.BuildWith = "go"
			}
			if l.BuildWith != "" {
				addDependency(build, l.BuildWith)
			}
		}
	}

	// build images until there are no pending builds left
	done := make(chan *Build, len(builds))
	failures := make(map[string]error)
	for len(builds) > 0 {
		for _, build := range builds {
			// if the build has no more pending dependencies, build it
			if len(build.Dependencies) == 0 {
				build.Once.Do(func() {
					// if the build is aborted due to a dependency
					// failure, just send it to the done channel
					if build.Abort {
						b.log.Debug(fmt.Sprintf("%s build abort", build.Image.ID))
						done <- build
						return
					}

					b.log.Debug(fmt.Sprintf("%s build start", build.Image.ID))
					go func(build *Build) {
						build.StartedAt = time.Now()
						build.Err = b.BuildImage(build.Image)
						done <- build
					}(build)
				})
			}
		}

		// wait for a build to finish
		build := <-done
		b.bar.Increment()
		if build.Err == nil {
			b.log.Debug(fmt.Sprintf("%s build done", build.Image.ID), "duration", time.Since(build.StartedAt))
		} else {
			b.log.Error(fmt.Sprintf("%s build error", build.Image.ID), "duration", time.Since(build.StartedAt), "err", build.Err)
		}

		// remove from the pending list
		delete(builds, build.Image.ID)

		// remove the build as a pending dependency from all
		// dependents
		for dependent := range build.Dependents {
			// if the build failed or was aborted, abort the
			// dependent builds
			if build.Err != nil || build.Abort {
				dependent.Abort = true
			}
			dependent.RemoveDependency(build)
		}

		if build.Err != nil {
			failures[build.Image.ID] = build.Err
		}
	}

	if len(failures) > 0 {
		b.log.Error("the following builds failed:")
		for id, err := range failures {
			b.log.Error("* "+id, "err", err)
		}
		return fmt.Errorf("%d builds failed", len(failures))
	}

	return nil
}
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
}
165340
func (f *RemoteRuntime) PullImage(ctx context.Context, req *kubeapi.PullImageRequest) (*kubeapi.PullImageResponse, error) {
	image, err := f.ImageService.PullImage(req.Image, req.Auth, req.SandboxConfig)
	if err != nil {
		return nil, err
	}

	return &kubeapi.PullImageResponse{
		ImageRef: image,
	}, nil
}
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
}