// Build is part of the ModelOperation interface.
775395
func (op *UpdateUnitsOperation) Build(attempt int) ([]txn.Op, error) {
	var ops []txn.Op

	all := op.allOps()
	for _, op := range all {
		switch nextOps, err := op.Build(attempt); err {
		case jujutxn.ErrNoOperations:
			continue
		case nil:
			ops = append(ops, nextOps...)
		default:
			return nil, errors.Trace(err)
		}
	}
	return ops, nil
}
79981
func (builder *ListKeysCommandBuilder) 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.streaming && builder.callback == nil {
		return nil, newClientError("ListKeysCommand requires a callback when streaming.", nil)
	}
	if !builder.allowListing {
		return nil, ErrListingDisabled
	}
	return &ListKeysCommand{
		listingImpl: listingImpl{
			allowListing: builder.allowListing,
		},
		timeoutImpl: timeoutImpl{
			timeout: builder.timeout,
		},
		protobuf:  builder.protobuf,
		streaming: builder.streaming,
		callback:  builder.callback,
	}, nil
}
696693
func (f *FailureResponseBuilder) Build() *FailureResponse {
	return &FailureResponse{
		error:         f.error,
		statusCode:    f.statusCode,
		loggerAction:  f.loggerAction,
		emptyResponse: f.emptyResponse,
		errorKey:      f.errorKey,
	}
}
151869
func (b *KubeAPIServerBuilder) Build(c *fi.ModelBuilderContext) error {
	if !b.IsMaster {
		return nil
	}

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

	if b.Cluster.Spec.EncryptionConfig != nil {
		if *b.Cluster.Spec.EncryptionConfig && b.IsKubernetesGTE("1.7") {
			b.Cluster.Spec.KubeAPIServer.ExperimentalEncryptionProviderConfig = fi.String(filepath.Join(b.PathSrvKubernetes(), "encryptionconfig.yaml"))
			key := "encryptionconfig"
			encryptioncfg, _ := b.SecretStore.Secret(key)
			if encryptioncfg != nil {
				contents := string(encryptioncfg.Data)
				t := &nodetasks.File{
					Path:     *b.Cluster.Spec.KubeAPIServer.ExperimentalEncryptionProviderConfig,
					Contents: fi.NewStringResource(contents),
					Mode:     fi.String("600"),
					Type:     nodetasks.FileType_File,
				}
				c.AddTask(t)
			}
		}
	}
	{
		pod, err := b.buildPod()
		if err != nil {
			return fmt.Errorf("error building kube-apiserver manifest: %v", err)
		}

		manifest, err := k8scodecs.ToVersionedYaml(pod)
		if err != nil {
			return fmt.Errorf("error marshaling manifest to yaml: %v", err)
		}

		c.AddTask(&nodetasks.File{
			Path:     "/etc/kubernetes/manifests/kube-apiserver.manifest",
			Contents: fi.NewBytesResource(manifest),
			Type:     nodetasks.FileType_File,
		})
	}

	// @check if we are using secure client certificates for kubelet and grab the certificates
	if b.UseSecureKubelet() {
		name := "kubelet-api"
		if err := b.BuildCertificateTask(c, name, name+".pem"); err != nil {
			return err
		}
		if err := b.BuildPrivateKeyTask(c, name, name+"-key.pem"); err != nil {
			return err
		}
	}

	c.AddTask(&nodetasks.File{
		Path:        "/var/log/kube-apiserver.log",
		Contents:    fi.NewStringResource(""),
		Type:        nodetasks.FileType_File,
		Mode:        s("0400"),
		IfNotExists: true,
	})

	return nil
}
651124
func (op *LeaveScopeOperation) Build(attempt int) ([]txn.Op, error) {
	if attempt > 0 {
		if err := op.ru.relation.Refresh(); errors.IsNotFound(err) {
			return nil, jujutxn.ErrNoOperations
		} else if err != nil {
			return nil, err
		}
	}
	// When 'force' is set on the operation, this call will return needed operations
	// and accumulate all operational errors encountered in the operation.
	// If the 'force' is not set, any error will be fatal and no operations will be returned.
	switch ops, err := op.internalLeaveScope(); err {
	case errRefresh:
	case errAlreadyDying:
		return nil, jujutxn.ErrNoOperations
	case nil:
		return ops, nil
	default:
		if op.Force {
			logger.Warningf("forcing %v to leave scope despite error %v", op.Description(), err)
			return ops, nil
		}
		return nil, err
	}
	return nil, jujutxn.ErrNoOperations
}
325252
func (b *KubectlBuilder) Build(c *fi.ModelBuilderContext) error {
	if !b.IsMaster {
		return nil
	}

	{
		// TODO: Extract to common function?
		assetName := "kubectl"
		assetPath := ""
		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.KubectlPath() + "/" + assetName,
			Contents: asset,
			Type:     nodetasks.FileType_File,
			Mode:     s("0755"),
		})
	}

	{
		kubeconfig, err := b.BuildPKIKubeconfig("kubecfg")
		if err != nil {
			return err
		}

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

		adminUser, adminGroup, err := b.findKubeconfigUser()
		if err != nil {
			return err
		}

		if adminUser != nil && adminUser.Home != "" {
			c.AddTask(&nodetasks.File{
				Path:  adminUser.Home + "/.kube/",
				Type:  nodetasks.FileType_Directory,
				Mode:  s("0700"),
				Owner: s(adminUser.Name),
				Group: s(adminGroup.Name),
			})

			c.AddTask(&nodetasks.File{
				Path:     adminUser.Home + "/.kube/config",
				Contents: fi.NewStringResource(kubeconfig),
				Type:     nodetasks.FileType_File,
				Mode:     s("0400"),
				Owner:    s(adminUser.Name),
				Group:    s(adminGroup.Name),
			})
		}
	}

	return nil
}
235817
func (r *Resolver) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) {
	r.cc = cc
	if r.bootstrapState != nil {
		r.UpdateState(*r.bootstrapState)
	}
	return r, nil
}
1178868
func (d *DaemonBuilder) Build(ctx context.Context, imageName string) error {
	buildCtx, err := CreateTar(d.ContextDirectory, d.Dockerfile)
	if err != nil {
		return err
	}
	defer buildCtx.Close()
	if d.LoggerFactory == nil {
		d.LoggerFactory = &logger.NullLogger{}
	}

	l := d.LoggerFactory.CreateBuildLogger(imageName)

	progBuff := &logger.Wrapper{
		Err:    false,
		Logger: l,
	}

	buildBuff := &logger.Wrapper{
		Err:    false,
		Logger: l,
	}

	errBuff := &logger.Wrapper{
		Err:    true,
		Logger: l,
	}

	// Setup an upload progress bar
	progressOutput := streamformatter.NewProgressOutput(progBuff)

	var body io.Reader = progress.NewProgressReader(buildCtx, progressOutput, 0, "", "Sending build context to Docker daemon")

	logrus.Infof("Building %s...", imageName)

	outFd, isTerminalOut := term.GetFdInfo(os.Stdout)
	w := l.OutWriter()
	if w != nil {
		outFd, isTerminalOut = term.GetFdInfo(w)
	}

	// Convert map[string]*string to map[string]string
	labels := make(map[string]string)
	for lk, lv := range d.Labels {
		labels[lk] = *lv
	}

	response, err := d.Client.ImageBuild(ctx, body, types.ImageBuildOptions{
		Tags:        []string{imageName},
		NoCache:     d.NoCache,
		Remove:      true,
		ForceRemove: d.ForceRemove,
		PullParent:  d.Pull,
		Dockerfile:  d.Dockerfile,
		AuthConfigs: d.AuthConfigs,
		BuildArgs:   d.BuildArgs,
		CacheFrom:   d.CacheFrom,
		Labels:      labels,
		NetworkMode: d.Network,
		Target:      d.Target,
	})
	if err != nil {
		return err
	}

	err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, outFd, isTerminalOut, nil)
	if err != nil {
		if jerr, ok := err.(*jsonmessage.JSONError); ok {
			// If no error code is set, default to 1
			if jerr.Code == 0 {
				jerr.Code = 1
			}
			errBuff.Write([]byte(jerr.Error()))
			return fmt.Errorf("Status: %s, Code: %d", jerr.Message, jerr.Code)
		}
	}
	return err
}
977758
func (b *OpenAPI3Builder) build(document *openapiv3.Document) (err error) {
	// Collect service type descriptions from Components/Schemas.
	if document.Components != nil && document.Components.Schemas != nil {
		for _, pair := range document.Components.Schemas.AdditionalProperties {
			t, err := b.buildTypeFromSchemaOrReference(pair.Name, pair.Value)
			if err != nil {
				return err
			}
			if t != nil {
				b.model.addType(t)
			}
		}
	}
	// Collect service method descriptions from each PathItem.
	if document.Paths != nil {
		for _, pair := range document.Paths.Path {
			b.buildMethodFromPathItem(pair.Name, pair.Value)
		}
	}
	return err
}
267713
func (b *EtcdManagerBuilder) Build(c *fi.ModelBuilderContext) error {
	for _, etcdCluster := range b.Cluster.Spec.EtcdClusters {
		if etcdCluster.Provider != kops.EtcdProviderTypeManager {
			continue
		}

		name := etcdCluster.Name
		version := etcdCluster.Version

		backupStore := ""
		if etcdCluster.Backups != nil {
			backupStore = etcdCluster.Backups.BackupStore
		}
		if backupStore == "" {
			return fmt.Errorf("backupStore must be set for use with etcd-manager")
		}

		manifest, err := b.buildManifest(etcdCluster)
		if err != nil {
			return err
		}

		manifestYAML, err := k8scodecs.ToVersionedYaml(manifest)
		if err != nil {
			return fmt.Errorf("error marshaling manifest to yaml: %v", err)
		}

		c.AddTask(&fitasks.ManagedFile{
			Contents:  fi.WrapResource(fi.NewBytesResource(manifestYAML)),
			Lifecycle: b.Lifecycle,
			Location:  fi.String("manifests/etcd/" + name + ".yaml"),
			Name:      fi.String("manifests-etcdmanager-" + name),
		})

		info := &etcdClusterSpec{
			EtcdVersion: version,
			MemberCount: int32(len(etcdCluster.Members)),
		}

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

		format := string(fi.KeysetFormatV1Alpha2)

		c.AddTask(&fitasks.ManagedFile{
			Contents:  fi.WrapResource(fi.NewBytesResource(d)),
			Lifecycle: b.Lifecycle,
			// TODO: We need this to match the backup base (currently)
			Location: fi.String("backups/etcd/" + etcdCluster.Name + "/control/etcd-cluster-spec"),
			Name:     fi.String("etcd-cluster-spec-" + name),
		})

		// We create a CA keypair to enable secure communication
		c.AddTask(&fitasks.Keypair{
			Name:    fi.String("etcd-manager-ca-" + etcdCluster.Name),
			Subject: "cn=etcd-manager-ca-" + etcdCluster.Name,
			Type:    "ca",
			Format:  format,
		})

		// We create a CA for etcd peers and a separate one for clients
		c.AddTask(&fitasks.Keypair{
			Name:    fi.String("etcd-peers-ca-" + etcdCluster.Name),
			Subject: "cn=etcd-peers-ca-" + etcdCluster.Name,
			Type:    "ca",
			Format:  format,
		})

		// Because API server can only have a single client-cert, we need to share a client CA
		if err := c.EnsureTask(&fitasks.Keypair{
			Name:    fi.String("etcd-clients-ca"),
			Subject: "cn=etcd-clients-ca",
			Type:    "ca",
			Format:  format,
		}); err != nil {
			return err
		}
	}

	return nil
}
111253
func (b *DockerBuilder) Build(c *fi.ModelBuilderContext) error {

	// @check: neither coreos or containeros need provision docker.service, just the docker daemon options
	switch b.Distribution {
	case distros.DistributionCoreOS:
		glog.Infof("Detected CoreOS; won't install Docker")
		if err := b.buildContainerOSConfigurationDropIn(c); err != nil {
			return err
		}
		return nil

	case distros.DistributionContainerOS:
		glog.Infof("Detected ContainerOS; won't install Docker")
		if err := b.buildContainerOSConfigurationDropIn(c); err != nil {
			return err
		}
		return nil
	}

	// Add Apache2 license
	{
		t := &nodetasks.File{
			Path:     "/usr/share/doc/docker/apache.txt",
			Contents: fi.NewStringResource(resources.DockerApache2License),
			Type:     nodetasks.FileType_File,
		}
		c.AddTask(t)
	}

	dockerVersion := b.dockerVersion()

	// Add packages
	{
		count := 0
		for i := range dockerVersions {
			dv := &dockerVersions[i]
			if !dv.matches(b.Architecture, dockerVersion, b.Distribution) {
				continue
			}

			count++

			var packageTask fi.Task
			if dv.PlainBinary {
				packageTask = &nodetasks.Archive{
					Name:            "docker",
					Source:          dv.Source,
					Hash:            dv.Hash,
					TargetDir:       "/usr/bin/",
					StripComponents: 1,
				}
				c.AddTask(packageTask)

				c.AddTask(b.buildDockerGroup())
				c.AddTask(b.buildSystemdSocket())
			} else {
				var extraPkgs []*nodetasks.Package
				for name, pkg := range dv.ExtraPackages {
					dep := &nodetasks.Package{
						Name:         name,
						Version:      s(pkg.Version),
						Source:       s(pkg.Source),
						Hash:         s(pkg.Hash),
						PreventStart: fi.Bool(true),
					}
					extraPkgs = append(extraPkgs, dep)
				}
				packageTask = &nodetasks.Package{
					Name:    dv.Name,
					Version: s(dv.Version),
					Source:  s(dv.Source),
					Hash:    s(dv.Hash),
					Deps:    extraPkgs,

					// TODO: PreventStart is now unused?
					PreventStart: fi.Bool(true),
				}
				c.AddTask(packageTask)
			}

			// As a mitigation for CVE-2019-5736 (possibly a fix, definitely defense-in-depth) we chattr docker-runc to be immutable
			for _, f := range dv.MarkImmutable {
				c.AddTask(&nodetasks.Chattr{
					File: f,
					Mode: "+i",
					Deps: []fi.Task{packageTask},
				})
			}

			for _, dep := range dv.Dependencies {
				c.AddTask(&nodetasks.Package{Name: dep})
			}

			// Note we do _not_ stop looping... centos/rhel comprises multiple packages
		}

		if count == 0 {
			glog.Warningf("Did not find docker package for %s %s %s", b.Distribution, b.Architecture, dockerVersion)
		}
	}

	// Split into major.minor.(patch+pr+meta)
	parts := strings.SplitN(dockerVersion, ".", 3)
	if len(parts) != 3 {
		return fmt.Errorf("error parsing docker version %q, no Major.Minor.Patch elements found", dockerVersion)
	}

	// Validate major
	dockerVersionMajor, err := strconv.ParseInt(parts[0], 10, 64)
	if err != nil {
		return fmt.Errorf("error parsing major docker version %q: %v", parts[0], err)
	}

	// Validate minor
	dockerVersionMinor, err := strconv.ParseInt(parts[1], 10, 64)
	if err != nil {
		return fmt.Errorf("error parsing minor docker version %q: %v", parts[1], err)
	}

	c.AddTask(b.buildSystemdService(dockerVersionMajor, dockerVersionMinor))

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

	return nil
}
920309
func (builder *FetchBucketTypePropsCommandBuilder) 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 &FetchBucketTypePropsCommand{protobuf: builder.protobuf}, nil
}
948271
func Build(c *model.CommandConfig, paths *model.RevelContainer) (_ *App, err error) {
	// First, clear the generated files (to avoid them messing with ProcessSource).
	cleanSource(paths, "tmp", "routes")

	sourceInfo, err := parser.ProcessSource(paths)
	if err != nil {
		return
	}

	// Add the db.import to the import paths.
	if dbImportPath, found := paths.Config.String("db.import"); found {
		sourceInfo.InitImportPaths = append(sourceInfo.InitImportPaths, strings.Split(dbImportPath, ",")...)
	}

	// Sort controllers so that file generation is reproducible
	controllers := sourceInfo.ControllerSpecs()
	sort.Stable(ByString(controllers))

	// Generate two source files.
	templateArgs := map[string]interface{}{
		"ImportPath":     paths.ImportPath,
		"Controllers":    controllers,
		"ValidationKeys": sourceInfo.ValidationKeys,
		"ImportPaths":    calcImportAliases(sourceInfo),
		"TestSuites":     sourceInfo.TestSuites(),
	}

	// Generate code for the main, run and routes file.
	// The run file allows external programs to launch and run the application
	// without being the main thread
	cleanSource(paths, "tmp", "routes")

	if err = genSource(paths, "tmp", "main.go", RevelMainTemplate, templateArgs); err != nil {
		return
	}
	if err = genSource(paths, filepath.Join("tmp", "run"), "run.go", RevelRunTemplate, templateArgs); err != nil {
		return
	}
	if err = genSource(paths, "routes", "routes.go", RevelRoutesTemplate, templateArgs); err != nil {
		return
	}

	// Read build config.
	buildTags := paths.Config.StringDefault("build.tags", "")

	// Build the user program (all code under app).
	// It relies on the user having "go" installed.
	goPath, err := exec.LookPath("go")
	if err != nil {
		utils.Logger.Fatal("Go executable not found in PATH.")
	}

	// Detect if deps tool should be used (is there a vendor folder ?)
	useVendor := utils.DirExists(filepath.Join(paths.BasePath, "vendor"))
	basePath := paths.BasePath
	for !useVendor {
		basePath = filepath.Dir(basePath)
		found := false
		// Check to see if we are still in the GOPATH
		for _, gopath := range filepath.SplitList(build.Default.GOPATH) {
			if strings.HasPrefix(basePath, gopath) {
				found = true
				break
			}
		}
		if !found {
			break
		} else {
			useVendor = utils.DirExists(filepath.Join(basePath, "vendor"))
		}
	}

	pkg, err := build.Default.Import(paths.ImportPath, "", build.FindOnly)
	if err != nil {
		return
	}

	// Binary path is a combination of $GOBIN/revel.d directory, app's import path and its name.
	binName := filepath.Join(pkg.BinDir, "revel.d", paths.ImportPath, filepath.Base(paths.BasePath))

	// Change binary path for Windows build
	goos := runtime.GOOS
	if goosEnv := os.Getenv("GOOS"); goosEnv != "" {
		goos = goosEnv
	}
	if goos == "windows" {
		binName += ".exe"
	}

	gotten := make(map[string]struct{})
	contains := func(s []string, e string) bool {
		for _, a := range s {
			if a == e {
				return true
			}
		}
		return false
	}

	for {
		appVersion := getAppVersion(paths)

		buildTime := time.Now().UTC().Format(time.RFC3339)
		versionLinkerFlags := fmt.Sprintf("-X %s/app.AppVersion=%s -X %s/app.BuildTime=%s",
			paths.ImportPath, appVersion, paths.ImportPath, buildTime)

		// Append any build flags specified, they will override existing flags
		flags := []string{}
		if len(c.BuildFlags) == 0 {
			flags = []string{
				"build",
				"-i",
				"-ldflags", versionLinkerFlags,
				"-tags", buildTags,
				"-o", binName}
		} else {
			if !contains(c.BuildFlags, "build") {
				flags = []string{"build"}
			}
			flags = append(flags, c.BuildFlags...)
			if !contains(flags, "-ldflags") {
				flags = append(flags, "-ldflags", versionLinkerFlags)
			}
			if !contains(flags, "-tags") {
				flags = append(flags, "-tags", buildTags)
			}
			if !contains(flags, "-o") {
				flags = append(flags, "-o", binName)
			}
		}

		// Add in build flags
		flags = append(flags, c.BuildFlags...)

		// This is Go main path
		gopath := c.GoPath
		for _, o := range paths.ModulePathMap {
			gopath += string(filepath.ListSeparator) + o
		}

		// Note: It's not applicable for filepath.* usage
		flags = append(flags, path.Join(paths.ImportPath, "app", "tmp"))

		buildCmd := exec.Command(goPath, flags...)
		buildCmd.Env = append(os.Environ(),
			"GOPATH="+gopath,
		)
		utils.CmdInit(buildCmd, c.AppPath)
		utils.Logger.Info("Exec:", "args", buildCmd.Args)
		output, err := buildCmd.CombinedOutput()

		// If the build succeeded, we're done.
		if err == nil {
			utils.Logger.Info("Build successful continuing")
			return NewApp(binName, paths), nil
		}

		// Since there was an error, capture the output in case we need to report it
		stOutput := string(output)

		// See if it was an import error that we can go get.
		matches := importErrorPattern.FindAllStringSubmatch(stOutput, -1)
		utils.Logger.Info("Build failed checking for missing imports", "message", stOutput, "missing_imports", len(matches))
		if matches == nil {
			utils.Logger.Info("Build failed no missing imports", "message", stOutput)
			return nil, newCompileError(paths, output)
		}
		utils.Logger.Warn("Detected missing packages, importing them", "packages", len(matches))
		for _, match := range matches {
			// Ensure we haven't already tried to go get it.
			pkgName := match[1]
			utils.Logger.Info("Trying to import ", "package", pkgName)
			if _, alreadyTried := gotten[pkgName]; alreadyTried {
				utils.Logger.Error("Failed to import ", "package", pkgName)
				return nil, newCompileError(paths, output)
			}
			gotten[pkgName] = struct{}{}
			if err := c.PackageResolver(pkgName); err != nil {
				utils.Logger.Error("Unable to resolve package", "package", pkgName, "error", err)
				return nil, newCompileError(paths, []byte(err.Error()))
			}
		}

		// Success getting the import, attempt to build again.
	}

	// TODO remove this unreachable code and document it
	utils.Logger.Fatal("Not reachable")
	return nil, nil
}
1323266
func (b *APILoadBalancerBuilder) Build(c *fi.ModelBuilderContext) error {
	// Configuration where an ELB fronts the API
	if !b.UseLoadBalancerForAPI() {
		return nil
	}

	lbSpec := b.Cluster.Spec.API.LoadBalancer
	if lbSpec == nil {
		// Skipping API ELB creation; not requested in Spec
		return nil
	}

	switch lbSpec.Type {
	case kops.LoadBalancerTypeInternal, kops.LoadBalancerTypePublic:
	// OK

	default:
		return fmt.Errorf("unhandled LoadBalancer type %q", lbSpec.Type)
	}

	// Compute the subnets - only one per zone, and then break ties based on chooseBestSubnetForELB
	var elbSubnets []*awstasks.Subnet
	{
		subnetsByZone := make(map[string][]*kops.ClusterSubnetSpec)
		for i := range b.Cluster.Spec.Subnets {
			subnet := &b.Cluster.Spec.Subnets[i]

			switch subnet.Type {
			case kops.SubnetTypePublic, kops.SubnetTypeUtility:
				if lbSpec.Type != kops.LoadBalancerTypePublic {
					continue
				}

			case kops.SubnetTypePrivate:
				if lbSpec.Type != kops.LoadBalancerTypeInternal {
					continue
				}

			default:
				return fmt.Errorf("subnet %q had unknown type %q", subnet.Name, subnet.Type)
			}

			subnetsByZone[subnet.Zone] = append(subnetsByZone[subnet.Zone], subnet)
		}

		for zone, subnets := range subnetsByZone {
			subnet := b.chooseBestSubnetForELB(zone, subnets)

			elbSubnets = append(elbSubnets, b.LinkToSubnet(subnet))
		}
	}

	var elb *awstasks.LoadBalancer
	{
		loadBalancerName := b.GetELBName32("api")

		idleTimeout := LoadBalancerDefaultIdleTimeout
		if lbSpec.IdleTimeoutSeconds != nil {
			idleTimeout = time.Second * time.Duration(*lbSpec.IdleTimeoutSeconds)
		}

		listeners := map[string]*awstasks.LoadBalancerListener{
			"443": {InstancePort: 443},
		}

		if lbSpec.SSLCertificate != "" {
			listeners["443"] = &awstasks.LoadBalancerListener{InstancePort: 443, SSLCertificateID: lbSpec.SSLCertificate}
		}

		if lbSpec.SecurityGroupOverride != nil {
			glog.V(1).Infof("WARNING: You are overwriting the Load Balancers, Security Group. When this is done you are responsible for ensure the correct rules!")
		}

		tags := b.CloudTags(loadBalancerName, false)
		for k, v := range b.Cluster.Spec.CloudLabels {
			tags[k] = v
		}
		// Override the returned name to be the expected ELB name
		tags["Name"] = "api." + b.ClusterName()

		elb = &awstasks.LoadBalancer{
			Name:      fi.String("api." + b.ClusterName()),
			Lifecycle: b.Lifecycle,

			LoadBalancerName: fi.String(loadBalancerName),
			SecurityGroups: []*awstasks.SecurityGroup{
				b.LinkToELBSecurityGroup("api"),
			},
			Subnets:   elbSubnets,
			Listeners: listeners,

			// Configure fast-recovery health-checks
			HealthCheck: &awstasks.LoadBalancerHealthCheck{
				Target:             fi.String("SSL:443"),
				Timeout:            fi.Int64(5),
				Interval:           fi.Int64(10),
				HealthyThreshold:   fi.Int64(2),
				UnhealthyThreshold: fi.Int64(2),
			},

			ConnectionSettings: &awstasks.LoadBalancerConnectionSettings{
				IdleTimeout: fi.Int64(int64(idleTimeout.Seconds())),
			},

			Tags: tags,
		}

		switch lbSpec.Type {
		case kops.LoadBalancerTypeInternal:
			elb.Scheme = fi.String("internal")
		case kops.LoadBalancerTypePublic:
			elb.Scheme = nil
		default:
			return fmt.Errorf("unknown elb Type: %q", lbSpec.Type)
		}

		c.AddTask(elb)
	}

	// Create security group for API ELB
	var lbSG *awstasks.SecurityGroup
	{
		lbSG = &awstasks.SecurityGroup{
			Name:             fi.String(b.ELBSecurityGroupName("api")),
			Lifecycle:        b.SecurityLifecycle,
			Description:      fi.String("Security group for api ELB"),
			RemoveExtraRules: []string{"port=443"},
			VPC:              b.LinkToVPC(),
		}
		lbSG.Tags = b.CloudTags(*lbSG.Name, false)

		if lbSpec.SecurityGroupOverride != nil {
			lbSG.ID = fi.String(*lbSpec.SecurityGroupOverride)
			lbSG.Shared = fi.Bool(true)
		}

		c.AddTask(lbSG)
	}

	// Allow traffic from ELB to egress freely
	{
		t := &awstasks.SecurityGroupRule{
			Name:          fi.String("api-elb-egress"),
			Lifecycle:     b.SecurityLifecycle,
			CIDR:          fi.String("0.0.0.0/0"),
			Egress:        fi.Bool(true),
			SecurityGroup: lbSG,
		}
		c.AddTask(t)
	}

	// Allow traffic into the ELB from KubernetesAPIAccess CIDRs
	{
		for _, cidr := range b.Cluster.Spec.KubernetesAPIAccess {
			t := &awstasks.SecurityGroupRule{
				Name:          fi.String("https-api-elb-" + cidr),
				Lifecycle:     b.SecurityLifecycle,
				CIDR:          fi.String(cidr),
				FromPort:      fi.Int64(443),
				Protocol:      fi.String("tcp"),
				SecurityGroup: lbSG,
				ToPort:        fi.Int64(443),
			}
			c.AddTask(t)

			// Allow ICMP traffic required for PMTU discovery
			c.AddTask(&awstasks.SecurityGroupRule{
				Name:          fi.String("icmp-pmtu-api-elb-" + cidr),
				Lifecycle:     b.SecurityLifecycle,
				CIDR:          fi.String(cidr),
				FromPort:      fi.Int64(3),
				Protocol:      fi.String("icmp"),
				SecurityGroup: lbSG,
				ToPort:        fi.Int64(4),
			})
		}
	}

	// Add precreated additional security groups to the ELB
	{
		for _, id := range b.Cluster.Spec.API.LoadBalancer.AdditionalSecurityGroups {
			t := &awstasks.SecurityGroup{
				Name:      fi.String(id),
				Lifecycle: b.SecurityLifecycle,
				ID:        fi.String(id),
				Shared:    fi.Bool(true),
			}
			if err := c.EnsureTask(t); err != nil {
				return err
			}
			elb.SecurityGroups = append(elb.SecurityGroups, t)
		}
	}

	masterGroups, err := b.GetSecurityGroups(kops.InstanceGroupRoleMaster)
	if err != nil {
		return err
	}

	// Allow HTTPS to the master instances from the ELB
	{
		for _, masterGroup := range masterGroups {
			suffix := masterGroup.Suffix
			c.AddTask(&awstasks.SecurityGroupRule{
				Name:          fi.String(fmt.Sprintf("https-elb-to-master%s", suffix)),
				Lifecycle:     b.SecurityLifecycle,
				FromPort:      fi.Int64(443),
				Protocol:      fi.String("tcp"),
				SecurityGroup: masterGroup.Task,
				SourceGroup:   lbSG,
				ToPort:        fi.Int64(443),
			})
		}
	}

	if dns.IsGossipHostname(b.Cluster.Name) || b.UsePrivateDNS() {
		// Ensure the ELB hostname is included in the TLS certificate,
		// if we're not going to use an alias for it
		// TODO: I don't love this technique for finding the task by name & modifying it
		masterKeypairTask, found := c.Tasks["Keypair/master"]
		if !found {
			return fmt.Errorf("keypair/master task not found")
		}
		masterKeypair := masterKeypairTask.(*fitasks.Keypair)
		masterKeypair.AlternateNameTasks = append(masterKeypair.AlternateNameTasks, elb)
	}

	// When Spotinst Elastigroups are used, there is no need to create
	// a separate task for the attachment of the load balancer since this
	// is already done as part of the Elastigroup's creation, if needed.
	if !featureflag.Spotinst.Enabled() {
		for _, ig := range b.MasterInstanceGroups() {
			c.AddTask(&awstasks.LoadBalancerAttachment{
				Name:             fi.String("api-" + ig.ObjectMeta.Name),
				Lifecycle:        b.Lifecycle,
				AutoscalingGroup: b.LinkToAutoscalingGroup(ig),
				LoadBalancer:     b.LinkToELB("api"),
			})
		}
	}

	return 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)
	}
}
664966
func (builder *SearchCommandBuilder) Build() (Command, error) {
	if builder.protobuf == nil {
		panic("builder.protobuf must not be nil")
	}
	return &SearchCommand{protobuf: builder.protobuf}, nil
}
1245312
func (builder *FetchSetCommandBuilder) 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 &FetchSetCommand{
		timeoutImpl: timeoutImpl{
			timeout: builder.timeout,
		},
		protobuf: builder.protobuf,
	}, nil
}