keel

package module
v0.36.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 36 Imported by: 6 modules, 31 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

CodeQL Coverage GoDoc GitHub Stars

keel

keel

Opinionated way to run services on Kubernetes

Stack

  • Zap
  • Nats
  • Viper
  • GoTSRPC
  • Temporal
  • OpenTelemetry

Examples

See the examples folder for usages

package main

import (
  "net/http"

  "github.com/foomo/keel"
  "github.com/foomo/keel/service"
)

func main() {
  svr := keel.NewServer(
    keel.WithHTTPZapService(true),
    keel.WithHTTPViperService(true),
    keel.WithHTTPPrometheusService(true),
  )

  l := svr.Logger()

  svs := newService()

  svr.AddService(
    service.NewHTTP(l, "demo", "localhost:8080", svs),
  )

  svr.Run()
}

func newService() *http.ServeMux {
  s := http.NewServeMux()
  s.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    _, _ = w.Write([]byte("OK"))
  })
  return s
}

How to Contribute

Contributions are welcome! Please read the contributing guide.

Contributors

License

Distributed under MIT License, please read the license file for more details.

Made with ♥ foomo by bestbytes

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

View Source
const (
	CLICommandServer  = "server"
	CLICommandInit    = "init"
	CLICommandSidecar = "sidecar"
)

Standard command names registered by the CLI role helpers.

View Source
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

View Source
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")
)
View Source
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

func IsCloser(v any) bool

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

func IsHealthz(v any) bool

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 NewCLI added in v0.36.0

func NewCLI(opts ...CLIOption) *CLI

NewCLI creates a CLI configured by opts.

func (*CLI) Add added in v0.36.0

func (c *CLI) Add(name, short string, run RunFunc) *cobra.Command

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

func (c *CLI) AddCommand(cmds ...*cobra.Command)

AddCommand registers cmds. Adding a name twice panics.

func (*CLI) AddInit added in v0.36.0

func (c *CLI) AddInit(run RunFunc) *cobra.Command

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

func (c *CLI) AddServer(run RunFunc) *cobra.Command

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

func (c *CLI) AddSidecar(run RunFunc) *cobra.Command

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

func (c *CLI) Execute(args []string) error

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

func (c *CLI) Root() *cobra.Command

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

func CLIWithDefault(name string) CLIOption

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

func NewJob(opts ...JobOption) *Job

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

func (j *Job) AddCloser(closer any)

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

func (j *Job) AddClosers(closers ...any)

AddClosers calls Job.AddCloser for each of closers.

func (*Job) AddStep added in v0.28.0

func (j *Job) AddStep(name string, fn StepFn)

AddStep adds a step to be run in registration order. It is not safe for concurrent use.

func (*Job) Config added in v0.28.0

func (j *Job) Config() *viper.Viper

Config returns the job config.

func (*Job) Context added in v0.28.0

func (j *Job) Context() context.Context

Context returns the job context.

func (*Job) Logger added in v0.28.0

func (j *Job) Logger() *zap.Logger

Logger returns the job logger.

func (*Job) Meter added in v0.28.0

func (j *Job) Meter() metric.Meter

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.

func (*Job) RunE added in v0.28.0

func (j *Job) RunE() error

RunE executes the job steps in order and finalizes telemetry and resources. It returns the first step error (or the context error on interruption/timeout), or nil on success. Finalization (metric push/flush, closers) always runs, even on error or interruption.

func (*Job) Tracer added in v0.28.0

func (j *Job) Tracer() trace.Tracer

Tracer returns the global OpenTelemetry tracer from telemetry.Tracer.

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

func JobWithCloser(closer any) JobOption

JobWithCloser registers closer to be called during job finalization. See Job.AddCloser.

func JobWithConfig added in v0.28.0

func JobWithConfig(c *viper.Viper) JobOption

JobWithConfig sets the job configuration. Defaults to config.Config.

func JobWithContext added in v0.28.0

func JobWithContext(ctx context.Context) JobOption

JobWithContext sets the parent of the job context. Defaults to context.Background.

func JobWithGracefulPeriod added in v0.28.0

func JobWithGracefulPeriod(gracefulPeriod time.Duration) JobOption

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

func JobWithLogFields(fields ...zap.Field) JobOption

JobWithLogFields adds fields to the job logger.

func JobWithLogger added in v0.28.0

func JobWithLogger(l *zap.Logger) JobOption

JobWithLogger sets the job logger. Defaults to log.Logger.

func JobWithName added in v0.28.0

func JobWithName(name string) JobOption

JobWithName overrides the default job name (OTEL_SERVICE_NAME, falling back to telemetry.DefaultServiceName).

func JobWithOTLPGRCPLogger added in v0.28.0

func JobWithOTLPGRCPLogger(enabled bool) JobOption

JobWithOTLPGRCPLogger sets an OTLP gRPC logger provider. enabled is the default for the otel.enabled config key.

func JobWithOTLPGRPCMeter added in v0.28.0

func JobWithOTLPGRPCMeter(enabled bool) JobOption

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

func JobWithOTLPGRPCTracer(enabled bool) JobOption

JobWithOTLPGRPCTracer sets an OTLP gRPC trace provider. enabled is the default for the otel.enabled config key.

func JobWithOTLPHTTPLogger added in v0.28.0

func JobWithOTLPHTTPLogger(enabled bool) JobOption

JobWithOTLPHTTPLogger sets an OTLP HTTP logger provider. enabled is the default for the otel.enabled config key.

func JobWithOTLPHTTPMeter added in v0.28.0

func JobWithOTLPHTTPMeter(enabled bool) JobOption

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

func JobWithOTLPHTTPTracer(enabled bool) JobOption

JobWithOTLPHTTPTracer sets an OTLP HTTP trace provider. enabled is the default for the otel.enabled config key.

func JobWithParallel added in v0.28.0

func JobWithParallel(limit int) JobOption

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

func JobWithPushgatewayMeter(url string) JobOption

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

func JobWithShutdownSignals(shutdownSignals ...os.Signal) JobOption

JobWithShutdownSignals sets the signals that interrupt the job. Defaults to SIGINT and SIGTERM.

func JobWithStdOutMeter added in v0.28.0

func JobWithStdOutMeter(enabled bool) JobOption

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

func JobWithStdOutTracer(enabled bool) JobOption

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

func JobWithTimeout(timeout time.Duration) JobOption

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

func WithConfig(c *viper.Viper) Option

WithConfig sets the server configuration. Defaults to config.Config.

func WithContext

func WithContext(ctx context.Context) Option

WithContext sets the parent of the server context. Defaults to context.Background.

func WithGracefulPeriod added in v0.18.0

func WithGracefulPeriod(gracefulPeriod time.Duration) Option

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

func WithHTTPHealthzService(enabled bool) Option

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

func WithHTTPPProfService(enabled bool) Option

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

func WithHTTPPrometheusService(enabled bool) Option

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

func WithHTTPReadmeService(enabled bool) Option

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

func WithHTTPViperService(enabled bool) Option

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

func WithHTTPZapService(enabled bool) Option

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

func WithInitService(service Service) Option

WithInitService registers service as an init service, started in NewServer. Nil and already registered services are ignored.

func WithLogFields

func WithLogFields(fields ...zap.Field) Option

WithLogFields adds fields to the server logger.

func WithLogger

func WithLogger(l *zap.Logger) Option

WithLogger sets the server logger. Defaults to log.Logger.

func WithOTLPGRCPLogger added in v0.28.0

func WithOTLPGRCPLogger(enabled bool) Option

WithOTLPGRCPLogger sets an OTLP gRPC logger provider. enabled is the default for the otel.enabled config key.

func WithOTLPGRPCMeter added in v0.28.0

func WithOTLPGRPCMeter(enabled bool) Option

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

func WithOTLPGRPCTracer(enabled bool) Option

WithOTLPGRPCTracer sets an OTLP gRPC trace provider. enabled is the default for the otel.enabled config key.

func WithOTLPHTTPLogger added in v0.28.0

func WithOTLPHTTPLogger(enabled bool) Option

WithOTLPHTTPLogger sets an OTLP HTTP logger provider. enabled is the default for the otel.enabled config key.

func WithOTLPHTTPMeter added in v0.28.0

func WithOTLPHTTPMeter(enabled bool) Option

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

func WithOTLPHTTPTracer(enabled bool) Option

WithOTLPHTTPTracer sets an OTLP HTTP trace provider. enabled is the default for the otel.enabled config key.

func WithPrometheusMeter added in v0.8.0

func WithPrometheusMeter(enabled bool) Option

WithPrometheusMeter sets a Prometheus meter provider. enabled is the default for the otel.enabled config key.

func WithPushgatewayMeter added in v0.28.0

func WithPushgatewayMeter(url string) Option

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

func WithPyroscopeService(enabled bool) Option

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

func WithRemoteConfig(provider, endpoint, path string) Option

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

func WithShutdownSignals(shutdownSignals ...os.Signal) Option

WithShutdownSignals sets the signals that trigger graceful shutdown. Defaults to SIGINT and SIGTERM.

func WithStdOutLogger added in v0.22.0

func WithStdOutLogger(enabled bool) Option

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

func WithStdOutMeter(enabled bool) Option

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

func WithStdOutTracer(enabled bool) Option

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 RunFunc added in v0.36.0

type RunFunc = func(cmd *cobra.Command, args []string) error

RunFunc is the cobra RunE signature used by CLI commands.

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

func NewServer(opts ...Option) *Server

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

func (s *Server) AddAlwaysHealthzers(probes ...any)

AddAlwaysHealthzers registers probes that are checked by every probe type.

func (*Server) AddCloser

func (s *Server) AddCloser(closer any)

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

func (s *Server) AddClosers(closers ...any)

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

func (s *Server) AddHealthzer(typ healthz.Type, probe any)

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

func (s *Server) AddHealthzers(typ healthz.Type, probes ...any)

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

func (s *Server) AddLivenessHealthzers(probes ...any)

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

func (s *Server) AddReadinessHealthzers(probes ...any)

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

func (s *Server) AddService(v Service)

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

func (s *Server) AddServices(services ...Service)

AddServices calls Server.AddService for each of services.

func (*Server) AddStartupHealthzers added in v0.9.3

func (s *Server) AddStartupHealthzers(probes ...any)

AddStartupHealthzers registers probes for the startup check.

func (*Server) Config

func (s *Server) Config() *viper.Viper

Config returns the server configuration.

func (*Server) Context

func (s *Server) Context() context.Context

Context returns the server context. It is canceled when Server.Run returns.

func (*Server) Healthz added in v0.9.1

func (s *Server) Healthz() error

Healthz returns ErrServerNotRunning unless Server.Run is in progress.

func (*Server) Logger

func (s *Server) Logger() *zap.Logger

Logger returns the server logger.

func (*Server) Meter added in v0.8.0

func (s *Server) Meter() metric.Meter

Meter returns the global OpenTelemetry meter from telemetry.Meter.

func (*Server) Readme added in v0.17.0

func (s *Server) Readme() string

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

func (s *Server) ShutdownContext() context.Context

ShutdownContext returns a context that is canceled when graceful shutdown is triggered by a shutdown signal, Server.ShutdownCancel or a failing service.

func (*Server) Tracer added in v0.8.0

func (s *Server) Tracer() trace.Tracer

Tracer returns the global OpenTelemetry tracer from telemetry.Tracer.

type Service

type Service interface {
	Start(ctx context.Context) error
}

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

type ServiceFunc func(ctx context.Context) error

ServiceFunc adapts a function to the Service interface.

func (ServiceFunc) Start added in v0.28.0

func (fn ServiceFunc) Start(ctx context.Context) error

Start calls fn(ctx).

type StepFn added in v0.28.0

type StepFn func(ctx context.Context, l *zap.Logger) error

StepFn is a single unit of work within a Job. It receives the (cancellable) job context and an enriched logger and returns an error to fail the job.

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.
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.

Jump to

Keyboard shortcuts

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