// claimExistingTasks is called on startup to claim all tasks in the store.
322121
func (c *Coordinator) claimExistingTasks() {
	tasks, _, err := c.TaskService.FindTasks(context.Background(), platform.TaskFilter{})
	if err != nil {
		return
	}
	newLatestCompleted := time.Now().UTC().Format(time.RFC3339)
	for len(tasks) > 0 {
		for _, task := range tasks {

			task, err := c.TaskService.UpdateTask(context.Background(), task.ID, platform.TaskUpdate{LatestCompleted: &newLatestCompleted})
			if err != nil {
				c.logger.Error("failed to set latestCompleted", zap.Error(err))
			}

			if task.Status != string(backend.TaskActive) {
				// Don't claim inactive tasks at startup.
				continue
			}

			// I may need a context with an auth here
			if err := c.sch.ClaimTask(context.Background(), task); err != nil {
				c.logger.Error("failed claim task", zap.Error(err))
				continue
			}
		}
		tasks, _, err = c.TaskService.FindTasks(context.Background(), platform.TaskFilter{
			After: &tasks[len(tasks)-1].ID,
		})
		if err != nil {
			c.logger.Error("failed list additional tasks", zap.Error(err))
			return
		}
	}
}
728921
func (s *leaseStore) ClaimLease(key lease.Key, req lease.Request, _ <-chan struct{}) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	if _, found := s.entries[key]; found {
		return lease.ErrInvalid
	}
	s.entries[key] = &entry{
		holder:   req.Holder,
		start:    s.clock.Now(),
		duration: req.Duration,
	}
	s.target.Claimed(key, req.Holder)
	return nil
}
352067
func RunningTasksCount(client client.ServiceAPIClient, serviceID string, instances uint64) func(log poll.LogT) poll.Result {
	return func(log poll.LogT) poll.Result {
		filter := filters.NewArgs()
		filter.Add("service", serviceID)
		tasks, err := client.TaskList(context.Background(), types.TaskListOptions{
			Filters: filter,
		})
		var running int
		var taskError string
		for _, task := range tasks {
			switch task.Status.State {
			case swarmtypes.TaskStateRunning:
				running++
			case swarmtypes.TaskStateFailed:
				if task.Status.Err != "" {
					taskError = task.Status.Err
				}
			}
		}

		switch {
		case err != nil:
			return poll.Error(err)
		case running > int(instances):
			return poll.Continue("waiting for tasks to terminate")
		case running < int(instances) && taskError != "":
			return poll.Continue("waiting for tasks to enter run state. task failed with error: %s", taskError)
		case running == int(instances):
			return poll.Success()
		default:
			return poll.Continue("running task count at %d waiting for %d (total tasks: %d)", running, instances, len(tasks))
		}
	}
}
1028681
func ValidateTask(resources *api.Resources) error {
	for _, v := range resources.Generic {
		if v.GetDiscreteResourceSpec() != nil {
			continue
		}

		return fmt.Errorf("invalid argument for resource %s", Kind(v))
	}

	return nil
}
286722
func invokeFind(e Task, c *Context) (Task, error) {
	rv, err := reflectutils.InvokeMethod(e, "Find", c)
	if err != nil {
		return nil, err
	}
	var task Task
	if !rv[0].IsNil() {
		task = rv[0].Interface().(Task)
	}
	if !rv[1].IsNil() {
		err = rv[1].Interface().(error)
	}
	return task, err
}
970644
func (c *BundlingChecker) PresumeExists(item *Item) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.existingDigests[string(item.Digest)] = struct{}{}
}
767101
func GetRunningTasks(t *testing.T, c client.ServiceAPIClient, serviceID string) []swarmtypes.Task {
	t.Helper()

	tasks, err := c.TaskList(context.Background(), types.TaskListOptions{
		Filters: filters.NewArgs(
			filters.Arg("service", serviceID),
			filters.Arg("desired-state", "running"),
		),
	})

	assert.NilError(t, err)
	return tasks
}
655082
func (l *DefaultLifecycle) addTask(t *Task) {
	l.rmu.Lock()
	defer l.rmu.Unlock()

	l.registry = append([]*Task{t}, l.registry...)
	l.wg.Add(1)
}
472193
func reqProcessingTask(c *asyncConnHdl, ctl workerCtl) (ic *interrupt_code, ts *taskStatus) {

	var err error
	var errmsg string

	bytecnt := 0
	blen := 0
	bufsize := c.spec().wBufSize
	var sig interrupt_code

	select {
	case req := <-c.pendingReqs:
		blen, err := c.processAsyncRequest(req)
		if err != nil {
			errmsg = fmt.Sprintf("processAsyncRequest error in initial phase")
			goto proc_error
		}
		bytecnt += blen
	case sig := <-ctl:
		return &sig, &ok_status
	}

	for bytecnt < bufsize {
		select {
		case req := <-c.pendingReqs:
			blen, err = c.processAsyncRequest(req)
			if err != nil {
				errmsg = fmt.Sprintf("processAsyncRequest error in batch phase")
				goto proc_error
			}
			if blen > 0 {
				bytecnt += blen
			} else {
				bytecnt = 0
			}

		case sig = <-ctl:
			ic = &sig
			goto done

		default:
			goto done
		}
	}

done:
	c.writer.Flush()
	return ic, &ok_status

proc_error:
	log.Println(errmsg, err)
	return nil, &taskStatus{snderr, err}
}
266897
func (s *Server) RemoveTask(ctx context.Context, request *api.RemoveTaskRequest) (*api.RemoveTaskResponse, error) {
	if request.TaskID == "" {
		return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
	}

	err := s.store.Update(func(tx store.Tx) error {
		return store.DeleteTask(tx, request.TaskID)
	})
	if err != nil {
		if err == store.ErrNotExist {
			return nil, status.Errorf(codes.NotFound, "task %s not found", request.TaskID)
		}
		return nil, err
	}
	return &api.RemoveTaskResponse{}, nil
}
922696
func successTask(id string, cacheable Cacheable) task {
	return func(c *cache) error {
		// Check for discarded Cacheable first.
		if c.buckets[id] == nil {
			return nil
		}
		// Set bucket values.
		b := c.buckets[id]
		b.cacheable = cacheable
		b.status = statusLoaded
		b.loaded = time.Now()
		b.lastUsed = b.loaded
		// Notify all waiters.
		for _, waiter := range c.buckets[id].waiters {
			waiter <- func() (Cacheable, error) {
				return cacheable, nil
			}
		}
		b.waiters = nil
		return nil
	}
}
897846
func (client *Client) GetApplicationTasks(appGUID string, query ...Query) ([]Task, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetApplicationTasksRequest,
		URIParams: internal.Params{
			"app_guid": appGUID,
		},
		Query: query,
	})
	if err != nil {
		return nil, nil, err
	}

	var fullTasksList []Task
	warnings, err := client.paginate(request, Task{}, func(item interface{}) error {
		if task, ok := item.(Task); ok {
			fullTasksList = append(fullTasksList, task)
		} else {
			return ccerror.UnknownObjectInListError{
				Expected:   Task{},
				Unexpected: item,
			}
		}
		return nil
	})

	return fullTasksList, warnings, err
}
900112
func (server *Server) GetRegisteredTask(name string) (interface{}, error) {
	taskFunc, ok := server.registeredTasks[name]
	if !ok {
		return nil, fmt.Errorf("Task not registered error: %s", name)
	}
	return taskFunc, nil
}
213984
func (s *Server) verifyAccountClaims(claimJWT string) (*jwt.AccountClaims, string, error) {
	if accClaims, err := jwt.DecodeAccountClaims(claimJWT); err != nil {
		return nil, _EMPTY_, err
	} else {
		vr := jwt.CreateValidationResults()
		accClaims.Validate(vr)
		if vr.IsBlocking(true) {
			return nil, _EMPTY_, ErrAccountValidation
		}
		return accClaims, claimJWT, nil
	}
}
754805
func (l lazyLeaseClaimer) Claim(leaseName, holderName string, duration time.Duration) error {
	claimer, err := l.leaseClaimer()
	if err != nil {
		return errors.Trace(err)
	}
	return claimer.Claim(leaseName, holderName, duration)
}
1089217
func NewRetryTaskState(signature *Signature) *TaskState {
	return &TaskState{
		TaskUUID: signature.UUID,
		State:    StateRetry,
	}
}
717251
func (c oauthClient) UpdateTask(task wl.Task) (wl.Task, error) {
	err := c.validateRecurrence(task.RecurrenceType, task.RecurrenceCount)
	if err != nil {
		return wl.Task{}, err
	}

	origTask, err := c.Task(task.ID)
	if err != nil {
		return wl.Task{}, err
	}

	tuc := TaskUpdateConfig{
		Title:     task.Title,
		Revision:  task.Revision,
		Completed: task.Completed,
		Starred:   task.Starred,
		ListID:    task.ListID,

		Remove: []string{},
	}

	if origTask.AssigneeID == task.AssigneeID {
		tuc.AssigneeID = origTask.AssigneeID
	} else {
		if task.AssigneeID == 0 {
			tuc.Remove = append(tuc.Remove, "assignee_id")
		} else {
			tuc.AssigneeID = task.AssigneeID
		}
	}

	if origTask.DueDate == task.DueDate {
		tuc.DueDate = dueDateToString(origTask.DueDate)
	} else {
		if task.DueDate.IsZero() {
			tuc.Remove = append(tuc.Remove, "due_date")
		} else {
			tuc.DueDate = dueDateToString(task.DueDate)
		}
	}

	if origTask.RecurrenceCount == task.RecurrenceCount &&
		origTask.RecurrenceType == task.RecurrenceType {
		tuc.RecurrenceCount = origTask.RecurrenceCount
		tuc.RecurrenceType = origTask.RecurrenceType
	} else {
		if task.RecurrenceCount == 0 {
			tuc.Remove = append(tuc.Remove, "recurrence_type")
			tuc.Remove = append(tuc.Remove, "recurrence_count")
		} else {
			tuc.RecurrenceCount = task.RecurrenceCount
			tuc.RecurrenceType = task.RecurrenceType
		}
	}

	body, err := json.Marshal(tuc)
	if err != nil {
		return wl.Task{}, err
	}

	url := fmt.Sprintf(
		"%s/tasks/%d",
		c.apiURL,
		task.ID,
	)

	req, err := c.newPatchRequest(url, body)
	if err != nil {
		return wl.Task{}, err
	}

	resp, err := c.do(req)
	if err != nil {
		return wl.Task{}, err
	}

	if resp.StatusCode != http.StatusOK {
		return wl.Task{}, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusOK)
	}

	transport := transportTask{}
	err = json.NewDecoder(resp.Body).Decode(&transport)
	if err != nil {
		return wl.Task{}, err
	}
	return taskFromTransport(transport)
}