// NewServer builds and returns a Server for high-level interaction with the
// input LXD container server.
173011
func NewServer(svr lxd.ContainerServer) (*Server, error) {
	info, _, err := svr.GetServer()
	if err != nil {
		return nil, errors.Trace(err)
	}

	apiExt := info.APIExtensions

	name := info.Environment.ServerName
	clustered := info.Environment.ServerClustered
	if name == "" && !clustered {
		// If the name is set to empty and clustering is false, then it's highly
		// likely that we're on an older version of LXD. So in that case we
		// need to set the name to something and internally LXD sets this type
		// of node to "none".
		// LP:#1786309
		name = "none"
	}
	serverCertificate := info.Environment.Certificate
	hostArch := arch.NormaliseArch(info.Environment.KernelArchitecture)

	return &Server{
		ContainerServer:   svr,
		name:              name,
		clustered:         clustered,
		serverCertificate: serverCertificate,
		hostArch:          hostArch,
		networkAPISupport: shared.StringInSlice("network", apiExt),
		clusterAPISupport: shared.StringInSlice("clustering", apiExt),
		storageAPISupport: shared.StringInSlice("storage", apiExt),
		serverVersion:     info.Environment.ServerVersion,
		clock:             clock.WallClock,
	}, nil
}
1266794
func NewServer(api *operations.TodoListAPI) *Server {
	s := new(Server)

	s.EnabledListeners = enabledListeners
	s.CleanupTimeout = cleanupTimeout
	s.GracefulTimeout = gracefulTimeout
	s.MaxHeaderSize = maxHeaderSize
	s.SocketPath = socketPath
	s.Host = stringEnvOverride(host, "", "HOST")
	s.Port = intEnvOverride(port, 0, "PORT")
	s.ListenLimit = listenLimit
	s.KeepAlive = keepAlive
	s.ReadTimeout = readTimeout
	s.WriteTimeout = writeTimeout
	s.TLSHost = stringEnvOverride(tlsHost, s.Host, "TLS_HOST", "HOST")
	s.TLSPort = intEnvOverride(tlsPort, 0, "TLS_PORT")
	s.TLSCertificate = stringEnvOverride(tlsCertificate, "", "TLS_CERTIFICATE")
	s.TLSCertificateKey = stringEnvOverride(tlsCertificateKey, "", "TLS_PRIVATE_KEY")
	s.TLSCACertificate = stringEnvOverride(tlsCACertificate, "", "TLS_CA_CERTIFICATE")
	s.TLSListenLimit = tlsListenLimit
	s.TLSKeepAlive = tlsKeepAlive
	s.TLSReadTimeout = tlsReadTimeout
	s.TLSWriteTimeout = tlsWriteTimeout
	s.shutdown = make(chan struct{})
	s.api = api
	s.interrupt = make(chan os.Signal, 1)
	return s
}
797699
func NewServer(t testing.TB, h http.Handler, client *http.Client) *Server {
	return newServer(t, httptest.NewServer(h), client)
}
771204
func NewServer(loader Loader) transport.Transport {
	return &server{
		loader,
		&handler{asClient: false},
	}
}
162286
func NewServer() *Server {
	s := &Server{
		Router: newRouter(),
		Addr:   "",
		TLS:    nil,
	}

	s.ErrorHandler = StdErrorHandler

	return s
}
1158153
func NewServer(redisHost, redisPort, redisPassword string, redisDb int64, port string) *Server {
	observer := NewObserver(redisHost, redisPort, redisPassword, redisDb)
	s := &Server{
		port:     port,
		observer: observer,
	}
	return s
}
1139863
func NewServer(opts ...MockDiscoveryServerOpt) *MockDiscoveryServer {
	s := &MockDiscoveryServer{}
	for _, opt := range opts {
		opt(s)
	}
	return s
}
715620
func NewServer(api *restapi.CiliumHealthAPI) *Server {
	s := new(Server)

	s.shutdown = make(chan struct{})
	s.api = api
	s.interrupt = make(chan os.Signal, 1)
	return s
}
843188
func NewServer(archiver pkgarchive.Archiver, opts ServerOptions) Server {
	return newServer(archiver, opts)
}
519361
func (s *Server) newServer(proto, addr string) ([]*HTTPServer, error) {
	var (
		ls []net.Listener
	)
	switch proto {
	case "tcp":
		l, err := s.initTCPSocket(addr)
		if err != nil {
			return nil, err
		}
		ls = append(ls, l)

	default:
		return nil, errors.New("Invalid protocol format. Windows only supports tcp.")
	}

	var res []*HTTPServer
	for _, l := range ls {
		res = append(res, &HTTPServer{
			&http.Server{
				Addr: addr,
			},
			l,
		})
	}
	return res, nil

}
721842
func (s *Server) newServer(proto, addr string) ([]*HTTPServer, error) {
	var (
		err error
		ls  []net.Listener
	)
	switch proto {
	case "fd":
		ls, err = listenFD(addr, s.cfg.TLSConfig)
		if err != nil {
			return nil, err
		}
	case "tcp":
		l, err := s.initTCPSocket(addr)
		if err != nil {
			return nil, err
		}
		ls = append(ls, l)
	case "unix":
		l, err := sockets.NewUnixSocket(addr, s.cfg.SocketGroup)
		if err != nil {
			return nil, fmt.Errorf("can't create unix socket %s: %v", addr, err)
		}
		ls = append(ls, l)
	default:
		return nil, fmt.Errorf("Invalid protocol format: %q", proto)
	}
	var res []*HTTPServer
	for _, l := range ls {
		res = append(res, &HTTPServer{
			&http.Server{
				Addr: addr,
			},
			l,
		})
	}
	return res, nil
}
1227627
func NewServer(store mailstore.Mailstore) *Server {
	s := &Server{
		Addr:       defaultAddress,
		mailstore:  store,
		Transcript: ioutil.Discard,
	}
	return s
}
853190
func NewServer(address string, handler Handler, opts Options) Server {
	instrumentOpts := opts.InstrumentOptions()
	scope := instrumentOpts.MetricsScope()

	s := &server{
		address:                      address,
		log:                          instrumentOpts.Logger(),
		retryOpts:                    opts.RetryOptions(),
		reportInterval:               instrumentOpts.ReportInterval(),
		tcpConnectionKeepAlive:       opts.TCPConnectionKeepAlive(),
		tcpConnectionKeepAlivePeriod: opts.TCPConnectionKeepAlivePeriod(),
		closedChan:                   make(chan struct{}),
		metrics:                      newServerMetrics(scope),
		handler:                      handler,
	}

	// Set up the connection functions.
	s.addConnectionFn = s.addConnection
	s.removeConnectionFn = s.removeConnection

	// Start reporting metrics.
	go s.reportMetrics()

	return s
}
444030
func NewServer(config *Config, consulCatalog consul.CatalogAPI) (*Server, error) {
	// Check the protocol version
	if err := config.CheckVersion(); err != nil {
		return nil, err
	}

	// Create an eval broker
	evalBroker, err := NewEvalBroker(
		config.EvalNackTimeout,
		config.EvalNackInitialReenqueueDelay,
		config.EvalNackSubsequentReenqueueDelay,
		config.EvalDeliveryLimit)
	if err != nil {
		return nil, err
	}

	// Configure TLS
	tlsConf, err := tlsutil.NewTLSConfiguration(config.TLSConfig, true, true)
	if err != nil {
		return nil, err
	}
	incomingTLS, tlsWrap, err := getTLSConf(config.TLSConfig.EnableRPC, tlsConf)
	if err != nil {
		return nil, err
	}

	// Create the ACL object cache
	aclCache, err := lru.New2Q(aclCacheSize)
	if err != nil {
		return nil, err
	}

	// Create the logger
	logger := config.Logger.ResetNamed("nomad")

	// Create the server
	s := &Server{
		config:        config,
		consulCatalog: consulCatalog,
		connPool:      pool.NewPool(logger, serverRPCCache, serverMaxStreams, tlsWrap),
		logger:        logger,
		tlsWrap:       tlsWrap,
		rpcServer:     rpc.NewServer(),
		streamingRpcs: structs.NewStreamingRpcRegistry(),
		nodeConns:     make(map[string][]*nodeConnState),
		peers:         make(map[string][]*serverParts),
		localPeers:    make(map[raft.ServerAddress]*serverParts),
		reconcileCh:   make(chan serf.Member, 32),
		eventCh:       make(chan serf.Event, 256),
		evalBroker:    evalBroker,
		blockedEvals:  NewBlockedEvals(evalBroker, logger),
		rpcTLS:        incomingTLS,
		aclCache:      aclCache,
		shutdownCh:    make(chan struct{}),
	}

	// Create the RPC handler
	s.rpcHandler = newRpcHandler(s)

	// Create the planner
	planner, err := newPlanner(s)
	if err != nil {
		return nil, err
	}
	s.planner = planner

	// Create the node heartbeater
	s.nodeHeartbeater = newNodeHeartbeater(s)

	// Create the periodic dispatcher for launching periodic jobs.
	s.periodicDispatcher = NewPeriodicDispatch(s.logger, s)

	// Initialize the stats fetcher that autopilot will use.
	s.statsFetcher = NewStatsFetcher(s.logger, s.connPool, s.config.Region)

	// Setup Vault
	if err := s.setupVaultClient(); err != nil {
		s.Shutdown()
		s.logger.Error("failed to setup Vault client", "error", err)
		return nil, fmt.Errorf("Failed to setup Vault client: %v", err)
	}

	// Initialize the RPC layer
	if err := s.setupRPC(tlsWrap); err != nil {
		s.Shutdown()
		s.logger.Error("failed to start RPC layer", "error", err)
		return nil, fmt.Errorf("Failed to start RPC layer: %v", err)
	}

	// Initialize the Raft server
	if err := s.setupRaft(); err != nil {
		s.Shutdown()
		s.logger.Error("failed to start Raft", "error", err)
		return nil, fmt.Errorf("Failed to start Raft: %v", err)
	}

	// Initialize the wan Serf
	s.serf, err = s.setupSerf(config.SerfConfig, s.eventCh, serfSnapshot)
	if err != nil {
		s.Shutdown()
		s.logger.Error("failed to start serf WAN", "error", err)
		return nil, fmt.Errorf("Failed to start serf: %v", err)
	}

	// Initialize the scheduling workers
	if err := s.setupWorkers(); err != nil {
		s.Shutdown()
		s.logger.Error("failed to start workers", "error", err)
		return nil, fmt.Errorf("Failed to start workers: %v", err)
	}

	// Setup the Consul syncer
	if err := s.setupConsulSyncer(); err != nil {
		s.logger.Error("failed to create server consul syncer", "error", err)
		return nil, fmt.Errorf("failed to create server Consul syncer: %v", err)
	}

	// Setup the deployment watcher.
	if err := s.setupDeploymentWatcher(); err != nil {
		s.logger.Error("failed to create deployment watcher", "error", err)
		return nil, fmt.Errorf("failed to create deployment watcher: %v", err)
	}

	// Setup the node drainer.
	s.setupNodeDrainer()

	// Setup the enterprise state
	if err := s.setupEnterprise(config); err != nil {
		return nil, err
	}

	// Monitor leadership changes
	go s.monitorLeadership()

	// Start ingesting events for Serf
	go s.serfEventHandler()

	// start the RPC listener for the server
	s.startRPCListener()

	// Emit metrics for the eval broker
	go evalBroker.EmitStats(time.Second, s.shutdownCh)

	// Emit metrics for the plan queue
	go s.planQueue.EmitStats(time.Second, s.shutdownCh)

	// Emit metrics for the blocked eval tracker.
	go s.blockedEvals.EmitStats(time.Second, s.shutdownCh)

	// Emit metrics for the Vault client.
	go s.vault.EmitStats(time.Second, s.shutdownCh)

	// Emit metrics
	go s.heartbeatStats()

	// Start enterprise background workers
	s.startEnterpriseBackground()

	// Done
	return s, nil
}
934025
func NewServer(r *multichannel.Registrar, metricsProvider metrics.Provider, debug *localconfig.Debug, timeWindow time.Duration, mutualTLS bool) ab.AtomicBroadcastServer {
	s := &server{
		dh: deliver.NewHandler(deliverSupport{Registrar: r}, timeWindow, mutualTLS, deliver.NewMetrics(metricsProvider)),
		bh: &broadcast.Handler{
			SupportRegistrar: broadcastSupport{Registrar: r},
			Metrics:          broadcast.NewMetrics(metricsProvider),
		},
		debug:     debug,
		Registrar: r,
	}
	return s
}
490057
func NewServer(name string, s func(...server.Option) server.Server) Option {
	return func(o *Options) {
		o.Servers[name] = s
	}
}
362442
func (s *Service) NewServer() *Server {
	s.RegisterSDK(Map)

	mux := s.ServeMux
	vim := Map.Path + "/vimService"
	s.sdk[vim] = s.sdk[vim25.Path]
	mux.HandleFunc(vim, s.ServeSDK)
	mux.HandleFunc(Map.Path+"/vimServiceVersions.xml", s.ServiceVersions)
	mux.HandleFunc(folderPrefix, s.ServeDatastore)
	mux.HandleFunc(nfcPrefix, ServeNFC)
	mux.HandleFunc("/about", s.About)

	ts := internal.NewUnstartedServer(mux, s.Listen)
	addr := ts.Listener.Addr().(*net.TCPAddr)
	port := strconv.Itoa(addr.Port)
	u := &url.URL{
		Scheme: "http",
		Host:   net.JoinHostPort(defaultIP(addr), port),
		Path:   Map.Path,
	}
	if s.TLS != nil {
		u.Scheme += "s"
	}

	// Redirect clients to this http server, rather than HostSystem.Name
	Map.SessionManager().ServiceHostName = u.Host

	// Add vcsim config to OptionManager for use by SDK handlers (see lookup/simulator for example)
	m := Map.OptionManager()
	m.Setting = append(m.Setting,
		&types.OptionValue{
			Key:   "vcsim.server.url",
			Value: u.String(),
		},
	)

	u.User = url.UserPassword("user", "pass")

	if s.TLS != nil {
		ts.TLS = s.TLS
		ts.TLS.ClientAuth = tls.RequestClientCert // Used by SessionManager.LoginExtensionByCertificate
		Map.SessionManager().TLSCert = func() string {
			return base64.StdEncoding.EncodeToString(ts.TLS.Certificates[0].Certificate[0])
		}
		ts.StartTLS()
	} else {
		ts.Start()
	}

	return &Server{
		Server: ts,
		URL:    u,
	}
}