// leaderLoop runs as long as we are the leader to run various
// maintenance activities
328794
func (s *Server) leaderLoop(stopCh chan struct{}) {
	var reconcileCh chan serf.Member
	establishedLeader := false

RECONCILE:
	// Setup a reconciliation timer
	reconcileCh = nil
	interval := time.After(s.config.ReconcileInterval)

	// Apply a raft barrier to ensure our FSM is caught up
	start := time.Now()
	barrier := s.raft.Barrier(barrierWriteTimeout)
	if err := barrier.Error(); err != nil {
		s.logger.Error("failed to wait for barrier", "error", err)
		goto WAIT
	}
	metrics.MeasureSince([]string{"nomad", "leader", "barrier"}, start)

	// Check if we need to handle initial leadership actions
	if !establishedLeader {
		if err := s.establishLeadership(stopCh); err != nil {
			s.logger.Error("failed to establish leadership", "error", err)

			// Immediately revoke leadership since we didn't successfully
			// establish leadership.
			if err := s.revokeLeadership(); err != nil {
				s.logger.Error("failed to revoke leadership", "error", err)
			}

			goto WAIT
		}

		establishedLeader = true
		defer func() {
			if err := s.revokeLeadership(); err != nil {
				s.logger.Error("failed to revoke leadership", "error", err)
			}
		}()
	}

	// Reconcile any missing data
	if err := s.reconcile(); err != nil {
		s.logger.Error("failed to reconcile", "error", err)
		goto WAIT
	}

	// Initial reconcile worked, now we can process the channel
	// updates
	reconcileCh = s.reconcileCh

	// Poll the stop channel to give it priority so we don't waste time
	// trying to perform the other operations if we have been asked to shut
	// down.
	select {
	case <-stopCh:
		return
	default:
	}

WAIT:
	// Wait until leadership is lost
	for {
		select {
		case <-stopCh:
			return
		case <-s.shutdownCh:
			return
		case <-interval:
			goto RECONCILE
		case member := <-reconcileCh:
			s.reconcileMember(member)
		}
	}
}
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)
		}
	}
}
809352
func (rtm *Client) pingLoop() {
	var err error
	for rtm.connected {
		time.Sleep(rtm.pingInterval)
		err = rtm.doPing()
		if err != nil {
			rtm.logf("go-slack :: pingLook() :: error => %v", err)
		}
	}
}
282606
func (s *Session) recvLoop() error {
	defer close(s.recvDoneCh)
	hdr := header(make([]byte, headerSize))
	for {
		// Read the header
		if _, err := io.ReadFull(s.bufRead, hdr); err != nil {
			if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") {
				s.logger.Printf("[ERR] yamux: Failed to read header: %v", err)
			}
			return err
		}

		// Verify the version
		if hdr.Version() != protoVersion {
			s.logger.Printf("[ERR] yamux: Invalid protocol version: %d", hdr.Version())
			return ErrInvalidVersion
		}

		mt := hdr.MsgType()
		if mt < typeData || mt > typeGoAway {
			return ErrInvalidMsgType
		}

		if err := handlers[mt](s, hdr); err != nil {
			return err
		}
	}
}
822863
func (p *Pool) queryLoop() error {
	if err := p.sendNextJobs(p.config.BatchSize); err != nil {
		return err
	}
	for {
		minWait := time.After(p.config.MinWait)
		select {
		case <-p.exit:
			// Close the channel to tell workers to stop executing new jobs
			close(p.jobs)
			return nil
		case <-minWait:
			if err := p.sendNextJobs(p.config.BatchSize); err != nil {
				return err
			}
		}
	}
	return nil
}
152477
func (j *JournalManager) FinishSingleOp(ctx context.Context, tlfID tlf.ID,
	lc *keybase1.LockContext, priority keybase1.MDPriority) (err error) {
	j.log.CDebugf(ctx, "Finishing single op for %s", tlfID)
	if tlfJournal, ok := j.getTLFJournal(tlfID, nil); ok {
		return tlfJournal.finishSingleOp(ctx, lc, priority)
	}

	j.log.CDebugf(ctx, "Journal not enabled for %s", tlfID)
	return nil
}
1257705
func (conn *Conn) runLoop() {
	defer conn.wg.Done()
	for {
		select {
		case line := <-conn.in:
			conn.dispatch(line)
		case <-conn.die:
			// control channel closed, bail out
			return
		}
	}
}
335043
func (s *Server) monitorLeadership() {
	var weAreLeaderCh chan struct{}
	var leaderLoop sync.WaitGroup
	for {
		select {
		case isLeader := <-s.leaderCh:
			switch {
			case isLeader:
				if weAreLeaderCh != nil {
					s.logger.Error("attempted to start the leader loop while running")
					continue
				}

				weAreLeaderCh = make(chan struct{})
				leaderLoop.Add(1)
				go func(ch chan struct{}) {
					defer leaderLoop.Done()
					s.leaderLoop(ch)
				}(weAreLeaderCh)
				s.logger.Info("cluster leadership acquired")

			default:
				if weAreLeaderCh == nil {
					s.logger.Error("attempted to stop the leader loop while not running")
					continue
				}

				s.logger.Debug("shutting down leader loop")
				close(weAreLeaderCh)
				leaderLoop.Wait()
				weAreLeaderCh = nil
				s.logger.Info("cluster leadership lost")
			}

		case <-s.shutdownCh:
			return
		}
	}
}
959397
func RunLoop(netplugin *plugin.NetPlugin, ctrlIP, vtepIP, hostname string) error {
	// Register ourselves
	err := registerService(ObjdbClient, ctrlIP, vtepIP, hostname, netplugin.PluginConfig.Instance.VxlanUDPPort)

	// Start peer discovery loop
	go peerDiscoveryLoop(netplugin, ObjdbClient, ctrlIP, vtepIP)

	return err
}
448252
func DoLeaderElection(ctx context.Context, logger *zap.Logger, component string, config LeaderElectionOptions, configMapsGetter core_v1client.ConfigMapsGetter, recorder record.EventRecorder) (context.Context, error) {
	id, err := os.Hostname()
	if err != nil {
		return nil, err
	}
	ctxRet, cancel := context.WithCancel(ctx)
	startedLeading := make(chan struct{})
	le, err := leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{
		Lock: &resourcelock.ConfigMapLock{
			ConfigMapMeta: meta_v1.ObjectMeta{
				Namespace: config.ConfigMapNamespace,
				Name:      config.ConfigMapName,
			},
			Client: configMapsGetter,
			LockConfig: resourcelock.ResourceLockConfig{
				Identity:      id + "-" + component,
				EventRecorder: recorder,
			},
		},
		LeaseDuration: config.LeaseDuration,
		RenewDeadline: config.RenewDeadline,
		RetryPeriod:   config.RetryPeriod,
		Callbacks: leaderelection.LeaderCallbacks{
			OnStartedLeading: func(ctx context.Context) {
				logger.Info("Started leading")
				close(startedLeading)
			},
			OnStoppedLeading: func() {
				logger.Info("Leader status lost")
				cancel()
			},
		},
	})
	if err != nil {
		cancel()
		return nil, err
	}
	go func() {
		// note: because le.Run() also adds a logging panic handler panics with be logged 3 times
		defer logz.LogStructuredPanic()
		le.Run(ctx)
	}()
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case <-startedLeading:
		return ctxRet, nil
	}
}
20439
func (ec *ServiceManager) eventLoop() (err error) {
	// Run event loop
	for {
		// Await event on global channel
		event, open := <-ec.in

		if open {
			// Dispatch to bound services
			for _, s := range ec.services {
				s.SendEvent(event)
			}
		} else {
			// Close service channels
			for _, s := range ec.services {
				s.Exit()
			}
			break
		}
	}
	return nil
}
484163
func (s *Server) mainloop() {
	if s.ipv4conn != nil {
		go s.recv(s.ipv4conn)
	}
	if s.ipv6conn != nil {
		go s.recv(s.ipv6conn)
	}
}
134751
func (d *MasterDaemon) runLeader() {
	router := mux.NewRouter()

	// Create a new api controller
	apiConfig := &objApi.APIControllerConfig{
		NetForwardMode: d.NetForwardMode,
		NetInfraType:   d.NetInfraType,
	}
	d.apiController = objApi.NewAPIController(router, d.objdbClient, apiConfig)

	//Restore state from clusterStore
	d.restoreCache()

	// Register netmaster service
	d.registerService()

	// initialize policy manager
	mastercfg.InitPolicyMgr(d.stateDriver, d.ofnetMaster)

	// setup HTTP routes
	d.registerRoutes(router)

	d.startListeners(router, d.stopLeaderChan)

	log.Infof("Exiting Leader mode")
}
1036161
func (s *scheduler) mainloop(conn coordclient.Connection) {
	// become the leader
	leader, err := conn.NewLeader("/scheduler")
	if err != nil {
		glog.Errorf("Could not initialize leader node for scheduler: %s", err)
		return
	}
	leaderDone := make(chan struct{})
	defer close(leaderDone)
	event, err := leader.TakeLead(&zzk.HostLeader{HostID: s.instance_id, Realm: s.realm}, leaderDone)
	if err != nil {
		glog.Errorf("Could not become the leader: %s", err)
		return
	}
	defer leader.ReleaseLead()

	// did I shut down before I became the leader?
	select {
	case <-s.shutdown:
		return
	default:
	}

	var wg sync.WaitGroup
	defer wg.Wait()

	_shutdown := make(chan interface{})
	defer close(_shutdown)

	stopped := make(chan struct{}, 2)

	// ensure all the services are unlocked
	glog.Infof("Resetting service locks")
	locker := s.facade.DFSLock(datastore.Get())
	locker.Lock("reset service locks")
	if err := s.facade.ResetLocks(datastore.Get()); err != nil {
		glog.Errorf("Could not reset dfs locks: %s", err)
		return
	}
	locker.Unlock()
	glog.Infof("DFS locks are all reset")

	// start the storage server
	wg.Add(1)
	go func() {
		defer glog.Infof("Stopping storage sync")
		defer wg.Done()
		if err := s.storageServer.Run(_shutdown, conn); err != nil {
			glog.Errorf("Could not maintain storage lead: %s", err)
			stopped <- struct{}{}
		}
	}()

	// synchronize locally
	wg.Add(1)
	go func() {
		defer glog.Infof("Stopping local sync")
		defer wg.Done()
		s.localSync(_shutdown, conn)
	}()

	wg.Add(1)
	go func() {
		defer glog.Infof("Stopping pool listeners")
		defer wg.Done()
		zzk.Start(_shutdown, conn, s, s.pushreg)
		stopped <- struct{}{}
	}()

	// kicks off the snapshot cleaning goroutine
	if s.snapshotTTL > 0 {
		wg.Add(1)
		go func() {
			defer glog.Infof("Stopping snapshot ttl")
			defer wg.Done()
			ttl.RunSnapshotTTL(s.cpDao, _shutdown, time.Minute, time.Duration(s.snapshotTTL)*time.Hour)
		}()
	}

	// wait for something to happen
	for {
		select {
		case <-event:
			glog.Warningf("Coup d'etat, re-electing...")
			return
		case <-stopped:
			glog.Warningf("Leader died, re-electing...")
			return
		case <-s.shutdown:
			return
		}
	}
}
208029
func (s *Status) Leader(args *structs.GenericRequest, reply *string) error {
	if args.Region == "" {
		args.Region = s.srv.config.Region
	}
	if done, err := s.srv.forward("Status.Leader", args, args, reply); done {
		return err
	}

	leader := string(s.srv.raft.Leader())
	if leader != "" {
		*reply = leader
	} else {
		*reply = ""
	}
	return nil
}
493768
func (orc *orcClient) DiscoverLoop(agent *ActionAgent) {
	if *orcInterval == 0 {
		// 0 means never.
		return
	}
	log.Infof("Starting periodic Orchestrator self-registration: API URL = %v, interval = %v", *orcAddr, *orcInterval)

	// Randomly vary the interval by +/- 25% to reduce the potential for spikes.
	ticker := timer.NewRandTicker(*orcInterval, *orcInterval/4)

	// Remember whether we've most recently succeeded or failed.
	var lastErr error

	for {
		// Do the first attempt immediately.
		err := orc.Discover(agent.Tablet())

		// Only log if we're transitioning between success and failure states.
		if (err != nil) != (lastErr != nil) {
			if err != nil {
				log.Warningf("Orchestrator self-registration attempt failed: %v", err)
			} else {
				log.Infof("Orchestrator self-registration succeeded.")
			}
		}
		lastErr = err

		// Wait for the next tick.
		// The only way to stop the loop is to terminate the process.
		<-ticker.C
	}
}
1027446
func (s *LesServer) startEventLoop() {
	s.protocolManager.wg.Add(1)

	var processing bool
	blockProcFeed := make(chan bool, 100)
	s.protocolManager.blockchain.(*core.BlockChain).SubscribeBlockProcessingEvent(blockProcFeed)
	totalRechargeCh := make(chan uint64, 100)
	totalRecharge := s.costTracker.subscribeTotalRecharge(totalRechargeCh)
	totalCapacityCh := make(chan uint64, 100)
	updateRecharge := func() {
		if processing {
			s.protocolManager.servingQueue.setThreads(s.thcBlockProcessing)
			s.fcManager.SetRechargeCurve(flowcontrol.PieceWiseLinear{{0, 0}, {totalRecharge, totalRecharge}})
		} else {
			s.protocolManager.servingQueue.setThreads(s.thcNormal)
			s.fcManager.SetRechargeCurve(flowcontrol.PieceWiseLinear{{0, 0}, {totalRecharge / 10, totalRecharge}, {totalRecharge, totalRecharge}})
		}
	}
	updateRecharge()
	totalCapacity := s.fcManager.SubscribeTotalCapacity(totalCapacityCh)
	s.priorityClientPool.setLimits(s.maxPeers, totalCapacity)

	go func() {
		for {
			select {
			case processing = <-blockProcFeed:
				updateRecharge()
			case totalRecharge = <-totalRechargeCh:
				updateRecharge()
			case totalCapacity = <-totalCapacityCh:
				s.priorityClientPool.setLimits(s.maxPeers, totalCapacity)
			case <-s.protocolManager.quitSync:
				s.protocolManager.wg.Done()
				return
			}
		}
	}()
}