// makeJob builds UI presentation for engine.Job.
546369
func makeJob(c context.Context, j *engine.Job, log *engine.JobTriageLog) *schedulerJob {
	traits, err := presentation.GetJobTraits(c, config(c).Catalog, j)
	if err != nil {
		logging.WithError(err).Warningf(c, "Failed to get task traits for %s", j.JobID)
	}

	now := clock.Now(c).UTC()
	nextRun := ""
	switch ts := j.CronTickTime(); {
	case ts == schedule.DistantFuture:
		nextRun = "-"
	case !ts.IsZero():
		nextRun = humanize.RelTime(ts, now, "ago", "from now")
	default:
		nextRun = "not scheduled yet"
	}

	// Internal state names aren't very user friendly. Introduce some aliases.
	state := presentation.GetPublicStateKind(j, traits)
	labelClass := stateToLabelClass[state]

	// Put triggers after regular jobs.
	sortGroup := "A"
	if j.Flavor == catalog.JobFlavorTrigger {
		sortGroup = "B"
	}

	out := &schedulerJob{
		ProjectID:      j.ProjectID,
		JobName:        j.JobName(),
		Schedule:       j.Schedule,
		Definition:     taskToText(j.Task),
		Policy:         policyToText(j.TriggeringPolicyRaw),
		Revision:       j.Revision,
		RevisionURL:    j.RevisionURL,
		State:          string(state),
		NextRun:        nextRun,
		Paused:         j.Paused,
		LabelClass:     labelClass,
		JobFlavorIcon:  flavorToIconClass[j.Flavor],
		JobFlavorTitle: flavorToTitle[j.Flavor],

		sortGroup: sortGroup,
		now:       now,
		traits:    traits,
	}

	// Fill in job triage log details if available. They are not available in
	// job listings, for example.
	if log != nil {
		out.TriageLog.Available = true
		out.TriageLog.LastTriage = humanize.RelTime(log.LastTriage, now, "ago", "")
		out.TriageLog.Stale = log.Stale()
		out.TriageLog.Staleness = j.LastTriage.Sub(log.LastTriage)
		out.TriageLog.DebugLog = log.DebugLog
	}

	return out
}
1017436
func (b *builder) renderJobTemplates(
	releaseJobs []bireljob.Job,
	releaseJobProperties map[string]*biproperty.Map,
	jobProperties biproperty.Map,
	globalProperties biproperty.Map,
	deploymentName string,
	address string,
	stage biui.Stage,
) (renderedJobs, error) {
	var (
		renderedJobListArchive bitemplate.RenderedJobListArchive
		blobID                 string
	)
	err := stage.Perform("Rendering job templates", func() error {
		renderedJobList, err := b.jobListRenderer.Render(releaseJobs, releaseJobProperties, jobProperties, globalProperties, deploymentName, address)
		if err != nil {
			return err
		}
		defer renderedJobList.DeleteSilently()

		renderedJobListArchive, err = b.renderedJobListCompressor.Compress(renderedJobList)
		if err != nil {
			return bosherr.WrapError(err, "Compressing rendered job templates")
		}
		defer renderedJobListArchive.DeleteSilently()

		blobID, err = b.blobstore.Add(renderedJobListArchive.Path())
		if err != nil {
			return bosherr.WrapErrorf(err, "Uploading rendered job template archive '%s' to the blobstore", renderedJobListArchive.Path())
		}

		return nil
	})
	if err != nil {
		return renderedJobs{}, err
	}

	return renderedJobs{
		BlobstoreID: blobID,
		Archive:     renderedJobListArchive,
	}, nil
}
1052919
func (e *EvalEligibility) SetJob(job *structs.Job) {
	// Determine whether the job has escaped constraints.
	e.jobEscaped = len(structs.EscapedConstraints(job.Constraints)) != 0

	// Determine the escaped constraints per task group.
	for _, tg := range job.TaskGroups {
		constraints := tg.Constraints
		for _, task := range tg.Tasks {
			constraints = append(constraints, task.Constraints...)
		}

		e.tgEscapedConstraints[tg.Name] = len(structs.EscapedConstraints(constraints)) != 0
	}
}
248960
func workJobs(prs []*processNode, pus []*publishNode, t *task, pj job) {
	// optimize for no jobs
	if len(prs) == 0 && len(pus) == 0 {
		return
	}
	// Create waitgroup to block until all jobs are submitted
	wg := &sync.WaitGroup{}
	workflowLogger.WithFields(log.Fields{
		"_block":              "work-jobs",
		"task-id":             t.id,
		"task-name":           t.name,
		"count-process-nodes": len(prs),
		"count-publish-nodes": len(pus),
		"parent-node-type":    pj.TypeString(),
	}).Debug("Batch submission of process and publish nodes")
	// range over the process jobs and call submitProcessJob
	for _, pr := range prs {
		// increment the wait group (before starting goroutine to prevent a race condition)
		wg.Add(1)
		// Start goroutine to submit the process job
		go submitProcessJob(pj, t, wg, pr)
	}
	// range over the publish jobs and call submitPublishJob
	for _, pu := range pus {
		// increment the wait group (before starting goroutine to prevent a race condition)
		wg.Add(1)
		// Start goroutine to submit the process job
		go submitPublishJob(pj, t, wg, pu)
	}
	// Wait until all job submisson goroutines are done
	wg.Wait()
	workflowLogger.WithFields(log.Fields{
		"_block":              "work-jobs",
		"task-id":             t.id,
		"task-name":           t.name,
		"count-process-nodes": len(prs),
		"count-publish-nodes": len(pus),
		"parent-node-type":    pj.TypeString(),
	}).Debug("Batch submission complete")
}
836071
func (s *SchedulerServer) getJob(ctx context.Context, ref *scheduler.JobRef) (*engine.Job, error) {
	jobID := ref.GetProject() + "/" + ref.GetJob()
	switch job, err := s.Engine.GetVisibleJob(ctx, jobID); {
	case err == nil:
		return job, nil
	case err == engine.ErrNoSuchJob:
		return nil, status.Errorf(codes.NotFound, "no such job or no READ permission")
	default:
		return nil, status.Errorf(codes.Internal, "internal error when fetching job: %s", err)
	}
}
1132757
func (j *JobGetter) ApiJob(jpath string) (*api.Job, error) {
	var jobfile io.Reader
	switch jpath {
	case "-":
		if j.testStdin != nil {
			jobfile = j.testStdin
		} else {
			jobfile = os.Stdin
		}
	default:
		if len(jpath) == 0 {
			return nil, fmt.Errorf("Error jobfile path has to be specified.")
		}

		job, err := ioutil.TempFile("", "jobfile")
		if err != nil {
			return nil, err
		}
		defer os.Remove(job.Name())

		if err := job.Close(); err != nil {
			return nil, err
		}

		// Get the pwd
		pwd, err := os.Getwd()
		if err != nil {
			return nil, err
		}

		client := &gg.Client{
			Src: jpath,
			Pwd: pwd,
			Dst: job.Name(),
		}

		if err := client.Get(); err != nil {
			return nil, fmt.Errorf("Error getting jobfile from %q: %v", jpath, err)
		} else {
			file, err := os.Open(job.Name())
			defer file.Close()
			if err != nil {
				return nil, fmt.Errorf("Error opening file %q: %v", jpath, err)
			}
			jobfile = file
		}
	}

	// Parse the JobFile
	jobStruct, err := jobspec.Parse(jobfile)
	if err != nil {
		return nil, fmt.Errorf("Error parsing job file from %s: %v", jpath, err)
	}

	return jobStruct, nil
}
232535
func (e *engineImpl) GetVisibleJob(c context.Context, jobID string) (*Job, error) {
	job, err := e.getJob(c, jobID)
	switch {
	case err != nil:
		return nil, err
	case job == nil || !job.Enabled:
		return nil, ErrNoSuchJob
	}
	if err := job.CheckRole(c, acl.Reader); err != nil {
		if err == ErrNoPermission {
			err = ErrNoSuchJob // pretend protected jobs don't exist
		}
		return nil, err
	}
	return job, nil
}
1069009
func (m *Meta) EnQueueDDLJob(job *model.Job) error {
	return m.enQueueDDLJob(m.jobListKey, job)
}
757380
func (worker *Worker) AddJob(qorJob QorJobInterface) error {
	return worker.Queue.Add(qorJob)
}
891819
func (c *Host) StopJob(id string) error {
	return c.c.Delete(fmt.Sprintf("/host/jobs/%s", id))
}
655504
func (e *engineImpl) PauseJob(c context.Context, job *Job) error {
	if err := job.CheckRole(c, acl.Owner); err != nil {
		return err
	}
	return e.setJobPausedFlag(c, job, true, auth.CurrentIdentity(c))
}
34574
func (a *S3Store) makeBlockJobs(ctx context.Context, r io.Reader, blockCh chan job, stashKey StashKey, previous *AttachmentInfo) error {
	var partNumber int
	for {
		partNumber++
		block := make([]byte, blockSize)
		// must call io.ReadFull to ensure full block read
		n, err := io.ReadFull(r, block)
		// io.ErrUnexpectedEOF will be returned for last partial block,
		// which is ok.
		if err != nil && err != io.ErrUnexpectedEOF && err != io.EOF {
			return err
		}
		if n < blockSize {
			block = block[:n]
		}
		if n > 0 {
			md5sum := md5.Sum(block)
			md5hex := hex.EncodeToString(md5sum[:])

			if previous != nil {
				// resuming an upload, so check local stash record
				// and abort on mismatch before adding a job for this block
				// because if we don't it amounts to nonce reuse
				lhash, found := previous.Parts[partNumber]
				if found && lhash != md5hex {
					a.Debug(ctx, "makeBlockJobs: part %d failed local part record verification", partNumber)
					return ErrAbortOnPartMismatch
				}
			}

			if err := a.addJob(ctx, blockCh, block, partNumber, md5hex); err != nil {
				return err
			}
		}
		if err == io.EOF || err == io.ErrUnexpectedEOF {
			break
		}

		if a.blockLimit > 0 && partNumber >= a.blockLimit {
			a.Debug(ctx, "makeBlockJobs: hit blockLimit of %d", a.blockLimit)
			break
		}
	}
	return nil
}
799345
func (e *engineImpl) getJob(c context.Context, jobID string) (*Job, error) {
	job := &Job{JobID: jobID}
	switch err := ds.Get(c, job); {
	case err == nil:
		return job, nil
	case err == ds.ErrNoSuchEntity:
		return nil, nil
	default:
		return nil, transient.Tag.Apply(err)
	}
}
932958
func (a *S3Store) addJob(ctx context.Context, blockCh chan job, block []byte, partNumber int, hash string) error {
	// Create a job, unless the context has been canceled.
	select {
	case blockCh <- job{block: block, index: partNumber, hash: hash}:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}
644500
func builder(jobs <-chan string, buildStarted chan<- string, buildDone chan<- bool) {
	createThreshold := func() <-chan time.Time {
		return time.After(time.Duration(WorkDelay * time.Millisecond))
	}

	threshold := createThreshold()
	eventPath := ""

	for {
		select {
		case eventPath = <-jobs:
			threshold = createThreshold()
		case <-threshold:
			buildStarted <- eventPath
			buildDone <- build()
		}
	}
}
259723
func awaitJob(ctx context.Context, client api.Server, jobID job.ID) (job.Result, error) {
	var result job.Result
	err := backoff(100*time.Millisecond, 2, 50, 1*time.Minute, func() (bool, error) {
		j, err := client.JobStatus(ctx, jobID)
		if err != nil {
			return false, err
		}
		switch j.StatusString {
		case job.StatusFailed:
			return false, j
		case job.StatusSucceeded:
			if j.Err != "" {
				// How did we succeed but still get an error!?
				return false, j
			}
			result = j.Result
			return true, nil
		}
		return false, nil
	})
	return result, err
}
390143
func (j *Jenkins) CopyJob(copyFrom string, newName string) (*Job, error) {
	job := Job{Jenkins: j, Raw: new(JobResponse), Base: "/job/" + copyFrom}
	_, err := job.Poll()
	if err != nil {
		return nil, err
	}
	return job.Copy(newName)
}