gserver

package
v0.25.559 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 8, 2024 License: MIT Imports: 43 Imported by: 8

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CORS

type CORS struct {

	// Enabled specifies if the CORS is enabled.
	Enabled *bool `json:"enabled,omitempty" yaml:"enabled,omitempty"`

	// MaxAge indicates how long (in seconds) the results of a preflight request can be cached.
	MaxAge int `json:"max_age,omitempty" yaml:"max_age,omitempty"`

	// AllowedOrigins is a list of origins a cross-domain request can be executed from.
	AllowedOrigins []string `json:"allowed_origins,omitempty" yaml:"allowed_origins,omitempty"`

	// AllowedMethods is a list of methods the client is allowed to use with cross-domain requests.
	AllowedMethods []string `json:"allowed_methods,omitempty" yaml:"allowed_methods,omitempty"`

	// AllowedHeaders is list of non simple headers the client is allowed to use with cross-domain requests.
	AllowedHeaders []string `json:"allowed_headers,omitempty" yaml:"allowed_headers,omitempty"`

	// ExposedHeaders indicates which headers are safe to expose to the API of a CORS API specification.
	ExposedHeaders []string `json:"exposed_headers,omitempty" yaml:"exposed_headers,omitempty"`

	// AllowCredentials indicates whether the request can include user credentials.
	AllowCredentials *bool `json:"allow_credentials,omitempty" yaml:"allow_credentials,omitempty"`

	// OptionsPassthrough instructs preflight to let other potential next handlers to process the OPTIONS method.
	OptionsPassthrough *bool `json:"options_pass_through,omitempty" yaml:"options_pass_through,omitempty"`

	// Debug flag adds additional output to debug server side CORS issues.
	Debug *bool `json:"debug,omitempty" yaml:"debug,omitempty"`
}

CORS contains configuration for CORS.

func (*CORS) GetAllowCredentials

func (c *CORS) GetAllowCredentials() bool

GetAllowCredentials flag

func (*CORS) GetDebug

func (c *CORS) GetDebug() bool

GetDebug flag adds additional output to debug server side CORS issues.

func (*CORS) GetEnabled

func (c *CORS) GetEnabled() bool

GetEnabled specifies if the CORS is enabled.

func (*CORS) GetOptionsPassthrough

func (c *CORS) GetOptionsPassthrough() bool

GetOptionsPassthrough flag

type Config

type Config struct {
	// DebugLogs allows to add extra debog logs
	DebugLogs bool `json:"debug_logs" yaml:"debug_logs"`

	// Description provides description of the server
	Description string `json:"description,omitempty" yaml:"description,omitempty"`

	// Disabled specifies if the service is disabled
	Disabled bool `json:"disabled,omitempty" yaml:"disabled,omitempty"`

	// ClientURL is the public URL exposed to clients
	ClientURL string `json:"client_url" yaml:"client_url"`

	// ListenURLs is the list of URLs that the server will be listen on
	ListenURLs []string `json:"listen_urls" yaml:"listen_urls"`

	// ServerTLS provides TLS config for server
	ServerTLS *TLSInfo `json:"server_tls,omitempty" yaml:"server_tls,omitempty"`

	// SkipLogPaths if set, specifies a list of paths to not log.
	// this can be used for /v1/status/node or /metrics
	SkipLogPaths []telemetry.LoggerSkipPath `json:"logger_skip_paths,omitempty" yaml:"logger_skip_paths,omitempty"`

	// PromGrpc allows to submit gRPC metrics to Prometheus interceptors
	PromGrpc bool `json:"prom_grpc" yaml:"prom_grpc"`

	// Services is a list of services to enable for this server
	Services []string `json:"services" yaml:"services"`

	// IdentityMap contains configuration for the roles
	IdentityMap *roles.IdentityMap `json:"identity_map" yaml:"identity_map"`

	// Authz contains configuration for the authorization module
	Authz *authz.Config `json:"authz" yaml:"authz"`

	// CORS contains configuration for CORS.
	CORS *CORS `json:"cors,omitempty" yaml:"cors,omitempty"`

	// RateLimit contains configuration for the rate limiter
	RateLimit *RateLimit `json:"rate_limit,omitempty" yaml:"rate_limit,omitempty"`

	// Timeout settings
	Timeout struct {
		// Request is the timeout for client requests to finish.
		Request time.Duration `json:"request,omitempty" yaml:"request,omitempty"`
	} `json:"timeout" yaml:"timeout"`

	// KeepAlive settings
	KeepAlive KeepAliveCfg `json:"keep_alive" yaml:"keep_alive"`
}

Config contains the configuration of the server

func (*Config) ParseListenURLs

func (c *Config) ParseListenURLs() ([]*url.URL, error)

ParseListenURLs constructs a list of listen peers URLs

type GRPCRegistrator

type GRPCRegistrator interface {
	RegisterGRPC(*grpc.Server)
}

GRPCRegistrator provides interface to register gRPC service

type GServer added in v0.14.0

type GServer interface {
	// Name returns server name
	Name() string
	// Configuration of the server
	Configuration() *Config
	// AddService to the server
	AddService(svc Service)
	// Service returns service by name
	Service(name string) Service
	// IsReady returns true when the server is ready to serve
	IsReady() bool
	// StartedAt returns Time when the server has started
	StartedAt() time.Time
	// ListenURLs is the list of URLs that the server listens on
	ListenURLs() []string
	// Hostname is the hostname
	Hostname() string
	// LocalIP is the local IP4
	LocalIP() string
	// Discovery returns Discovery interface
	Discovery() discovery.Discovery
	// Err returns error channel
	Err() <-chan error
	// Close gracefully shuts down all servers/listeners.
	// Client requests will be terminated with request timeout.
	// After timeout, enforce remaning requests be closed immediately.
	Close()
}

GServer is the interface for gRPC server

func Start

func Start(
	name string,
	cfg *Config,
	container *dig.Container,
	serviceFactories map[string]ServiceFactory,
	opts ...Option,
) (GServer, error)

Start returns running Server

type KeepAliveCfg

type KeepAliveCfg struct {
	// MinTime is the minimum interval that a client should wait before pinging server.
	MinTime time.Duration `json:"min_time,omitempty" yaml:"min_time,omitempty"`

	// Interval is the frequency of server-to-client ping to check if a connection is alive.
	Interval time.Duration `json:"interval,omitempty" yaml:"interval,omitempty"`

	// Timeout is the additional duration of wait before closing a non-responsive connection, use 0 to disable.
	Timeout time.Duration `json:"timeout,omitempty" yaml:"timeout,omitempty"`
}

KeepAliveCfg settings

type Middleware

type Middleware func(handler http.Handler) http.Handler

Middleware defines middleware handler

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is an option that can be passed to New(). Option configures how we set up the client

func WithMiddleware

func WithMiddleware(otherHandler Middleware) Option

WithMiddleware option to provide HTTP handler

func WithStreamServerInterceptor

func WithStreamServerInterceptor(other grpc.StreamServerInterceptor) Option

WithStreamServerInterceptor option to provide RPC StreamServerInterceptor

func WithUnaryServerInterceptor

func WithUnaryServerInterceptor(other grpc.UnaryServerInterceptor) Option

WithUnaryServerInterceptor option to provide RPC UnaryServerInterceptor

type RateLimit

type RateLimit struct {
	// Enabled specifies if the Rate Limititing is enabled.
	Enabled *bool `json:"enabled,omitempty" yaml:"enabled,omitempty"`
	// RequestsPerSecond specifies the maximum number of requests per second.
	RequestsPerSecond int `json:"requests_per_second,omitempty" yaml:"requests_per_second,omitempty"`
	// ExpirationTTL specifies the TTL for token bucket, default 10 mins
	ExpirationTTL time.Duration `json:"expiration_ttl,omitempty" yaml:"expiration_ttl,omitempty"`
	// HeadersIPLookups, default is  "X-Forwarded-For", "X-Real-IP" or "RemoteAddr".
	HeadersIPLookups []string `json:"headers_ip_lookups,omitempty" yaml:"headers_ip_lookups,omitempty"`
	// Metods, can be: "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS".
	Metods []string `json:"metods,omitempty" yaml:"metods,omitempty"`
}

RateLimit contains configuration for Rate Limititing.

func (*RateLimit) GetEnabled

func (c *RateLimit) GetEnabled() bool

GetEnabled specifies if the Rate Limititing is enabled.

type RouteRegistrator

type RouteRegistrator interface {
	RegisterRoute(restserver.Router)
}

RouteRegistrator provides interface to register HTTP route

type Server

type Server struct {
	Listeners []net.Listener
	// contains filtered or unexported fields
}

Server contains a running server and its listeners.

Example
sigs := make(chan os.Signal, 2)

cfg := &gserver.Config{
	ListenURLs: []string{"https://127.0.0.1:12345", "unix:///tmp/gserver_test.sock"},
	Services:   []string{"test"},
	KeepAlive: gserver.KeepAliveCfg{
		MinTime:  time.Second,
		Interval: time.Second,
		Timeout:  time.Second,
	},
	ServerTLS: &gserver.TLSInfo{
		CertFile:      "testdata/test-server.pem",
		KeyFile:       "testdata/test-server-key.pem",
		TrustedCAFile: "testdata/test-server-rootca.pem",
	},
	RateLimit: &gserver.RateLimit{
		RequestsPerSecond: 10,
	},
}

c := mockappcontainer.NewBuilder().
	WithJwtParser(nil).
	WithDiscovery(discovery.New()).
	Container()

fact := map[string]gserver.ServiceFactory{
	"test": testServiceFactory,
}
fmt.Println("starting server")
srv, err := gserver.Start("Empty", cfg, c, fact)
if err != nil {
	panic("unable to start the server: " + err.Error())
}

go func() {
	// Send STOP signal after few seconds,
	// in production the service should listen to
	// os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGUSR2, syscall.SIGABRT events
	time.Sleep(3 * time.Second)
	fmt.Println("sending syscall.SIGTERM signal")
	sigs <- syscall.SIGTERM
}()

// register for signals, and wait to be shutdown
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM)
// Block until a signal is received.
sig := <-sigs

fmt.Printf("received signal: %v\n", sig)

srv.Close()
fmt.Println("stopped server")
Output:

starting server
sending syscall.SIGTERM signal
received signal: terminated
stopped server

func (*Server) AddService

func (e *Server) AddService(svc Service)

AddService to the server

func (*Server) Close

func (e *Server) Close()

Close gracefully shuts down all servers/listeners. Client requests will be terminated with request timeout. After timeout, enforce remaning requests be closed immediately.

func (*Server) Configuration

func (e *Server) Configuration() *Config

Configuration of the server

func (*Server) Discovery

func (e *Server) Discovery() discovery.Discovery

Discovery returns Discovery interface

func (*Server) Err

func (e *Server) Err() <-chan error

Err returns error channel

func (*Server) Hostname

func (e *Server) Hostname() string

Hostname is the hostname

func (*Server) IsReady

func (e *Server) IsReady() bool

IsReady returns true when the server is ready to serve

func (*Server) ListenURLs

func (e *Server) ListenURLs() []string

ListenURLs is the list of URLs that the server listens on

func (*Server) LocalIP

func (e *Server) LocalIP() string

LocalIP is the local IP4

func (*Server) Name

func (e *Server) Name() string

Name returns server name

func (*Server) Service

func (e *Server) Service(name string) Service

Service returns service by name

func (*Server) StartedAt

func (e *Server) StartedAt() time.Time

StartedAt returns Time when the server has started

type Service

type Service interface {
	Name() string
	Close()
	// IsReady indicates that service is ready to serve its end-points
	IsReady() bool
}

Service provides a way for subservices to be registered so they get added to the http API.

type ServiceFactory

type ServiceFactory func(GServer) interface{}

ServiceFactory is interface to create Services

type StartSubcriber

type StartSubcriber interface {
	// OnStarted is called when the server started and
	// is ready to serve requests
	OnStarted() error
}

StartSubcriber provides

type SwaggerCfg

type SwaggerCfg struct {
	// Enabled allows Swagger
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Files is a map of service name to location
	Files map[string]string `json:"files" yaml:"files"`
}

SwaggerCfg specifies the configuration for Swagger

type TLSInfo

type TLSInfo struct {

	// CertFile specifies location of the cert
	CertFile string `json:"cert,omitempty" yaml:"cert,omitempty"`

	// KeyFile specifies location of the key
	KeyFile string `json:"key,omitempty" yaml:"key,omitempty"`

	// TrustedCAFile specifies location of the trusted Root file
	TrustedCAFile string `json:"trusted_ca,omitempty" yaml:"trusted_ca,omitempty"`

	// CRLFile specifies location of the CRL
	CRLFile string `json:"crl,omitempty" yaml:"crl,omitempty"`

	// OCSPFile specifies location of the OCSP response
	OCSPFile string `json:"ocsp,omitempty" yaml:"ocsp,omitempty"`

	// CipherSuites allows to speciy Cipher suites
	CipherSuites []string `json:"cipher_suites,omitempty" yaml:"cipher_suites,omitempty"`

	// ClientCertAuth controls client auth
	ClientCertAuth *bool `json:"client_cert_auth,omitempty" yaml:"client_cert_auth,omitempty"`
}

TLSInfo contains configuration info for the TLS

func (*TLSInfo) Empty

func (info *TLSInfo) Empty() bool

Empty returns true if TLS info is empty

func (*TLSInfo) GetClientCertAuth

func (info *TLSInfo) GetClientCertAuth() bool

GetClientCertAuth controls client auth

func (*TLSInfo) String

func (info *TLSInfo) String() string

Directories

Path Synopsis
Package credentials implements gRPC credential interface with etcd specific logic.
Package credentials implements gRPC credential interface with etcd specific logic.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL