Documentation
¶
Overview ¶
Package custom holds the customer-extensible check modules of wt-agent: Nagios-style plugins and Prometheus text-exposition scrapes.
Index ¶
- func AsyncProfile(ctx context.Context, raw json.RawMessage, post PostProfile) error
- func Emit(out Sink, check, plugin string, labels map[string]string, r Result, ...)
- func EmitLocal(out Sink, script string, labels map[string]string, r LocalResult, at time.Time)
- func JoinCluster(ctx context.Context, c ClusterConfig, out Sink) (func(string) bool, error)
- func PluginName(p string) bool
- func PprofScrape(ctx context.Context, raw json.RawMessage, post PostProfile) error
- func ReadTextfiles(dir string, out Sink, now time.Time)
- func Relabel(labels map[string]string, rules []RelabelRule) (map[string]string, bool)
- func ValidateRelabel(rules []RelabelRule) error
- type AsyncProfilerConfig
- type CheckSpec
- type ClusterConfig
- type DogStatsD
- type DogStatsDConfig
- type EnrichConfig
- type EnrichRule
- type Enricher
- type LocalChecks
- type LocalConfig
- type LocalResult
- type Nagios
- type NagiosConfig
- type Perf
- type PostProfile
- type PprofConfig
- type PromConfig
- type Prometheus
- func (p Prometheus) Overlay(local, remote json.RawMessage) (json.RawMessage, error)
- func (p Prometheus) Run(ctx context.Context, raw json.RawMessage, out Sink) error
- func (p Prometheus) Scrape(ctx context.Context, spec TargetSpec, out Sink, now time.Time) error
- func (p Prometheus) Watch(ctx context.Context, every time.Duration, ...)
- type RelabelRule
- type RemoteCheck
- type RemoteConfig
- type Result
- type SDConfig
- type Sink
- type Status
- type TargetSpec
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 ¶
Emit turns a result into samples: `wt_check_status` (0 to 3) and one gauge per perfdata item.
func EmitLocal ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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, d: <name>.count (cumulative, scaled by the sample rate), .avg, .min, .max, .95percentile s set: <name> is the number of distinct values in the interval
Tags (`#k:v,flag`) become attributes. Events and service checks are ignored and counted in `wt_dogstatsd_ignored_total`; unparsable lines in `wt_dogstatsd_invalid_total`.
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
}
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.
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.
type NagiosConfig ¶
type NagiosConfig struct {
Checks []CheckSpec `json:"checks"`
}
NagiosConfig is the module config.
type Perf ¶
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 ¶
ParsePerfdata parses the Nagios performance data format. Unparseable items are skipped and reported in the error; the good ones are still returned.
type PostProfile ¶
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 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.
The four Nagios states, equal to the plugin exit codes 0 to 3.
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.