// Run the Consul main loop which retries operations against Consul. It should
// be called exactly once.
551508
func (c *ServiceClient) Run() {
	defer close(c.exitCh)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// init will be closed when Consul has been contacted
	init := make(chan struct{})
	go checkConsulTLSSkipVerify(ctx, c.logger, c.client, init)

	// Process operations while waiting for initial contact with Consul but
	// do not sync until contact has been made.
INIT:
	for {
		select {
		case <-init:
			c.markSeen()
			break INIT
		case <-c.shutdownCh:
			return
		case ops := <-c.opCh:
			c.merge(ops)
		}
	}
	c.logger.Trace("able to contact Consul")

	// Block until contact with Consul has been established
	// Start checkWatcher
	go c.checkWatcher.Run(ctx)

	// Always immediately sync to reconcile Nomad and Consul's state
	retryTimer := time.NewTimer(0)

	failures := 0
	for {
		select {
		case <-retryTimer.C:
		case <-c.shutdownCh:
			// Cancel check watcher but sync one last time
			cancel()
		case ops := <-c.opCh:
			c.merge(ops)
		}

		if err := c.sync(); err != nil {
			if failures == 0 {
				// Log on the first failure
				c.logger.Warn("failed to update services in Consul", "error", err)
			} else if failures%10 == 0 {
				// Log every 10th consecutive failure
				c.logger.Error("still unable to update services in Consul", "failures", failures, "error", err)
			}

			failures++
			if !retryTimer.Stop() {
				// Timer already expired, since the timer may
				// or may not have been read in the select{}
				// above, conditionally receive on it
				select {
				case <-retryTimer.C:
				default:
				}
			}
			backoff := c.retryInterval * time.Duration(failures)
			if backoff > c.maxRetryInterval {
				backoff = c.maxRetryInterval
			}
			retryTimer.Reset(backoff)
		} else {
			if failures > 0 {
				c.logger.Info("successfully updated services in Consul")
				failures = 0
			}

			// Reset timer to periodic interval to periodically
			// reconile with Consul
			if !retryTimer.Stop() {
				select {
				case <-retryTimer.C:
				default:
				}
			}
			retryTimer.Reset(c.periodicInterval)
		}

		select {
		case <-c.shutdownCh:
			// Exit only after sync'ing all outstanding operations
			if len(c.opCh) > 0 {
				for len(c.opCh) > 0 {
					c.merge(<-c.opCh)
				}
				continue
			}
			return
		default:
		}

	}
}
12264
func (c *CloudNodeLifecycleController) Run(stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()

	// The following loops run communicate with the APIServer with a worst case complexity
	// of O(num_nodes) per cycle. These functions are justified here because these events fire
	// very infrequently. DO NOT MODIFY this to perform frequent operations.

	// Start a loop to periodically check if any nodes have been
	// deleted or shutdown from the cloudprovider
	wait.Until(c.MonitorNodes, c.nodeMonitorPeriod, stopCh)
}
561522
func (d *DockerDiscovery) Run(looper director.Looper) {
	connQuitChan := make(chan bool)

	go d.manageConnection(connQuitChan)

	go func() {
		// Loop around, process any events which came in, and
		// periodically fetch the whole container list
		looper.Loop(func() error {
			select {
			case event := <-d.events:
				if event == nil {
					// This usually happens because of a Docker restart.
					// Sleep, let us reconnect in the background, then loop.
					return nil
				}
				log.Debugf("Event: %#v\n", event)
				d.handleEvent(*event)
			case <-time.After(d.sleepInterval):
				d.getContainers()
			case <-time.After(CacheDrainInterval):
				d.containerCache.Drain(len(d.services))
			}

			return nil
		})

		// Propagate quit channel message
		close(connQuitChan)
	}()
}
84853
func main() {
	logger.Level = golog.INFO

	app.Version("1.0.2")

	// install dependencies
	outputCmd("go", []string{"get", "github.com/ivpusic/rerun"})

	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case run.FullCommand():
		handleRunCommand()
	case newCmd.FullCommand():
		handleNewCommand()
	default:
		app.Usage(os.Stdout)
	}
}
1153379
func (r *reporter) run() {
	// signal that the reporter loop is done
	defer close(r.done)

	intervalTicker := time.NewTicker(r.interval)

	for {
		select {
		case <-intervalTicker.C:
			//at each tick send the metrics
			if err := r.save(); err != nil {
				log.Error("unable to send metrics to LevelDB", "err", err)
				//If there is an error in writing, exit the routine; we assume here that the error is
				//severe and don't attempt to write again.
				//Also, this should prevent leaking when the node is stopped
				return
			}
		case <-r.quit:
			//graceful shutdown
			if err := r.save(); err != nil {
				log.Error("unable to send metrics to LevelDB", "err", err)
			}
			return
		}
	}
}
239945
func (m *Monitor) Run(looper director.Looper) {
	looper.Loop(func() error {
		log.Debugf("Running checks")

		var wg sync.WaitGroup

		// Make immutable copy of m.Checks (checks are still mutable)
		m.RLock()
		checks := make(map[string]*Check, len(m.Checks))
		for k, v := range m.Checks {
			checks[k] = v
		}
		m.RUnlock()

		wg.Add(len(checks))
		for _, check := range checks {
			// Run all checks in parallel in goroutines
			resultChan := make(chan checkResult, 1)

			go func(check *Check, resultChan chan checkResult) {
				result, err := check.Command.Run(check.Args)
				resultChan <- checkResult{result, err}
			}(check, resultChan) // copy check pointer for the goroutine

			go func(check *Check, resultChan chan checkResult) {
				defer wg.Done()

				// We make the call but we time out if it gets too close to the
				// m.CheckInterval.
				select {
				case result := <-resultChan:
					check.UpdateStatus(result.status, result.err)
				case <-time.After(m.CheckInterval - 1*time.Millisecond):
					log.Errorf("Error, check %s timed out! (%v)", check.ID, check.Args)
					check.UpdateStatus(UNKNOWN, errors.New("Timed out!"))
				}
			}(check, resultChan) // copy check pointer for the goroutine
		}

		// Let's make sure we don't continue to spool up
		// huge quantities of goroutines. Wait on all of them
		// to complete before moving on. This could slow down
		// our check loop if something doesn't time out properly.
		wg.Wait()

		return nil
	})
}
806956
func Run(ctx context.Context, cfg Config, newTeleport NewProcess) error {
	if newTeleport == nil {
		newTeleport = newTeleportProcess
	}
	copyCfg := cfg
	srv, err := newTeleport(&copyCfg)
	if err != nil {
		return trace.Wrap(err, "initialization failed")
	}
	if srv == nil {
		return trace.BadParameter("process has returned nil server")
	}
	if err := srv.Start(); err != nil {
		return trace.Wrap(err, "startup failed")
	}
	// Wait and reload until called exit.
	for {
		srv, err = waitAndReload(ctx, cfg, srv, newTeleport)
		if err != nil {
			// This error means that was a clean shutdown
			// and no reload is necessary.
			if err == ErrTeleportExited {
				return nil
			}
			return trace.Wrap(err)
		}
	}
}
801846
func Run() error {
	if service.Registry != nil {
		service.Registry.Register(service)
	}

	// Start a metrics server in the background
	startPrometheusServer()

	// Create and then server a gRPC server
	err := ServeGRPC()
	if service.Registry != nil {
		service.Registry.DeRegister(service)
	}
	return err
}
362977
func (l *LinuxMonitor) Run(ctx context.Context) error {

	if err := l.proc.config.IsComplete(); err != nil {
		return fmt.Errorf("linux %t: %s", l.proc.host, err)
	}

	return l.Resync(ctx)
}
1068337
func (u *DropsondeUnmarshallerCollection) Run(inputChan <-chan []byte, outputChan chan<- *events.Envelope, waitGroup *sync.WaitGroup) {
	for _, unmarshaller := range u.unmarshallers {
		go func(um *DropsondeUnmarshaller) {
			defer waitGroup.Done()
			um.Run(inputChan, outputChan)
		}(unmarshaller)
	}
}
426804
func Execute(args ...string) int {
	cli := &cli.CLI{
		Args:     args,
		Commands: Commands,
		HelpFunc: cli.BasicHelpFunc("consul"),
	}

	exitCode, err := cli.Run()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error executing CLI: %s\n", err.Error())
		return 1
	}

	return exitCode
}
1050930
func (o *Organizer) Run() {
	if o.only != nil {
		o.runTest(o.only)
		return
	}

	for _, test := range o.tests {
		o.runTest(&test)
	}
}
408192
func (m *Mux) Run(phase string, ctx *c.Context) *c.Context {
	return m.Middleware.Run(phase, ctx)
}
1027860
func (ce *ContainerEndpoints) Run(cancel <-chan struct{}) {

	// register all of the exports
	for _, bind := range ce.state.Exports {
		ce.ports[bind.PortNumber] = struct{}{}
		go ce.AddExport(cancel, bind)
	}

	// track all of the imports
	// TODO: set up another tracker for cc exports
	go ce.RunImportListener(cancel, ce.opts.TenantID, ce.state.Imports...)
}
927195
func (s *sender) run() {
	var q queue // q is nil initially as we have no credit.
	for {
		select {
		case _, ok := <-s.credit:
			if !ok { // sender closed
				return
			}
			q = s.q // We have credit, enable selecting on the queue.

		case m, ok := <-q: // q is only enabled when we have credit.
			if !ok { // queue closed
				return
			}
			q = nil                      // Assume all credit will be used used, will be signaled otherwise.
			s.h.injecter.Inject(func() { // Inject handler function to actually send
				if s.h.senders[s.l] != s { // The sender has been closed by the remote end.
					q.PutBack(m) // Put the message back on the queue but don't block
					return
				}
				if s.sendOne(m) != nil {
					return
				}
				// Send as many more messages as we can without blocking
				for s.l.Credit() > 0 {
					select { // Non blocking receive from q
					case m, ok := <-s.q:
						if ok {
							s.sendOne(m)
						}
					default: // Queue is empty but we have credit, signal the run() goroutine.
						s.sendable()
					}
				}
			})
		}
	}
}
597361
func (d *StaticDiscovery) Run(looper director.Looper) {
	var err error

	d.Targets, err = d.ParseConfig(d.ConfigFile)
	if err != nil {
		log.Errorf("StaticDiscovery cannot parse: %s", err.Error())
		looper.Done(nil)
	}
}
605744
func (c *ClusterQuotaReconcilationController) Run(workers int, stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()

	klog.Infof("Starting the cluster quota reconciliation controller")

	// the controllers that replenish other resources to respond rapidly to state changes
	go c.quotaMonitor.Run(stopCh)

	if !controller.WaitForCacheSync("cluster resource quota", stopCh, c.informerSyncedFuncs...) {
		return
	}

	// the workers that chug through the quota calculation backlog
	for i := 0; i < workers; i++ {
		go wait.Until(c.worker, time.Second, stopCh)
	}

	// the timer for how often we do a full recalculation across all quotas
	go wait.Until(func() { c.calculateAll() }, c.resyncPeriod, stopCh)

	<-stopCh
	klog.Infof("Shutting down ClusterQuotaReconcilationController")
	c.queue.ShutDown()
}