// run is a long running goroutine that scans for new hosts periodically
190782
func (m *AgentMDNS) run() {
	hosts := make(chan *mdns.ServiceEntry, 32)
	poll := time.After(0)
	var quiet <-chan time.Time
	var join []string

	for {
		select {
		case h := <-hosts:
			// Format the host address
			addr := net.TCPAddr{IP: h.Addr, Port: h.Port}
			addrS := addr.String()

			// Skip if we've handled this host already
			if _, ok := m.seen[addrS]; ok {
				continue
			}

			// Queue for handling
			join = append(join, addrS)
			quiet = time.After(mdnsQuietInterval)

		case <-quiet:
			// Attempt the join
			n, err := m.agent.Join(join, m.replay)
			if err != nil {
				m.logger.Printf("[ERR] agent.mdns: Failed to join: %v", err)
			}
			if n > 0 {
				m.logger.Printf("[INFO] agent.mdns: Joined %d hosts", n)
			}

			// Mark all as seen
			for _, n := range join {
				m.seen[n] = struct{}{}
			}
			join = nil

		case <-poll:
			poll = time.After(mdnsPollInterval)
			go m.poll(hosts)
		}
	}
}
352114
func (s *Scheduler) Run(ctx context.Context) error {
	go func(s *Scheduler, ctx context.Context) {
		for {
			select {
			case <-ctx.Done():
				return
			case <-time.After(s.Interval): // TODO: change to ticker because of garbage collection
				s.gather <- struct{}{}
			}
		}
	}(s, ctx)
	return s.run(ctx)
}
306498
func Run(apps map[string]interface{}, port string) {
	router := mux.NewRouter()
	initialize(apps, router)

	n := negroni.Classic()
	n.UseHandler(router)
	n.Run(":" + port)
}
304597
func (ds *RemoteCache) Run(ctx context.Context) error {
	//create new interface if more clients need GC jobs
	backgroundjob, ok := ds.client.(registry.BackgroundService)
	if ok {
		return backgroundjob.Run(ctx)
	}

	<-ctx.Done()
	return ctx.Err()
}
1164276
func (c *AddPhysicalHostCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
	ctx := cli.GetContext(app, c, env)
	// TODO(smut): Validate required fields client-side.
	req := &crimson.CreatePhysicalHostRequest{
		Host: &c.host,
	}
	client := getClient(ctx)
	resp, err := client.CreatePhysicalHost(ctx, req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printPhysicalHosts(c.f.tsv, resp)
	return 0
}
1305136
func (s *Scheduler) Run() {
	s.mu.Lock()
	s.state = stateRunning
	s.mu.Unlock()

	s.startProcessRequestsLoop()
}
246174
func (m *Manager) Run() {
	m.lock.Lock()
	if m.runState != managerStateIdle {
		m.lock.Unlock()
		return
	}

	// Set the state to running
	m.runState = managerStateRunning
	m.lock.Unlock()

	// Start a goroutine that just waits for a stop request
	stopCh := make(chan struct{})
	go func() {
		defer close(stopCh)
		m.lock.Lock()
		defer m.lock.Unlock()

		// We wait for anything not running, just so we're more resilient
		// in the face of state machine issues. Basically any state change
		// will cause us to quit.
		for m.runState == managerStateRunning {
			m.cond.Wait()
		}
	}()

	// When we exit, we set the state to stopped and broadcast to any
	// waiting Close functions that they can return.
	defer func() {
		m.lock.Lock()
		m.runState = managerStateStopped
		m.cond.Broadcast()
		m.lock.Unlock()
	}()

	// Register for proxy catalog change notifications
	notifyCh := make(chan struct{}, 1)
	m.State.NotifyProxy(notifyCh)
	defer m.State.StopNotifyProxy(notifyCh)

	// Start the timer for snapshots. We don't use a ticker because disk
	// IO can be slow and we don't want overlapping notifications. So we only
	// reset the timer once the snapshot is complete rather than continuously.
	snapshotTimer := time.NewTimer(m.SnapshotPeriod)
	defer snapshotTimer.Stop()

	m.Logger.Println("[DEBUG] agent/proxy: managed Connect proxy manager started")
SYNC:
	for {
		// Sync first, before waiting on further notifications so that
		// we can start with a known-current state.
		m.sync()

		// Note for these variables we don't use a time.Timer because both
		// periods are relatively short anyways so they end up being eligible
		// for GC very quickly, so overhead is not a concern.
		var quiescent, quantum <-chan time.Time

		// Start a loop waiting for events from the local state store. This
		// loops rather than just `select` so we can coalesce many state
		// updates over a period of time.
		for {
			select {
			case <-notifyCh:
				// If this is our first notification since the last sync,
				// reset the quantum timer which is the max time we'll wait.
				if quantum == nil {
					quantum = time.After(m.CoalescePeriod)
				}

				// Always reset the quiescent timer
				quiescent = time.After(m.QuiescentPeriod)

			case <-quantum:
				continue SYNC

			case <-quiescent:
				continue SYNC

			case <-snapshotTimer.C:
				// Perform a snapshot
				if path := m.SnapshotPath(); path != "" {
					if err := m.snapshot(path, true); err != nil {
						m.Logger.Printf("[WARN] agent/proxy: failed to snapshot state: %s", err)
					}
				}

				// Reset
				snapshotTimer.Reset(m.SnapshotPeriod)

			case <-stopCh:
				// Stop immediately, no cleanup
				m.Logger.Println("[DEBUG] agent/proxy: Stopping managed Connect proxy manager")
				return
			}
		}
	}
}
123687
func (s *Server) Run() {
	var err error

	addr := s.config.Get("server.host") + ":" + s.config.Get("server.port")
	log.Printf("Listening on address: %q", addr)

	s.net, err = net.Listen("tcp", addr)
	if err != nil {
		log.Fatal(err)
	}
	defer s.net.Close()

	// Start server ticker
	go s.doTick()

	for !s.working {
		// Wait for a connection.
		conn, err := s.net.Accept()
		if err != nil {
			log.Println(err)
		}

		// Handle the connection in a new goroutine.
		// Multiple connections may be served concurrently.
		go s.handle(conn)
	}
}
110838
func Run(ctx context.Context, network, address string) error {
	l, err := net.Listen(network, address)
	if err != nil {
		return err
	}
	defer func() {
		if err := l.Close(); err != nil {
			glog.Errorf("Failed to close %s %s: %v", network, address, err)
		}
	}()

	s := grpc.NewServer()
	examples.RegisterEchoServiceServer(s, newEchoServer())
	examples.RegisterFlowCombinationServer(s, newFlowCombinationServer())

	abe := newABitOfEverythingServer()
	examples.RegisterABitOfEverythingServiceServer(s, abe)
	examples.RegisterStreamServiceServer(s, abe)
	examples.RegisterResponseBodyServiceServer(s, newResponseBodyServer())

	go func() {
		defer s.GracefulStop()
		<-ctx.Done()
	}()
	return s.Serve(l)
}
4541
func Run() {
	mux := NewServeMux(viper.GetString("static"))
	err := ServeMux(
		mux,
		viper.GetString("addr"),
		viper.GetString("port"),
		viper.GetString("cert"),
		viper.GetString("key"),
	)
	if err != nil {
		log.Println(err)
		return
	}
}
380862
func (u *user) run() {
	done := false
	for !done {
		select {
		case ca := <-u.checkCh:
			u.check(ca)
		case <-u.stopCh:
			u.ca.log.Debug("Stopping user loop for %s", u)
			done = true
		case <-u.ca.shutdownCh:
			done = true
		}
	}
	u.ca.eng.Evicted(u.uid)
}
1041697
func Run(addr string, timeout time.Duration, n http.Handler) {
	srv := &Server{
		Timeout:      timeout,
		TCPKeepAlive: 3 * time.Minute,
		Server:       &http.Server{Addr: addr, Handler: n},
		// Logger:       DefaultLogger(),
	}

	if err := srv.ListenAndServe(); err != nil {
		if opErr, ok := err.(*net.OpError); !ok || (ok && opErr.Op != "accept") {
			srv.logf("%s", err)
			os.Exit(1)
		}
	}

}
887320
func (g *getManifestCmd) run() error {
	res, err := g.client.ReleaseContent(g.release, helm.ContentReleaseVersion(g.version))
	if err != nil {
		return prettyError(err)
	}
	fmt.Fprintln(g.out, res.Release.Manifest)
	return nil
}
1347803
func (s *Server) Run(addr string) error {
	timeout := kGracefulTimeout * time.Second
	if s.debug {
		timeout = 0
	}
	s.srv = &graceful.Server{
		Timeout: timeout,
		Server: &http.Server{
			Addr:    addr,
			Handler: s.router,
		},
	}
	log.Infof("Server is listening on %s", addr)
	return s.srv.ListenAndServe()
}
946759
func (s *Server) Run() error {
	metrics.ServerEventCounter.WithLabelValues(metrics.EventStart).Inc()

	// Start HTTP API to report tidb info such as TPS.
	if s.cfg.Status.ReportStatus {
		s.startStatusHTTP()
	}
	for {
		conn, err := s.listener.Accept()
		if err != nil {
			if opErr, ok := err.(*net.OpError); ok {
				if opErr.Err.Error() == "use of closed network connection" {
					return nil
				}
			}

			// If we got PROXY protocol error, we should continue accept.
			if proxyprotocol.IsProxyProtocolError(err) {
				logutil.Logger(context.Background()).Error("PROXY protocol failed", zap.Error(err))
				continue
			}

			logutil.Logger(context.Background()).Error("accept failed", zap.Error(err))
			return errors.Trace(err)
		}
		if s.shouldStopListener() {
			err = conn.Close()
			terror.Log(errors.Trace(err))
			break
		}

		clientConn := s.newConn(conn)

		err = plugin.ForeachPlugin(plugin.Audit, func(p *plugin.Plugin) error {
			authPlugin := plugin.DeclareAuditManifest(p.Manifest)
			if authPlugin.OnConnectionEvent != nil {
				host, err := clientConn.PeerHost("")
				if err != nil {
					logutil.Logger(context.Background()).Error("get peer host failed", zap.Error(err))
					terror.Log(clientConn.Close())
					return errors.Trace(err)
				}
				err = authPlugin.OnConnectionEvent(context.Background(), &auth.UserIdentity{Hostname: host}, plugin.PreAuth, nil)
				if err != nil {
					logutil.Logger(context.Background()).Info("do connection event failed", zap.Error(err))
					terror.Log(clientConn.Close())
					return errors.Trace(err)
				}
			}
			return nil
		})
		if err != nil {
			continue
		}

		go s.onConn(clientConn)
	}
	err := s.listener.Close()
	terror.Log(errors.Trace(err))
	s.listener = nil
	for {
		metrics.ServerEventCounter.WithLabelValues(metrics.EventHang).Inc()
		logutil.Logger(context.Background()).Error("listener stopped, waiting for manual kill.")
		time.Sleep(time.Minute)
	}
}
676779
func Run(sOpts *Options, nOpts *natsd.Options) (*StanServer, error) {
	return RunServerWithOpts(sOpts, nOpts)
}
1332127
func Run() {
	if Config.Debug {
		gin.SetMode(gin.DebugMode)
		log.SetLevel(log.DebugLevel)
	} else {
		gin.SetMode(gin.ReleaseMode)
		log.SetLevel(log.InfoLevel)
	}

	if Config.MongoLogging {
		mongoURIParsed, _ := url.Parse(Config.MongoURL)

		hooker, err := mgorus.NewHooker(mongoURIParsed.Host, mongoURIParsed.Path[1:], "logs")

		if err == nil {
			log.AddHook(hooker)
		}
	}

	// This will test TG tokens and creates API
	time.Sleep(time.Second * 1)
	initBots()

	for _, s := range services {
		if Config.IsStandAloneServiceInstance() {
			// save the service info as a job to Redis. The MAIN instance will process it
			serviceURL := Config.StandAloneServiceURL
			if serviceURL == "" {
				serviceURL = fmt.Sprintf("http://%s:%s", s.Name, Config.Port)
			}
			_, err := ensureStandAloneServiceJob.Schedule(1, time.Now(), s.Name, serviceURL, s.Bot().tgToken())

			if err != nil {
				log.WithError(err).Panic("ensureStandAloneServiceJob error")
			}
		}
	}

	// Configure
	router := gin.New()

	// register some HTML templates
	templ := template.Must(template.New("webpreview").Parse(htmlTemplateWebpreview))
	template.Must(templ.New("determineTZ").Parse(htmlTemplateDetermineTZ))

	router.SetHTMLTemplate(templ)

	// Middlewares
	router.Use(cloneMiddleware)
	router.Use(ginRecovery)
	router.Use(ginLogger)

	if Config.Debug {
		router.Use(gin.Logger())
	}

	if Config.IsMainInstance() || Config.IsSingleProcessInstance() {
		router.StaticFile("/", "index.html")
	}

	router.NoRoute(func(c *gin.Context) {
		// todo: good 404
		if len(c.Request.RequestURI) > 10 && (c.Request.RequestURI[1:2] == "c" || c.Request.RequestURI[1:2] == "u" || c.Request.RequestURI[1:2] == "h") {
			c.String(404, "Hi here!! This link isn't working in a browser. Please follow the instructions in the chat")
		}
	})

	/*
		Possible URLs

		Service webhooks:

		token resolving handled by framework:
		/service_name/token
		/token - DEPRECATED, to be removed, auto-detect the service

		token resolving handled by service
		/service_name/service
		/service_name

		OAuth:
		/oauth1/service_name/auth_temp_id – OAuth1 initial redirect

		/auth/service_name - OAuth2 redirect URL
		/auth/service_name/provider_id - adds provider_id for the custom OAuth provider (e.g. self-hosted instance)


		WebPreview resolving:
		/a/token
	*/

	router.HEAD("/:param1/:param2/:param3", serviceHookHandler)
	router.GET("/:param1/:param2/:param3", serviceHookHandler)
	router.POST("/:param1/:param2/:param3", serviceHookHandler)

	router.HEAD("/:param1/:param2", serviceHookHandler)
	router.GET("/:param1/:param2", serviceHookHandler)
	router.POST("/:param1/:param2", serviceHookHandler)

	router.HEAD("/:param1", serviceHookHandler)
	router.GET("/:param1", serviceHookHandler)
	router.POST("/:param1", serviceHookHandler)

	// Start listening

	var err error

	go gracefulShutdownJobPools()

	if Config.Port == "443" || Config.Port == "1443" {
		if _, err := os.Stat(Config.ConfigDir + string(os.PathSeparator) + "ssl.crt"); !os.IsNotExist(err) {
			log.Infof("SSL: Using ssl.key/ssl.crt")
			err = router.RunTLS(":"+Config.Port, Config.ConfigDir+string(os.PathSeparator)+"ssl.crt", Config.ConfigDir+string(os.PathSeparator)+"ssl.key")
		} else {
			log.Fatalf("INTEGRAM_PORT set to 443, but ssl.crt and ssl.key files not found at '%s'", Config.ConfigDir)
		}

	} else {
		if Config.IsMainInstance() || Config.IsSingleProcessInstance() {
			log.Warnf("WARNING! It is recommended to use Integram with a SSL.\n"+
				"Set the INTEGRAM_PORT to 443 and put integram.crt & integram.key files at '%s'", Config.ConfigDir)
		}
		err = router.Run(":" + Config.Port)
	}

	if err != nil {
		log.WithError(err).Fatal("Can't start the router")
	}
}