checks

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: 6 Imported by: 0

README

Checks Package

The checks package provides CEL (Common Expression Language) expression evaluation for health check validation. It is used by providers to validate responses and resources using powerful, flexible expressions.

Debugging CEL Expressions

Use ph context to inspect the evaluation context available to your CEL expressions:

# View context for a configured component
ph context my-app

# View context for ad-hoc provider
ph context kubernetes --kind deployment --namespace default --name my-app

# Output as YAML for readability
ph context my-app -o yaml

CEL Expression Syntax

CEL expressions must evaluate to a boolean (true for healthy, false for unhealthy). Expressions have access to provider-specific context variables (e.g., response for HTTP, resource for Kubernetes).

Check Modes

Each check can optionally specify a mode field:

  • default (no mode field): The expression is evaluated once against the full provider context.
  • mode: "each": The expression is evaluated per-item for providers that return collections (e.g., Kubernetes with label selectors). Each item is evaluated independently, and failures reference the specific item.
checks:
  - check: "resource.status.readyReplicas >= resource.spec.replicas"
    message: "Not all replicas ready"
    mode: "each"

Built-in Functions

The following custom functions are available in all CEL expressions:

  • time.Now() - Returns the current timestamp
  • time.Since(timestamp) - Returns the duration elapsed since the given timestamp
  • time.Until(timestamp) - Returns the duration until the given timestamp
checks:
  - check: "time.Until(tls.validUntil) > duration('168h')"
    message: "Certificate expires within 7 days"

Standard Extensions

The following CEL extension libraries are available:

  • Strings: Additional string functions (charAt, indexOf, replace, split, substring, trim, upperAscii, lowerAscii)
  • Lists: List manipulation functions (slice, flatten)
  • Encoders: Base64 encoding/decoding (base64.encode, base64.decode)
  • Math: Math functions (math.greatest, math.least)
  • Sets: Set operations (sets.contains, sets.intersects, sets.equivalent)
  • Bindings: Variable binding via cel.bind()

Common CEL Patterns

Note: The examples below use data as a generic illustrative placeholder variable. Actual CEL context variables are provider-specific — for example, response for HTTP, resource for Kubernetes, tls for TLS, health for Vault, and release/chart for Helm. See each provider's README for its available CEL variables, or use ph context to inspect the evaluation context.

Simple Field Validation
checks:
  - check: "data.ready == true"
    message: "Service not ready"
Nested Field Access
checks:
  - check: "data.services.database.connected == true"
    message: "Database not connected"
Numeric Comparisons
checks:
  - check: "data.activeConnections < 1000"
    message: "Too many active connections"
Array Operations
checks:
  - check: "size(data.errors) == 0"
    message: "System has reported errors"
  - check: "size(data.items) > 0"
    message: "No items in response"
String Operations
checks:
  - check: 'data.message.contains("SUCCESS")'
    message: "Success message not found"
  - check: 'data.version.startsWith("2.")'
    message: "Wrong API version"
Logical Operations
checks:
  - check: "data.value >= 200 && data.value < 300"
    message: "Value outside expected range"
  - check: 'data.state == "active" || data.state == "standby"'
    message: "Service in unexpected state"
Regex Pattern Matching
checks:
  - check: 'data.id.matches("\\d{3}-\\d{2}-\\d{4}")'
    message: "Invalid format in response"
  - check: 'data.status.matches("(?i)success|ok|healthy")'
    message: "No success indicator found"
Existence Checks (Lists)
checks:
  - check: "data.conditions.exists(c, c.type == 'Ready' && c.status == 'True')"
    message: "Ready condition not met"
Map Key Checks
checks:
  - check: "'required_key' in data.config"
    message: "Required key missing from config"

Security

  • CEL expressions are validated at configuration load time to catch syntax errors early
  • CEL expressions are sandboxed and cannot execute arbitrary code or access the filesystem
  • Expression evaluation is deterministic and side-effect free

Documentation

Overview

Package checks provides shared CEL (Common Expression Language) evaluation capabilities for health check providers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ValidateExpression

func ValidateExpression(expression string, variables ...cel.EnvOption) error

ValidateExpression validates CEL expression syntax at configuration time. Variables should be declared using cel.Variable() options.

Types

type CEL

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

CEL holds configuration for CEL expression evaluation including variable declarations and a cache for compiled ASTs.

func NewCEL

func NewCEL(variables ...cel.EnvOption) *CEL

NewCEL creates a CEL configuration with the given variable declarations. Standard functions (like `time.Now()`) are automatically included. Each provider should create a package-level instance.

func (*CEL) Compile added in v0.7.0

func (c *CEL) Compile(expr Expression) (*Check, error)

Compile compiles a single expression into a Check.

func (*CEL) CompileAll added in v0.7.0

func (c *CEL) CompileAll(exprs []Expression) ([]*Check, error)

CompileAll compiles multiple expressions into Checks.

func (*CEL) EvaluateAny added in v0.7.0

func (c *CEL) EvaluateAny(expr string, celCtx map[string]any) (any, error)

EvaluateAny compiles and evaluates a CEL expression returning its result. Unlike Check.Evaluate(), this does not require boolean output - any type is allowed. The result is converted to native Go types for serialization. Note: Uses the cached environment but compiles the AST directly (no caching) since the boolean output validation in getOrCompileAST() doesn't apply here.

func (*CEL) EvaluateEach added in v0.7.0

func (c *CEL) EvaluateEach(expr string, celCtx map[string]any, manyKey, singleKey string) ([]any, error)

EvaluateEach evaluates a CEL expression for each item in a collection. Parameters:

  • expr: the CEL expression to evaluate
  • celCtx: the full CEL context
  • manyKey: the key in celCtx containing a []any of items (e.g., "items")
  • singleKey: the key to use when creating per-item context (e.g., "resource")

If manyKey exists and is a []any, evaluates expr against each item with context {singleKey: item}. Otherwise, evaluates expr once against the full context and returns a single-element slice.

func (*CEL) EvaluateEachConfigured added in v0.7.0

func (c *CEL) EvaluateEachConfigured(expr string, celCtx map[string]any) ([]any, error)

EvaluateEachConfigured evaluates a CEL expression using the configured iteration keys. If IterationKeys is configured, iterates over the collection; otherwise evaluates once. This is the preferred method for context inspection where keys come from the provider.

func (*CEL) SupportsEachMode added in v0.7.0

func (c *CEL) SupportsEachMode() bool

SupportsEachMode returns true if this CEL configuration supports per-item iteration.

func (*CEL) WithIterationKeys added in v0.7.0

func (c *CEL) WithIterationKeys(manyKey, singleKey string) *CEL

WithIterationKeys configures iteration support for per-item evaluation. Providers that return collections (e.g., Kubernetes with label selectors) should call this to enable --expr-each in the context command.

type Check added in v0.7.0

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

Check represents a single compiled CEL check.

func (*Check) Evaluate added in v0.7.0

func (c *Check) Evaluate(celCtx map[string]any, bindings ...cel.EnvOption) (string, error)

Evaluate runs this check against the context with optional runtime function bindings. Bindings are added via env.Extend() to inject runtime-specific implementations (e.g., kubernetes.Get with client context). Returns ("", nil) on success, (message, nil) on check failure, ("", err) on evaluation error.

type Expression

type Expression struct {
	Expression string `mapstructure:"check"`
	Message    string `mapstructure:"message"`
	Mode       string `mapstructure:"mode"` // "each" for per-item evaluation, empty for default
}

Expression represents a CEL expression validation rule

func ParseConfig added in v0.7.0

func ParseConfig(raw any) ([]Expression, error)

ParseConfig converts raw YAML config to []Expression. Accepts either:

  • A slice of strings (simple expressions)
  • A slice of maps with "check" and optional "message" keys

func (Expression) Each added in v0.7.0

func (e Expression) Each() bool

Each returns true if this expression should be evaluated per-item

type IterationKeys added in v0.7.0

type IterationKeys struct {
	ManyKey   string // Key in context containing []any of items (e.g., "items")
	SingleKey string // Key used when evaluating per-item (e.g., "resource")
}

IterationKeys defines how to iterate over multiple items in a provider's context. Only applicable to providers that return collections (e.g., Kubernetes with label selectors).

type Mode added in v0.7.0

type Mode int

Mode represents a check execution mode (default or per-item).

const (
	ModeDefault Mode = iota // checks with no mode or empty mode
	ModeEach                // checks with mode: "each" (per-item)
)

Directories

Path Synopsis
Package functions provides custom CEL functions for health check expressions.
Package functions provides custom CEL functions for health check expressions.

Jump to

Keyboard shortcuts

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