// TaskWaitAllC returns a channel that is closed only when all the specified
// tasks are completed.
542411
func TaskWaitAllC(ctx types.Context, taskIDs ...int) <-chan int {
	return getTaskService(ctx).TaskWaitAllC(taskIDs...)
}
987032
func pollTaskAndWait(task enamlbosh.BoshTask, client *enamlbosh.Client, tries int) error {
	UIPrint("polling task...")
	defer UIPrint(fmt.Sprintf("Finished with Task %s", task.Description))
	ticker := time.Tick(time.Second)
	count := 0
	for {
		<-ticker
		var err error
		task, err = client.GetTask(task.ID)
		if err != nil {
			return err
		}
		switch task.State {
		case enamlbosh.StatusDone:
			UIPrintStatus(fmt.Sprintf("task state %s", task.State))
			return nil
		case enamlbosh.StatusCancelled, enamlbosh.StatusError:
			err := fmt.Errorf("%s - %s", task.State, task.Description)
			lo.G.Error("task error: " + err.Error())
			return err
		default:
			UIPrintStatus(fmt.Sprintf("task '%s' is %s", task.Description, task.State))
		}
		count++

		if tries != -1 && count >= tries {
			UIPrintStatus("hit poll limit, exiting task poller without error")
			return nil
		}
	}
}
1123304
func TaskControlAdaptor(s Store, lw LogWriter, lr LogReader) TaskControlService {
	return &taskControlAdaptor{s, lw, lr}
}
678713
func (tr *TaskRunner) handleTaskExitResult(result *drivers.ExitResult) (retryWait bool) {
	if result == nil {
		return false
	}

	if result.Err == bstructs.ErrPluginShutdown {
		dn := tr.Task().Driver
		tr.logger.Debug("driver plugin has shutdown; attempting to recover task", "driver", dn)

		// Initialize a new driver handle
		if err := tr.initDriver(); err != nil {
			tr.logger.Error("failed to initialize driver after it exited unexpectedly", "error", err, "driver", dn)
			return false
		}

		// Try to restore the handle
		tr.stateLock.RLock()
		h := tr.localState.TaskHandle
		net := tr.localState.DriverNetwork
		tr.stateLock.RUnlock()
		if !tr.restoreHandle(h, net) {
			tr.logger.Error("failed to restore handle on driver after it exited unexpectedly", "driver", dn)
			return false
		}

		tr.logger.Debug("task successfully recovered on driver", "driver", dn)
		return true
	}

	// Emit Terminated event
	tr.emitExitResultEvent(result)

	return false
}
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
}
158676
func (c *ServiceClient) RemoveTask(task *TaskServices) {
	ops := operations{}

	for _, service := range task.Services {
		id := makeTaskServiceID(task.AllocID, task.Name, service, task.Canary)
		ops.deregServices = append(ops.deregServices, id)

		for _, check := range service.Checks {
			cid := makeCheckID(id, check)
			ops.deregChecks = append(ops.deregChecks, cid)

			if check.TriggersRestarts() {
				c.checkWatcher.Unwatch(cid)
			}
		}
	}

	// Remove the task from the alloc's registrations
	c.removeTaskRegistration(task.AllocID, task.Name)

	// Now add them to the deregistration fields; main Run loop will update
	c.commit(&ops)
}
1031805
func (m *Projection) CloseFinal() error {
	//u.Debugf("Projection CloseFinal  alreadyclosed?%v", m.closed)
	defer func() {
		if r := recover(); r != nil {
			u.Warnf("error on close %v", r)
		}
	}()
	//return nil
	return m.TaskBase.Close()
}
944035
func (w *Worker) WaitForTask(taskId string) chan TaskInfo {
	out := make(chan TaskInfo)
	go func() {
		defer close(out)
		retryDelay := 100 * time.Millisecond

		for {
			info, err := w.TaskInfo(taskId)
			if err != nil {
				return
			}

			if info.Status == "queued" || info.Status == "running" {
				time.Sleep(retryDelay)
				retryDelay = sleepBetweenRetries(retryDelay)
			} else {
				out <- info
				return
			}
		}
	}()

	return out
}
1248431
func (c oauthClient) DeleteTask(task wl.Task) error {
	url := fmt.Sprintf(
		"%s/tasks/%d?revision=%d",
		c.apiURL,
		task.ID,
		task.Revision,
	)

	req, err := c.newDeleteRequest(url)
	if err != nil {
		return err
	}

	resp, err := c.do(req)
	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusNoContent {
		return fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusNoContent)
	}

	return nil
}
16744
func (m TaskManager) LaunchTask(c context.Context, ctl task.Controller) error {
	cfg := ctl.Task().(*messages.NoopTask)

	sleepFor := time.Duration(cfg.SleepMs) * time.Millisecond
	if sleepFor == 0 {
		sleepFor = 20 * time.Second
	}
	ctl.DebugLog("Running noop task for %s", sleepFor)
	clock.Sleep(c, sleepFor)

	for i := int64(0); i < cfg.TriggersCount; i++ {
		ctl.EmitTrigger(c, &internal.Trigger{
			Id:      fmt.Sprintf("noop:%d:%d", ctl.InvocationID(), i),
			Payload: &internal.Trigger_Noop{Noop: &api.NoopTrigger{}},
		})
	}

	ctl.State().Status = task.StatusSucceeded
	return nil
}
980404
func (f *HostPortFilter) SetTask(t *api.Task) bool {
	if t.Endpoint != nil {
		for _, port := range t.Endpoint.Ports {
			if port.PublishMode == api.PublishModeHost && port.PublishedPort != 0 {
				f.t = t
				return true
			}
		}
	}

	return false
}
745186
func ApiTaskToStructsTask(apiTask *api.Task, structsTask *structs.Task) {
	structsTask.Name = apiTask.Name
	structsTask.Driver = apiTask.Driver
	structsTask.User = apiTask.User
	structsTask.Leader = apiTask.Leader
	structsTask.Config = apiTask.Config
	structsTask.Env = apiTask.Env
	structsTask.Meta = apiTask.Meta
	structsTask.KillTimeout = *apiTask.KillTimeout
	structsTask.ShutdownDelay = apiTask.ShutdownDelay
	structsTask.KillSignal = apiTask.KillSignal
	structsTask.Constraints = ApiConstraintsToStructs(apiTask.Constraints)
	structsTask.Affinities = ApiAffinitiesToStructs(apiTask.Affinities)

	if l := len(apiTask.Services); l != 0 {
		structsTask.Services = make([]*structs.Service, l)
		for i, service := range apiTask.Services {
			structsTask.Services[i] = &structs.Service{
				Name:        service.Name,
				PortLabel:   service.PortLabel,
				Tags:        service.Tags,
				CanaryTags:  service.CanaryTags,
				AddressMode: service.AddressMode,
			}

			if l := len(service.Checks); l != 0 {
				structsTask.Services[i].Checks = make([]*structs.ServiceCheck, l)
				for j, check := range service.Checks {
					structsTask.Services[i].Checks[j] = &structs.ServiceCheck{
						Name:          check.Name,
						Type:          check.Type,
						Command:       check.Command,
						Args:          check.Args,
						Path:          check.Path,
						Protocol:      check.Protocol,
						PortLabel:     check.PortLabel,
						AddressMode:   check.AddressMode,
						Interval:      check.Interval,
						Timeout:       check.Timeout,
						InitialStatus: check.InitialStatus,
						TLSSkipVerify: check.TLSSkipVerify,
						Header:        check.Header,
						Method:        check.Method,
						GRPCService:   check.GRPCService,
						GRPCUseTLS:    check.GRPCUseTLS,
					}
					if check.CheckRestart != nil {
						structsTask.Services[i].Checks[j].CheckRestart = &structs.CheckRestart{
							Limit:          check.CheckRestart.Limit,
							Grace:          *check.CheckRestart.Grace,
							IgnoreWarnings: check.CheckRestart.IgnoreWarnings,
						}
					}
				}
			}
		}
	}

	structsTask.Resources = ApiResourcesToStructs(apiTask.Resources)

	structsTask.LogConfig = &structs.LogConfig{
		MaxFiles:      *apiTask.LogConfig.MaxFiles,
		MaxFileSizeMB: *apiTask.LogConfig.MaxFileSizeMB,
	}

	if l := len(apiTask.Artifacts); l != 0 {
		structsTask.Artifacts = make([]*structs.TaskArtifact, l)
		for k, ta := range apiTask.Artifacts {
			structsTask.Artifacts[k] = &structs.TaskArtifact{
				GetterSource:  *ta.GetterSource,
				GetterOptions: ta.GetterOptions,
				GetterMode:    *ta.GetterMode,
				RelativeDest:  *ta.RelativeDest,
			}
		}
	}

	if apiTask.Vault != nil {
		structsTask.Vault = &structs.Vault{
			Policies:     apiTask.Vault.Policies,
			Env:          *apiTask.Vault.Env,
			ChangeMode:   *apiTask.Vault.ChangeMode,
			ChangeSignal: *apiTask.Vault.ChangeSignal,
		}
	}

	if l := len(apiTask.Templates); l != 0 {
		structsTask.Templates = make([]*structs.Template, l)
		for i, template := range apiTask.Templates {
			structsTask.Templates[i] = &structs.Template{
				SourcePath:   *template.SourcePath,
				DestPath:     *template.DestPath,
				EmbeddedTmpl: *template.EmbeddedTmpl,
				ChangeMode:   *template.ChangeMode,
				ChangeSignal: *template.ChangeSignal,
				Splay:        *template.Splay,
				Perms:        *template.Perms,
				LeftDelim:    *template.LeftDelim,
				RightDelim:   *template.RightDelim,
				Envvars:      *template.Envvars,
				VaultGrace:   *template.VaultGrace,
			}
		}
	}

	if apiTask.DispatchPayload != nil {
		structsTask.DispatchPayload = &structs.DispatchPayloadConfig{
			File: apiTask.DispatchPayload.File,
		}
	}
}
59317
func (s *SimpleTask) Complete() {
	s.wg.Add(1)
	close(s.ch)
	s.wg.Wait()
}
855299
func (client *Client) UpdateTaskCancel(taskGUID string) (Task, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PutTaskCancelRequest,
		URIParams: internal.Params{
			"task_guid": taskGUID,
		},
	})
	if err != nil {
		return Task{}, nil, err
	}

	var task Task
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &task,
	}

	err = client.connection.Make(request, &response)
	if err != nil {
		return Task{}, response.Warnings, err
	}

	return task, response.Warnings, nil
}
1076511
func taskInTerminalState(task *api.Task) bool {
	return task.Status.State > api.TaskStateRunning
}
32724
func (b *Broker) nextDelayedTask(key string) (result []byte, err error) {
	conn := b.open()
	defer conn.Close()

	defer func() {
		// Return connection to normal state on error.
		// https://redis.io/commands/discard
		if err != nil {
			conn.Do("DISCARD")
		}
	}()

	var (
		items [][]byte
		reply interface{}
	)

	var pollPeriod = 500 // default poll period for delayed tasks
	if b.GetConfig().Redis != nil {
		configuredPollPeriod := b.GetConfig().Redis.DelayedTasksPollPeriod
		// the default period is 0, which bombards redis with requests, despite
		// our intention of doing the opposite
		if configuredPollPeriod > 0 {
			pollPeriod = configuredPollPeriod
		}
	}

	for {
		// Space out queries to ZSET so we don't bombard redis
		// server with relentless ZRANGEBYSCOREs
		time.Sleep(time.Duration(pollPeriod) * time.Millisecond)
		if _, err = conn.Do("WATCH", key); err != nil {
			return
		}

		now := time.Now().UTC().UnixNano()

		// https://redis.io/commands/zrangebyscore
		items, err = redis.ByteSlices(conn.Do(
			"ZRANGEBYSCORE",
			key,
			0,
			now,
			"LIMIT",
			0,
			1,
		))
		if err != nil {
			return
		}
		if len(items) != 1 {
			err = redis.ErrNil
			return
		}

		_ = conn.Send("MULTI")
		_ = conn.Send("ZREM", key, items[0])
		reply, err = conn.Do("EXEC")
		if err != nil {
			return
		}

		if reply != nil {
			result = items[0]
			break
		}
	}

	return
}
604120
func (s *StartChildWorkflowExecutionInitiatedEventAttributes) SetTaskStartToCloseTimeout(v string) *StartChildWorkflowExecutionInitiatedEventAttributes {
	s.TaskStartToCloseTimeout = &v
	return s
}