endpoint

package
v1.2.12 Latest Latest
Warning

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

Go to latest
Published: May 7, 2026 License: AGPL-3.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotStandalone    = errors.New("endpoint is not standalone")
	ErrEndpointNotFound = errors.New("endpoint not found")
	ErrLimitReached     = errors.New("endpoint limit reached")
)

Functions

func ClearLinkLocalWarning

func ClearLinkLocalWarning(endpointID int64)

ClearLinkLocalWarning removes the link-local warning state for an endpoint (e.g., on reconfigure).

func ParseEndpointLabels

func ParseEndpointLabels(labels map[string]string, logger *slog.Logger) ([]*ParsedEndpoint, []*LabelParseError)

ParseEndpointLabels extracts endpoint definitions from a Docker container's labels. Returns parsed endpoints and any configuration errors encountered.

Types

type AlertCallback

type AlertCallback func(ep *Endpoint, result CheckResult) (eventType string, eventData interface{})

AlertCallback is called after ProcessCheckResult to evaluate alert thresholds. It receives the updated endpoint and the check result. It should return an event type ("endpoint.alert" or "endpoint.recovery") and event data, or empty string if no alert.

type AlertState

type AlertState string

AlertState represents the current alert state of an endpoint.

const (
	AlertNormal   AlertState = "normal"
	AlertAlerting AlertState = "alerting"
)

type CheckEngine

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

CheckEngine manages per-endpoint check goroutines.

func NewCheckEngine

func NewCheckEngine(callback CheckResultCallback, logger *slog.Logger) *CheckEngine

NewCheckEngine creates a new check engine.

func (*CheckEngine) ActiveCount

func (e *CheckEngine) ActiveCount() int

ActiveCount returns the number of active check goroutines.

func (*CheckEngine) AddEndpoint

func (e *CheckEngine) AddEndpoint(ctx context.Context, ep *Endpoint)

AddEndpoint starts a check goroutine for the given endpoint. If a goroutine already exists for this endpoint, it is stopped first.

func (*CheckEngine) ReconfigureEndpoint

func (e *CheckEngine) ReconfigureEndpoint(ctx context.Context, ep *Endpoint)

ReconfigureEndpoint stops and restarts the check goroutine with updated configuration.

func (*CheckEngine) RemoveEndpoint

func (e *CheckEngine) RemoveEndpoint(endpointID int64)

RemoveEndpoint stops the check goroutine for the given endpoint ID.

func (*CheckEngine) Stop

func (e *CheckEngine) Stop()

Stop cancels all running check goroutines and waits for them to finish.

type CheckResult

type CheckResult struct {
	ID                  int64               `json:"id"`
	EndpointID          int64               `json:"endpoint_id"`
	Success             bool                `json:"success"`
	ResponseTimeMs      int64               `json:"response_time_ms"`
	HTTPStatus          *int                `json:"http_status,omitempty"`
	ErrorMessage        string              `json:"error_message,omitempty"`
	Timestamp           time.Time           `json:"timestamp"`
	TLSPeerCertificates []*x509.Certificate `json:"-"`
}

CheckResult represents a single probe result for an endpoint.

func CheckHTTP

func CheckHTTP(ctx context.Context, ep *Endpoint, logger interface{ Warn(string, ...any) }) CheckResult

CheckHTTP performs an HTTP(S) health check against the given endpoint.

func CheckTCP

func CheckTCP(ctx context.Context, ep *Endpoint, logger interface{ Warn(string, ...any) }) CheckResult

CheckTCP performs a TCP connectivity probe against the given endpoint.

type CheckResultCallback

type CheckResultCallback func(endpointID int64, result CheckResult)

CheckResultCallback is called when a check completes.

type DefaultLicenseChecker added in v1.2.2

type DefaultLicenseChecker struct {
	MaxEndpoints int
}

DefaultLicenseChecker implements Community edition limits.

func (*DefaultLicenseChecker) CanCreateEndpoint added in v1.2.2

func (c *DefaultLicenseChecker) CanCreateEndpoint(currentCount int) bool

type Deps added in v1.1.0

type Deps struct {
	Store                   EndpointStore           // required
	Engine                  *CheckEngine            // required
	Logger                  *slog.Logger            // required
	LicenseChecker          LicenseChecker          // optional — defaults to community limits
	EventCallback           EventCallback           // optional — nil-safe
	AlertCallback           AlertCallback           // optional — nil-safe
	EndpointRemovedCallback EndpointRemovedCallback // optional — nil-safe
}

Deps holds all dependencies for the endpoint Service.

type Endpoint

type Endpoint struct {
	ID                   int64          `json:"id"`
	ContainerName        string         `json:"container_name"`
	LabelKey             string         `json:"label_key"`
	ExternalID           string         `json:"external_id"`
	EndpointType         EndpointType   `json:"endpoint_type"`
	Target               string         `json:"target"`
	Status               EndpointStatus `json:"status"`
	AlertState           AlertState     `json:"alert_state"`
	ConsecutiveFailures  int            `json:"consecutive_failures"`
	ConsecutiveSuccesses int            `json:"consecutive_successes"`
	LastCheckAt          *time.Time     `json:"last_check_at,omitempty"`
	LastResponseTimeMs   *int64         `json:"last_response_time_ms,omitempty"`
	LastHTTPStatus       *int           `json:"last_http_status,omitempty"`
	LastError            string         `json:"last_error,omitempty"`
	Config               EndpointConfig `json:"config"`
	Active               bool           `json:"active"`
	FirstSeenAt          time.Time      `json:"first_seen_at"`
	LastSeenAt           time.Time      `json:"last_seen_at"`
	OrchestrationGroup   string         `json:"orchestration_group,omitempty"`
	OrchestrationUnit    string         `json:"orchestration_unit,omitempty"`
	Source               EndpointSource `json:"source"`
	Name                 string         `json:"name,omitempty"`
}

Endpoint represents a monitored HTTP or TCP target.

func (*Endpoint) ConfigJSON

func (e *Endpoint) ConfigJSON() string

ConfigJSON returns the JSON-encoded configuration.

type EndpointConfig

type EndpointConfig struct {
	Interval          time.Duration     `json:"interval"`
	Timeout           time.Duration     `json:"timeout"`
	FailureThreshold  int               `json:"failure_threshold"`
	RecoveryThreshold int               `json:"recovery_threshold"`
	Method            string            `json:"method,omitempty"`
	ExpectedStatus    string            `json:"expected_status,omitempty"`
	TLSVerify         bool              `json:"tls_verify"`
	Headers           map[string]string `json:"headers,omitempty"`
	MaxRedirects      int               `json:"max_redirects,omitempty"`
}

EndpointConfig holds the configuration parameters for endpoint checks.

func DefaultConfig

func DefaultConfig() EndpointConfig

DefaultConfig returns an EndpointConfig with sensible defaults.

func (EndpointConfig) MarshalJSON

func (c EndpointConfig) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for EndpointConfig to use string durations.

func (EndpointConfig) UnmarshalJSON

func (c EndpointConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for EndpointConfig with string durations.

type EndpointRemovedCallback

type EndpointRemovedCallback func(ctx context.Context, endpointID int64)

EndpointRemovedCallback is called when an endpoint is deactivated (label removed or container destroyed).

type EndpointSource added in v1.1.2

type EndpointSource string

EndpointSource represents the origin of an endpoint definition.

const (
	SourceLabel      EndpointSource = "label"
	SourceStandalone EndpointSource = "standalone"
)

type EndpointStatus

type EndpointStatus string

EndpointStatus represents the current check status.

const (
	StatusUp      EndpointStatus = "up"
	StatusDown    EndpointStatus = "down"
	StatusUnknown EndpointStatus = "unknown"
)

type EndpointStore

type EndpointStore interface {
	// Endpoint CRUD (label-discovered)
	UpsertEndpoint(ctx context.Context, e *Endpoint) (int64, error)
	GetEndpointByIdentity(ctx context.Context, containerName, labelKey string) (*Endpoint, error)
	GetEndpointByID(ctx context.Context, id int64) (*Endpoint, error)
	ListEndpoints(ctx context.Context, opts ListEndpointsOpts) ([]*Endpoint, error)
	ListEndpointsByExternalID(ctx context.Context, externalID string) ([]*Endpoint, error)
	CountActiveEndpoints(ctx context.Context) (int, error)
	DeactivateEndpoint(ctx context.Context, id int64) error

	// Standalone endpoint CRUD
	InsertStandaloneEndpoint(ctx context.Context, e *Endpoint) (int64, error)
	UpdateStandaloneEndpoint(ctx context.Context, id int64, name, target string, endpointType EndpointType, configJSON string) error
	DeleteStandaloneEndpoint(ctx context.Context, id int64) error

	// Check result updates on the endpoint record
	UpdateCheckResult(ctx context.Context, id int64, status EndpointStatus, alertState AlertState,
		consecutiveFailures, consecutiveSuccesses int,
		responseTimeMs int64, httpStatus *int, lastError string) error

	// Check result persistence
	InsertCheckResult(ctx context.Context, result *CheckResult) (int64, error)
	ListCheckResults(ctx context.Context, endpointID int64, opts ListChecksOpts) ([]*CheckResult, int, error)
	GetCheckResultsInWindow(ctx context.Context, endpointID int64, from, to time.Time) (int, int, error)

	// Retention
	DeleteCheckResultsBefore(ctx context.Context, before time.Time, batchSize int) (int64, error)
	DeleteInactiveEndpointsBefore(ctx context.Context, before time.Time) (int64, error)
}

EndpointStore defines the persistence interface for endpoint monitoring data.

type EndpointType

type EndpointType string

EndpointType represents the protocol type of a monitored endpoint.

const (
	TypeHTTP EndpointType = "http"
	TypeTCP  EndpointType = "tcp"
)

type EventCallback

type EventCallback func(eventType string, data interface{})

EventCallback is called when an endpoint event occurs (for SSE broadcasting).

type LabelParseError

type LabelParseError struct {
	LabelKey string
	Value    string
	Message  string
}

LabelParseError represents a label validation error.

func (*LabelParseError) Error

func (e *LabelParseError) Error() string

type LicenseChecker added in v1.2.2

type LicenseChecker interface {
	CanCreateEndpoint(currentCount int) bool
}

LicenseChecker determines license-gated capabilities for endpoints.

type ListChecksOpts

type ListChecksOpts struct {
	Limit  int
	Offset int
	Since  *time.Time
}

ListChecksOpts configures check result listing queries.

type ListEndpointsOpts

type ListEndpointsOpts struct {
	Status             string
	ContainerName      string
	OrchestrationGroup string
	EndpointType       string
	Source             string
	IncludeInactive    bool
}

ListEndpointsOpts configures endpoint listing queries.

type ParsedEndpoint

type ParsedEndpoint struct {
	LabelKey     string
	EndpointType EndpointType
	Target       string
	Config       EndpointConfig
	Index        int
}

ParsedEndpoint holds a parsed endpoint definition from container labels.

type Service

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

Service orchestrates endpoint discovery, persistence, and the check engine.

func NewService

func NewService(d Deps) *Service

NewService creates a new endpoint service with all dependencies.

func (*Service) CalculateUptime

func (s *Service) CalculateUptime(ctx context.Context, endpointID int64) map[string]float64

CalculateUptime computes uptime percentages for an endpoint across multiple time windows.

func (*Service) CountActiveEndpoints added in v1.2.2

func (s *Service) CountActiveEndpoints(ctx context.Context) (int, error)

CountActiveEndpoints returns the count of all active endpoints (both standalone and label-discovered).

func (*Service) CreateStandalone added in v1.1.2

func (s *Service) CreateStandalone(ctx context.Context, name, target string, epType EndpointType, config EndpointConfig) (*Endpoint, error)

CreateStandalone creates a manually-defined endpoint and starts monitoring it.

func (*Service) DeleteStandalone added in v1.1.2

func (s *Service) DeleteStandalone(ctx context.Context, id int64) error

DeleteStandalone removes a standalone endpoint and stops monitoring it.

func (*Service) GetEndpoint

func (s *Service) GetEndpoint(ctx context.Context, id int64) (*Endpoint, error)

GetEndpoint retrieves an endpoint by ID.

func (*Service) HandleContainerDestroy

func (s *Service) HandleContainerDestroy(ctx context.Context, externalID string)

HandleContainerDestroy deactivates all endpoints for a destroyed container.

func (*Service) HandleContainerStart

func (s *Service) HandleContainerStart(ctx context.Context, containerName, externalID string, labels map[string]string, orchestrationGroup, orchestrationUnit string)

HandleContainerStart re-syncs endpoint labels and resumes checks when a container starts.

func (*Service) HandleContainerStop

func (s *Service) HandleContainerStop(ctx context.Context, externalID string)

HandleContainerStop pauses checks and sets endpoints to unknown for a stopped container.

func (*Service) ListCheckResults

func (s *Service) ListCheckResults(ctx context.Context, endpointID int64, opts ListChecksOpts) ([]*CheckResult, int, error)

ListCheckResults returns check results for an endpoint.

func (*Service) ListEndpoints

func (s *Service) ListEndpoints(ctx context.Context, opts ListEndpointsOpts) ([]*Endpoint, error)

ListEndpoints returns endpoints matching the given options.

func (*Service) ProcessCheckResult

func (s *Service) ProcessCheckResult(ctx context.Context, endpointID int64, result CheckResult)

ProcessCheckResult handles a check result: updates the endpoint state and persists the result.

func (*Service) SetAlertCallback

func (s *Service) SetAlertCallback(cb AlertCallback)

SetAlertCallback sets the callback for evaluating alert thresholds on check results.

func (*Service) SetEndpointRemovedCallback

func (s *Service) SetEndpointRemovedCallback(cb EndpointRemovedCallback)

SetEndpointRemovedCallback sets the callback for when an endpoint is deactivated.

func (*Service) SetEventCallback

func (s *Service) SetEventCallback(cb EventCallback)

SetEventCallback sets the callback for broadcasting endpoint events.

func (*Service) Start

func (s *Service) Start(ctx context.Context)

Start begins the check engine and stores the context for adding endpoints later.

func (*Service) Stop

func (s *Service) Stop()

Stop shuts down the check engine.

func (*Service) SyncEndpoints

func (s *Service) SyncEndpoints(ctx context.Context, containerName, externalID string, labels map[string]string, orchestrationGroup, orchestrationUnit string)

SyncEndpoints synchronizes endpoint definitions from container labels with the store and check engine.

func (*Service) UpdateStandalone added in v1.1.2

func (s *Service) UpdateStandalone(ctx context.Context, id int64, name, target string, epType EndpointType, config EndpointConfig) (*Endpoint, error)

UpdateStandalone updates a standalone endpoint's configuration and restarts monitoring.

type StatusMatcher

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

StatusMatcher evaluates whether an HTTP status code matches the expected pattern.

func NewStatusMatcher

func NewStatusMatcher(pattern string) *StatusMatcher

NewStatusMatcher parses an expected-status string (e.g., "2xx", "200,201", "2xx,301") and returns a StatusMatcher. Returns a default 2xx matcher on empty input.

func (*StatusMatcher) Matches

func (m *StatusMatcher) Matches(statusCode int) bool

Matches returns true if the given HTTP status code matches any of the expected patterns.

Jump to

Keyboard shortcuts

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