Documentation
¶
Overview ¶
Package service provides ready made github.com/foomo/keel.Service implementations for running HTTP servers, goroutines and message subscriptions under a keel server.
HTTP wraps a net/http.Server; GoRoutine runs a function in one or more goroutines; Subscription runs a goflux.Subscriber. All of them implement Healthz and Close(ctx) error so they double as health probes and closers.
The package also provides constructors for keel's built-in internal HTTP services, each with a NewDefaultHTTPXxx variant using the DefaultHTTPXxx name, address and path variables:
- NewHealthz: Kubernetes health probes (default :9400/healthz)
- NewHTTPPrometheus: Prometheus metrics (default :9200/metrics)
- NewHTTPPProf: pprof profiling (default localhost:6060/debug/pprof)
- NewHTTPZap: runtime log level control (default localhost:9100/log)
- NewHTTPViper: runtime configuration access (default localhost:9300/config)
- NewHTTPReadme: markdown readme (default localhost:9001/readme, deprecated)
Index ¶
- Variables
- type GoRoutine
- type GoRoutineFn
- type GoRoutineOption
- type HTTP
- func NewDefaultHTTPPProf(l *zap.Logger) *HTTP
- func NewDefaultHTTPProbes(l *zap.Logger, probes map[healthz.Type][]any) *HTTP
- func NewDefaultHTTPPrometheus(l *zap.Logger) *HTTP
- func NewDefaultHTTPReadme(l *zap.Logger, readmers func() []interfaces.Readmer) *HTTPdeprecated
- func NewDefaultHTTPViper(l *zap.Logger) *HTTP
- func NewDefaultHTTPZap(l *zap.Logger) *HTTP
- func NewHTTP(l *zap.Logger, name, addr string, handler http.Handler, ...) *HTTP
- func NewHTTPPProf(l *zap.Logger, name, addr, path string) *HTTP
- func NewHTTPPrometheus(l *zap.Logger, name, addr, path string) *HTTP
- func NewHTTPReadme(l *zap.Logger, name, addr, path string, readmers func() []interfaces.Readmer) *HTTPdeprecated
- func NewHTTPViper(l *zap.Logger, c *viper.Viper, name, addr, path string) *HTTP
- func NewHTTPZap(l *zap.Logger, name, addr, path string) *HTTP
- func NewHealthz(l *zap.Logger, name, addr, path string, probes map[healthz.Type][]any) *HTTP
- type Subscription
- type SubscriptionOption
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrServiceNotRunning is returned by the Healthz methods while a service is // not running. ErrServiceNotRunning = errors.New("service not running") // ErrServiceShutdown is the cancellation cause of a service context canceled // by Close. ErrServiceShutdown = errors.New("service shutdown") )
var ( DefaultHTTPHealthzName = "healthz" DefaultHTTPHealthzAddr = ":9400" DefaultHTTPHealthzPath = "/healthz" )
Default name, address and path of the service returned by NewDefaultHTTPProbes.
var ( // ErrUnhandledHealthzProbe is reported for a probe of an unsupported type. ErrUnhandledHealthzProbe = errors.New("unhandled healthz probe") // ErrProbeFailed is reported when a boolean probe fails on the aggregate path. ErrProbeFailed = errors.New("probe failed") // ErrLivenessProbeFailed is reported when a boolean liveness probe fails. ErrLivenessProbeFailed = errors.New("liveness probe failed") // ErrReadinessProbeFailed is reported when a boolean readiness probe fails. ErrReadinessProbeFailed = errors.New("readiness probe failed") // ErrStartupProbeFailed is reported when a boolean startup probe fails. ErrStartupProbeFailed = errors.New("startup probe failed") )
Errors reported by the health probe handlers.
var ( DefaultHTTPPProfName = "pprof" DefaultHTTPPProfAddr = "localhost:6060" DefaultHTTPPProfPath = "/debug/pprof" )
Default name, address and path of the service returned by NewDefaultHTTPPProf.
var ( DefaultHTTPPrometheusName = "prometheus" DefaultHTTPPrometheusAddr = ":9200" DefaultHTTPPrometheusPath = "/metrics" )
Default name, address and path of the service returned by NewDefaultHTTPPrometheus.
var ( DefaultHTTPReadmeName = "readme" DefaultHTTPReadmeAddr = "localhost:9001" DefaultHTTPReadmePath = "/readme" )
Default name, address and path of the service returned by NewDefaultHTTPReadme.
var ( DefaultHTTPViperName = "viper" DefaultHTTPViperAddr = "localhost:9300" DefaultHTTPViperPath = "/config" )
Default name, address and path of the service returned by NewDefaultHTTPViper.
var ( DefaultHTTPZapName = "zap" DefaultHTTPZapAddr = "localhost:9100" DefaultHTTPZapPath = "/log" )
Default name, address and path of the service returned by NewDefaultHTTPZap.
Functions ¶
This section is empty.
Types ¶
type GoRoutine ¶
type GoRoutine struct {
// contains filtered or unexported fields
}
GoRoutine is a service that runs a GoRoutineFn in one or more goroutines until it returns or the service is closed. Create it with NewGoRoutine.
func NewGoRoutine ¶
func NewGoRoutine(l *zap.Logger, name string, handler GoRoutineFn, opts ...GoRoutineOption) *GoRoutine
NewGoRoutine returns a GoRoutine named name that runs handler. A nil l defaults to log.Logger. By default handler runs in a single goroutine.
Example ¶
var once sync.Once
// unset for github actions
_ = os.Setenv("GITHUB_REPOSITORY", "")
svr := keel.NewServer(
keel.WithLogger(zap.NewExample()),
keel.WithGracefulPeriod(3*time.Second),
)
svr.AddService(
service.NewGoRoutine(svr.Logger(), "demo", func(ctx context.Context, l *zap.Logger) error {
for {
// handle graceful shutdowns
if err := ctx.Err(); errors.Is(context.Cause(ctx), service.ErrServiceShutdown) {
l.Info("context has been canceled du to graceful shutdown")
return nil
} else if err != nil {
return errors.Wrap(err, "unexpected context error")
}
l.Info("ping")
time.Sleep(700 * time.Millisecond)
once.Do(shutdown)
}
}),
)
svr.Run()
Output: {"level":"info","msg":"starting keel server"} {"level":"info","msg":"starting keel service","keel_service_type":"goroutine","keel_service_name":"demo"} {"level":"info","msg":"ping","keel_service_type":"goroutine","keel_service_name":"demo","keel_service_inst":0} {"level":"info","msg":"ping","keel_service_type":"goroutine","keel_service_name":"demo","keel_service_inst":0} {"level":"info","msg":"keel closer closed","keel_graceful_period":3} {"level":"info","msg":"keel closer closed: closers"} {"level":"info","msg":"stopping keel service","keel_service_type":"goroutine","keel_service_name":"demo"} {"level":"info","msg":"context has been canceled du to graceful shutdown","keel_service_type":"goroutine","keel_service_name":"demo","keel_service_inst":0} {"level":"debug","msg":"keel closer closed","keel_closer_type":"*service.GoRoutine"} {"level":"debug","msg":"keel closer closed","keel_closer_type":"noop.TracerProvider"} {"level":"debug","msg":"keel closer closed","keel_closer_type":"noop.MeterProvider"} {"level":"debug","msg":"keel closer closed","keel_closer_type":"noop.LoggerProvider"} {"level":"info","msg":"keel closer closed: complete"} {"level":"info","msg":"keel server stopped"}
func (*GoRoutine) Close ¶
Close cancels the handler context with cause ErrServiceShutdown and waits for all goroutines to return, returning the first non-nil handler error. ctx is not used. If called before GoRoutine.Start, Start cancels the handler context immediately.
func (*GoRoutine) Healthz ¶
Healthz returns ErrServiceNotRunning unless GoRoutine.Start is in progress.
type GoRoutineFn ¶
GoRoutineFn is the function run by a GoRoutine. ctx is canceled with cause ErrServiceShutdown when the service is closed; l is enriched with the service name and goroutine instance.
type GoRoutineOption ¶
type GoRoutineOption func(*GoRoutine)
GoRoutineOption configures a GoRoutine in NewGoRoutine.
func GoRoutineWithParallel ¶ added in v0.30.0
func GoRoutineWithParallel(v int) GoRoutineOption
GoRoutineWithParallel sets the number of goroutines running the handler concurrently. Defaults to 1.
type HTTP ¶
type HTTP struct {
// contains filtered or unexported fields
}
HTTP is a service that serves an net/http.Server. Create it with NewHTTP.
func NewDefaultHTTPPProf ¶
NewDefaultHTTPPProf returns NewHTTPPProf using DefaultHTTPPProfName, DefaultHTTPPProfAddr and DefaultHTTPPProfPath.
func NewDefaultHTTPProbes ¶
NewDefaultHTTPProbes returns NewHealthz using DefaultHTTPHealthzName, DefaultHTTPHealthzAddr and DefaultHTTPHealthzPath.
func NewDefaultHTTPPrometheus ¶
NewDefaultHTTPPrometheus returns NewHTTPPrometheus using DefaultHTTPPrometheusName, DefaultHTTPPrometheusAddr and DefaultHTTPPrometheusPath.
func NewDefaultHTTPReadme
deprecated
func NewDefaultHTTPReadme(l *zap.Logger, readmers func() []interfaces.Readmer) *HTTP
NewDefaultHTTPReadme returns NewHTTPReadme using DefaultHTTPReadmeName, DefaultHTTPReadmeAddr and DefaultHTTPReadmePath.
Deprecated: Readme support will be removed in a future release.
func NewDefaultHTTPViper ¶
NewDefaultHTTPViper returns NewHTTPViper for config.Config using DefaultHTTPViperName, DefaultHTTPViperAddr and DefaultHTTPViperPath.
func NewDefaultHTTPZap ¶
NewDefaultHTTPZap returns NewHTTPZap using DefaultHTTPZapName, DefaultHTTPZapAddr and DefaultHTTPZapPath.
func NewHTTP ¶
func NewHTTP(l *zap.Logger, name, addr string, handler http.Handler, middlewares ...keelhttp.Middleware) *HTTP
NewHTTP returns an HTTP service named name listening on addr and serving handler wrapped in middlewares. See keelhttp.NewServer. A nil l defaults to log.Logger.
func NewHTTPPProf ¶
NewHTTPPProf returns an HTTP service exposing the net/http/pprof handlers below path. The CPU profile endpoint is served by Pyroscope's pprof handler.
func NewHTTPPrometheus ¶
NewHTTPPrometheus returns an HTTP service exposing the metrics of prometheus.DefaultGatherer on path, with OpenMetrics enabled.
func NewHTTPReadme
deprecated
func NewHTTPReadme(l *zap.Logger, name, addr, path string, readmers func() []interfaces.Readmer) *HTTP
NewHTTPReadme returns an HTTP service that responds to GET requests on path with the concatenated markdown of the readmers returned by readmers.
Deprecated: Readme support will be removed in a future release.
func NewHTTPViper ¶
NewHTTPViper returns an HTTP service exposing c on path. GET responds with all settings as JSON; PUT sets a single value from a {"key": ..., "value": ...} JSON body.
func NewHTTPZap ¶
NewHTTPZap returns an HTTP service controlling the global logger on path. GET responds with the level, disableCaller and disableStacktrace settings as JSON; PUT updates any of them from a JSON body of the same shape and responds with the resulting settings.
func NewHealthz ¶
NewHealthz returns an HTTP service serving health checks for probes:
- path runs all probes except healthz.TypeStartup ones
- path/liveness runs healthz.TypeAlways and healthz.TypeLiveness probes
- path/readiness runs healthz.TypeAlways and healthz.TypeReadiness probes
- path/startup runs healthz.TypeAlways and healthz.TypeStartup probes
Each endpoint responds 200 OK when all probes pass and 503 Service Unavailable at the first failing probe. probes is read on every request, so probes added to the map later are included.
func (*HTTP) Healthz ¶
Healthz returns ErrServiceNotRunning unless the server is listening.
type Subscription ¶ added in v0.24.0
type Subscription[T any] struct { // contains filtered or unexported fields }
Subscription is a service that manages the lifecycle of a goflux subscriber. Create it with NewSubscription.
func NewSubscription ¶ added in v0.24.0
func NewSubscription[T any]( l *zap.Logger, name string, subscriber goflux.Subscriber[T], subject string, handler goflux.Handler[T], opts ...SubscriptionOption[T], ) *Subscription[T]
NewSubscription returns a Subscription named name that subscribes subscriber to subject with handler. A nil l defaults to log.Logger.
func (*Subscription[T]) Close ¶ added in v0.24.0
func (s *Subscription[T]) Close(ctx context.Context) error
Close cancels the subscription context with cause ErrServiceShutdown, closes the subscriber (logging a failure) and waits for the subscription to end. ctx is not used. If called before Subscription.Start, Start cancels the subscription context immediately.
func (*Subscription[T]) Healthz ¶ added in v0.24.0
func (s *Subscription[T]) Healthz() error
Healthz returns ErrServiceNotRunning unless Subscription.Start is in progress.
func (*Subscription[T]) Name ¶ added in v0.24.0
func (s *Subscription[T]) Name() string
Name returns the service name.
func (*Subscription[T]) Start ¶ added in v0.24.0
func (s *Subscription[T]) Start(ctx context.Context) error
Start subscribes to the subject and blocks until the subscription ends, returning the error from the subscriber.
func (*Subscription[T]) String ¶ added in v0.24.0
func (s *Subscription[T]) String() string
String returns a short description of the subject used in the readme.
type SubscriptionOption ¶ added in v0.24.0
type SubscriptionOption[T any] func(*Subscription[T])
SubscriptionOption configures a Subscription in NewSubscription.