// Build is responsible for pulling down the secrets
975314
func (b *SecretBuilder) Build(c *fi.ModelBuilderContext) error {
	if b.KeyStore == nil {
		return fmt.Errorf("KeyStore not set")
	}

	// @step: retrieve the platform ca
	if err := b.BuildCertificateTask(c, fi.CertificateId_CA, "ca.crt"); err != nil {
		return err
	}

	if b.SecretStore != nil {
		key := "dockerconfig"
		dockercfg, _ := b.SecretStore.Secret(key)
		if dockercfg != nil {
			contents := string(dockercfg.Data)
			c.AddTask(&nodetasks.File{
				Path:     filepath.Join("root", ".docker", "config.json"),
				Contents: fi.NewStringResource(contents),
				Type:     nodetasks.FileType_File,
				Mode:     s("0600"),
			})
		}
	}

	// if we are not a master we can stop here
	if !b.IsMaster {
		return nil
	}

	{
		name := "master"
		if err := b.BuildCertificateTask(c, name, "server.cert"); err != nil {
			return err
		}
		if err := b.BuildPrivateKeyTask(c, name, "server.key"); err != nil {
			return err
		}
	}

	if b.IsKubernetesGTE("1.7") {
		// TODO: Remove - we use the apiserver-aggregator keypair instead (which is signed by a different CA)
		if err := b.BuildCertificateTask(c, "apiserver-proxy-client", "proxy-client.cert"); err != nil {
			return err
		}
		if err := b.BuildPrivateKeyTask(c, "apiserver-proxy-client", "proxy-client.key"); err != nil {
			return err
		}
	}

	if b.IsKubernetesGTE("1.7") {
		if err := b.BuildCertificateTask(c, "apiserver-aggregator", "apiserver-aggregator.cert"); err != nil {
			return err
		}
		if err := b.BuildPrivateKeyTask(c, "apiserver-aggregator", "apiserver-aggregator.key"); err != nil {
			return err
		}
	}

	if b.IsKubernetesGTE("1.7") {
		if err := b.BuildCertificateTask(c, "apiserver-aggregator-ca", "apiserver-aggregator-ca.cert"); err != nil {
			return err
		}
	}

	if b.SecretStore != nil {
		key := "kube"
		token, err := b.SecretStore.FindSecret(key)
		if err != nil {
			return err
		}
		if token == nil {
			return fmt.Errorf("token not found: %q", key)
		}
		csv := string(token.Data) + "," + adminUser + "," + adminUser + "," + adminGroup

		t := &nodetasks.File{
			Path:     filepath.Join(b.PathSrvKubernetes(), "basic_auth.csv"),
			Contents: fi.NewStringResource(csv),
			Type:     nodetasks.FileType_File,
			Mode:     s("0600"),
		}
		c.AddTask(t)
	}

	if b.SecretStore != nil {
		allTokens, err := b.allAuthTokens()
		if err != nil {
			return err
		}

		var lines []string
		for id, token := range allTokens {
			if id == adminUser {
				lines = append(lines, token+","+id+","+id+","+adminGroup)
			} else {
				lines = append(lines, token+","+id+","+id)
			}
		}
		csv := strings.Join(lines, "\n")

		c.AddTask(&nodetasks.File{
			Path:     filepath.Join(b.PathSrvKubernetes(), "known_tokens.csv"),
			Contents: fi.NewStringResource(csv),
			Type:     nodetasks.FileType_File,
			Mode:     s("0600"),
		})
	}

	return nil
}
59205
func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder.Result, error) {
	var rc = opt.Source

	if buildID := opt.Options.BuildID; buildID != "" {
		b.mu.Lock()

		upload := false
		if strings.HasPrefix(buildID, "upload-request:") {
			upload = true
			buildID = strings.TrimPrefix(buildID, "upload-request:")
		}

		if _, ok := b.jobs[buildID]; !ok {
			b.jobs[buildID] = newBuildJob()
		}
		j := b.jobs[buildID]
		var cancel func()
		ctx, cancel = context.WithCancel(ctx)
		j.cancel = cancel
		b.mu.Unlock()

		if upload {
			ctx2, cancel := context.WithTimeout(ctx, 5*time.Second)
			defer cancel()
			err := j.SetUpload(ctx2, rc)
			return nil, err
		}

		if remoteContext := opt.Options.RemoteContext; remoteContext == "upload-request" {
			ctx2, cancel := context.WithTimeout(ctx, 5*time.Second)
			defer cancel()
			var err error
			rc, err = j.WaitUpload(ctx2)
			if err != nil {
				return nil, err
			}
			opt.Options.RemoteContext = ""
		}

		defer func() {
			delete(b.jobs, buildID)
		}()
	}

	var out builder.Result

	id := identity.NewID()

	frontendAttrs := map[string]string{}

	if opt.Options.Target != "" {
		frontendAttrs["target"] = opt.Options.Target
	}

	if opt.Options.Dockerfile != "" && opt.Options.Dockerfile != "." {
		frontendAttrs["filename"] = opt.Options.Dockerfile
	}

	if opt.Options.RemoteContext != "" {
		if opt.Options.RemoteContext != "client-session" {
			frontendAttrs["context"] = opt.Options.RemoteContext
		}
	} else {
		url, cancel := b.reqBodyHandler.newRequest(rc)
		defer cancel()
		frontendAttrs["context"] = url
	}

	cacheFrom := append([]string{}, opt.Options.CacheFrom...)

	frontendAttrs["cache-from"] = strings.Join(cacheFrom, ",")

	for k, v := range opt.Options.BuildArgs {
		if v == nil {
			continue
		}
		frontendAttrs["build-arg:"+k] = *v
	}

	for k, v := range opt.Options.Labels {
		frontendAttrs["label:"+k] = v
	}

	if opt.Options.NoCache {
		frontendAttrs["no-cache"] = ""
	}

	if opt.Options.PullParent {
		frontendAttrs["image-resolve-mode"] = "pull"
	} else {
		frontendAttrs["image-resolve-mode"] = "default"
	}

	if opt.Options.Platform != "" {
		// same as in newBuilder in builder/dockerfile.builder.go
		// TODO: remove once opt.Options.Platform is of type specs.Platform
		sp, err := platforms.Parse(opt.Options.Platform)
		if err != nil {
			return nil, err
		}
		if err := system.ValidatePlatform(sp); err != nil {
			return nil, err
		}
		frontendAttrs["platform"] = opt.Options.Platform
	}

	switch opt.Options.NetworkMode {
	case "host", "none":
		frontendAttrs["force-network-mode"] = opt.Options.NetworkMode
	case "", "default":
	default:
		return nil, errors.Errorf("network mode %q not supported by buildkit", opt.Options.NetworkMode)
	}

	extraHosts, err := toBuildkitExtraHosts(opt.Options.ExtraHosts)
	if err != nil {
		return nil, err
	}
	frontendAttrs["add-hosts"] = extraHosts

	exporterName := ""
	exporterAttrs := map[string]string{}

	if len(opt.Options.Outputs) > 1 {
		return nil, errors.Errorf("multiple outputs not supported")
	} else if len(opt.Options.Outputs) == 0 {
		exporterName = "moby"
	} else {
		// cacheonly is a special type for triggering skipping all exporters
		if opt.Options.Outputs[0].Type != "cacheonly" {
			exporterName = opt.Options.Outputs[0].Type
			exporterAttrs = opt.Options.Outputs[0].Attrs
		}
	}

	if exporterName == "moby" {
		if len(opt.Options.Tags) > 0 {
			exporterAttrs["name"] = strings.Join(opt.Options.Tags, ",")
		}
	}

	cache := controlapi.CacheOptions{}

	if inlineCache := opt.Options.BuildArgs["BUILDKIT_INLINE_CACHE"]; inlineCache != nil {
		if b, err := strconv.ParseBool(*inlineCache); err == nil && b {
			cache.Exports = append(cache.Exports, &controlapi.CacheOptionsEntry{
				Type: "inline",
			})
		}
	}

	req := &controlapi.SolveRequest{
		Ref:           id,
		Exporter:      exporterName,
		ExporterAttrs: exporterAttrs,
		Frontend:      "dockerfile.v0",
		FrontendAttrs: frontendAttrs,
		Session:       opt.Options.SessionID,
		Cache:         cache,
	}

	if opt.Options.NetworkMode == "host" {
		req.Entitlements = append(req.Entitlements, entitlements.EntitlementNetworkHost)
	}

	aux := streamformatter.AuxFormatter{Writer: opt.ProgressWriter.Output}

	eg, ctx := errgroup.WithContext(ctx)

	eg.Go(func() error {
		resp, err := b.controller.Solve(ctx, req)
		if err != nil {
			return err
		}
		if exporterName != "moby" {
			return nil
		}
		id, ok := resp.ExporterResponse["containerimage.digest"]
		if !ok {
			return errors.Errorf("missing image id")
		}
		out.ImageID = id
		return aux.Emit("moby.image.id", types.BuildResult{ID: id})
	})

	ch := make(chan *controlapi.StatusResponse)

	eg.Go(func() error {
		defer close(ch)
		// streamProxy.ctx is not set to ctx because when request is cancelled,
		// only the build request has to be cancelled, not the status request.
		stream := &statusProxy{streamProxy: streamProxy{ctx: context.TODO()}, ch: ch}
		return b.controller.Status(&controlapi.StatusRequest{Ref: id}, stream)
	})

	eg.Go(func() error {
		for sr := range ch {
			dt, err := sr.Marshal()
			if err != nil {
				return err
			}
			if err := aux.Emit("moby.buildkit.trace", dt); err != nil {
				return err
			}
		}
		return nil
	})

	if err := eg.Wait(); err != nil {
		return nil, err
	}

	return &out, nil
}
1283889
func (p *PrintingKubeClient) Build(ns string, reader io.Reader) (kube.Result, error) {
	return []*resource.Info{}, nil
}
664966
func (builder *SearchCommandBuilder) Build() (Command, error) {
	if builder.protobuf == nil {
		panic("builder.protobuf must not be nil")
	}
	return &SearchCommand{protobuf: builder.protobuf}, nil
}
937728
func (builder *RequestBuilder) Build() (*kv.Request, error) {
	return &builder.Request, builder.err
}
300948
func (b *KubeRouterBuilder) Build(c *fi.ModelBuilderContext) error {
	{
		kubeconfig, err := b.BuildPKIKubeconfig("kube-router")
		if err != nil {
			return err
		}

		c.AddTask(&nodetasks.File{
			Path:     "/var/lib/kube-router/kubeconfig",
			Contents: fi.NewStringResource(kubeconfig),
			Type:     nodetasks.FileType_File,
			Mode:     s("0400"),
		})
	}

	return nil
}
1067134
func (b *Builder) Build() Container {
	if err := checkScopes(b.scopes); err != nil {
		return nil
	}

	defs := b.Definitions()

	for name, def := range defs {
		if def.Scope == "" {
			def.Scope = b.scopes[0]
			defs[name] = def
		}
	}

	return &container{
		containerCore: &containerCore{
			scopes:      b.scopes,
			scope:       b.scopes[0],
			definitions: defs,
			parent:      nil,
			children:    map[*containerCore]struct{}{},
			objects:     map[string]interface{}{},
		},
	}
}
840664
func (builder *TsDeleteRowCommandBuilder) Build() (Command, error) {
	if builder.protobuf == nil {
		panic("builder.protobuf must not be nil")
	}

	if len(builder.protobuf.GetTable()) == 0 {
		return nil, ErrTableRequired
	}

	if len(builder.protobuf.GetKey()) == 0 {
		return nil, ErrKeyRequired
	}

	return &TsDeleteRowCommand{
		timeoutImpl: timeoutImpl{
			timeout: builder.timeout,
		},
		protobuf: builder.protobuf,
	}, nil
}
1353882
func (b *OpenAPI2Builder) build(document *openapiv2.Document) (err error) {
	// Collect service type descriptions from Definitions section.
	if document.Definitions != nil {
		for _, pair := range document.Definitions.AdditionalProperties {
			t, err := b.buildTypeFromDefinition(pair.Name, pair.Value)
			if err != nil {
				return err
			}
			b.model.addType(t)
		}
	}
	// Collect service method descriptions from Paths section.
	if document.Paths != nil {
		for _, pair := range document.Paths.Path {
			v := pair.Value
			if v.Get != nil {
				b.buildMethodFromOperation(v.Get, "GET", pair.Name)
			}
			if v.Post != nil {
				b.buildMethodFromOperation(v.Post, "POST", pair.Name)
			}
			if v.Put != nil {
				b.buildMethodFromOperation(v.Put, "PUT", pair.Name)
			}
			if v.Delete != nil {
				b.buildMethodFromOperation(v.Delete, "DELETE", pair.Name)
			}
		}
	}
	return err
}
378229
func (b *NodeAuthorizationBuilder) Build(c *fi.ModelBuilderContext) error {
	// @check if we are a master and download the certificates for the node-authozier
	if b.UseBootstrapTokens() && b.IsMaster {
		name := "node-authorizer"
		// creates /src/kubernetes/node-authorizer/{tls,tls-key}.pem
		if err := b.BuildCertificatePairTask(c, name, name, "tls"); err != nil {
			return err
		}
		// creates /src/kubernetes/node-authorizer/ca.pem
		if err := b.BuildCertificateTask(c, fi.CertificateId_CA, filepath.Join(name, "ca.pem")); err != nil {
			return err
		}
	}

	authorizerDir := "node-authorizer"
	// @check if bootstrap tokens are enabled and download client certificates for nodes
	if b.UseBootstrapTokens() && !b.IsMaster {
		if err := b.BuildCertificatePairTask(c, "node-authorizer-client", authorizerDir, "tls"); err != nil {
			return err
		}
		if err := b.BuildCertificateTask(c, fi.CertificateId_CA, authorizerDir+"/ca.pem"); err != nil {
			return err
		}
	}

	glog.V(3).Infof("bootstrap: %t, node authorization: %t, node authorizer: %t", b.UseBootstrapTokens(),
		b.UseNodeAuthorization(), b.UseNodeAuthorizer())

	// @check if the NodeAuthorizer provision the client service for nodes
	if b.UseNodeAuthorizer() && !b.IsMaster {
		na := b.Cluster.Spec.NodeAuthorization.NodeAuthorizer

		glog.V(3).Infof("node authorization service is enabled, authorizer: %s", na.Authorizer)
		glog.V(3).Infof("node authorization url: %s", na.NodeURL)

		// @step: create the systemd unit to run the node authorization client
		man := &systemd.Manifest{}
		man.Set("Unit", "Description", "Node Authorization Client")
		man.Set("Unit", "Documentation", "https://github.com/kubernetes/kops")
		man.Set("Unit", "After", "docker.service")
		man.Set("Unit", "Before", "kubelet.service")

		clientCert := filepath.Join(b.PathSrvKubernetes(), authorizerDir, "tls.pem")
		man.Set("Service", "Type", "oneshot")
		man.Set("Service", "RemainAfterExit", "yes")
		man.Set("Service", "EnvironmentFile", "/etc/environment")
		man.Set("Service", "ExecStartPre", "/bin/mkdir -p /var/lib/kubelet")
		man.Set("Service", "ExecStartPre", "/usr/bin/docker pull "+na.Image)
		man.Set("Service", "ExecStartPre", "/bin/bash -c 'while [ ! -f "+clientCert+" ]; do sleep 5; done; sleep 5'")

		interval := 10 * time.Second
		timeout := 5 * time.Minute

		// @node: using a string array just to make it easier to read
		dockerCmd := []string{
			"/usr/bin/docker",
			"run",
			"--rm",
			"--net=host",
			"--volume=" + path.Dir(b.KubeletBootstrapKubeconfig()) + ":/var/lib/kubelet",
			"--volume=" + filepath.Join(b.PathSrvKubernetes(), authorizerDir) + ":/config:ro",
			na.Image,
			"client",
			"--authorizer=" + na.Authorizer,
			"--interval=" + interval.String(),
			"--kubeapi-url=" + fmt.Sprintf("https://%s", b.Cluster.Spec.MasterInternalName),
			"--kubeconfig=" + b.KubeletBootstrapKubeconfig(),
			"--node-url=" + na.NodeURL,
			"--timeout=" + timeout.String(),
			"--tls-client-ca=/config/ca.pem",
			"--tls-cert=/config/tls.pem",
			"--tls-private-key=/config/tls-key.pem",
		}
		man.Set("Service", "ExecStart", strings.Join(dockerCmd, " "))

		// @step: add the service task
		c.AddTask(&nodetasks.Service{
			Name: "node-authorizer.service",

			Definition:   s(man.Render()),
			Enabled:      fi.Bool(true),
			ManageState:  fi.Bool(true),
			Running:      fi.Bool(true),
			SmartRestart: fi.Bool(true),
		})
	}

	return nil
}
477162
func Build(payload Sendable) *Document {
	document := New()
	document.validated = true

	object, isObject := payload.(*Object)
	if isObject {
		document.Data = List{object}
		document.Status = object.Status
		document.Mode = ObjectMode
	}

	list, isList := payload.(List)
	if isList {
		document.Data = list
		document.Status = http.StatusOK
		document.Mode = ListMode
	}

	err, isError := payload.(*Error)
	if isError {
		document.Errors = ErrorList{err}
		document.Status = err.Status
		document.Mode = ErrorMode
	}

	errorList, isErrorList := payload.(ErrorList)
	if isErrorList {
		document.Errors = errorList
		document.Status = errorList[0].Status
		document.Mode = ErrorMode
	}

	return document
}
1089368
func Convert_v1_SecretBuildSource_To_build_SecretBuildSource(in *v1.SecretBuildSource, out *build.SecretBuildSource, s conversion.Scope) error {
	return autoConvert_v1_SecretBuildSource_To_build_SecretBuildSource(in, out, s)
}
962248
func (builder *DeleteValueCommandBuilder) Build() (Command, error) {
	if builder.protobuf == nil {
		panic("builder.protobuf must not be nil")
	}
	if err := validateLocatable(builder.protobuf); err != nil {
		return nil, err
	}
	return &DeleteValueCommand{
		timeoutImpl: timeoutImpl{
			timeout: builder.timeout,
		},
		protobuf: builder.protobuf,
	}, nil
}
1054102
func (o *FindTodosURL) Build() (*url.URL, error) {
	var _result url.URL

	var _path = "/"

	_basePath := o._basePath
	_result.Path = golangswaggerpaths.Join(_basePath, _path)

	qs := make(url.Values)

	var limit string
	if o.Limit != nil {
		limit = swag.FormatInt32(*o.Limit)
	}
	if limit != "" {
		qs.Set("limit", limit)
	}

	var since string
	if o.Since != nil {
		since = swag.FormatInt64(*o.Since)
	}
	if since != "" {
		qs.Set("since", since)
	}

	_result.RawQuery = qs.Encode()

	return &_result, nil
}
504547
func (b *DiskBuilder) Build() (*DiskBuildResult, error) {

	// start
	b.callEventHandlerIfExists(DiskBuildOnStart)

	// create parameters
	b.currentDiskBuildValue = &DiskBuildValue{}
	b.currentDiskBuildResult = &DiskBuildResult{}

	if err := b.buildDiskParams(); err != nil {
		return nil, err
	}

	// create disk
	b.callEventHandlerIfExists(DiskBuildOnCreateDiskBefore)
	if err := b.createDisk(b.currentDiskBuildValue.Disk, b.currentDiskBuildValue.Edit); err != nil {
		return b.currentDiskBuildResult, err
	}
	b.callEventHandlerIfExists(DiskBuildOnCreateDiskAfter)

	// cleanup
	if b.isSSHKeysEphemeral && (len(b.currentDiskBuildResult.SSHKeys) > 0 || b.currentDiskBuildResult.GeneratedSSHKey != nil) {
		b.callEventHandlerIfExists(DiskBuildOnCleanupSSHKeyBefore)

		// created keys
		for _, key := range b.currentDiskBuildResult.SSHKeys {
			_, err := b.client.SSHKeyDelete(key.ID)
			if err != nil {
				return b.currentDiskBuildResult, err
			}
		}

		// generated key
		if b.currentDiskBuildResult.GeneratedSSHKey != nil {
			_, err := b.client.SSHKeyDelete(b.currentDiskBuildResult.GeneratedSSHKey.ID)
			if err != nil {
				return b.currentDiskBuildResult, err
			}
		}

		b.callEventHandlerIfExists(DiskBuildOnCleanupSSHKeyAfter)
	}
	if b.isNotesEphemeral && len(b.currentDiskBuildResult.Notes) > 0 {
		b.callEventHandlerIfExists(DiskBuildOnCleanupNoteBefore)

		for _, note := range b.currentDiskBuildResult.Notes {
			_, err := b.client.NoteDelete(note.ID)
			if err != nil {
				return b.currentDiskBuildResult, err
			}
		}

		b.callEventHandlerIfExists(DiskBuildOnCleanupNoteAfter)
	}

	b.callEventHandlerIfExists(DiskBuildOnComplete)

	return b.currentDiskBuildResult, nil
}
484916
func (r *Request) Build() {
	if !r.built {
		r.Handlers.Build.Run(r)
		r.built = true
		if r.Error != nil {
			return
		}
		r.Handlers.Sign.Run(r)
	}
}
143936
func (h *HugoSites) Build(config BuildCfg, events ...fsnotify.Event) error {
	ctx, task := trace.NewTask(context.Background(), "Build")
	defer task.End()

	errCollector := h.StartErrorCollector()
	errs := make(chan error)

	go func(from, to chan error) {
		var errors []error
		i := 0
		for e := range from {
			i++
			if i > 50 {
				break
			}
			errors = append(errors, e)
		}
		to <- h.pickOneAndLogTheRest(errors)

		close(to)

	}(errCollector, errs)

	if h.Metrics != nil {
		h.Metrics.Reset()
	}

	// Need a pointer as this may be modified.
	conf := &config

	if conf.whatChanged == nil {
		// Assume everything has changed
		conf.whatChanged = &whatChanged{source: true, other: true}
	}

	var prepareErr error

	if !config.PartialReRender {
		prepare := func() error {
			for _, s := range h.Sites {
				s.Deps.BuildStartListeners.Notify()
			}

			if len(events) > 0 {
				// Rebuild
				if err := h.initRebuild(conf); err != nil {
					return err
				}
			} else {
				if err := h.initSites(conf); err != nil {
					return err
				}
			}

			var err error

			f := func() {
				err = h.process(conf, events...)
			}
			trace.WithRegion(ctx, "process", f)
			if err != nil {
				return err
			}

			f = func() {
				err = h.assemble(conf)
			}
			trace.WithRegion(ctx, "assemble", f)
			if err != nil {
				return err
			}

			return nil
		}

		f := func() {
			prepareErr = prepare()
		}
		trace.WithRegion(ctx, "prepare", f)
		if prepareErr != nil {
			h.SendError(prepareErr)
		}

	}

	if prepareErr == nil {
		var err error
		f := func() {
			err = h.render(conf)
		}
		trace.WithRegion(ctx, "render", f)
		if err != nil {
			h.SendError(err)
		}
	}

	if h.Metrics != nil {
		var b bytes.Buffer
		h.Metrics.WriteMetrics(&b)

		h.Log.FEEDBACK.Printf("\nTemplate Metrics:\n\n")
		h.Log.FEEDBACK.Print(b.String())
		h.Log.FEEDBACK.Println()
	}

	select {
	// Make sure the channel always gets something.
	case errCollector <- nil:
	default:
	}
	close(errCollector)

	err := <-errs
	if err != nil {
		return err
	}

	if err := h.fatalErrorHandler.getErr(); err != nil {
		return err
	}

	errorCount := h.Log.ErrorCounter.Count()
	if errorCount > 0 {
		return fmt.Errorf("logged %d error(s)", errorCount)
	}

	return nil

}