// Serve starts the Supervisor tree. It can be started only once at a time. If
// stopped (canceled), it can be restarted. In case of concurrent calls, it will
// hang until the current call is completed.
349651
func (s *Supervisor) Serve(ctx context.Context) {
	s.prepare()
	restartCtx, cancel := context.WithCancel(ctx)
	processFailure := func() {
		restart := s.shouldRestart()
		if !restart {
			cancel()
		}
	}
	serve(s, restartCtx, processFailure)
}
503382
func Serve(l net.Listener, h Handler, appname, hostname string) (err error) {
  serv := Server{
    Appname: appname,
    Hostname: hostname,
    Handler: h,
  }
  return serv.Serve(l)
}
1370606
func (s *Server) Serve(ctx context.Context) error {
	logger := &chronograf.NoopLogger{}
	_, err := NewCustomLinks(s.CustomLinks)
	if err != nil {
		logger.
			WithField("component", "server").
			WithField("CustomLink", "invalid").
			Error(err)
		return err
	}
	service := openService(ctx, s.BuildInfo, s.BoltPath, s.newBuilders(logger), logger, s.useAuth())
	service.SuperAdminProviderGroups = superAdminProviderGroups{
		auth0: s.Auth0SuperAdminOrg,
	}
	service.Env = chronograf.Environment{
		TelegrafSystemInterval: s.TelegrafSystemInterval,
	}
	if err := service.HandleNewSources(ctx, s.NewSources); err != nil {
		logger.
			WithField("component", "server").
			WithField("new-sources", "invalid").
			Error(err)
		return err
	}

	if !validBasepath(s.Basepath) {
		err := fmt.Errorf("invalid basepath, must follow format \"/mybasepath\"")
		logger.
			WithField("component", "server").
			WithField("basepath", "invalid").
			Error(err)
		return err
	}

	providerFuncs := []func(func(oauth2.Provider, oauth2.Mux)){}

	auth := oauth2.NewCookieJWT(s.TokenSecret, s.AuthDuration)
	providerFuncs = append(providerFuncs, provide(s.githubOAuth(logger, auth)))
	providerFuncs = append(providerFuncs, provide(s.googleOAuth(logger, auth)))
	providerFuncs = append(providerFuncs, provide(s.herokuOAuth(logger, auth)))
	providerFuncs = append(providerFuncs, provide(s.genericOAuth(logger, auth)))
	providerFuncs = append(providerFuncs, provide(s.auth0OAuth(logger, auth)))

	s.handler = NewMux(MuxOpts{
		Develop:       s.Develop,
		Auth:          auth,
		Logger:        logger,
		UseAuth:       s.useAuth(),
		ProviderFuncs: providerFuncs,
		Basepath:      s.Basepath,
		StatusFeedURL: s.StatusFeedURL,
		CustomLinks:   s.CustomLinks,
	}, service)

	// Add chronograf's version header to all requests
	s.handler = Version(s.BuildInfo.Version, s.handler)

	if s.useTLS() {
		// Add HSTS to instruct all browsers to change from http to https
		s.handler = HSTS(s.handler)
	}

	listener, err := s.NewListener()
	if err != nil {
		logger.
			WithField("component", "server").
			Error(err)
		return err
	}
	s.Listener = listener

	// Using a log writer for http server logging
	w := logger.Writer()
	defer w.Close()
	stdLog := log.New(w, "", 0)

	// TODO: Remove graceful when changing to go 1.8
	httpServer := &graceful.Server{
		Server: &http.Server{
			ErrorLog: stdLog,
			Handler:  s.handler,
		},
		Logger:       stdLog,
		TCPKeepAlive: 5 * time.Second,
	}
	httpServer.SetKeepAlivesEnabled(true)

	if !s.ReportingDisabled {
		go reportUsageStats(s.BuildInfo, logger)
	}
	scheme := "http"
	if s.useTLS() {
		scheme = "https"
	}
	logger.
		WithField("component", "server").
		Info("Serving chronograf at ", scheme, "://", s.Listener.Addr())

	if err := httpServer.Serve(s.Listener); err != nil {
		logger.
			WithField("component", "server").
			Error(err)
		return err
	}

	logger.
		WithField("component", "server").
		Info("Stopped serving chronograf at ", scheme, "://", s.Listener.Addr())

	return nil
}
423519
func (s *syncServer) serve(l *net.TCPListener) error {
	defer l.Close()

	s.server = rpc.NewServer()
	s.server.Register(&SeesawSync{s})

	for {
		c, err := l.AcceptTCP()
		if err != nil {
			if ne, ok := err.(net.Error); ok && ne.Temporary() {
				time.Sleep(100 * time.Millisecond)
				continue
			}
			return err
		}
		raddr := c.RemoteAddr().String()
		host, _, err := net.SplitHostPort(raddr)
		if err != nil {
			log.Errorf("Failed to parse remote address %q: %v", raddr, err)
			c.Close()
			continue
		}
		rip := net.ParseIP(host)
		if rip == nil || (!rip.IsLoopback() && !rip.Equal(s.engine.config.Peer.IPv4Addr) && !rip.Equal(s.engine.config.Peer.IPv6Addr)) {
			log.Warningf("Rejecting connection from non-peer (%s)...", rip)
			c.Close()
			continue
		}
		log.Infof("Sync connection established from %s", rip)
		go s.server.ServeConn(c)
	}
}
941318
func (l *listener) serve() {
	for {
		select {
		case <-l.sock.closeq:
			return
		default:
		}

		// If the underlying PipeListener is closed, or not
		// listening, we expect to return back with an error.
		if pipe, err := l.l.Accept(); err == nil {
			l.sock.addPipe(pipe, nil, l)
		} else if err == ErrClosed {
			return
		}
	}
}
733530
func (s *Server) serve(lis net.Listener) {
	s.wg.Add(1)
	go func() {
		log.Infof("Listening on %s", lis.Addr())
		err := s.httpServer.Serve(lis)
		log.Tracef("Finished serving RPC: %v", err)
		s.wg.Done()
	}()
}
1050237
func (srv *Server) Serve(listener net.Listener) error {

	if srv.ListenLimit != 0 {
		listener = LimitListener(listener, srv.ListenLimit)
	}

	// Make our stopchan
	srv.StopChan()

	// Track connection state
	add := make(chan net.Conn)
	idle := make(chan net.Conn)
	active := make(chan net.Conn)
	remove := make(chan net.Conn)

	srv.Server.ConnState = func(conn net.Conn, state http.ConnState) {
		switch state {
		case http.StateNew:
			add <- conn
		case http.StateActive:
			active <- conn
		case http.StateIdle:
			idle <- conn
		case http.StateClosed, http.StateHijacked:
			remove <- conn
		}

		srv.stopLock.Lock()
		defer srv.stopLock.Unlock()

		if srv.ConnState != nil {
			srv.ConnState(conn, state)
		}
	}

	// Manage open connections
	shutdown := make(chan chan struct{})
	kill := make(chan struct{})
	go srv.manageConnections(add, idle, active, remove, shutdown, kill)

	interrupt := srv.interruptChan()
	// Set up the interrupt handler
	if !srv.NoSignalHandling {
		signalNotify(interrupt)
	}
	quitting := make(chan struct{})
	go srv.handleInterrupt(interrupt, quitting, listener)

	// Serve with graceful listener.
	// Execution blocks here until listener.Close() is called, above.
	err := srv.Server.Serve(listener)
	if err != nil {
		// If the underlying listening is closed, Serve returns an error
		// complaining about listening on a closed socket. This is expected, so
		// let's ignore the error if we are the ones who explicitly closed the
		// socket.
		select {
		case <-quitting:
			err = nil
		default:
		}
	}

	srv.shutdown(shutdown, kill)

	return err
}
1041718
func (l *LoadBalancer) Serve() error {
	defer l.waitCancel()
	backoffTimer := time.NewTicker(5 * time.Second)
	defer backoffTimer.Stop()
	for {
		conn, err := l.listener.Accept()
		if err != nil {
			if l.isClosed() {
				return trace.ConnectionProblem(nil, "listener is closed")
			}
			select {
			case <-backoffTimer.C:
				l.Debugf("backoff on network error")
			case <-l.ctx.Done():
				return trace.ConnectionProblem(nil, "context is closing")
			}
		}
		go l.forwardConnection(conn)
	}
}
203022
func Serve(d DriverPlugin, logger hclog.Logger) {
	plugin.Serve(&plugin.ServeConfig{
		HandshakeConfig: base.Handshake,
		Plugins: map[string]plugin.Plugin{
			base.PluginTypeBase:   &base.PluginBase{Impl: d},
			base.PluginTypeDriver: &PluginDriver{impl: d, logger: logger},
		},
		GRPCServer: plugin.DefaultGRPCServer,
		Logger:     logger,
	})
}
1212532
func (s Server) Serve(l net.Listener) error {
	originalHandler := s.Server.Handler
	if originalHandler == nil {
		originalHandler = http.DefaultServeMux
	}
	s.Server.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "PRI" && r.URL.Path == "*" && r.Proto == "HTTP/2.0" {
			if http2VerboseLogs {
				log.Debugf("Attempting h2c with prior knowledge.")
			}
			conn, err := initH2CWithPriorKnowledge(w)
			if err != nil {
				if http2VerboseLogs {
					log.Debugf("Error h2c with prior knowledge: %v", err)
				}
				return
			}
			defer conn.Close()
			h2cSrv := &http2.Server{}
			h2cSrv.ServeConn(conn, &http2.ServeConnOpts{Handler: originalHandler})
			return
		}
		if conn, err := h2cUpgrade(w, r); err == nil {
			defer conn.Close()
			h2cSrv := &http2.Server{}
			h2cSrv.ServeConn(conn, &http2.ServeConnOpts{Handler: originalHandler})
			return
		}
		originalHandler.ServeHTTP(w, r)
	})
	return s.Server.Serve(l)
}
76086
func (srv *Server) Serve(l net.Listener) error {
	// Spawn a shadow http.Server to do the actual servering. We do this
	// because we need to sketch on some of the parameters you passed in,
	// and it's nice to keep our sketching to ourselves.
	shadow := *(*http.Server)(srv)
	shadow.ConnState = connState(shadow.ConnState).Wrap

	l = gracefulServer{l, &shadow}
	wrap := listener.Wrap(l, listener.Automatic)
	appendListener(wrap)

	err := shadow.Serve(wrap)
	return peacefulError(err)
}
13563
func (service *Service) Serve(l net.Listener) error {
	return service.Server.Serve(l)
}
1147973
func (s *ServerRPC) Serve(addr string) error {
	s.Log(hlog.DEBUG, "start server at %s", addr)
	l, err := net.Listen("tcp", addr)
	if err != nil {
		s.Log(hlog.ERROR, "Failed to listen %s: %v", addr, err)
		return err
	}

	return s.server.Serve(l)
}
388995
func Serve(servers ...*http.Server) error {
	a := newApp(servers)
	return a.run()
}
468141
func serve(ctx context.Context, server *ttrpc.Server, path string) error {
	var (
		l   net.Listener
		err error
	)
	if path == "" {
		l, err = net.FileListener(os.NewFile(3, "socket"))
		path = "[inherited from parent]"
	} else {
		if len(path) > 106 {
			return errors.Errorf("%q: unix socket path too long (> 106)", path)
		}
		l, err = net.Listen("unix", "\x00"+path)
	}
	if err != nil {
		return err
	}
	logrus.WithField("socket", path).Debug("serving api on unix socket")
	go func() {
		defer l.Close()
		if err := server.Serve(ctx, l); err != nil &&
			!strings.Contains(err.Error(), "use of closed network connection") {
			logrus.WithError(err).Fatal("containerd-shim: ttrpc server failure")
		}
	}()
	return nil
}
454807
func (f *FS) Serve(ctx context.Context) error {
	srv := fs.New(f.conn, &fs.Config{
		WithContext: func(ctx context.Context, _ fuse.Request) context.Context {
			return f.WithContext(ctx)
		},
	})
	f.fuse = srv

	f.notifications.LaunchProcessor(ctx)
	f.remoteStatus.Init(ctx, f.log, f.config, f)
	// Blocks forever, unless an interrupt signal is received
	// (handled by libkbfs.Init).
	return srv.Serve(f)
}
506241
func (srv *Server) Serve(l net.Listener) error {
	defer l.Close()

	// When the handler is not specified, the default dispatcher
	// will be used instead.
	handler := srv.Handler
	if handler == nil {
		handler = DefaultMux
	}

	hr := srv.HandlerRunner
	if hr == nil {
		hr = OnDemandRoutineRunner{}
	}

	cr := srv.ConnRunner
	if cr == nil {
		cr = OnDemandRoutineRunner{}
	}

	// Initialize a channel used to terminate the main handling loop.
	srv.once.Do(func() { srv.stop = make(chan struct{}) })

	for {
		err := srv.accept(l, cr, hr, handler)
		if err != nil {
			return err
		}
	}
}