Documentation
¶
Overview ¶
Package keel provides an opinionated runtime for services and jobs running on Kubernetes, with graceful shutdown, structured logging, configuration, OpenTelemetry and health probes.
Server ¶
A Server orchestrates a set of Service values. It is created with NewServer and configured through Option values such as WithHTTPZapService, WithHTTPHealthzService or WithTelemetry. Logging defaults to log.Logger and configuration to config.Config.
svr := keel.NewServer( keel.WithHTTPZapService(true), keel.WithHTTPViperService(true), keel.WithHTTPPrometheusService(true), keel.WithHTTPHealthzService(true), ) svr.AddService(service.NewHTTP(svr.Logger(), "demo", "localhost:8080", handler)) svr.Run()
Services ¶
Init services (registered by the WithHTTPXxxService options or WithInitService) are started immediately inside NewServer. Services added with Server.AddService, Server.AddHTTPService, Server.AddGoRoutine and friends are started by Server.Run. Ready made implementations live in github.com/foomo/keel/service. ServiceFunc adapts a plain function and ServiceEnabler starts and stops a service dynamically.
Graceful shutdown ¶
Server.Run blocks until a shutdown signal (SIGINT and SIGTERM by default, see WithShutdownSignals) is received, Server.ShutdownCancel is called, or a service fails. The server then reports not ready, and calls every registered closer followed by the trace, meter and logger providers, all bounded by the graceful period (KEEL_GRACEFUL_PERIOD seconds, default 30, see WithGracefulPeriod). A closer is any value implementing one of the Close, Shutdown, Stop or Unsubscribe shapes declared in github.com/foomo/keel/interfaces; see IsCloser. Services are registered as closers automatically.
Health probes ¶
Probes are registered per healthz.Type with Server.AddStartupHealthzers, Server.AddReadinessHealthzers, Server.AddLivenessHealthzers and Server.AddAlwaysHealthzers; see IsHealthz for the accepted shapes. They are served by the service enabled through WithHTTPHealthzService.
Jobs ¶
A Job, created with NewJob and configured through JobOption values, runs a list of steps to completion instead of blocking until a signal, as suited for a Kubernetes Job. Both Server and Job implement Runtime.
job := keel.NewJob(keel.JobWithTelemetry())
job.AddStep("migrate", func(ctx context.Context, l *zap.Logger) error {
return migrate(ctx)
})
job.Run()
Index ¶
- Constants
- Variables
- func IsCloser(v any) bool
- func IsHealthz(v any) bool
- type CLI
- func (c *CLI) Add(name, short string, run RunFunc) *cobra.Command
- func (c *CLI) AddCommand(cmds ...*cobra.Command)
- func (c *CLI) AddInit(run RunFunc) *cobra.Command
- func (c *CLI) AddServer(run RunFunc) *cobra.Command
- func (c *CLI) AddSidecar(run RunFunc) *cobra.Command
- func (c *CLI) Execute(args []string) error
- func (c *CLI) Root() *cobra.Command
- func (c *CLI) Run()
- type CLIOption
- type Job
- func (j *Job) AddCloser(closer any)
- func (j *Job) AddClosers(closers ...any)
- func (j *Job) AddStep(name string, fn StepFn)
- func (j *Job) Config() *viper.Viper
- func (j *Job) Context() context.Context
- func (j *Job) Logger() *zap.Logger
- func (j *Job) Meter() metric.Meter
- func (j *Job) Run()
- func (j *Job) RunE() error
- func (j *Job) Tracer() trace.Tracer
- type JobOption
- func JobWithCloser(closer any) JobOption
- func JobWithConfig(c *viper.Viper) JobOption
- func JobWithContext(ctx context.Context) JobOption
- func JobWithGracefulPeriod(gracefulPeriod time.Duration) JobOption
- func JobWithLogFields(fields ...zap.Field) JobOption
- func JobWithLogger(l *zap.Logger) JobOption
- func JobWithName(name string) JobOption
- func JobWithOTLPGRCPLogger(enabled bool) JobOption
- func JobWithOTLPGRPCMeter(enabled bool) JobOption
- func JobWithOTLPGRPCTracer(enabled bool) JobOption
- func JobWithOTLPHTTPLogger(enabled bool) JobOption
- func JobWithOTLPHTTPMeter(enabled bool) JobOption
- func JobWithOTLPHTTPTracer(enabled bool) JobOption
- func JobWithParallel(limit int) JobOption
- func JobWithPushgatewayMeter(url string) JobOption
- func JobWithShutdownSignals(shutdownSignals ...os.Signal) JobOption
- func JobWithStdOutMeter(enabled bool) JobOption
- func JobWithStdOutTracer(enabled bool) JobOption
- func JobWithTelemetry() JobOption
- func JobWithTimeout(timeout time.Duration) JobOption
- type Option
- func WithConfig(c *viper.Viper) Option
- func WithContext(ctx context.Context) Option
- func WithGracefulPeriod(gracefulPeriod time.Duration) Option
- func WithHTTPHealthzService(enabled bool) Option
- func WithHTTPPProfService(enabled bool) Option
- func WithHTTPPrometheusService(enabled bool) Option
- func WithHTTPReadmeService(enabled bool) Optiondeprecated
- func WithHTTPViperService(enabled bool) Option
- func WithHTTPZapService(enabled bool) Option
- func WithInitService(service Service) Option
- func WithLogFields(fields ...zap.Field) Option
- func WithLogger(l *zap.Logger) Option
- func WithOTLPGRCPLogger(enabled bool) Option
- func WithOTLPGRPCMeter(enabled bool) Option
- func WithOTLPGRPCTracer(enabled bool) Option
- func WithOTLPHTTPLogger(enabled bool) Option
- func WithOTLPHTTPMeter(enabled bool) Option
- func WithOTLPHTTPTracer(enabled bool) Option
- func WithPrometheusMeter(enabled bool) Option
- func WithPushgatewayMeter(url string) Option
- func WithPyroscopeService(enabled bool) Option
- func WithRemoteConfig(provider, endpoint, path string) Option
- func WithShutdownSignals(shutdownSignals ...os.Signal) Option
- func WithStdOutLogger(enabled bool) Option
- func WithStdOutMeter(enabled bool) Option
- func WithStdOutTracer(enabled bool) Option
- func WithTelemetry() Option
- type RunFunc
- type Runtime
- type Server
- func (s *Server) AddAlwaysHealthzers(probes ...any)
- func (s *Server) AddCloser(closer any)
- func (s *Server) AddClosers(closers ...any)
- func (s *Server) AddGoRoutine(name string, handler service.GoRoutineFn, opts ...service.GoRoutineOption)
- func (s *Server) AddHTTPService(name, addr string, handler http.Handler, middleware ...keelhttp.Middleware)
- func (s *Server) AddHealthzer(typ healthz.Type, probe any)
- func (s *Server) AddHealthzers(typ healthz.Type, probes ...any)
- func (s *Server) AddInternalHTTPService(handler http.Handler, middleware ...keelhttp.Middleware)
- func (s *Server) AddLivenessHealthzers(probes ...any)
- func (s *Server) AddPublicHTTPService(handler http.Handler, middleware ...keelhttp.Middleware)
- func (s *Server) AddReadinessHealthzers(probes ...any)
- func (s *Server) AddReadmer(readmer interfaces.Readmer)deprecated
- func (s *Server) AddReadmers(readmers ...interfaces.Readmer)deprecated
- func (s *Server) AddService(v Service)
- func (s *Server) AddServices(services ...Service)
- func (s *Server) AddStartupHealthzers(probes ...any)
- func (s *Server) Config() *viper.Viper
- func (s *Server) Context() context.Context
- func (s *Server) Healthz() error
- func (s *Server) Logger() *zap.Logger
- func (s *Server) Meter() metric.Meter
- func (s *Server) Readme() string
- func (s *Server) Run()
- func (s *Server) ShutdownCancel() context.CancelFunc
- func (s *Server) ShutdownContext() context.Context
- func (s *Server) Tracer() trace.Tracer
- type Service
- type ServiceEnabler
- type ServiceFn
- type ServiceFunc
- type StepFn
Constants ¶
const ( CLICommandServer = "server" CLICommandInit = "init" CLICommandSidecar = "sidecar" )
Standard command names registered by the CLI role helpers.
const ( ServiceNameInternalHTTP = "internal" ServiceAddrInternalHTTP = ":8080" ServiceNamePublicHTTP = "public" ServiceAddrPublicHTTP = ":8000" )
Names and default addresses of the HTTP services registered by Server.AddInternalHTTPService and Server.AddPublicHTTPService.
Variables ¶
var ( // ErrServerNotRunning is returned by [Server.Healthz] while the server is not running. ErrServerNotRunning = errors.New("server not running") // ErrServerShutdown is returned by the readiness probe and the server's error // group once graceful shutdown has started. ErrServerShutdown = errors.New("server is shutting down") )
var ( // Version is the build version, set with: // // -ldflags "-X github.com/foomo/keel.Version=$VERSION" Version string // GitCommit is the build commit, set with: // // -ldflags "-X github.com/foomo/keel.GitCommit=$GIT_COMMIT" GitCommit string // BuildTime is the build time, set with: // // -ldflags "-X 'github.com/foomo/keel.BuildTime=$(date -u '+%Y-%m-%d %H:%M:%S')'" BuildTime string )
Build information, intended to be set at link time.
Functions ¶
func IsCloser ¶ added in v0.17.0
IsCloser reports whether v implements any of the closer interfaces declared in github.com/foomo/keel/interfaces (Closer, Shutdowner, Stopper or Unsubscriber in any of their error or context variants).
func IsHealthz ¶ added in v0.17.0
IsHealthz reports whether v implements one of the accepted probe interfaces: healthz.BoolHealthzer, healthz.BoolHealthzerWithContext, healthz.ErrorHealthzer, healthz.ErrorHealthzWithContext, interfaces.ErrorPinger or interfaces.ErrorPingerWithContext.
Types ¶
type CLI ¶ added in v0.36.0
type CLI struct {
// contains filtered or unexported fields
}
CLI dispatches one binary to one of several named [cobra.Command]s, e.g. to reuse one image as main container, initContainer, native sidecar and helm hook Job. Name hook commands after what they do, e.g. "migrate", since one Job usually serves several hooks (helm.sh/hook: pre-install,pre-upgrade).
Each command builds and runs its own Server or Job, so only the selected command constructs a runtime. The command is selected from the arguments, else the KEEL_COMMAND environment variable, else the default command (see CLIWithDefault and CLI.AddServer).
func (*CLI) Add ¶ added in v0.36.0
Add registers and returns the command name described by short. run is called only when name is selected and is expected to build and run a Server or Job itself. Use the returned command to add flags.
func (*CLI) AddCommand ¶ added in v0.36.0
AddCommand registers cmds. Adding a name twice panics.
func (*CLI) AddInit ¶ added in v0.36.0
AddInit registers run as the initContainer command "init". Use CLI.Add with a custom name for further init containers.
func (*CLI) AddServer ¶ added in v0.36.0
AddServer registers run as the main container command "server". It becomes the default command unless CLIWithDefault was set, so the main container needs no args.
func (*CLI) AddSidecar ¶ added in v0.36.0
AddSidecar registers run as the native sidecar command "sidecar", i.e. an initContainer with restartPolicy Always. Use CLI.Add with a custom name for further sidecars.
func (*CLI) Execute ¶ added in v0.36.0
Execute selects and runs a command. Without args the KEEL_COMMAND environment variable selects the command. If args select no command, e.g. none or only flags, the default command is prepended unless help is requested.
func (*CLI) Root ¶ added in v0.36.0
Root returns the root command, e.g. to add persistent flags or a version.
func (*CLI) Run ¶ added in v0.36.0
func (c *CLI) Run()
Run calls CLI.Execute with the process arguments and exits 1 on error.
type CLIOption ¶ added in v0.36.0
type CLIOption func(inst *CLI)
CLIOption configures a CLI in NewCLI.
func CLIWithDefault ¶ added in v0.36.0
CLIWithDefault sets the command run when neither an argument nor the KEEL_COMMAND environment variable selects one. Overrides the default set by CLI.AddServer.
type Job ¶ added in v0.28.0
type Job struct {
// contains filtered or unexported fields
}
Job runs a keel workload to completion, as suited for a Kubernetes Job.
Unlike Server (which blocks until a shutdown signal), a Job runs its steps in order, then exits: Job.RunE returns the step error (or nil), and Job.Run translates that into a process exit code so Kubernetes can apply backoffLimit. SIGINT/SIGTERM are treated as an abnormal interruption that cancels the running step. No init HTTP services are started; metrics are pushed/flushed on exit rather than exposed.
func NewJob ¶ added in v0.28.0
NewJob creates a Job configured by opts. The job name defaults to OTEL_SERVICE_NAME (falling back to telemetry.DefaultServiceName) and can be overridden with JobWithName. It is used as the root routine/span label, the Pushgateway group, and a log field.
func (*Job) AddCloser ¶ added in v0.28.0
AddCloser registers closer to be called during job finalization. Values that do not satisfy IsCloser are ignored with a warning; adding the same closer twice is a no-op.
func (*Job) AddClosers ¶ added in v0.28.0
AddClosers calls Job.AddCloser for each of closers.
func (*Job) AddStep ¶ added in v0.28.0
AddStep adds a step to be run in registration order. It is not safe for concurrent use.
func (*Job) Meter ¶ added in v0.28.0
Meter returns the global OpenTelemetry meter from telemetry.Meter.
func (*Job) Run ¶ added in v0.28.0
func (j *Job) Run()
Run executes the job and exits the process: 0 on success, 1 on failure. This is the convenience entrypoint for a job's main(); use Job.RunE if you need to handle the error yourself.
type JobOption ¶ added in v0.28.0
type JobOption func(inst *Job)
JobOption configures a Job in NewJob.
func JobWithCloser ¶ added in v0.28.0
JobWithCloser registers closer to be called during job finalization. See Job.AddCloser.
func JobWithConfig ¶ added in v0.28.0
JobWithConfig sets the job configuration. Defaults to config.Config.
func JobWithContext ¶ added in v0.28.0
JobWithContext sets the parent of the job context. Defaults to context.Background.
func JobWithGracefulPeriod ¶ added in v0.28.0
JobWithGracefulPeriod sets the budget for flushing telemetry and closing resources after the job completes or is interrupted. Defaults to KEEL_GRACEFUL_PERIOD seconds, or 30 seconds.
func JobWithLogFields ¶ added in v0.28.0
JobWithLogFields adds fields to the job logger.
func JobWithLogger ¶ added in v0.28.0
JobWithLogger sets the job logger. Defaults to log.Logger.
func JobWithName ¶ added in v0.28.0
JobWithName overrides the default job name (OTEL_SERVICE_NAME, falling back to telemetry.DefaultServiceName).
func JobWithOTLPGRCPLogger ¶ added in v0.28.0
JobWithOTLPGRCPLogger sets an OTLP gRPC logger provider. enabled is the default for the otel.enabled config key.
func JobWithOTLPGRPCMeter ¶ added in v0.28.0
JobWithOTLPGRPCMeter sets an OTLP gRPC meter provider. enabled is the default for the otel.enabled config key. Metrics are pushed via OTLP gRPC and flushed on job exit, suiting jobs that finish before a Prometheus scrape.
func JobWithOTLPGRPCTracer ¶ added in v0.28.0
JobWithOTLPGRPCTracer sets an OTLP gRPC trace provider. enabled is the default for the otel.enabled config key.
func JobWithOTLPHTTPLogger ¶ added in v0.28.0
JobWithOTLPHTTPLogger sets an OTLP HTTP logger provider. enabled is the default for the otel.enabled config key.
func JobWithOTLPHTTPMeter ¶ added in v0.28.0
JobWithOTLPHTTPMeter sets an OTLP HTTP meter provider. enabled is the default for the otel.enabled config key. Metrics are pushed via OTLP HTTP and flushed on job exit, suiting jobs that finish before a Prometheus scrape.
func JobWithOTLPHTTPTracer ¶ added in v0.28.0
JobWithOTLPHTTPTracer sets an OTLP HTTP trace provider. enabled is the default for the otel.enabled config key.
func JobWithParallel ¶ added in v0.28.0
JobWithParallel runs the job steps concurrently instead of sequentially. limit caps the number of steps running at once; limit <= 0 means unbounded. The first failing step cancels the rest (fail-fast) and Job.RunE returns the joined error.
func JobWithPushgatewayMeter ¶ added in v0.28.0
JobWithPushgatewayMeter pushes Prometheus metrics to a Pushgateway on job exit, grouped by the job name. url is the default for the service.pushgateway.url config key (env SERVICE_PUSHGATEWAY_URL); an empty result disables it. It sets up a Prometheus meter provider (unless one is already configured) so OTEL metrics are included in the push.
func JobWithShutdownSignals ¶ added in v0.28.0
JobWithShutdownSignals sets the signals that interrupt the job. Defaults to SIGINT and SIGTERM.
func JobWithStdOutMeter ¶ added in v0.28.0
JobWithStdOutMeter sets a meter provider that writes to stdout. enabled is the default for the otel.enabled config key.
func JobWithStdOutTracer ¶ added in v0.28.0
JobWithStdOutTracer sets a trace provider that writes to stdout. enabled is the default for the otel.enabled config key.
func JobWithTelemetry ¶ added in v0.28.0
func JobWithTelemetry() JobOption
JobWithTelemetry wires the OpenTelemetry trace, metric and logger providers from the standard OTEL environment variables:
OTEL_TRACES_EXPORTER none(default) | console | otlp
OTEL_METRICS_EXPORTER none(default) | console | otlp | prometheus
OTEL_LOGS_EXPORTER none(default) | console | otlp
OTEL_EXPORTER_OTLP_PROTOCOL grpc | http/protobuf(default)
(per-signal override: OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_PROTOCOL)
A signal set to none leaves its provider unset, so the job falls back to a no-op provider. Call this before JobWithPushgatewayMeter so its nil meter-provider guard still fires when OTEL_METRICS_EXPORTER is none.
func JobWithTimeout ¶ added in v0.28.0
JobWithTimeout sets an in-process deadline for the whole job run. A zero duration (default) disables the in-process deadline; Kubernetes activeDeadlineSeconds still applies via SIGTERM handling.
type Option ¶
type Option func(inst *Server)
Option configures a Server in NewServer.
func WithConfig ¶
WithConfig sets the server configuration. Defaults to config.Config.
func WithContext ¶
WithContext sets the parent of the server context. Defaults to context.Background.
func WithGracefulPeriod ¶ added in v0.18.0
WithGracefulPeriod sets the time budget for closing resources on graceful shutdown. It should match the pod's terminationGracePeriodSeconds. Defaults to KEEL_GRACEFUL_PERIOD seconds, or 30 seconds.
func WithHTTPHealthzService ¶ added in v0.9.2
WithHTTPHealthzService registers the health probe service from service.NewDefaultHTTPProbes as an init service. enabled is the default for the service.healthz.enabled config key.
func WithHTTPPProfService ¶ added in v0.16.0
WithHTTPPProfService registers the pprof service from service.NewDefaultHTTPPProf as an init service. enabled is the default for the service.pprof.enabled config key.
func WithHTTPPrometheusService ¶ added in v0.2.0
WithHTTPPrometheusService registers the metrics service from service.NewDefaultHTTPPrometheus as an init service. enabled is the default for the service.prometheus.enabled config key.
func WithHTTPReadmeService
deprecated
added in
v0.17.0
WithHTTPReadmeService registers the readme service from service.NewDefaultHTTPReadme as an init service. enabled is the default for the service.readme.enabled config key.
Deprecated: Readme support will be removed in a future release.
func WithHTTPViperService ¶ added in v0.2.0
WithHTTPViperService registers the configuration service from service.NewDefaultHTTPViper as an init service. enabled is the default for the service.viper.enabled config key.
func WithHTTPZapService ¶ added in v0.2.0
WithHTTPZapService registers the log level service from service.NewDefaultHTTPZap as an init service. enabled is the default for the service.zap.enabled config key.
func WithInitService ¶ added in v0.27.0
WithInitService registers service as an init service, started in NewServer. Nil and already registered services are ignored.
func WithLogFields ¶
WithLogFields adds fields to the server logger.
func WithLogger ¶
WithLogger sets the server logger. Defaults to log.Logger.
func WithOTLPGRCPLogger ¶ added in v0.28.0
WithOTLPGRCPLogger sets an OTLP gRPC logger provider. enabled is the default for the otel.enabled config key.
func WithOTLPGRPCMeter ¶ added in v0.28.0
WithOTLPGRPCMeter sets an OTLP gRPC meter provider. enabled is the default for the otel.enabled config key. Metrics are pushed by a periodic reader, suiting setups that export metrics instead of exposing a Prometheus scrape endpoint.
func WithOTLPGRPCTracer ¶ added in v0.8.0
WithOTLPGRPCTracer sets an OTLP gRPC trace provider. enabled is the default for the otel.enabled config key.
func WithOTLPHTTPLogger ¶ added in v0.28.0
WithOTLPHTTPLogger sets an OTLP HTTP logger provider. enabled is the default for the otel.enabled config key.
func WithOTLPHTTPMeter ¶ added in v0.28.0
WithOTLPHTTPMeter sets an OTLP HTTP meter provider. enabled is the default for the otel.enabled config key. Metrics are pushed by a periodic reader, suiting setups that export metrics instead of exposing a Prometheus scrape endpoint.
func WithOTLPHTTPTracer ¶ added in v0.8.0
WithOTLPHTTPTracer sets an OTLP HTTP trace provider. enabled is the default for the otel.enabled config key.
func WithPrometheusMeter ¶ added in v0.8.0
WithPrometheusMeter sets a Prometheus meter provider. enabled is the default for the otel.enabled config key.
func WithPushgatewayMeter ¶ added in v0.28.0
WithPushgatewayMeter registers an init service that pushes Prometheus metrics to a Pushgateway on an interval and once more on graceful shutdown. url is the default for the service.pushgateway.url config key; an empty result disables it. The push interval is read from service.pushgateway.interval (default 15s). It sets up a Prometheus meter provider (unless one is already configured) so OTEL metrics are included in the push.
func WithPyroscopeService ¶ added in v0.22.0
WithPyroscopeService registers an init service running the Pyroscope profiler from telemetry.NewProfiler. enabled is the default for the otel.enabled config key.
func WithRemoteConfig ¶ added in v0.10.0
WithRemoteConfig adds a remote configuration source using config.WithRemoteConfig unless config.remote.enabled is false. Failing to add the source is fatal.
func WithShutdownSignals ¶ added in v0.6.4
WithShutdownSignals sets the signals that trigger graceful shutdown. Defaults to SIGINT and SIGTERM.
func WithStdOutLogger ¶ added in v0.22.0
WithStdOutLogger sets a logger provider that writes to stdout. enabled is the default for the otel.enabled config key.
func WithStdOutMeter ¶ added in v0.8.0
WithStdOutMeter sets a meter provider that writes to stdout. enabled is the default for the otel.enabled config key.
func WithStdOutTracer ¶ added in v0.8.0
WithStdOutTracer sets a trace provider that writes to stdout. enabled is the default for the otel.enabled config key.
func WithTelemetry ¶ added in v0.28.0
func WithTelemetry() Option
WithTelemetry wires the OpenTelemetry trace, metric and logger providers from the standard OTEL environment variables:
OTEL_TRACES_EXPORTER none(default) | console | otlp
OTEL_METRICS_EXPORTER none(default) | console | otlp | prometheus
OTEL_LOGS_EXPORTER none(default) | console | otlp
OTEL_EXPORTER_OTLP_PROTOCOL grpc | http/protobuf(default)
(per-signal override: OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_PROTOCOL)
A signal set to none leaves its provider unset, so the server falls back to a no-op provider. Call this before WithPushgatewayMeter so its nil meter-provider guard still fires when OTEL_METRICS_EXPORTER is none.
type Runtime ¶ added in v0.28.0
type Runtime interface {
// Logger returns the structured logger.
Logger() *zap.Logger
// Config returns the configuration.
Config() *viper.Viper
// Context returns the root context.
Context() context.Context
// Meter returns the OpenTelemetry meter.
Meter() metric.Meter
// Tracer returns the OpenTelemetry tracer.
Tracer() trace.Tracer
// AddCloser registers a closer to be called on shutdown/finalization.
AddCloser(closer any)
// AddClosers registers the given closers to be called on shutdown/finalization.
AddClosers(closers ...any)
}
Runtime is the shared accessor surface of Server and Job. Integrations should accept a Runtime instead of a concrete *Server so the same instrumented helper works under a long-lived Server or a short-lived Job.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server runs a set of Service values until a shutdown signal is received and then shuts them down gracefully. Create it with NewServer; the zero value is not usable. Registration methods are safe for concurrent use.
func NewServer ¶
NewServer creates a Server configured by opts and immediately starts its init services. It sets the global OpenTelemetry logger, error handler and text map propagator, falls back to no-op trace, meter and logger providers when none are configured, and registers the server itself as an always probe and a readiness probe that fails once shutdown has started.
func (*Server) AddAlwaysHealthzers ¶ added in v0.9.3
AddAlwaysHealthzers registers probes that are checked by every probe type.
func (*Server) AddCloser ¶
AddCloser registers closer to be called on graceful shutdown. Closers are called in registration order. A warning is logged if closer does not satisfy IsCloser; adding the same closer twice is a no-op.
func (*Server) AddClosers ¶
AddClosers calls Server.AddCloser for each of closers.
func (*Server) AddGoRoutine ¶ added in v0.24.0
func (s *Server) AddGoRoutine(name string, handler service.GoRoutineFn, opts ...service.GoRoutineOption)
AddGoRoutine registers a service.GoRoutine named name running handler.
func (*Server) AddHTTPService ¶ added in v0.24.0
func (s *Server) AddHTTPService(name, addr string, handler http.Handler, middleware ...keelhttp.Middleware)
AddHTTPService registers a service.HTTP named name serving handler wrapped in middleware. The listen address is read from the config key service.http.<name>.addr and defaults to addr.
func (*Server) AddHealthzer ¶ added in v0.9.3
AddHealthzer registers probe for health checks of type typ. Values that do not satisfy IsHealthz are ignored.
func (*Server) AddHealthzers ¶ added in v0.9.3
AddHealthzers calls Server.AddHealthzer for each of probes.
func (*Server) AddInternalHTTPService ¶ added in v0.24.0
func (s *Server) AddInternalHTTPService(handler http.Handler, middleware ...keelhttp.Middleware)
AddInternalHTTPService registers an HTTP service named ServiceNameInternalHTTP listening on ServiceAddrInternalHTTP by default. See Server.AddHTTPService.
func (*Server) AddLivenessHealthzers ¶ added in v0.9.3
AddLivenessHealthzers registers probes for the liveness check.
func (*Server) AddPublicHTTPService ¶ added in v0.24.0
func (s *Server) AddPublicHTTPService(handler http.Handler, middleware ...keelhttp.Middleware)
AddPublicHTTPService registers an HTTP service named ServiceNamePublicHTTP listening on ServiceAddrPublicHTTP by default. See Server.AddHTTPService.
func (*Server) AddReadinessHealthzers ¶ added in v0.9.3
AddReadinessHealthzers registers probes for the readiness check.
func (*Server) AddReadmer
deprecated
added in
v0.17.0
func (s *Server) AddReadmer(readmer interfaces.Readmer)
AddReadmer adds readmer to the readme exposed by the readme service.
Deprecated: Readme support will be removed in a future release.
func (*Server) AddReadmers
deprecated
added in
v0.17.0
func (s *Server) AddReadmers(readmers ...interfaces.Readmer)
AddReadmers adds readmers to the readme exposed by the readme service.
Deprecated: Readme support will be removed in a future release.
func (*Server) AddService ¶
AddService registers v to be started by Server.Run, as an always probe and as a closer. Adding the same service twice is a no-op.
func (*Server) AddServices ¶
AddServices calls Server.AddService for each of services.
func (*Server) AddStartupHealthzers ¶ added in v0.9.3
AddStartupHealthzers registers probes for the startup check.
func (*Server) Context ¶
Context returns the server context. It is canceled when Server.Run returns.
func (*Server) Healthz ¶ added in v0.9.1
Healthz returns ErrServerNotRunning unless Server.Run is in progress.
func (*Server) Meter ¶ added in v0.8.0
Meter returns the global OpenTelemetry meter from telemetry.Meter.
func (*Server) Readme ¶ added in v0.17.0
Readme returns a markdown description of the registered services, health probes and closers.
func (*Server) Run ¶
func (s *Server) Run()
Run starts the registered services and blocks until the server has shut down, either gracefully after a shutdown signal or because a service failed. The outcome is logged; Run does not exit the process.
func (*Server) ShutdownCancel ¶ added in v0.18.0
func (s *Server) ShutdownCancel() context.CancelFunc
ShutdownCancel returns a function that triggers graceful shutdown.
func (*Server) ShutdownContext ¶ added in v0.18.0
ShutdownContext returns a context that is canceled when graceful shutdown is triggered by a shutdown signal, Server.ShutdownCancel or a failing service.
type Service ¶
Service is a unit of work run by a Server. Start is called with the server context and is expected to block until the service has stopped; a returned error other than net/http.ErrServerClosed fails the server. Services typically also implement a closer interface (see IsCloser) so they are stopped on graceful shutdown.
type ServiceEnabler ¶ added in v0.10.12
type ServiceEnabler struct {
// contains filtered or unexported fields
}
ServiceEnabler is a Service that starts and stops a wrapped service at runtime depending on the result of an enabled function. The enabled function is polled once per second; when it flips to true a fresh service is created with the ServiceFn and started, when it flips to false the service is closed. Failing to start or close a service dynamically is fatal.
func NewServiceEnabler ¶ added in v0.10.12
func NewServiceEnabler(l *zap.Logger, name string, serviceFn ServiceFn, enabledFn func() bool) *ServiceEnabler
NewServiceEnabler returns a ServiceEnabler named name that creates its service with serviceFn and reads its state from enabledFn. enabledFn is called once immediately to determine the initial state.
func (*ServiceEnabler) Close ¶ added in v0.10.12
func (w *ServiceEnabler) Close(ctx context.Context) error
Close stops watching the enabled function and closes the wrapped service if it is enabled. The wrapped service is closed with the context passed to Start rather than ctx.
func (*ServiceEnabler) Name ¶ added in v0.10.12
func (w *ServiceEnabler) Name() string
Name returns the name of the service enabler.
func (*ServiceEnabler) Start ¶ added in v0.10.12
func (w *ServiceEnabler) Start(ctx context.Context) error
Start starts watching the enabled function and starts the wrapped service if it is enabled. While the wrapped service is enabled, Start blocks for as long as the wrapped service's Start does and returns its error.
type ServiceFn ¶ added in v0.28.0
type ServiceFn func() Service
ServiceFn creates a Service. It is used by ServiceEnabler to create a fresh service each time it is enabled.
type ServiceFunc ¶ added in v0.10.12
ServiceFunc adapts a function to the Service interface.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package config provides typed, lazily evaluated accessors for configuration values backed by github.com/spf13/viper.
|
Package config provides typed, lazily evaluated accessors for configuration values backed by github.com/spf13/viper. |
|
Package env provides typed accessors for environment variables with fallback defaults.
|
Package env provides typed accessors for environment variables with fallback defaults. |
|
example
module
|
|
|
jetbench
module
|
|
|
examples
module
|
|
|
Package healthz provides the probe types and interfaces used by keel to implement Kubernetes startup, readiness and liveness checks.
|
Package healthz provides the probe types and interfaces used by keel to implement Kubernetes startup, readiness and liveness checks. |
|
integration
|
|
|
gotsrpc
module
|
|
|
nats
module
|
|
|
temporal
module
|
|
|
Package interfaces defines small structural interface contracts used throughout keel to describe the lifecycle and identity of services and resources: closing, shutting down, stopping, unsubscribing, pinging, naming, and self-documenting.
|
Package interfaces defines small structural interface contracts used throughout keel to describe the lifecycle and identity of services and resources: closing, shutting down, stopping, unsubscribing, pinging, naming, and self-documenting. |
|
internal
|
|
|
otel
Package otel provides adapters that route OpenTelemetry's internal logging and error reporting to zap.
|
Package otel provides adapters that route OpenTelemetry's internal logging and error reporting to zap. |
|
otel/exporters/zap
Package zap provides an OpenTelemetry log exporter that writes log records to a go.uber.org/zap.Logger.
|
Package zap provides an OpenTelemetry log exporter that writes log records to a go.uber.org/zap.Logger. |
|
pyroscope
Package pyroscope provides a logger adapter for the pyroscope client.
|
Package pyroscope provides a logger adapter for the pyroscope client. |
|
sync
Package sync provides a pool of reusable bytes.Buffer values.
|
Package sync provides a pool of reusable bytes.Buffer values. |
|
Package jwt provides helpers for signing and verifying RS256 JSON Web Tokens on top of github.com/golang-jwt/jwt/v5, including support for key rotation via deprecated verification keys.
|
Package jwt provides helpers for signing and verifying RS256 JSON Web Tokens on top of github.com/golang-jwt/jwt/v5, including support for key rotation via deprecated verification keys. |
|
Package keeltest provides helpers for testing keel services.
|
Package keeltest provides helpers for testing keel services. |
|
assert
Package keelassert provides inline snapshot assertions in the style of github.com/stretchr/testify/assert, see keeltest.Inline.
|
Package keelassert provides inline snapshot assertions in the style of github.com/stretchr/testify/assert, see keeltest.Inline. |
|
require
Package keelrequire provides inline snapshot assertions in the style of github.com/stretchr/testify/require, see keeltest.Inline.
|
Package keelrequire provides inline snapshot assertions in the style of github.com/stretchr/testify/require, see keeltest.Inline. |
|
Package log provides the zap logger setup used by keel together with helpers for building structured log fields.
|
Package log provides the zap logger setup used by keel together with helpers for building structured log fields. |
|
Package markdown provides a small builder for markdown text, including tables, and helpers for formatting values as markdown.
|
Package markdown provides a small builder for markdown text, including tables, and helpers for formatting values as markdown. |
|
net
|
|
|
http
Package http provides HTTP client and server constructors tuned for services running on Kubernetes, together with middleware composition and common header name constants.
|
Package http provides HTTP client and server constructors tuned for services running on Kubernetes, together with middleware composition and common header name constants. |
|
http/context
Package context provides helpers to store and retrieve request-scoped identifiers in a context.Context: the referer, request ID, session ID and tracking ID.
|
Package context provides helpers to store and retrieve request-scoped identifiers in a context.Context: the referer, request ID, session ID and tracking ID. |
|
http/cookie
Package cookie provides a declarative helper to read, write and delete an HTTP cookie with consistent attributes.
|
Package cookie provides a declarative helper to read, write and delete an HTTP cookie with consistent attributes. |
|
http/log
Package log provides helpers to attach a github.com/foomo/keel/log.Labeler to an HTTP request context, so code handling the request can collect additional log fields for it.
|
Package log provides helpers to attach a github.com/foomo/keel/log.Labeler to an HTTP request context, so code handling the request can collect additional log fields for it. |
|
http/middleware
Package middleware provides HTTP server middlewares for keel services.
|
Package middleware provides HTTP server middlewares for keel services. |
|
http/provider
Package provider provides pluggable value providers for HTTP middleware and round-trippers, such as RequestID generators.
|
Package provider provides pluggable value providers for HTTP middleware and round-trippers, such as RequestID generators. |
|
http/rbac
Package rbac provides path-based, role-driven access control rules for HTTP requests.
|
Package rbac provides path-based, role-driven access control rules for HTTP requests. |
|
http/roundtripware
Package roundtripware provides HTTP client middlewares, called RoundTripwares, that wrap an net/http.RoundTripper.
|
Package roundtripware provides HTTP client middlewares, called RoundTripwares, that wrap an net/http.RoundTripper. |
|
stream
module
|
|
|
Package keelpersistence provides backend-agnostic persistence contracts shared by the keel storage integrations: the sentinel errors ErrNotFound and ErrDirtyWrite, and the DistributedRWLock interface.
|
Package keelpersistence provides backend-agnostic persistence contracts shared by the keel storage integrations: the sentinel errors ErrNotFound and ErrDirtyWrite, and the DistributedRWLock interface. |
|
mongo
module
|
|
|
postgres
module
|
|
|
Package semconv provides OpenTelemetry attribute keys and constructors for keel specific semantic conventions.
|
Package semconv provides OpenTelemetry attribute keys and constructors for keel specific semantic conventions. |
|
Package service provides ready made github.com/foomo/keel.Service implementations for running HTTP servers, goroutines and message subscriptions under a keel server.
|
Package service provides ready made github.com/foomo/keel.Service implementations for running HTTP servers, goroutines and message subscriptions under a keel server. |
|
leaderfollower
module
|
|
|
leaderfollower/threephase
module
|
|
|
Package telemetry provides OpenTelemetry tracing, metrics, logging and profiling helpers for keel services.
|
Package telemetry provides OpenTelemetry tracing, metrics, logging and profiling helpers for keel services. |
|
telemetrytest
Package telemetrytest provides helpers for testing code instrumented with github.com/foomo/keel/telemetry.
|
Package telemetrytest provides helpers for testing code instrumented with github.com/foomo/keel/telemetry. |
|
Package keeltime provides a replaceable clock for deterministic tests.
|
Package keeltime provides a replaceable clock for deterministic tests. |
|
utils
|
|
|
net/http
Package httputils provides helpers for HTTP handlers: writing error responses with logging and telemetry, inspecting request host and client address, and hashing basic auth passwords.
|
Package httputils provides helpers for HTTP handlers: writing error responses with logging and telemetry, inspecting request host and client address, and hashing basic auth passwords. |