// RunServer starts a metrics server
767648
func RunServer(ctx context.Context, config PrometheusConfig, registry *prometheus.Registry) {
	mux := http.NewServeMux()
	mux.Handle(config.Path, promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
	srv := &http.Server{Addr: fmt.Sprintf(":%s", config.Port), Handler: mux}

	defer func() {
		if cerr := srv.Close(); cerr != nil {
			log.Fatalf("Encountered an '%s' error when tried to close the metrics server running on '%s'", cerr, config.Port)
		}
	}()

	log.Infof("Starting prometheus metrics server at 0.0.0.0:%s%s", config.Port, config.Path)
	if err := srv.ListenAndServe(); err != nil {
		panic(err)
	}

	<-ctx.Done()
}
416876
func RunHTTPServer() (err error) {
	if !PushConf.Core.Enabled {
		LogAccess.Debug("httpd server is disabled.")
		return nil
	}

	server := &http.Server{
		Addr:    PushConf.Core.Address + ":" + PushConf.Core.Port,
		Handler: routerEngine(),
	}

	LogAccess.Debug("HTTPD server is running on " + PushConf.Core.Port + " port.")
	if PushConf.Core.AutoTLS.Enabled {
		return startServer(autoTLSServer())
	} else if PushConf.Core.SSL {
		config := &tls.Config{
			MinVersion: tls.VersionTLS10,
		}

		if config.NextProtos == nil {
			config.NextProtos = []string{"http/1.1"}
		}

		config.Certificates = make([]tls.Certificate, 1)
		if PushConf.Core.CertPath != "" && PushConf.Core.KeyPath != "" {
			config.Certificates[0], err = tls.LoadX509KeyPair(PushConf.Core.CertPath, PushConf.Core.KeyPath)
			if err != nil {
				LogError.Error("Failed to load https cert file: ", err)
				return err
			}
		} else if PushConf.Core.CertBase64 != "" && PushConf.Core.KeyBase64 != "" {
			cert, err := base64.StdEncoding.DecodeString(PushConf.Core.CertBase64)
			if err != nil {
				LogError.Error("base64 decode error:", err.Error())
				return err
			}
			key, err := base64.StdEncoding.DecodeString(PushConf.Core.KeyBase64)
			if err != nil {
				LogError.Error("base64 decode error:", err.Error())
				return err
			}
			if config.Certificates[0], err = tls.X509KeyPair(cert, key); err != nil {
				LogError.Error("tls key pair error:", err.Error())
				return err
			}
		} else {
			return errors.New("missing https cert config")
		}

		server.TLSConfig = config
	}

	return startServer(server)
}
1350949
func httpServer() http.Handler {
	r := mux.NewRouter()

	// Ping Resource
	r.HandleFunc(clients.ApiPingRoute, pingHandler).Methods(http.MethodGet)

	// Configuration
	r.HandleFunc(clients.ApiConfigRoute, configHandler).Methods(http.MethodGet)

	// Metrics
	r.HandleFunc(clients.ApiMetricsRoute, metricsHandler).Methods(http.MethodGet)

	r.HandleFunc(clients.ApiNotifyRegistrationRoute, replyNotifyRegistrations).Methods(http.MethodPut)

	r.Use(correlation.ManageHeader)
	r.Use(correlation.OnResponseComplete)
	r.Use(correlation.OnRequestBegin)

	return r
}
639504
func StartServer(info ServerInfo, opts ...grpc.ServerOption) func() {
	opts = append(opts, grpc.WriteBufferSize(128*1024))
	opts = append(opts, grpc.ReadBufferSize(128*1024))
	s := grpc.NewServer(opts...)
	switch info.Type {
	case "protobuf":
		testpb.RegisterBenchmarkServiceServer(s, &testServer{})
	case "bytebuf":
		respSize, ok := info.Metadata.(int32)
		if !ok {
			grpclog.Fatalf("failed to StartServer, invalid metadata: %v, for Type: %v", info.Metadata, info.Type)
		}
		testpb.RegisterBenchmarkServiceServer(s, &byteBufServer{respSize: respSize})
	default:
		grpclog.Fatalf("failed to StartServer, unknown Type: %v", info.Type)
	}
	go s.Serve(info.Listener)
	return func() {
		s.Stop()
	}
}
1242532
func (v *vserver) run() {
	statsTicker := time.NewTicker(v.engine.config.StatsInterval)
	for {
		select {
		case <-v.quit:
			// Shutdown active vservers, services and destinations.
			// There is no race between this and new healthcheck
			// notifications, since they are also handled via the
			// same vserver go routine.
			v.downAll()
			statsTicker.Stop()
			v.engine.hcManager.vcc <- vserverChecks{vserverName: v.config.Name}
			v.unconfigureVIPs()

			// Return any firewall marks that were allocated to
			// this vserver.
			for _, fwm := range v.fwm {
				v.engine.fwmAlloc.put(fwm)
			}

			v.stopped <- true
			return

		case o := <-v.overrideChan:
			v.handleOverride(o)
			v.engine.hcManager.vcc <- v.healthchecks()

		case config := <-v.update:
			v.handleConfigUpdate(config)
			v.engine.hcManager.vcc <- v.healthchecks()

		case n := <-v.notify:
			v.handleCheckNotification(n)

		case <-statsTicker.C:
			v.updateStats()
		}

		// Something changed - export a new vserver snapshot.
		// The goroutine that drains v.engine.vserverChan also does a blocking write
		// to each vserver's vserver.notify channel, which is drained by each
		// vserver's goroutine (i.e., this one). So we need a timeout to avoid a
		// deadlock.
		timeout := time.After(1 * time.Second)
		select {
		case v.engine.vserverChan <- v.snapshot():
		case <-timeout:
			log.Warningf("%v: failed to send snapshot", v)
		}
	}
}
905387
func (s *Server) ServeMetrics(l net.Listener) error {
	m := http.NewServeMux()
	m.Handle("/v1/metrics", metrics.Handler())
	return trapClosedConnErr(http.Serve(l, m))
}
178990
func (s *Server) RunScgi(addr string) {
	s.initServer()
	s.Logger.Printf("web.go serving scgi %s\n", addr)
	s.listenAndServeScgi(addr)
}
474679
func (s *Server) RunTLS(addr string, config *tls.Config) error {
	s.initServer()
	mux := http.NewServeMux()
	mux.Handle("/", s)

	l, err := tls.Listen("tcp", addr, config)
	if err != nil {
		log.Fatal("Listen:", err)
		return err
	}
	s.Logger.Printf("web.go serving %s\n", l.Addr())

	s.l = l
	return http.Serve(s.l, mux)
}
854014
func (sl *ServerLookup) Server(addr raft.ServerAddress) *metadata.Server {
	sl.lock.RLock()
	defer sl.lock.RUnlock()
	svr, _ := sl.addressToServer[addr]
	return svr
}
1227850
func (md *metricsDu) runDiskUsage(metrics *Metrics) error {
	used, err := fs.DiskUsage(md.path)
	if err != nil {
		return err
	}
	metrics.Used = used
	return nil
}
260434
func StartServer(cfg abcconfig.ServerConfig, router http.Handler, logger *zap.Logger) error {
	var err error
	server := http.Server{
		ReadTimeout:  cfg.ReadTimeout,
		WriteTimeout: cfg.WriteTimeout,
		IdleTimeout:  cfg.IdleTimeout,
		ErrorLog:     log.New(serverErrLogger{logger}, "", 0),
		Handler:      router,
	}

	server.TLSConfig = &tls.Config{
		// Causes servers to use Go's default ciphersuite preferences,
		// which are tuned to avoid attacks. Does nothing on clients.
		PreferServerCipherSuites: true,
		// Only use curves which have assembly implementations
		CurvePreferences: []tls.CurveID{
			tls.CurveP256,
			tls.X25519, // Go 1.8 only
		},
	}

	// subscribe to SIGINT signals
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)

	// Start server graceful shutdown goroutine
	go func() {
		<-quit
		log.Println("Shutting down server...")
		if err := server.Shutdown(context.Background()); err != nil {
			log.Fatalf("could not shutdown: %v", err)
		}
	}()

	if len(cfg.TLSBind) > 0 {
		logger.Info("starting https listener", zap.String("bind", cfg.TLSBind))
		server.Addr = cfg.TLSBind

		// Redirect http requests to https
		go Redirect(cfg, logger)

		if err := server.ListenAndServeTLS(cfg.TLSCertFile, cfg.TLSKeyFile); err != nil {
			fmt.Printf("failed to ListenAndServeTLS: %v", err)
			return nil
		}
	} else {
		logger.Info("starting http listener", zap.String("bind", cfg.Bind))
		server.Addr = cfg.Bind
		if err := server.ListenAndServe(); err != nil {
			fmt.Printf("failed to ListenAndServe: %v", err)
			return nil
		}
	}

	return errors.Wrap(err, "failed to StartServer")
}
862018
func RunServer(ID string) (*StanServer, error) {
	sOpts := GetDefaultOptions()
	sOpts.ID = ID
	nOpts := DefaultNatsServerOptions
	return RunServerWithOpts(sOpts, &nOpts)
}
35625
func StartServer(addr string, shutdownSignal <-chan struct{}) {
	log.Infof("Starting apiserver on address %s", addr)

	http.HandleFunc("/healthz", healthHandler)

	srv := &http.Server{Addr: addr}

	go func() {
		<-shutdownSignal
		if err := srv.Shutdown(context.Background()); err != nil {
			log.WithError(err).Error("apiserver shutdown")
		}
	}()

	if err := srv.ListenAndServe(); err != nil {
		log.WithError(err).Error("apiserver listen")
	}
}
1287075
func StartHTTPServer(listener net.Listener, handler http.Handler, logger log.Logger, config *Config) error {
	logger.Info(fmt.Sprintf("Starting RPC HTTP server on %s", listener.Addr()))
	s := &http.Server{
		Handler:        RecoverAndLogHandler(maxBytesHandler{h: handler, n: maxBodyBytes}, logger),
		ReadTimeout:    config.ReadTimeout,
		WriteTimeout:   config.WriteTimeout,
		MaxHeaderBytes: maxHeaderBytes,
	}
	err := s.Serve(listener)
	logger.Info("RPC HTTP server stopped", "err", err)
	return err
}
676779
func Run(sOpts *Options, nOpts *natsd.Options) (*StanServer, error) {
	return RunServerWithOpts(sOpts, nOpts)
}
862070
func (s *Server) Serve() error {
	if !atomic.CompareAndSwapInt32(&s.listening, 0, 1) {
		return errors.New("rpc: server is already running")
	}

	err := s.initListeners()
	if err != nil {
		return err
	}

	s.pool.Start()
	if s.opts.HeartbeatInterval > 0 {
		s.hb = times.NewWheel(time.Second, int(s.opts.HeartbeatInterval.Seconds()))
	}

	// todo: use errgroup.Group
	errs := make(chan error, len(s.listeners))
	for _, l := range s.listeners {
		go func(l net.Listener) {
			s.logger.Infof("rpc > Server is listening on %v", l.Addr())
			errs <- s.serve(l)
		}(l)
	}

	s.initRegistry()

	err = <-errs
	if err != ErrServerClosed {
		s.logger.Errorf("rpc > Failed to run server: %s", err)
		s.Close(0)
		s.listening = 0
	}
	return err
}
425178
func (c *MetricsCommand) Run(ctx *cmd.Context) error {
	client, err := newClient(c.ModelCommandBase)
	if err != nil {
		return errors.Trace(err)
	}
	var metrics []params.MetricResult
	if c.All {
		metrics, err = client.GetMetrics()
	} else {
		metrics, err = client.GetMetrics(c.Tags...)
	}
	if err != nil {
		return errors.Trace(err)
	}
	defer client.Close()
	if len(metrics) == 0 {
		return nil
	}
	results := make([]metric, len(metrics))
	for i, m := range metrics {
		results[i] = metric{
			Unit:      m.Unit,
			Timestamp: m.Time,
			Metric:    m.Key,
			Value:     m.Value,
			Labels:    m.Labels,
		}
	}
	sortedResults := metricSlice(results)
	sort.Sort(sortedResults)

	return errors.Trace(c.out.Write(ctx, results))
}