// CheckRunningTaskImages returns the times each image is running as a task.
179112
func (d *Daemon) CheckRunningTaskImages(c *check.C) (interface{}, check.CommentInterface) {
	cli := d.NewClientT(c)
	defer cli.Close()

	filterArgs := filters.NewArgs()
	filterArgs.Add("desired-state", "running")

	options := types.TaskListOptions{
		Filters: filterArgs,
	}

	tasks, err := cli.TaskList(context.Background(), options)
	assert.NilError(c, err)

	result := make(map[string]int)
	for _, task := range tasks {
		if task.Status.State == swarm.TaskStateRunning && task.Spec.ContainerSpec != nil {
			result[task.Spec.ContainerSpec.Image]++
		}
	}
	return result, nil
}
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
}
196398
func (r *StandardRegistry) RunHealthchecks() {
	r.mutex.Lock()
	defer r.mutex.Unlock()
	for _, i := range r.metrics {
		if h, ok := i.(Healthcheck); ok {
			h.Check()
		}
	}
}
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
}
725176
func (e *Executor) RunningFor(taskID platform.ID) []*RunPromise {
	e.mu.Lock()
	defer e.mu.Unlock()

	var rps []*RunPromise
	for _, rp := range e.running {
		if rp.Run().TaskID == taskID {
			rps = append(rps, rp)
		}
	}

	return rps
}
1248118
func IsRunning() (string, error) {
	var (
		cmdOut []byte
		err    error
		path   string
	)
	cmd := "fcagent"
	args := []string{"echo"}

	if path, err = exec.LookPath(cmd); err != nil {
		log.Debug(err)
	}
	log.Debug(path, args[0])

	if cmdOut, err = exec.Command(cmd, args...).Output(); err != nil {
		log.Debug(err)
	}
	return string(cmdOut), err
}
1296247
func CheckTasks(ctx context.Context, s *store.MemoryStore, readTx store.ReadTx, initHandler InitHandler, startSupervisor *restart.Supervisor) error {
	instances := make(map[orchestrator.SlotTuple][]*api.Task)
	err := s.Batch(func(batch *store.Batch) error {
		tasks, err := store.FindTasks(readTx, store.All)
		if err != nil {
			return err
		}
		for _, t := range tasks {
			if t.ServiceID == "" {
				continue
			}

			// TODO(aluzzardi): We should NOT retrieve the service here.
			service := store.GetService(readTx, t.ServiceID)
			if service == nil {
				// Service was deleted
				err := batch.Update(func(tx store.Tx) error {
					return store.DeleteTask(tx, t.ID)
				})
				if err != nil {
					log.G(ctx).WithError(err).Error("failed to delete task")
				}
				continue
			}
			if !initHandler.IsRelatedService(service) {
				continue
			}

			tuple := initHandler.SlotTuple(t)
			instances[tuple] = append(instances[tuple], t)

			// handle task updates from agent which should have been triggered by task update events
			initHandler.FixTask(ctx, batch, t)

			// desired state ready is a transient state that it should be started.
			// however previous leader may not have started it, retry start here
			if t.DesiredState != api.TaskStateReady || t.Status.State > api.TaskStateRunning {
				continue
			}
			restartDelay, _ := gogotypes.DurationFromProto(defaults.Service.Task.Restart.Delay)
			if t.Spec.Restart != nil && t.Spec.Restart.Delay != nil {
				var err error
				restartDelay, err = gogotypes.DurationFromProto(t.Spec.Restart.Delay)
				if err != nil {
					log.G(ctx).WithError(err).Error("invalid restart delay")
					restartDelay, _ = gogotypes.DurationFromProto(defaults.Service.Task.Restart.Delay)
				}
			}
			if restartDelay != 0 {
				var timestamp time.Time
				if t.Status.AppliedAt != nil {
					timestamp, err = gogotypes.TimestampFromProto(t.Status.AppliedAt)
				} else {
					timestamp, err = gogotypes.TimestampFromProto(t.Status.Timestamp)
				}
				if err == nil {
					restartTime := timestamp.Add(restartDelay)
					calculatedRestartDelay := time.Until(restartTime)
					if calculatedRestartDelay < restartDelay {
						restartDelay = calculatedRestartDelay
					}
					if restartDelay > 0 {
						_ = batch.Update(func(tx store.Tx) error {
							t := store.GetTask(tx, t.ID)
							// TODO(aluzzardi): This is shady as well. We should have a more generic condition.
							if t == nil || t.DesiredState != api.TaskStateReady {
								return nil
							}
							startSupervisor.DelayStart(ctx, tx, nil, t.ID, restartDelay, true)
							return nil
						})
						continue
					}
				} else {
					log.G(ctx).WithError(err).Error("invalid status timestamp")
				}
			}

			// Start now
			err := batch.Update(func(tx store.Tx) error {
				return startSupervisor.StartNow(tx, t.ID)
			})
			if err != nil {
				log.G(ctx).WithError(err).WithField("task.id", t.ID).Error("moving task out of delayed state failed")
			}
		}
		return nil
	})
	if err != nil {
		return err
	}

	for tuple, instance := range instances {
		// Find the most current spec version. That's the only one
		// we care about for the purpose of reconstructing restart
		// history.
		maxVersion := uint64(0)
		for _, t := range instance {
			if t.SpecVersion != nil && t.SpecVersion.Index > maxVersion {
				maxVersion = t.SpecVersion.Index
			}
		}

		// Create a new slice with just the current spec version tasks.
		var upToDate []*api.Task
		for _, t := range instance {
			if t.SpecVersion != nil && t.SpecVersion.Index == maxVersion {
				upToDate = append(upToDate, t)
			}
		}

		// Sort by creation timestamp
		sort.Sort(tasksByCreationTimestamp(upToDate))

		// All up-to-date tasks in this instance except the first one
		// should be considered restarted.
		if len(upToDate) < 2 {
			continue
		}
		for _, t := range upToDate[1:] {
			startSupervisor.RecordRestartHistory(tuple, t)
		}
	}
	return nil
}
1274827
func (s *Server) isRunning() bool {
	s.mu.Lock()
	running := s.running
	s.mu.Unlock()
	return running
}
426040
func (c *Container) IsRunning(ctx context.Context) bool {
	return c.container.State.Running
}
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
}
1147040
func taskWillNeverRun(task *api.Task) bool {
	return task.Status.State < api.TaskStateAssigned && task.DesiredState > api.TaskStateRunning
}
1047815
func (p *StatusTable) IsRunning(name string) bool {
	p.RLock()
	defer p.RUnlock()

	return p.pool[name]
}
1352005
func GetTaskAncestry(taskName string, tasks []wfv1.DAGTask) []string {
	taskByName := make(map[string]wfv1.DAGTask)
	for _, task := range tasks {
		taskByName[task.Name] = task
	}

	visited := make(map[string]bool)
	var getAncestry func(s string)
	getAncestry = func(currTask string) {
		task := taskByName[currTask]
		for _, depTask := range task.Dependencies {
			getAncestry(depTask)
		}
		if currTask != taskName {
			visited[currTask] = true
		}
	}

	getAncestry(taskName)
	ancestry := make([]string, 0)
	for ancestor := range visited {
		ancestry = append(ancestry, ancestor)
	}
	return ancestry
}
409233
func (s *Scheduler) RunPending() {
	runnableJobs, n := s.getRunnableJobs()

	if n != 0 {
		for i := 0; i < n; i++ {
			runnableJobs[i].run()
		}
	}
}
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
		}
	}
}
505423
func (s *globalTaskService) TaskTrack(ctx types.Context) *types.Task {
	return &s.taskTrack(ctx).Task
}
310363
func (tl *TaskLogger) IsRunning() bool {
	if tl.lro != nil && tl.lro.isRunning() {
		return true
	}
	if tl.lre != nil && tl.lre.isRunning() {
		return true
	}

	return false
}