Documentation
¶
Overview ¶
Package types provides core type definitions and interfaces for the monitor system.
This package defines the fundamental contracts and types used throughout the github.com/nabbar/golib/monitor ecosystem. It serves as the foundation for monitor implementations and integrations.
Core Components ¶
The package provides:
- Monitor interface: Primary contract for health monitoring implementations
- Config struct: Configuration for monitor behavior and thresholds
- Info interface: Metadata about monitored components
- HealthCheck function type: Health check implementation contract
- Error definitions: Standardized error handling
Monitor Interface ¶
The Monitor interface combines multiple sub-interfaces:
- MonitorInfo: Metadata management (name, version, description)
- MonitorStatus: Status querying (OK/Warn/KO, latency, uptime/downtime)
- MonitorMetrics: Prometheus metrics integration
- libsrv.Runner: Lifecycle management (Start, Stop, IsRunning)
Configuration ¶
The Config struct defines all monitor behavior parameters:
- Check intervals (normal, falling, rising)
- Timeout for health checks
- Thresholds for status transitions
- Logger configuration
Example configuration:
cfg := types.Config{
Name: "database",
CheckTimeout: duration.ParseDuration(5 * time.Second),
IntervalCheck: duration.ParseDuration(10 * time.Second),
FallCountKO: 3,
RiseCountKO: 3,
}
Status Transitions ¶
The monitor uses thresholds to prevent status flapping:
- FallCountWarn: Failures needed to go from OK to Warn
- FallCountKO: Failures needed to go from Warn to KO
- RiseCountKO: Successes needed to go from KO to Warn
- RiseCountWarn: Successes needed to go from Warn to OK
Health Check Function ¶
The HealthCheck function type defines the contract for health check implementations:
type HealthCheck func(ctx context.Context) error
Implementations should:
- Respect context cancellation and timeout
- Return nil for healthy status
- Return descriptive errors for unhealthy status
- Complete quickly (within CheckTimeout)
Metrics Integration ¶
The MonitorMetrics interface provides Prometheus integration:
monitor.RegisterMetricsName("service_health", "service_latency")
monitor.RegisterCollectMetrics(func(ctx context.Context, names ...string) {
// Update Prometheus metrics
})
Related Packages ¶
- github.com/nabbar/golib/monitor: Main monitor implementation
- github.com/nabbar/golib/monitor/info: Dynamic metadata management
- github.com/nabbar/golib/monitor/status: Health status type
- github.com/nabbar/golib/monitor/pool: Monitor pool management
Thread Safety ¶
All interfaces and types in this package are designed for safe concurrent use. Implementations must ensure thread safety for all operations.
Index ¶
- Constants
- func DefaultConfig(indent string) []byte
- func SetDefaultConfig(cfg []byte)
- type Config
- type ConfigCompatdeprecated
- type FuncPool
- type HealthCheck
- type Info
- type InfoData
- type InfoName
- type Monitor
- type MonitorInfo
- type MonitorMetrics
- type MonitorStatus
- type Pool
- type PoolManage
- type PoolShell
- type PoolStatus
Constants ¶
const ( // ErrorParamEmpty indicates an empty or nil parameter was provided. ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgMonitorCfg // ErrorValidatorError indicates configuration validation failed. ErrorValidatorError )
Error codes for monitor configuration validation and operations.
Variables ¶
This section is empty.
Functions ¶
func DefaultConfig ¶
DefaultConfig returns the default configuration as a formatted JSON byte slice. The indent parameter specifies the indentation string to use for JSON formatting. This is useful for generating configuration file templates or documentation.
func SetDefaultConfig ¶
func SetDefaultConfig(cfg []byte)
SetDefaultConfig sets the default configuration template used by DefaultConfig. This allows customizing the default configuration values for monitors.
Types ¶
type Config ¶
type Config struct {
// Name define the name of the monitor
Name string `json:"name" yaml:"name" toml:"name" mapstructure:"name"`
// CheckTimeout define the timeout use for healthcheck. Default is 5 second.
CheckTimeout libdur.Duration `json:"check-timeout" yaml:"check-timeout" toml:"check-timeout" mapstructure:"check-timeout"`
// IntervalCheck define the time waiting between 2 healthcheck. Default is 5 second.
IntervalCheck libdur.Duration `json:"interval-check" yaml:"interval-check" toml:"interval-check" mapstructure:"interval-check"`
// IntervalFall define the time waiting between 2 healthcheck when last check is KO. Default is 5 second.
IntervalFall libdur.Duration `json:"interval-fall" yaml:"interval-fall" toml:"interval-fall" mapstructure:"interval-down"`
// IntervalRise define the time waiting between 2 healthcheck when status is KO or Warn but last check is OK. Default is 5 second.
IntervalRise libdur.Duration `json:"interval-rise" yaml:"interval-rise" toml:"interval-rise" mapstructure:"interval-rise"`
// FallCountKO define the number of KO before considerate the component as down.
FallCountKO uint8 `json:"fall-count-ko" yaml:"fall-count-ko" toml:"fall-count-ko" mapstructure:"fall-count-ko"`
// FallCountWarn define the number of KO before considerate the component as warn.
FallCountWarn uint8 `json:"fall-count-warn" yaml:"fall-count-warn" toml:"fall-count-warn" mapstructure:"fall-count-warn"`
// RiseCountKO define the number of OK when status is KO before considerate the component as up.
RiseCountKO uint8 `json:"rise-count-ko" yaml:"rise-count-ko" toml:"rise-count-ko" mapstructure:"rise-count-ko"`
// RiseCountWarn define the number of OK when status is Warn before considerate the component as up.
RiseCountWarn uint8 `json:"rise-count-warn" yaml:"rise-count-warn" toml:"rise-count-warn" mapstructure:"rise-count-warn"`
// Logger define the logger options for current monitor log
Logger logcfg.Options `json:"logger" yaml:"logger" toml:"logger" mapstructure:"logger"`
}
func (Config) Clone ¶
Clone return a copy of the config.
It is usefull when you want to create a new monitor from an existing one. The returned config is a deep copy of the original one.
func (Config) Compat ¶ added in v1.17.8
func (o Config) Compat() ConfigCompat
Compat return a ConfigCompat object which is a copy of the current config.
The returned ConfigCompat object is a deep copy of the original one. It is usefull when you want to create a new monitor from an existing one.
The returned ConfigCompat object is compatible with the ConfigCompat object from the monitor/v1 package.
type ConfigCompat
deprecated
added in
v1.17.8
type ConfigCompat struct {
// Name define the name of the monitor
Name string `json:"name" yaml:"name" toml:"name" mapstructure:"name"`
// CheckTimeout define the timeout use for healthcheck. Default is 5 second.
CheckTimeout time.Duration `json:"check-timeout" yaml:"check-timeout" toml:"check-timeout" mapstructure:"check-timeout"`
// IntervalCheck define the time waiting between 2 healthcheck. Default is 5 second.
IntervalCheck time.Duration `json:"interval-check" yaml:"interval-check" toml:"interval-check" mapstructure:"interval-check"`
// IntervalFall define the time waiting between 2 healthcheck when last check is KO. Default is 5 second.
IntervalFall time.Duration `json:"interval-fall" yaml:"interval-fall" toml:"interval-fall" mapstructure:"interval-down"`
// IntervalRise define the time waiting between 2 healthcheck when status is KO or Warn but last check is OK. Default is 5 second.
IntervalRise time.Duration `json:"interval-rise" yaml:"interval-rise" toml:"interval-rise" mapstructure:"interval-rise"`
// FallCountKO define the number of KO before considerate the component as down.
FallCountKO uint8 `json:"fall-count-ko" yaml:"fall-count-ko" toml:"fall-count-ko" mapstructure:"fall-count-ko"`
// FallCountWarn define the number of KO before considerate the component as warn.
FallCountWarn uint8 `json:"fall-count-warn" yaml:"fall-count-warn" toml:"fall-count-warn" mapstructure:"fall-count-warn"`
// RiseCountKO define the number of OK when status is KO before considerate the component as up.
RiseCountKO uint8 `json:"rise-count-ko" yaml:"rise-count-ko" toml:"rise-count-ko" mapstructure:"rise-count-ko"`
// RiseCountWarn define the number of OK when status is Warn before considerate the component as up.
RiseCountWarn uint8 `json:"rise-count-warn" yaml:"rise-count-warn" toml:"rise-count-warn" mapstructure:"rise-count-warn"`
// Logger define the logger options for current monitor log
Logger logcfg.Options `json:"logger" yaml:"logger" toml:"logger" mapstructure:"logger"`
}
ConfigCompat provides backward compatibility for monitor configurations using standard time.Duration. This type uses time.Duration instead of libdur.Duration for the timeout and interval fields. Use Config type for new code, which provides better serialization support.
Deprecated: Use Config type instead, which uses libdur.Duration for better JSON/YAML serialization.
func (ConfigCompat) Clone ¶ added in v1.17.8
func (o ConfigCompat) Clone() ConfigCompat
Clone clone the config options.
Return a new ConfigCompat with the same value as the current config options. This function is thread-safe.
func (ConfigCompat) Config ¶ added in v1.17.8
func (o ConfigCompat) Config() Config
Config returns a new Config with the same value as the current config options.
This function is thread-safe.
Config is created from ConfigCompat, which is used to configure the monitor.
The fields of Config are explained as follows:
- Name: the name of the monitor.
- CheckTimeout: the timeout for checking the status of the target.
- IntervalCheck: the interval for checking the status of the target.
- IntervalFall: the interval for falling into a KO state.
- IntervalRise: the interval for rising from a KO state.
- FallCountKO: the count for falling into a KO state.
- FallCountWarn: the count for warning a KO state.
- R iseCountKO: the count for rising from a KO state.
- R iseCountWarn: the count for warning a rise from a KO state.
- Logger: the logger for logging the status of the target.
func (ConfigCompat) Validate ¶ added in v1.17.8
func (o ConfigCompat) Validate() error
Validate validate the config options using libval validation tags. Return liberr.Error if config is not valid.
type FuncPool ¶
type FuncPool func() Pool
FuncPool is a function type that returns a Pool instance. This is used for dependency injection and lazy initialization of pools.
type HealthCheck ¶
HealthCheck is a function type that performs a health check operation. The function should return nil if the component is healthy, or an error describing the issue if it's not. The context should be respected for timeout and cancellation.
Example:
healthCheck := func(ctx context.Context) error {
return db.PingContext(ctx)
}
type Info ¶
Info is the main interface for component metadata management. It combines name and data retrieval with encoding capabilities.
type InfoData ¶ added in v1.18.0
type InfoData interface {
// Info returns a map of string to interface that contains information about the
// monitor. Common keys include "version", "build", "uptime", etc.
Info() map[string]interface{}
}
InfoData provides a method for retrieving dynamic information about a component. Implementations can return runtime-generated metadata as a key-value map.
type InfoName ¶ added in v1.18.0
type InfoName interface {
// Name returns the name of the component.
// The name is used to identify the component in logs and metrics.
Name() string
}
InfoName provides a method for retrieving the component name. This interface allows for static or dynamic name generation.
type Monitor ¶
type Monitor interface {
MonitorInfo
MonitorStatus
MonitorMetrics
libsrv.Runner
// SetConfig is used to set or update config of the monitor
SetConfig(ctx context.Context, cfg Config) error
// RegisterLoggerDefault is used to define the default logger.
// Default logger can be used to extend options logger from it
RegisterLoggerDefault(fct liblog.FuncLog)
// GetConfig is used to retrieve config of the monitor
GetConfig() Config
// SetHealthCheck is used to set or update the healthcheck func
SetHealthCheck(fct HealthCheck)
// GetHealthCheck is used to retrieve the healthcheck func
GetHealthCheck() HealthCheck
// Clone is used to clone monitor to another standalone instance
Clone(ctx context.Context) (Monitor, error)
}
type MonitorInfo ¶
type MonitorInfo interface {
// InfoGet returns the current information of the monitor.
//
// It returns the monitor information as a struct of type Info.
//
// Parameters:
// None.
//
// Returns:
// Info - the current information of the monitor.
InfoGet() Info
// InfoUpd updates the information of the monitor.
//
// Parameters:
// - inf Info: the new information of the monitor.
//
// Returns:
// - None.
InfoUpd(inf Info)
// InfoName returns the name of the monitor information.
//
// Parameters:
// None.
//
// Returns:
// string - the name of the monitor information.
InfoName() string
// InfoMap returns the current information of the monitor as a map of strings to
// interface values.
//
// It is a convenience function that allows to access the information
// without having to know the exact structure of the Info type.
//
// Parameters:
// None.
//
// Returns:
// map[string]interface{} - the current information of the monitor as a map.
//
InfoMap() map[string]interface{}
}
type MonitorMetrics ¶
type MonitorMetrics interface {
// RegisterMetricsName registers names of metrics for this monitor.
// The names are stored in memory and used to register metrics
// when calling RegisterCollectMetrics.
//
// The metric names should be in the format:
// <monitor_name>_<metric_name>
//
// For example:
// monitor_latency
// monitor_uptime
// monitor_downtime
//
// The names are case-sensitive.
//
// Parameters:
// names - a list of metric names to register.
//
// Returns:
// None.
RegisterMetricsName(names ...string)
// RegisterMetricsAddName registers additional names of metrics for this monitor.
// The names are added to the list of names stored in memory and used to register metrics
// when calling RegisterCollectMetrics.
//
// The metric names should be in the format:
// <monitor_name>_<metric_name>
//
// For example:
// monitor_latency
// monitor_uptime
// monitor_downtime
//
// The names are case-sensitive.
//
// Parameters:
// names - a list of metric names to register.
//
// Returns:
// None.
RegisterMetricsAddName(names ...string)
// RegisterCollectMetrics registers a function to collect metrics for this monitor.
//
// The function will be called by the monitor with the correct context and metric names.
// The function should update the metrics with the correct values.
//
// Parameters:
// fct - the function to register.
//
// Returns:
// None.
RegisterCollectMetrics(fct libprm.FuncCollectMetrics)
// CollectLatency returns the last check's latency.
//
// It returns the time spent between the start of the last check and the moment
// the last check returned a status (OK, Warn, KO).
//
// It returns an error if the last check didn't return a status.
//
// Parameters:
// None.
//
// Returns:
// time.Duration - the last check's latency.
// liberr.Error - an error if the last check didn't return a status.
CollectLatency() time.Duration
// CollectUpTime returns the total duration of uptime (OK status) since the
// monitor was created.
//
// Parameters:
// None.
//
// Returns:
// time.Duration - the total duration of uptime (OK status).
CollectUpTime() time.Duration
// CollectDownTime returns the total duration of downtime (KO status) since the
// monitor was created.
//
// Parameters:
// None.
//
// Returns:
// time.Duration - the total duration of downtime (KO status).
CollectDownTime() time.Duration
// CollectRiseTime returns the total duration of rising status since the monitor was created.
//
// Parameters:
// None.
//
// Returns:
// time.Duration - the total duration of rising status.
CollectRiseTime() time.Duration
// CollectFallTime returns the total duration of falling status since the
// monitor was created.
//
// Parameters:
// None.
//
// Returns:
// time.Duration - the total duration of falling status.
CollectFallTime() time.Duration
// CollectStatus returns the current status of the monitor and whether
// the status is rising or falling.
//
// Parameters:
// None.
//
// Returns:
// sts monsts.Status - the current status of the monitor.
// rise bool - whether the status is rising.
// fall bool - whether the status is falling.
CollectStatus() (sts monsts.Status, rise bool, fall bool)
}
type MonitorStatus ¶
type MonitorStatus interface {
encoding.TextMarshaler
json.Marshaler
// Name return the name of the monitor.
Name() string
// Status return the last status (OK / Warn / KO).
Status() monsts.Status
// Message return the last error, warning, message of the last status
Message() string
// IsRise return true if rising status from KO or Warn
IsRise() bool
// IsFall return true if falling status to KO or Warn
IsFall() bool
// Latency return the last check's latency
Latency() time.Duration
// Uptime return the total duration of uptime (OK status)
Uptime() time.Duration
// Downtime return the total duration of downtime (KO status)
Downtime() time.Duration
}
MonitorStatus provides methods for querying the current status and state of a monitor. It includes encoding capabilities for serializing status information.
type Pool ¶
type Pool interface {
PoolStatus
PoolShell
}
Pool is the main interface for monitor pool management. It combines status tracking, monitor management, and shell command capabilities.
type PoolManage ¶ added in v1.11.3
type PoolManage interface {
// MonitorAdd adds a monitor to the pool.
// Returns an error if the monitor is nil or has an empty name.
// If the pool is running, the monitor is automatically started.
MonitorAdd(mon Monitor) error
// MonitorGet retrieves a monitor from the pool by name.
// Returns nil if the monitor is not found.
MonitorGet(name string) Monitor
// MonitorSet updates or adds a monitor in the pool.
// If the monitor doesn't exist, it will be added.
// Returns an error if the monitor is nil or has an empty name.
MonitorSet(mon Monitor) error
// MonitorDel removes a monitor from the pool by name.
// Does nothing if the monitor doesn't exist.
MonitorDel(name string)
// MonitorList returns a slice of all monitor names in the pool.
MonitorList() []string
// MonitorWalk iterates over monitors in the pool, calling the provided function for each.
// The iteration stops if the function returns false.
// The validName parameter optionally filters which monitors to visit.
MonitorWalk(fct func(name string, val Monitor) bool, validName ...string)
}
PoolManage defines the interface for managing monitors within a pool. It provides CRUD operations and iteration capabilities for monitors.
type PoolShell ¶ added in v1.11.3
type PoolShell interface {
// GetShellCommand returns a list of available shell commands for pool operations.
// Common commands include: list, info, start, stop, restart, and status.
GetShellCommand(ctx context.Context) []shlcmd.Command
}
PoolShell provides shell command interface for pool operations. This enables CLI-style control of the pool and its monitors.
type PoolStatus ¶
type PoolStatus interface {
encoding.TextMarshaler
json.Marshaler
PoolManage
}
PoolStatus combines pool management with encoding capabilities. It allows pools to be marshaled to text and JSON formats.