custom

package
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 49 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package custom holds the customer-extensible check modules of wt-agent: Nagios-style plugins and Prometheus text-exposition scrapes.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AsyncProfile

func AsyncProfile(ctx context.Context, raw json.RawMessage, post PostProfile) error

AsyncProfile attaches to every matching JVM each interval until ctx ends. Without a config it waits.

func Emit

func Emit(out Sink, check, plugin string, labels map[string]string, r Result, at time.Time)

Emit turns a result into samples: `wt_check_status` (0 to 3) and one gauge per perfdata item.

func EmitLocal

func EmitLocal(out Sink, script string, labels map[string]string, r LocalResult, at time.Time)

EmitLocal writes one local-check result as wt_check_status and wt_check_perf_* (the nagios series, plugin = script), on the piggyback host when the line came from such a block.

func JoinCluster

func JoinCluster(ctx context.Context, c ClusterConfig, out Sink) (func(string) bool, error)

JoinCluster starts membership for a non-scrape user (cluster checks) and returns the owner test: owns(key) is true on exactly one live peer for every key.

func PluginName

func PluginName(p string) bool

PluginName reports whether p is a bare, plain file name.

func PprofScrape

func PprofScrape(ctx context.Context, raw json.RawMessage, post PostProfile) error

PprofScrape runs until ctx ends.

func ReadTextfiles

func ReadTextfiles(dir string, out Sink, now time.Time)

ReadTextfiles forwards the samples of every *.prom file in dir (the node_exporter textfile collector format). Files older than staleAfter are skipped and counted in the gauge `wt_textfile_stale_files`; unreadable or malformed files are skipped with a debug log.

func Relabel

func Relabel(labels map[string]string, rules []RelabelRule) (map[string]string, bool)

Relabel applies rules in order to a copy of labels. The bool is false when a keep or drop rule removed the target (the labels are then nil). A rule with an invalid regex or action is skipped; ValidateRelabel reports those at config load.

func ValidateRelabel

func ValidateRelabel(rules []RelabelRule) error

ValidateRelabel checks the rules once so a bad config fails at load time, not on every scrape.

Types

type AsyncProfilerConfig

type AsyncProfilerConfig struct {
	Binary   string `json:"binary"`   // absolute path of asprof; required
	Match    string `json:"match"`    // regexp on /proc/<pid>/cmdline; required, must match a java process
	Service  string `json:"service"`  // service name, default the JVM's main class
	Event    string `json:"event"`    // default cpu
	Interval string `json:"interval"` // default 60s, at least 30s
	Seconds  int    `json:"seconds"`  // sampling time per round, default 10
}

AsyncProfilerConfig is the `async_profiler` module config.

type CheckSpec

type CheckSpec struct {
	Name     string            `json:"name"`
	Plugin   string            `json:"plugin"`
	Args     []string          `json:"args"`
	Interval string            `json:"interval"`
	Timeout  string            `json:"timeout"`
	Enabled  *bool             `json:"enabled"`
	Labels   map[string]string `json:"labels"`
}

CheckSpec is one plugin to run. Plugin and Args come only from the agent's own config file: Plugin is a bare file name inside plugin_dir and Args go to it as argv (no shell). Remote config can only set Enabled, Interval, Timeout and Labels of a check the file defines.

type ClusterConfig

type ClusterConfig struct {
	PeersDNS string   `json:"peers_dns"`
	Peers    []string `json:"peers"`
	Self     string   `json:"self"`
	Refresh  string   `json:"refresh_interval"`
}

ClusterConfig names the peers. PeersDNS is resolved to A/AAAA records every Refresh (default 15 s); Peers is a static list instead. Self is this agent's address among them (default $POD_IP, else the first local interface address found in the peer list).

type DogMapping added in v0.3.1

type DogMapping struct {
	Match  string            `json:"match"`  // dotted glob, `*` = exactly one segment
	Name   string            `json:"name"`   // new metric name, $1.. = captures
	Labels map[string]string `json:"labels"` // extra tags, values may use $1..
}

DogMapping is one name-mapping rule (statsd_exporter style).

type DogStatsD

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

DogStatsD aggregates StatsD/DogStatsD datagrams into OTLP gauges and sums, flushed every 10 s:

g  gauge: the last value                    c  counter: cumulative sum of value/sample-rate
ms, h: <name>.count (cumulative, scaled by the sample rate), .avg, .min, .max, .95percentile
d  distribution: a cumulative histogram on fixed log-spaced bounds (mergeable across hosts and
   series); only an exporter without histograms gets the summary above instead
s  set: <name> is the number of distinct values in the interval

Tags (`#k:v,flag`) become attributes. Events (`_e{..}:title|text|...`) become log records tagged `datadog.event` and service checks (`_sc|name|status|...`) the gauge `datadog.check_run.status`, the same shapes the gateway builds for the Datadog Agent API. Unparsable lines are counted in `wt_dogstatsd_invalid_total`.

func NewDogStatsD

func NewDogStatsD() *DogStatsD

NewDogStatsD returns an empty aggregator.

func (*DogStatsD) Feed

func (d *DogStatsD) Feed(datagram string)

Feed parses one datagram (any number of newline-separated lines).

func (*DogStatsD) Flush

func (d *DogStatsD) Flush(out Sink, now time.Time)

Flush writes what changed since the last flush. Gauges and counters are sent when touched; timer and histogram summaries and set sizes cover the interval and then reset.

func (*DogStatsD) Run

func (*DogStatsD) Run(ctx context.Context, raw json.RawMessage, out Sink) error

Run listens on UDP and/or a Unix datagram socket and flushes every 10 s until ctx ends.

type DogStatsDConfig

type DogStatsDConfig struct {
	Listen string `json:"listen"` // UDP address, default 127.0.0.1:8125
	Socket string `json:"socket"` // Unix datagram socket path, as well as or instead of Listen
	// Mappings rewrite dotted metric names into a name plus labels, first match wins. In Match,
	// `*` is one dot-separated segment; Name and Label values refer to the captures as $1, $2, ...
	Mappings []DogMapping `json:"mappings"`
}

DogStatsDConfig is the module config. It is local-file only (no Overlay): a listen address is a network exposure the server must not be able to open.

type EnrichConfig

type EnrichConfig struct {
	Rules   []EnrichRule `json:"rules"`
	Refresh string       `json:"refresh"` // default 60s
}

EnrichConfig is the module config.

type EnrichRule

type EnrichRule struct {
	SDConfigs   []SDConfig        `json:"sd_configs"`
	MatchAttr   string            `json:"match_attr"`   // e.g. host.name, net.host.ip, k8s.pod.name
	TargetLabel string            `json:"target_label"` // default __address__
	Labels      map[string]string `json:"labels"`       // target label -> attribute to set
}

EnrichRule joins one discovery set into the data.

func (EnrichRule) Index

func (r EnrichRule) Index(ts []TargetSpec) map[string]map[string]string

Index builds the lookup of one rule from targets.

type Enricher

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

Enricher is safe for concurrent use; Apply is a no-op until Run has loaded targets.

func (*Enricher) Apply

func (e *Enricher) Apply(attrs map[string]string)

Apply adds the joined labels to attrs (in place); existing attributes are kept.

func (*Enricher) Run

func (e *Enricher) Run(ctx context.Context, raw json.RawMessage) error

Run loads cfg and refreshes the targets until ctx ends; then Apply stops enriching.

type LocalChecks

type LocalChecks struct{}

LocalChecks runs Checkmk-style local checks: every executable in Dir prints lines of

<status> <service> <perfdata> <text>

where status is 0-3 or P (computed from the perfdata thresholds), service may be "quoted", perfdata is `-` or `name=value;warn;crit;min;max|...`. Lines between `<<<<host>>>>` and `<<<<>>>>` are piggyback data: they are reported with that host.name instead of the agent's. Dir comes only from the agent's own config file; remote config can only toggle the module.

func (LocalChecks) Run

func (LocalChecks) Run(ctx context.Context, raw json.RawMessage, out Sink) error

Run executes the scripts on the interval until ctx ends.

type LocalConfig

type LocalConfig struct {
	Dir      string            `json:"dir"`
	Interval string            `json:"interval"` // default 60s
	Timeout  string            `json:"timeout"`  // per script, default 10s
	Labels   map[string]string `json:"labels"`
}

LocalConfig is the local_checks module config.

type LocalResult

type LocalResult struct {
	Host    string // piggyback host, "" for the agent's own host
	Service string
	Result
}

LocalResult is one parsed local-check line.

func ParseLocal

func ParseLocal(out string) []LocalResult

ParseLocal parses local-check output, including piggyback blocks. Bad lines are skipped.

type Nagios

type Nagios struct {
	PluginDir string
}

Nagios runs plugins from PluginDir.

func (Nagios) Overlay

func (n Nagios) Overlay(local, remote json.RawMessage) (json.RawMessage, error)

Overlay applies a remote-origin config to the local one. Remote entries must name a check the local file defines, may carry only name, enabled, interval, timeout and labels (unknown keys such as plugin, args or env fail the decode), and cannot add checks. Local checks the remote does not mention stay as they are.

func (Nagios) Run

func (n Nagios) Run(ctx context.Context, raw json.RawMessage, out Sink) error

Run schedules every check until ctx ends.

func (Nagios) RunCheck

func (n Nagios) RunCheck(ctx context.Context, spec CheckSpec) Result

RunCheck runs one plugin. The plugin gets a minimal environment, never the agent's own (which holds the credential), and the output is capped.

type NagiosConfig

type NagiosConfig struct {
	Checks []CheckSpec `json:"checks"`
}

NagiosConfig is the module config.

type Perf

type Perf struct {
	Label                string
	Value                float64
	UOM                  string
	Warn, Crit, Min, Max *float64
}

Perf is one `label=value[UOM];warn;crit;min;max` datum. Thresholds that are not plain numbers (Nagios ranges such as `10:20`) are left nil.

func ParsePerfdata

func ParsePerfdata(s string) ([]Perf, error)

ParsePerfdata parses the Nagios performance data format. Unparseable items are skipped and reported in the error; the good ones are still returned.

type PostProfile

type PostProfile func(ctx context.Context, service, sampleType string, gz []byte) error

PostProfile uploads one gzip'd pprof for service.

type PprofConfig

type PprofConfig struct {
	Targets    []TargetSpec `json:"targets"`     // url = http(s)://host:port; labels.service names the service
	SDConfigs  []SDConfig   `json:"sd_configs"`  // any discovery the prometheus module has
	Profiles   []string     `json:"profiles"`    // default cpu, heap, goroutine
	Interval   string       `json:"interval"`    // default 60s
	CPUSeconds int          `json:"cpu_seconds"` // default 10, at most interval - 5s
}

PprofConfig is the `pprof_scrape` module config.

type PromConfig

type PromConfig struct {
	Targets []TargetSpec `json:"targets"`
	// TargetsFile is a JSON or YAML file in Prometheus file_sd form
	// (`[{"targets": ["host:port"], "labels": {...}}]`), re-read every 30 s.
	TargetsFile string `json:"targets_file"`
	// TextfileDir holds `*.prom` files in exposition format (the textfile collector).
	TextfileDir string `json:"textfile_dir"`
	// SDConfigs discover targets (http, dns, consul, ec2; see promsd.go), local config only.
	SDConfigs []SDConfig `json:"sd_configs"`
	// ShardTotal and ShardIndex split every target (static, file and discovered) across agents
	// sharing one config: this agent scrapes the targets whose md5(url) mod ShardTotal is ShardIndex.
	ShardTotal int `json:"shard_total"`
	ShardIndex int `json:"shard_index"`
	// Cluster replaces static sharding with automatic distribution: every agent with the same
	// config scrapes the targets that rendezvous-hash to it over the live peers (see cluster.go).
	Cluster *ClusterConfig `json:"cluster"`
}

PromConfig is the module config. TargetsFile and TextfileDir name local paths, so only the agent's own config file may set them, never remote config.

type Prometheus

type Prometheus struct {
	// Allow lists the host:port values a remote-origin config may scrape. Targets in the agent's
	// own config file are always allowed. Empty means remote config can add no targets.
	Allow  []string
	Client *http.Client
}

Prometheus scrapes targets and forwards them as OTLP samples.

func (Prometheus) Overlay

func (p Prometheus) Overlay(local, remote json.RawMessage) (json.RawMessage, error)

Overlay adds the targets of a remote-origin config to the local ones, after checking each against the allow list. Remote config cannot remove or change a local target.

func (Prometheus) Run

func (p Prometheus) Run(ctx context.Context, raw json.RawMessage, out Sink) error

Run scrapes every target on its interval until ctx ends. A failed scrape is reported through `up{job}`-style gauge `wt_scrape_up` (1 or 0), never as a crash.

func (Prometheus) Scrape

func (p Prometheus) Scrape(ctx context.Context, spec TargetSpec, out Sink, now time.Time) error

Scrape fetches one target and writes its samples to out. Counters become cumulative sums, gauges and untyped values gauges. A histogram becomes `<name>_bucket{le}`, `<name>_sum` and `<name>_count`; a summary `<name>{quantile}`, `<name>_sum` and `<name>_count` (the Prometheus naming, so existing queries port). The target may answer in OpenMetrics, whose exemplars become `wt.exemplar.*` attributes on the sample. A target over sample_limit fails the scrape and emits nothing.

func (Prometheus) Watch

func (p Prometheus) Watch(ctx context.Context, every time.Duration, list func(context.Context) ([]TargetSpec, error), out Sink)

Watch scrapes the targets list returns, re-polled every `every`: new targets start, gone ones stop with a staleness marker (k8s pod and Docker label autodiscovery feed it).

type RelabelRule

type RelabelRule struct {
	SourceLabels []string `json:"source_labels"`
	Separator    *string  `json:"separator"` // default ";"
	TargetLabel  string   `json:"target_label"`
	Regex        string   `json:"regex"` // default "(.*)"; anchored as ^(?:regex)$
	Modulus      uint64   `json:"modulus"`
	Replacement  *string  `json:"replacement"` // default "$1"
	Action       string   `json:"action"`      // default "replace"
}

RelabelRule is one Prometheus `relabel_config` entry.

type RemoteCheck

type RemoteCheck struct {
	Name     string            `json:"name"`
	Enabled  *bool             `json:"enabled"`
	Interval string            `json:"interval"`
	Timeout  string            `json:"timeout"`
	Labels   map[string]string `json:"labels"`
}

RemoteCheck is all that remote config may say about a check.

type RemoteConfig

type RemoteConfig struct {
	Checks []RemoteCheck `json:"checks"`
}

RemoteConfig is the nagios module config as the server may send it.

type Result

type Result struct {
	Status Status
	Text   string
	Perf   []Perf
}

Result is one finished check.

type SDConfig

type SDConfig struct {
	Type    string `json:"type"`
	Refresh string `json:"refresh_interval"` // default 1m, 5s to 1h
	// URL is the http_sd document or the consul HTTP API base (http://127.0.0.1:8500).
	URL string `json:"url"`
	// Scheme and Path shape the scrape URL for dns, consul and ec2 targets (http, /metrics).
	Scheme string `json:"scheme"`
	Path   string `json:"path"`
	// dns: Names to resolve, RecordType A, AAAA or SRV; Port is required for A and AAAA.
	Names      []string `json:"names"`
	RecordType string   `json:"record_type"`
	Port       int      `json:"port"`
	// consul: Services to scrape (empty: every service), Datacenter and ACL Token optional.
	Services   []string `json:"services"`
	Datacenter string   `json:"datacenter"`
	Token      string   `json:"token"`
	// ec2: Region, optional static keys (else the SDK default chain), Endpoint for tests, Filters
	// such as {"tag:env": "prod"}; Port is the exporter port (default 9100). Only running instances.
	Region          string            `json:"region"`
	AccessKeyID     string            `json:"access_key_id"`
	SecretAccessKey string            `json:"secret_access_key"`
	Endpoint        string            `json:"endpoint"`
	Filters         map[string]string `json:"filters"`
	// kubernetes: Role pod, service, endpoints, node or ingress; dockerswarm: nodes or tasks.
	// Namespaces (default all) and Selector (a label selector) also scope prometheus_operator,
	// whose Kinds are servicemonitor, podmonitor, probe and scrapeconfig (default all).
	Role       string   `json:"role"`
	Namespaces []string `json:"namespaces"`
	Selector   string   `json:"selector"`
	Kinds      []string `json:"kinds"`
	// file: Files in file_sd form. docker/dockerswarm: Host (unix:///var/run/docker.sock default).
	Files []string `json:"files"`
	Host  string   `json:"host"`
	// Query: puppetdb PQL, gce filter. Public: use the public instead of the private address.
	Query  string `json:"query"`
	Public bool   `json:"public"`
	// azure: SubscriptionID, optional ResourceGroup; TenantID/ClientID/ClientSecret, else managed identity.
	SubscriptionID string `json:"subscription_id"`
	ResourceGroup  string `json:"resource_group"`
	TenantID       string `json:"tenant_id"`
	ClientID       string `json:"client_id"`
	ClientSecret   string `json:"client_secret"`
	// gce: Project and Zone (token from the metadata server unless Token is set); openstack: URL
	// is the Keystone v3 endpoint, Username, Password, Project, DomainName (default "Default").
	Project    string `json:"project"`
	Zone       string `json:"zone"`
	Username   string `json:"username"`
	Password   string `json:"password"`
	DomainName string `json:"domain_name"`
	// serverset, nerve: ZooKeeper Servers and the Paths whose children are members. triton: Account,
	// DNSSuffix. ionos: DatacenterID. ovhcloud: ApplicationKey, ApplicationSecret, ConsumerKey.
	Servers           []string `json:"servers"`
	Paths             []string `json:"paths"`
	Account           string   `json:"account"`
	DNSSuffix         string   `json:"dns_suffix"`
	DatacenterID      string   `json:"datacenter_id"`
	ApplicationKey    string   `json:"application_key"`
	ApplicationSecret string   `json:"application_secret"`
	ConsumerKey       string   `json:"consumer_key"`
	// RelabelConfigs and MetricRelabelConfigs apply to every discovered target (a target's own,
	// e.g. a ServiceMonitor's relabelings, run first when it has them).
	RelabelConfigs       []RelabelRule `json:"relabel_configs"`
	MetricRelabelConfigs []RelabelRule `json:"metric_relabel_configs"`
}

SDConfig is one discovery source. Type is http, dns, consul, ec2, file, kubernetes, prometheus_operator, consulagent, docker, dockerswarm, nomad, eureka, kuma, marathon, puppetdb, azure, gce, digitalocean, hetzner, linode, openstack, or a type registered in promsd_*.go (kubelet, scaleway, lightsail, ionos, ovhcloud, triton, uyuni, serverset, nerve, process).

type Sink

type Sink interface {
	Gauge(name, unit string, value float64, attrs map[string]string, at time.Time)
	// Sum is a cumulative monotonic counter.
	Sum(name, unit string, value float64, attrs map[string]string, at time.Time)
}

Sink receives samples. The agent's OTLP exporter satisfies it.

type Status

type Status int

Status is a Nagios plugin state.

const (
	OK Status = iota
	Warning
	Critical
	Unknown
)

The four Nagios states, equal to the plugin exit codes 0 to 3.

func Exit

func Exit(code int) Status

Exit maps a plugin exit code to a status: 0 to 3 as is, anything else is UNKNOWN.

func (Status) String

func (s Status) String() string

type TargetSpec

type TargetSpec struct {
	URL      string            `json:"url"`
	Interval string            `json:"interval"` // older name of scrape_interval
	Labels   map[string]string `json:"labels"`
	// ScrapeInterval is 5s to 1h (default 60s); ScrapeTimeout 1s to 1h (default 10s).
	ScrapeInterval string `json:"scrape_interval"`
	ScrapeTimeout  string `json:"scrape_timeout"`
	// HonorLabels keeps a scraped label that clashes with a target label; otherwise the target
	// label wins and the scraped one is renamed `exported_<name>` (Prometheus behavior).
	HonorLabels bool `json:"honor_labels"`
	// SampleLimit fails the whole scrape when the target exposes more samples (default 50,000).
	SampleLimit int `json:"sample_limit"`
	// RelabelConfigs run on the target labels before the scrape (`__address__`, `__scheme__`,
	// `__metrics_path__` and the configured labels); MetricRelabelConfigs on every sample after
	// it (`__name__` is the metric name).
	RelabelConfigs       []RelabelRule `json:"relabel_configs"`
	MetricRelabelConfigs []RelabelRule `json:"metric_relabel_configs"`
}

TargetSpec is one text-exposition endpoint.

Jump to

Keyboard shortcuts

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