// GetBuilder is the implementation for getting a milo builder page from
// buildbot.
514148
func GetBuilder(c context.Context, masterName, builderName string, limit int, cursor string) (*ui.Builder, error) {
	if err := buildstore.CanAccessMaster(c, masterName); err != nil {
		return nil, err
	}
	result := &ui.Builder{
		Name: builderName,
	}
	master, err := buildstore.GetMaster(c, masterName, false)
	if err != nil {
		return nil, err
	}
	if clock.Now(c).Sub(master.Modified) > 2*time.Minute {
		warning := fmt.Sprintf(
			"WARNING: buildbotMasterEntry data is stale (last updated %s)", master.Modified)
		logging.Warningf(c, warning)
		result.Warning = warning
	}

	builder, ok := master.Builders[builderName]
	if !ok {
		// This long block is just to return a good error message when an invalid
		// buildbot builder is specified.
		keys := make([]string, 0, len(master.Builders))
		for k := range master.Builders {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		// TODO(iannucci): add error-info-helper tags to give the error page enough
		// information to render link-to-master and link-to-builder.
		builders := strings.Join(keys, "\n")
		return nil, errors.Reason(
			"Cannot find builder %q in master %q.\nAvailable builders: \n%s",
			builderName, masterName, builders,
		).Tag(grpcutil.NotFoundTag).Err()
	}

	// Extract pending builds out of the master.
	result.PendingBuilds = make([]*ui.BuildSummary, len(builder.PendingBuildStates))
	result.PendingBuildNum = builder.PendingBuilds
	logging.Debugf(c, "Number of pending builds: %d", len(builder.PendingBuildStates))
	for i, pb := range builder.PendingBuildStates {
		start := time.Unix(int64(pb.SubmittedAt), 0).UTC()
		result.PendingBuilds[i] = &ui.BuildSummary{
			PendingTime: ui.NewInterval(c, start, time.Time{}),
			Blame:       make([]*ui.Commit, len(pb.Source.Changes)),
		}
		for j, cm := range pb.Source.Changes {
			result.PendingBuilds[i].Blame[j] = &ui.Commit{
				AuthorEmail: cm.Who,
				CommitURL:   cm.Revlink,
			}
		}
	}

	baseURL := "https://build.chromium.org/p/"
	if master.Internal {
		baseURL = "https://uberchromegw.corp.google.com/i/"
	}
	result.MachinePool = summarizeSlavePool(c, baseURL+master.Name, builder.Slaves, master.Slaves)

	return result, parallel.FanOutIn(func(work chan<- func() error) {
		q := buildstore.Query{
			Master:  masterName,
			Builder: builderName,

			NoAnnotationFetch: true,
		}
		work <- func() error {
			q := q
			q.Limit = limit
			q.Cursor = cursor
			q.Finished = buildstore.Yes
			res, err := buildstore.GetBuilds(c, q)
			if err != nil {
				return err
			}
			result.NextCursor = res.NextCursor
			result.PrevCursor = res.PrevCursor
			result.FinishedBuilds = make([]*ui.BuildSummary, len(res.Builds))
			for i, b := range res.Builds {
				result.FinishedBuilds[i] = renderBuild(c, b, false).BuildSummary()
			}
			return err
		}
		work <- func() error {
			q := q
			q.Finished = buildstore.No
			res, err := buildstore.GetBuilds(c, q)
			if err != nil {
				return err
			}
			result.CurrentBuilds = make([]*ui.BuildSummary, len(res.Builds))
			for i, b := range res.Builds {
				// currentBuilds is presented in reversed order, so flip it
				result.CurrentBuilds[len(res.Builds)-i-1] = renderBuild(c, b, false).BuildSummary()
			}
			return err
		}
	})
}
919451
func NewBuilder(configs map[string]*config.Middleware, serviceBuilder serviceBuilder) *Builder {
	return &Builder{configs: configs, serviceBuilder: serviceBuilder}
}
406201
func processBuilders(c context.Context, r *swarmbucketAPI.LegacySwarmbucketApiGetBuildersResponseMessage) ([]model.PoolDescriptor, error) {
	var builderPools []model.BuilderPool
	var descriptors []model.PoolDescriptor
	seen := stringset.New(0)
	for _, bucket := range r.Buckets {
		for _, builder := range bucket.Builders {
			bid := NewBuilderID(bucket.Name, builder.Name)
			if bid.Project == "" {
				// This may happen if the bucket or builder does not fulfill the LUCI
				// naming convention.
				logging.Warningf(c, "invalid bucket/builder %q/%q, skipping", bucket.Name, builder.Name)
				continue
			}
			id := bid.String()
			dimensions := stripEmptyDimensions(builder.SwarmingDimensions)
			descriptor := model.NewPoolDescriptor(builder.SwarmingHostname, dimensions)
			dID := descriptor.PoolID()
			builderPools = append(builderPools, model.BuilderPool{
				BuilderID: datastore.MakeKey(c, model.BuilderSummaryKind, id),
				PoolKey:   datastore.MakeKey(c, model.BotPoolKind, dID),
			})
			if added := seen.Add(dID); added {
				descriptors = append(descriptors, descriptor)
			}
		}
	}
	return descriptors, datastore.Put(c, builderPools)
}
671260
func (b *serverBuilder) GetEventHandler(event ServerBuildEvents) *ServerBuildEventHandler {
	if handler, ok := b.buildEventHandlers[event]; ok {
		return &handler
	}
	return nil
}
223535
func (p *BuildInfoProvider) GetBuildInfo(c context.Context, req *milo.BuildInfoRequest_Swarming,
	projectHint string) (*milo.BuildInfoResponse, error) {

	// Load the Swarming task (no log content).
	sf, err := p.newSwarmingService(c, req.Host)
	if err != nil {
		logging.WithError(err).Errorf(c, "Failed to create Swarming fetcher.")
		return nil, grpcutil.Internal
	}

	// Use default Swarming host.
	host := sf.GetHost()
	logging.Infof(c, "Loading build info for Swarming host %s, task %s.", host, req.Task)

	fr, err := swarmingFetch(c, sf, req.Task, swarmingFetchParams{})
	if err != nil {
		if err == ErrNotMiloJob {
			logging.Warningf(c, "User requested nonexistent task or does not have permissions.")
			return nil, grpcutil.NotFound
		}

		logging.WithError(err).Errorf(c, "Failed to load Swarming task.")
		return nil, grpcutil.Internal
	}

	// Determine the LogDog annotation stream path for this Swarming task.
	//
	// On failure, will return a gRPC error.
	stream, err := resolveLogDogAnnotations(c, fr.res.Tags)
	if err != nil {
		logging.WithError(err).Warningf(c, "Failed to get annotation stream parameters.")
		return nil, err
	}

	logging.Fields{
		"host":    stream.Host,
		"project": stream.Project,
		"path":    stream.Path,
	}.Infof(c, "Resolved LogDog annotation stream.")

	step, err := rawpresentation.ReadAnnotations(c, stream)
	if err != nil {
		return nil, errors.Annotate(err, "failed to read annotations").Err()
	}

	// Add Swarming task parameters to the Milo step.
	if err := addTaskToMiloStep(c, sf.GetHost(), fr.res, step); err != nil {
		return nil, err
	}

	prefix, name := stream.Path.Split()
	return &milo.BuildInfoResponse{
		Project: string(stream.Project),
		Step:    step,
		AnnotationStream: &miloProto.LogdogStream{
			Server: stream.Host,
			Prefix: string(prefix),
			Name:   string(name),
		},
	}, nil
}
421359
func (o *Organization) GetBuild(ctx context.Context, projectUUID, buildUUID string) (Build, Response, error) {
	path := fmt.Sprintf("/organizations/%s/projects/%s/builds/%s", o.UUID, projectUUID, buildUUID)

	body, resp, err := o.client.request(ctx, "GET", path, nil)
	if err != nil {
		return Build{}, resp, errors.Wrap(err, "unable to get build")
	}

	var build buildResponse
	if err = json.Unmarshal(body, &build); err != nil {
		return Build{}, resp, errors.Wrap(err, "unable to unmarshal response into Build")
	}

	return build.Build, resp, nil
}
560013
func (s *Style) Builder() *StyleBuilder {
	return &StyleBuilder{
		name:    s.Name,
		entries: map[TokenType]string{},
		parent:  s,
	}
}
395346
func (m *Manager) GetCompiler() *ast.Compiler {
	m.compilerMux.RLock()
	defer m.compilerMux.RUnlock()
	return m.compiler
}
542214
func GetBuild(c context.Context, id buildbot.BuildID) (*buildbot.Build, error) {
	return getBuild(c, id, true, true)
}
1050180
func getBanner(c context.Context, b *buildbot.Build) *ui.LogoBanner {
	osLogo := func() *ui.Logo {
		result := &ui.Logo{}
		switch b.OSFamily {
		case "windows":
			result.LogoBase = ui.Windows
		case "Darwin":
			result.LogoBase = ui.OSX
		case "Debian":
			result.LogoBase = ui.Ubuntu
		default:
			return nil
		}
		result.Subtitle = b.OSVersion
		return result
	}()
	if osLogo != nil {
		return &ui.LogoBanner{
			OS: []ui.Logo{*osLogo},
		}
	}
	return nil
}
245990
func (s *Service) GetBuilders() *GetBuildersCall {
	c := &GetBuildersCall{s: s, urlParams_: make(gensupport.URLParams)}
	return c
}
304997
func (c *AppConfig) validateBuilders(components app.ComponentReferences) error {
	if c.Strategy != newapp.StrategyUnspecified {
		return nil
	}
	errs := []error{}
	for _, ref := range components {
		input := ref.Input()
		// if we're supposed to build this thing, and the image/imagestream we've matched it to did not come from an explicit CLI argument,
		// and the image/imagestream we matched to is not explicitly an s2i builder, and we're doing a source-type build, warn the user
		// that this probably won't work and force them to declare their intention explicitly.
		if input.ExpectToBuild && input.ResolvedMatch != nil && !app.IsBuilderMatch(input.ResolvedMatch) && input.Uses != nil && input.Uses.GetStrategy() == newapp.StrategySource {
			errs = append(errs, fmt.Errorf("the image match %q for source repository %q does not appear to be a source-to-image builder.\n\n- to attempt to use this image as a source builder, pass \"--strategy=source\"\n- to use it as a base image for a Docker build, pass \"--strategy=docker\"", input.ResolvedMatch.Name, input.Uses))
			continue
		}
	}
	return kutilerrors.NewAggregate(errs)
}
823569
func (g *GeneratorArgs) NewBuilder() (*parser.Builder, error) {
	b := parser.New()
	// Ignore all auto-generated files.
	b.AddBuildTags(g.GeneratedBuildTag)

	for _, d := range g.InputDirs {
		var err error
		if strings.HasSuffix(d, "/...") {
			err = b.AddDirRecursive(strings.TrimSuffix(d, "/..."))
		} else {
			err = b.AddDir(d)
		}
		if err != nil {
			return nil, fmt.Errorf("unable to add directory %q: %v", d, err)
		}
	}
	return b, nil
}
1001934
func (c *ApiController) GetActiveBuilds() {
	// TODO(tobe): this is not implemented because nobody uses it yet.
	log.Info("Get active builds")

	result := "Not implemented"
	c.Ctx.WriteString(result)
}
701864
func GetBuildEnv(build *buildv1.Build) []corev1.EnvVar {
	switch {
	case build.Spec.Strategy.SourceStrategy != nil:
		return build.Spec.Strategy.SourceStrategy.Env
	case build.Spec.Strategy.DockerStrategy != nil:
		return build.Spec.Strategy.DockerStrategy.Env
	case build.Spec.Strategy.CustomStrategy != nil:
		return build.Spec.Strategy.CustomStrategy.Env
	case build.Spec.Strategy.JenkinsPipelineStrategy != nil:
		return build.Spec.Strategy.JenkinsPipelineStrategy.Env
	default:
		return nil
	}
}
555543
func getBuild(c context.Context, id buildbot.BuildID, fetchAnnotations, fetchChanges bool) (*buildbot.Build, error) {
	if !EmulationEnabled(c) {
		return getDatastoreBuild(c, id)
	}

	// Is it a LUCI build?
	build, err := getEmulatedBuild(c, id, fetchAnnotations, fetchChanges)
	switch {
	case err != nil:
		return nil, err
	case build != nil:
		// does not exist or experimental.
		return build, nil
	}

	// Is it a Buildbot build?
	build, err = getDatastoreBuild(c, id)
	switch {
	case err != nil:
		return nil, err
	case build == nil:
		return nil, nil
	case build.Experimental():
		return nil, nil
	default:
		return build, nil
	}
}
261908
func (bc *BuildController) handleBuildError(err error, key interface{}) {
	if err == nil {
		bc.buildQueue.Forget(key)
		return
	}

	if strategy.IsFatal(err) {
		klog.V(2).Infof("Will not retry fatal error for key %v: %v", key, err)
		bc.buildQueue.Forget(key)
		return
	}

	if bc.buildQueue.NumRequeues(key) < maxRetries {
		klog.V(4).Infof("Retrying key %v: %v", key, err)
		bc.buildQueue.AddRateLimited(key)
		return
	}

	klog.V(2).Infof("Giving up retrying %v: %v", key, err)
	bc.buildQueue.Forget(key)
}