// GetBuild fetches a build by UUID
//
// Codeship API docs: https://apidocs.codeship.com/v2/builds/get-build
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
}
965544
func GetRebuildImage(docker Docker, config *api.Config) (*PullResult, error) {
	return pullAndCheck(config.Tag, docker, config.BuilderPullPolicy, config)
}
435277
func extractBuild(c context.Context, r *http.Request) (*Build, error) {
	// sent by pubsub.
	// This struct is just convenient for unwrapping the json message
	var msg struct {
		Message struct {
			Data []byte
		}
		Attributes map[string]interface{}
	}
	if err := json.NewDecoder(r.Body).Decode(&msg); err != nil {
		return nil, errors.Annotate(err, "could not decode message").Err()
	}

	if v, ok := msg.Attributes["version"].(string); ok && v != "v1" {
		// Ignore v2 pubsub messages. TODO(nodir): use v2.
		return nil, nil
	}
	var message struct {
		Build    bbv1.ApiCommonBuildMessage
		Hostname string
	}
	switch err := json.Unmarshal(msg.Message.Data, &message); {
	case err != nil:
		return nil, errors.Annotate(err, "could not parse pubsub message data").Err()
	case !strings.HasPrefix(message.Build.Bucket, "luci."):
		logging.Infof(c, "Received build that isn't part of LUCI, ignoring...")
		return nil, nil
	case message.Build.Status != bbv1.StatusCompleted:
		logging.Infof(c, "Received build that hasn't completed yet, ignoring...")
		return nil, nil
	}

	buildsClient, err := newBuildsClient(c, message.Hostname, message.Build.Project)
	if err != nil {
		return nil, err
	}

	logging.Infof(c, "fetching build %d", message.Build.Id)
	res, err := buildsClient.GetBuild(c, &buildbucketpb.GetBuildRequest{
		Id:     message.Build.Id,
		Fields: buildFieldMask,
	})
	switch {
	case status.Code(err) == codes.NotFound:
		logging.Warningf(c, "no access to build %d", message.Build.Id)
		return nil, nil
	case err != nil:
		err = grpcutil.WrapIfTransient(err)
		err = errors.Annotate(err, "could not fetch buildbucket build %d", message.Build.Id).Err()
		return nil, err
	}

	emails, err := extractEmailNotifyValues(res, message.Build.ParametersJson)
	if err != nil {
		return nil, errors.Annotate(err, "could not decode email_notify").Err()
	}

	return &Build{
		Build:       *res,
		EmailNotify: emails,
	}, nil
}
1209187
func GetRawBuild(c context.Context, address string) (*bbv1.ApiCommonBuildMessage, error) {
	host, err := getHost(c)
	if err != nil {
		return nil, err
	}

	client, err := newBuildbucketClient(c, host)
	if err != nil {
		return nil, err
	}
	// This runs a search RPC against BuildBucket, but it is optimized for speed.
	build, err := bbv1.GetByAddress(c, client, address)
	switch {
	case err != nil:
		return nil, errors.Annotate(err, "could not get build at %q", address).Err()
	case build == nil && auth.CurrentUser(c).Identity == identity.AnonymousIdentity:
		return nil, errors.Reason("not logged in").Tag(grpcutil.UnauthenticatedTag).Err()
	case build == nil:
		return nil, errors.Reason("build at %q not found", address).Tag(grpcutil.NotFoundTag).Err()
	default:
		return build, nil
	}
}
464719
func (c *ApiController) GetBuildLogsAll() {
	log.Info("Get all build logs")

	//buildId := c.GetString(":buildId")
	//field := 0
	//result := redisutil.HgetString(buildId, field)
	//c.Ctx.WriteString(result)

	// TODO(tobe): change to hgetall  from redis
	mystruct := `{0: "apt-get install", 1: "go test"}`

	c.Data["json"] = &mystruct
	c.ServeJson()
}
337017
func GetBuildPage(ctx *router.Context, br buildbucketpb.GetBuildRequest, forceBlamelist bool) (*ui.BuildPage, error) {
	c := ctx.Context
	host, err := getHost(c)
	if err != nil {
		return nil, err
	}
	client, err := buildbucketClient(c, host, auth.AsUser)
	if err != nil {
		return nil, err
	}

	var b *buildbucketpb.Build
	var relatedBuilds []*ui.Build
	var blame []*ui.Commit
	var blameErr error
	if err = parallel.FanOutIn(func(ch chan<- func() error) {
		ch <- func() (err error) {
			fullbr := br // Copy request
			fullbr.Fields = fullBuildMask
			b, err = client.GetBuild(c, &fullbr)
			return common.TagGRPC(c, err)
		}

		// Fetch a small build with just a tiny bit of information.
		// We use this to get the Gitiles tag so that we can fetch
		// related builds and blamelist in parallel.
		smallbr := br // Copy request
		smallbr.Fields = tagsAndGitilesMask
		sb, err := client.GetBuild(c, &smallbr)
		if err != nil {
			return
		}
		ch <- func() (err error) {
			relatedBuilds, err = getRelatedBuilds(c, client, sb)
			return
		}
		ch <- func() error {
			timeout := 1 * time.Second
			if forceBlamelist {
				timeout = 55 * time.Second
			}
			nc, cancel := context.WithTimeout(c, timeout)
			defer cancel()
			blame, blameErr = getBlame(nc, host, sb)
			return nil
		}
	}); err != nil {
		return nil, err
	}
	link, err := getBugLink(ctx, b)
	logging.Infof(c, "Got all the things")
	return &ui.BuildPage{
		Build:           ui.Build{b},
		Blame:           blame,
		RelatedBuilds:   relatedBuilds,
		BuildBugLink:    link,
		BuildbucketHost: host,
		Now:             clock.Now(c),
		BlamelistError:  blameErr,
		ForcedBlamelist: forceBlamelist,
	}, err
}
1131276
func (s *BuildStore) Get(ctx context.Context) (chronograf.BuildInfo, error) {
	var build chronograf.BuildInfo
	if err := s.client.db.View(func(tx *bolt.Tx) error {
		var err error
		build, err = s.get(ctx, tx)
		if err != nil {
			return err
		}
		return nil
	}); err != nil {
		return chronograf.BuildInfo{}, err
	}

	return build, nil
}
591196
func getBuildModule() *debug.Module {
	bi, ok := debug.ReadBuildInfo()
	if ok {
		// The recommended way to build Caddy involves
		// creating a separate main module, which
		// preserves caddy a read-only dependency
		// TODO: track related Go issue: https://github.com/golang/go/issues/29228
		for _, mod := range bi.Deps {
			if mod.Path == "github.com/mholt/caddy" {
				return mod
			}
		}
	}
	return &debug.Module{Version: "unknown"}
}
14249
func (g *BuildGenerator) createBuild(ctx context.Context, build *buildv1.Build) (*buildv1.Build, error) {
	if !rest.ValidNamespace(ctx, &build.ObjectMeta) {
		return nil, errors.NewConflict(buildv1.Resource("build"), build.Namespace, fmt.Errorf("Build.Namespace does not match the provided context"))
	}
	rest.FillObjectMetaSystemFields(&build.ObjectMeta)
	err := g.Client.CreateBuild(ctx, build)
	if err != nil {
		return nil, err
	}
	return g.Client.GetBuild(ctx, build.Name, &metav1.GetOptions{})
}
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
}
152940
func generateBuildFromBuild(build *buildv1.Build, buildConfig *buildv1.BuildConfig) *buildv1.Build {
	buildCopy := build.DeepCopy()

	newBuild := &buildv1.Build{
		Spec: buildCopy.Spec,
		ObjectMeta: metav1.ObjectMeta{
			Name:            getNextBuildNameFromBuild(buildCopy, buildConfig),
			Labels:          buildCopy.ObjectMeta.Labels,
			Annotations:     buildCopy.ObjectMeta.Annotations,
			OwnerReferences: buildCopy.ObjectMeta.OwnerReferences,
		},
		Status: buildv1.BuildStatus{
			Phase:  buildv1.BuildPhaseNew,
			Config: buildCopy.Status.Config,
		},
	}
	// TODO remove/update this when we support cloning binary builds
	// we need to explicitly set type to empty string so that this does not get
	// defaulted to non-empty binary build
	newBuild.Spec.Source.Type = ""
	newBuild.Spec.Source.Binary = nil
	if newBuild.Annotations == nil {
		newBuild.Annotations = make(map[string]string)
	}
	newBuild.Annotations[buildutil.BuildCloneAnnotation] = build.Name
	if buildConfig != nil {
		newBuild.Annotations[buildutil.BuildNumberAnnotation] = strconv.FormatInt(buildConfig.Status.LastVersion, 10)
	} else {
		// builds without a buildconfig don't have build numbers.
		delete(newBuild.Annotations, buildutil.BuildNumberAnnotation)
	}

	// if they exist, Jenkins reporting annotations must be removed when cloning.
	delete(newBuild.Annotations, buildutil.BuildJenkinsStatusJSONAnnotation)
	delete(newBuild.Annotations, buildutil.BuildJenkinsLogURLAnnotation)
	delete(newBuild.Annotations, buildutil.BuildJenkinsConsoleLogURLAnnotation)
	delete(newBuild.Annotations, buildutil.BuildJenkinsBlueOceanLogURLAnnotation)
	delete(newBuild.Annotations, buildutil.BuildJenkinsBuildURIAnnotation)

	// remove the BuildPodNameAnnotation for good measure.
	delete(newBuild.Annotations, buildutil.BuildPodNameAnnotation)

	return newBuild
}
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
}
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
}
87585
func (c *ApiController) GetSearchBuilds() {
	log.Info("Get search builds")

	result := "Not implemented"
	c.Ctx.WriteString(result)
}
218058
func (c Client) UpdateBuild(ctx context.Context, build *buildv1.Build) error {
	_, err := c.Builds.Builds(apirequest.NamespaceValue(ctx)).Update(build)
	return err
}
652770
func (s *Server) getBuilder(path string) (*ring.Builder, error) {
	_, b, err := ring.RingOrBuilder(path)
	return b, err
}
61183
func GetBuilderID(c context.Context, id int64) (builder *buildbucketpb.BuilderID, number int32, err error) {
	host, err := getHost(c)
	if err != nil {
		return
	}
	client, err := buildbucketClient(c, host, auth.AsUser)
	if err != nil {
		return
	}
	br, err := client.GetBuild(c, &buildbucketpb.GetBuildRequest{
		Id:     id,
		Fields: builderIDMask,
	})
	switch grpcutil.Code(err) {
	case codes.OK:
		builder = br.Builder
		number = br.Number
	case codes.NotFound:
		if auth.CurrentIdentity(c) == identity.AnonymousIdentity {
			err = ErrNotLoggedIn
			return
		}
		fallthrough
	case codes.PermissionDenied:
		err = ErrNotFound
	}
	return
}