// waitForJob is a helper that waits for a job to complete.
//
// This operates on an event returned from a watcher.
331401
func (c *Client) waitForJob(e watch.Event, name string) (bool, error) {
	job := &batch.Job{}
	err := legacyscheme.Scheme.Convert(e.Object, job, nil)
	if err != nil {
		return true, err
	}

	for _, c := range job.Status.Conditions {
		if c.Type == batch.JobComplete && c.Status == v1.ConditionTrue {
			return true, nil
		} else if c.Type == batch.JobFailed && c.Status == v1.ConditionTrue {
			return true, fmt.Errorf("Job failed: %s", c.Reason)
		}
	}

	c.Log("%s: Jobs active: %d, jobs failed: %d, jobs succeeded: %d", name, job.Status.Active, job.Status.Failed, job.Status.Succeeded)
	return false, nil
}
1024932
func waitForProcess(ctx context.Context, process *process, p *os.Process, s *service) {
	pid := uint32(p.Pid)

	// Store the default non-exited value for calls to stat
	process.exit.Store(&processExit{
		pid:        pid,
		exitStatus: 255,
		exitedAt:   time.Time{},
		exitErr:    nil,
	})

	var status int
	processState, eerr := p.Wait()
	if eerr != nil {
		status = 255
		p.Kill()
	} else {
		status = processState.Sys().(syscall.WaitStatus).ExitStatus()
	}

	now := time.Now()
	process.exit.Store(&processExit{
		pid:        pid,
		exitStatus: uint32(status),
		exitedAt:   now,
		exitErr:    eerr,
	})

	// Wait for the relay
	process.relay.wait()

	// Wait for the started event to fire if it hasn't already
	process.startedWg.Wait()

	// We publish the exit before freeing upstream so that the exit event always
	// happens before any delete event.
	s.publisher.Publish(
		ctx,
		runtime.TaskExitEventTopic,
		&eventstypes.TaskExit{
			ContainerID: process.cid,
			ID:          process.id,
			Pid:         pid,
			ExitStatus:  uint32(status),
			ExitedAt:    now,
		})

	// close the client io, and free upstream waiters
	process.close()
}
350972
func (job *QorJob) GetJob() *Job {
	if job.Job != nil {
		return job.Job
	}
	return nil
}
789373
func (d *Daemon) executeJob(id job.ID, do jobFunc, logger log.Logger) (job.Result, error) {
	ctx, cancel := context.WithTimeout(context.Background(), defaultJobTimeout)
	defer cancel()
	d.JobStatusCache.SetStatus(id, job.Status{StatusString: job.StatusRunning})
	result, err := do(ctx, id, logger)
	if err != nil {
		d.JobStatusCache.SetStatus(id, job.Status{StatusString: job.StatusFailed, Err: err.Error()})
		return result, err
	}
	d.JobStatusCache.SetStatus(id, job.Status{StatusString: job.StatusSucceeded, Result: result})
	return result, nil
}
555138
func (pf *PortForwarder) waitForConnection(listener net.Listener, port ForwardedPort) {
	for {
		conn, err := listener.Accept()
		if err != nil {
			// TODO consider using something like https://github.com/hydrogen18/stoppableListener?
			if !strings.Contains(strings.ToLower(err.Error()), "use of closed network connection") {
				runtime.HandleError(fmt.Errorf("Error accepting connection on port %d: %v", port.Local, err))
			}
			return
		}
		go pf.handleConnection(conn, port)
	}
}
269899
func (e *Endpoint) WaitForProxyCompletions(proxyWaitGroup *completion.WaitGroup) error {
	if proxyWaitGroup == nil {
		return nil
	}

	err := proxyWaitGroup.Context().Err()
	if err != nil {
		return fmt.Errorf("context cancelled before waiting for proxy updates: %s", err)
	}

	start := time.Now()

	e.getLogger().Debug("Waiting for proxy updates to complete...")
	err = proxyWaitGroup.Wait()
	if err != nil {
		return fmt.Errorf("proxy state changes failed: %s", err)
	}
	e.getLogger().Debug("Wait time for proxy updates: ", time.Since(start))

	return nil
}
619116
func (s *ReindexService) WaitForCompletion(waitForCompletion bool) *ReindexService {
	s.waitForCompletion = &waitForCompletion
	return s
}
781281
func (wg *WaitGroup) WaitFor(timeout time.Duration) bool {
	if timeout == time.Duration(0) {
		wg.Wait()
		return true // ### return, always true ###
	}

	start := time.Now()
	spin := NewSpinner(SpinPriorityHigh)
	for wg.Active() {
		if time.Since(start) > timeout {
			return false // ### return, timed out ###
		}
		spin.Yield()
	}
	return true
}
1210675
func (self *Commands) WaitFor(event string, args *WaitForArgs) error {
	if args == nil {
		args = &WaitForArgs{}
	}

	defaults.SetDefaults(args)
	args.Timeout = utils.FudgeDuration(args.Timeout)

	if waiter, err := self.browser.Tab().CreateEventWaiter(event); err == nil {
		defer waiter.Remove()

		// wait for the first event matching the given pattern
		_, err := waiter.Wait(args.Timeout)
		return err
	} else {
		return err
	}
}
895163
func newWaitWorker(config Config, targetVersion int) (worker.Worker, error) {
	watcher, err := config.Facade.WatchModelEnvironVersion(config.ModelTag)
	if err != nil {
		return nil, errors.Trace(err)
	}
	ww := waitWorker{
		watcher:       watcher,
		facade:        config.Facade,
		modelTag:      config.ModelTag,
		gate:          config.GateUnlocker,
		targetVersion: targetVersion,
	}
	if err := catacomb.Invoke(catacomb.Plan{
		Site: &ww.catacomb,
		Init: []worker.Worker{watcher},
		Work: ww.loop,
	}); err != nil {
		return nil, errors.Trace(err)
	}
	return &ww, nil
}
91969
func (d *driverMock) WaitForImageCreation(ctx context.Context, id string) error {
	return d.WaitForImageCreationErr
}
248960
func workJobs(prs []*processNode, pus []*publishNode, t *task, pj job) {
	// optimize for no jobs
	if len(prs) == 0 && len(pus) == 0 {
		return
	}
	// Create waitgroup to block until all jobs are submitted
	wg := &sync.WaitGroup{}
	workflowLogger.WithFields(log.Fields{
		"_block":              "work-jobs",
		"task-id":             t.id,
		"task-name":           t.name,
		"count-process-nodes": len(prs),
		"count-publish-nodes": len(pus),
		"parent-node-type":    pj.TypeString(),
	}).Debug("Batch submission of process and publish nodes")
	// range over the process jobs and call submitProcessJob
	for _, pr := range prs {
		// increment the wait group (before starting goroutine to prevent a race condition)
		wg.Add(1)
		// Start goroutine to submit the process job
		go submitProcessJob(pj, t, wg, pr)
	}
	// range over the publish jobs and call submitPublishJob
	for _, pu := range pus {
		// increment the wait group (before starting goroutine to prevent a race condition)
		wg.Add(1)
		// Start goroutine to submit the process job
		go submitPublishJob(pj, t, wg, pu)
	}
	// Wait until all job submisson goroutines are done
	wg.Wait()
	workflowLogger.WithFields(log.Fields{
		"_block":              "work-jobs",
		"task-id":             t.id,
		"task-name":           t.name,
		"count-process-nodes": len(prs),
		"count-publish-nodes": len(pus),
		"parent-node-type":    pj.TypeString(),
	}).Debug("Batch submission complete")
}
1079918
func (c *Ctx) WaitForSlotEvent(flags uint) chan SlotEvent {
	sl := make(chan SlotEvent, 1) // hold one element
	go c.waitForSlotEventHelper(flags, sl)
	return sl
}
1215995
func (d *Daemon) queueJob(do jobFunc) job.ID {
	id := job.ID(guid.New())
	enqueuedAt := time.Now()
	d.Jobs.Enqueue(&job.Job{
		ID: id,
		Do: func(logger log.Logger) error {
			queueDuration.Observe(time.Since(enqueuedAt).Seconds())
			_, err := d.executeJob(id, do, logger)
			if err != nil {
				return err
			}
			return nil
		},
	})
	queueLength.Set(float64(d.Jobs.Len()))
	d.JobStatusCache.SetStatus(id, job.Status{StatusString: job.StatusQueued})
	return id
}
513416
func (s *UpdateByQueryService) WaitForCompletion(waitForCompletion bool) *UpdateByQueryService {
	s.waitForCompletion = &waitForCompletion
	return s
}
105593
func (client *Client) WaitForAssembly(ctx context.Context, assembly *AssemblyInfo) (*AssemblyInfo, error) {
	for {
		res, err := client.GetAssembly(ctx, assembly.AssemblySSLURL)
		if err != nil {
			return nil, err
		}

		// Abort polling if the assembly has entered an error state
		if res.Error != "" {
			return res, nil
		}

		// The polling is done if the assembly is not uploading or executing anymore.
		if res.Ok != "ASSEMBLY_UPLOADING" && res.Ok != "ASSEMBLY_EXECUTING" {
			return res, nil
		}

		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		case <-time.After(time.Second):
			continue
		}
	}
}
1295326
func (c *Client) GetJob(appID, jobID string) (*ct.Job, error) {
	job := &ct.Job{}
	return job, c.Get(fmt.Sprintf("/apps/%s/jobs/%s", appID, jobID), job)
}