// Build creates the tasks that set up storage acls
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
}
932569
func (t *ProtokubeBuilder) Build(c *fi.ModelBuilderContext) error {
	useGossip := dns.IsGossipHostname(t.Cluster.Spec.MasterInternalName)

	// check is not a master and we are not using gossip (https://github.com/kubernetes/kops/pull/3091)
	if !t.IsMaster && !useGossip {
		glog.V(2).Infof("skipping the provisioning of protokube on the nodes")
		return nil
	}

	if t.IsMaster {
		kubeconfig, err := t.BuildPKIKubeconfig("kops")
		if err != nil {
			return err
		}

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

		// retrieve the etcd peer certificates and private keys from the keystore
		if !t.UseEtcdManager() && t.UseEtcdTLS() {
			for _, x := range []string{"etcd", "etcd-peer", "etcd-client"} {
				if err := t.BuildCertificateTask(c, x, fmt.Sprintf("%s.pem", x)); err != nil {
					return err
				}
			}
			for _, x := range []string{"etcd", "etcd-peer", "etcd-client"} {
				if err := t.BuildPrivateKeyTask(c, x, fmt.Sprintf("%s-key.pem", x)); err != nil {
					return err
				}
			}
		}
	}

	service, err := t.buildSystemdService()
	if err != nil {
		return err
	}
	c.AddTask(service)

	return nil
}
1305006
func (builder *TsFetchRowCommandBuilder) 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 &TsFetchRowCommand{
		timeoutImpl: timeoutImpl{
			timeout: builder.timeout,
		},
		protobuf: builder.protobuf,
	}, nil
}
809707
func (b *FirewallModelBuilder) Build(c *fi.ModelBuilderContext) error {

	roles := []kops.InstanceGroupRole{kops.InstanceGroupRoleMaster, kops.InstanceGroupRoleNode}
	if b.UsesSSHBastion() {
		roles = append(roles, kops.InstanceGroupRoleBastion)
	}

	sgMap := make(map[string]*openstacktasks.SecurityGroup)

	if b.UseLoadBalancerForAPI() {
		sg := &openstacktasks.SecurityGroup{
			Name:      s(b.Cluster.Spec.MasterPublicName),
			Lifecycle: b.Lifecycle,
		}
		c.AddTask(sg)
		sgMap[b.Cluster.Spec.MasterPublicName] = sg
	}
	for _, role := range roles {

		// Create Security Group for Role
		groupName := b.SecurityGroupName(role)
		sg := &openstacktasks.SecurityGroup{
			Name:      s(groupName),
			Lifecycle: b.Lifecycle,
		}
		c.AddTask(sg)
		sgMap[groupName] = sg
	}

	//Add API Server Rules
	b.addHTTPSRules(c, sgMap)
	//Add SSH
	b.addSSHRules(c, sgMap)
	//Allow overlay DNS
	b.addDNSRules(c, sgMap)
	//Add Kubelet Rules
	b.addKubeletRules(c, sgMap)
	// Protokube Rules
	b.addProtokubeRules(c, sgMap)
	//Allow necessary local traffic
	b.addCNIRules(c, sgMap)
	//ETCD Leader Election
	b.addETCDRules(c, sgMap)
	// Add NodePort Rules:
	err := b.addNodePortRules(c, sgMap)
	if err != nil {
		return err
	}

	return nil

}
1289408
func (d *AllocDir) Build() error {
	// Make the alloc directory, owned by the nomad process.
	if err := os.MkdirAll(d.AllocDir, 0755); err != nil {
		return fmt.Errorf("Failed to make the alloc directory %v: %v", d.AllocDir, err)
	}

	// Make the shared directory and make it available to all user/groups.
	if err := os.MkdirAll(d.SharedDir, 0777); err != nil {
		return err
	}

	// Make the shared directory have non-root permissions.
	if err := dropDirPermissions(d.SharedDir, os.ModePerm); err != nil {
		return err
	}

	// Create shared subdirs
	for _, dir := range SharedAllocDirs {
		p := filepath.Join(d.SharedDir, dir)
		if err := os.MkdirAll(p, 0777); err != nil {
			return err
		}
		if err := dropDirPermissions(p, os.ModePerm); err != nil {
			return err
		}
	}

	// Mark as built
	d.mu.Lock()
	d.built = true
	d.mu.Unlock()
	return nil
}
878312
func (b *GCSBuilder) Build() (*gcs.Filter, error) {
	// Do nothing if the builder's already errored out.
	if b.err != nil {
		return nil, b.err
	}

	// We'll ensure that all the parmaters we need to actually build the
	// filter properly are set.
	if b.p == 0 {
		return nil, fmt.Errorf("p value is not set, cannot build")
	}
	if b.m == 0 {
		return nil, fmt.Errorf("m value is not set, cannot build")
	}

	dataSlice := make([][]byte, 0, len(b.data))
	for item := range b.data {
		dataSlice = append(dataSlice, []byte(item))
	}

	return gcs.BuildGCSFilter(b.p, b.m, b.key, dataSlice)
}
771454
func (f *FileAssetsBuilder) Build(c *fi.ModelBuilderContext) error {
	// used to keep track of previous file, so a instanceGroup can override a cluster wide one
	tracker := make(map[string]bool, 0)

	// ensure the default path exists
	c.EnsureTask(&nodetasks.File{
		Path: f.FileAssetsDefaultPath(),
		Type: nodetasks.FileType_Directory,
		Mode: s("0755"),
	})

	// do we have any instanceGroup file assets
	if f.InstanceGroup.Spec.FileAssets != nil {
		if err := f.buildFileAssets(c, f.InstanceGroup.Spec.FileAssets, tracker); err != nil {
			return err
		}
	}
	if f.Cluster.Spec.FileAssets != nil {
		if err := f.buildFileAssets(c, f.Cluster.Spec.FileAssets, tracker); err != nil {
			return err
		}
	}

	return nil
}
115149
func Build(path string, dns, dnsSearch, dnsOptions []string) (*File, error) {
	content := bytes.NewBuffer(nil)
	if len(dnsSearch) > 0 {
		if searchString := strings.Join(dnsSearch, " "); strings.Trim(searchString, " ") != "." {
			if _, err := content.WriteString("search " + searchString + "\n"); err != nil {
				return nil, err
			}
		}
	}
	for _, dns := range dns {
		if _, err := content.WriteString("nameserver " + dns + "\n"); err != nil {
			return nil, err
		}
	}
	if len(dnsOptions) > 0 {
		if optsString := strings.Join(dnsOptions, " "); strings.Trim(optsString, " ") != "" {
			if _, err := content.WriteString("options " + optsString + "\n"); err != nil {
				return nil, err
			}
		}
	}

	hash, err := ioutils.HashData(bytes.NewReader(content.Bytes()))
	if err != nil {
		return nil, err
	}

	return &File{Content: content.Bytes(), Hash: hash}, ioutil.WriteFile(path, content.Bytes(), 0644)
}
1193159
func (b *KubeletBuilder) Build(c *fi.ModelBuilderContext) error {
	kubeletConfig, err := b.buildKubeletConfig()
	if err != nil {
		return fmt.Errorf("error building kubelet config: %v", err)
	}

	{
		t, err := b.buildSystemdEnvironmentFile(kubeletConfig)
		if err != nil {
			return err
		}
		c.AddTask(t)
	}

	{
		// @TODO Extract to common function?
		assetName := "kubelet"
		assetPath := ""
		// @TODO make Find call to an interface, we cannot mock out this function because it finds a file on disk
		asset, err := b.Assets.Find(assetName, assetPath)
		if err != nil {
			return fmt.Errorf("error trying to locate asset %q: %v", assetName, err)
		}
		if asset == nil {
			return fmt.Errorf("unable to locate asset %q", assetName)
		}

		c.AddTask(&nodetasks.File{
			Path:     b.kubeletPath(),
			Contents: asset,
			Type:     nodetasks.FileType_File,
			Mode:     s("0755"),
		})
	}
	{
		if kubeletConfig.PodManifestPath != "" {
			t, err := b.buildManifestDirectory(kubeletConfig)
			if err != nil {
				return err
			}
			c.EnsureTask(t)
		}
	}
	{
		// We always create the directory, avoids circular dependency on a bind-mount
		c.AddTask(&nodetasks.File{
			Path: filepath.Dir(b.KubeletKubeConfig()),
			Type: nodetasks.FileType_Directory,
			Mode: s("0755"),
		})

		// @check if bootstrap tokens are enabled and create the appropreiate certificates
		if b.UseBootstrapTokens() {
			// @check if a master and if so, we bypass the token strapping and instead generate our own kubeconfig
			if b.IsMaster {
				glog.V(3).Info("kubelet bootstrap tokens are enabled and running on a master")

				task, err := b.buildMasterKubeletKubeconfig()
				if err != nil {
					return err
				}
				c.AddTask(task)
			}
		} else {
			kubeconfig, err := b.BuildPKIKubeconfig("kubelet")
			if err != nil {
				return err
			}

			c.AddTask(&nodetasks.File{
				Path:     b.KubeletKubeConfig(),
				Contents: fi.NewStringResource(kubeconfig),
				Type:     nodetasks.FileType_File,
				Mode:     s("0400"),
			})
		}
	}

	if b.UsesCNI() {
		c.AddTask(&nodetasks.File{
			Path: b.CNIConfDir(),
			Type: nodetasks.FileType_Directory,
		})
	}

	if err := b.addStaticUtils(c); err != nil {
		return err
	}

	if err := b.addContainerizedMounter(c); err != nil {
		return err
	}

	c.AddTask(b.buildSystemdService())

	return nil
}
134683
func (s *scheduler) build(ctx context.Context, edge Edge) (CachedResult, error) {
	s.mu.Lock()
	e := s.ef.getEdge(edge)
	if e == nil {
		s.mu.Unlock()
		return nil, errors.Errorf("invalid request %v for build", edge)
	}

	wait := make(chan struct{})

	var p *pipe.Pipe
	p = s.newPipe(e, nil, pipe.Request{Payload: &edgeRequest{desiredState: edgeStatusComplete}})
	p.OnSendCompletion = func() {
		p.Receiver.Receive()
		if p.Receiver.Status().Completed {
			close(wait)
		}
	}
	s.mu.Unlock()

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

	go func() {
		<-ctx.Done()
		p.Receiver.Cancel()
	}()

	<-wait

	if err := p.Receiver.Status().Err; err != nil {
		return nil, err
	}
	return p.Receiver.Status().Value.(*edgeState).result.Clone(), nil
}
667471
func (e *ExecuteExec) Build() error {
	ok, err := IsPointGetWithPKOrUniqueKeyByAutoCommit(e.ctx, e.plan)
	if err != nil {
		return err
	}
	if ok {
		err = e.ctx.InitTxnWithStartTS(math.MaxUint64)
	}
	if err != nil {
		return err
	}
	b := newExecutorBuilder(e.ctx, e.is)
	stmtExec := b.build(e.plan)
	if b.err != nil {
		log.Warn("rebuild plan in EXECUTE statement failed", zap.String("labelName of PREPARE statement", e.name))
		return errors.Trace(b.err)
	}
	e.stmtExec = stmtExec
	CountStmtNode(e.stmt, e.ctx.GetSessionVars().InRestrictedSQL)
	logExpensiveQuery(e.stmt, e.plan)
	return nil
}
1239335
func (builder *SecondaryIndexQueryCommandBuilder) Build() (Command, error) {
	if builder.protobuf == nil {
		panic("builder.protobuf must not be nil")
	}
	if err := validateLocatable(builder.protobuf); err != nil {
		return nil, err
	}
	if builder.protobuf.GetKey() == nil &&
		(builder.protobuf.GetRangeMin() == nil || builder.protobuf.GetRangeMax() == nil) {
		return nil, newClientError("either WithIndexKey or WithRange are required", nil)
	}
	if builder.protobuf.GetStream() && builder.callback == nil {
		return nil, newClientError("SecondaryIndexQueryCommand requires a callback when streaming.", nil)
	}
	return &SecondaryIndexQueryCommand{
		timeoutImpl: timeoutImpl{
			timeout: builder.timeout,
		},
		protobuf: builder.protobuf,
		callback: builder.callback,
	}, nil
}
127722
func (fdb FileDictionaryBuilder) Build(dict *collection.Dictionary) (err error) {
	var handle *os.File
	handle, err = os.Open(fdb.Target)

	var currentLine string

	for {
		_, err = fmt.Fscanln(handle, &currentLine)

		switch err {
		case nil:
			dict.Add(currentLine)
		case io.EOF:
			err = nil
			fallthrough
		default:
			return
		}
	}
}
1219849
func (s *Service) Build(ctx context.Context, buildOptions options.Build) error {
	return s.build(ctx, buildOptions)
}
808892
func (l *OptionsLoader) Build(userConfig interface{}) (interface{}, error) {
	options := userConfig
	iteration := 0
	for {
		nextOptions, err := l.iterate(userConfig, options)
		if err != nil {
			return nil, err
		}

		if reflect.DeepEqual(options, nextOptions) {
			return options, nil
		}

		iteration++
		if iteration > maxIterations {
			return nil, fmt.Errorf("options did not converge after %d iterations", maxIterations)
		}

		options = nextOptions
	}
}
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
}
572977
func (l *Loader) Build(baseDir vfs.Path) (map[string]fi.Task, error) {
	// First pass: load options
	tw := &loader.TreeWalker{
		DefaultHandler: ignoreHandler,
		Contexts: map[string]loader.Handler{
			"files":    ignoreHandler,
			"disks":    ignoreHandler,
			"packages": ignoreHandler,
			"services": ignoreHandler,
			"users":    ignoreHandler,
		},
		Tags: l.tags,
	}

	err := tw.Walk(baseDir)
	if err != nil {
		return nil, err
	}

	// Second pass: load everything else
	tw = &loader.TreeWalker{
		DefaultHandler: l.handleFile,
		Contexts: map[string]loader.Handler{
			"files":    l.handleFile,
			"disks":    l.newTaskHandler("disk/", nodetasks.NewMountDiskTask),
			"packages": l.newTaskHandler("package/", nodetasks.NewPackage),
			"services": l.newTaskHandler("service/", nodetasks.NewService),
			"users":    l.newTaskHandler("user/", nodetasks.NewUserTask),
		},
		Tags: l.tags,
	}

	err = tw.Walk(baseDir)
	if err != nil {
		return nil, err
	}

	for _, builder := range l.Builders {
		context := &fi.ModelBuilderContext{
			Tasks: l.tasks,
		}
		err := builder.Build(context)
		if err != nil {
			return nil, err
		}
		l.tasks = context.Tasks
	}

	// If there is a package task, we need an update packages task
	for _, t := range l.tasks {
		if _, ok := t.(*nodetasks.Package); ok {
			glog.Infof("Package task found; adding UpdatePackages task")
			l.tasks["UpdatePackages"] = nodetasks.NewUpdatePackages()
			break
		}
	}
	if l.tasks["UpdatePackages"] == nil {
		glog.Infof("No package task found; won't update packages")
	}

	return l.tasks, nil
}