apiserver

package module
v0.0.0-...-b563d55 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2020 License: Apache-2.0 Imports: 48 Imported by: 0

README

API Server

Build Status codecov GoDoc License Go Report Card Run Status GitHub release DepShield Badge DeepSource

API Server is an opionated harness to serve gRPC and HTTP servers.

Example

This example runs a server hosted on gRPC with an HTTP REST API.

func main() {
  servemain.Serve(BindServer)
}

func BindServer(p *apiserver.ServerParams) {
  // Handler for the gRPC traffic.
  es := &echoHandler{}

  // Adds the Echo service gRPC and HTTP REST bindings to the server.
  p.AddBinding(func(s *grpc.Server) {
      pb.RegisterEchoServer(s, es)
    },
    pb.RegisterEchoHandlerFromEndpoint,
    apiserver.AlwaysReady)
  }
}

Features

  • gRPC and HTTP REST proxy
  • TLS or insecure serving modes.
  • OpenCensus Metrics
  • zPages
  • Certificate Tools
  • Logging

Documentation

Overview

Package apiserver is an opinionated server harness for gRPC and HTTP servers that serve an API.

Features

* TLS (RSA and ECDSA certificates) and Insecure modes. * Readiness probe /healthz?readiness=true * Liveness probe /healthz * OpenCensus monitoring for Prometheus, OpenZipkin, and Jaeger. * Server Health zPages * Fault Injection * Test harness * Zap Logging * Multiple Interceptors * Loopback Clients

Example

 func main() {
	  servemain.Serve(app.BindServer)
 }

 func BindServer(p *apiserver.ServerParams) {
   es := &echoHandler{}
   p.AddBinding(func(s *grpc.Server) {
     pb.RegisterEchoServer(s, es)
   },
     pb.RegisterEchoHandlerFromEndpoint,
    apiserver.AlwaysReady)
   }

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AlwaysReady

func AlwaysReady(context.Context) error

AlwaysReady indicates that the service does can always service traffic.

func ConfigureMonitoring

func ConfigureMonitoring(sp *ServerParams)

ConfigureMonitoring configures monitoring.

func GRPCClient

func GRPCClient(params *ClientParams) (*grpc.ClientConn, error)

GRPCClient returns a client based on parameters.

func HTTPClient

func HTTPClient(params *ClientParams) (*http.Client, string, error)

HTTPClient returns a client based on parameters.

func Maybe

func Maybe(f func() error) error

Maybe wraps a func() error function with randomized faults.

func MustServeBindingForever

func MustServeBindingForever(p *ServerParams, bindings ...func(*ServerParams))

MustServeBindingForever is similar to MustServeForever but for service binding functions.

func MustServeForever

func MustServeForever(p *ServerParams)

MustServeForever creates a server from parameters and runs the server indefinitely.

func NewCounter

func NewCounter(name string, description string, tagKeys ...tag.Key) *stats.Int64Measure

NewCounter creates a counter metric.

func NewDistribution

func NewDistribution(name string, description string, tagKeys ...tag.Key) *stats.Int64Measure

NewDistribution creates a histrogram metric for tracking latencies for tracking RPC requests.

func NewDistributionForLongRunningOperations

func NewDistributionForLongRunningOperations(name string, description string, tagKeys ...tag.Key) *stats.Int64Measure

NewDistributionForLongRunningOperations creates a histrogram metric for tracking latencies for long running operations.

func NewGauge

func NewGauge(name string, description string, tagKeys ...tag.Key) *stats.Int64Measure

NewGauge creates a gauge metric.

func RandomFailure

func RandomFailure() error

RandomFailure occasionally returns a failure.

func StartServingIndefinitely

func StartServingIndefinitely(params *ServerParams) (func(), func(), error)

StartServingIndefinitely creates a server from parameters and runs the server First method returned is used to wait indefinitely, second function is for manually killing the server.

Types

type ClientParams

type ClientParams struct {
	Address                 string
	TrustedCertificate      []byte
	EnableRPCLogging        bool
	EnableRPCPayloadLogging bool
	EnableMetrics           bool
}

ClientParams configure a gRPC/HTTP client.

type GrpcBinder

type GrpcBinder func(*grpc.Server)

GrpcBinder is a callback function for binding to a gRPC server. This method may be called multiple times based on the number of endpoints.

type GrpcProxyBinder

type GrpcProxyBinder func(context.Context, *runtime.ServeMux, string, []grpc.DialOption) error

GrpcProxyBinder is a callback function for binding to a gRPC server with HTTP(S). This method may be called multiple times based on the number of endpoints.

type MultiClose

type MultiClose struct {
	// contains filtered or unexported fields
}

MultiClose is a helper for calling multiple close functions at the end of a program.

func NewMultiClose

func NewMultiClose() *MultiClose

NewMultiClose creates a new aggregated close functor.

func (*MultiClose) AddCloseFunc

func (mc *MultiClose) AddCloseFunc(closer func())

AddCloseFunc adds a close function.

func (*MultiClose) AddCloseWithErrorFunc

func (mc *MultiClose) AddCloseWithErrorFunc(closer func() error)

AddCloseWithErrorFunc adds a close function.

func (*MultiClose) Close

func (mc *MultiClose) Close()

Close calls all the close callbacks once.

type ReadinessCheckFunc

type ReadinessCheckFunc func(context.Context) error

ReadinessCheckFunc is a method that runs while a prober checks for the server's ability to serve traffic. If a readiness check function returns an error it's reported to the user as an HTTP 503 "Service Unavailable". This method is periodically run.

type Self

type Self struct {
	// contains filtered or unexported fields
}

Self is a descriptor of this server. It contains information to call back to the server itself.

func (*Self) NewGRPCParams

func (s *Self) NewGRPCParams() *ClientParams

NewGRPCParams returns parameters that can be used to communicate with the server via gRPC.

func (*Self) NewHTTPParams

func (s *Self) NewHTTPParams() *ClientParams

NewHTTPParams returns parameters that can be used to communicate with the server via HTTP.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server manages gRPC and HTTP server endpoints. It provides many capabilities that are automatically configured such as pprof, health checking, etc.

func NewServer

func NewServer() *Server

NewServer creates a new server.

func (*Server) Start

func (s *Server) Start(p *ServerParams) (func(), error)

Start initializes the server. Returns a wait function. Returns immediately if called while running.

func (*Server) StartAndWait

func (s *Server) StartAndWait(p *ServerParams) error

StartAndWait initializes the server and waits for it until it's able to serve traffic. Returns immediately if called while running.

func (*Server) Stop

func (s *Server) Stop()

Stop shutsdown the server. Once this method is called the server may not be re-used.

type ServerParams

type ServerParams struct {
	// contains filtered or unexported fields
}

ServerParams is the configuration of the server.

func NewServerParams

func NewServerParams() *ServerParams

NewServerParams creates a new initialized server params with default values.

func (*ServerParams) AddBinding

func (sp *ServerParams) AddBinding(grpcBinding GrpcBinder, proxyBinding GrpcProxyBinder, readinessCheckFunc ReadinessCheckFunc) *ServerParams

AddBinding adds registration of a gRPC service against gRPC and HTTP proxy.

func (*ServerParams) AddCloseFunc

func (sp *ServerParams) AddCloseFunc(closer func()) *ServerParams

AddCloseFunc adds a close function.

func (*ServerParams) AddCloseWithErrorFunc

func (sp *ServerParams) AddCloseWithErrorFunc(closer func() error) *ServerParams

AddCloseWithErrorFunc adds a close function.

func (*ServerParams) AddGrpc

func (sp *ServerParams) AddGrpc(grpcBinding GrpcBinder) ServiceRegistration

AddGrpc adds registration of a gRPC service.

func (*ServerParams) AddProxy

func (sp *ServerParams) AddProxy(proxyBinding GrpcProxyBinder) ServiceRegistration

AddProxy adds HTTP proxy handler.

func (*ServerParams) AddReadinessCheck

func (sp *ServerParams) AddReadinessCheck(readinessCheckFunc ReadinessCheckFunc) ServiceRegistration

AddReadinessCheck adds service readiness check.

func (*ServerParams) AddStreamInterceptor

func (sp *ServerParams) AddStreamInterceptor(s grpc.StreamServerInterceptor) *ServerParams

AddStreamInterceptor adds a gRPC Stream interceptor to the server.

func (*ServerParams) AddUnaryInterceptor

func (sp *ServerParams) AddUnaryInterceptor(i grpc.UnaryServerInterceptor) *ServerParams

AddUnaryInterceptor adds a gRPC Unary interceptor to the server.

func (*ServerParams) GetSelf

func (sp *ServerParams) GetSelf() *Self

GetSelf returns the server descriptor that can be used to communicate with itself.

func (*ServerParams) Handle

func (sp *ServerParams) Handle(pattern string, handler http.Handler) *ServerParams

Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func (*ServerParams) HandleFunc

func (sp *ServerParams) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) *ServerParams

HandleFunc registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.

func (*ServerParams) SetDebugEndpoint

func (sp *ServerParams) SetDebugEndpoint(endpoint string) *ServerParams

SetDebugEndpoint configures the HTTP page that will return debug pages. If the value is empty, debug pages will not be available. Default: /debug

func (*ServerParams) SetFaultRatio

func (sp *ServerParams) SetFaultRatio(faultRatio float64) *ServerParams

SetFaultRatio determines how often to send a random failure instead of calling the RPC handler.

func (*ServerParams) SetGrpcListener

func (sp *ServerParams) SetGrpcListener(listener net.Listener) *ServerParams

SetGrpcListener sets the TCP listener (already opened port) to bind the server to the gRPC serving path.

func (*ServerParams) SetGrpcPort

func (sp *ServerParams) SetGrpcPort(port int) *ServerParams

SetGrpcPort sets the port to open for gRPC traffic.

func (*ServerParams) SetGrpcPortFromFlag

func (sp *ServerParams) SetGrpcPortFromFlag(port *int) *ServerParams

SetGrpcPortFromFlag sets the port to open for gRPC traffic.

func (*ServerParams) SetHealthCheckDeadline

func (sp *ServerParams) SetHealthCheckDeadline(healthCheckDeadline time.Duration) *ServerParams

SetHealthCheckDeadline determines how long a health check can wait until it times out.

func (*ServerParams) SetMetricsEndpoint

func (sp *ServerParams) SetMetricsEndpoint(endpoint string) *ServerParams

SetMetricsEndpoint configures the HTTP page that will return metrics. If the value is empty, metrics will not be available. Default: /metrics

func (*ServerParams) SetMonitoringLabels

func (sp *ServerParams) SetMonitoringLabels(labels map[string]string) *ServerParams

SetMonitoringLabels adds labels to monitoring output.

func (*ServerParams) SetProxyListener

func (sp *ServerParams) SetProxyListener(listener net.Listener) *ServerParams

SetProxyListener sets the TCP listener (already opened port) to bind the server to the HTTP/proxy serving path.

func (*ServerParams) SetProxyPort

func (sp *ServerParams) SetProxyPort(port int) *ServerParams

SetProxyPort sets the port to open for HTTP traffic.

func (*ServerParams) SetProxyPortFromFlag

func (sp *ServerParams) SetProxyPortFromFlag(port *int) *ServerParams

SetProxyPortFromFlag sets the port to open for HTTP traffic from a flag.

func (*ServerParams) SetRPCLogging

func (sp *ServerParams) SetRPCLogging(enableRPCLogging bool) *ServerParams

SetRPCLogging configures the server to log all requests and responses. Default: false

func (*ServerParams) SetRPCPayloadLogging

func (sp *ServerParams) SetRPCPayloadLogging(enableRPCPayloadLogging bool) *ServerParams

SetRPCPayloadLogging configures the server to log all requests and responses. Default: false

func (*ServerParams) WithMutualTLS

func (sp *ServerParams) WithMutualTLS() *ServerParams

WithMutualTLS enables TLS serving and requires the client to send an authenticated TLS certificate.

func (*ServerParams) WithTLS

func (sp *ServerParams) WithTLS(publicCertificatePEM []byte, privateKeyPEM []byte) *ServerParams

WithTLS enables TLS support using the public certificate/private key pair.

func (*ServerParams) WithTLSFromFiles

func (sp *ServerParams) WithTLSFromFiles(publicCertFilePath string, privateKeyFilePath string) *ServerParams

WithTLSFromFiles is similar to WithTLS but reads the the public certificate/private key pair from files on disk.

func (*ServerParams) WithTLSWithCA

func (sp *ServerParams) WithTLSWithCA(rootCAPublicCertificatePEM []byte, publicCertificatePEM []byte, privateKeyPEM []byte) *ServerParams

WithTLSWithCA is similar to WithTLS but indicates the public certificate/private key pair were created from a certificate authority. This is preferred.

func (*ServerParams) WithTLSWithCAFromFiles

func (sp *ServerParams) WithTLSWithCAFromFiles(rootCAPublicCertFilePath string, publicCertFilePath string, privateKeyFilePath string) *ServerParams

WithTLSWithCAFromFiles is similar to WithTLSWithCA but reads the the public certificate/private key pair from files on disk.

type ServiceRegistration

type ServiceRegistration interface {
	// AddGrpc adds registration of a gRPC service.
	AddGrpc(grpcBinding GrpcBinder) ServiceRegistration
	// AddProxy adds HTTP proxy handler.
	AddProxy(proxyBinding GrpcProxyBinder) ServiceRegistration
	// AddReadinessCheck adds service readiness check.
	AddReadinessCheck(readinessCheckFunc ReadinessCheckFunc) ServiceRegistration
}

ServiceRegistration provides callbacks to register a service.

Directories

Path Synopsis
example
cmd/echo
Package main is the entry point for echo server.
Package main is the entry point for echo server.
cmd/echoclient
Package main is the entry point for the echo client.
Package main is the entry point for the echo client.
echo
Package echo is the core logic for echo server and client.
Package echo is the core logic for echo server and client.
proto
Package proto is a reverse proxy.
Package proto is a reverse proxy.
Package log provides logging for apiserver.
Package log provides logging for apiserver.
Package testing provides primitives for testing API servers.
Package testing provides primitives for testing API servers.
tools
cert
Package main is the entrypoint for the cert tool.
Package main is the entrypoint for the cert tool.
cert/internal
Package internal holds the logic for generating certificates.
Package internal holds the logic for generating certificates.
cert/testing
Package testing provides easy to use methods for creating certificates using a CA, derived, or standalone certificate.
Package testing provides easy to use methods for creating certificates using a CA, derived, or standalone certificate.

Jump to

Keyboard shortcuts

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