// runServer runs the simple BQL endpoint.
184887
func runServer(ctx context.Context, cmd *command.Command, args []string, store storage.Store, chanSize, bulkSize int) int {
	// Check parameters.
	if len(args) < 2 {
		log.Printf("[%v] Missing required port number. ", time.Now())
		cmd.Usage()
		return 2
	}

	// Validate port number.
	p := strings.TrimSpace(args[len(args)-1])
	port, err := strconv.Atoi(p)
	if err != nil {
		log.Printf("[%v] Invalid port number %q; %v\n", time.Now(), p, err)
		return 2
	}

	// Start the server.
	log.Printf("[%v] Starting server at port %d\n", time.Now(), port)
	s := &serverConfig{
		store:    store,
		chanSize: chanSize,
		bulkSize: bulkSize,
	}
	http.HandleFunc("/bql", s.bqlHandler)
	http.HandleFunc("/", defaultHandler)
	if err := http.ListenAndServe(":"+p, nil); err != nil {
		log.Printf("[%v] Failed to start server on port %s; %v", time.Now(), p, err)
		return 2
	}
	return 0
}
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)
}
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)
	}
}
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)
}
178990
func (s *Server) RunScgi(addr string) {
	s.initServer()
	s.Logger.Printf("web.go serving scgi %s\n", addr)
	s.listenAndServeScgi(addr)
}
670916
func (s *Server) startServer(server *http.Server, errs chan error) {
	var (
		network string
		err     error
		ln      net.Listener
	)

	network, server.Addr = s.parseAddress(server.Addr)
	if network == "unix" {
		// TODO: handle error
		os.Remove(server.Addr)
	}
	ln, err = net.Listen(network, server.Addr)

	if err == nil {
		ln = tcpKeepAliveListener{ln.(*net.TCPListener)}
		if server.TLSConfig == nil {
			s.Logger.Infof("web > Server started on %s", server.Addr)
			err = server.Serve(ln)
		} else {
			s.Logger.Infof("web > Server started on %s(tls)", server.Addr)
			err = server.ServeTLS(ln, "", "")
		}
	}
	errs <- err
}
387370
func RunWithErr(addr string, timeout time.Duration, n http.Handler) error {
	srv := &Server{
		Timeout:      timeout,
		TCPKeepAlive: 3 * time.Minute,
		Server:       &http.Server{Addr: addr, Handler: n},
		Logger:       DefaultLogger(),
	}

	return srv.ListenAndServe()
}
733413
func (p *Proxy) RunNetworkServer(ctx context.Context, listener net.Listener, encrypted bool) error {

	// Encryption is done transparently for TCP.
	go p.serve(ctx, listener)

	return nil
}
992413
func StartServer(connParams, connAppDebugParams mysql.ConnParams, dbName string) error {
	// Setup a fake vtgate server.
	protocol := "resolveTest"
	*vtgateconn.VtgateProtocol = protocol
	vtgateconn.RegisterDialer(protocol, func(context.Context, string) (vtgateconn.Impl, error) {
		return &txResolver{
			FakeVTGateConn: fakerpcvtgateconn.FakeVTGateConn{},
		}, nil
	})

	dbcfgs := dbconfigs.NewTestDBConfigs(connParams, connAppDebugParams, dbName)

	config := tabletenv.DefaultQsConfig
	config.EnableAutoCommit = true
	config.StrictTableACL = true
	config.TwoPCEnable = true
	config.TwoPCAbandonAge = 1
	config.TwoPCCoordinatorAddress = "fake"
	config.EnableHotRowProtection = true

	Target = querypb.Target{
		Keyspace:   "vttest",
		Shard:      "0",
		TabletType: topodatapb.TabletType_MASTER,
	}

	Server = tabletserver.NewTabletServerWithNilTopoServer(config)
	Server.Register()
	err := Server.StartService(Target, dbcfgs)
	if err != nil {
		return vterrors.Wrap(err, "could not start service")
	}

	// Start http service.
	ln, err := net.Listen("tcp", ":0")
	if err != nil {
		return vterrors.Wrap(err, "could not start listener")
	}
	ServerAddress = fmt.Sprintf("http://%s", ln.Addr().String())
	go http.Serve(ln, nil)
	for {
		time.Sleep(10 * time.Millisecond)
		response, err := http.Get(fmt.Sprintf("%s/debug/vars", ServerAddress))
		if err == nil {
			response.Body.Close()
			break
		}
	}
	return nil
}
862018
func RunServer(ID string) (*StanServer, error) {
	sOpts := GetDefaultOptions()
	sOpts.ID = ID
	nOpts := DefaultNatsServerOptions
	return RunServerWithOpts(sOpts, &nOpts)
}
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)
		}
	}

}
880142
func Run(server *Server) error {
	if dockerized {
		server.Start()
		return nil
	}
	run := svc.Run
	isInteractive, err := svc.IsAnInteractiveSession()
	if err != nil {
		return err
	}
	if isInteractive {
		run = debug.Run
	}
	return run(serviceName, &winServiceWrapper{server})
}
540393
func (q *Query) RunOne(model Model) error {
	tx := q.pool.NewTransaction()
	newTransactionQuery(q.query, tx).RunOne(model)
	return tx.Exec()
}
702659
func GenerateServer(name string, modelNames, operationIDs []string, opts *GenOpts) error {
	generator, err := newAppGenerator(name, modelNames, operationIDs, opts)
	if err != nil {
		return err
	}
	return generator.Generate()
}
451221
func StartServer(handler http.Handler) *Server {
	ch := make(chan *ReceivedRequest)
	closeSig := make(chan struct{})
	wrapper := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		u := uuid.New()
		w.Header().Add(UUIDHeaderName, u)
		handler.ServeHTTP(w, r)
		flusher := w.(http.Flusher) // TODO: what if you can't convert to a Flusher?
		flusher.Flush()
		req := &ReceivedRequest{Request: r, Time: time.Now(), UUID: u}
		select {
		case <-closeSig:
		case ch <- req:
		}
	})

	s := httptest.NewServer(wrapper)
	return &Server{
		lck:      &sync.Mutex{},
		closed:   0,
		closeSig: closeSig,
		ch:       ch,
		srv:      s,
	}
}
1357857
func (c *AppConfig) RunQuery() (*QueryResult, error) {
	environment, buildEnvironment, parameters, err := c.validate()
	if err != nil {
		return nil, err
	}
	// TODO: I don't belong here
	c.ensureDockerSearch()

	if c.AsList {
		if c.AsSearch {
			return nil, errors.New("--list and --search can't be used together")
		}
		if c.HasArguments() {
			return nil, errors.New("--list can't be used with arguments")
		}
		c.Components = append(c.Components, "*")
	}

	b := &app.ReferenceBuilder{}
	s := &c.SourceRepositories
	i := &c.ImageStreams
	if err := AddComponentInputsToRefBuilder(b, &c.Resolvers, &c.ComponentInputs, &c.GenerationInputs, s, i); err != nil {
		return nil, err
	}
	components, repositories, errs := b.Result()
	if len(errs) > 0 {
		return nil, kutilerrors.NewAggregate(errs)
	}

	if len(components) == 0 && !c.AsList {
		return nil, ErrNoInputs
	}

	if len(repositories) > 0 {
		errs = append(errs, errors.New("--search can't be used with source code"))
	}
	if len(environment) > 0 {
		errs = append(errs, errors.New("--search can't be used with --env"))
	}
	if len(buildEnvironment) > 0 {
		errs = append(errs, errors.New("--search can't be used with --build-env"))
	}
	if len(parameters) > 0 {
		errs = append(errs, errors.New("--search can't be used with --param"))
	}
	if len(errs) > 0 {
		return nil, kutilerrors.NewAggregate(errs)
	}

	if err := components.Search(); err != nil {
		return nil, err
	}

	klog.V(4).Infof("Code %v", repositories)
	klog.V(4).Infof("Components %v", components)

	matches := app.ComponentMatches{}
	objects := app.Objects{}
	for _, ref := range components {
		for _, match := range ref.Input().SearchMatches {
			matches = append(matches, match)
			if match.IsTemplate() {
				objects = append(objects, match.Template)
			} else if match.IsImage() {
				if match.ImageStream != nil {
					objects = append(objects, match.ImageStream)
				}
				if match.DockerImage != nil {
					objects = append(objects, match.DockerImage)
				}
			}
		}
	}

	return &QueryResult{
		Matches: matches,
		List:    &kapi.List{Items: objects},
	}, nil
}
566336
func RunServer(srv *http.Server, shutdownFuncs ...func()) {
	done := make(chan struct{})

	go func() {
		// Handle SIGINT and SIGTERM.
		sigCh := make(chan os.Signal, 1)
		signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

		sig := <-sigCh
		fmt.Println("Received signal, stopping.", "signal", sig)

		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()

		// We received an interrupt signal, shut down.
		if err := srv.Shutdown(ctx); err != nil {
			// Error from closing listeners, or context timeout:
			fmt.Printf("HTTP server Shutdown: %v\n", err)
		}
		// Run shutdown functions
		for _, sf := range shutdownFuncs {
			sf()
		}

		close(done)
	}()

	fmt.Printf("HTTP server listening on address: \"%s\"\n", srv.Addr)
	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
		// Error starting or closing listener:
		fmt.Printf("HTTP server ListenAndServe: %v\n", err)
		os.Exit(1)
	}

	<-done
}