// IsErrUnknownJob returns whether the error is due to an unknown
// job.
14453
func IsErrUnknownJob(err error) bool {
	return err != nil && strings.Contains(err.Error(), ErrUnknownJobPrefix)
}
585279
func (worker *Worker) GetJob(jobID string) (QorJobInterface, error) {
	qorJob := worker.JobResource.NewStruct().(QorJobInterface)

	context := worker.Admin.NewContext(nil, nil)
	context.ResourceID = jobID
	context.Resource = worker.JobResource

	if err := worker.JobResource.FindOneHandler(qorJob, nil, context.Context); err == nil {
		for _, job := range worker.Jobs {
			if job.Name == qorJob.GetJobName() {
				qorJob.SetJob(job)
				return qorJob, nil
			}
		}
		return nil, fmt.Errorf("failed to load job: %v, unregistered job type: %v", jobID, qorJob.GetJobName())
	}
	return nil, fmt.Errorf("failed to find job: %v", jobID)
}
1080936
func CancelJobs(txn kv.Transaction, ids []int64) ([]error, error) {
	if len(ids) == 0 {
		return nil, nil
	}

	jobs, err := GetDDLJobs(txn)
	if err != nil {
		return nil, errors.Trace(err)
	}

	errs := make([]error, len(ids))
	t := meta.NewMeta(txn)
	for i, id := range ids {
		found := false
		for j, job := range jobs {
			if id != job.ID {
				logutil.Logger(context.Background()).Debug("the job that needs to be canceled isn't equal to current job",
					zap.Int64("need to canceled job ID", id),
					zap.Int64("current job ID", job.ID))
				continue
			}
			found = true
			// These states can't be cancelled.
			if job.IsDone() || job.IsSynced() {
				errs[i] = ErrCancelFinishedDDLJob.GenWithStackByArgs(id)
				continue
			}
			// If the state is rolling back, it means the work is cleaning the data after cancelling the job.
			if job.IsCancelled() || job.IsRollingback() || job.IsRollbackDone() {
				continue
			}
			if !IsJobRollbackable(job) {
				errs[i] = ErrCannotCancelDDLJob.GenWithStackByArgs(job.ID)
				continue
			}

			job.State = model.JobStateCancelling
			// Make sure RawArgs isn't overwritten.
			err := job.DecodeArgs(job.RawArgs)
			if err != nil {
				errs[i] = errors.Trace(err)
				continue
			}
			if job.Type == model.ActionAddIndex {
				err = t.UpdateDDLJob(int64(j), job, true, meta.AddIndexJobListKey)
			} else {
				err = t.UpdateDDLJob(int64(j), job, true)
			}
			if err != nil {
				errs[i] = errors.Trace(err)
			}
		}
		if !found {
			errs[i] = ErrDDLJobNotFound.GenWithStackByArgs(id)
		}
	}
	return errs, nil
}
1180647
func (c *Host) GetJob(id string) (*host.ActiveJob, error) {
	var res host.ActiveJob
	err := c.c.Get(fmt.Sprintf("/host/jobs/%s", id), &res)
	return &res, err
}
379848
func (s *Server) UpdateJob(j *Job, status JobStatus, code int, message string) error {
	var mr multipartRequest
	mr.init()
	mr.WriteField("jobid", j.ID)
	mr.WriteField("printerid", j.PrinterID)
	mr.WriteField("status", string(status))
	if status == JobError {
		mr.WriteField("code", fmt.Sprint(code))
		mr.WriteField("message", message)
	}

	err := jsonRPC(&s.auth, "POST", cloudprintURL+"/control", &mr, nil)
	if err != nil {
		return fmt.Errorf("UpdateJob: %v", err)
	}
	return nil
}
626761
func newScanJobsHandler(jobs *[]*Job) replyHandler {
	return func(reply interface{}) error {
		values, err := redis.Values(reply, nil)
		if err != nil {
			return nil
		}
		for _, fields := range values {
			job := &Job{}
			if err := scanJob(fields, job); err != nil {
				return err
			}
			(*jobs) = append((*jobs), job)
		}
		return nil
	}
}
441232
func (c *FakeJobController) IsCleaningJobRunning(pvName string) bool {
	c.IsRunningCount++
	_, exists := c.pvCleanupRunning[pvName]
	return exists
}
252696
func NewCleanupJob(pv *apiv1.PersistentVolume, volMode apiv1.PersistentVolumeMode, imageName string, nodeName string, namespace string, mountPath string,
	config common.MountConfig) (*batch_v1.Job, error) {
	priv := true
	// Container definition
	jobContainer := apiv1.Container{
		Name:  JobContainerName,
		Image: imageName,
		SecurityContext: &apiv1.SecurityContext{
			Privileged: &priv,
		},
	}
	if volMode == apiv1.PersistentVolumeBlock {
		jobContainer.Command = config.BlockCleanerCommand
		jobContainer.Env = []apiv1.EnvVar{{Name: common.LocalPVEnv, Value: mountPath}}
	} else if volMode == apiv1.PersistentVolumeFilesystem {
		// We only have one way to clean filesystem, so no need to customize
		// filesystem cleaner command.
		jobContainer.Command = []string{"/scripts/fsclean.sh"}
		jobContainer.Env = []apiv1.EnvVar{{Name: common.LocalFilesystemEnv, Value: mountPath}}
	} else {
		return nil, fmt.Errorf("unknown PersistentVolume mode: %v", volMode)
	}
	mountName := common.GenerateMountName(&config)
	volumes := []apiv1.Volume{
		{
			Name: mountName,
			VolumeSource: apiv1.VolumeSource{
				HostPath: &apiv1.HostPathVolumeSource{
					Path: config.HostDir,
				},
			},
		},
	}
	jobContainer.VolumeMounts = []apiv1.VolumeMount{{
		Name:      mountName,
		MountPath: config.MountDir},
	}

	// Make job query-able by some useful labels for admins.
	labels := map[string]string{
		common.NodeNameLabel: nodeName,
		PVLabel:              pv.Name,
		PVUuidLabel:          string(pv.UID),
	}

	// Annotate job with useful information that cannot be set as labels due to label name restrictions.
	annotations := map[string]string{
		DeviceAnnotation:    mountPath,
		StartTimeAnnotation: time.Now().Format(time.RFC3339Nano),
	}

	podTemplate := apiv1.Pod{}
	podTemplate.Spec = apiv1.PodSpec{
		Containers:   []apiv1.Container{jobContainer},
		Volumes:      volumes,
		NodeSelector: map[string]string{common.NodeNameLabel: nodeName},
	}
	podTemplate.ObjectMeta = meta_v1.ObjectMeta{
		Name:        generateCleaningJobName(pv.Name),
		Namespace:   namespace,
		Labels:      labels,
		Annotations: annotations,
	}
	job := &batch_v1.Job{}
	job.ObjectMeta = podTemplate.ObjectMeta
	job.Spec.Template.Spec = podTemplate.Spec
	job.Spec.Template.Spec.RestartPolicy = apiv1.RestartPolicyOnFailure

	return job, nil
}
1095808
func IsErrUnknownMethod(err error) bool {
	return err != nil && strings.Contains(err.Error(), errUnknownMethod)
}
1088507
func (s *Service) SheduleJob(handlerFunc interface{}, priority int, time time.Time, data ...interface{}) (*jobs.Job, error) {
	if jobsPerName, ok := jobsPerService[s.Name]; ok {
		if jobType, ok := jobsPerName[s.getShortFuncPath(handlerFunc)]; ok {
			return jobType.Schedule(priority, time, data...)
		}
		panic("SheduleJob: Job type not found")
	}
	panic("SheduleJob: Service pool not found")
}
987944
func (p *ReadOnlySchedulerClient) PopulateJobConfig(ctx context.Context, description *JobConfiguration) (r *Response, err error) {
  var _args68 ReadOnlySchedulerPopulateJobConfigArgs
  _args68.Description = description
  var _result69 ReadOnlySchedulerPopulateJobConfigResult
  if err = p.Client_().Call(ctx, "populateJobConfig", &_args68, &_result69); err != nil {
    return
  }
  return _result69.GetSuccess(), nil
}
1289406
func runJob(job *Job, ctxType reflect.Type, middleware []*middlewareHandler, jt *jobType) (returnCtx reflect.Value, returnError error) {
	returnCtx = reflect.New(ctxType)
	currentMiddleware := 0
	maxMiddleware := len(middleware)

	var next NextMiddlewareFunc
	next = func() error {
		if currentMiddleware < maxMiddleware {
			mw := middleware[currentMiddleware]
			currentMiddleware++
			if mw.IsGeneric {
				return mw.GenericMiddlewareHandler(job, next)
			}
			res := mw.DynamicMiddleware.Call([]reflect.Value{returnCtx, reflect.ValueOf(job), reflect.ValueOf(next)})
			x := res[0].Interface()
			if x == nil {
				return nil
			}
			return x.(error)
		}
		if jt.IsGeneric {
			return jt.GenericHandler(job)
		}
		res := jt.DynamicHandler.Call([]reflect.Value{returnCtx, reflect.ValueOf(job)})
		x := res[0].Interface()
		if x == nil {
			return nil
		}
		return x.(error)
	}

	defer func() {
		if panicErr := recover(); panicErr != nil {
			// err turns out to be interface{}, of actual type "runtime.errorCString"
			// Luckily, the err sprints nicely via fmt.
			errorishError := fmt.Errorf("%v", panicErr)
			logError("runJob.panic", errorishError)
			returnError = errorishError
		}
	}()

	returnError = next()

	return
}
260826
func (j *Jenkins) BuildJob(name string, options ...interface{}) (int64, error) {
	job := Job{Jenkins: j, Raw: new(JobResponse), Base: "/job/" + name}
	var params map[string]string
	if len(options) > 0 {
		params, _ = options[0].(map[string]string)
	}
	return job.InvokeSimple(params)
}
126215
func checkJobReadiness(obj runtime.Object) (bool, bool, error) {
	var (
		hasCompletionTime bool
		isJobFailed       bool
	)
	switch j := obj.(type) {
	case *batchv1.Job:
		hasCompletionTime = j.Status.CompletionTime != nil
		isJobFailed = j.Status.Failed > 0
	default:
		return false, false, fmt.Errorf("unsupported job version: %T", j)
	}
	return hasCompletionTime, isJobFailed, nil
}
639166
func (c *Controller) enqueueJob(obj interface{}) {
	var key string
	var err error
	if key, err = getCacheKey(obj); err != nil {
		return
	}
	c.releaseWorkqueue.AddRateLimited(key)
}
150972
func (n *nomadFSM) handleJobDeregister(index uint64, jobID, namespace string, purge bool, tx state.Txn) error {
	// If it is periodic remove it from the dispatcher
	if err := n.periodicDispatcher.Remove(namespace, jobID); err != nil {
		n.logger.Error("periodicDispatcher.Remove failed", "error", err)
		return err
	}

	if purge {
		if err := n.state.DeleteJobTxn(index, namespace, jobID, tx); err != nil {
			n.logger.Error("DeleteJob failed", "error", err)
			return err
		}

		// We always delete from the periodic launch table because it is possible that
		// the job was updated to be non-periodic, thus checking if it is periodic
		// doesn't ensure we clean it up properly.
		n.state.DeletePeriodicLaunchTxn(index, namespace, jobID, tx)
	} else {
		// Get the current job and mark it as stopped and re-insert it.
		ws := memdb.NewWatchSet()
		current, err := n.state.JobByIDTxn(ws, namespace, jobID, tx)
		if err != nil {
			n.logger.Error("JobByID lookup failed", "error", err)
			return err
		}

		if current == nil {
			return fmt.Errorf("job %q in namespace %q doesn't exist to be deregistered", jobID, namespace)
		}

		stopped := current.Copy()
		stopped.Stop = true

		if err := n.state.UpsertJobTxn(index, stopped, tx); err != nil {
			n.logger.Error("UpsertJob failed", "error", err)
			return err
		}
	}

	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)
	}
}