// FindRuns returns a list of runs that match a filter and the total count of returned runs.
// First attempt to use the TaskService, then append additional analytical's runs to the list
162296
func (as *AnalyticalStorage) FindRuns(ctx context.Context, filter influxdb.RunFilter) ([]*influxdb.Run, int, error) {
	if filter.Limit == 0 || filter.Limit > influxdb.TaskMaxPageSize {
		filter.Limit = influxdb.TaskMaxPageSize
	}

	runs, n, err := as.TaskService.FindRuns(ctx, filter)
	if err != nil {
		return runs, n, err
	}

	// if we reached the limit lets stop here
	if len(runs) >= filter.Limit {
		return runs, n, err
	}

	task, err := as.TaskService.FindTaskByID(ctx, filter.Task)
	if err != nil {
		return runs, n, err
	}

	filterPart := ""
	if filter.After != nil {
		filterPart = fmt.Sprintf(`|> filter(fn: (r) => r.runID > %q)`, filter.After.String())
	}

	// the data will be stored for 7 days in the system bucket so pulling 14d's is sufficient.
	runsScript := fmt.Sprintf(`from(bucketID: "000000000000000a")
	  |> range(start: -14d)
	  |> filter(fn: (r) => r._measurement == "runs" and r.taskID == %q)
	  %s
	  |> group(columns: ["taskID"])
	  |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")

	  `, filter.Task.String(), filterPart)

	auth, err := pctx.GetAuthorizer(ctx)
	if err != nil {
		return nil, 0, err
	}
	if auth.Kind() != "authorization" {
		return nil, 0, influxdb.ErrAuthorizerNotSupported
	}
	request := &query.Request{Authorization: auth.(*influxdb.Authorization), OrganizationID: task.OrganizationID, Compiler: lang.FluxCompiler{Query: runsScript}}

	ittr, err := as.qs.Query(ctx, request)
	if err != nil {
		return nil, 0, err
	}
	defer ittr.Release()

	re := &runReader{}
	for ittr.More() {
		err := ittr.Next().Tables().Do(re.readTable)
		if err != nil {
			return runs, n, err
		}
	}

	runs = append(runs, re.runs...)

	return runs, n, err
}
1043439
func (c *Container) setRuns(runs []interval16) {
	if roaringParanoia {
		if c.typ != containerRun {
			panic("attempt to write non-run's runs")
		}
	}
	// no array: start with our default 2-value array
	if runs == nil {
		c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedRunSize
		return
	}
	h := (*reflect.SliceHeader)(unsafe.Pointer(&runs))
	if h.Data == uintptr(unsafe.Pointer(c.pointer)) {
		// nothing to do but update length
		c.len = int32(h.Len)
		return
	}

	// array we can fit in data store:
	if len(runs) <= stashedRunSize {
		newRuns := *(*[]interval16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(&c.data[0])), Len: stashedRunSize, Cap: stashedRunSize}))
		copy(newRuns, runs)
		c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(len(runs)), stashedRunSize
		c.mapped = false // this is no longer using a hypothetical mmapped input array
		return
	}
	c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap)
	runtime.KeepAlive(&runs)
}
522835
func FindTasks(tx ReadTx, by By) ([]*api.Task, error) {
	checkType := func(by By) error {
		switch by.(type) {
		case byName, byNamePrefix, byIDPrefix, byRuntime, byDesiredState, byTaskState, byNode, byService, bySlot, byReferencedNetworkID, byReferencedSecretID, byReferencedConfigID, byCustom, byCustomPrefix:
			return nil
		default:
			return ErrInvalidFindBy
		}
	}

	taskList := []*api.Task{}
	appendResult := func(o api.StoreObject) {
		taskList = append(taskList, o.(*api.Task))
	}

	err := tx.find(tableTask, by, checkType, appendResult)
	return taskList, err
}
1314281
func (_m *Marathon) Tasks(application string) (*marathon.Tasks, error) {
	ret := _m.Called(application)

	var r0 *marathon.Tasks
	if rf, ok := ret.Get(0).(func(string) *marathon.Tasks); ok {
		r0 = rf(application)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*marathon.Tasks)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string) error); ok {
		r1 = rf(application)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
118068
func (sorter *TimSorter) nextRun() int {
	runBase := sorter.runEnd(0)
	assert2(runBase < sorter.to, fmt.Sprintf("runBase=%v to=%v", runBase, sorter.to))
	if runBase == sorter.to-1 {
		return 1
	}
	o := runBase + 2
	if sorter.Less(runBase+1, runBase) {
		// run must be strictly descending
		for o < sorter.to && sorter.Less(o, o-1) {
			o++
		}
		sorter.reverse(runBase, o)
	} else {
		// run must be non-descending
		for o < sorter.to && !sorter.Less(o, o-1) {
			o++
		}
	}
	runHi := runBase + sorter.minRun
	if sorter.to < runHi {
		runHi = sorter.to
	}
	if o > runHi {
		runHi = o
	}
	sorter.binarySort(runBase, runHi, o)
	for i := runBase; i < runHi-1; i++ {
		assert(!sorter.Less(i+1, i))
	}
	return runHi - runBase
}
637033
func RunStories(ctx context.Context, st storage.Store, b literal.Builder, stories []*Story, chanSize, bulkSize int) *AssertionBattery {
	results := &AssertionBattery{}
	for _, s := range stories {
		o, err := s.Run(ctx, st, b, chanSize, bulkSize)
		results.Entries = append(results.Entries, &AssertionBatteryEntry{
			Story:   s,
			Outcome: o,
			Err:     err,
		})
	}
	return results
}
474307
func (s *inmem) FinishRun(ctx context.Context, taskID, runID platform.ID) error {
	s.mu.RLock()
	stm, ok := s.meta[taskID]
	s.mu.RUnlock()

	if !ok {
		return errors.New("taskRunner not found")
	}

	if !stm.FinishRun(runID) {
		return errors.New("run not found")
	}

	s.mu.Lock()
	s.meta[taskID] = stm
	s.mu.Unlock()

	return nil
}
71452
func (s *Scheduler) getRunnableJobs() (running_jobs [MAXJOBNUM]*Job, n int) {
	runnableJobs := [MAXJOBNUM]*Job{}
	n = 0
	sort.Sort(s)
	for i := 0; i < s.size; i++ {
		if s.jobs[i].shouldRun() {

			runnableJobs[n] = s.jobs[i]
			//fmt.Println(runnableJobs)
			n++
		} else {
			break
		}
	}
	return runnableJobs, n
}
447565
func (r *Root) FindFiles(ctx context.Context, fi *dokan.FileInfo, ignored string, callback func(*dokan.NamedStat) error) error {
	var ns dokan.NamedStat
	var err error
	ns.FileAttributes = dokan.FileAttributeDirectory
	ename, esize := r.private.fs.remoteStatus.ExtraFileNameAndSize()
	switch ename {
	case "":
		ns.Name = PrivateName
		err = callback(&ns)
		if err != nil {
			return err
		}
		ns.Name = TeamName
		err = callback(&ns)
		if err != nil {
			return err
		}
		fallthrough
	case libfs.HumanNoLoginFileName:
		ns.Name = PublicName
		err = callback(&ns)
		if err != nil {
			return err
		}
	}
	if ename != "" {
		ns.Name = ename
		ns.FileAttributes = dokan.FileAttributeNormal
		ns.FileSize = esize
		err = callback(&ns)
		if err != nil {
			return err
		}
	}
	return nil
}
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
}
81988
func (e *executor) RunTasks(taskMap map[string]Task) error {
	dependencies := FindTaskDependencies(taskMap)

	taskStates := make(map[string]*taskState)

	for k, task := range taskMap {
		ts := &taskState{
			key:  k,
			task: task,
		}
		taskStates[k] = ts
	}

	for k, ts := range taskStates {
		for _, dep := range dependencies[k] {
			d := taskStates[dep]
			if d == nil {
				glog.Fatalf("did not find task state for dependency: %q", k)
			}
			ts.dependencies = append(ts.dependencies, d)
		}
	}

	for {
		var canRun []*taskState
		doneCount := 0
		for _, ts := range taskStates {
			if ts.done {
				doneCount++
				continue
			}
			ready := true
			for _, dep := range ts.dependencies {
				if !dep.done {
					ready = false
					break
				}
			}
			if ready {
				if ts.deadline.IsZero() {
					ts.deadline = time.Now().Add(e.options.MaxTaskDuration)
				} else if time.Now().After(ts.deadline) {
					return fmt.Errorf("deadline exceeded executing task %v. Example error: %v", ts.key, ts.lastError)
				}
				canRun = append(canRun, ts)
			}
		}

		glog.Infof("Tasks: %d done / %d total; %d can run", doneCount, len(taskStates), len(canRun))
		if len(canRun) == 0 {
			break
		}

		progress := false

		var tasks []*taskState
		for _, ts := range canRun {
			tasks = append(tasks, ts)
		}

		taskErrors := e.forkJoin(tasks)
		var errors []error
		for i, err := range taskErrors {
			ts := tasks[i]
			if err != nil {
				//  print warning message and continue like the task succeeded
				if _, ok := err.(*ExistsAndWarnIfChangesError); ok {
					glog.Warningf(err.Error())
					ts.done = true
					ts.lastError = nil
					progress = true
					continue
				}

				remaining := time.Second * time.Duration(int(ts.deadline.Sub(time.Now()).Seconds()))
				glog.Warningf("error running task %q (%v remaining to succeed): %v", ts.key, remaining, err)
				errors = append(errors, err)
				ts.lastError = err
			} else {
				ts.done = true
				ts.lastError = nil
				progress = true
			}
		}

		if !progress {
			if len(errors) == 0 {
				// Logic error!
				panic("did not make progress executing tasks; but no errors reported")
			}
			glog.Infof("No progress made, sleeping before retrying %d failed task(s)", len(errors))
			time.Sleep(e.options.WaitAfterAllTasksFailed)
		}
	}

	// Raise error if not all tasks done - this means they depended on each other
	var notDone []string
	for _, ts := range taskStates {
		if !ts.done {
			notDone = append(notDone, ts.key)
		}
	}
	if len(notDone) != 0 {
		return fmt.Errorf("Unable to execute tasks (circular dependency): %s", strings.Join(notDone, ", "))
	}

	return nil
}
309816
func (this Collection) FindAll(s interface{}) Collection {
    re := getRegexp(s)
    var result Collection
    for _, c := range this {
        result = append(result, c.FindAll(re)...)
    }

    return result
}
1082317
func (s *ListRunsOutput) SetRuns(v []*Run) *ListRunsOutput {
	s.Runs = v
	return s
}
1037495
func FindServices(tx ReadTx, by By) ([]*api.Service, error) {
	checkType := func(by By) error {
		switch by.(type) {
		case byName, byNamePrefix, byIDPrefix, byRuntime, byReferencedNetworkID, byReferencedSecretID, byReferencedConfigID, byCustom, byCustomPrefix, byAll:
			return nil
		default:
			return ErrInvalidFindBy
		}
	}

	serviceList := []*api.Service{}
	appendResult := func(o api.StoreObject) {
		serviceList = append(serviceList, o.(*api.Service))
	}

	err := tx.find(tableService, by, checkType, appendResult)
	return serviceList, err
}
542856
func (s *Service) FindRunByID(ctx context.Context, taskID, runID influxdb.ID) (*influxdb.Run, error) {
	var run *influxdb.Run
	err := s.kv.View(ctx, func(tx Tx) error {
		r, err := s.findRunByID(ctx, tx, taskID, runID)
		if err != nil {
			return err
		}
		run = r
		return nil
	})
	if err != nil {
		return nil, err
	}

	return run, nil
}
736704
func (c *Container) runContains(v uint16) bool {
	_, found := binSearchRuns(v, c.runs())
	return found
}
115793
func (s *Scheduler) InstancesFromAttachedRuns(ctx context.Context, app string) ([]*twelvefactor.Task, error) {
	// Filter only docker containers that were started as an attached run.
	attached := fmt.Sprintf("%s=%s", runLabel, Attached)
	return s.instances(ctx, app, attached)
}