/*
trackerLoop runs all day and manages stuff.
*/
422889
func (t *requestTracker) trackerLoop() {
	activeRequests := 0
	stopping := false
	sentStop := false
	graceTimer := time.NewTimer(time.Duration(math.MaxInt64))

	for !sentStop {
		select {
		case cmd := <-t.commandChan:
			switch cmd {
			case startRequest:
				activeRequests++
			case endRequest:
				activeRequests--
				if stopping && activeRequests == 0 {
					sentStop = t.sendStop(sentStop)
				}
			case shutdown:
				stopping = true
				atomic.StoreInt32(&t.shutdownState, shutDown)
				if activeRequests <= 0 {
					sentStop = t.sendStop(sentStop)
				} else {
					graceTimer.Reset(t.shutdownWait)
				}
			}
		case <-graceTimer.C:
			sentStop = t.sendStop(sentStop)
		}
	}
}
663553
func (ar *allocRunner) handleAllocUpdate(update *structs.Allocation) {
	// Detect Stop updates
	stopping := !ar.Alloc().TerminalStatus() && update.TerminalStatus()

	// Update ar.alloc
	ar.setAlloc(update)

	// Run update hooks if not stopping or dead
	if !update.TerminalStatus() {
		if err := ar.update(update); err != nil {
			ar.logger.Error("error running update hooks", "error", err)
		}

	}

	// Update task runners
	for _, tr := range ar.tasks {
		tr.Update(update)
	}

	// If alloc is being terminated, kill all tasks, leader first
	if stopping {
		ar.killTasks()
	}

}
141688
func (api *API) TrackBranch(arg params.BranchTrackArg) (params.ErrorResults, error) {
	isModelAdmin, err := api.hasAdminAccess()
	if err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}
	if !isModelAdmin && !api.isControllerAdmin {
		return params.ErrorResults{}, common.ErrPerm
	}

	branch, err := api.model.Branch(arg.BranchName)
	if err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}

	result := params.ErrorResults{
		Results: make([]params.ErrorResult, len(arg.Entities)),
	}
	for i, entity := range arg.Entities {
		tag, err := names.ParseTag(entity.Tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		switch tag.Kind() {
		case names.ApplicationTagKind:
			result.Results[i].Error = common.ServerError(branch.AssignAllUnits(tag.Id()))
		case names.UnitTagKind:
			result.Results[i].Error = common.ServerError(branch.AssignUnit(tag.Id()))
		default:
			result.Results[i].Error = common.ServerError(
				errors.Errorf("expected names.UnitTag or names.ApplicationTag, got %T", tag))
		}
	}
	return result, nil
}
362288
func (e *TrackToken) Run(m libkb.MetaContext) (err error) {
	defer m.Trace("TrackToken#Run", func() error { return err })()

	if len(e.arg.Token) == 0 && e.arg.Outcome == nil {
		err = fmt.Errorf("missing TrackToken argument")
		return err
	}
	if err = e.loadMe(m); err != nil {
		m.Info("loadme err: %s", err)
		return err
	}

	// We can either pass this in directly, or look it up via TrackToken
	outcome := e.arg.Outcome
	if outcome == nil {
		outcome, err = m.G().TrackCache().Get(e.arg.Token)
		if err != nil {
			return err
		}
	}

	if outcome.TrackStatus() == keybase1.TrackStatus_UPDATE_OK && !e.arg.Options.ForceRetrack {
		m.Debug("tracking statement up-to-date.")
		return nil
	}

	if err = e.loadThem(m, outcome.Username); err != nil {
		return err
	}

	if e.arg.Me.Equal(e.them) {
		err = libkb.SelfTrackError{}
		return err
	}

	if err = e.isTrackTokenStale(m, outcome); err != nil {
		m.Debug("Track statement is stale")
		return err
	}

	// need public signing key for track statement
	signingKeyPub, err := e.arg.Me.SigningKeyPub()
	if err != nil {
		return err
	}

	e.trackStatement, err = e.arg.Me.TrackingProofFor(m, signingKeyPub, libkb.SigVersion(*e.arg.Options.SigVersion), e.them, outcome)
	if err != nil {
		m.Debug("tracking proof err: %s", err)
		return err
	}
	if e.trackStatementBytes, err = e.trackStatement.J.Marshal(); err != nil {
		return err
	}

	m.Debug("| Tracking statement: %s", string(e.trackStatementBytes))

	if e.arg.Options.LocalOnly || e.arg.Options.ExpiringLocal {
		m.Debug("| Local")
		err = e.storeLocalTrack(m)
	} else {
		err = e.storeRemoteTrack(m, signingKeyPub.GetKID())
		if err == nil {
			// if the remote track succeeded, remove local tracks
			// (this also removes any snoozes)
			e.removeLocalTracks(m)
		}
	}

	if err == nil {
		// Remove this after desktop notification change complete:
		m.G().UserChanged(m.Ctx(), e.them.GetUID())

		// Remove these after desktop notification change complete, but
		// add in: m.G().BustLocalUserCache(e.arg.Me.GetUID())
		m.G().UserChanged(m.Ctx(), e.arg.Me.GetUID())

		// Keep these:
		m.G().NotifyRouter.HandleTrackingChanged(e.arg.Me.GetUID(), e.arg.Me.GetNormalizedName(), false)
		m.G().NotifyRouter.HandleTrackingChanged(e.them.GetUID(), e.them.GetNormalizedName(), true)

		// Dismiss any associated gregor item.
		if outcome.ResponsibleGregorItem != nil {
			err = m.G().GregorState.DismissItem(m.Ctx(), nil,
				outcome.ResponsibleGregorItem.Metadata().MsgID())
		}
	}

	return err
}
1153257
func (p *prober) RunLoop() {
	// FIXME: Spread the probes out across the probing interval
	p.Pinger.RunLoop()

	go func() {
		tick := time.NewTicker(p.server.ProbeInterval)
	loop:
		for {
			select {
			case <-p.stop:
				break loop
			case <-tick.C:
				p.runHTTPProbe()
				continue
			}
		}
		tick.Stop()
		close(p.proberExited)
	}()
}
1141753
func (c *BoundChooser) IsRunning() bool {
	return c.chooserList.IsRunning() && c.updater.IsRunning()
}
154786
func NewTrackerqueryController(service *goa.Service, db application.DB, scheduler *remoteworkitem.Scheduler, configuration trackerQueryConfiguration, authService auth.AuthService) *TrackerqueryController {
	return &TrackerqueryController{
		Controller:    service.NewController("TrackerqueryController"),
		db:            db,
		scheduler:     scheduler,
		configuration: configuration,
		authService:   authService,
	}
}
937581
func (g *Gui) MainLoop() error {
	go func() {
		for {
			g.tbEvents <- termbox.PollEvent()
		}
	}()

	inputMode := termbox.InputAlt
	if g.InputEsc {
		inputMode = termbox.InputEsc
	}
	if g.Mouse {
		inputMode |= termbox.InputMouse
	}
	termbox.SetInputMode(inputMode)

	if err := g.flush(); err != nil {
		return err
	}
	for {
		select {
		case ev := <-g.tbEvents:
			if err := g.handleEvent(&ev); err != nil {
				return err
			}
		case ev := <-g.userEvents:
			if err := ev.f(g); err != nil {
				return err
			}
		}
		if err := g.consumeevents(); err != nil {
			return err
		}
		if err := g.flush(); err != nil {
			return err
		}
	}
}
1152299
func (d *MasterDaemon) agentDiscoveryLoop() {

	// Create channels for watch thread
	agentEventCh := make(chan objdb.WatchServiceEvent, 1)
	watchStopCh := make(chan bool, 1)

	// Start a watch on netplugin service
	err := d.objdbClient.WatchService("netplugin", agentEventCh, watchStopCh)
	if err != nil {
		log.Fatalf("Could not start a watch on netplugin service. Err: %v", err)
	}

	for {
		agentEv := <-agentEventCh
		log.Debugf("Received netplugin watch event: %+v", agentEv)
		// build host info
		nodeInfo := ofnet.OfnetNode{
			HostAddr: agentEv.ServiceInfo.HostAddr,
			HostPort: uint16(agentEv.ServiceInfo.Port),
		}

		if agentEv.EventType == objdb.WatchServiceEventAdd {
			err = d.ofnetMaster.AddNode(nodeInfo)
			if err != nil {
				log.Errorf("Error adding node %v. Err: %v", nodeInfo, err)
			}
		} else if agentEv.EventType == objdb.WatchServiceEventDel {
			var res bool
			log.Infof("Unregister node %+v", nodeInfo)
			d.ofnetMaster.UnRegisterNode(&nodeInfo, &res)

			go d.startDeferredCleanup(nodeInfo, agentEv.ServiceInfo.Hostname)
		}

		// Dont process next peer event for another 100ms
		time.Sleep(100 * time.Millisecond)
	}
}
1053066
func timerLoop(api APIClient, requestedId string, wait, tick *time.Timer) (params.ActionResult, error) {
	var (
		result params.ActionResult
		err    error
	)

	// Loop over results until we get "failed" or "completed".  Wait for
	// timer, and reset it each time.
	for {
		result, err = fetchResult(api, requestedId)
		if err != nil {
			return result, err
		}

		// Whether or not we're waiting for a result, if a completed
		// result arrives, we're done.
		switch result.Status {
		case params.ActionRunning, params.ActionPending:
		default:
			return result, nil
		}

		// Block until a tick happens, or the timeout arrives.
		select {
		case _ = <-wait.C:
			return result, nil

		case _ = <-tick.C:
			tick.Reset(2 * time.Second)
		}
	}
}
394254
func (g *gossipRegistry) connectLoop() {
	// try every second
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-g.done:
			return
		case <-g.options.Context.Done():
			g.Stop()
			return
		case <-ticker.C:
			var addrs []string

			g.RLock()

			// only process if we have a memberlist
			if g.member == nil {
				g.RUnlock()
				continue
			}

			// self
			local := g.member.LocalNode().Address()

			// operate on each member
			for node, action := range g.members {
				switch action {
				// process leave event
				case nodeActionLeave:
					// don't process self
					if node == local {
						continue
					}
					addrs = append(addrs, node)
				}
			}

			g.RUnlock()

			// connect to all the members
			// TODO: only connect to new members
			if len(addrs) > 0 {
				g.connect(addrs)
			}
		}
	}
}
435681
func (m *Monitor) recalculateNetworkUptimeLoop() {
	for {
		select {
		case <-m.monitorQuit:
			return
		case <-time.After(m.recalculateNetworkUptimeEvery):
			m.Network.RecalculateUptime()
		}
	}
}
484163
func (s *Server) mainloop() {
	if s.ipv4conn != nil {
		go s.recv(s.ipv4conn)
	}
	if s.ipv6conn != nil {
		go s.recv(s.ipv6conn)
	}
}
461957
func (a *AllocGarbageCollector) Run() {
	ticker := time.NewTicker(a.config.Interval)
	for {
		select {
		case <-a.triggerCh:
		case <-ticker.C:
		case <-a.shutdownCh:
			ticker.Stop()
			return
		}

		if err := a.keepUsageBelowThreshold(); err != nil {
			a.logger.Error("error garbage collecting allocations", "error", err)
		}
	}
}
1230836
func (b *stdBackend) backendLoop(l loop.Loop) error {
	// Init the monitor.
	b.init()
	// Run loop.
	for {
		select {
		case <-l.ShallStop():
			return nil
		case measuring := <-b.measuringC:
			// Received a new measuring.
			if mp, ok := b.etmData[measuring.id]; ok {
				mp.update(measuring)
			} else {
				b.etmData[measuring.id] = newStdMeasuringPoint(measuring)
			}
		case ssvChange := <-b.ssvChangeC:
			// Received a new change.
			if ssv, ok := b.ssvData[ssvChange.id]; ok {
				ssv.update(ssvChange)
			} else {
				b.ssvData[ssvChange.id] = newStdStaySetVariable(ssvChange)
			}
		case registration := <-b.retrieverRegistrationC:
			// Received a new retriever for registration.
			b.dsrData[registration.id] = registration.dsr
		case cmd := <-b.commandC:
			// Received a command to process.
			b.processCommand(cmd)
		}
	}
}
822495
func (ad *applicationData) watchLoop(exposed bool) error {
	appWatcher, err := ad.application.Watch()
	if err != nil {
		if params.IsCodeNotFound(err) {
			return nil
		}
		return errors.Trace(err)
	}
	if err := ad.catacomb.Add(appWatcher); err != nil {
		return errors.Trace(err)
	}
	for {
		select {
		case <-ad.catacomb.Dying():
			return ad.catacomb.ErrDying()
		case _, ok := <-appWatcher.Changes():
			if !ok {
				return errors.New("application watcher closed")
			}
			change, err := ad.application.IsExposed()
			if err != nil {
				if errors.IsNotFound(err) {
					logger.Debugf("application(%q).IsExposed() returned NotFound: %v", ad.application.Name(), err)
					return nil
				}
				return errors.Trace(err)
			}
			if change == exposed {
				logger.Tracef("application(%q).IsExposed() == %v (unchanged)", ad.application.Name(), exposed)
				continue
			}
			logger.Tracef("application(%q).IsExposed() changed %v => %v", ad.application.Name(), exposed, change)

			exposed = change
			select {
			case <-ad.catacomb.Dying():
				return ad.catacomb.ErrDying()
			case ad.fw.exposedChange <- &exposedChange{ad, change}:
			}
		}
	}
}
1133485
func eventLoop(ctx context.Context, config Config, eventDecoder encoding.Decoder) (err error) {
	for err == nil {
		select {
		case <-ctx.Done():
			err = ctx.Err()
			return
		default:
		}

		var e scheduler.Event
		if err = eventDecoder.Decode(&e); err != nil {
			return
		}

		err = config.handler.HandleEvent(ctx, &e)
	}
	return
}