# vmalert `vmalert` executes a list of the given [alerting](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) or [recording](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/) rules against configured `-datasource.url` compatible with Prometheus HTTP API. For sending alerting notifications vmalert relies on [Alertmanager](https://github.com/prometheus/alertmanager) configured via `-notifier.url` flag. Recording rules results are persisted via [remote write](https://prometheus.io/docs/prometheus/latest/storage/#remote-storage-integrations) protocol and require `-remoteWrite.url` to be configured. Vmalert is heavily inspired by [Prometheus](https://prometheus.io/docs/alerting/latest/overview/) implementation and aims to be compatible with its syntax. A [single-node](https://docs.victoriametrics.com/Single-server-VictoriaMetrics.html#vmalert) or [cluster version](https://docs.victoriametrics.com/Cluster-VictoriaMetrics.html#vmalert) of VictoriaMetrics are capable of proxying requests to vmalert via `-vmalert.proxyURL` command-line flag. Use this feature for the following cases: * for proxying requests from [Grafana Alerting UI](https://grafana.com/docs/grafana/latest/alerting/); * for accessing vmalerts UI through VictoriaMetrics Web interface. ## Features * Integration with [VictoriaMetrics](https://github.com/VictoriaMetrics/VictoriaMetrics) TSDB; * VictoriaMetrics [MetricsQL](https://docs.victoriametrics.com/MetricsQL.html) support and expressions validation; * Prometheus [alerting rules definition format](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/#defining-alerting-rules) support; * Integration with [Alertmanager](https://github.com/prometheus/alertmanager) starting from [Alertmanager v0.16.0-alpha](https://github.com/prometheus/alertmanager/releases/tag/v0.16.0-alpha.0); * Keeps the alerts [state on restarts](#alerts-state-on-restarts); * Graphite datasource can be used for alerting and recording rules. See [these docs](#graphite); * Recording and Alerting rules backfilling (aka `replay`). See [these docs](#rules-backfilling); * Lightweight and without extra dependencies. * Supports [reusable templates](#reusable-templates) for annotations; * Load of recording and alerting rules from local filesystem, URL, GCS and S3; * Detect alerting rules which [don't match any series](https://github.com/VictoriaMetrics/VictoriaMetrics/issues/4039). ## Limitations * `vmalert` execute queries against remote datasource which has reliability risks because of the network. It is recommended to configure alerts thresholds and rules expressions with the understanding that network requests may fail; * by default, rules execution is sequential within one group, but persistence of execution results to remote storage is asynchronous. Hence, user shouldn't rely on chaining of recording rules when result of previous recording rule is reused in the next one; ## QuickStart To build `vmalert` from sources: ```console git clone https://github.com/VictoriaMetrics/VictoriaMetrics cd VictoriaMetrics make vmalert ``` The build binary will be placed in `VictoriaMetrics/bin` folder. To start using `vmalert` you will need the following things: * list of rules - PromQL/MetricsQL expressions to execute; * datasource address - reachable endpoint with [Prometheus HTTP API](https://prometheus.io/docs/prometheus/latest/querying/api/#http-api) support for running queries against; * notifier address [optional] - reachable [Alert Manager](https://github.com/prometheus/alertmanager) instance for processing, aggregating alerts, and sending notifications. Please note, notifier address also supports Consul and DNS Service Discovery via [config file](https://github.com/VictoriaMetrics/VictoriaMetrics/blob/master/app/vmalert/notifier/config.go). * remote write address [optional] - [remote write](https://prometheus.io/docs/prometheus/latest/storage/#remote-storage-integrations) compatible storage to persist rules and alerts state info. To persist results to multiple destinations use vmagent configured with multiple remote writes as a proxy; * remote read address [optional] - MetricsQL compatible datasource to restore alerts state from. Then configure `vmalert` accordingly: ```console ./bin/vmalert -rule=alert.rules \ # Path to the file with rules configuration. Supports wildcard -datasource.url=http://localhost:8428 \ # Prometheus HTTP API compatible datasource -notifier.url=http://localhost:9093 \ # AlertManager URL (required if alerting rules are used) -notifier.url=http://127.0.0.1:9093 \ # AlertManager replica URL -remoteWrite.url=http://localhost:8428 \ # Remote write compatible storage to persist rules and alerts state info (required if recording rules are used) -remoteRead.url=http://localhost:8428 \ # Prometheus HTTP API compatible datasource to restore alerts state from -external.label=cluster=east-1 \ # External label to be applied for each rule -external.label=replica=a # Multiple external labels may be set ``` Note there's a separate `-remoteWrite.url` command-line flag to allow writing results of alerting/recording rules into a different storage than the initial data that's queried. This allows using `vmalert` to aggregate data from a short-term, high-frequency, high-cardinality storage into a long-term storage with decreased cardinality and a bigger interval between samples. See also [stream aggregation](https://docs.victoriametrics.com/stream-aggregation.html). See the full list of configuration flags in [configuration](#configuration) section. If you run multiple `vmalert` services for the same datastore or AlertManager - do not forget to specify different `-external.label` command-line flags in order to define which `vmalert` generated rules or alerts. Configuration for [recording](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/) and [alerting](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) rules is very similar to Prometheus rules and configured using YAML. Configuration examples may be found in [testdata](https://github.com/VictoriaMetrics/VictoriaMetrics/blob/master/app/vmalert/config/testdata) folder. Every `rule` belongs to a `group` and every configuration file may contain arbitrary number of groups: ```yaml groups: [ - ] ``` ### Groups Each group has the following attributes: ```yaml # The name of the group. Must be unique within a file. name: # How often rules in the group are evaluated. [ interval: | default = -evaluationInterval flag ] # Limit the number of alerts an alerting rule and series a recording # rule can produce. 0 is no limit. [ limit: | default = 0 ] # How many rules execute at once within a group. Increasing concurrency may speed # up round execution speed. [ concurrency: | default = 1 ] # Optional type for expressions inside the rules. Supported values: "graphite" and "prometheus". # By default "prometheus" type is used. [ type: ] # Optional list of HTTP URL parameters # applied for all rules requests within a group # For example: # params: # nocache: ["1"] # disable caching for vmselect # denyPartialResponse: ["true"] # fail if one or more vmstorage nodes returned an error # extra_label: ["env=dev"] # apply additional label filter "env=dev" for all requests # see more details at https://docs.victoriametrics.com#prometheus-querying-api-enhancements params: [ : [, ...]] # Optional list of HTTP headers in form `header-name: value` # applied for all rules requests within a group # For example: # headers: # - "CustomHeader: foo" # - "CustomHeader2: bar" # Headers set via this param have priority over headers set via `-datasource.headers` flag. headers: [ , ...] # Optional list of HTTP headers in form `header-name: value` # applied for all alert notifications sent to notifiers # generated by rules of this group. # For example: # notifier_headers: # - "TenantID: foo" notifier_headers: [ , ...] # Optional list of labels added to every rule within a group. # It has priority over the external labels. # Labels are commonly used for adding environment # or tenant-specific tag. labels: [ : ... ] rules: [ - ... ] ``` ### Rules Every rule contains `expr` field for [PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/) or [MetricsQL](https://docs.victoriametrics.com/MetricsQL.html) expression. `vmalert` will execute the configured expression and then act according to the Rule type. There are two types of Rules: * [alerting](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/) - Alerting rules allow defining alert conditions via `expr` field and to send notifications to [Alertmanager](https://github.com/prometheus/alertmanager) if execution result is not empty. * [recording](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/) - Recording rules allow defining `expr` which result will be then backfilled to configured `-remoteWrite.url`. Recording rules are used to precompute frequently needed or computationally expensive expressions and save their result as a new set of time series. `vmalert` forbids defining duplicates - rules with the same combination of name, expression, and labels within one group. #### Alerting rules The syntax for alerting rule is the following: ```yaml # The name of the alert. Must be a valid metric name. alert: # The expression to evaluate. The expression language depends on the type value. # By default, PromQL/MetricsQL expression is used. If group.type="graphite", then the expression # must contain valid Graphite expression. expr: # Alerts are considered firing once they have been returned for this long. # Alerts which have not yet been fired for long enough are considered pending. # If param is omitted or set to 0 then alerts will be immediately considered # as firing once they return. [ for: | default = 0s ] # Whether to print debug information into logs. # Information includes alerts state changes and requests sent to the datasource. # Please note, that if rule's query params contain sensitive # information - it will be printed to logs. # Is applicable to alerting rules only. # Available starting from https://docs.victoriametrics.com/CHANGELOG.html#v1820 [ debug: | default = false ] # Defines the number of rule's updates entries stored in memory # and available for view on rule's Details page. # Overrides `rule.updateEntriesLimit` value for this specific rule. # Available starting from https://docs.victoriametrics.com/CHANGELOG.html#v1860 [ update_entries_limit: | default 0 ] # Labels to add or overwrite for each alert. labels: [ : ] # Annotations to add to each alert. annotations: [ : ] ``` #### Templating It is allowed to use [Go templating](https://golang.org/pkg/text/template/) in annotations to format data, iterate over or execute expressions. The following variables are available in templating: | Variable | Description | Example | |------------------------------------|-----------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | $value or .Value | The current alert's value. Avoid using value in labels, it may cause unexpected issues. | {% raw %}Number of connections is {{ $value }}{% endraw %} | | $activeAt or .ActiveAt | The moment of [time](https://pkg.go.dev/time) when alert became active (`pending` or `firing`). | {% raw %}http://vm-grafana.com/panelId=xx?from={{($activeAt.Add (parseDurationTime \"1h\")).Unix}}&to={{($activeAt.Add (parseDurationTime \"-1h\")).Unix}}{% endraw %} | | $labels or .Labels | The list of labels of the current alert. Use as ".Labels.". | {% raw %}Too high number of connections for {{ .Labels.instance }}{% endraw %} | | $alertID or .AlertID | The current alert's ID generated by vmalert. | {% raw %}Link: vmalert/alert?group_id={{.GroupID}}&alert_id={{.AlertID}}{% endraw %} | | $groupID or .GroupID | The current alert's group ID generated by vmalert. | {% raw %}Link: vmalert/alert?group_id={{.GroupID}}&alert_id={{.AlertID}}{% endraw %} | | $expr or .Expr | Alert's expression. Can be used for generating links to Grafana or other systems. | {% raw %}/api/v1/query?query={{ $expr|queryEscape }}{% endraw %} | | $for or .For | Alert's configured for param. | {% raw %}Number of connections is too high for more than {{ .For }}{% endraw %} | | $externalLabels or .ExternalLabels | List of labels configured via `-external.label` command-line flag. | {% raw %}Issues with {{ $labels.instance }} (datacenter-{{ $externalLabels.dc }}){% endraw %} | | $externalURL or .ExternalURL | URL configured via `-external.url` command-line flag. Used for cases when vmalert is hidden behind proxy. | {% raw %}Visit {{ $externalURL }} for more details{% endraw %} | Additionally, `vmalert` provides some extra templating functions listed [here](#template-functions) and [reusable templates](#reusable-templates). #### Template functions `vmalert` provides the following template functions, which can be used during [templating](#templating): - `args arg0 ... argN` - converts the input args into a map with `arg0`, ..., `argN` keys. - `externalURL` - returns the value of `-external.url` command-line flag. - `first` - returns the first result from the input query results returned by `query` function. - `htmlEscape` - escapes special chars in input string, so it can be safely embedded as a plaintext into HTML. - `humanize` - converts the input number into human-readable format by adding [metric prefixes](https://en.wikipedia.org/wiki/Metric_prefix). For example, `100000` is converted into `100K`. - `humanize1024` - converts the input number into human-readable format with 1024 base. For example, `1024` is converted into 1ki`. - `humanizeDuration` - converts the input number in seconds into human-readable duration. - `humanizePercentage` - converts the input number to percentage. For example, `0.123` is converted into `12.3%`. - `humanizeTimestamp` - converts the input unix timestamp into human-readable time. - `jsonEscape` - JSON-encodes the input string. - `label name` - returns the value of the label with the given `name` from the input query result. - `match regex` - matches the input string against the provided `regex`. - `parseDuration` - parses the input string into duration in seconds. For example, `1h` is parsed into `3600`. - `parseDurationTime` - parses the input string into [time.Duration](https://pkg.go.dev/time#Duration). - `pathEscape` - escapes the input string, so it can be safely put inside path part of URL. - `pathPrefix` - returns the path part of the `-external.url` command-line flag. - `query` - executes the [MetricsQL](https://docs.victoriametrics.com/MetricsQL.html) query against `-datasource.url` and returns the query result. For example, {% raw %}`{{ query "sort_desc(process_resident_memory_bytes)" | first | value }}`{% endraw %} executes the `sort_desc(process_resident_memory_bytes)` query at `-datasource.url` and returns the first result. - `queryEscape` - escapes the input string, so it can be safely put inside [query arg](https://en.wikipedia.org/wiki/Percent-encoding) part of URL. - `quotesEscape` - escapes the input string, so it can be safely embedded into JSON string. - `reReplaceAll regex repl` - replaces all the occurrences of the `regex` in input string with the `repl`. - `safeHtml` - marks the input string as safe to use in HTML context without the need to html-escape it. - `sortByLabel name` - sorts the input query results by the label with the given `name`. - `stripDomain` - leaves the first part of the domain. For example, `foo.bar.baz` is converted to `foo`. The port part is left in the output string. E.g. `foo.bar:1234` is converted into `foo:1234`. - `stripPort` - strips `port` part from `host:port` input string. - `strvalue` - returns the metric name from the input query result. - `title` - converts the first letters of every input word to uppercase. - `toLower` - converts all the chars in the input string to lowercase. - `toTime` - converts the input unix timestamp to [time.Time](https://pkg.go.dev/time#Time). - `toUpper` - converts all the chars in the input string to uppercase. - `value` - returns the numeric value from the input query result. #### Reusable templates Like in Alertmanager you can define [reusable templates](https://prometheus.io/docs/prometheus/latest/configuration/template_examples/#defining-reusable-templates) to share same templates across annotations. Just define the templates in a file and set the path via `-rule.templates` flag. For example, template `grafana.filter` can be defined as following: {% raw %} ``` {{ define "grafana.filter" -}} {{- $labels := .arg0 -}} {{- range $name, $label := . -}} {{- if (ne $name "arg0") -}} {{- ( or (index $labels $label) "All" ) | printf "&var-%s=%s" $label -}} {{- end -}} {{- end -}} {{- end -}} ``` {% endraw %} And then used in annotations: {% raw %} ```yaml groups: - name: AlertGroupName rules: - alert: AlertName expr: any_metric > 100 for: 30s labels: alertname: 'Any metric is too high' severity: 'warning' annotations: dashboard: '{{ $externalURL }}/d/dashboard?orgId=1{{ template "grafana.filter" (args .CommonLabels "account_id" "any_label") }}' ``` {% endraw %} The `-rule.templates` flag supports wildcards so multiple files with templates can be loaded. The content of `-rule.templates` can be also [hot reloaded](#hot-config-reload). #### Recording rules The syntax for recording rules is following: ```yaml # The name of the time series to output to. Must be a valid metric name. record: # The expression to evaluate. The expression language depends on the type value. # By default, MetricsQL expression is used. If group.type="graphite", then the expression # must contain valid Graphite expression. expr: # Labels to add or overwrite before storing the result. labels: [ : ] # Defines the number of rule's updates entries stored in memory # and available for view on rule's Details page. # Overrides `rule.updateEntriesLimit` value for this specific rule. [ update_entries_limit: | default 0 ] ``` For recording rules to work `-remoteWrite.url` must be specified. ### Alerts state on restarts `vmalert` is stateless, it holds alerts state in the process memory. Restarting of `vmalert` process will reset alerts state in memory. To prevent `vmalert` from losing alerts state it should be configured to persist the state to the remote destination via the following flags: * `-remoteWrite.url` - URL to VictoriaMetrics (Single) or vminsert (Cluster). `vmalert` will persist alerts state to the configured address in the form of [time series](https://docs.victoriametrics.com/keyConcepts.html#time-series) `ALERTS` and `ALERTS_FOR_STATE` via remote-write protocol. These time series can be queried from VictoriaMetrics just as any other time series. The state will be persisted to the configured address on each evaluation. * `-remoteRead.url` - URL to VictoriaMetrics (Single) or vmselect (Cluster). `vmalert` will try to restore alerts state from the configured address by querying time series with name `ALERTS_FOR_STATE`. The restore happens only once when `vmalert` process starts, and only for the configured rules. Config [hot reload](#hot-config-reload) doesn't trigger state restore. Both flags are required for proper state restoration. Restore process may fail if time series are missing in configured `-remoteRead.url`, weren't updated in the last `1h` (controlled by `-remoteRead.lookback`) or received state doesn't match current `vmalert` rules configuration. `vmalert` marks successfully restored rules with `restored` label in [web UI](#WEB). ### Multitenancy There are the following approaches exist for alerting and recording rules across [multiple tenants](https://docs.victoriametrics.com/Cluster-VictoriaMetrics.html#multitenancy): * To run a separate `vmalert` instance per each tenant. The corresponding tenant must be specified in `-datasource.url` command-line flag according to [these docs](https://docs.victoriametrics.com/Cluster-VictoriaMetrics.html#url-format). For example, `/path/to/vmalert -datasource.url=http://vmselect:8481/select/123/prometheus` would run alerts against `AccountID=123`. For recording rules the `-remoteWrite.url` command-line flag must contain the url for the specific tenant as well. For example, `-remoteWrite.url=http://vminsert:8480/insert/123/prometheus` would write recording rules to `AccountID=123`. * To specify `tenant` parameter per each alerting and recording group if [enterprise version of vmalert](https://docs.victoriametrics.com/enterprise.html) is used with `-clusterMode` command-line flag. For example: ```yaml groups: - name: rules_for_tenant_123 tenant: "123" rules: # Rules for accountID=123 - name: rules_for_tenant_456:789 tenant: "456:789" rules: # Rules for accountID=456, projectID=789 ``` The results of alerting and recording rules contain `vm_account_id` and `vm_project_id` labels if `-clusterMode` is enabled. These labels can be used during [templating](https://docs.victoriametrics.com/vmalert.html#templating), and help to identify to which account or project the triggered alert or produced recording belongs. If `-clusterMode` is enabled, then `-datasource.url`, `-remoteRead.url` and `-remoteWrite.url` must contain only the hostname without tenant id. For example: `-datasource.url=http://vmselect:8481`. `vmalert` automatically adds the specified tenant to urls per each recording rule in this case. If `-clusterMode` is enabled and the `tenant` in a particular group is missing, then the tenant value is obtained from `-defaultTenant.prometheus` or `-defaultTenant.graphite` depending on the `type` of the group. The enterprise version of vmalert is available in `vmutils-*-enterprise.tar.gz` files at [release page](https://github.com/VictoriaMetrics/VictoriaMetrics/releases) and in `*-enterprise` tags at [Docker Hub](https://hub.docker.com/r/victoriametrics/vmalert/tags). ### Reading rules from object storage [Enterprise version](https://docs.victoriametrics.com/enterprise.html) of `vmalert` may read alerting and recording rules from object storage: - `./bin/vmalert -rule=s3://bucket/dir/alert.rules` would read rules from the given path at S3 bucket - `./bin/vmalert -rule=gs://bucket/bir/alert.rules` would read rules from the given path at GCS bucket S3 and GCS paths support only matching by prefix, e.g. `s3://bucket/dir/rule_` matches all files with prefix `rule_` in the folder `dir`. The following [command-line flags](#flags) can be used for fine-tuning access to S3 and GCS: - `-s3.credsFilePath` - path to file with GCS or S3 credentials. Credentials are loaded from default locations if not set. - `-s3.configFilePath` - path to file with S3 configs. Configs are loaded from default location if not set. - `-s3.configProfile` - profile name for S3 configs. If no set, the value of the environment variable will be loaded (`AWS_PROFILE` or `AWS_DEFAULT_PROFILE`). - `-s3.customEndpoint` - custom S3 endpoint for use with S3-compatible storages (e.g. MinIO). S3 is used if not set. - `-s3.forcePathStyle` - prefixing endpoint with bucket name when set false, true by default. ### Topology examples The following sections are showing how `vmalert` may be used and configured for different scenarios. Please note, not all flags in examples are required: * `-remoteWrite.url` and `-remoteRead.url` are optional and are needed only if you have recording rules or want to store [alerts state](#alerts-state-on-restarts) on `vmalert` restarts; * `-notifier.url` is optional and is needed only if you have alerting rules. #### Single-node VictoriaMetrics The simplest configuration where one single-node VM server is used for rules execution, storing recording rules results and alerts state. `vmalert` configuration flags: ``` ./bin/vmalert -rule=rules.yml \ # Path to the file with rules configuration. Supports wildcard -datasource.url=http://victoriametrics:8428 \ # VM-single addr for executing rules expressions -remoteWrite.url=http://victoriametrics:8428 \ # VM-single addr to persist alerts state and recording rules results -remoteRead.url=http://victoriametrics:8428 \ # VM-single addr for restoring alerts state after restart -notifier.url=http://alertmanager:9093 # AlertManager addr to send alerts when they trigger ``` vmalert single #### Cluster VictoriaMetrics In [cluster mode](https://docs.victoriametrics.com/Cluster-VictoriaMetrics.html) VictoriaMetrics has separate components for writing and reading path: `vminsert` and `vmselect` components respectively. `vmselect` is used for executing rules expressions and `vminsert` is used to persist recording rules results and alerts state. Cluster mode could have multiple `vminsert` and `vmselect` components. `vmalert` configuration flags: ``` ./bin/vmalert -rule=rules.yml \ # Path to the file with rules configuration. Supports wildcard -datasource.url=http://vmselect:8481/select/0/prometheus # vmselect addr for executing rules expressions -remoteWrite.url=http://vminsert:8480/insert/0/prometheus # vminsert addr to persist alerts state and recording rules results -remoteRead.url=http://vmselect:8481/select/0/prometheus # vmselect addr for restoring alerts state after restart -notifier.url=http://alertmanager:9093 # AlertManager addr to send alerts when they trigger ``` vmalert cluster In case when you want to spread the load on these components - add balancers before them and configure `vmalert` with balancer addresses. Please, see more about VM's cluster architecture [here](https://docs.victoriametrics.com/Cluster-VictoriaMetrics.html#architecture-overview). #### HA vmalert For HA user can run multiple identically configured `vmalert` instances. It means all of them will execute the same rules, write state and results to the same destinations, and send alert notifications to multiple configured Alertmanagers. `vmalert` configuration flags: ``` ./bin/vmalert -rule=rules.yml \ # Path to the file with rules configuration. Supports wildcard -datasource.url=http://victoriametrics:8428 \ # VM-single addr for executing rules expressions -remoteWrite.url=http://victoriametrics:8428 \ # VM-single addr to persist alerts state and recording rules results -remoteRead.url=http://victoriametrics:8428 \ # VM-single addr for restoring alerts state after restart -notifier.url=http://alertmanager1:9093 \ # Multiple AlertManager addresses to send alerts when they trigger -notifier.url=http://alertmanagerN:9093 # The same alert will be sent to all configured notifiers ``` vmalert ha To avoid recording rules results and alerts state duplication in VictoriaMetrics server don't forget to configure [deduplication](https://docs.victoriametrics.com/Single-server-VictoriaMetrics.html#deduplication). The recommended value for `-dedup.minScrapeInterval` must be greater or equal to vmalert `evaluation_interval`. If you observe inconsistent or "jumping" values in series produced by vmalert, try disabling `-datasource.queryTimeAlignment` command line flag. Because of alignment, two or more vmalert HA pairs will produce results with the same timestamps. But due of backfilling (data delivered to the datasource with some delay) values of such results may differ, which would affect deduplication logic and result into "jumping" datapoints. Alertmanager will automatically deduplicate alerts with identical labels, so ensure that all `vmalert`s are having the same config. Don't forget to configure [cluster mode](https://prometheus.io/docs/alerting/latest/alertmanager/) for Alertmanagers for better reliability. List all Alertmanager URLs in vmalert `-notifier.url` to ensure [high availability](https://github.com/prometheus/alertmanager#high-availability). This example uses single-node VM server for the sake of simplicity. Check how to replace it with [cluster VictoriaMetrics](#cluster-victoriametrics) if needed. #### Downsampling and aggregation via vmalert _Please note, [stream aggregation](https://docs.victoriametrics.com/stream-aggregation.html) might be more efficient for cases when downsampling or aggregation need to be applied **before data gets into the TSDB.**_ `vmalert` can't modify existing data. But it can run arbitrary PromQL/MetricsQL queries via [recording rules](#recording-rules) and backfill results to the configured `-remoteWrite.url`. This ability allows to aggregate data. For example, the following rule will calculate the average value for metric `http_requests` on the `5m` interval: ```yaml - record: http_requests:avg5m expr: avg_over_time(http_requests[5m]) ``` Every time this rule will be evaluated, `vmalert` will backfill its results as a new time series `http_requests:avg5m` to the configured `-remoteWrite.url`. `vmalert` executes rules with specified interval (configured via flag `-evaluationInterval` or as [group's](#groups) `interval` param). The interval helps to control "resolution" of the produced series. This ability allows to downsample data. For example, the following config will execute the rule only once every `5m`: ```yaml groups: - name: my_group interval: 5m rules: - record: http_requests:avg5m expr: avg_over_time(http_requests[5m]) ``` Ability of `vmalert` to be configured with different `-datasource.url` and `-remoteWrite.url` command-line flags allows reading data from one data source and backfilling results to another. This helps to build a system for aggregating and downsampling the data. The following example shows how to build a topology where `vmalert` will process data from one cluster and write results into another. Such clusters may be called as "hot" (low retention, high-speed disks, used for operative monitoring) and "cold" (long term retention, slower/cheaper disks, low resolution data). With help of `vmalert`, user can setup recording rules to process raw data from "hot" cluster (by applying additional transformations or reducing resolution) and push results to "cold" cluster. `vmalert` configuration flags: ``` ./bin/vmalert -rule=downsampling-rules.yml \ # Path to the file with rules configuration. Supports wildcard -datasource.url=http://raw-cluster-vmselect:8481/select/0/prometheus # vmselect addr for executing recording rules expressions -remoteWrite.url=http://aggregated-cluster-vminsert:8480/insert/0/prometheus # vminsert addr to persist recording rules results ``` vmalert multi cluster Please note, [replay](#rules-backfilling) feature may be used for transforming historical data. Flags `-remoteRead.url` and `-notifier.url` are omitted since we assume only recording rules are used. See also [stream aggregation](https://docs.victoriametrics.com/stream-aggregation.html) and [downsampling](https://docs.victoriametrics.com/#downsampling). #### Multiple remote writes For persisting recording or alerting rule results `vmalert` requires `-remoteWrite.url` to be set. But this flag supports only one destination. To persist rule results to multiple destinations we recommend using [vmagent](https://docs.victoriametrics.com/vmagent.html) as fan-out proxy: vmalert multiple remote write destinations In this topology, `vmalert` is configured to persist rule results to `vmagent`. And `vmagent` is configured to fan-out received data to two or more destinations. Using `vmagent` as a proxy provides additional benefits such as [data persisting when storage is unreachable](https://docs.victoriametrics.com/vmagent.html#replication-and-high-availability), or time series modification via [relabeling](https://docs.victoriametrics.com/vmagent.html#relabeling). ### Web `vmalert` runs a web-server (`-httpListenAddr`) for serving metrics and alerts endpoints: * `http://` - UI; * `http:///api/v1/rules` - list of all loaded groups and rules; * `http:///api/v1/alerts` - list of all active alerts; * `http:///vmalert/api/v1/alert?group_id=&alert_id=` - get alert status in JSON format. Used as alert source in AlertManager. * `http:///vmalert/alert?group_id=&alert_id=` - get alert status in web UI. * `http:///vmalert/rule?group_id=&rule_id=` - get rule status in web UI. * `http:///metrics` - application metrics. * `http:///-/reload` - hot configuration reload. `vmalert` web UI can be accessed from [single-node version of VictoriaMetrics](https://docs.victoriametrics.com/Single-server-VictoriaMetrics.html) and from [cluster version of VictoriaMetrics](https://docs.victoriametrics.com/Cluster-VictoriaMetrics.html). This may be used for better integration with Grafana unified alerting system. See the following docs for details: * [How to query vmalert from single-node VictoriaMetrics](https://docs.victoriametrics.com/Single-server-VictoriaMetrics.html#vmalert) * [How to query vmalert from VictoriaMetrics cluster](https://docs.victoriametrics.com/Cluster-VictoriaMetrics.html#vmalert) ## Graphite vmalert sends requests to `<-datasource.url>/render?format=json` during evaluation of alerting and recording rules if the corresponding group or rule contains `type: "graphite"` config option. It is expected that the `<-datasource.url>/render` implements [Graphite Render API](https://graphite.readthedocs.io/en/stable/render_api.html) for `format=json`. When using vmalert with both `graphite` and `prometheus` rules configured against cluster version of VM do not forget to set `-datasource.appendTypePrefix` flag to `true`, so vmalert can adjust URL prefix automatically based on the query type. ## Rules backfilling vmalert supports alerting and recording rules backfilling (aka `replay`). In replay mode vmalert can read the same rules configuration as normal, evaluate them on the given time range and backfill results via remote write to the configured storage. vmalert supports any PromQL/MetricsQL compatible data source for backfilling. Please note, that response caching may lead to unexpected results during and after backfilling process. In order to avoid this you need to reset cache contents or disable caching when using backfilling as described in [backfilling docs](https://docs.victoriametrics.com/Single-server-VictoriaMetrics.html#backfilling). See a blogpost about [Rules backfilling via vmalert](https://victoriametrics.com/blog/rules-replay/). ### How it works In `replay` mode vmalert works as a cli-tool and exits immediately after work is done. To run vmalert in `replay` mode: ``` ./bin/vmalert -rule=path/to/your.rules \ # path to files with rules you usually use with vmalert -datasource.url=http://localhost:8428 \ # Prometheus HTTP API compatible datasource -remoteWrite.url=http://localhost:8428 \ # remote write compatible storage to persist results -replay.timeFrom=2021-05-11T07:21:43Z \ # time from begin replay -replay.timeTo=2021-05-29T18:40:43Z # time to finish replay ``` The output of the command will look like the following: ``` Replay mode: from: 2021-05-11 07:21:43 +0000 UTC # set by -replay.timeFrom to: 2021-05-29 18:40:43 +0000 UTC # set by -replay.timeTo max data points per request: 1000 # set by -replay.maxDatapointsPerQuery Group "ReplayGroup" interval: 1m0s requests to make: 27 max range per request: 16h40m0s > Rule "type:vm_cache_entries:rate5m" (ID: 1792509946081842725) 27 / 27 [----------------------------------------------------------------------------------------------------] 100.00% 78 p/s > Rule "go_cgo_calls_count:rate5m" (ID: 17958425467471411582) 27 / 27 [-----------------------------------------------------------------------------------------------------] 100.00% ? p/s Group "vmsingleReplay" interval: 30s requests to make: 54 max range per request: 8h20m0s > Rule "RequestErrorsToAPI" (ID: 17645863024999990222) 54 / 54 [-----------------------------------------------------------------------------------------------------] 100.00% ? p/s > Rule "TooManyLogs" (ID: 9042195394653477652) 54 / 54 [-----------------------------------------------------------------------------------------------------] 100.00% ? p/s 2021-06-07T09:59:12.098Z info app/vmalert/replay.go:68 replay finished! Imported 511734 samples ``` In `replay` mode all groups are executed sequentially one-by-one. Rules within the group are executed sequentially as well (`concurrency` setting is ignored). Vmalert sends rule's expression to [/query_range](https://docs.victoriametrics.com/keyConcepts.html#range-query) endpoint of the configured `-datasource.url`. Returned data is then processed according to the rule type and backfilled to `-remoteWrite.url` via [remote Write protocol](https://prometheus.io/docs/prometheus/latest/storage/#remote-storage-integrations). Vmalert respects `evaluationInterval` value set by flag or per-group during the replay. Vmalert automatically disables caching on VictoriaMetrics side by sending `nocache=1` param. It allows to prevent cache pollution and unwanted time range boundaries adjustment during backfilling. #### Recording rules The result of recording rules `replay` should match with results of normal rules evaluation. #### Alerting rules The result of alerting rules `replay` is time series reflecting [alert's state](#alerts-state-on-restarts). To see if `replayed` alert has fired in the past use the following PromQL/MetricsQL expression: ``` ALERTS{alertname="your_alertname", alertstate="firing"} ``` Execute the query against storage which was used for `-remoteWrite.url` during the `replay`. ### Additional configuration There are following non-required `replay` flags: * `-replay.maxDatapointsPerQuery` - the max number of data points expected to receive in one request. In two words, it affects the max time range for every `/query_range` request. The higher the value, the fewer requests will be issued during `replay`. * `-replay.ruleRetryAttempts` - when datasource fails to respond vmalert will make this number of retries per rule before giving up. * `-replay.rulesDelay` - delay between sequential rules execution. Important in cases if there are chaining (rules which depend on each other) rules. It is expected, that remote storage will be able to persist previously accepted data during the delay, so data will be available for the subsequent queries. Keep it equal or bigger than `-remoteWrite.flushInterval`. * `-replay.disableProgressBar` - whether to disable progress bar which shows progress work. Progress bar may generate a lot of log records, which is not formatted as standard VictoriaMetrics logger. It could break logs parsing by external system and generate additional load on it. See full description for these flags in `./vmalert -help`. ### Limitations * Graphite engine isn't supported yet; * `query` template function is disabled for performance reasons (might be changed in future); * `limit` group's param has no effect during replay (might be changed in future); ## Unit Testing for Rules > Unit testing is available from v1.92.0. > Unit tests do not respect `-clusterMode` for now. You can use `vmalert` to run unit tests for alerting and recording rules. In unit test mode vmalert performs the following actions: * sets up an isolated VictoriaMetrics instance; * simulates the periodic ingestion of time series; * queries the ingested data for recording and alerting rules evaluation; * tests whether the firing alerts or resulting recording rules match the expected results. See how to run vmalert in unit test mode below: ``` # Run vmalert with one or multiple test files via -unittestFile cmd-line flag ./vmalert -unittestFile=test1.yaml -unittestFile=test2.yaml ``` vmalert is compatible with [Prometheus config format for tests](https://prometheus.io/docs/prometheus/latest/configuration/unit_testing_rules/#test-file-format) except `promql_expr_test` field. Use `metricsql_expr_test` field name instead. The name is different because vmalert validates and executes [MetricsQL](https://docs.victoriametrics.com/MetricsQL.html) expressions, which aren't always backward compatible with [PromQL](https://prometheus.io/docs/prometheus/latest/querying/basics/). ### Test file format The configuration format for files specified in `-unittestFile` cmd-line flag is the following: ``` # Path to the files or http url containing [rule groups](https://docs.victoriametrics.com/vmalert.html#groups) configuration. # Enterprise version of vmalert supports S3 and GCS paths to rules. rule_files: [ - ] # The evaluation interval for rules specified in `rule_files` [ evaluation_interval: | default = 1m ] # Groups listed below will be evaluated by order. # Not All the groups need not be mentioned, if not, they will be evaluated by define order in rule_files. group_eval_order: [ - ] # The list of unit test files to be checked during evaluation. tests: [ - ] ``` #### `` ``` # Interval between samples for input series interval: # Time series to persist into the database according to configured before running tests. input_series: [ - ] # Name of the test group, optional [ name: ] # Unit tests for alerting rules alert_rule_test: [ - ] # Unit tests for Metricsql expressions. metricsql_expr_test: [ - ] # External labels accessible for templating. external_labels: [ : ... ] ``` #### `` ``` # series in the following format '{