// BuildLayer either returns a cached layer or runs a job to build the layer
435517
func (b *Builder) BuildLayer(l *Layer, id, name string, run []string, env map[string]string, artifact *ct.Artifact, inputs []string) (*ct.ImageLayer, error) {
	// try and get the cached layer first
	layer, err := b.GetCachedLayer(name, id)
	if err != nil {
		return nil, err
	} else if layer != nil {
		return layer, nil
	}

	// create a shared directory containing the inputs so we can ensure the
	// job only accesses declared inputs (thus enforcing the correctness of
	// the generated layer ID)
	dir, err := ioutil.TempDir("", "flynn-build-mnt")
	if err != nil {
		return nil, err
	}
	defer os.RemoveAll(dir)
	if err := os.Chmod(dir, 0755); err != nil {
		return nil, err
	}
	for _, subdir := range []string{"bin", "out", "src"} {
		if err := os.MkdirAll(filepath.Join(dir, subdir), 0755); err != nil {
			return nil, err
		}
	}
	copyFile := func(srcPath, dstPath string) error {
		src, err := os.Open(srcPath)
		if err != nil {
			return err
		}
		defer src.Close()
		stat, err := src.Stat()
		if err != nil {
			return err
		}
		path := filepath.Join(dir, dstPath)
		if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
			return err
		}
		dst, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, stat.Mode())
		if err != nil {
			return err
		}
		defer dst.Close()
		_, err = io.Copy(dst, src)
		return err
	}
	for _, input := range inputs {
		if err := copyFile(input, filepath.Join("src", input)); err != nil {
			b.log.Error("error copying input", "input", input, "err", err)
			return nil, err
		}
	}

	// copy the flynn-builder binary into the shared directory so we can
	// run it inside the job
	if err := copyFile(os.Args[0], "bin/flynn-builder"); err != nil {
		b.log.Error("error copying flynn-builder binary", "err", err)
		return nil, err
	}

	job := &host.Job{
		Config: host.ContainerConfig{
			Env:        env,
			DisableLog: true,
		},
		Resources: resource.Defaults(),
		Metadata: map[string]string{
			"flynn-controller.app_name": "builder",
			"flynn-controller.type":     name,
		},
	}
	cmd := exec.Cmd{Job: job}

	// run bash inside the job, passing the commands via stdin
	job.Config.Args = []string{"/mnt/bin/flynn-builder", "run", "bash", "-exs"}
	job.Config.Stdin = true
	cmd.Stdin = strings.NewReader(strings.Join(run, "\n"))

	// set FLYNN_VERSION which will be assigned to the pkg/version.version
	// constant using ldflags when building Go binaries.
	//
	// This is not treated as an input because we only want to build a new
	// binary with the given version if the build inputs have changed.
	job.Config.Env["FLYNN_VERSION"] = b.version

	// run the job in the host network to avoid a kernel bug which causes
	// subsequent jobs to block waiting on the lo network device to become
	// free (see https://github.com/docker/docker/issues/5618).
	//
	// NOTE: this leads to an impure build, jobs sometimes use the state of
	//   the network to change the installation procedure (e.g. PostgreSQL
	//   changes the default port to 5433 if something is already listening
	//   on port 5432 at install time)
	job.Config.HostNetwork = true

	linuxCapabilities := append(host.DefaultCapabilities, l.LinuxCapabilities...)
	job.Config.LinuxCapabilities = &linuxCapabilities

	for typ, v := range l.Limits {
		limit, err := resource.ParseLimit(resource.Type(typ), v)
		if err != nil {
			return nil, fmt.Errorf("error parsing limit %q = %q: %s", typ, v, err)
		}
		job.Resources.SetLimit(resource.Type(typ), limit)
	}

	// mount the shared directory at /mnt as a 9p filesystem
	ln, err := net.Listen("tcp", os.Getenv("EXTERNAL_IP")+":0")
	if err != nil {
		return nil, err
	}
	defer ln.Close()
	go serveFilesystem(dir, ln)
	addr := ln.Addr().(*net.TCPAddr)
	job.Config.Mounts = append(job.Config.Mounts, host.Mount{
		Device:   "9p",
		Location: "/mnt",
		Target:   addr.IP.String(),
		Data:     fmt.Sprintf("trans=tcp,port=%d", addr.Port),
	})
	job.Config.WorkingDir = "/mnt/src"

	if artifact == nil {
		// use the base layer if there is no artifact to build with
		job.Mountspecs = []*host.Mountspec{b.baseLayer}
	} else {
		utils.SetupMountspecs(job, []*ct.Artifact{artifact})
	}

	// copy output to log file + prefix stdout / stderr with the layer name
	logPath := filepath.Join("build/log", name+".log")
	if err := os.MkdirAll(filepath.Dir(logPath), 0755); err != nil {
		return nil, err
	}
	logFile, err := os.Create(logPath)
	if err != nil {
		return nil, err
	}
	logR, logW := io.Pipe()
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}
	go io.Copy(logW, stdout)
	stderr, err := cmd.StderrPipe()
	if err != nil {
		return nil, err
	}
	go io.Copy(logW, stderr)
	go func() {
		defer logFile.Close()
		s := bufio.NewScanner(logR)
		for s.Scan() {
			fmt.Fprintf(os.Stderr, "%s: %s: %s\n", time.Now().Format("15:04:05.999"), name, s.Text())
			fmt.Fprintln(logFile, s.Text())
		}
	}()

	// run the job
	b.log.Info("building layer", "layer.name", name, "layer.id", id)
	if err := cmd.Run(); err != nil {
		b.log.Error("error running the build job", "name", name, "err", err)
		return nil, err
	}

	// copy the layer to the cache
	f, err := os.Open(filepath.Join(dir, "out", "layer.squashfs"))
	if err != nil {
		return nil, fmt.Errorf("error opening SquashFS layer: %s", err)
	}
	defer f.Close()
	stat, err := f.Stat()
	if err != nil {
		return nil, fmt.Errorf("error opening SquashFS layer: %s", err)
	}
	h := sha512.New512_256()
	dst, err := os.Create(b.layerPath(id))
	if err != nil {
		return nil, fmt.Errorf("error writing to layer cache: %s", err)
	}
	defer dst.Close()
	if _, err := io.Copy(dst, io.TeeReader(f, h)); err != nil {
		return nil, fmt.Errorf("error writing to layer cache: %s", err)
	}
	layer = &ct.ImageLayer{
		ID:     id,
		Type:   ct.ImageLayerTypeSquashfs,
		Length: stat.Size(),
		Hashes: map[string]string{
			"sha512_256": hex.EncodeToString(h.Sum(nil)),
		},
	}
	data, err := json.Marshal(layer)
	if err != nil {
		return nil, fmt.Errorf("error encoding layer config: %s", err)
	}
	if err := ioutil.WriteFile(b.layerConfigPath(id), data, 0644); err != nil {
		return nil, fmt.Errorf("error writing to layer cache: %s", err)
	}
	return layer, nil
}
876032
func (builder *Layered) Build(config *api.Config) (*api.Result, error) {
	buildResult := &api.Result{}

	if config.HasOnBuild && config.BlockOnBuild {
		buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason(
			utilstatus.ReasonOnBuildForbidden,
			utilstatus.ReasonMessageOnBuildForbidden,
		)
		return buildResult, errors.New("builder image uses ONBUILD instructions but ONBUILD is not allowed")
	}

	if config.BuilderImage == "" {
		buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason(
			utilstatus.ReasonGenericS2IBuildFailed,
			utilstatus.ReasonMessageGenericS2iBuildFailed,
		)
		return buildResult, errors.New("builder image name cannot be empty")
	}

	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"), false)
	defer tarStream.Close()

	newBuilderImage := fmt.Sprintf("s2i-layered-temp-image-%d", time.Now().UnixNano())

	outReader, outWriter := io.Pipe()
	opts := docker.BuildImageOptions{
		Name:         newBuilderImage,
		Stdin:        tarStream,
		Stdout:       outWriter,
		CGroupLimits: config.CGroupLimits,
	}
	docker.StreamContainerIO(outReader, nil, func(s string) { glog.V(2).Info(s) })

	glog.V(2).Infof("Building new image %s with scripts and sources already inside", newBuilderImage)
	startTime := time.Now()
	err := builder.docker.BuildImage(opts)
	buildResult.BuildInfo.Stages = api.RecordStageAndStepInfo(buildResult.BuildInfo.Stages, api.StageBuild, api.StepBuildDockerImage, startTime, time.Now())
	if err != nil {
		buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason(
			utilstatus.ReasonDockerImageBuildFailed,
			utilstatus.ReasonMessageDockerImageBuildFailed,
		)
		return buildResult, err
	}

	// upon successful build we need to modify current config
	builder.config.LayeredBuild = true
	// new image name
	builder.config.BuilderImage = newBuilderImage
	// see CreateDockerfile, conditional copy, location of scripts
	scriptsIncluded := checkValidDirWithContents(path.Join(config.WorkingDir, constants.UploadScripts))
	glog.V(2).Infof("Scripts dir has contents %v", scriptsIncluded)
	if scriptsIncluded {
		builder.config.ScriptsURL = "image://" + path.Join(getDestination(config), "scripts")
	} else {
		var err error
		builder.config.ScriptsURL, err = builder.docker.GetScriptsURL(newBuilderImage)
		if err != nil {
			buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason(
				utilstatus.ReasonGenericS2IBuildFailed,
				utilstatus.ReasonMessageGenericS2iBuildFailed,
			)
			return buildResult, err
		}
	}

	glog.V(2).Infof("Building %s using sti-enabled image", builder.config.Tag)
	startTime = time.Now()
	err = builder.scripts.Execute(constants.Assemble, config.AssembleUser, builder.config)
	buildResult.BuildInfo.Stages = api.RecordStageAndStepInfo(buildResult.BuildInfo.Stages, api.StageAssemble, api.StepAssembleBuildScripts, startTime, time.Now())
	if err != nil {
		buildResult.BuildInfo.FailureReason = utilstatus.NewFailureReason(
			utilstatus.ReasonAssembleFailed,
			utilstatus.ReasonMessageAssembleFailed,
		)
		switch e := err.(type) {
		case s2ierr.ContainerError:
			return buildResult, s2ierr.NewAssembleError(builder.config.Tag, e.Output, e)
		default:
			return buildResult, err
		}
	}
	buildResult.Success = true

	return buildResult, nil
}
136961
func (ls Layers) ProjectToTile(tile maptile.Tile) {
	for _, l := range ls {
		l.ProjectToTile(tile)
	}
}
1021087
func (o *GetMapURL) Build() (*url.URL, error) {
	var _result url.URL

	var _path = "/map"

	_basePath := o._basePath
	if _basePath == "" {
		_basePath = "/v1"
	}
	_result.Path = golangswaggerpaths.Join(_basePath, _path)

	return &_result, nil
}
122709
func (c *Context) BuildURL(ctl string, act string, args ...interface{}) string {
	return c.Application.URLBuilder.Build(c.Module.Name, ctl, act, args...)
}
789299
func buildPool(runCmd runFunc) error {
	// This can run without error if the pool isn't active.
	output, err := runCmd("", virsh, "pool-build", poolName)
	if err != nil {
		return errors.Trace(err)
	}
	logger.Debugf("pool-build output %s", output)
	return nil
}
767042
func build(targets ...string) error {
	if v, _ := strconv.ParseBool(os.Getenv("CAMLI_FAST_DEV")); v {
		// Demo mode. See dev/demo.sh.
		return nil
	}
	var fullTargets []string
	for _, t := range targets {
		t = filepath.ToSlash(t)
		if !strings.HasPrefix(t, "perkeep.org") {
			t = pathpkg.Join("perkeep.org", t)
		}
		fullTargets = append(fullTargets, t)
	}
	targetsComma := strings.Join(fullTargets, ",")
	args := []string{
		"run", "make.go",
		"--quiet",
		"--race=" + strconv.FormatBool(*race),
		"--embed_static=false",
		"--sqlite=" + strconv.FormatBool(withSqlite),
		"--targets=" + targetsComma,
	}
	cmd := exec.Command("go", args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("error building %v: %v", targetsComma, err)
	}
	return nil
}
98604
func (builder *Dockerfile) Build(config *api.Config) (*api.Result, error) {

	// Handle defaulting of the configuration that is unique to the dockerfile strategy
	if strings.HasSuffix(config.AsDockerfile, string(os.PathSeparator)) {
		config.AsDockerfile = config.AsDockerfile + "Dockerfile"
	}
	if len(config.AssembleUser) == 0 {
		config.AssembleUser = "1001"
	}
	if !user.IsUserAllowed(config.AssembleUser, &config.AllowedUIDs) {
		builder.setFailureReason(utilstatus.ReasonAssembleUserForbidden, utilstatus.ReasonMessageAssembleUserForbidden)
		return builder.result, s2ierr.NewUserNotAllowedError(config.AssembleUser, false)
	}

	dir, _ := filepath.Split(config.AsDockerfile)
	if len(dir) == 0 {
		dir = "."
	}
	config.PreserveWorkingDir = true
	config.WorkingDir = dir

	if config.BuilderImage == "" {
		builder.setFailureReason(utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed)
		return builder.result, errors.New("builder image name cannot be empty")
	}

	if err := builder.Prepare(config); err != nil {
		return builder.result, err
	}

	if err := builder.CreateDockerfile(config); err != nil {
		builder.setFailureReason(utilstatus.ReasonDockerfileCreateFailed, utilstatus.ReasonMessageDockerfileCreateFailed)
		return builder.result, err
	}

	builder.result.Success = true

	return builder.result, nil
}
870259
func BuildSqlJobPlanned(planner plan.Planner, executor Executor, ctx *plan.Context) (Task, error) {

	//u.Debugf("build: %q", ctx.Raw)
	if ctx.Raw == "" {
		return nil, fmt.Errorf("no sql provided")
	}
	stmt, err := rel.ParseSql(ctx.Raw)
	if err != nil {
		u.Debugf("could not parse sql : %v", err)
		return nil, err
	}
	if stmt == nil {
		return nil, fmt.Errorf("Not statement for parse? %v", ctx.Raw)
	}
	ctx.Stmt = stmt

	pln, err := plan.WalkStmt(ctx, stmt, planner)

	if err != nil {
		return nil, err
	}
	if pln == nil {
		u.Warnf("error, no plan task, should not be possible?  %v", err)
		return nil, fmt.Errorf("No plan root task found? %v", ctx.Raw)
	}

	execRoot, err := executor.WalkPlan(pln)

	if err != nil {
		return nil, err
	}
	if execRoot == nil {
		return nil, fmt.Errorf("No plan root task found? %v", ctx.Raw)
	}

	return execRoot, err
}
356949
func (b *Backend) Build(ctx context.Context, config backend.BuildConfig) (string, error) {
	options := config.Options
	useBuildKit := options.Version == types.BuilderBuildKit

	tagger, err := NewTagger(b.imageComponent, config.ProgressWriter.StdoutFormatter, options.Tags)
	if err != nil {
		return "", err
	}

	var build *builder.Result
	if useBuildKit {
		build, err = b.buildkit.Build(ctx, config)
		if err != nil {
			return "", err
		}
	} else {
		build, err = b.builder.Build(ctx, config)
		if err != nil {
			return "", err
		}
	}

	if build == nil {
		return "", nil
	}

	var imageID = build.ImageID
	if options.Squash {
		if imageID, err = squashBuild(build, b.imageComponent); err != nil {
			return "", err
		}
		if config.ProgressWriter.AuxFormatter != nil {
			if err = config.ProgressWriter.AuxFormatter.Emit("moby.image.id", types.BuildResult{ID: imageID}); err != nil {
				return "", err
			}
		}
	}

	if !useBuildKit {
		stdout := config.ProgressWriter.StdoutFormatter
		fmt.Fprintf(stdout, "Successfully built %s\n", stringid.TruncateID(imageID))
	}
	err = tagger.TagImages(image.ID(imageID))
	return imageID, err
}
506461
func BuildLayerTargets(path, target string) ([]string, error) {
	layerStems := []string{}
	layers, err := ioutil.ReadDir(path)
	if err != nil {
		return layerStems, err
	}
	for _, layer := range layers {
		if layer.IsDir() {
			layerStems = append(layerStems, filepath.Join(path, layer.Name(), target))
		}
	}
	return layerStems, nil
}
1070764
func (r *Registry) DownloadLayer(ctx context.Context, repository string, digest digest.Digest) (io.ReadCloser, error) {
	url := r.url("/v2/%s/blobs/%s", repository, digest)
	r.Logf("registry.layer.download url=%s repository=%s digest=%s", url, repository, digest)

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	resp, err := r.Client.Do(req.WithContext(ctx))
	if err != nil {
		return nil, err
	}

	return resp.Body, nil
}
865513
func (i *ImageService) CreateLayer(container *container.Container, initFunc layer.MountInit) (layer.RWLayer, error) {
	var layerID layer.ChainID
	if container.ImageID != "" {
		img, err := i.imageStore.Get(container.ImageID)
		if err != nil {
			return nil, err
		}
		layerID = img.RootFS.ChainID()
	}

	rwLayerOpts := &layer.CreateRWLayerOpts{
		MountLabel: container.MountLabel,
		InitFunc:   initFunc,
		StorageOpt: container.HostConfig.StorageOpt,
	}

	// Indexing by OS is safe here as validation of OS has already been performed in create() (the only
	// caller), and guaranteed non-nil
	return i.layerStores[container.OS].CreateRWLayer(container.ID, layerID, rwLayerOpts)
}
331032
func NewBuildQueue(name string) *BuildQueue {
	q := &BuildQueue{
		name:             name,
		buildStatus:      buildStatusMap{},
		workerBuildQueue: make(chan Builder, buildQueueSize),
		stopWorker:       make(chan struct{}, 0),
		regularBuilds: buildGroup{
			condition: func(q *BuildQueue) bool {
				return q.exclusiveBuilds.waiting == 0 && q.exclusiveBuilds.running == 0
			},
		},
		exclusiveBuilds: buildGroup{
			condition: func(q *BuildQueue) bool {
				return q.exclusiveBuilds.running == 0 && q.regularBuilds.running == 0
			},
		},
	}

	q.waitingBuilders = sync.NewCond(&q.mutex)

	nWorkers := numWorkerThreads()
	for w := 0; w < nWorkers; w++ {
		go q.runWorker()
	}

	return q
}
381180
func (b *PKIModelBuilder) Build(c *fi.ModelBuilderContext) error {

	// We specify the KeysetFormatV1Alpha2 format, to upgrade from the legacy representation (separate files)
	// to the newer keyset.yaml representation.
	format := string(fi.KeysetFormatV1Alpha2)

	// TODO: Only create the CA via this task
	defaultCA := &fitasks.Keypair{
		Name:      fi.String(fi.CertificateId_CA),
		Lifecycle: b.Lifecycle,
		Subject:   "cn=kubernetes",
		Type:      "ca",
		Format:    format,
	}
	c.AddTask(defaultCA)

	{
		// @check of bootstrap tokens are enable if so, disable the creation of the kubelet certificate - we also
		// block at the IAM level for AWS cluster for pre-existing clusters.
		if !b.UseBootstrapTokens() {
			c.AddTask(&fitasks.Keypair{
				Name:      fi.String("kubelet"),
				Lifecycle: b.Lifecycle,
				Subject:   "o=" + user.NodesGroup + ",cn=kubelet",
				Type:      "client",
				Signer:    defaultCA,
				Format:    format,
			})
		}
	}
	{
		// Generate a kubelet client certificate for api to speak securely to kubelets. This change was first
		// introduced in https://github.com/kubernetes/kops/pull/2831 where server.cert/key were used. With kubernetes >= 1.7
		// the certificate usage is being checked (obviously the above was server not client certificate) and so now fails
		c.AddTask(&fitasks.Keypair{
			Name:      fi.String("kubelet-api"),
			Lifecycle: b.Lifecycle,
			Subject:   "cn=kubelet-api",
			Type:      "client",
			Signer:    defaultCA,
			Format:    format,
		})
	}
	{
		t := &fitasks.Keypair{
			Name:      fi.String("kube-scheduler"),
			Lifecycle: b.Lifecycle,
			Subject:   "cn=" + user.KubeScheduler,
			Type:      "client",
			Signer:    defaultCA,
			Format:    format,
		}
		c.AddTask(t)
	}

	{
		t := &fitasks.Keypair{
			Name:      fi.String("kube-proxy"),
			Lifecycle: b.Lifecycle,
			Subject:   "cn=" + user.KubeProxy,
			Type:      "client",
			Signer:    defaultCA,
			Format:    format,
		}
		c.AddTask(t)
	}

	{
		t := &fitasks.Keypair{
			Name:      fi.String("kube-controller-manager"),
			Lifecycle: b.Lifecycle,
			Subject:   "cn=" + user.KubeControllerManager,
			Type:      "client",
			Signer:    defaultCA,
			Format:    format,
		}
		c.AddTask(t)
	}

	if b.UseEtcdManager() {
		// We generate keypairs in the etcdmanager task itself
	} else if b.UseEtcdTLS() {
		// check if we need to generate certificates for etcd peers certificates from a different CA?
		// @question i think we should use another KeyStore for this, perhaps registering a EtcdKeyStore given
		// that mutual tls used to verify between the peers we don't want certificates for kubernetes able to act as a peer.
		// For clients assuming we are using etcdv3 is can switch on user authentication and map the common names for auth.
		servingNames := []string{fmt.Sprintf("*.internal.%s", b.ClusterName()), "localhost", "127.0.0.1"}
		// @question should wildcard's be here instead of generating per node. If we ever provide the
		// ability to resize the master, this will become a blocker
		c.AddTask(&fitasks.Keypair{
			AlternateNames: servingNames,
			Lifecycle:      b.Lifecycle,
			Name:           fi.String("etcd"),
			Subject:        "cn=etcd",
			// TODO: Can this be "server" now that we're not using it for peer connectivity?
			Type:   "clientServer",
			Signer: defaultCA,
			Format: format,
		})

		// For peer authentication, the same cert is used both as a client
		// cert and as a server cert (which is unusual).  Moreover, etcd
		// 3.2 introduces some breaking changes to certificate validation
		// where it tries to match any IP or DNS names to the client IP
		// (including reverse DNS lookups!)  We _could_ include a wildcard
		// reverse DNS name e.g. *.ec2.internal for EC2, but it seems
		// better just to list the names that we expect peer connectivity
		// to happen on.
		var peerNames []string
		for _, etcdCluster := range b.Cluster.Spec.EtcdClusters {
			prefix := "etcd-" + etcdCluster.Name + "-"
			if prefix == "etcd-main-" {
				prefix = "etcd-"
			}
			for _, m := range etcdCluster.Members {
				peerNames = append(peerNames, prefix+m.Name+".internal."+b.ClusterName())
			}
		}
		c.AddTask(&fitasks.Keypair{
			AlternateNames: peerNames,

			Lifecycle: b.Lifecycle,
			Name:      fi.String("etcd-peer"),
			Subject:   "cn=etcd-peer",
			Type:      "clientServer",
			Signer:    defaultCA,
			Format:    format,
		})

		c.AddTask(&fitasks.Keypair{
			Name:      fi.String("etcd-client"),
			Lifecycle: b.Lifecycle,
			Subject:   "cn=etcd-client",
			Type:      "client",
			Signer:    defaultCA,
			Format:    format,
		})

		// @check if calico or Cilium is enabled as the CNI provider
		if b.KopsModelContext.Cluster.Spec.Networking.Calico != nil || b.KopsModelContext.Cluster.Spec.Networking.Cilium != nil {
			c.AddTask(&fitasks.Keypair{
				Name:      fi.String("calico-client"),
				Lifecycle: b.Lifecycle,
				Subject:   "cn=calico-client",
				Type:      "client",
				Signer:    defaultCA,
				Format:    format,
			})
		}
	}

	if b.KopsModelContext.Cluster.Spec.Networking.Kuberouter != nil {
		t := &fitasks.Keypair{
			Name:    fi.String("kube-router"),
			Subject: "cn=" + "system:kube-router",
			Type:    "client",
			Signer:  defaultCA,
			Format:  format,
		}
		c.AddTask(t)
	}

	{
		t := &fitasks.Keypair{
			Name:      fi.String("kubecfg"),
			Lifecycle: b.Lifecycle,
			Subject:   "o=" + user.SystemPrivilegedGroup + ",cn=kubecfg",
			Type:      "client",
			Signer:    defaultCA,
			Format:    format,
		}
		c.AddTask(t)
	}

	{
		t := &fitasks.Keypair{
			Name:      fi.String("apiserver-proxy-client"),
			Lifecycle: b.Lifecycle,
			Subject:   "cn=apiserver-proxy-client",
			Type:      "client",
			Signer:    defaultCA,
			Format:    format,
		}
		c.AddTask(t)
	}

	{
		aggregatorCA := &fitasks.Keypair{
			Name:      fi.String("apiserver-aggregator-ca"),
			Lifecycle: b.Lifecycle,
			Subject:   "cn=apiserver-aggregator-ca",
			Type:      "ca",
			Format:    format,
		}
		c.AddTask(aggregatorCA)

		aggregator := &fitasks.Keypair{
			Name:      fi.String("apiserver-aggregator"),
			Lifecycle: b.Lifecycle,
			// Must match RequestheaderAllowedNames
			Subject: "cn=aggregator",
			Type:    "client",
			Signer:  aggregatorCA,
			Format:  format,
		}
		c.AddTask(aggregator)
	}

	{
		// Used by e.g. protokube
		t := &fitasks.Keypair{
			Name:      fi.String("kops"),
			Lifecycle: b.Lifecycle,
			Subject:   "o=" + user.SystemPrivilegedGroup + ",cn=kops",
			Type:      "client",
			Signer:    defaultCA,
			Format:    format,
		}
		c.AddTask(t)
	}

	{
		// A few names used from inside the cluster, which all resolve the same based on our default suffixes
		alternateNames := []string{
			"kubernetes",
			"kubernetes.default",
			"kubernetes.default.svc",
			"kubernetes.default.svc." + b.Cluster.Spec.ClusterDNSDomain,
		}

		// Names specified in the cluster spec
		alternateNames = append(alternateNames, b.Cluster.Spec.MasterPublicName)
		alternateNames = append(alternateNames, b.Cluster.Spec.MasterInternalName)
		alternateNames = append(alternateNames, b.Cluster.Spec.AdditionalSANs...)

		// Referencing it by internal IP should work also
		{
			ip, err := b.WellKnownServiceIP(1)
			if err != nil {
				return err
			}
			alternateNames = append(alternateNames, ip.String())
		}

		// We also want to be able to reference it locally via https://127.0.0.1
		alternateNames = append(alternateNames, "127.0.0.1")

		t := &fitasks.Keypair{
			Name:           fi.String("master"),
			Lifecycle:      b.Lifecycle,
			Subject:        "cn=kubernetes-master",
			Type:           "server",
			AlternateNames: alternateNames,
			Signer:         defaultCA,
			Format:         format,
		}
		c.AddTask(t)
	}

	if b.Cluster.Spec.Authentication != nil {
		if b.KopsModelContext.Cluster.Spec.Authentication.Aws != nil {
			alternateNames := []string{
				"localhost",
				"127.0.0.1",
			}

			t := &fitasks.Keypair{
				Name:           fi.String("aws-iam-authenticator"),
				Subject:        "cn=aws-iam-authenticator",
				Type:           "server",
				AlternateNames: alternateNames,
				Signer:         defaultCA,
				Format:         format,
			}
			c.AddTask(t)
		}
	}

	// @TODO this is VERY presumptuous, i'm going on the basis we can make it configurable in the future.
	// But I'm conscious not to do too much work on bootstrap tokens as it might overlay further down the
	// line with the machines api
	if b.UseBootstrapTokens() {
		serviceName := "node-authorizer-internal"

		alternateNames := []string{
			"127.0.0.1",
			"localhost",
			serviceName,
			strings.Join([]string{serviceName, b.Cluster.Name}, "."),
			strings.Join([]string{serviceName, b.Cluster.Spec.DNSZone}, "."),
		}

		// @note: the certificate used by the node authorizers
		c.AddTask(&fitasks.Keypair{
			Name:           fi.String("node-authorizer"),
			Subject:        "cn=node-authorizaer",
			Type:           "server",
			AlternateNames: alternateNames,
			Signer:         defaultCA,
			Format:         format,
		})

		// @note: we use this for mutual tls between node and authorizer
		c.AddTask(&fitasks.Keypair{
			Name:    fi.String("node-authorizer-client"),
			Subject: "cn=node-authorizer-client",
			Type:    "client",
			Signer:  defaultCA,
			Format:  format,
		})
	}

	// Create auth tokens (though this is deprecated)
	for _, x := range tokens.GetKubernetesAuthTokens_Deprecated() {
		c.AddTask(&fitasks.Secret{Name: fi.String(x), Lifecycle: b.Lifecycle})
	}

	{
		mirrorPath, err := vfs.Context.BuildVfsPath(b.Cluster.Spec.SecretStore)
		if err != nil {
			return err
		}

		t := &fitasks.MirrorSecrets{
			Name:       fi.String("mirror-secrets"),
			MirrorPath: mirrorPath,
		}
		c.AddTask(t)
	}

	{
		mirrorPath, err := vfs.Context.BuildVfsPath(b.Cluster.Spec.KeyStore)
		if err != nil {
			return err
		}

		// Keypair used by the kubelet
		t := &fitasks.MirrorKeystore{
			Name:       fi.String("mirror-keystore"),
			MirrorPath: mirrorPath,
		}
		c.AddTask(t)
	}

	return nil
}
980928
func buildBody(ctx context.Context, configuration configuration, level, title string, extras map[string]interface{}) map[string]interface{} {
	timestamp := time.Now().Unix()

	data := map[string]interface{}{
		"environment":  configuration.environment,
		"title":        title,
		"level":        level,
		"timestamp":    timestamp,
		"platform":     configuration.platform,
		"language":     "go",
		"code_version": configuration.codeVersion,
		"server": map[string]interface{}{
			"host": configuration.serverHost,
			"root": configuration.serverRoot,
		},
		"notifier": map[string]interface{}{
			"name":    NAME,
			"version": VERSION,
		},
	}

	custom := buildCustom(configuration.custom, extras)
	if custom != nil {
		data["custom"] = custom
	}

	person, ok := PersonFromContext(ctx)
	if !ok {
		person = &configuration.person
	}
	if person.Id != "" {
		data["person"] = map[string]string{
			"id":       person.Id,
			"username": person.Username,
			"email":    person.Email,
		}
	}

	return map[string]interface{}{
		"access_token": configuration.token,
		"data":         data,
	}
}
472500
func (q *BaseQueryBuilder) BuildJoin(joins []JoinInfo, params Params) string {
	if len(joins) == 0 {
		return ""
	}
	parts := []string{}
	for _, join := range joins {
		sql := join.Join + " " + q.quoteTableNameAndAlias(join.Table)
		on := ""
		if join.On != nil {
			on = join.On.Build(q.db, params)
		}
		if on != "" {
			sql += " ON " + on
		}
		parts = append(parts, sql)
	}
	return strings.Join(parts, " ")
}