server

package
v0.0.0-...-5f64320 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2026 License: Apache-2.0 Imports: 49 Imported by: 37

Documentation

Index

Constants

View Source
const (
	// DefaultNetwork  the host resolves to multiple IP addresses,
	// Dial will try each IP address in order until one succeeds
	DefaultNetwork = "tcp"
	// NetworkTCPV4 for IPV4 only
	NetworkTCPV4 = "tcp4"
)

Listen on the named network

Variables

View Source
var (
	ErrInvalidLengthFakeServer = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowFakeServer   = fmt.Errorf("proto: integer overflow")
)

Functions

func BuildHTTPMiddleware

func BuildHTTPMiddleware(cfg Config, router *mux.Router, metrics *Metrics, logger gokit_log.Logger) ([]middleware.Interface, error)

func RegisterFakeServerServer

func RegisterFakeServerServer(s *grpc.Server, srv FakeServerServer)

func RegisterInstrumentation

func RegisterInstrumentation(router *mux.Router)

RegisterInstrumentation on the given router.

func RegisterInstrumentationWithGatherer

func RegisterInstrumentationWithGatherer(router *mux.Router, gatherer prometheus.Gatherer)

RegisterInstrumentationWithGatherer on the given router.

Types

type Config

type Config struct {
	MetricsNamespace string `yaml:"-"`
	// Set to > 1 to add native histograms to requestDuration.
	// See documentation for NativeHistogramBucketFactor in
	// https://pkg.go.dev/github.com/prometheus/client_golang/prometheus#HistogramOpts
	// for details. A generally useful value is 1.1.
	MetricsNativeHistogramFactor float64 `yaml:"-"`
	// MetricsMessageSizeNativeHistograms enables use of MetricsNativeHistogramFactor for response_message_bytes,
	// request_message_bytes metrics
	MetricsMessageSizeNativeHistograms bool `yaml:"-"`

	HTTPListenNetwork           string `yaml:"http_listen_network"`
	HTTPListenAddress           string `yaml:"http_listen_address"`
	HTTPListenPort              int    `yaml:"http_listen_port"`
	HTTPConnLimit               int    `yaml:"http_listen_conn_limit"`
	GRPCListenNetwork           string `yaml:"grpc_listen_network"`
	GRPCListenAddress           string `yaml:"grpc_listen_address"`
	GRPCListenPort              int    `yaml:"grpc_listen_port"`
	GRPCConnLimit               int    `yaml:"grpc_listen_conn_limit"`
	GRPCCollectMaxStreamsByConn bool   `yaml:"grpc_collect_max_streams_by_conn"`
	ProxyProtocolEnabled        bool   `yaml:"proxy_protocol_enabled"`

	CipherSuites  string    `yaml:"tls_cipher_suites"`
	MinVersion    string    `yaml:"tls_min_version"`
	HTTPTLSConfig TLSConfig `yaml:"http_tls_config"`
	GRPCTLSConfig TLSConfig `yaml:"grpc_tls_config"`

	RegisterInstrumentation                  bool `yaml:"register_instrumentation"`
	ReportGRPCCodesInInstrumentationLabel    bool `yaml:"report_grpc_codes_in_instrumentation_label_enabled"`
	ReportHTTP4XXCodesInInstrumentationLabel bool `yaml:"-"`
	ExcludeRequestInLog                      bool `yaml:"-"`
	DisableRequestSuccessLog                 bool `yaml:"-"`

	PerTenantInstrumentation middleware.PerTenantCallback `yaml:"-"`

	ServerGracefulShutdownTimeout time.Duration `yaml:"graceful_shutdown_timeout"`
	HTTPServerReadTimeout         time.Duration `yaml:"http_server_read_timeout"`
	HTTPServerReadHeaderTimeout   time.Duration `yaml:"http_server_read_header_timeout"`
	HTTPServerWriteTimeout        time.Duration `yaml:"http_server_write_timeout"`
	HTTPServerIdleTimeout         time.Duration `yaml:"http_server_idle_timeout"`

	HTTPLogClosedConnectionsWithoutResponse bool `yaml:"http_log_closed_connections_without_response_enabled"`

	GRPCOptions                   []grpc.ServerOption            `yaml:"-"`
	GRPCTapHandles                []tap.ServerInHandle           `yaml:"-"`
	GRPCMiddleware                []grpc.UnaryServerInterceptor  `yaml:"-"`
	GRPCStreamMiddleware          []grpc.StreamServerInterceptor `yaml:"-"`
	HTTPMiddleware                []middleware.Interface         `yaml:"-"`
	Router                        *mux.Router                    `yaml:"-"`
	DoNotAddDefaultHTTPMiddleware bool                           `yaml:"-"`

	GRPCServerMaxRecvMsgSize           int           `yaml:"grpc_server_max_recv_msg_size"`
	GRPCServerMaxSendMsgSize           int           `yaml:"grpc_server_max_send_msg_size"`
	GRPCServerMaxConcurrentStreams     uint          `yaml:"grpc_server_max_concurrent_streams"`
	GRPCServerMaxConnectionIdle        time.Duration `yaml:"grpc_server_max_connection_idle"`
	GRPCServerMaxConnectionAge         time.Duration `yaml:"grpc_server_max_connection_age"`
	GRPCServerMaxConnectionAgeGrace    time.Duration `yaml:"grpc_server_max_connection_age_grace"`
	GRPCServerTime                     time.Duration `yaml:"grpc_server_keepalive_time"`
	GRPCServerTimeout                  time.Duration `yaml:"grpc_server_keepalive_timeout"`
	GRPCServerMinTimeBetweenPings      time.Duration `yaml:"grpc_server_min_time_between_pings"`
	GRPCServerPingWithoutStreamAllowed bool          `yaml:"grpc_server_ping_without_stream_allowed"`
	GRPCServerNumWorkers               int           `yaml:"grpc_server_num_workers"`
	GRPCServerStatsTrackingEnabled     bool          `yaml:"grpc_server_stats_tracking_enabled"`
	GRPCServerRecvBufferPoolsEnabled   bool          `yaml:"grpc_server_recv_buffer_pools_enabled"`
	GRPCServerReadBufferSize           int           `yaml:"grpc_server_read_buffer_size"`
	GRPCServerWriteBufferSize          int           `yaml:"grpc_server_write_buffer_size"`

	LogFormat                    string           `yaml:"log_format"`
	LogLevel                     log.Level        `yaml:"log_level"`
	Log                          gokit_log.Logger `yaml:"-"`
	LogSourceIPs                 bool             `yaml:"log_source_ips_enabled"`
	LogSourceIPsFull             bool             `yaml:"log_source_ips_full"`
	LogSourceIPsHeader           string           `yaml:"log_source_ips_header"`
	LogSourceIPsRegex            string           `yaml:"log_source_ips_regex"`
	LogRequestHeaders            bool             `yaml:"log_request_headers"`
	LogRequestAtInfoLevel        bool             `yaml:"log_request_at_info_level_enabled"`
	LogRequestExcludeHeadersList string           `yaml:"log_request_exclude_headers_list"`

	TraceRequestHeaders            bool   `yaml:"trace_request_headers"`
	TraceRequestExcludeHeadersList string `yaml:"trace_request_exclude_headers_list"`

	// If not set, default signal handler is used.
	SignalHandler SignalHandler `yaml:"-"`

	// If not set, default Prometheus registry is used.
	Registerer prometheus.Registerer `yaml:"-"`
	Gatherer   prometheus.Gatherer   `yaml:"-"`

	PathPrefix string `yaml:"http_path_prefix"`

	// This limiter is called for every started and finished gRPC request.
	GrpcMethodLimiter GrpcInflightMethodLimiter `yaml:"-"`

	Throughput Throughput `yaml:"-"`

	ClusterValidation clusterutil.ServerClusterValidationConfig `yaml:"cluster_validation" category:"experimental"`

	// PublicEndpointFn will create a new trace instead of continuing an
	// existing trace when the function returns true. A span link will be used
	// to connect to any existing trace. It only works if using Open-Telemetry
	// tracing.
	PublicEndpointFn func(*http.Request) bool `yaml:"-"`
	CreateNewTraces  bool                     `yaml:"create_new_traces"`
}

Config for a Server

func (*Config) RegisterFlags

func (cfg *Config) RegisterFlags(f *flag.FlagSet)

RegisterFlags adds the flags required to config this to the given FlagSet

func (*Config) Validate

func (cfg *Config) Validate() error

type FailWithHTTPErrorRequest

type FailWithHTTPErrorRequest struct {
	Code int32 `protobuf:"varint,1,opt,name=Code,proto3" json:"Code,omitempty"`
}

func (*FailWithHTTPErrorRequest) Descriptor

func (*FailWithHTTPErrorRequest) Descriptor() ([]byte, []int)

func (*FailWithHTTPErrorRequest) Equal

func (this *FailWithHTTPErrorRequest) Equal(that interface{}) bool

func (*FailWithHTTPErrorRequest) GetCode

func (m *FailWithHTTPErrorRequest) GetCode() int32

func (*FailWithHTTPErrorRequest) GoString

func (this *FailWithHTTPErrorRequest) GoString() string

func (*FailWithHTTPErrorRequest) Marshal

func (m *FailWithHTTPErrorRequest) Marshal() (dAtA []byte, err error)

func (*FailWithHTTPErrorRequest) MarshalTo

func (m *FailWithHTTPErrorRequest) MarshalTo(dAtA []byte) (int, error)

func (*FailWithHTTPErrorRequest) MarshalToSizedBuffer

func (m *FailWithHTTPErrorRequest) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*FailWithHTTPErrorRequest) ProtoMessage

func (*FailWithHTTPErrorRequest) ProtoMessage()

func (*FailWithHTTPErrorRequest) Reset

func (m *FailWithHTTPErrorRequest) Reset()

func (*FailWithHTTPErrorRequest) Size

func (m *FailWithHTTPErrorRequest) Size() (n int)

func (*FailWithHTTPErrorRequest) String

func (this *FailWithHTTPErrorRequest) String() string

func (*FailWithHTTPErrorRequest) Unmarshal

func (m *FailWithHTTPErrorRequest) Unmarshal(dAtA []byte) error

func (*FailWithHTTPErrorRequest) XXX_DiscardUnknown

func (m *FailWithHTTPErrorRequest) XXX_DiscardUnknown()

func (*FailWithHTTPErrorRequest) XXX_Marshal

func (m *FailWithHTTPErrorRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*FailWithHTTPErrorRequest) XXX_Merge

func (m *FailWithHTTPErrorRequest) XXX_Merge(src proto.Message)

func (*FailWithHTTPErrorRequest) XXX_Size

func (m *FailWithHTTPErrorRequest) XXX_Size() int

func (*FailWithHTTPErrorRequest) XXX_Unmarshal

func (m *FailWithHTTPErrorRequest) XXX_Unmarshal(b []byte) error

type FakeServerClient

type FakeServerClient interface {
	Succeed(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error)
	FailWithError(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error)
	FailWithHTTPError(ctx context.Context, in *FailWithHTTPErrorRequest, opts ...grpc.CallOption) (*empty.Empty, error)
	Sleep(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*empty.Empty, error)
	StreamSleep(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (FakeServer_StreamSleepClient, error)
	ReturnProxyProtoCallerIP(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*ProxyProtoIPResponse, error)
}

FakeServerClient is the client API for FakeServer service.

For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.

func NewFakeServerClient

func NewFakeServerClient(cc *grpc.ClientConn) FakeServerClient

type FakeServerServer

type FakeServerServer interface {
	Succeed(context.Context, *empty.Empty) (*empty.Empty, error)
	FailWithError(context.Context, *empty.Empty) (*empty.Empty, error)
	FailWithHTTPError(context.Context, *FailWithHTTPErrorRequest) (*empty.Empty, error)
	Sleep(context.Context, *empty.Empty) (*empty.Empty, error)
	StreamSleep(*empty.Empty, FakeServer_StreamSleepServer) error
	ReturnProxyProtoCallerIP(context.Context, *empty.Empty) (*ProxyProtoIPResponse, error)
}

FakeServerServer is the server API for FakeServer service.

type FakeServer_StreamSleepClient

type FakeServer_StreamSleepClient interface {
	Recv() (*empty.Empty, error)
	grpc.ClientStream
}

type FakeServer_StreamSleepServer

type FakeServer_StreamSleepServer interface {
	Send(*empty.Empty) error
	grpc.ServerStream
}

type GrpcInflightMethodLimiter

type GrpcInflightMethodLimiter interface {
	// RPCCallStarting is called before request has been read into memory.
	// All that's known about the request at this point is grpc method name.
	//
	// Returned context is used during the remainder of the gRPC call.
	//
	// Returned error should be convertible to gRPC Status via status.FromError,
	// otherwise gRPC-server implementation-specific error will be returned to the client (codes.PermissionDenied in grpc@v1.55.0).
	RPCCallStarting(ctx context.Context, methodName string, md metadata.MD) (context.Context, error)

	// RPCCallProcessing is called by a server interceptor, allowing request pre-processing or request blocking to be
	// performed. The returned function will be applied after the request is handled, providing any error that occurred while
	// handling the request.
	RPCCallProcessing(ctx context.Context, methodName string) (func(error), error)

	// RPCCallFinished is called when an RPC call is finished being handled.
	// Under certain very rare race conditions it might be called earlier than the actual request processing is finished.
	RPCCallFinished(ctx context.Context)
}

type Metrics

type Metrics struct {
	TCPConnections             *prometheus.GaugeVec
	TCPConnectionsLimit        *prometheus.GaugeVec
	GRPCConcurrentStreamsLimit *prometheus.GaugeVec
	RequestDuration            *prometheus.HistogramVec
	PerTenantRequestDuration   *prometheus.HistogramVec
	PerTenantRequestTotal      *prometheus.CounterVec
	ReceivedMessageSize        *prometheus.HistogramVec
	SentMessageSize            *prometheus.HistogramVec
	InflightRequests           *prometheus.GaugeVec
	RequestThroughput          *prometheus.HistogramVec
	InvalidClusterRequests     *prometheus.CounterVec
}

func NewServerMetrics

func NewServerMetrics(cfg Config) *Metrics

type ProxyProtoIPResponse

type ProxyProtoIPResponse struct {
	IP string `protobuf:"bytes,1,opt,name=IP,proto3" json:"IP,omitempty"`
}

func (*ProxyProtoIPResponse) Descriptor

func (*ProxyProtoIPResponse) Descriptor() ([]byte, []int)

func (*ProxyProtoIPResponse) Equal

func (this *ProxyProtoIPResponse) Equal(that interface{}) bool

func (*ProxyProtoIPResponse) GetIP

func (m *ProxyProtoIPResponse) GetIP() string

func (*ProxyProtoIPResponse) GoString

func (this *ProxyProtoIPResponse) GoString() string

func (*ProxyProtoIPResponse) Marshal

func (m *ProxyProtoIPResponse) Marshal() (dAtA []byte, err error)

func (*ProxyProtoIPResponse) MarshalTo

func (m *ProxyProtoIPResponse) MarshalTo(dAtA []byte) (int, error)

func (*ProxyProtoIPResponse) MarshalToSizedBuffer

func (m *ProxyProtoIPResponse) MarshalToSizedBuffer(dAtA []byte) (int, error)

func (*ProxyProtoIPResponse) ProtoMessage

func (*ProxyProtoIPResponse) ProtoMessage()

func (*ProxyProtoIPResponse) Reset

func (m *ProxyProtoIPResponse) Reset()

func (*ProxyProtoIPResponse) Size

func (m *ProxyProtoIPResponse) Size() (n int)

func (*ProxyProtoIPResponse) String

func (this *ProxyProtoIPResponse) String() string

func (*ProxyProtoIPResponse) Unmarshal

func (m *ProxyProtoIPResponse) Unmarshal(dAtA []byte) error

func (*ProxyProtoIPResponse) XXX_DiscardUnknown

func (m *ProxyProtoIPResponse) XXX_DiscardUnknown()

func (*ProxyProtoIPResponse) XXX_Marshal

func (m *ProxyProtoIPResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*ProxyProtoIPResponse) XXX_Merge

func (m *ProxyProtoIPResponse) XXX_Merge(src proto.Message)

func (*ProxyProtoIPResponse) XXX_Size

func (m *ProxyProtoIPResponse) XXX_Size() int

func (*ProxyProtoIPResponse) XXX_Unmarshal

func (m *ProxyProtoIPResponse) XXX_Unmarshal(b []byte) error

type Server

type Server struct {
	HTTP       *mux.Router
	HTTPServer *http.Server
	GRPC       *grpc.Server
	Log        gokit_log.Logger
	Registerer prometheus.Registerer
	Gatherer   prometheus.Gatherer
	// contains filtered or unexported fields
}

Server wraps a HTTP and gRPC server, and some common initialization.

Servers will be automatically instrumented for Prometheus metrics.

func New

func New(cfg Config) (*Server, error)

New makes a new Server. It will panic if the metrics cannot be registered.

func NewWithMetrics

func NewWithMetrics(cfg Config, metrics *Metrics) (*Server, error)

NewWithMetrics makes a new Server using the provided Metrics. It will not attempt to register the metrics, the user is responsible for doing so.

func (*Server) GRPCListenAddr

func (s *Server) GRPCListenAddr() net.Addr

GRPCListenAddr exposes `net.Addr` that `Server` is listening to for GRPC connections.

func (*Server) HTTPListenAddr

func (s *Server) HTTPListenAddr() net.Addr

HTTPListenAddr exposes `net.Addr` that `Server` is listening to for HTTP connections.

func (*Server) Run

func (s *Server) Run() error

Run the server; blocks until SIGTERM (if signal handling is enabled), an error is received, or Stop() is called.

func (*Server) Shutdown

func (s *Server) Shutdown()

Shutdown the server, gracefully. Should be defered after New().

func (*Server) Stop

func (s *Server) Stop()

Stop unblocks Run().

type SignalHandler

type SignalHandler interface {
	// Starts the signals handler. This method is blocking, and returns only after signal is received,
	// or "Stop" is called.
	Loop()

	// Stop blocked "Loop" method.
	Stop()
}

SignalHandler used by Server.

type TLSConfig

type TLSConfig struct {
	TLSCert       string        `yaml:"cert" doc:"description=Server TLS certificate. This configuration parameter is YAML only."`
	TLSKey        config.Secret `yaml:"key" doc:"description=Server TLS key. This configuration parameter is YAML only."`
	ClientCAsText string        `` /* 140-byte string literal not displayed */
	TLSCertPath   string        `yaml:"cert_file"`
	TLSKeyPath    string        `yaml:"key_file"`
	ClientAuth    string        `yaml:"client_auth_type"`
	ClientCAs     string        `yaml:"client_ca_file"`
}

TLSConfig contains TLS parameters for Config.

type Throughput

type Throughput struct {
	LatencyCutoff time.Duration `yaml:"throughput_latency_cutoff"`
	Unit          string        `yaml:"throughput_unit"`
}

type UnimplementedFakeServerServer

type UnimplementedFakeServerServer struct {
}

UnimplementedFakeServerServer can be embedded to have forward compatible implementations.

func (*UnimplementedFakeServerServer) FailWithError

func (*UnimplementedFakeServerServer) FailWithError(ctx context.Context, req *empty.Empty) (*empty.Empty, error)

func (*UnimplementedFakeServerServer) FailWithHTTPError

func (*UnimplementedFakeServerServer) ReturnProxyProtoCallerIP

func (*UnimplementedFakeServerServer) ReturnProxyProtoCallerIP(ctx context.Context, req *empty.Empty) (*ProxyProtoIPResponse, error)

func (*UnimplementedFakeServerServer) Sleep

func (*UnimplementedFakeServerServer) StreamSleep

func (*UnimplementedFakeServerServer) Succeed

Jump to

Keyboard shortcuts

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