// OldTaskResources returns the pre-0.9.0 map of task resources
431545
func (a *AllocatedResources) OldTaskResources() map[string]*Resources {
	m := make(map[string]*Resources, len(a.Tasks))
	for name, res := range a.Tasks {
		m[name] = &Resources{
			CPU:      int(res.Cpu.CpuShares),
			MemoryMB: int(res.Memory.MemoryMB),
			Networks: res.Networks,
		}
	}

	return m
}
465251
func (s *Service) findTasksByUser(ctx context.Context, tx Tx, filter influxdb.TaskFilter) ([]*influxdb.Task, int, error) {
	if filter.User == nil {
		return nil, 0, ErrTaskNotFound
	}
	var org *influxdb.Organization
	var err error
	if filter.OrganizationID != nil {
		org, err = s.findOrganizationByID(ctx, tx, *filter.OrganizationID)
		if err != nil {
			return nil, 0, err
		}
	} else if filter.Organization != "" {
		org, err = s.findOrganizationByName(ctx, tx, filter.Organization)
		if err != nil {
			return nil, 0, err
		}
	}

	var ts []*influxdb.Task

	maps, err := s.findUserResourceMappings(
		ctx,
		tx,
		influxdb.UserResourceMappingFilter{
			ResourceType: influxdb.TasksResourceType,
			UserID:       *filter.User,
			UserType:     influxdb.Owner,
		},
	)
	if err != nil {
		return nil, 0, err
	}

	for _, m := range maps {
		task, err := s.findTaskByID(ctx, tx, m.ResourceID)
		if err != nil {
			return nil, 0, err
		}

		if org != nil && task.OrganizationID != org.ID {
			continue
		}

		ts = append(ts, task)

		if len(ts) >= filter.Limit {
			break
		}
	}
	return ts, len(ts), nil
}
1269835
func (tr *TaskRunner) UpdateStats(ru *cstructs.TaskResourceUsage) {
	tr.resourceUsageLock.Lock()
	tr.resourceUsage = ru
	tr.resourceUsageLock.Unlock()
	if ru != nil {
		tr.emitStats(ru)
	}
}
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
}
186988
func (hw *horizontalReshardingWorkflow) GetTasks(phase workflow.PhaseType) []*workflowpb.Task {
	var shards []string
	switch phase {
	case phaseCopySchema, phaseWaitForFilteredReplication, phaseDiff:
		shards = strings.Split(hw.checkpoint.Settings["destination_shards"], ",")
	case phaseClone, phaseMigrateRdonly, phaseMigrateReplica, phaseMigrateMaster:
		shards = strings.Split(hw.checkpoint.Settings["source_shards"], ",")
	default:
		log.Fatalf("BUG: unknown phase type: %v", phase)
	}

	var tasks []*workflowpb.Task
	for _, s := range shards {
		taskID := createTaskID(phase, s)
		tasks = append(tasks, hw.checkpoint.Tasks[taskID])
	}
	return tasks
}
869165
func (c *Client) GetTasks() *GetTasksResult {
	resp, err := c.do("GET", "/tasks", ContentTypeJSON, nil)
	if err != nil {
		return &GetTasksResult{Err: err}
	}

	switch resp.Meta.Type {
	case rbody.ScheduledTaskListReturnedType:
		// Success
		return &GetTasksResult{resp.Body.(*rbody.ScheduledTaskListReturned), nil}
	case rbody.ErrorType:
		return &GetTasksResult{Err: resp.Body.(*rbody.Error)}
	default:
		return &GetTasksResult{Err: ErrAPIResponseMetaType}
	}
}
421106
func RunTasks(path string, tasksToExlude []string) (successTasks []map[string]interface{}, failedTasks []map[string]interface{}) {
	var wg sync.WaitGroup
	sourcePath = path
	sourceGoPath = strings.Replace(sourcePath, os.Getenv("GOPATH")+"/src/", "", 1)

	excludeTasks(&checkList, tasksToExlude)

	wg.Add(len(checkList))
	for _, task := range checkList {
		go func(task checkItem) {
			if ok := task.run(); ok {
				successTasks = append(successTasks, structs.Map(task))
			} else {
				failedTasks = append(failedTasks, structs.Map(task))
			}
			wg.Done()
		}(task)
	}

	wg.Wait()
	return successTasks, failedTasks
}
436527
func FindTaskDependencies(tasks map[string]Task) map[string][]string {
	taskToId := make(map[interface{}]string)
	for k, t := range tasks {
		taskToId[t] = k
	}

	edges := make(map[string][]string)

	for k, t := range tasks {
		task := t.(Task)

		var dependencies []Task
		if hd, ok := task.(HasDependencies); ok {
			dependencies = hd.GetDependencies(tasks)
		} else {
			dependencies = reflectForDependencies(tasks, task)
		}

		var dependencyKeys []string
		for _, dep := range dependencies {
			dependencyKey, found := taskToId[dep]
			if !found {
				glog.Fatalf("dependency not found: %v", dep)
			}
			dependencyKeys = append(dependencyKeys, dependencyKey)
		}

		edges[k] = dependencyKeys
	}

	glog.V(4).Infof("Dependencies:")
	for k, v := range edges {
		glog.V(4).Infof("\t%s:\t%v", k, v)
	}

	return edges
}
217709
func TaskArchival(c context.Context, state *coordinator.LogStreamState, delay time.Duration) error {
	// Now task the archival.
	state.Updated = clock.Now(c).UTC()
	state.ArchivalKey = []byte{'1'} // Use a fake key just to signal that we've tasked the archival.
	if err := ds.Put(c, state); err != nil {
		log.Fields{
			log.ErrorKey: err,
		}.Errorf(c, "Failed to Put() LogStream.")
		return grpcutil.Internal
	}

	project := string(coordinator.ProjectFromNamespace(state.Parent.Namespace()))
	id := string(state.ID())
	t, err := tqTask(&logdog.ArchiveTask{Project: project, Id: id})
	if err != nil {
		log.WithError(err).Errorf(c, "could not create archival task")
		return grpcutil.Internal
	}
	t.Delay = delay
	if err := taskqueue.Add(c, ArchiveQueueName, t); err != nil {
		log.WithError(err).Errorf(c, "could not task archival")
		return grpcutil.Internal
	}
	return nil

}
415976
func (t *Template) GetAllAWSKMSKeyResources() map[string]*resources.AWSKMSKey {
	results := map[string]*resources.AWSKMSKey{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSKMSKey:
			results[name] = resource
		}
	}
	return results
}
805020
func (n *Node) ComparableResources() *ComparableResources {
	// Node already has 0.9+ behavior
	if n.NodeResources != nil {
		return n.NodeResources.Comparable()
	}

	// Upgrade path
	return &ComparableResources{
		Flattened: AllocatedTaskResources{
			Cpu: AllocatedCpuResources{
				CpuShares: int64(n.Resources.CPU),
			},
			Memory: AllocatedMemoryResources{
				MemoryMB: int64(n.Resources.MemoryMB),
			},
		},
		Shared: AllocatedSharedResources{
			DiskMB: int64(n.Resources.DiskMB),
		},
	}
}
877603
func (r *marathonClient) AllTasks(opts *AllTasksOpts) (*Tasks, error) {
	path, err := addOptions(marathonAPITasks, opts)
	if err != nil {
		return nil, err
	}

	tasks := new(Tasks)
	if err := r.apiGet(path, nil, tasks); err != nil {
		return nil, err
	}

	return tasks, nil
}
366792
func (r *Application) AllTaskRunning() bool {
	if r.Instances == nil || *r.Instances == 0 {
		return true
	}
	if r.Tasks == nil {
		return false
	}
	if r.TasksRunning == *r.Instances {
		return true
	}
	return false
}
1198000
func (a *Archivist) archiveTaskImpl(c context.Context, task *logdog.ArchiveTask) error {
	// Validate the project name.
	if err := types.ProjectName(task.Project).Validate(); err != nil {
		log.WithError(err).Errorf(c, "invalid project name %q: %s", task.Project)
		return nil
	}

	// Load the log stream's current state. If it is already archived, we will
	// return an immediate success.
	ls, err := a.Service.LoadStream(c, &logdog.LoadStreamRequest{
		Project: task.Project,
		Id:      task.Id,
		Desc:    true,
	})
	switch {
	case err != nil:
		log.WithError(err).Errorf(c, "Failed to load log stream.")
		return err

	case ls.State == nil:
		log.Errorf(c, "Log stream did not include state.")
		return errors.New("log stream did not include state")

	case ls.State.Purged:
		log.Warningf(c, "Log stream is purged. Discarding archival request.")
		return nil

	case ls.State.Archived:
		log.Infof(c, "Log stream is already archived. Discarding archival request.")
		return nil

	case ls.State.ProtoVersion != logpb.Version:
		log.Fields{
			"protoVersion":    ls.State.ProtoVersion,
			"expectedVersion": logpb.Version,
		}.Errorf(c, "Unsupported log stream protobuf version.")
		return errors.New("unsupported log stream protobuf version")

	case ls.Desc == nil:
		log.Errorf(c, "Log stream did not include a descriptor.")
		return errors.New("log stream did not include a descriptor")
	}

	// Load archival settings for this project.
	settings, err := a.loadSettings(c, types.ProjectName(task.Project))
	if err != nil {
		log.Fields{
			log.ErrorKey: err,
			"project":    task.Project,
		}.Errorf(c, "Failed to load settings for project.")
		// This project has bad or no archival settings, this is non-transient, discard the task.
		return nil
	}

	ar := logdog.ArchiveStreamRequest{
		Project: task.Project,
		Id:      task.Id,
	}

	// Build our staged archival plan. This doesn't actually do any archiving.
	uid := fmt.Sprintf("%d", mathrand.Int63(c))
	staged, err := a.makeStagedArchival(c, types.ProjectName(task.Project), settings, ls, uid)
	if err != nil {
		log.WithError(err).Errorf(c, "Failed to create staged archival plan.")
		return err
	}
	defer staged.Close()

	// Archive to staging.
	//
	// If a non-transient failure occurs here, we will report it to the Archivist
	// under the assumption that it will continue occurring.
	//
	// We will handle error creating the plan and executing the plan in the same
	// switch statement below.
	switch err = staged.stage(c); {
	case transient.Tag.In(err):
		// If this is a transient error, exit immediately and do not delete the
		// archival task.
		log.WithError(err).Warningf(c, "TRANSIENT error during archival operation.")
		return err

	case err != nil:
		// This is a non-transient error, so we are confident that any future
		// Archival will also encounter this error. We will mark this archival
		// as an error and report it to the Coordinator.
		log.WithError(err).Errorf(c, "Archival failed with non-transient error.")
		ar.Error = err.Error()
		if ar.Error == "" {
			// This needs to be non-nil, so if our acutal error has an empty string,
			// fill in a generic message.
			ar.Error = "archival error"
		}

	default:
		// In case something fails, clean up our staged archival (best effort).
		defer staged.cleanup(c)

		// Finalize the archival.
		if err := staged.finalize(c, &ar); err != nil {
			log.WithError(err).Errorf(c, "Failed to finalize archival.")
			return err
		}

		// Add metrics for this successful archival.
		streamType := staged.desc.StreamType.String()

		staged.stream.addMetrics(c, tsEntriesField, streamType)
		staged.index.addMetrics(c, tsIndexField, streamType)
		staged.data.addMetrics(c, tsDataField, streamType)

		tsLogEntries.Add(c, float64(staged.logEntryCount), streamType)
		tsTotalLogEntries.Add(c, staged.logEntryCount, streamType)
	}

	log.Fields{
		"streamURL":     ar.StreamUrl,
		"indexURL":      ar.IndexUrl,
		"dataURL":       ar.DataUrl,
		"terminalIndex": ar.TerminalIndex,
		"logEntryCount": ar.LogEntryCount,
		"hadError":      ar.Error,
		"complete":      ar.Complete(),
	}.Debugf(c, "Finished archival round. Reporting archive state.")

	if _, err := a.Service.ArchiveStream(c, &ar); err != nil {
		log.WithError(err).Errorf(c, "Failed to report archive state.")
		return err
	}

	return nil
}
505423
func (s *globalTaskService) TaskTrack(ctx types.Context) *types.Task {
	return &s.taskTrack(ctx).Task
}
1221048
func upgradeTaskBucket(logger hclog.Logger, bkt *bolt.Bucket) (*taskRunnerState08, error) {
	simpleFound := false
	var trState taskRunnerState08

	cur := bkt.Cursor()
	for k, v := cur.First(); k != nil; k, v = cur.Next() {
		if v == nil {
			// value is nil: delete unexpected bucket
			logger.Warn("deleting unexpected task state bucket",
				"bucket", string(k),
			)

			if err := bkt.DeleteBucket(k); err != nil {
				return nil, fmt.Errorf("error deleting unexpected task bucket %q: %v", string(k), err)
			}
			continue
		}

		if !bytes.Equal(k, []byte("simple-all")) {
			// value is non-nil: delete unexpected entry
			logger.Warn("deleting unexpected task state entry",
				"key", string(k), "value_bytes", len(v),
			)

			if err := cur.Delete(); err != nil {
				return nil, fmt.Errorf("error delting unexpected task key %q: %v", string(k), err)
			}
			continue
		}

		// Decode simple-all
		simpleFound = true
		if err := codec.NewDecoderBytes(v, structs.MsgpackHandle).Decode(&trState); err != nil {
			return nil, fmt.Errorf("failed to decode task state from 'simple-all' entry: %v", err)
		}
	}

	if !simpleFound {
		return nil, fmt.Errorf("task state entry not found")
	}

	return &trState, nil
}
302232
func oldResourceShim(in dynamic.ResourceInterface, subresources []string) ResourceInterface {
	return oldResourceShimType{ResourceInterface: in, subresources: subresources}
}