service

package
v0.17.3 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2023 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	DefaultHTTPHealthzName = "healthz"
	DefaultHTTPHealthzAddr = ":9400"
	DefaultHTTPHealthzPath = "/healthz"
)
View Source
const (
	DefaultHTTPPProfName = "pprof"
	DefaultHTTPPProfAddr = "localhost:6060"
	DefaultHTTPPProfPath = "/debug/pprof"
)
View Source
const (
	DefaultHTTPPrometheusName = "prometheus"
	DefaultHTTPPrometheusAddr = ":9200"
	DefaultHTTPPrometheusPath = "/metrics"
)
View Source
const (
	DefaultHTTPReadmeName = "readme"
	DefaultHTTPReadmeAddr = "localhost:9001"
	DefaultHTTPReadmePath = "/readme"
)
View Source
const (
	DefaultHTTPViperName = "viper"
	DefaultHTTPViperAddr = "localhost:9300"
	DefaultHTTPViperPath = "/config"
)
View Source
const (
	DefaultHTTPZapName = "zap"
	DefaultHTTPZapAddr = "localhost:9100"
	DefaultHTTPZapPath = "/log"
)

Variables

View Source
var (
	ErrServiceNotRunning = errors.New("service not running")
	ErrServiceShutdown   = errors.New("service shutdown")
)
View Source
var (
	ErrUnhandledHealthzProbe = errors.New("unhandled healthz probe")
	ErrProbeFailed           = errors.New("probe failed")
	ErrLivenessProbeFailed   = errors.New("liveness probe failed")
	ErrReadinessProbeFailed  = errors.New("readiness probe failed")
	ErrStartupProbeFailed    = errors.New("startup probe failed")
)

Functions

This section is empty.

Types

type GoRoutine

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

GoRoutine struct

func NewGoRoutine

func NewGoRoutine(l *zap.Logger, name string, handler GoRoutineFn, opts ...GoRoutineOption) *GoRoutine
Example
var once sync.Once

svr := keel.NewServer(
	keel.WithLogger(zap.NewExample()),
)

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 shutdow")
				return nil
			} else if err != nil {
				return errors.Wrap(err, "unexpected context error")
			}

			l.Info("ping")
			time.Sleep(time.Second)
			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":"debug","msg":"keel graceful shutdown"}
{"level":"info","msg":"stopping keel service","keel_service_type":"goroutine","keel_service_name":"demo"}
{"level":"info","msg":"context has been canceled du to graceful shutdow","keel_service_type":"goroutine","keel_service_name":"demo","keel_service_inst":0}
{"level":"info","msg":"keel server stopped"}

func (*GoRoutine) Close

func (s *GoRoutine) Close(ctx context.Context) error

func (*GoRoutine) Healthz

func (s *GoRoutine) Healthz() error

func (*GoRoutine) Name

func (s *GoRoutine) Name() string

func (*GoRoutine) Start

func (s *GoRoutine) Start(ctx context.Context) error

func (*GoRoutine) String

func (s *GoRoutine) String() string

type GoRoutineFn

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

GoRoutine struct

type GoRoutineOption

type GoRoutineOption func(*GoRoutine)

GoRoutine struct

func GoRoutineWithPralllel

func GoRoutineWithPralllel(v int) GoRoutineOption

type HTTP

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

HTTP struct

func NewDefaultHTTPPProf

func NewDefaultHTTPPProf(l *zap.Logger) *HTTP

func NewDefaultHTTPProbes

func NewDefaultHTTPProbes(l *zap.Logger, probes map[healthz.Type][]interface{}) *HTTP

func NewDefaultHTTPPrometheus

func NewDefaultHTTPPrometheus(l *zap.Logger) *HTTP

func NewDefaultHTTPReadme

func NewDefaultHTTPReadme(l *zap.Logger, readmers func() []interfaces.Readmer) *HTTP

func NewDefaultHTTPViper

func NewDefaultHTTPViper(l *zap.Logger) *HTTP

func NewDefaultHTTPZap

func NewDefaultHTTPZap(l *zap.Logger) *HTTP

func NewHTTP

func NewHTTP(l *zap.Logger, name, addr string, handler http.Handler, middlewares ...middleware.Middleware) *HTTP
Example
svr := keel.NewServer(
	keel.WithLogger(zap.NewExample()),
)

l := svr.Logger()

svr.AddService(
	service.NewHTTP(l, "demo", "localhost:8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("OK"))
	})),
)

go func() {
	waitFor("localhost:8080")
	l.Info(httpGet("http://localhost:8080"))
	shutdown()
}()

svr.Run()
Output:

{"level":"info","msg":"starting keel server"}
{"level":"info","msg":"starting keel service","keel_service_type":"http","keel_service_name":"demo","net_host_ip":"localhost","net_host_port":"8080"}
{"level":"info","msg":"OK"}
{"level":"debug","msg":"keel graceful shutdown"}
{"level":"info","msg":"stopping keel service","keel_service_type":"http","keel_service_name":"demo"}
{"level":"info","msg":"keel server stopped"}

func NewHTTPPProf

func NewHTTPPProf(l *zap.Logger, name, addr, path string) *HTTP

func NewHTTPPrometheus

func NewHTTPPrometheus(l *zap.Logger, name, addr, path string) *HTTP

func NewHTTPReadme

func NewHTTPReadme(l *zap.Logger, name, addr, path string, readmers func() []interfaces.Readmer) *HTTP
Example
// define vars so it does not panic
_ = os.Setenv("EXAMPLE_REQUIRED_BOOL", "true")
_ = os.Setenv("EXAMPLE_REQUIRED_STRING", "foo")

svr := keel.NewServer(
	keel.WithLogger(zap.NewNop()),
	keel.WithPrometheusMeter(true),
	keel.WithHTTPReadmeService(true),
)

// access some env vars
_ = env.Get("EXAMPLE_STRING", "demo")
_ = env.GetBool("EXAMPLE_BOOL", false)
_ = env.MustGet("EXAMPLE_REQUIRED_STRING")
_ = env.MustGetBool("EXAMPLE_REQUIRED_BOOL")

l := svr.Logger()

c := svr.Config()
// config with fallback
_ = config.GetBool(c, "example.bool", false)
_ = config.GetString(c, "example.string", "fallback")
// required configs
_ = config.MustGetBool(c, "example.required.bool")
_ = config.MustGetString(c, "example.required.string")

m := svr.Meter()

// add metrics
fooBarCounter := promauto.NewCounter(prometheus.CounterOpts{
	Name: "foo_bar_total",
	Help: "Foo bar metrics",
})
fooBazCounter, _ := m.SyncInt64().Counter("foo_baz_total", instrument.WithDescription("Foo baz metrics"))

fooBarCounter.Add(1)
fooBazCounter.Add(svr.Context(), 1)

// add http service
svr.AddService(service.NewHTTP(l, "demp-http", "localhost:8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte("OK"))
})))

// add go routine service
svr.AddService(service.NewGoRoutine(l, "demo-goroutine", func(ctx context.Context, l *zap.Logger) error {
	return nil
}))

go func() {
	waitFor("localhost:9001")
	fmt.Print(httpGet("http://localhost:9001/readme"))
	shutdown()
}()

svr.Run()
Output:

### Env

List of all accessed environment variables.

| Key                       | Type     | Required | Default   |
| ------------------------- | -------- | -------- | --------- |
| `EXAMPLE_BOOL`            | `bool`   |          |           |
| `EXAMPLE_REQUIRED_BOOL`   | `bool`   |          |           |
| `EXAMPLE_REQUIRED_BOOL`   | `bool`   | `true`   |           |
| `EXAMPLE_REQUIRED_STRING` | `string` |          |           |
| `EXAMPLE_REQUIRED_STRING` | `string` | `true`   |           |
| `EXAMPLE_STRING`          | `string` |          | `demo`    |
| `LOG_DISABLE_CALLER`      | `bool`   |          |           |
| `LOG_DISABLE_STACKTRACE`  | `bool`   |          |           |
| `LOG_ENCODING`            | `string` |          | `json`    |
| `LOG_LEVEL`               | `string` |          | `info`    |
| `LOG_MODE`                | `string` |          | `prod`    |
| `OTEL_ENABLED`            | `bool`   |          |           |
| `OTEL_SERVICE_NAME`       | `string` |          | `service` |

### Config

List of all registered config variables with their defaults.

| Key                       | Type     | Required | Default    |
| ------------------------- | -------- | -------- | ---------- |
| `example.bool`            | `bool`   |          | `false`    |
| `example.required.bool`   | `bool`   | `true`   |            |
| `example.required.string` | `string` | `true`   |            |
| `example.string`          | `string` |          | `fallback` |
| `otel.enabled`            | `bool`   |          | `true`     |
| `service.readme.enabled`  | `bool`   |          | `true`     |

### Init Services

List of all registered init services that are being immediately started.

| Name     | Type            | Address                              |
| -------- | --------------- | ------------------------------------ |
| `readme` | `*service.HTTP` | `*http.ServeMux` on `localhost:9001` |

### Runtime Services

List of all registered services that are being started.

| Name             | Type                 | Description                            |
| ---------------- | -------------------- | -------------------------------------- |
| `demo-goroutine` | `*service.GoRoutine` | parallel: `1`                          |
| `demp-http`      | `*service.HTTP`      | `http.HandlerFunc` on `localhost:8080` |

### Health probes

List of all registered healthz probes that are being called during startup and runtime.

| Name             | Probe    | Type                 | Description                            |
| ---------------- | -------- | -------------------- | -------------------------------------- |
|                  | `always` | `*keel.Server`       |                                        |
| `demo-goroutine` | `always` | `*service.GoRoutine` | parallel: `1`                          |
| `demp-http`      | `always` | `*service.HTTP`      | `http.HandlerFunc` on `localhost:8080` |
| `readme`         | `always` | `*service.HTTP`      | `*http.ServeMux` on `localhost:9001`   |

### Closers

List of all registered closers that are being called during graceful shutdown.

| Name             | Type                 | Closer                   | Description                            |
| ---------------- | -------------------- | ------------------------ | -------------------------------------- |
| `demo-goroutine` | `*service.GoRoutine` | `ErrorCloserWithContext` | parallel: `1`                          |
| `demp-http`      | `*service.HTTP`      | `ErrorCloserWithContext` | `http.HandlerFunc` on `localhost:8080` |
| `readme`         | `*service.HTTP`      | `ErrorCloserWithContext` | `*http.ServeMux` on `localhost:9001`   |

### Metrics

List of all registered metrics than are being exposed.

| Name                               | Type    | Description                                                        |
| ---------------------------------- | ------- | ------------------------------------------------------------------ |
| `foo_bar_total`                    | COUNTER | Foo bar metrics                                                    |
| `foo_baz_total`                    | COUNTER | Foo baz metrics                                                    |
| `go_gc_duration_seconds`           | SUMMARY | A summary of the pause duration of garbage collection cycles.      |
| `go_goroutines`                    | GAUGE   | Number of goroutines that currently exist.                         |
| `go_info`                          | GAUGE   | Information about the Go environment.                              |
| `go_memstats_alloc_bytes_total`    | COUNTER | Total number of bytes allocated, even if freed.                    |
| `go_memstats_alloc_bytes`          | GAUGE   | Number of bytes allocated and still in use.                        |
| `go_memstats_buck_hash_sys_bytes`  | GAUGE   | Number of bytes used by the profiling bucket hash table.           |
| `go_memstats_frees_total`          | COUNTER | Total number of frees.                                             |
| `go_memstats_gc_sys_bytes`         | GAUGE   | Number of bytes used for garbage collection system metadata.       |
| `go_memstats_heap_alloc_bytes`     | GAUGE   | Number of heap bytes allocated and still in use.                   |
| `go_memstats_heap_idle_bytes`      | GAUGE   | Number of heap bytes waiting to be used.                           |
| `go_memstats_heap_inuse_bytes`     | GAUGE   | Number of heap bytes that are in use.                              |
| `go_memstats_heap_objects`         | GAUGE   | Number of allocated objects.                                       |
| `go_memstats_heap_released_bytes`  | GAUGE   | Number of heap bytes released to OS.                               |
| `go_memstats_heap_sys_bytes`       | GAUGE   | Number of heap bytes obtained from system.                         |
| `go_memstats_last_gc_time_seconds` | GAUGE   | Number of seconds since 1970 of last garbage collection.           |
| `go_memstats_lookups_total`        | COUNTER | Total number of pointer lookups.                                   |
| `go_memstats_mallocs_total`        | COUNTER | Total number of mallocs.                                           |
| `go_memstats_mcache_inuse_bytes`   | GAUGE   | Number of bytes in use by mcache structures.                       |
| `go_memstats_mcache_sys_bytes`     | GAUGE   | Number of bytes used for mcache structures obtained from system.   |
| `go_memstats_mspan_inuse_bytes`    | GAUGE   | Number of bytes in use by mspan structures.                        |
| `go_memstats_mspan_sys_bytes`      | GAUGE   | Number of bytes used for mspan structures obtained from system.    |
| `go_memstats_next_gc_bytes`        | GAUGE   | Number of heap bytes when next garbage collection will take place. |
| `go_memstats_other_sys_bytes`      | GAUGE   | Number of bytes used for other system allocations.                 |
| `go_memstats_stack_inuse_bytes`    | GAUGE   | Number of bytes in use by the stack allocator.                     |
| `go_memstats_stack_sys_bytes`      | GAUGE   | Number of bytes obtained from system for stack allocator.          |
| `go_memstats_sys_bytes`            | GAUGE   | Number of bytes obtained from system.                              |
| `go_threads`                       | GAUGE   | Number of OS threads created.                                      |
| `process_cpu_seconds_total`        | COUNTER | Total user and system CPU time spent in seconds.                   |
| `process_max_fds`                  | GAUGE   | Maximum number of open file descriptors.                           |
| `process_open_fds`                 | GAUGE   | Number of open file descriptors.                                   |
| `process_resident_memory_bytes`    | GAUGE   | Resident memory size in bytes.                                     |
| `process_start_time_seconds`       | GAUGE   | Start time of the process since unix epoch in seconds.             |
| `process_virtual_memory_bytes`     | GAUGE   | Virtual memory size in bytes.                                      |
| `process_virtual_memory_max_bytes` | GAUGE   | Maximum amount of virtual memory available in bytes.               |

func NewHTTPViper

func NewHTTPViper(l *zap.Logger, c *viper.Viper, name, addr, path string) *HTTP

func NewHTTPZap

func NewHTTPZap(l *zap.Logger, name, addr, path string) *HTTP

func NewHealthz

func NewHealthz(l *zap.Logger, name, addr, path string, probes map[healthz.Type][]interface{}) *HTTP

func (*HTTP) Close

func (s *HTTP) Close(ctx context.Context) error

func (*HTTP) Healthz

func (s *HTTP) Healthz() error

func (*HTTP) Name

func (s *HTTP) Name() string

func (*HTTP) Start

func (s *HTTP) Start(ctx context.Context) error

func (*HTTP) String

func (s *HTTP) String() string

Jump to

Keyboard shortcuts

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