// Build creates tasks for copying the manifests
169990
func (b *ManifestsBuilder) Build(c *fi.ModelBuilderContext) error {
	// Write etcd manifests (currently etcd <=> master)
	if b.IsMaster {
		for _, manifest := range b.NodeupConfig.EtcdManifests {
			p, err := vfs.Context.BuildVfsPath(manifest)
			if err != nil {
				return fmt.Errorf("error parsing path for etcd manifest %s: %v", manifest, err)
			}
			data, err := p.ReadFile()
			if err != nil {
				return fmt.Errorf("error reading etcd manifest %s: %v", manifest, err)
			}

			name := p.Base()
			name = strings.TrimSuffix(name, filepath.Ext(name))

			key := "etcd-" + name

			manifestPath := "/etc/kubernetes/manifests/" + key + ".manifest"

			c.AddTask(&nodetasks.File{
				Contents: fi.NewBytesResource(data),
				Mode:     s("0440"),
				Path:     manifestPath,
				Type:     nodetasks.FileType_File,
			})
		}
	}

	return nil
}
789199
func (b *Builder) Build(plugins ...account.Plugin) (account.Account, error) {
	if b.settings.AddrGen == nil {
		b.settings.AddrGen = account.DefaultAddrGen(b.settings.SeedProv, true)
	}
	if b.settings.PrepareTransfers == nil {
		b.settings.PrepareTransfers = account.DefaultPrepareTransfers(b.settings.API, b.settings.SeedProv)
	}
	for _, p := range plugins {
		b.settings.Plugins[p.Name()] = p
	}
	settsCopy := *b.settings
	return account.NewAccount(&settsCopy)
}
1172847
func (bm *BuildManager) Build(ctx context.Context, config backend.BuildConfig) (*builder.Result, error) {
	buildsTriggered.Inc()
	if config.Options.Dockerfile == "" {
		config.Options.Dockerfile = builder.DefaultDockerfileName
	}

	source, dockerfile, err := remotecontext.Detect(config)
	if err != nil {
		return nil, err
	}
	defer func() {
		if source != nil {
			if err := source.Close(); err != nil {
				logrus.Debugf("[BUILDER] failed to remove temporary context: %v", err)
			}
		}
	}()

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	if src, err := bm.initializeClientSession(ctx, cancel, config.Options); err != nil {
		return nil, err
	} else if src != nil {
		source = src
	}

	builderOptions := builderOptions{
		Options:        config.Options,
		ProgressWriter: config.ProgressWriter,
		Backend:        bm.backend,
		PathCache:      bm.pathCache,
		IDMapping:      bm.idMapping,
	}
	b, err := newBuilder(ctx, builderOptions)
	if err != nil {
		return nil, err
	}
	return b.build(source, dockerfile)
}
1366659
func (b *Builder) Build(p *Params) {
	go b.registerSignalHandler()
	go func() {
		// used for triggering the first build
		b.watcher.update <- struct{}{}
	}()

	for range b.watcher.Wait() {
		fileName := p.generateBinaryName()

		pkg := p.packagePath()

		log.Println("build started")
		color.Cyan("Building %s...\n", pkg)

		// build package
		cmd, err := runCommand("go", "build", "-i", "-o", fileName, pkg)
		if err != nil {
			log.Fatalf("Could not run 'go build' command: %s", err)
			continue
		}

		if err := cmd.Wait(); err != nil {
			if err := interpretError(err); err != nil {
				color.Red("An error occurred while building: %s", err)
			} else {
				color.Red("A build error occurred. Please update your code...")
			}

			continue
		}
		log.Println("build completed")

		// and start the new process
		b.runner.restart(fileName)
	}
}
1103569
func (b *Builder) Build() (*FileSorter, error) {
	// Sanity checks
	if b.sc == nil {
		return nil, errors.New("StatementContext is nil")
	}
	if b.keySize != len(b.byDesc) {
		return nil, errors.New("mismatch in key size and byDesc slice")
	}
	if b.keySize <= 0 {
		return nil, errors.New("key size is not positive")
	}
	if b.valSize <= 0 {
		return nil, errors.New("value size is not positive")
	}
	if b.bufSize <= 0 {
		return nil, errors.New("buffer size is not positive")
	}
	_, err := os.Stat(b.tmpDir)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, errors.New("tmpDir does not exist")
		}
		return nil, errors.Trace(err)
	}

	ws := make([]*Worker, b.nWorkers)
	for i := range ws {
		ws[i] = &Worker{
			keySize: b.keySize,
			valSize: b.valSize,
			rowSize: b.keySize + b.valSize + 1,
			bufSize: b.bufSize / b.nWorkers,
			buf:     make([]*comparableRow, 0, b.bufSize/b.nWorkers),
			head:    make([]byte, headSize),
		}
	}

	rh := &rowHeap{sc: b.sc,
		ims:    make([]*item, 0),
		byDesc: b.byDesc,
	}

	fs := &FileSorter{sc: b.sc,
		workers:  ws,
		nWorkers: b.nWorkers,
		cWorker:  0,

		head:    make([]byte, headSize),
		dcod:    make([]types.Datum, 0, b.keySize+b.valSize+1),
		keySize: b.keySize,
		valSize: b.valSize,

		tmpDir:  b.tmpDir,
		files:   make([]string, 0),
		byDesc:  b.byDesc,
		rowHeap: rh,
	}

	for i := 0; i < b.nWorkers; i++ {
		fs.workers[i].ctx = fs
	}

	return fs, nil
}
750042
func (op *AddUnitOperation) Build(attempt int) ([]txn.Op, error) {
	if alive, err := isAlive(op.application.st, applicationsC, op.application.doc.DocID); err != nil {
		return nil, err
	} else if !alive {
		return nil, applicationNotAliveErr
	}

	var ops []txn.Op

	addUnitArgs := AddUnitParams{
		ProviderId: op.props.ProviderId,
		Address:    op.props.Address,
		Ports:      op.props.Ports,
	}
	name, addOps, err := op.application.addUnitOps("", addUnitArgs, nil)
	if err != nil {
		return nil, errors.Trace(err)
	}

	op.unitName = name
	ops = append(ops, addOps...)

	if op.props.CloudContainerStatus != nil {
		now := op.application.st.clock().Now()
		doc := statusDoc{
			Status:     op.props.CloudContainerStatus.Status,
			StatusInfo: op.props.CloudContainerStatus.Message,
			StatusData: mgoutils.EscapeKeys(op.props.CloudContainerStatus.Data),
			Updated:    now.UnixNano(),
		}

		newStatusOps := createStatusOp(op.application.st, globalCloudContainerKey(name), doc)
		ops = append(ops, newStatusOps)
	}

	return ops, nil
}
930000
func (*Builder) Build(ctx *context.Context, build config.Build, options api.Options) error {
	if err := checkMain(build); err != nil {
		return err
	}
	target, err := newBuildTarget(options.Target)
	if err != nil {
		return err
	}

	var cmd = []string{"go", "build"}

	var env = append(ctx.Env.Strings(), build.Env...)
	env = append(env, target.Env()...)

	flags, err := processFlags(ctx, env, build.Flags, "")
	if err != nil {
		return err
	}
	cmd = append(cmd, flags...)

	asmflags, err := processFlags(ctx, env, build.Asmflags, "-asmflags=")
	if err != nil {
		return err
	}
	cmd = append(cmd, asmflags...)

	gcflags, err := processFlags(ctx, env, build.Gcflags, "-gcflags=")
	if err != nil {
		return err
	}
	cmd = append(cmd, gcflags...)

	ldflags, err := processFlags(ctx, env, build.Ldflags, "-ldflags=")
	if err != nil {
		return err
	}
	cmd = append(cmd, ldflags...)

	cmd = append(cmd, "-o", options.Path, build.Main)
	if err := run(ctx, cmd, env); err != nil {
		return errors.Wrapf(err, "failed to build for %s", options.Target)
	}
	ctx.Artifacts.Add(artifact.Artifact{
		Type:   artifact.Binary,
		Path:   options.Path,
		Name:   options.Name,
		Goos:   target.os,
		Goarch: target.arch,
		Goarm:  target.arm,
		Extra: map[string]interface{}{
			"Binary": build.Binary,
			"Ext":    options.Ext,
			"ID":     build.ID,
		},
	})
	return nil
}
25225
func (g *Gen) Build(config *Config) error {
	if _, err := os.Stat(config.SearchDir); os.IsNotExist(err) {
		return fmt.Errorf("dir: %s is not exist", config.SearchDir)
	}

	log.Println("Generate swagger docs....")
	p := swag.New()
	p.PropNamingStrategy = config.PropNamingStrategy
	p.ParseVendor = config.ParseVendor

	if err := p.ParseAPI(config.SearchDir, config.MainAPIFile); err != nil {
		return err
	}
	swagger := p.GetSwagger()

	b, err := json.MarshalIndent(swagger, "", "    ")
	if err != nil {
		return err
	}

	os.MkdirAll(config.OutputDir, os.ModePerm)
	docs, err := os.Create(path.Join(config.OutputDir, "docs.go"))
	if err != nil {
		return err
	}
	defer docs.Close()

	swaggerJSON, err := os.Create(path.Join(config.OutputDir, "swagger.json"))
	if err != nil {
		return err
	}

	defer swaggerJSON.Close()
	swaggerJSON.Write(b)

	swaggerYAML, err := os.Create(path.Join(config.OutputDir, "swagger.yaml"))
	if err != nil {
		return err
	}

	defer swaggerYAML.Close()
	y, err := yaml.JSONToYAML(b)
	if err != nil {
		return errors.Wrap(err, "cannot covert json to yaml")
	}

	swaggerYAML.Write(y)

	if err := packageTemplate.Execute(docs, struct {
		Timestamp time.Time
		Doc       string
	}{
		Timestamp: time.Now(),
		Doc:       "`" + string(b) + "`",
	}); err != nil {
		return err
	}

	log.Printf("create docs.go at  %+v", docs.Name())
	log.Printf("create swagger.json at  %+v", swaggerJSON.Name())
	log.Printf("create swagger.yaml at  %+v", swaggerYAML.Name())

	return nil
}
763208
func (o *objectCache) build(ctx context.Context, cfg *templateCfg, hash string) error {
	templatePath := filepath.Join(o.workingDirectory, defaults.TemplatesDir, hash)
	headerPath := filepath.Join(templatePath, common.CHeaderFileName)
	objectPath := filepath.Join(templatePath, endpointObj)

	if err := os.MkdirAll(templatePath, defaults.StateDirRights); err != nil {
		return &os.PathError{
			Op:   "failed to create template directory",
			Path: templatePath,
			Err:  err,
		}
	}

	f, err := os.Create(headerPath)
	if err != nil {
		return &os.PathError{
			Op:   "failed to open template header for writing",
			Path: headerPath,
			Err:  err,
		}
	}

	if err = o.Datapath.WriteEndpointConfig(f, cfg); err != nil {
		return &os.PathError{
			Op:   "failed to write template header",
			Path: headerPath,
			Err:  err,
		}
	}

	cfg.stats.bpfCompilation.Start()
	err = compileTemplate(ctx, templatePath)
	cfg.stats.bpfCompilation.End(err == nil)
	if err != nil {
		return &os.PathError{
			Op:   "failed to compile template program",
			Path: templatePath,
			Err:  err,
		}
	}

	log.WithFields(logrus.Fields{
		logfields.Path:               objectPath,
		logfields.BPFCompilationTime: cfg.stats.bpfCompilation.Total(),
	}).Info("Compiled new BPF template")

	o.insert(hash, objectPath)
	return nil
}
117093
func (b *Builder) Build() *TaskEnv {
	nodeAttrs := make(map[string]string)
	envMap := make(map[string]string)
	var deviceEnvs map[string]string

	b.mu.RLock()
	defer b.mu.RUnlock()

	// Add the directories
	if b.allocDir != "" {
		envMap[AllocDir] = b.allocDir
	}
	if b.localDir != "" {
		envMap[TaskLocalDir] = b.localDir
	}
	if b.secretsDir != "" {
		envMap[SecretsDir] = b.secretsDir
	}

	// Add the resource limits
	if b.memLimit != 0 {
		envMap[MemLimit] = strconv.FormatInt(b.memLimit, 10)
	}
	if b.cpuLimit != 0 {
		envMap[CpuLimit] = strconv.FormatInt(b.cpuLimit, 10)
	}

	// Add the task metadata
	if b.allocId != "" {
		envMap[AllocID] = b.allocId
	}
	if b.allocName != "" {
		envMap[AllocName] = b.allocName
	}
	if b.groupName != "" {
		envMap[GroupName] = b.groupName
	}
	if b.allocIndex != -1 {
		envMap[AllocIndex] = strconv.Itoa(b.allocIndex)
	}
	if b.taskName != "" {
		envMap[TaskName] = b.taskName
	}
	if b.jobName != "" {
		envMap[JobName] = b.jobName
	}
	if b.datacenter != "" {
		envMap[Datacenter] = b.datacenter
	}
	if b.region != "" {
		envMap[Region] = b.region

		// Copy region over to node attrs
		nodeAttrs[nodeRegionKey] = b.region
	}

	// Build the network related env vars
	buildNetworkEnv(envMap, b.networks, b.driverNetwork)

	// Build the addr of the other tasks
	for k, v := range b.otherPorts {
		envMap[k] = v
	}

	// Build the Vault Token
	if b.injectVaultToken && b.vaultToken != "" {
		envMap[VaultToken] = b.vaultToken
	}

	// Build the Vault Namespace
	if b.injectVaultToken && b.vaultNamespace != "" {
		envMap[VaultNamespace] = b.vaultNamespace
	}

	// Copy task meta
	for k, v := range b.taskMeta {
		envMap[k] = v
	}

	// Copy node attributes
	for k, v := range b.nodeAttrs {
		nodeAttrs[k] = v
	}

	// Interpolate and add environment variables
	for k, v := range b.hostEnv {
		envMap[k] = hargs.ReplaceEnv(v, nodeAttrs, envMap)
	}

	// Copy interpolated task env vars second as they override host env vars
	for k, v := range b.envvars {
		envMap[k] = hargs.ReplaceEnv(v, nodeAttrs, envMap)
	}

	// Copy hook env vars in the order the hooks were run
	for _, h := range b.hookNames {
		for k, v := range b.hookEnvs[h] {
			e := hargs.ReplaceEnv(v, nodeAttrs, envMap)
			envMap[k] = e

			if h == b.deviceHookName {
				if deviceEnvs == nil {
					deviceEnvs = make(map[string]string, len(b.hookEnvs[h]))
				}

				deviceEnvs[k] = e
			}
		}
	}

	// Copy template env vars as they override task env vars
	for k, v := range b.templateEnv {
		envMap[k] = v
	}

	// Clean keys (see #2405)
	cleanedEnv := make(map[string]string, len(envMap))
	for k, v := range envMap {
		cleanedK := helper.CleanEnvVar(k, '_')
		cleanedEnv[cleanedK] = v
	}

	var cleanedDeviceEnvs map[string]string
	if deviceEnvs != nil {
		cleanedDeviceEnvs = make(map[string]string, len(deviceEnvs))
		for k, v := range deviceEnvs {
			cleanedK := helper.CleanEnvVar(k, '_')
			cleanedDeviceEnvs[cleanedK] = v
		}
	}

	return NewTaskEnv(cleanedEnv, cleanedDeviceEnvs, nodeAttrs)
}
804462
func (b *EtcdManagerTLSBuilder) Build(ctx *fi.ModelBuilderContext) error {
	if !b.IsMaster {
		return nil
	}

	for _, k := range []string{"main", "events"} {
		d := "/etc/kubernetes/pki/etcd-manager-" + k

		keys := make(map[string]string)
		keys["etcd-manager-ca"] = "etcd-manager-ca-" + k
		keys["etcd-peers-ca"] = "etcd-peers-ca-" + k
		// Because API server can only have a single client-cert, we need to share a client CA
		keys["etcd-clients-ca"] = "etcd-clients-ca"

		for fileName, keystoreName := range keys {
			cert, err := b.KeyStore.FindCert(keystoreName)
			if err != nil {
				return err
			}
			if cert == nil {
				glog.Warningf("keypair %q not found, won't configure", keystoreName)
				continue
			}

			if err := b.BuildCertificateTask(ctx, keystoreName, d+"/"+fileName+".crt"); err != nil {
				return err
			}
			if err := b.BuildPrivateKeyTask(ctx, keystoreName, d+"/"+fileName+".key"); err != nil {
				return err
			}
		}
	}

	// We also dynamically generate the client keypair for apiserver
	if err := b.buildKubeAPIServerKeypair(); err != nil {
		return err
	}
	return nil
}
467003
func (b *Builder) Build() (*ZkPlus, error) {
	prefix := b.pathPrefix
	if len(prefix) == 0 {
		prefix = ""
	} else if prefix[0] != '/' {
		return nil, errInvalidPathPrefix
	} else if prefix[len(prefix)-1] == '/' {
		return nil, errInvalidPathSuffix
	}
	b.logger.Log(logkey.ZkPrefix, prefix, "new with prefix")

	ret := &ZkPlus{
		pathPrefix: prefix,
		logger:     b.logger,

		zkConnector: b.zkConnector,
		exposedChan: make(chan zk.Event),
		shouldQuit:  make(chan chan struct{}),
		askForConn:  make(chan chan zktest.ZkConnSupported),
	}
	go ret.eventLoop()
	return ret, nil
}
236800
func (r *Request) Build() error {
	err := r.check()
	if err != nil {
		return err
	}

	err = r.build()
	if err != nil {
		return err
	}

	return nil
}
496072
func (h *HookBuilder) Build(c *fi.ModelBuilderContext) error {
	// we keep a list of hooks name so we can allow local instanceGroup hooks override the cluster ones
	hookNames := make(map[string]bool, 0)
	for i, spec := range []*[]kops.HookSpec{&h.InstanceGroup.Spec.Hooks, &h.Cluster.Spec.Hooks} {
		for j, hook := range *spec {
			isInstanceGroup := i == 0
			// filter roles if required
			if len(hook.Roles) > 0 && !containsRole(h.InstanceGroup.Spec.Role, hook.Roles) {
				continue
			}

			// I don't want to affect those whom are already using the hooks, so I'm going to try to keep the name for now
			// i.e. use the default naming convention - kops-hook-<index>, only those using the Name or hooks in IG should alter
			var name string
			switch hook.Name {
			case "":
				name = fmt.Sprintf("kops-hook-%d", j)
				if isInstanceGroup {
					name += "-ig"
				}
			default:
				name = hook.Name
			}

			if _, found := hookNames[name]; found {
				glog.V(2).Infof("Skipping the hook: %v as we've already processed a similar service name", name)
				continue
			}
			hookNames[name] = true

			// are we disabling the service?
			if hook.Disabled {
				enabled := false
				managed := true
				c.AddTask(&nodetasks.Service{
					Name:        h.EnsureSystemdSuffix(name),
					ManageState: &managed,
					Enabled:     &enabled,
					Running:     &enabled,
				})
				continue
			}

			service, err := h.buildSystemdService(name, &hook)
			if err != nil {
				return err
			}

			if service != nil {
				c.AddTask(service)
			}
		}
	}

	return nil
}
1317826
func (b *RefreshGraphBuilder) Build(path addrs.ModuleInstance) (*Graph, tfdiags.Diagnostics) {
	return (&BasicGraphBuilder{
		Steps:    b.Steps(),
		Validate: b.Validate,
		Name:     "RefreshGraphBuilder",
	}).Build(path)
}
185297
func (b *StorageAclBuilder) Build(c *fi.ModelBuilderContext) error {
	serviceAccount, err := b.Cloud.ServiceAccount()
	if err != nil {
		return fmt.Errorf("error fetching ServiceAccount: %v", err)
	}

	if featureflag.GoogleCloudBucketACL.Enabled() {
		clusterPath := b.Cluster.Spec.ConfigBase
		p, err := vfs.Context.BuildVfsPath(clusterPath)
		if err != nil {
			return fmt.Errorf("cannot parse cluster path %q: %v", clusterPath, err)
		}

		switch p := p.(type) {
		case *vfs.GSPath:
			// It's not ideal that we have to do this at the bucket level,
			// but GCS doesn't seem to have a way to do subtrees (like AWS IAM does)
			// Note this permission only lets us list objects, not read them
			c.AddTask(&gcetasks.StorageBucketAcl{
				Name:      s("serviceaccount-statestore-list"),
				Lifecycle: b.Lifecycle,
				Bucket:    s(p.Bucket()),
				Entity:    s("user-" + serviceAccount),
				Role:      s("READER"),
			})
		}
	}

	glog.Warningf("we need to split master / node roles")
	role := kops.InstanceGroupRoleMaster
	writeablePaths, err := iam.WriteableVFSPaths(b.Cluster, role)
	if err != nil {
		return err
	}

	buckets := sets.NewString()
	for _, p := range writeablePaths {
		if gcsPath, ok := p.(*vfs.GSPath); ok {
			bucket := gcsPath.Bucket()
			if buckets.Has(bucket) {
				continue
			}

			glog.Warningf("adding bucket level write ACL to gs://%s to support etcd backup", bucket)

			c.AddTask(&gcetasks.StorageBucketAcl{
				Name:      s("serviceaccount-backup-readwrite-" + bucket),
				Lifecycle: b.Lifecycle,
				Bucket:    s(bucket),
				Entity:    s("user-" + serviceAccount),
				Role:      s("WRITER"),
			})

			buckets.Insert(bucket)
		} else {
			glog.Warningf("unknown path, can't apply IAM policy: %q", p)
		}
	}

	return nil
}
906810
func (b *multiErrBuilder) Build() error {
	if len(b.errs) == 0 {
		return nil
	}

	msgs := make([]string, len(b.errs))

	for i, err := range b.errs {
		msgs[i] = err.Error()
	}

	return errors.New(strings.Join(msgs, " AND "))
}