// DestroyTask removes the task from the driver's in memory state. The task
// cannot be running unless force is set to true. If force is set to true the
// driver will forcefully terminate the task before removing it.
348231
func (d *driverPluginClient) DestroyTask(taskID string, force bool) error {
	req := &proto.DestroyTaskRequest{
		TaskId: taskID,
		Force:  force,
	}

	_, err := d.client.DestroyTask(d.doneCtx, req)
	return grpcutils.HandleGrpcErr(err, d.doneCtx)
}
52105
func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error {
	cfg := ctl.Task().(*messages.GitilesTask)
	ctl.DebugLog("Repo: %s, Refs: %s", cfg.Repo, cfg.Refs)

	g, err := m.getGitilesClient(c, ctl, cfg)
	if err != nil {
		return err
	}
	refs, err := m.fetchRefsState(c, ctl, cfg, g)
	if err != nil {
		ctl.DebugLog("Error fetching state of the world: %s", err)
		return err
	}

	refs.pruneKnown(ctl)
	leftToProcess, err := m.emitTriggersRefAtATime(c, ctl, g, cfg, refs)

	if err != nil {
		switch {
		case leftToProcess == 0:
			panic(err) // leftToProcess must include the one processing of which failed.
		case refs.changed > 0:
			// Even though we hit error, we had progress. So, ignore error as transient.
			ctl.DebugLog("ignoring error %s as transient", err)
		default:
			ctl.DebugLog("no progress made due to %s", err)
			return err
		}
	}

	switch {
	case leftToProcess > 0 && refs.changed == 0:
		panic(errors.New("no progress with no errors must not happen"))
	case refs.changed == 0:
		ctl.DebugLog("No changes detected")
		ctl.State().Status = task.StatusSucceeded
		return nil
	case leftToProcess > 0:
		ctl.DebugLog("%d changed refs processed, %d refs not yet examined", refs.changed, leftToProcess)
	default:
		ctl.DebugLog("All %d changed refs processed", refs.changed)
	}
	// Force save to ensure triggers are actually emitted.
	if err := ctl.Save(c); err != nil {
		// At this point, triggers have not been sent, so bail now and don't save
		// the refs' heads newest values.
		return err
	}
	if err := saveState(c, ctl.JobID(), cfg.Repo, refs.known); err != nil {
		return err
	}
	ctl.DebugLog("Saved %d known refs", len(refs.known))
	ctl.State().Status = task.StatusSucceeded
	return nil
}
155906
func (l *DefaultLifecycle) removeTask(task *Task) (err error) {
	l.rmu.Lock()
	defer l.rmu.Unlock()
	cnx := l.pool.Get()
	defer cnx.Close()

	i := l.findTaskIndex(task)
	if i == -1 {
		return ErrNotFound
	}

	count := len(l.registry)
	l.registry = append(l.registry[:i], l.registry[i+1:]...)

	// We set the item relative to the end position of the list. Since the
	// queue is running BRPOPLPUSH, the index relative to the start of the
	// list (left side) might change in the meantime.
	_, err = cnx.Do("LSET", l.workingTasks.Dest(), i-count, deleteToken)
	if err != nil {
		return
	}

	// Ignore errors from trimming. If this fails, it's unfortunate, but the
	// task was still removed successfully. The next LTRIM will remove the
	// item or, if not, we'll just ignore it if we read it from the queue.
	cnx.Do("LREM", l.workingTasks.Dest(), 0, deleteToken)

	l.wg.Done()
	return nil
}
1024544
func PutTask(tx *bolt.Tx, task *api.Task) error {
	return withCreateTaskBucketIfNotExists(tx, task.ID, func(bkt *bolt.Bucket) error {
		taskCopy := *task
		taskCopy.Status = api.TaskStatus{} // blank out the status.

		p, err := proto.Marshal(&taskCopy)
		if err != nil {
			return err
		}
		return bkt.Put(bucketKeyData, p)
	})
}
570784
func (tr *TaskRunner) handleKill() *drivers.ExitResult {
	// Run the pre killing hooks
	tr.preKill()

	// Tell the restart tracker that the task has been killed so it doesn't
	// attempt to restart it.
	tr.restartTracker.SetKilled()

	// Check it is running
	handle := tr.getDriverHandle()
	if handle == nil {
		return nil
	}

	// Kill the task using an exponential backoff in-case of failures.
	killErr := tr.killTask(handle)
	if killErr != nil {
		// We couldn't successfully destroy the resource created.
		tr.logger.Error("failed to kill task. Resources may have been leaked", "error", killErr)
		tr.setKillErr(killErr)
	}

	// Block until task has exited.
	waitCh, err := handle.WaitCh(tr.shutdownCtx)

	// The error should be nil or TaskNotFound, if it's something else then a
	// failure in the driver or transport layer occurred
	if err != nil {
		if err == drivers.ErrTaskNotFound {
			return nil
		}
		tr.logger.Error("failed to wait on task. Resources may have been leaked", "error", err)
		tr.setKillErr(killErr)
		return nil
	}

	select {
	case result := <-waitCh:
		return result
	case <-tr.shutdownCtx.Done():
		return nil
	}
}
680991
func (r *marathonClient) KillTask(taskID string, opts *KillTaskOpts) (*Task, error) {
	appName := taskID[0:strings.LastIndex(taskID, ".")]
	appName = strings.Replace(appName, "_", "/", -1)
	taskID = strings.Replace(taskID, "/", "_", -1)

	path := fmt.Sprintf("%s/%s/tasks/%s", marathonAPIApps, appName, taskID)
	path, err := addOptions(path, opts)
	if err != nil {
		return nil, err
	}

	wrappedTask := new(struct {
		Task Task `json:"task"`
	})

	if err := r.apiDelete(path, nil, wrappedTask); err != nil {
		return nil, err
	}

	return &wrappedTask.Task, nil
}
314619
func (c *Context) Destroy() error {
	c.debug("removing work directory: %v", c.workdir)
	return os.RemoveAll(c.workdir)
}
802788
func (f *PluginFilter) SetTask(t *api.Task) bool {
	c := t.Spec.GetContainer()

	var volumeTemplates bool
	if c != nil {
		for _, mount := range c.Mounts {
			if referencesVolumePlugin(mount) {
				volumeTemplates = true
				break
			}
		}
	}

	if (c != nil && volumeTemplates) || len(t.Networks) > 0 || t.Spec.LogDriver != nil {
		f.t = t
		return true
	}

	return false
}
212636
func (c oauthClient) DeleteAllTasks() error {
	tasks, err := c.Tasks()
	if err != nil {
		return err
	}

	taskCount := len(tasks)
	c.logger.Debug(
		"delete-all-tasks",
		map[string]interface{}{"taskCount": taskCount},
	)

	idErrChan := make(chan idErr, taskCount)
	for _, f := range tasks {
		go func(task wl.Task) {
			c.logger.Debug(
				"delete-all-tasks - deleting task",
				map[string]interface{}{"taskID": task.ID},
			)
			err := c.DeleteTask(task)
			idErrChan <- idErr{idType: "task", id: task.ID, err: err}
		}(f)
	}

	e := multiIDErr{}
	for i := 0; i < taskCount; i++ {
		idErr := <-idErrChan
		if idErr.err != nil {
			c.logger.Debug(
				"delete-all-tasks - error received",
				map[string]interface{}{"id": idErr.id, "err": err},
			)
			e.addError(idErr)
		}
	}

	if len(e.errors()) > 0 {
		return e
	}

	return nil
}
980404
func (f *HostPortFilter) SetTask(t *api.Task) bool {
	if t.Endpoint != nil {
		for _, port := range t.Endpoint.Ports {
			if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 {
				f.t = t
				return true
			}
		}
	}

	return false
}
678713
func (tr *TaskRunner) handleTaskExitResult(result *drivers.ExitResult) (retryWait bool) {
	if result == nil {
		return false
	}

	if result.Err == bstructs.ErrPluginShutdown {
		dn := tr.Task().Driver
		tr.logger.Debug("driver plugin has shutdown; attempting to recover task", "driver", dn)

		// Initialize a new driver handle
		if err := tr.initDriver(); err != nil {
			tr.logger.Error("failed to initialize driver after it exited unexpectedly", "error", err, "driver", dn)
			return false
		}

		// Try to restore the handle
		tr.stateLock.RLock()
		h := tr.localState.TaskHandle
		net := tr.localState.DriverNetwork
		tr.stateLock.RUnlock()
		if !tr.restoreHandle(h, net) {
			tr.logger.Error("failed to restore handle on driver after it exited unexpectedly", "driver", dn)
			return false
		}

		tr.logger.Debug("task successfully recovered on driver", "driver", dn)
		return true
	}

	// Emit Terminated event
	tr.emitExitResultEvent(result)

	return false
}
776622
func discardTask(id string, responsec responder) task {
	return func(c *cache) error {
		bucket, ok := c.buckets[id]
		if !ok {
			// Not found, so nothing to discard.
			responsec <- func() (Cacheable, error) {
				return nil, nil
			}
			return nil
		}
		// Discard Cacheable, notify possible waiters,
		// delete bucket, and notify caller.
		var err error
		if bucket.cacheable != nil {
			err = bucket.cacheable.Discard()
		}
		for _, waiter := range bucket.waiters {
			waiter <- func() (Cacheable, error) {
				return nil, errors.New(ErrDiscardedWhileLoading, errorMessages, id)
			}
		}
		delete(c.buckets, id)
		if err != nil {
			err = errors.Annotate(err, ErrDiscard, errorMessages, id)
		}
		responsec <- func() (Cacheable, error) {
			return nil, err
		}
		return nil
	}
}
189751
func (b *Builder) setTask(task *structs.Task) *Builder {
	b.taskName = task.Name
	b.envvars = make(map[string]string, len(task.Env))
	for k, v := range task.Env {
		b.envvars[k] = v
	}

	// COMPAT(0.11): Remove in 0.11
	if task.Resources == nil {
		b.memLimit = 0
		b.cpuLimit = 0
	} else {
		b.memLimit = int64(task.Resources.MemoryMB)
		b.cpuLimit = int64(task.Resources.CPU)
	}
	return b
}
540894
func (client *Client) DeleteScheduledTask(args *DeleteScheduledTaskArgs) (resp *DeleteScheduledTaskResponse, err error) {
	response := DeleteScheduledTaskResponse{}
	err = client.Invoke("DeleteScheduledTask", args, &response)

	if err != nil {
		return nil, err
	}
	return &response, nil
}
309820
func (s *SubmitContainerStateChangeInput) SetTask(v string) *SubmitContainerStateChangeInput {
	s.Task = &v
	return s
}
641374
func (_class DRTaskClass) Destroy(sessionID SessionRef, self DRTaskRef) (_err error) {
	_method := "DR_task.destroy"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertDRTaskRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_, _err =  _class.client.APICall(_method, _sessionIDArg, _selfArg)
	return
}
1209665
func (w *CeleryWorker) RunTask(message *TaskMessage) (*ResultMessage, error) {

	// get task
	task := w.GetTask(message.Task)
	if task == nil {
		return nil, fmt.Errorf("task %s is not registered", message.Task)
	}

	// convert to task interface
	taskInterface, ok := task.(CeleryTask)
	if ok {
		if err := taskInterface.ParseKwargs(message.Kwargs); err != nil {
			return nil, err
		}
		val, err := taskInterface.RunTask()
		if err != nil {
			return nil, err
		}
		return getResultMessage(val), err
	}

	// use reflection to execute function ptr
	taskFunc := reflect.ValueOf(task)
	return runTaskFunc(&taskFunc, message)
}