// Job instantiates a Transfer job from the TransferConfig struct
626
func (t *TransferConfig) Job() (*storagetransfer.TransferJob, error) {
	if t.DestBucket == "" || t.Src == nil {
		return nil, ErrBadConfig
	}

	// Google returns an error if more than 20 inclusionary/exclusionary fields are included
	if len(t.IncludePrefixes) > MaxPrefix || len(t.ExcludePrefixes) > MaxPrefix {
		return nil, ErrBadFilter
	}

	spec := t.Src.TransferSpec(t.DestBucket)

	// Set the file-filters if the conditions are met
	if len(t.IncludePrefixes) > 0 || len(t.ExcludePrefixes) > 0 {
		spec.ObjectConditions = &storagetransfer.ObjectConditions{
			ExcludePrefixes: t.ExcludePrefixes,
			IncludePrefixes: t.IncludePrefixes,
		}
	}

	// if a schedule is not provided, create a 1-time transfer schedule
	var schedule *storagetransfer.Schedule
	if t.Schedule == nil {
		schedule = oneTimeJobSchedule(time.Now())
	}

	description := fmt.Sprintf("%s_%s_transfer", t.DestBucket, t.Src)
	return newTransferJob(t.ProjectID, description, spec, schedule), nil
}
887283
func (s *Server) Jobs(p *Printer) ([]*Job, error) {
	var mr multipartRequest
	mr.init()
	mr.WriteField("printerid", p.ID)

	var resp jobsResponse
	err := jsonRPC(&s.auth, "POST", cloudprintURL+"/fetch", &mr, &resp)
	if err != nil {
		return nil, fmt.Errorf("Jobs: %v", err)
	}

	var list []*Job
	for _, desc := range resp.Jobs {
		list = append(list, desc.Job())
	}
	return list, nil
}
1122870
func (j *Job) save() error {
	t := newTransaction()
	t.saveJob(j)
	if err := t.exec(); err != nil {
		return err
	}
	return nil
}
403564
func (c *jobs) Update(job *extensions.Job) (result *extensions.Job, err error) {
	result = &extensions.Job{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("jobs").
		Name(job.Name).
		Body(job).
		Do().
		Into(result)
	return
}
539151
func (p *workerPool) work() {
	for task := range p.tasksChan {
		task.Run(&p.wg)
	}
}
610564
func (p *Pool) Put(job func()) error {
	if atomic.LoadInt32(&p.state) != 1 {
		return ErrPoolShutdown
	}

	select {
	case p.jobs <- job:
		if p.busy >= p.current && p.current < p.Max {
			go p.short()
		}
		return nil
	default:
		return ErrPoolFull
	}
}
1040671
func (c *Client) PutJob(job *ct.Job) error {
	if job.UUID == "" || job.AppID == "" {
		return errors.New("controller: missing job uuid and/or app id")
	}
	return c.Put(fmt.Sprintf("/apps/%s/jobs/%s", job.AppID, job.UUID), job, job)
}
1065234
func (s *StateStore) UpsertJob(index uint64, job *structs.Job) error {
	txn := s.db.Txn(true)
	defer txn.Abort()
	if err := s.upsertJobImpl(index, job, false, txn); err != nil {
		return err
	}
	txn.Commit()
	return nil
}
1360612
func (o *CreateJobOptions) Run() error {
	var job *batchv1.Job
	if len(o.Image) > 0 {
		job = o.createJob()
	} else {
		infos, err := o.Builder.
			Unstructured().
			NamespaceParam(o.Namespace).DefaultNamespace().
			ResourceTypeOrNameArgs(false, o.From).
			Flatten().
			Latest().
			Do().
			Infos()
		if err != nil {
			return err
		}
		if len(infos) != 1 {
			return fmt.Errorf("from must be an existing cronjob")
		}

		uncastVersionedObj, err := scheme.Scheme.ConvertToVersion(infos[0].Object, batchv1beta1.SchemeGroupVersion)
		if err != nil {
			return fmt.Errorf("from must be an existing cronjob: %v", err)
		}
		cronJob, ok := uncastVersionedObj.(*batchv1beta1.CronJob)
		if !ok {
			return fmt.Errorf("from must be an existing cronjob")
		}

		job = o.createJobFromCronJob(cronJob)
	}
	if !o.DryRun {
		var err error
		job, err = o.Client.Jobs(o.Namespace).Create(job)
		if err != nil {
			return fmt.Errorf("failed to create job: %v", err)
		}
	}

	return o.PrintObj(job)
}
912636
func (j *Jobs) Register(job *Job, q *WriteOptions) (*JobRegisterResponse, *WriteMeta, error) {
	return j.RegisterOpts(job, nil, q)
}
960312
func (dbCallback *DbCallbackImplied) Work(value interface{}, worker *DbWorker) {
	dbCallback.WorkFn(value, worker)
}
934668
func (ts *taskScheduler) Work() {
	for _, r := range ts.runners {
		r.Start()
		if r.IsIdle() {
			// Ran out of jobs to start.
			break
		}
	}
}
393810
func (j *Job) Done() {
	j.mu.Lock()
	defer j.mu.Unlock()

	if j.conn == nil || j.pool == nil {
		// already marked as done
		return
	}

	var ok bool
	// Swallow this error because we don't want an unlock failure to cause work to
	// stop.
	_ = j.conn.QueryRow("que_unlock_job", j.ID).Scan(&ok)

	j.pool.Release(j.conn)
	j.pool = nil
	j.conn = nil
}
95643
func (j *resizeJob) run() error {
	j.Logger.Printf("run resizeJob")
	// Set job state to RUNNING.
	j.setState(resizeJobStateRunning)

	// Job can be considered done in the case where it doesn't require any action.
	if !j.nodesArePending() {
		j.Logger.Printf("resizeJob contains no pending tasks; mark as done")
		j.result <- resizeJobStateDone
		return nil
	}

	j.Logger.Printf("distribute tasks for resizeJob")
	err := j.distributeResizeInstructions()
	if err != nil {
		j.result <- resizeJobStateAborted
		return errors.Wrap(err, "distributing instructions")
	}
	return nil
}
1193809
func (s V1ApplySpec) Jobs() []models.Job {
	jobsWithSource := []models.Job{}

	if s.RenderedTemplatesArchiveSpec != nil {
		for _, j := range s.JobSpec.JobTemplateSpecsAsJobs() {
			j.Source = s.RenderedTemplatesArchiveSpec.AsSource(j)
			j.Packages = s.Packages()
			jobsWithSource = append(jobsWithSource, j)
		}
	}

	return jobsWithSource
}
1086800
func (c *Conn) StatsJob(id uint64) (map[string]string, error) {
	r, err := c.cmd(nil, nil, nil, "stats-job", id)
	if err != nil {
		return nil, err
	}
	body, err := c.readResp(r, true, "OK")
	return parseDict(body), err
}
604804
func (j *Job) Dispatch(args *structs.JobDispatchRequest, reply *structs.JobDispatchResponse) error {
	if done, err := j.srv.forward("Job.Dispatch", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince([]string{"nomad", "job", "dispatch"}, time.Now())

	// Check for submit-job permissions
	if aclObj, err := j.srv.ResolveToken(args.AuthToken); err != nil {
		return err
	} else if aclObj != nil && !aclObj.AllowNsOp(args.RequestNamespace(), acl.NamespaceCapabilityDispatchJob) {
		return structs.ErrPermissionDenied
	}

	// Lookup the parameterized job
	if args.JobID == "" {
		return fmt.Errorf("missing parameterized job ID")
	}

	snap, err := j.srv.fsm.State().Snapshot()
	if err != nil {
		return err
	}
	ws := memdb.NewWatchSet()
	parameterizedJob, err := snap.JobByID(ws, args.RequestNamespace(), args.JobID)
	if err != nil {
		return err
	}
	if parameterizedJob == nil {
		return fmt.Errorf("parameterized job not found")
	}

	if !parameterizedJob.IsParameterized() {
		return fmt.Errorf("Specified job %q is not a parameterized job", args.JobID)
	}

	if parameterizedJob.Stop {
		return fmt.Errorf("Specified job %q is stopped", args.JobID)
	}

	// Validate the arguments
	if err := validateDispatchRequest(args, parameterizedJob); err != nil {
		return err
	}

	// Derive the child job and commit it via Raft
	dispatchJob := parameterizedJob.Copy()
	dispatchJob.ID = structs.DispatchedID(parameterizedJob.ID, time.Now())
	dispatchJob.ParentID = parameterizedJob.ID
	dispatchJob.Name = dispatchJob.ID
	dispatchJob.SetSubmitTime()
	dispatchJob.Dispatched = true

	// Merge in the meta data
	for k, v := range args.Meta {
		if dispatchJob.Meta == nil {
			dispatchJob.Meta = make(map[string]string, len(args.Meta))
		}
		dispatchJob.Meta[k] = v
	}

	// Compress the payload
	dispatchJob.Payload = snappy.Encode(nil, args.Payload)

	regReq := &structs.JobRegisterRequest{
		Job:          dispatchJob,
		WriteRequest: args.WriteRequest,
	}

	// Commit this update via Raft
	fsmErr, jobCreateIndex, err := j.srv.raftApply(structs.JobRegisterRequestType, regReq)
	if err, ok := fsmErr.(error); ok && err != nil {
		j.logger.Error("dispatched job register failed", "error", err, "fsm", true)
		return err
	}
	if err != nil {
		j.logger.Error("dispatched job register failed", "error", err, "raft", true)
		return err
	}

	reply.JobCreateIndex = jobCreateIndex
	reply.DispatchedJobID = dispatchJob.ID
	reply.Index = jobCreateIndex

	// If the job is periodic, we don't create an eval.
	if !dispatchJob.IsPeriodic() {
		// Create a new evaluation
		eval := &structs.Evaluation{
			ID:             uuid.Generate(),
			Namespace:      args.RequestNamespace(),
			Priority:       dispatchJob.Priority,
			Type:           dispatchJob.Type,
			TriggeredBy:    structs.EvalTriggerJobRegister,
			JobID:          dispatchJob.ID,
			JobModifyIndex: jobCreateIndex,
			Status:         structs.EvalStatusPending,
		}
		update := &structs.EvalUpdateRequest{
			Evals:        []*structs.Evaluation{eval},
			WriteRequest: structs.WriteRequest{Region: args.Region},
		}

		// Commit this evaluation via Raft
		_, evalIndex, err := j.srv.raftApply(structs.EvalUpdateRequestType, update)
		if err != nil {
			j.logger.Error("eval create failed", "error", err, "method", "dispatch")
			return err
		}

		// Setup the reply
		reply.EvalID = eval.ID
		reply.EvalCreateIndex = evalIndex
		reply.Index = evalIndex
	}

	return nil
}