lib

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: MIT Imports: 28 Imported by: 0

README ΒΆ

Checker Standard Library (lib) πŸ”‹

Welcome to the Standard Library of the Checker ecosystem!

Why write custom checks for common infrastructure when you can just plug and play? The lib package provides a robust collection of built-in checks and notifiers, ready to be used in your Go code or dynamically configured via JSON. No new DSL to learn, just pure Go!

πŸ•΅οΈβ€β™‚οΈ Available Checks

Here is a glimpse of what you get out of the box:

Network & Connectivity
  • Http: Hits an HTTP/HTTPS endpoint and validates the expected status code.
  • Ping: Sends ICMP echo requests to measure latency and verify connectivity.
  • Dns: Queries a specific DNS server to verify domain resolution.
  • Proxy: Tests HTTP proxy servers to ensure they are forwarding requests correctly.
  • Peer: Connects to the built-in HTTP server of a remote Checker instance to monitor the watcher.
System & Hardware (Powered by gopsutil)
  • Cpu: Monitors CPU utilization and alerts on high load.
  • Mem: Tracks virtual memory (RAM) usage.
  • Disk: Keeps an eye on your disk space usage.
  • Load: Monitors the 5-minute system load average.
  • Swap: Monitors swap memory usage.
  • Uptime: Ensures the system has been running for a minimum required time.
Processes & Execution
  • Cmd: Executes any local CLI command and analyzes its exit code or stdout.
  • Ssh: Attempts to connect, authenticate, and run commands against an SSH server.
  • ProcExists: Verifies if a vital background process (e.g., nginx, postgres) is currently running.
  • SysProcs: Tracks the total number of running processes to detect fork bombs or leaks.
Utilities
  • Fail: A meta-check useful for debugging or recursive logic.

πŸ“’ Available Notifiers

When things go wrong, you need to know immediately.

  • Email: Sends full-featured, customizable HTML or plaintext alerts via SMTP.
  • Pushover: Sends real-time push notifications straight to your phone, complete with priority routing and custom notification sounds!
  • Logging: The classic. Dumps check results to the standard Go log with a custom prefix.
  • Less: A smart meta-notifier that limits alert spam.

πŸ› οΈ Usage

From Go Code

Using the standard library directly in your Go code gives you perfect type safety and IDE support:

package main

import (
	"context"
	"time"

	chkr "github.com/tweithoener/checker"
	"github.com/tweithoener/checker/lib"
)

func main() {
	c := chkr.New()

	// Add built-in checks directly using their exported functions
	c.AddCheck("API Health", lib.Http("GET", "https://api.example.com/health", 200))
	c.AddCheck("System CPU", lib.Cpu(75.0, 90.0))

	// Add a built-in structured logging notifier (wrapped in rate-limiting)
	logger := lib.Logging(nil)
	c.AddNotifier(lib.Less(logger))

	c.SetInterval(30 * time.Second)
	c.Start()

	// ... wait for shutdown ...
}
From JSON Configuration

Prefer no recompiles? You can define everything in a config.json. The lib package automatically registers "Makers" for all components during initialization.

{
  "Checks": [
    {
      "Maker": "Http",
      "Name": "API Health",
      "Args": {
        "Method": "GET",
        "Url": "https://api.example.com/health",
        "Expected": 200
      }
    }
  ],
  "Notifiers": [
    {
      "Maker": "Less",
      "Args": {
        "Notifier": {
          "Maker": "Logging",
          "Args": {
            "Attributes": {
              "env": "production",
              "team": "backend"
            }
          }
        }
      }
    }
  ]
}

Just remember to blank-import the lib package in your main.go so the init hooks fire:

import _ "github.com/tweithoener/checker/lib"

Documentation ΒΆ

Overview ΒΆ

Package lib provides a robust collection of built-in Checks and Notifiers for the checker framework. It functions as the "Standard Library" of the checker ecosystem, allowing you to monitor common infrastructure without writing custom check logic.

Included components range from system metrics (CPU, Memory, Disk, Uptime) powered by gopsutil, to network diagnostics (Ping, DNS, HTTP, Proxy), and command execution (Cmd, SSH). It also provides notifiers for Logging, debugging, and mobile alerts via Pushover.

Usage in Go ΒΆ

You can instantiate checks directly using their exported functions (e.g., Http, Cpu, Ping) and add them to a Checker instance via `AddCheck`.

The JSON Registry (Inner Workings) ΒΆ

What makes the lib package powerful is its integration with the checker's JSON configuration system.

Upon package initialization (in `init()`), the lib package automatically registers a series of "Makers" (implementing [checker.CheckMaker] and [checker.NotifierMaker]) with the core checker registry. A Maker knows how to translate a generic JSON payload into a concrete arguments struct (like HttpArgs or CpuArgs) and eventually instantiate the actual Check or Notifier function.

This enables a completely data-driven monitoring setup: you can compile a single Go binary that imports this package anonymously (`_ "github.com/.../lib"`), and users can configure complex monitoring pipelines entirely through JSON, including recursive wrappers like Less and Fail.

Testing and Mocking ΒΆ

The lib package is designed with testability in mind. Most hardware- and network-dependent calls (like reading from /proc, spawning OS processes, or dialing raw ICMP sockets) are abstracted into package-level variables internally. This allows the test suite to safely mock these interactions without relying on the host system's state or privileges.

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func Cmd ΒΆ added in v0.2.0

func Cmd(analyze func(exitCode int, output string) (chkr.State, string), name string, args ...string) chkr.Check

Cmd returns a check that executes the given command and analyzes the results using the given analyze function. If analyze is nil a default analyzer function is used. This default function only considers the exit code of the called command (non zero exit code results in a failed check). Note: The default analyzer is also used when configuring this check using a json config file with checker.ReadConfig.

func Cpu ΒΆ added in v0.2.0

func Cpu(warnPercent, failPercent float64) chkr.Check

Cpu returns a check that verifies the system's total CPU usage percentage.

func Debug ΒΆ added in v0.3.0

func Debug(prefix string) chkr.Notifier

Debug returns a notifier that prints the check state directly to stdout. It is primarily intended for debugging and development. It replaces any timestamp in the output with '2001-01-01 01:01:01' to make it deterministic for testing.

func Disk ΒΆ added in v0.2.0

func Disk(path string, warnPercent, failPercent float64) chkr.Check

Disk returns a check that verifies the disk usage percentage for a specific path.

func Dns ΒΆ

func Dns(dns, hostname, address string) chkr.Check

Dns returns a check that verifies the resolution of a hostname to a specific address using a given DNS server.

func Email ΒΆ added in v0.3.0

func Email(smtpServer, user, password string, to []string, opts ...EmailOption) chkr.Notifier

Email returns a notifier that sends emails via SMTP.

func Fail ΒΆ

func Fail(chk chkr.Check) chkr.Check

Fail returns a check that wraps another check, inverting its success/fail result.

func Http ΒΆ

func Http(method, url string, expected int) chkr.Check

Http returns a check that performs an HTTP request and expects a specific status code.

func Less ΒΆ

func Less(n chkr.Notifier) chkr.Notifier

Less returns a notifier that wraps another notifier, rate-limiting the notifications.

func Load ΒΆ added in v0.2.0

func Load(warnLoad5, failLoad5 float64) chkr.Check

Load returns a check that verifies the 5-minute system load average.

func Logging ΒΆ

func Logging(logger *slog.Logger) chkr.Notifier

Logging returns a notifier that outputs check results using structured logging. If logger is nil, slog.Default() is used.

func Mem ΒΆ added in v0.2.0

func Mem(warnPercent, failPercent float64) chkr.Check

Mem returns a check that verifies the system's virtual memory usage percentage.

func Ping ΒΆ

func Ping(address string, warnMillis, failMillis int) chkr.Check

Ping returns a check that verifies connectivity via ICMP echo requests.

func ProcExists ΒΆ added in v0.2.0

func ProcExists(name string) chkr.Check

ProcExists returns a check that verifies if at least one process with the exact given name is running.

func Proxy ΒΆ

func Proxy(method, request, proxy string, expected int) chkr.Check

Proxy returns a check that performs an HTTP request through a specified proxy.

func Pushover ΒΆ

func Pushover(prefix, app, recipient string) chkr.Notifier

Pushover returns a notifier that sends messages to the Pushover service.

func Ssh ΒΆ added in v0.2.0

func Ssh(analyze func(exitCode int, output string) (chkr.State, string), host, user, command string) (chkr.Check, error)

Ssh returns a check that executes the given command on the remote host using the system's ssh command and then analyzing the command output using the analyze function. If analyze is nil a default analyzer function is used. This default function only considers the exit code of the called command (non zero exit code results in a failed check).

Note: The default analyzer is also used when configuring this check using a json config file with checker.ReadConfig.

Note: Make sure public key authentication and host key authorization is configured correctly for the user running checker for the remote machine.

func Swap ΒΆ added in v0.2.0

func Swap(warnPercent, failPercent float64) chkr.Check

Swap returns a check that verifies the system's swap memory usage percentage.

func SysProcs ΒΆ added in v0.2.0

func SysProcs(warnCount, failCount int) chkr.Check

SysProcs returns a check that verifies the total number of running processes on the system.

func Uptime ΒΆ added in v0.2.0

func Uptime(minUptime time.Duration) chkr.Check

Uptime returns a check that verifies the system's uptime and warns if it's lower than a minimum (e.g. after a reboot).

Types ΒΆ

type CmdArgs ΒΆ added in v0.2.0

type CmdArgs struct {
	Command string
	Args    []string
}

CmdArgs defines the arguments for a command execution check.

type CpuArgs ΒΆ added in v0.2.0

type CpuArgs struct {
	WarnPercent float64
	FailPercent float64
}

CpuArgs defines the arguments for a CPU usage check.

type DebugArgs ΒΆ added in v0.3.0

type DebugArgs struct {
	Prefix string
}

DebugArgs defines the arguments for a Debug notifier.

type DiskArgs ΒΆ added in v0.2.0

type DiskArgs struct {
	Path        string
	WarnPercent float64
	FailPercent float64
}

DiskArgs defines the arguments for a Disk usage check.

type DnsArgs ΒΆ

type DnsArgs struct {
	Dns      string
	Hostname string
	Address  string
}

DnsArgs defines the arguments for a DNS check.

type EmailArgs ΒΆ added in v0.3.0

type EmailArgs struct {
	SmtpServer string
	User       string
	Password   string
	To         []string
	From       string
	Template   string
}

EmailArgs defines the arguments for an Email notifier.

type EmailOption ΒΆ added in v0.3.0

type EmailOption func(*emailOptions)

EmailOption defines a functional option for the Email notifier.

func WithFrom ΒΆ added in v0.3.0

func WithFrom(from string) EmailOption

WithFrom returns an EmailOption that sets the sender address.

func WithTemplate ΒΆ added in v0.3.0

func WithTemplate(mailTemplate string) EmailOption

WithTemplate returns an EmailOption that sets a custom email body template.

type FailArgs ΒΆ

type FailArgs struct {
	chkr.WithRecursion
	Check chkr.CheckConfig
}

FailArgs defines the arguments for a Fail check wrapper.

type HttpArgs ΒΆ

type HttpArgs struct {
	Method   string
	Url      string
	Expected int
}

HttpArgs defines the arguments for an HTTP check.

type LessArgs ΒΆ

type LessArgs struct {
	Notifier chkr.NotifierConfig
}

LessArgs defines the arguments for a Less notifier wrapper.

type LoadArgs ΒΆ added in v0.2.0

type LoadArgs struct {
	WarnLoad5 float64
	FailLoad5 float64
}

LoadArgs defines the arguments for a Load Average check.

type LoggingArgs ΒΆ

type LoggingArgs struct {
	// Optional: Static attributes that will be added to every log event.
	Attributes map[string]string `json:"attributes,omitempty"`
}

LoggingArgs defines the arguments for a Logging notifier configured via JSON.

type MemArgs ΒΆ added in v0.2.0

type MemArgs struct {
	WarnPercent float64
	FailPercent float64
}

MemArgs defines the arguments for a memory usage check.

type PingArgs ΒΆ

type PingArgs struct {
	Address    string
	WarnMillis int
	FailMillis int
}

PingArgs defines the arguments for a Ping check.

type ProcExistsArgs ΒΆ added in v0.2.0

type ProcExistsArgs struct {
	Name string
}

ProcExistsArgs defines the arguments for a Process Exists check.

type ProxyArgs ΒΆ

type ProxyArgs struct {
	Method   string
	Request  string
	Proxy    string
	Expected int
}

ProxyArgs defines the arguments for a proxy connectivity check.

type PushoverArgs ΒΆ

type PushoverArgs struct {
	Prefix    string
	App       string
	Recipient string
}

PushoverArgs defines the arguments for a Pushover notifier.

type SshArgs ΒΆ added in v0.2.0

type SshArgs struct {
	Host    string
	User    string
	Command string
}

SshArgs defines the arguments for an SSH command execution check.

type SwapArgs ΒΆ added in v0.2.0

type SwapArgs struct {
	WarnPercent float64
	FailPercent float64
}

SwapArgs defines the arguments for a Swap usage check.

type SysProcsArgs ΒΆ added in v0.2.0

type SysProcsArgs struct {
	WarnCount int
	FailCount int
}

SysProcsArgs defines the arguments for a Total Process Count check.

type UptimeArgs ΒΆ added in v0.2.0

type UptimeArgs struct {
	MinMinutes uint64 // Warn if uptime is less than this value (e.g. recent reboot)
}

UptimeArgs defines the arguments for an Uptime check.

Jump to

Keyboard shortcuts

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