// Run starts a HTTP server and blocks while running if successful.
// The server will be shutdown when "ctx" is canceled.
334871
func Run(ctx context.Context, opts Options) error {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	conn, err := dial(ctx, opts.GRPCServer.Network, opts.GRPCServer.Addr)
	if err != nil {
		return err
	}
	go func() {
		<-ctx.Done()
		if err := conn.Close(); err != nil {
			glog.Errorf("Failed to close a client connection to the gRPC server: %v", err)
		}
	}()

	mux := http.NewServeMux()
	mux.HandleFunc("/swagger/", swaggerServer(opts.SwaggerDir))
	mux.HandleFunc("/healthz", healthzServer(conn))

	gw, err := newGateway(ctx, conn, opts.Mux)
	if err != nil {
		return err
	}
	mux.Handle("/", gw)

	s := &http.Server{
		Addr:    opts.Addr,
		Handler: allowCORS(mux),
	}
	go func() {
		<-ctx.Done()
		glog.Infof("Shutting down the http server")
		if err := s.Shutdown(context.Background()); err != nil {
			glog.Errorf("Failed to shutdown http server: %v", err)
		}
	}()

	glog.Infof("Starting listening at %s", opts.Addr)
	if err := s.ListenAndServe(); err != http.ErrServerClosed {
		glog.Errorf("Failed to listen and serve: %v", err)
		return err
	}
	return nil
}
625572
func (proxy *SCTPProxy) Run() {
	quit := make(chan bool)
	defer close(quit)
	for {
		client, err := proxy.listener.Accept()
		if err != nil {
			log.Printf("Stopping proxy on sctp/%v for sctp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err)
			return
		}
		go proxy.clientLoop(client.(*sctp.SCTPConn), quit)
	}
}
1237000
func (a *ArgoCDServer) Run(ctx context.Context, port int) {
	grpcS := a.newGRPCServer()
	grpcWebS := grpcweb.WrapServer(grpcS)
	var httpS *http.Server
	var httpsS *http.Server
	if a.useTLS() {
		httpS = newRedirectServer(port)
		httpsS = a.newHTTPServer(ctx, port, grpcWebS)
	} else {
		httpS = a.newHTTPServer(ctx, port, grpcWebS)
	}
	metricsServ := newAPIServerMetricsServer()

	// Start listener
	var conn net.Listener
	var realErr error
	_ = wait.ExponentialBackoff(backoff, func() (bool, error) {
		conn, realErr = net.Listen("tcp", fmt.Sprintf(":%d", port))
		if realErr != nil {
			a.log.Warnf("failed listen: %v", realErr)
			return false, nil
		}
		return true, nil
	})
	errors.CheckError(realErr)

	// Cmux is used to support servicing gRPC and HTTP1.1+JSON on the same port
	tcpm := cmux.New(conn)
	var tlsm cmux.CMux
	var grpcL net.Listener
	var httpL net.Listener
	var httpsL net.Listener
	if !a.useTLS() {
		httpL = tcpm.Match(cmux.HTTP1Fast())
		grpcL = tcpm.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
	} else {
		// We first match on HTTP 1.1 methods.
		httpL = tcpm.Match(cmux.HTTP1Fast())

		// If not matched, we assume that its TLS.
		tlsl := tcpm.Match(cmux.Any())
		tlsConfig := tls.Config{
			Certificates: []tls.Certificate{*a.settings.Certificate},
		}
		if a.TLSConfigCustomizer != nil {
			a.TLSConfigCustomizer(&tlsConfig)
		}
		tlsl = tls.NewListener(tlsl, &tlsConfig)

		// Now, we build another mux recursively to match HTTPS and gRPC.
		tlsm = cmux.New(tlsl)
		httpsL = tlsm.Match(cmux.HTTP1Fast())
		grpcL = tlsm.Match(cmux.Any())
	}

	// Start the muxed listeners for our servers
	log.Infof("argocd %s serving on port %d (url: %s, tls: %v, namespace: %s, sso: %v)",
		argocd.GetVersion(), port, a.settings.URL, a.useTLS(), a.Namespace, a.settings.IsSSOConfigured())

	go a.projInformer.Run(ctx.Done())
	go func() { a.checkServeErr("grpcS", grpcS.Serve(grpcL)) }()
	go func() { a.checkServeErr("httpS", httpS.Serve(httpL)) }()
	if a.useTLS() {
		go func() { a.checkServeErr("httpsS", httpsS.Serve(httpsL)) }()
		go func() { a.checkServeErr("tlsm", tlsm.Serve()) }()
	}
	go a.watchSettings(ctx)
	go a.rbacPolicyLoader(ctx)
	go func() { a.checkServeErr("tcpm", tcpm.Serve()) }()
	go func() { a.checkServeErr("metrics", metricsServ.ListenAndServe()) }()
	if !cache.WaitForCacheSync(ctx.Done(), a.projInformer.HasSynced) {
		log.Fatal("Timed out waiting for project cache to sync")
	}

	a.stopCh = make(chan struct{})
	<-a.stopCh
	errors.CheckError(conn.Close())
}
393355
func (s *Server) Run() {
	go s.updater()
	go s.notifier()
	go s.manager()

	<-s.quit
}
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)
		}
	}
}
18101
func (hs *HealthzServer) Run() {
	serveMux := http.NewServeMux()
	serveMux.Handle("/healthz", healthzHandler{hs: hs})
	server := hs.httpFactory.New(hs.addr, serveMux)

	go wait.Until(func() {
		klog.V(3).Infof("Starting goroutine for healthz on %s", hs.addr)

		listener, err := hs.listener.Listen(hs.addr)
		if err != nil {
			msg := fmt.Sprintf("Failed to start node healthz on %s: %v", hs.addr, err)
			if hs.recorder != nil {
				hs.recorder.Eventf(hs.nodeRef, api.EventTypeWarning, "FailedToStartNodeHealthcheck", msg)
			}
			klog.Error(msg)
			return
		}

		if err := server.Serve(listener); err != nil {
			klog.Errorf("Healthz closed with error: %v", err)
			return
		}
		klog.Error("Unexpected healthz closed.")
	}, nodeHealthzRetryInterval, wait.NeverStop)
}
761692
func (c *setSeriesCommand) Run(ctx *cmd.Context) error {
	var apiRoot api.Connection
	if c.setSeriesClient == nil {
		var err error
		apiRoot, err = c.NewAPIRoot()
		if err != nil {
			return errors.Trace(err)
		}
		defer apiRoot.Close()
	}

	if c.applicationName != "" {
		if c.setSeriesClient == nil {
			c.setSeriesClient = application.NewClient(apiRoot)
			defer c.setSeriesClient.Close()
		}
		if c.setSeriesClient.BestAPIVersion() < 5 {
			return errors.New("setting the application series is not supported by this API server")
		}
		return c.updateApplicationSeries()
	}

	// This should never happen...
	return errors.New("no application nor machine name specified")
}
5204
func (mod *WebBee) Run(cin chan bees.Event) {
	mod.eventChan = cin

	srv := &http.Server{Addr: mod.addr, Handler: mod}
	l, err := net.Listen("tcp", mod.addr)
	if err != nil {
		mod.LogErrorf("Can't listen on %s", mod.addr)
		return
	}
	defer l.Close()

	go func() {
		err := srv.Serve(l)
		if err != nil {
			mod.LogErrorf("Server error: %v", err)
		}
		// Go 1.8+: srv.Close()
	}()

	select {
	case <-mod.SigChan:
		return
	}
}
645911
func (i *Instance) Run(ctx context.Context) error {

	go func() {
		<-ctx.Done()
		zap.L().Debug("Stop the supervisor")

		i.CleanUp() // nolint
	}()

	// Clean any previous ACLs. This is needed in case we crashed at some
	// earlier point or there are other ACLs that create conflicts. We
	// try to clean only ACLs related to Trireme.
	if err := i.cleanACLs(); err != nil {
		return fmt.Errorf("Unable to clean previous acls while starting the supervisor: %s", err)
	}

	// Create all the basic target sets. These are the global target sets
	// that do not depend on policy configuration. If they already exist
	// we will delete them and start again.
	targetTCPSet, targetUDPSet, excludedSet, err := createGlobalSets(i.ipset)
	if err != nil {
		return fmt.Errorf("unable to create global sets: %s", err)
	}

	i.targetTCPSet = targetTCPSet
	i.targetUDPSet = targetUDPSet
	i.excludedNetworksSet = excludedSet

	if err := i.updateAllTargetNetworks(i.cfg, &runtime.Configuration{}); err != nil {
		// If there is a failure try to clean up on exit.
		i.ipset.DestroyAll(chainPrefix) // nolint errcheck
		return fmt.Errorf("unable to initialize target networks: %s", err)
	}

	// Initialize all the global Trireme chains. There are several global chaims
	// that apply to all PUs:
	// Tri-App/Tri-Net are the main chains for the egress/ingress directions
	// UID related chains for any UID PUs.
	// Host, Service, Pid chains for the different modes of operation (host mode, pu mode, host service).
	// The priority is explicit (Pid activations take precedence of Service activations and Host Services)
	if err := i.initializeChains(); err != nil {
		return fmt.Errorf("Unable to initialize chains: %s", err)
	}

	// Insert the global ACLS. These are the main ACLs that will direct traffic from
	// the INPUT/OUTPUT chains to the Trireme chains. They also includes the main
	// rules of the main chains. These rules are never touched again, unless
	// if we gracefully terminate.
	if err := i.setGlobalRules(); err != nil {
		return fmt.Errorf("failed to update synack networks: %s", err)
	}

	return nil
}
200107
func (client *AMIClient) Run() {
	go func() {
		for {
			data, err := client.conn.ReadMIMEHeader()
			if err != nil {
				switch err {
				case syscall.ECONNABORTED:
					fallthrough
				case syscall.ECONNRESET:
					fallthrough
				case syscall.ECONNREFUSED:
					fallthrough
				case io.EOF:
					client.NetError <- err
					<-client.waitNewConnection
				default:
					client.Error <- err
				}
				continue
			}

			if ev, err := newEvent(&data); err != nil {
				if err != errNotEvent {
					client.Error <- err
				}
			} else {
				client.Events <- ev
			}

			//only handle valid responses
			//@todo handle longs response
			// see  https://marcelog.github.io/articles/php_asterisk_manager_interface_protocol_tutorial_introduction.html
			if response, err := newResponse(&data); err == nil {
				client.notifyResponse(response)
			}

		}
	}()
}
381460
func (s *Simulator) Run() error {
	var err error
	s.conn, err = net.ListenUDP("udp4", &s.addr)
	if err != nil {
		return err
	}

	s.wg.Add(1)

	go func() {
		_ = s.serve()
		s.wg.Done()
	}()

	return nil
}
998782
func Run(r http.Handler, domain ...string) error {
	return http.Serve(autocert.NewListener(domain...), r)
}
450877
func (proxy *TCPProxy) Run() {
	quit := make(chan bool)
	defer close(quit)
	for {
		client, err := proxy.listener.Accept()
		if err != nil {
			log.Printf("Stopping proxy on tcp/%v for tcp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err)
			return
		}
		go proxy.clientLoop(client.(*net.TCPConn), quit)
	}
}
777604
func (f *Fibre) Run(opts HTTPOptions, files ...string) {

	var err error
	var s *graceful.Server

	w := f.logger.Writer()
	defer w.Close()

	switch v := opts.(type) {
	case string:
		s = &graceful.Server{
			Timeout: f.wait,
			Server: &http.Server{
				Addr:         v,
				Handler:      f,
				IdleTimeout:  f.itimeout,
				ReadTimeout:  f.rtimeout,
				WriteTimeout: f.wtimeout,
				ErrorLog:     log.New(w, "", 0),
			},
		}
	case *http.Server:
		s = &graceful.Server{
			Timeout: f.wait,
			Server:  v,
		}
		s.Server.Handler = f
	case *graceful.Server:
		s = v
		s.Server.Handler = f
	}

	if len(files) != 2 {
		err = s.ListenAndServe()
	}

	if len(files) == 2 {
		err = s.ListenAndServeTLS(files[0], files[1])
	}

	if err != nil {
		f.Logger().Fatal(err)
	}

}
239393
func (engine *Engine) Run(addr ...string) (err error) {
	defer func() { debugPrintError(err) }()

	address := resolveAddress(addr)
	debugPrint("Listening and serving HTTP on %s\n", address)
	err = http.ListenAndServe(address, engine)
	return
}
1322327
func (s *SecretsProxy) Run(ctx context.Context) error {
	s.Lock()
	defer s.Unlock()

	var err error

	// Start a custom listener
	addr, _ := net.ResolveUnixAddr("unix", s.socketPath)
	nl, err := net.ListenUnix("unix", addr)
	if err != nil {
		return fmt.Errorf("Unable to start API server: %s", err)
	}

	s.server = &http.Server{
		Handler: http.HandlerFunc(s.apiProcessor),
	}

	go func() {
		<-ctx.Done()
		s.server.Close() // nolint errcheck
	}()

	go s.server.Serve(server.NewUIDListener(nl)) // nolint errcheck

	return nil
}
41387
func (r *Router) Run(address string) error {
	return http.ListenAndServe(address, r.chain())
}