// Build is responsible for writing out the file assets from cluster and instanceGroup
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
}
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
}
765317
func (builder *MapReduceCommandBuilder) Build() (Command, error) {
	if builder.protobuf == nil {
		panic("builder.protobuf must not be nil")
	}
	if builder.streaming && builder.callback == nil {
		return nil, newClientError("MapReduceCommand requires a callback when streaming.", nil)
	}
	return &MapReduceCommand{
		protobuf:  builder.protobuf,
		streaming: builder.streaming,
		callback:  builder.callback,
	}, nil
}
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
}
768600
func (b *AutoscalingGroupModelBuilder) Build(c *fi.ModelBuilderContext) error {
	for _, ig := range b.InstanceGroups {
		name := b.AutoscalingGroupName(ig)

		// @check if his instancegroup is backed by a fleet and overide with a launch template
		task, err := func() (fi.Task, error) {
			switch UseLaunchTemplate(ig) {
			case true:
				return b.buildLaunchTemplateTask(c, name, ig)
			default:
				return b.buildLaunchConfigurationTask(c, name, ig)
			}
		}()
		if err != nil {
			return err
		}
		c.AddTask(task)

		// @step: now lets build the autoscaling group task
		tsk, err := b.buildAutoScalingGroupTask(c, name, ig)
		if err != nil {
			return err
		}
		switch UseLaunchTemplate(ig) {
		case true:
			tsk.LaunchTemplate = task.(*awstasks.LaunchTemplate)
		default:
			tsk.LaunchConfiguration = task.(*awstasks.LaunchConfiguration)
		}
		c.AddTask(tsk)

		// @step: add any external load balancer attachments
		if err := b.buildExternalLoadBalancerTasks(c, ig); err != nil {
			return err
		}
	}

	return 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
}
431011
func (builder *StoreIndexCommandBuilder) Build() (Command, error) {
	if builder.protobuf == nil {
		panic("builder.protobuf must not be nil")
	}
	return &StoreIndexCommand{
		timeoutImpl: timeoutImpl{
			timeout: builder.timeout,
		},
		protobuf: builder.protobuf,
	}, nil
}
1141544
func (p *StoragePool) Build(flags StoragePoolBuildFlags) error {
	var err C.virError
	result := C.virStoragePoolBuildWrapper(p.ptr, C.uint(flags), &err)
	if result == -1 {
		return makeError(&err)
	}
	return 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
}
1209041
func (t *Tree) Build(
	ctx context.Context, sm *SortedMap, txi TxInfo) (err error) {
	t.Lock()
	defer t.Unlock()

	var prevRoot, nextRoot Hash
	if prevRoot, err = t.eng.LookupRoot(ctx); err != nil {
		return err
	}
	if nextRoot, err = t.hashTreeRecursive(ctx,
		Level(0), sm, prevRoot); err != nil {
		return err
	}
	if err = t.eng.CommitRoot(ctx, prevRoot, nextRoot, txi); err != nil {
		return err
	}

	return err
}
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
}
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
}
264160
func (dh *Client) Build(r io.Reader, opts *BuildImageOptions) (imageId string, e error) {
	u := dh.Address + "/build"
	if opts == nil {
		opts = &BuildImageOptions{}
	}
	if enc := opts.encode(); enc != "" {
		u += "?" + enc
	}
	rsp, e := dh.postWithContentType(u, "application/tar", r)
	if e != nil {
		return "", e
	}
	defer rsp.Body.Close()

	ib := &imageBuildResponseHandler{userHandler: opts.Callback}
	return ib.Run(rsp.Body)
}
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
}
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

}
1241269
func Build(val interface{}) (Property, error) {
	if val == nil {
		return nil, nil
	}

	switch reflect.TypeOf(val).Kind() {
	case reflect.Map:
		valMap, ok := val.(map[interface{}]interface{})
		if !ok {
			return nil, bosherr.Errorf("Converting map %#v", val)
		}

		return BuildMap(valMap)

	case reflect.Slice:
		valSlice, ok := val.([]interface{})
		if !ok {
			return nil, bosherr.Errorf("Converting slice %#v", val)
		}

		return BuildList(valSlice)

	default:
		return val, 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 "))
}