// Tasks returns a combination of instances from the wrapped scheduler, as
// well as instances from attached runs.
969639
func (s *AttachedScheduler) Tasks(ctx context.Context, app string) ([]*twelvefactor.Task, error) {
	if !s.ShowAttached {
		return s.Scheduler.Tasks(ctx, app)
	}

	type instancesResult struct {
		instances []*twelvefactor.Task
		err       error
	}

	ch := make(chan instancesResult, 1)
	go func() {
		attachedInstances, err := s.dockerScheduler.InstancesFromAttachedRuns(ctx, app)
		ch <- instancesResult{attachedInstances, err}
	}()

	instances, err := s.Scheduler.Tasks(ctx, app)
	if err != nil {
		return instances, err
	}

	result := <-ch
	if err := result.err; err != nil {
		return instances, err
	}

	return append(instances, result.instances...), nil
}
756949
func (t TasksByTimestamp) Swap(i, j int) {
	t[i], t[j] = t[j], t[i]
}
675530
func (j *Job) CombinedTaskMeta(groupName, taskName string) map[string]string {
	group := j.LookupTaskGroup(groupName)
	if group == nil {
		return nil
	}

	task := group.LookupTask(taskName)
	if task == nil {
		return nil
	}

	meta := helper.CopyMapStringString(task.Meta)
	if meta == nil {
		meta = make(map[string]string, len(group.Meta)+len(j.Meta))
	}

	// Add the group specific meta
	for k, v := range group.Meta {
		if _, ok := meta[k]; !ok {
			meta[k] = v
		}
	}

	// Add the job specific meta
	for k, v := range j.Meta {
		if _, ok := meta[k]; !ok {
			meta[k] = v
		}
	}

	return meta
}
292809
func TaskEnqueue(
	ctx types.Context,
	run types.TaskRunFunc,
	schema []byte) *types.Task {
	return getTaskService(ctx).TaskEnqueue(ctx, run, schema)
}
760856
func (c oauthClient) Tasks() ([]wl.Task, error) {
	lists, err := c.Lists()
	if err != nil {
		return nil, err
	}

	listCount := len(lists)
	c.logger.Debug(
		"tasks",
		map[string]interface{}{"listCount": listCount},
	)

	tasksChan := make(chan []wl.Task, listCount)
	idErrChan := make(chan idErr, listCount)
	for _, l := range lists {
		go func(list wl.List) {
			c.logger.Debug(
				"tasks - getting tasks for list",
				map[string]interface{}{"listID": list.ID},
			)
			tasks, err := c.TasksForListID(list.ID)
			idErrChan <- idErr{idType: "list", id: list.ID, err: err}
			tasksChan <- tasks
		}(l)
	}

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

	totalTasks := []wl.Task{}
	for i := 0; i < listCount; i++ {
		tasks := <-tasksChan
		totalTasks = append(totalTasks, tasks...)
	}

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

	return totalTasks, nil
}
1164145
func (ar *AgentReconciler) calculateTasksForUnits(dState *AgentState, cState unitStates) []task {
	jobs := pkg.NewUnsafeSet()
	for cName := range cState {
		jobs.Add(cName)
	}

	for dName := range dState.Units {
		jobs.Add(dName)
	}

	sorted := sort.StringSlice(jobs.Values())
	sorted.Sort()

	var tasks []task
	for _, name := range sorted {
		tasks = append(tasks, ar.calculateTasksForUnit(dState, cState, name)...)
	}

	if len(tasks) == 0 {
		return nil
	}

	reloadTask := task{typ: taskTypeReloadUnitFiles, reason: taskReasonAlwaysReloadUnitFiles}
	tasks = append(tasks, reloadTask)

	sort.Sort(sortableTasks(tasks))

	// reload unnecessary if no UnloadUnit/LoadUnit tasks
	if tasks[0].typ == taskTypeReloadUnitFiles {
		tasks = tasks[1:]
	}

	return tasks
}
1335507
func (r *TasksService) List() *TasksListCall {
	c := &TasksListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
	return c
}
885076
func (client *Client) DescribeScheduledTasks(args *DescribeScheduledTasksArgs) (tasks []ScheduledTaskItemType, pagination *common.PaginationResult, err error) {
	args.Validate()
	response := DescribeScheduledTasksResponse{}

	err = client.InvokeByFlattenMethod("DescribeScheduledTasks", args, &response)

	if err == nil {
		return response.ScheduledTasks.ScheduledTask, &response.PaginationResult, nil
	}

	return nil, nil, err
}
806422
func (_m *Marathon) AllTasks(opts *marathon.AllTasksOpts) (*marathon.Tasks, error) {
	ret := _m.Called(opts)

	var r0 *marathon.Tasks
	if rf, ok := ret.Get(0).(func(*marathon.AllTasksOpts) *marathon.Tasks); ok {
		r0 = rf(opts)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*marathon.Tasks)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*marathon.AllTasksOpts) error); ok {
		r1 = rf(opts)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
81988
func (e *executor) RunTasks(taskMap map[string]Task) error {
	dependencies := FindTaskDependencies(taskMap)

	taskStates := make(map[string]*taskState)

	for k, task := range taskMap {
		ts := &taskState{
			key:  k,
			task: task,
		}
		taskStates[k] = ts
	}

	for k, ts := range taskStates {
		for _, dep := range dependencies[k] {
			d := taskStates[dep]
			if d == nil {
				glog.Fatalf("did not find task state for dependency: %q", k)
			}
			ts.dependencies = append(ts.dependencies, d)
		}
	}

	for {
		var canRun []*taskState
		doneCount := 0
		for _, ts := range taskStates {
			if ts.done {
				doneCount++
				continue
			}
			ready := true
			for _, dep := range ts.dependencies {
				if !dep.done {
					ready = false
					break
				}
			}
			if ready {
				if ts.deadline.IsZero() {
					ts.deadline = time.Now().Add(e.options.MaxTaskDuration)
				} else if time.Now().After(ts.deadline) {
					return fmt.Errorf("deadline exceeded executing task %v. Example error: %v", ts.key, ts.lastError)
				}
				canRun = append(canRun, ts)
			}
		}

		glog.Infof("Tasks: %d done / %d total; %d can run", doneCount, len(taskStates), len(canRun))
		if len(canRun) == 0 {
			break
		}

		progress := false

		var tasks []*taskState
		for _, ts := range canRun {
			tasks = append(tasks, ts)
		}

		taskErrors := e.forkJoin(tasks)
		var errors []error
		for i, err := range taskErrors {
			ts := tasks[i]
			if err != nil {
				//  print warning message and continue like the task succeeded
				if _, ok := err.(*ExistsAndWarnIfChangesError); ok {
					glog.Warningf(err.Error())
					ts.done = true
					ts.lastError = nil
					progress = true
					continue
				}

				remaining := time.Second * time.Duration(int(ts.deadline.Sub(time.Now()).Seconds()))
				glog.Warningf("error running task %q (%v remaining to succeed): %v", ts.key, remaining, err)
				errors = append(errors, err)
				ts.lastError = err
			} else {
				ts.done = true
				ts.lastError = nil
				progress = true
			}
		}

		if !progress {
			if len(errors) == 0 {
				// Logic error!
				panic("did not make progress executing tasks; but no errors reported")
			}
			glog.Infof("No progress made, sleeping before retrying %d failed task(s)", len(errors))
			time.Sleep(e.options.WaitAfterAllTasksFailed)
		}
	}

	// Raise error if not all tasks done - this means they depended on each other
	var notDone []string
	for _, ts := range taskStates {
		if !ts.done {
			notDone = append(notDone, ts.key)
		}
	}
	if len(notDone) != 0 {
		return fmt.Errorf("Unable to execute tasks (circular dependency): %s", strings.Join(notDone, ", "))
	}

	return nil
}
677464
func ReflectTaskResults(taskResults []*TaskResult) ([]reflect.Value, error) {
	resultValues := make([]reflect.Value, len(taskResults))
	for i, taskResult := range taskResults {
		resultValue, err := ReflectValue(taskResult.Type, taskResult.Value)
		if err != nil {
			return nil, err
		}
		resultValues[i] = resultValue
	}
	return resultValues, nil
}
978480
func (r *marathonClient) Tasks(id string) (*Tasks, error) {
	tasks := new(Tasks)
	if err := r.apiGet(fmt.Sprintf("%s/%s/tasks", marathonAPIApps, trimRootPath(id)), nil, tasks); err != nil {
		return nil, err
	}

	return tasks, nil
}
445066
func (actor Actor) RunTask(appGUID string, task Task) (Task, Warnings, error) {
	createdTask, warnings, err := actor.CloudControllerClient.CreateApplicationTask(appGUID, ccv3.Task(task))
	if err != nil {
		if e, ok := err.(ccerror.TaskWorkersUnavailableError); ok {
			return Task{}, Warnings(warnings), actionerror.TaskWorkersUnavailableError{Message: e.Error()}
		}
	}

	return Task(createdTask), Warnings(warnings), err
}
1296346
func TaskTrack(ctx types.Context) *types.Task {
	return getTaskService(ctx).TaskTrack(ctx)
}
1196312
func (s *TasksListService) Actions(actions ...string) *TasksListService {
	s.actions = append(s.actions, actions...)
	return s
}
490065
func Task(t *api.Task) string {
	if t.Annotations.Name != "" {
		// if set, use the container Annotations.Name field, set in the orchestrator.
		return t.Annotations.Name
	}

	slot := fmt.Sprint(t.Slot)
	if slot == "" || t.Slot == 0 {
		// when no slot id is assigned, we assume that this is node-bound task.
		slot = t.NodeID
	}

	// fallback to service.instance.id.
	return fmt.Sprintf("%s.%s.%s", t.ServiceAnnotations.Name, slot, t.ID)
}
387842
func (w *DefaultWorker) Start() (<-chan *Task, <-chan error) {
	w.smu.Lock()
	defer w.smu.Unlock()

	w.state = open
	w.lifecycle.SetQueues(w.availableTasks, w.workingTasks)
	w.janitorRunner = newJanitorRunner(w.pool, w.detector, w.janitor, w.availableTasks)

	errs1 := w.janitorRunner.Start()
	tasks, errs2 := w.lifecycle.Listen()

	return tasks, concatErrs(errs1, errs2)
}