// discardTask returns the task for discarding a Cacheable.
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
	}
}
308896
func (d *Dispatcher) tqTask(task *Task) (*taskqueue.Task, string, error) {
	handler, err := d.handler(task.Payload)
	if err != nil {
		return nil, "", err
	}

	blob, err := serializePayload(task.Payload)
	if err != nil {
		return nil, "", err
	}

	title := handler.typeName
	if task.Title != "" {
		title = task.Title
	}

	retryOpts := handler.retryOpts
	if task.RetryOptions != nil {
		retryOpts = task.RetryOptions
	}

	return &taskqueue.Task{
		Path:         fmt.Sprintf("%s%s/%s", d.baseURL(), handler.queue, title),
		Name:         task.Name(),
		Method:       "POST",
		Payload:      blob,
		ETA:          task.ETA,
		Delay:        task.Delay,
		RetryOptions: retryOpts,
	}, handler.queue, nil
}
775507
func (w *CeleryWorker) GetTask(name string) interface{} {
	w.taskLock.RLock()
	task, ok := w.registeredTasks[name]
	if !ok {
		w.taskLock.RUnlock()
		return nil
	}
	w.taskLock.RUnlock()
	return task
}
227714
func (s *Service) DeleteTask(ctx context.Context, id influxdb.ID) error {
	err := s.kv.Update(ctx, func(tx Tx) error {
		err := s.deleteTask(ctx, tx, id)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return err
	}

	return nil
}
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)
}
207386
func (c *Client) Cleanup(removeall bool) (Task, error) {
	task := Task{}
	r := c.NewRequest("POST", "/cleanup")
	var requestBody struct {
		Config struct {
			RemoveAll bool `json:"remove_all"`
		} `json:"config"`
	}
	requestBody.Config.RemoveAll = removeall
	b, err := json.Marshal(&requestBody)
	if err != nil {
		return task, err
	}
	r.body = bytes.NewBuffer(b)
	r.header["Content-Type"] = "application/json"
	resp, err := c.DoRequest(r)
	if err != nil {
		return task, err
	}

	defer resp.Body.Close()

	resBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Printf("Error reading task request %v", resBody)
		return task, err
	}
	err = json.Unmarshal(resBody, &task)
	if err != nil {
		log.Printf("Error unmarshaling task %v", err)
	}
	return task, err
}
1263032
func (s *Store) DeleteTask(ctx context.Context, id platform.ID) (deleted bool, err error) {
	encodedID, err := id.Encode()
	if err != nil {
		return false, err
	}
	err = s.db.Batch(func(tx *bolt.Tx) error {
		b := tx.Bucket(s.bucket)
		if check := b.Bucket(tasksPath).Get(encodedID); check == nil {
			return backend.ErrTaskNotFound
		}
		if err := b.Bucket(taskMetaPath).Delete(encodedID); err != nil {
			return err
		}
		if err := b.Bucket(tasksPath).Delete(encodedID); err != nil {
			return err
		}
		user := b.Bucket(userByTaskID).Get(encodedID)
		if len(user) > 0 {
			if err := b.Bucket(usersPath).Bucket(user).Delete(encodedID); err != nil {
				return err
			}
		}
		if err := b.Bucket(userByTaskID).Delete(encodedID); err != nil {
			return err
		}
		if err := b.Bucket(nameByTaskID).Delete(encodedID); err != nil {
			return err
		}

		org := b.Bucket(orgByTaskID).Get(encodedID)
		if len(org) > 0 {
			if err := b.Bucket(orgsPath).Bucket(org).Delete(encodedID); err != nil {
				return err
			}
		}
		return b.Bucket(orgByTaskID).Delete(encodedID)
	})
	if err != nil {
		if err == backend.ErrTaskNotFound {
			return false, nil
		}
		return false, err
	}
	return true, nil
}
593610
func (s *Server) GetTask(ctx context.Context, request *api.GetTaskRequest) (*api.GetTaskResponse, error) {
	if request.TaskID == "" {
		return nil, status.Errorf(codes.InvalidArgument, errInvalidArgument.Error())
	}

	var task *api.Task
	s.store.View(func(tx store.ReadTx) {
		task = store.GetTask(tx, request.TaskID)
	})
	if task == nil {
		return nil, status.Errorf(codes.NotFound, "task %s not found", request.TaskID)
	}
	return &api.GetTaskResponse{
		Task: task,
	}, nil
}
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
}
1272054
func (b *Builder) UpdateTask(alloc *structs.Allocation, task *structs.Task) *Builder {
	b.mu.Lock()
	defer b.mu.Unlock()
	return b.setTask(task).setAlloc(alloc)
}
602652
func (mc *cache) Discard(ids []string) {
	mc.mu.Lock()
	defer mc.mu.Unlock()
	for _, id := range ids {
		if mr := mc.inQueue[id]; mr != nil {
			// The row is still in the queue somewhere. Mark
			// it as defunct. It will be "garbage collected" later.
			mr.defunct = true
		}
		delete(mc.inQueue, id)
		delete(mc.inFlight, id)
	}
}
155950
func (task *TCPListenerTask) StopFunc(perform func()) {
	task.LoopTask.StopFunc(func() {
		task.stop()
		perform()
	})
}
1287788
func (t TaskService) DeleteTask(ctx context.Context, id platform.ID) error {
	span, _ := tracing.StartSpanFromContext(ctx)
	defer span.Finish()

	u, err := newURL(t.Addr, taskIDPath(id))
	if err != nil {
		return err
	}

	req, err := http.NewRequest("DELETE", u.String(), nil)
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json")
	SetToken(t.Token, req)
	tracing.InjectToHTTPRequest(span, req)

	hc := newClient(u.Scheme, t.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	return CheckErrorStatus(http.StatusNoContent, resp)
}
1327045
func (*NewGoroutineDispatcher) DispatchTask(task *swf.PollForActivityTaskOutput, handler func(*swf.PollForActivityTaskOutput)) {
	go handler(task)
}
1246371
func (server *Server) RegisterTask(name string, taskFunc interface{}) error {
	if err := tasks.ValidateTask(taskFunc); err != nil {
		return err
	}
	server.registeredTasks[name] = taskFunc
	server.broker.SetRegisteredTaskNames(server.GetRegisteredTaskNames())
	return nil
}
616186
func (tr *TaskRunner) killTask(handle *DriverHandle) error {
	// Cap the number of times we attempt to kill the task.
	var err error
	for i := 0; i < killFailureLimit; i++ {
		if err = handle.Kill(); err != nil {
			if err == drivers.ErrTaskNotFound {
				tr.logger.Warn("couldn't find task to kill", "task_id", handle.ID())
				return nil
			}
			// Calculate the new backoff
			backoff := (1 << (2 * uint64(i))) * killBackoffBaseline
			if backoff > killBackoffLimit {
				backoff = killBackoffLimit
			}

			tr.logger.Error("failed to kill task", "backoff", backoff, "error", err)
			time.Sleep(backoff)
		} else {
			// Kill was successful
			return nil
		}
	}
	return err
}
874924
func clearTask(responsec responder) task {
	return func(c *cache) error {
		var errs []error
		for id, bucket := range c.buckets {
			switch bucket.status {
			case statusLoading:
				for _, waiter := range bucket.waiters {
					waiter <- func() (Cacheable, error) {
						return nil, errors.New(ErrDiscardedWhileLoading, errorMessages, id)
					}
				}
			case statusLoaded:
				if err := bucket.cacheable.Discard(); err != nil {
					errs = append(errs, err)
				}
			}
		}
		c.buckets = make(map[string]*bucket)
		var err error
		if len(errs) > 0 {
			err = errors.Collect(errs...)
		}
		responsec <- func() (Cacheable, error) {
			return nil, err
		}
		return nil
	}
}