// GetTask retrieves registered task
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
}
17570
func (c *Client) GetTaskByGuid(guid string) (task Task, err error) {
	request := fmt.Sprintf("/v3/tasks/%s", guid)
	req := c.NewRequest("GET", request)

	resp, err := c.DoRequest(req)
	if err != nil {
		return task, errors.Wrap(err, "Error requesting task")
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return task, errors.Wrap(err, "Error reading task")
	}

	err = json.Unmarshal(body, &task)
	if err != nil {
		return task, errors.Wrap(err, "Error unmarshaling task")
	}
	return task, err
}
761231
func (i *Index) WaitTask(taskID int) error {
	return waitWithRetry(func() (bool, error) {
		res, err := i.GetStatus(taskID)
		if err != nil {
			return true, err
		}
		if res.Status == "published" {
			return true, nil
		}
		return false, nil
	})
}
1296346
func TaskTrack(ctx types.Context) *types.Task {
	return getTaskService(ctx).TaskTrack(ctx)
}
546160
func (a *Client) GetTaskDetails(params *GetTaskDetailsParams) (*GetTaskDetailsOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewGetTaskDetailsParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "getTaskDetails",
		Method:             "GET",
		PathPattern:        "/tasks/{id}",
		ProducesMediaTypes: []string{"application/vnd.goswagger.examples.task-tracker.v1+json"},
		ConsumesMediaTypes: []string{"application/vnd.goswagger.examples.task-tracker.v1+json"},
		Schemes:            []string{"http", "https"},
		Params:             params,
		Reader:             &GetTaskDetailsReader{formats: a.formats},
		Context:            params.Context,
		Client:             params.HTTPClient,
	})
	if err != nil {
		return nil, err
	}
	return result.(*GetTaskDetailsOK), nil

}
276076
func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error {
	cfg := ctl.Task().(*messages.UrlFetchTask)
	started := clock.Now(c)

	// Defaults.
	method := cfg.Method
	if method == "" {
		method = "GET"
	}
	timeout := cfg.TimeoutSec
	if timeout == 0 {
		timeout = 60
	}

	ctl.DebugLog("%s %s", method, cfg.Url)

	// There must be no errors here in reality, since cfg is validated already by
	// ValidateProtoMessage.
	u, err := url.Parse(cfg.Url)
	if err != nil {
		return err
	}

	type tuple struct {
		resp *http.Response
		body []byte // first 4Kb of the response, for debug log
		err  error
	}
	result := make(chan tuple)

	// Do the fetch asynchronously with datastore update.
	go func() {
		defer close(result)
		c, _ := clock.WithTimeout(c, time.Duration(timeout)*time.Second)
		client := &http.Client{Transport: urlfetch.Get(c)}
		resp, err := client.Do(&http.Request{
			Method: method,
			URL:    u,
		})
		if err != nil {
			result <- tuple{nil, nil, err}
			return
		}
		defer resp.Body.Close()
		// Ignore read errors here. HTTP status code is set, it's the main output
		// of the operation. Read 4K only since we use body only for debug message
		// that is limited in size.
		buf := bytes.Buffer{}
		io.CopyN(&buf, resp.Body, 4096)
		result <- tuple{resp, buf.Bytes(), nil}
	}()

	// Save the invocation log now (since URL fetch can take up to 8 minutes).
	// Ignore errors. As long as final Save is OK, we don't care about this one.
	// Do NOT set status to StatusRunning, because by doing so we take
	// responsibility to detect crashes below and we don't want to do it (let
	// the scheduler retry LaunchTask automatically instead).
	if err := ctl.Save(c); err != nil {
		logging.Warningf(c, "Failed to save invocation state: %s", err)
	}

	// Wait for completion.
	res := <-result

	duration := clock.Now(c).Sub(started)
	status := task.StatusSucceeded
	if res.err != nil || res.resp.StatusCode >= 400 {
		status = task.StatusFailed
	}

	ctl.DebugLog("Finished with overall status %s in %s", status, duration)
	if res.err != nil {
		ctl.DebugLog("URL fetch error: %s", res.err)
	} else {
		ctl.DebugLog(dumpResponse(res.resp, res.body))
	}
	ctl.State().Status = status
	return nil
}
538217
func (s *Service) GetTaskDef(legacyswarmbucketapigettaskdefinitionrequestmessage *LegacySwarmbucketApiGetTaskDefinitionRequestMessage) *GetTaskDefCall {
	c := &GetTaskDefCall{s: s, urlParams_: make(gensupport.URLParams)}
	c.legacyswarmbucketapigettaskdefinitionrequestmessage = legacyswarmbucketapigettaskdefinitionrequestmessage
	return c
}
362605
func (s *StopTaskOutput) SetTask(v *Task) *StopTaskOutput {
	s.Task = v
	return s
}
864175
func (c *Cluster) GetTasks(options apitypes.TaskListOptions) ([]types.Task, error) {
	var r *swarmapi.ListTasksResponse

	if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error {
		filterTransform := func(filter filters.Args) error {
			if filter.Contains("service") {
				serviceFilters := filter.Get("service")
				for _, serviceFilter := range serviceFilters {
					service, err := getService(ctx, state.controlClient, serviceFilter, false)
					if err != nil {
						return err
					}
					filter.Del("service", serviceFilter)
					filter.Add("service", service.ID)
				}
			}
			if filter.Contains("node") {
				nodeFilters := filter.Get("node")
				for _, nodeFilter := range nodeFilters {
					node, err := getNode(ctx, state.controlClient, nodeFilter)
					if err != nil {
						return err
					}
					filter.Del("node", nodeFilter)
					filter.Add("node", node.ID)
				}
			}
			if !filter.Contains("runtime") {
				// default to only showing container tasks
				filter.Add("runtime", "container")
				filter.Add("runtime", "")
			}
			return nil
		}

		filters, err := newListTasksFilters(options.Filters, filterTransform)
		if err != nil {
			return err
		}

		r, err = state.controlClient.ListTasks(
			ctx,
			&swarmapi.ListTasksRequest{Filters: filters},
			grpc.MaxCallRecvMsgSize(defaultRecvSizeForListResponse),
		)
		return err
	}); err != nil {
		return nil, err
	}

	tasks := make([]types.Task, 0, len(r.Tasks))
	for _, task := range r.Tasks {
		t, err := convert.TaskFromGRPC(*task)
		if err != nil {
			return nil, err
		}
		tasks = append(tasks, t)
	}
	return tasks, nil
}
1252076
func GetTask(tx ReadTx, id string) *api.Task {
	t := tx.get(tableTask, id)
	if t == nil {
		return nil
	}
	return t.(*api.Task)
}
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
	}
}
1125634
func (ds *DataSource) tryToGetDualTask() (task, error) {
	for _, cond := range ds.pushedDownConds {
		if con, ok := cond.(*expression.Constant); ok && con.DeferredExpr == nil {
			result, _, err := expression.EvalBool(ds.ctx, []expression.Expression{cond}, chunk.Row{})
			if err != nil {
				return nil, err
			}
			if !result {
				dual := PhysicalTableDual{}.Init(ds.ctx, ds.stats)
				dual.SetSchema(ds.schema)
				return &rootTask{
					p: dual,
				}, nil
			}
		}
	}
	return nil, nil
}
468830
func (w *tableWorker) executeTask(ctx context.Context, task *lookupTableTask) error {
	tableReader, err := w.buildTblReader(ctx, task.handles)
	if err != nil {
		logutil.Logger(ctx).Error("build table reader failed", zap.Error(err))
		return err
	}
	defer terror.Call(tableReader.Close)

	task.memTracker = w.memTracker
	memUsage := int64(cap(task.handles) * 8)
	task.memUsage = memUsage
	task.memTracker.Consume(memUsage)
	handleCnt := len(task.handles)
	task.rows = make([]chunk.Row, 0, handleCnt)
	for {
		chk := tableReader.newFirstChunk()
		err = tableReader.Next(ctx, chunk.NewRecordBatch(chk))
		if err != nil {
			logutil.Logger(ctx).Error("table reader fetch next chunk failed", zap.Error(err))
			return err
		}
		if chk.NumRows() == 0 {
			break
		}
		memUsage = chk.MemoryUsage()
		task.memUsage += memUsage
		task.memTracker.Consume(memUsage)
		iter := chunk.NewIterator4Chunk(chk)
		for row := iter.Begin(); row != iter.End(); row = iter.Next() {
			task.rows = append(task.rows, row)
		}
	}

	memUsage = int64(cap(task.rows)) * int64(unsafe.Sizeof(chunk.Row{}))
	task.memUsage += memUsage
	task.memTracker.Consume(memUsage)
	if w.keepOrder {
		task.rowIdx = make([]int, 0, len(task.rows))
		for i := range task.rows {
			handle := task.rows[i].GetInt64(w.handleIdx)
			task.rowIdx = append(task.rowIdx, task.indexOrder[handle])
		}
		memUsage = int64(cap(task.rowIdx) * 4)
		task.memUsage += memUsage
		task.memTracker.Consume(memUsage)
		sort.Sort(task)
	}

	if handleCnt != len(task.rows) {
		if w.isCheckOp {
			obtainedHandlesMap := make(map[int64]struct{}, len(task.rows))
			for _, row := range task.rows {
				handle := row.GetInt64(w.handleIdx)
				obtainedHandlesMap[handle] = struct{}{}
			}
			return errors.Errorf("inconsistent index %s handle count %d isn't equal to value count %d, missing handles %v in a batch",
				w.idxLookup.index.Name.O, handleCnt, len(task.rows), GetLackHandles(task.handles, obtainedHandlesMap))
		}

		if len(w.idxLookup.tblPlans) == 1 {
			// table scan in double read can never has conditions according to convertToIndexScan.
			// if this table scan has no condition, the number of rows it returns must equal to the length of handles.
			return errors.Errorf("inconsistent index %s handle count %d isn't equal to value count %d",
				w.idxLookup.index.Name.O, handleCnt, len(task.rows))
		}
	}

	return nil
}
470871
func (s *TasksService) FindResultByTask(t Task) (*http.Response, error) {
	return s.client.GetResultByURI(t.ResultURI)
}
852647
func (cat *catalog) marshalTask(task proto.Message) ([]byte, error) {
	if cat.GetTaskManager(task) == nil {
		return nil, fmt.Errorf("unrecognized task definition type %T", task)
	}
	// Enumerate all fields of the wrapper until we find a matching type.
	taskType := reflect.TypeOf(task)
	wrapper := messages.TaskDefWrapper{}
	v := reflect.ValueOf(&wrapper).Elem()
	for i := 0; i < v.NumField(); i++ {
		field := v.Field(i)
		if field.Type() == taskType {
			field.Set(reflect.ValueOf(task))
			return proto.Marshal(&wrapper)
		}
	}
	// This can happen only if TaskDefWrapper wasn't updated when a new task type
	// was added. This is a developer's mistake, not a config mistake.
	return nil, fmt.Errorf("could not find a field of type %T in TaskDefWrapper", task)
}
706999
func (a *Client) GetTaskComments(params *GetTaskCommentsParams) (*GetTaskCommentsOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewGetTaskCommentsParams()
	}

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "getTaskComments",
		Method:             "GET",
		PathPattern:        "/tasks/{id}/comments",
		ProducesMediaTypes: []string{"application/vnd.goswagger.examples.task-tracker.v1+json"},
		ConsumesMediaTypes: []string{"application/vnd.goswagger.examples.task-tracker.v1+json"},
		Schemes:            []string{"http", "https"},
		Params:             params,
		Reader:             &GetTaskCommentsReader{formats: a.formats},
		Context:            params.Context,
		Client:             params.HTTPClient,
	})
	if err != nil {
		return nil, err
	}
	return result.(*GetTaskCommentsOK), nil

}
1059412
func (*NewGoroutineDispatcher) DispatchTask(task *swf.PollForDecisionTaskOutput, handler func(*swf.PollForDecisionTaskOutput)) {
	go handler(task)
}