// getNextBuildNameFromBuild returns name of the next build with random uuid added at the end
13437
func getNextBuildNameFromBuild(build *buildv1.Build, buildConfig *buildv1.BuildConfig) string {
	var buildName string
	if buildConfig != nil {
		return getNextBuildName(buildConfig)
	}
	// for builds created by hand, append a timestamp when cloning/rebuilding them
	// because we don't have a sequence number to bump.
	buildName = build.Name
	// remove the old timestamp if we're cloning a build that is itself a clone.
	if matched, _ := regexp.MatchString(`^.+-\d{10}$`, buildName); matched {
		nameElems := strings.Split(buildName, "-")
		buildName = strings.Join(nameElems[:len(nameElems)-1], "-")
	}
	suffix := fmt.Sprintf("%v", metav1.Now().UnixNano())
	if len(suffix) > 10 {
		suffix = suffix[len(suffix)-10:]
	}
	return apihelpers.GetName(buildName, suffix, kvalidation.DNS1123SubdomainMaxLength)

}
87585
func (c *ApiController) GetSearchBuilds() {
	log.Info("Get search builds")

	result := "Not implemented"
	c.Ctx.WriteString(result)
}
229951
func (ctx *bytesKeyIterator) GetNext() (key string, rev int64, stop bool) {
	if ctx.index >= ctx.len {
		return "", 0, true
	}

	key = string(ctx.resp.Kvs[ctx.index].Key)
	rev = ctx.resp.Kvs[ctx.index].ModRevision
	ctx.index++

	return key, rev, false
}
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
}
729136
func (actor Actor) GetBuildpackByNameAndStack(buildpackName string, buildpackStack string) (Buildpack, Warnings, error) {
	var (
		ccv3Buildpacks []ccv3.Buildpack
		warnings       ccv3.Warnings
		err            error
	)

	if buildpackStack == "" {
		ccv3Buildpacks, warnings, err = actor.CloudControllerClient.GetBuildpacks(ccv3.Query{
			Key:    ccv3.NameFilter,
			Values: []string{buildpackName},
		})
	} else {
		ccv3Buildpacks, warnings, err = actor.CloudControllerClient.GetBuildpacks(
			ccv3.Query{
				Key:    ccv3.NameFilter,
				Values: []string{buildpackName},
			},
			ccv3.Query{
				Key:    ccv3.StackFilter,
				Values: []string{buildpackStack},
			},
		)
	}

	if err != nil {
		return Buildpack{}, Warnings(warnings), err
	}

	if len(ccv3Buildpacks) == 0 {
		return Buildpack{}, Warnings(warnings), actionerror.BuildpackNotFoundError{BuildpackName: buildpackName, StackName: buildpackStack}
	}

	if len(ccv3Buildpacks) > 1 {
		for _, buildpack := range ccv3Buildpacks {
			if buildpack.Stack == "" {
				return Buildpack(buildpack), Warnings(warnings), nil
			}
		}
		return Buildpack{}, Warnings(warnings), actionerror.MultipleBuildpacksFoundError{BuildpackName: buildpackName}
	}

	return Buildpack(ccv3Buildpacks[0]), Warnings(warnings), err
}
733166
func MarshalBuild(b chronograf.BuildInfo) ([]byte, error) {
	return proto.Marshal(&BuildInfo{
		Version: b.Version,
		Commit:  b.Commit,
	})
}
1278475
func (r *BytesKeyValIteratorWrapper) GetNext() (kv keyval.BytesKeyVal, stop bool) {
	kv, stop = r.BytesKeyValIterator.GetNext()
	if stop || kv == nil {
		return kv, stop
	}
	return &BytesKeyValWrapper{
		BytesKeyVal: kv,
		decryptData: r.decryptData,
	}, stop
}
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
}
938949
func (bc *BuildController) getBuildByKey(key string) (*buildv1.Build, error) {
	obj, exists, err := bc.buildInformer.GetIndexer().GetByKey(key)
	if err != nil {
		klog.V(2).Infof("Unable to retrieve build %q from store: %v", key, err)
		return nil, err
	}
	if !exists {
		klog.V(2).Infof("Build %q has been deleted", key)
		return nil, nil
	}

	return obj.(*buildv1.Build), nil
}
1078543
func GetAllBuilds() []*Build {
	o := orm.NewOrm()

	var builds []*Build
	// o.QueryTable("build").Filter("name", "slene").All(&builds) to filter with build status
	num, err := o.QueryTable("build").All(&builds)
	fmt.Printf("Returned Rows Num: %s, %s", num, err)
	return builds
}
921926
func (q *BuildQueue) checkBuildGuarantees() error {
	q.mutex.Lock()
	defer q.mutex.Unlock()

	buildCount := map[string]int{}

	for _, status := range q.buildStatus {
		if build := status.currentBuild; build != nil {
			buildCount[build.uuid]++
		}
	}

	switch {
	case q.exclusiveBuilds.running > 1:
		return fmt.Errorf("More than one exclusive build is running")
	case q.exclusiveBuilds.running > 0 && q.regularBuilds.running > 0:
		return fmt.Errorf("Exclusive build is running in parallel with regular build")
	default:
		for uuid, count := range buildCount {
			if count > 1 {
				return fmt.Errorf("UUID %s is being built in parallel", uuid)
			}
		}
	}

	return nil
}
855267
func GetBuild(c context.Context, id buildbot.BuildID) (*ui.MiloBuildLegacy, error) {
	if err := id.Validate(); err != nil {
		return nil, err
	}
	if err := buildstore.CanAccessMaster(c, id.Master); err != nil {
		return nil, err
	}

	switch b, err := buildstore.GetBuild(c, id); {
	case err != nil:
		return nil, err
	case b == nil:
		return nil, errors.Reason("build %s not found", &id).Tag(grpcutil.NotFoundTag).Err()
	default:
		return renderBuild(c, b, true), nil
	}
}
87704
func GetBuilds(c context.Context, q Query) (*QueryResult, error) {
	switch {
	case q.Master == "":
		return nil, errors.New("master is required")
	case q.Builder == "":
		return nil, errors.New("builder is required")
	}

	if !EmulationEnabled(c) {
		return getDatastoreBuilds(c, q, true)
	}

	var emulatedBuilds, buildbotBuilds []*buildbot.Build
	err := parallel.FanOutIn(func(work chan<- func() error) {
		work <- func() (err error) {
			res, err := getDatastoreBuilds(c, q, false)
			if res != nil {
				buildbotBuilds = res.Builds
			}
			return
		}
		work <- func() (err error) {
			emulatedBuilds, err = getEmulatedBuilds(c, q)
			return
		}
	})
	if err != nil {
		return nil, errors.Annotate(err, "could not load builds").Err()
	}

	mergedBuilds := mergeBuilds(emulatedBuilds, buildbotBuilds)
	if q.Limit > 0 && len(mergedBuilds) > q.Limit {
		mergedBuilds = mergedBuilds[:q.Limit]
	}
	return &QueryResult{Builds: mergedBuilds}, nil
}
1146793
func getBuildName(pod metav1.Object) string {
	if pod == nil {
		return ""
	}
	return pod.GetAnnotations()[buildutil.BuildAnnotation]
}
424891
func GetBuildWithId(buildId int64) Build {
	o := orm.NewOrm()

	build := Build{Id: buildId}
	err := o.Read(&build)
	fmt.Printf("ERR: %v\n", err)
	return build
}
1172512
func (c *ApiController) GetBuildLogsIndex() {
	log.Info("Get build log with index")

	buildId := c.GetString(":buildId")
	index, _ := c.GetInt(":index")

	log := redisutil.HgetString(buildId, index)

	next := false

	finish := redisutil.HgetBool(buildId, "finish")
	if finish == false {
		next = true
		fmt.Println("finish == false")
	}

	current := redisutil.HgetInt(buildId, "current")
	if index < current {
		next = true
		fmt.Println("index != current")
	}

	// TODO(tobe): throw error if index is larger than current
	// TODO(tobe): handle when get the index is more than current but it's not total

	response := &GetBuildLogsIndexResponse{
		Log:  log,
		Next: next}

	c.Data["json"] = response
	c.ServeJson()

}
71529
func (md *MDServerRemote) FindNextMD(
	ctx context.Context, tlfID tlf.ID, rootSeqno keybase1.Seqno) (
	nextKbfsRoot *kbfsmd.MerkleRoot, nextMerkleNodes [][]byte,
	nextRootSeqno keybase1.Seqno, err error) {
	ctx = rpc.WithFireNow(ctx)
	md.log.LazyTrace(ctx, "KeyServer: FindNextMD %s %d", tlfID, rootSeqno)
	md.log.CDebugf(ctx, "KeyServer: FindNextMD %s %d", tlfID, rootSeqno)
	defer func() {
		md.deferLog.LazyTrace(ctx, "KeyServer: FindNextMD %s %d done (err=%v)",
			tlfID, rootSeqno, err)
		md.deferLog.CDebugf(ctx, "KeyServer: FindNextMD %s %d done (err=%v)",
			tlfID, rootSeqno, err)
	}()

	arg := keybase1.FindNextMDArg{
		FolderID: tlfID.String(),
		Seqno:    rootSeqno,
	}

	response, err := md.getClient().FindNextMD(ctx, arg)
	if err != nil {
		return nil, nil, 0, err
	}

	if len(response.MerkleNodes) == 0 {
		md.log.CDebugf(ctx, "No merkle data found for %s, seqno=%d",
			tlfID, rootSeqno)
		return nil, nil, 0, nil
	}

	if response.KbfsRoot.Version != 1 {
		return nil, nil, 0,
			kbfsmd.NewMerkleVersionError{Version: response.KbfsRoot.Version}
	}

	// Verify this is a valid merkle root and KBFS root before we
	// decode the bytes.
	md.log.CDebugf(ctx, "Verifying merkle root %d", response.RootSeqno)
	root := keybase1.MerkleRootV2{
		Seqno:    response.RootSeqno,
		HashMeta: response.RootHash,
	}
	expectedKbfsRoot := keybase1.KBFSRoot{
		TreeID: tlfToMerkleTreeID(tlfID),
		Root:   response.KbfsRoot.Root,
	}
	err = md.config.KBPKI().VerifyMerkleRoot(ctx, root, expectedKbfsRoot)
	if err != nil {
		return nil, nil, 0, err
	}

	var kbfsRoot kbfsmd.MerkleRoot
	err = md.config.Codec().Decode(response.KbfsRoot.Root, &kbfsRoot)
	if err != nil {
		return nil, nil, 0, err
	}

	// Validate the hashes of the nodes all the way down to the leaf.
	err = verifyMerkleNodes(ctx, &kbfsRoot, response.MerkleNodes, tlfID)
	if err != nil {
		return nil, nil, 0, err
	}

	return &kbfsRoot, response.MerkleNodes, response.RootSeqno, nil
}