provider

package
v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2026 License: BSD-3-Clause Imports: 20 Imported by: 0

README

Platform Health Providers

Platform Health Providers are extensions to the platform-health server. They enable the server to report on the health and status of a variety of external systems. This extensibility allows the platform-health server to be a versatile tool for monitoring and maintaining the health of your entire platform.

Core Interfaces

To create a new provider, there are a few requirements:

type Instance interface {
    GetType() string
    GetName() string
    SetName(string)
    GetTimeout() time.Duration
    SetTimeout(time.Duration)
    GetHealth(context.Context) *ph.HealthCheckResponse
    Setup() error
}

Methods:

  • GetType(): Returns provider type (e.g., "tcp", "http", "system", etc.)
  • GetName(): Returns instance name (from config key)
  • SetName(): Sets the instance name
  • GetTimeout(): Returns the per-instance timeout override (0 means use parent context deadline)
  • SetTimeout(): Sets the per-instance timeout override
  • GetOrder(): Returns execution order group (default 0); lower values run first
  • SetOrder(): Sets execution order group
  • GetAlways(): Returns whether the instance always executes, even after fail-fast cancellation
  • SetAlways(): Sets the always-execute flag
  • GetHealth(): Performs the actual health check
  • Setup(): Sets default configuration and initializes the instance
  • Register with the internal registry: Providers must register themselves with the platform-health server's internal registry. This is done with a call to provider.Register in an init() function. The init() function is automatically called when the program starts, registering the provider before the server begins handling requests.

  • Include via blank import: To include the provider in the server, it must be imported using a blank import statement (i.e., _ path/to/module) in the main command.

By following these guidelines, you can extend the platform-health server to interact with any external system, making it a powerful tool for platform health monitoring.

Optional Interfaces

InstanceWithChecks

Providers can implement the InstanceWithChecks interface to support CEL (Common Expression Language) expressions for health checks:

type InstanceWithChecks interface {
    GetCheckConfig() *checks.CEL
    GetCheckContext(ctx context.Context) (map[string]any, error)
    GetChecks() []checks.Expression
    SetChecks([]checks.Expression) error
}

Methods:

  • GetCheckConfig(): Returns CEL configuration for the provider
  • GetCheckContext(): Returns evaluation context map for CEL expressions
  • GetChecks(): Returns configured CEL expressions
  • SetChecks(): Sets and compiles CEL expressions; returns an error if any expression is invalid

This enables:

  • Custom validation logic via CEL expressions
  • Context inspection via ph context command
  • Rich evaluation contexts with provider-specific data
BaseWithChecks

The BaseWithChecks struct provides reusable CEL handling that can be embedded by providers:

type BaseWithChecks struct {
    checks   []checks.Expression
    compiled []*checks.Check
}

Embed this in your provider to get default implementations of GetChecks(), HasChecks(), EvaluateChecks(), and EvaluateChecksByMode(). In your provider's SetChecks() method, call SetChecksAndCompile(exprs, celConfig) to compile the CEL expressions against your provider's CEL configuration.

Container

Providers that group related child health checks implement the Container interface:

type Container interface {
    SetComponents(config map[string]any)
    GetComponents() []Instance
    ComponentErrors() []error
}

Methods:

  • SetComponents(): Stores raw component configuration (called by factory before Setup)
  • GetComponents(): Returns resolved child instances (available after Setup)
  • ComponentErrors(): Returns validation errors from component resolution

The BaseContainer struct provides a default implementation. Call ResolveComponents() from your provider's Setup() method to resolve child instances from stored config.

Documentation

Index

Constants

View Source
const (
	FlagKindBool        = "bool"
	FlagKindCount       = "count"
	FlagKindInt         = "int"
	FlagKindString      = "string"
	FlagKindStringSlice = "stringSlice"
	FlagKindIntSlice    = "intSlice"
	FlagKindDuration    = "duration"
)

Flag kind constants for FlagValue.Kind.

Variables

View Source
var KnownComponentKeys = map[string]bool{
	"type":       true,
	"spec":       false,
	"checks":     false,
	"components": false,
	"timeout":    false,
	"includes":   false,
	"order":      false,
	"always":     false,
}

KnownComponentKeys defines valid keys at the component configuration level. The boolean value indicates whether the key is required (true) or optional (false). Key existence alone indicates validity; unknown keys will generate warnings.

Functions

func Check

func Check(ctx context.Context, instances []Instance) (response []*ph.HealthCheckResponse, status ph.Status)

func ConfigureFromFlags added in v0.6.0

func ConfigureFromFlags(instance Instance, fs *pflag.FlagSet) error

ConfigureFromFlags applies flag values from a pflag.FlagSet to a provider instance. It uses reflection to map flags to struct fields based on mapstructure tags.

func ExtractType added in v0.7.0

func ExtractType(rawConfig any) string

ExtractType extracts the "type" field from a raw component configuration. Returns "unknown" if the field is missing or not a string.

func GetHealthWithDuration

func GetHealthWithDuration(ctx context.Context, instance Instance) *ph.HealthCheckResponse

func ParseDuration added in v0.7.0

func ParseDuration(v any) (time.Duration, error)

ParseDuration parses a duration from various formats:

  • string: "10s", "1m", etc. (Go duration format)
  • int/float: interpreted as seconds
  • time.Duration: used directly

func ProviderList

func ProviderList() []string

List returns a list of registered providers.

func Register

func Register(name string, provider Instance)

Register adds a provider to the registry.

func SupportsChecks added in v0.6.0

func SupportsChecks(instance Instance) bool

SupportsChecks checks if a provider instance implements InstanceWithChecks.

Types

type Base added in v0.7.0

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

Base provides common functionality for all providers. Providers should embed this struct to get default implementations of GetName, SetName, GetTimeout, SetTimeout, and order/always accessors.

func (*Base) GetAlways added in v0.8.0

func (b *Base) GetAlways() bool

func (*Base) GetName added in v0.7.0

func (b *Base) GetName() string

func (*Base) GetOrder added in v0.8.0

func (b *Base) GetOrder() int

func (*Base) GetTimeout added in v0.7.0

func (b *Base) GetTimeout() time.Duration

func (*Base) SetAlways added in v0.8.0

func (b *Base) SetAlways(a bool)

func (*Base) SetName added in v0.7.0

func (b *Base) SetName(name string)

func (*Base) SetOrder added in v0.8.0

func (b *Base) SetOrder(o int)

func (*Base) SetTimeout added in v0.7.0

func (b *Base) SetTimeout(t time.Duration)

type BaseContainer added in v0.7.0

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

BaseContainer provides reusable container handling for providers with nested components. It manages component storage, resolution, and error collection.

func (*BaseContainer) ComponentErrors added in v0.7.0

func (b *BaseContainer) ComponentErrors() []error

ComponentErrors returns validation errors from resolution.

func (*BaseContainer) GetComponents added in v0.7.0

func (b *BaseContainer) GetComponents() []Instance

GetComponents returns resolved child instances. Available after ResolveComponents().

func (*BaseContainer) ResolveComponents added in v0.7.0

func (b *BaseContainer) ResolveComponents() error

ResolveComponents resolves all child components from stored config. Call this from the embedding provider's Setup() method.

func (*BaseContainer) SetComponents added in v0.7.0

func (b *BaseContainer) SetComponents(config map[string]any)

SetComponents stores raw component config. Called before Setup().

type BaseWithChecks added in v0.6.0

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

BaseWithChecks provides reusable CEL handling that can be embedded by providers. It manages CEL expression storage, compilation, and evaluation.

func (*BaseWithChecks) Checks added in v0.6.0

func (b *BaseWithChecks) Checks(modes ...checks.Mode) []*checks.Check

Checks returns compiled checks, optionally filtered by mode. Checks() returns all checks. Checks(checks.ModeEach) returns only per-item checks. Checks(checks.ModeDefault) returns only default checks.

func (*BaseWithChecks) EvaluateChecks added in v0.6.0

func (b *BaseWithChecks) EvaluateChecks(ctx context.Context, celCtx map[string]any, bindings ...cel.EnvOption) []string

EvaluateChecks runs all checks against the provided CEL context with optional runtime function bindings. Bindings are added via env.Extend() to inject runtime-specific implementations (e.g., kubernetes.Get with K8s client context). Call this from the provider's GetHealth() method. Returns nil if all expressions pass, or a slice of failure messages. If fail-fast mode is enabled in the Go context, returns immediately after first failure.

func (*BaseWithChecks) EvaluateChecksByMode added in v0.7.0

func (b *BaseWithChecks) EvaluateChecksByMode(ctx context.Context, mode checks.Mode, celCtx map[string]any, bindings ...cel.EnvOption) []string

EvaluateChecksByMode runs checks filtered by mode with fail-fast support. Use this when you need to evaluate only checks with a specific mode (e.g., ModeEach or ModeDefault). Returns nil if all expressions pass, or a slice of failure messages.

func (*BaseWithChecks) GetChecks added in v0.6.0

func (b *BaseWithChecks) GetChecks() []checks.Expression

GetChecks returns the raw check expressions configured for this provider.

func (*BaseWithChecks) HasChecks added in v0.6.0

func (b *BaseWithChecks) HasChecks() bool

HasChecks returns true if any CEL expressions are configured.

func (*BaseWithChecks) SetChecksAndCompile added in v0.7.0

func (b *BaseWithChecks) SetChecksAndCompile(exprs []checks.Expression, config *checks.CEL) error

SetChecksAndCompile is a helper for providers implementing SetChecks. It stores expressions and compiles them using the provided CEL config.

type Config

type Config interface {
	GetInstances() []Instance
}

Config is the interface through which the provider configuration is retrieved.

type Container added in v0.7.0

type Container interface {
	// SetComponents accepts the raw components config from YAML.
	// Called during config loading, before Setup().
	SetComponents(config map[string]any)

	// GetComponents returns the resolved child component instances.
	// Available after Setup() has been called.
	GetComponents() []Instance

	// ComponentErrors returns validation errors from child component resolution.
	ComponentErrors() []error
}

Container is implemented by providers that contain nested components. This enables recursive validation and generic config handling.

func AsContainer added in v0.7.0

func AsContainer(i Instance) Container

AsContainer returns the instance as Container if it implements it. Returns nil if the instance does not implement Container.

type FlagValue added in v0.7.0

type FlagValue struct {
	Shorthand    string
	Kind         string
	DefaultValue any
	NoOptDefault string
	Usage        string
}

FlagValue represents a single flag definition with metadata.

func (*FlagValue) BuildFlag added in v0.7.0

func (f *FlagValue) BuildFlag(flagSet *pflag.FlagSet, flagName string)

BuildFlag creates a pflag from the FlagValue definition.

type FlagValues added in v0.7.0

type FlagValues map[string]FlagValue

FlagValues is a map of flag names to their definitions.

func ProviderFlags added in v0.6.0

func ProviderFlags(instance Instance) FlagValues

ProviderFlags derives flag definitions from a provider instance using reflection. It reads struct tags to determine flag names, types, defaults, and descriptions:

  • mapstructure: flag name (skip if "-" or empty)
  • default: default value
  • description: custom usage text (auto-generated if not provided)
  • flag:"[name],[option]": name override (optional), option is "inline" or "nested"
  • flag:",inline": for struct fields, flatten without prefix (kind instead of resource.kind)
  • flag:",nested": for struct fields, flatten with prefix (resource.kind)

func (FlagValues) Register added in v0.7.0

func (f FlagValues) Register(flagSet *pflag.FlagSet, sort bool)

Register adds all flags in the set to the given pflag.FlagSet.

type Instance

type Instance interface {
	// GetType returns the provider type of the instance
	GetType() string
	// GetName returns the name of the instance
	GetName() string
	// SetName sets the name of the instance
	SetName(string)
	// GetTimeout returns the per-instance timeout override (0 means use parent context deadline)
	GetTimeout() time.Duration
	// SetTimeout sets the per-instance timeout override
	SetTimeout(time.Duration)
	// GetHealth checks and returns the instance
	GetHealth(context.Context) *ph.HealthCheckResponse
	// Setup sets the default values for the instance and validates specification.
	// Returns an error if the specification is invalid.
	Setup() error
}

Instance is the interface that must be implemented by all providers.

func New added in v0.7.0

func New(providerType string) (Instance, error)

New creates a raw provider instance without configuration or Setup(). Use this for capability detection (e.g., checking interface implementations). For configured instances, use NewInstance instead.

func NewInstance added in v0.6.0

func NewInstance(providerType string, opts ...Option) (Instance, error)

NewInstance creates a provider instance with the given options. Returns an error if the provider type is unknown or configuration fails. If no name is provided via WithName, defaults to the provider type.

func ResolveComponentConfig added in v0.7.0

func ResolveComponentConfig(name string, rawConfig any, validationErrors *[]error) (Instance, error)

ResolveComponentConfig validates raw component configuration and creates a provider instance. It validates component-level keys, checks for required fields, and builds the appropriate options.

Returns:

  • (Instance, nil): Successfully created with no warnings
  • (Instance, UnusedKeysWarning): Created successfully but has unknown spec keys
  • (nil, error): Failed to create - validation errors or creation failure

The validationErrors slice is populated with all validation issues found (for reporting), even if the instance was created successfully.

type InstanceError added in v0.7.0

type InstanceError struct {
	Type string
	Name string
	Err  error
}

InstanceError wraps an error with instance context (type and name).

func NewInstanceError added in v0.7.0

func NewInstanceError(providerType, name string, err error) InstanceError

NewInstanceError creates a new InstanceError.

func (InstanceError) Error added in v0.7.0

func (e InstanceError) Error() string

func (InstanceError) Unwrap added in v0.7.0

func (e InstanceError) Unwrap() error

type InstanceWithChecks added in v0.6.0

type InstanceWithChecks interface {
	Instance

	// GetCheckConfig returns the provider's CEL variable declarations.
	// This defines what variables are available in CEL expressions.
	GetCheckConfig() *checks.CEL

	// GetCheckContext fetches data and builds the evaluation context.
	// Used for both check evaluation AND context display (ph context).
	// Returns the context map with all variables populated.
	GetCheckContext(ctx context.Context) (map[string]any, error)

	// GetChecks returns configured CEL expressions.
	GetChecks() []checks.Expression

	// SetChecks sets and compiles CEL expressions.
	// Returns an error if any expression is invalid.
	SetChecks([]checks.Expression) error
}

InstanceWithChecks indicates a provider supports CEL expressions for health checks. Providers implementing this interface can participate in dynamic CLI commands and context inspection via `ph context`.

func AsInstanceWithChecks added in v0.6.0

func AsInstanceWithChecks(instance Instance) InstanceWithChecks

AsInstanceWithChecks returns the instance as InstanceWithChecks if it implements the interface. Returns nil if the instance does not implement InstanceWithChecks.

type Option added in v0.7.0

type Option func(*instanceConfig) error

Option configures instance creation.

func WithAlways added in v0.8.0

func WithAlways(always bool) Option

WithAlways marks the instance to always execute, even after fail-fast triggers.

func WithChecks added in v0.7.0

func WithChecks(exprs []checks.Expression) Option

WithChecks sets CEL check expressions. Returns an error during NewInstance if the provider doesn't implement InstanceWithChecks.

func WithComponents added in v0.7.0

func WithComponents(components map[string]any) Option

WithComponents sets nested component configuration. Returns an error during NewInstance if the provider doesn't implement Container.

func WithFlags added in v0.7.0

func WithFlags(fs *pflag.FlagSet) Option

WithFlags configures the provider from CLI flags. This is mutually exclusive with WithSpec - flags take precedence.

func WithName added in v0.7.0

func WithName(name string) Option

WithName sets the instance name.

func WithOrder added in v0.8.0

func WithOrder(order int) Option

WithOrder sets the execution order for the instance. Instances with lower order values run first. Default is 0.

func WithSpec added in v0.7.0

func WithSpec(spec map[string]any) Option

WithSpec sets provider-specific configuration (decoded via mapstructure).

func WithTimeout added in v0.7.0

func WithTimeout(timeout time.Duration) Option

WithTimeout sets a per-instance timeout override. When set, GetHealthWithDuration creates a child context with this timeout.

type ProviderRegistry

type ProviderRegistry map[string]reflect.Type

func RegistryForTesting added in v0.7.0

func RegistryForTesting() ProviderRegistry

RegistryForTesting returns a copy of the provider registry for test assertions.

type UnusedKeysWarning added in v0.7.0

type UnusedKeysWarning struct {
	Keys []string
}

UnusedKeysWarning indicates unknown fields were found in spec configuration. This is not necessarily a hard error - the caller decides based on strict mode.

func (*UnusedKeysWarning) Error added in v0.7.0

func (e *UnusedKeysWarning) Error() string

Directories

Path Synopsis
Package http provides an HTTP health check provider with response validation capabilities using CEL (Common Expression Language).
Package http provides an HTTP health check provider with response validation capabilities using CEL (Common Expression Language).
Code generated by go generate; DO NOT EDIT.
Code generated by go generate; DO NOT EDIT.
common command
testutil
Package testutil provides test utilities for the kubernetes provider.
Package testutil provides test utilities for the kubernetes provider.
Package ssh provides an SSH protocol health check provider.
Package ssh provides an SSH protocol health check provider.

Jump to

Keyboard shortcuts

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