1 { config, pkgs, lib, ... }:
6 yaml = pkgs.formats.yaml { };
7 cfg = config.services.prometheus;
9 (lib.isBool cfg.checkConfig && cfg.checkConfig)
10 || cfg.checkConfig == "syntax-only";
12 workingDir = "/var/lib/" + cfg.stateDir;
14 triggerReload = pkgs.writeShellScriptBin "trigger-reload-prometheus" ''
15 PATH="${makeBinPath (with pkgs; [ systemd ])}"
16 if systemctl -q is-active prometheus.service; then
17 systemctl reload prometheus.service
21 reload = pkgs.writeShellScriptBin "reload-prometheus" ''
22 PATH="${makeBinPath (with pkgs; [ systemd coreutils gnugrep ])}"
23 cursor=$(journalctl --show-cursor -n0 | grep -oP "cursor: \K.*")
25 journalctl -u prometheus.service --after-cursor="$cursor" -f \
26 | grep -m 1 "Completed loading of configuration file" > /dev/null
29 # a wrapper that verifies that the configuration is valid
30 promtoolCheck = what: name: file:
31 if checkConfigEnabled then
33 "${name}-${replaceStrings [" "] [""] what}-checked"
34 { nativeBuildInputs = [ cfg.package.cli ]; } ''
39 generatedPrometheusYml = yaml.generate "prometheus.yml" promConfig;
41 # This becomes the main config file for Prometheus
43 global = filterValidPrometheus cfg.globalConfig;
44 scrape_configs = filterValidPrometheus cfg.scrapeConfigs;
45 remote_write = filterValidPrometheus cfg.remoteWrite;
46 remote_read = filterValidPrometheus cfg.remoteRead;
47 rule_files = optionals (!(cfg.enableAgentMode)) (map (promtoolCheck "check rules" "rules") (cfg.ruleFiles ++ [
48 (pkgs.writeText "prometheus.rules" (concatStringsSep "\n" cfg.rules))
51 inherit (cfg) alertmanagers;
58 if cfg.configText != null then
59 pkgs.writeText "prometheus.yml" cfg.configText
60 else generatedPrometheusYml;
62 promtoolCheck "check config ${lib.optionalString (cfg.checkConfig == "syntax-only") "--syntax-only"}" "prometheus.yml" yml;
64 cmdlineArgs = cfg.extraFlags ++ [
67 then "/etc/prometheus/prometheus.yaml"
70 "--web.listen-address=${cfg.listenAddress}:${builtins.toString cfg.port}"
72 if (cfg.enableAgentMode) then [
73 "--enable-feature=agent"
75 "--alertmanager.notification-queue-capacity=${toString cfg.alertmanagerNotificationQueueCapacity }"
76 "--storage.tsdb.path=${workingDir}/data/"
78 ++ optional (cfg.webExternalUrl != null) "--web.external-url=${cfg.webExternalUrl}"
79 ++ optional (cfg.retentionTime != null) "--storage.tsdb.retention.time=${cfg.retentionTime}"
80 ++ optional (cfg.webConfigFile != null) "--web.config.file=${cfg.webConfigFile}";
82 filterValidPrometheus = filterAttrsListRecursive (n: v: !(n == "_module" || v == null));
83 filterAttrsListRecursive = pred: x:
91 (nameValuePair name (filterAttrsListRecursive pred v))
97 map (filterAttrsListRecursive pred) x
101 # Config types: helper functions
104 mkDefOpt = type: defaultStr: description: mkOpt type (description + ''
106 Defaults to ````${defaultStr}```` in prometheus
110 mkOpt = type: description: mkOption {
111 type = types.nullOr type;
113 description = description;
116 mkSdConfigModule = extraOptions: types.submodule {
118 basic_auth = mkOpt promTypes.basic_auth ''
119 Optional HTTP basic authentication information.
122 authorization = mkOpt
125 type = mkDefOpt types.str "Bearer" ''
126 Sets the authentication type.
129 credentials = mkOpt types.str ''
130 Sets the credentials. It is mutually exclusive with `credentials_file`.
133 credentials_file = mkOpt types.str ''
134 Sets the credentials to the credentials read from the configured file.
135 It is mutually exclusive with `credentials`.
139 Optional `Authorization` header configuration.
142 oauth2 = mkOpt promtypes.oauth2 ''
143 Optional OAuth 2.0 configuration.
144 Cannot be used at the same time as basic_auth or authorization.
147 proxy_url = mkOpt types.str ''
151 follow_redirects = mkDefOpt types.bool "true" ''
152 Configure whether HTTP requests follow HTTP 3xx redirects.
155 tls_config = mkOpt promTypes.tls_config ''
162 # Config types: general
165 promTypes.globalConfig = types.submodule {
167 scrape_interval = mkDefOpt types.str "1m" ''
168 How frequently to scrape targets by default.
171 scrape_timeout = mkDefOpt types.str "10s" ''
172 How long until a scrape request times out.
175 evaluation_interval = mkDefOpt types.str "1m" ''
176 How frequently to evaluate rules by default.
179 external_labels = mkOpt (types.attrsOf types.str) ''
180 The labels to add to any time series or alerts when
181 communicating with external systems (federation, remote
182 storage, Alertmanager).
185 query_log_file = mkOpt types.str ''
186 Path to the file prometheus should write its query log to.
191 promTypes.basic_auth = types.submodule {
193 username = mkOption {
199 password = mkOpt types.str "HTTP password";
200 password_file = mkOpt types.str "HTTP password file";
204 promTypes.tls_config = types.submodule {
206 ca_file = mkOpt types.str ''
207 CA certificate to validate API server certificate with.
210 cert_file = mkOpt types.str ''
211 Certificate file for client cert authentication to the server.
214 key_file = mkOpt types.str ''
215 Key file for client cert authentication to the server.
218 server_name = mkOpt types.str ''
219 ServerName extension to indicate the name of the server.
220 http://tools.ietf.org/html/rfc4366#section-3.1
223 insecure_skip_verify = mkOpt types.bool ''
224 Disable validation of the server certificate.
229 promtypes.oauth2 = types.submodule {
231 client_id = mkOpt types.str ''
235 client_secret = mkOpt types.str ''
239 client_secret_file = mkOpt types.str ''
240 Read the client secret from a file. It is mutually exclusive with `client_secret`.
243 scopes = mkOpt (types.listOf types.str) ''
244 Scopes for the token request.
247 token_url = mkOpt types.str ''
248 The URL to fetch the token from.
251 endpoint_params = mkOpt (types.attrsOf types.str) ''
252 Optional parameters to append to the token URL.
257 promTypes.scrape_config = types.submodule {
259 authorization = mkOption {
260 type = types.nullOr types.attrs;
263 Sets the `Authorization` header on every scrape request with the configured credentials.
266 job_name = mkOption {
269 The job name assigned to scraped metrics by default.
272 scrape_interval = mkOpt types.str ''
273 How frequently to scrape targets from this job. Defaults to the
274 globally configured default.
277 scrape_timeout = mkOpt types.str ''
278 Per-target timeout when scraping this job. Defaults to the
279 globally configured default.
282 metrics_path = mkDefOpt types.str "/metrics" ''
283 The HTTP resource path on which to fetch metrics from targets.
286 honor_labels = mkDefOpt types.bool "false" ''
287 Controls how Prometheus handles conflicts between labels
288 that are already present in scraped data and labels that
289 Prometheus would attach server-side ("job" and "instance"
290 labels, manually configured target labels, and labels
291 generated by service discovery implementations).
293 If honor_labels is set to "true", label conflicts are
294 resolved by keeping label values from the scraped data and
295 ignoring the conflicting server-side labels.
297 If honor_labels is set to "false", label conflicts are
298 resolved by renaming conflicting labels in the scraped data
299 to "exported_\<original-label\>" (for example
300 "exported_instance", "exported_job") and then attaching
301 server-side labels. This is useful for use cases such as
302 federation, where all labels specified in the target should
306 honor_timestamps = mkDefOpt types.bool "true" ''
307 honor_timestamps controls whether Prometheus respects the timestamps present
310 If honor_timestamps is set to `true`, the timestamps of the metrics exposed
311 by the target will be used.
313 If honor_timestamps is set to `false`, the timestamps of the metrics exposed
314 by the target will be ignored.
317 scheme = mkDefOpt (types.enum [ "http" "https" ]) "http" ''
318 The URL scheme with which to fetch metrics from targets.
321 params = mkOpt (types.attrsOf (types.listOf types.str)) ''
322 Optional HTTP URL parameters.
325 basic_auth = mkOpt promTypes.basic_auth ''
326 Sets the `Authorization` header on every scrape request with the
327 configured username and password.
328 password and password_file are mutually exclusive.
331 bearer_token = mkOpt types.str ''
332 Sets the `Authorization` header on every scrape request with
333 the configured bearer token. It is mutually exclusive with
334 {option}`bearer_token_file`.
337 bearer_token_file = mkOpt types.str ''
338 Sets the `Authorization` header on every scrape request with
339 the bearer token read from the configured file. It is mutually
340 exclusive with {option}`bearer_token`.
343 tls_config = mkOpt promTypes.tls_config ''
344 Configures the scrape request's TLS settings.
347 proxy_url = mkOpt types.str ''
351 azure_sd_configs = mkOpt (types.listOf promTypes.azure_sd_config) ''
352 List of Azure service discovery configurations.
355 consul_sd_configs = mkOpt (types.listOf promTypes.consul_sd_config) ''
356 List of Consul service discovery configurations.
359 digitalocean_sd_configs = mkOpt (types.listOf promTypes.digitalocean_sd_config) ''
360 List of DigitalOcean service discovery configurations.
363 docker_sd_configs = mkOpt (types.listOf promTypes.docker_sd_config) ''
364 List of Docker service discovery configurations.
367 dockerswarm_sd_configs = mkOpt (types.listOf promTypes.dockerswarm_sd_config) ''
368 List of Docker Swarm service discovery configurations.
371 dns_sd_configs = mkOpt (types.listOf promTypes.dns_sd_config) ''
372 List of DNS service discovery configurations.
375 ec2_sd_configs = mkOpt (types.listOf promTypes.ec2_sd_config) ''
376 List of EC2 service discovery configurations.
379 eureka_sd_configs = mkOpt (types.listOf promTypes.eureka_sd_config) ''
380 List of Eureka service discovery configurations.
383 file_sd_configs = mkOpt (types.listOf promTypes.file_sd_config) ''
384 List of file service discovery configurations.
387 gce_sd_configs = mkOpt (types.listOf promTypes.gce_sd_config) ''
388 List of Google Compute Engine service discovery configurations.
390 See [the relevant Prometheus configuration docs](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#gce_sd_config)
394 hetzner_sd_configs = mkOpt (types.listOf promTypes.hetzner_sd_config) ''
395 List of Hetzner service discovery configurations.
398 http_sd_configs = mkOpt (types.listOf promTypes.http_sd_config) ''
399 List of HTTP service discovery configurations.
402 kubernetes_sd_configs = mkOpt (types.listOf promTypes.kubernetes_sd_config) ''
403 List of Kubernetes service discovery configurations.
406 kuma_sd_configs = mkOpt (types.listOf promTypes.kuma_sd_config) ''
407 List of Kuma service discovery configurations.
410 lightsail_sd_configs = mkOpt (types.listOf promTypes.lightsail_sd_config) ''
411 List of Lightsail service discovery configurations.
414 linode_sd_configs = mkOpt (types.listOf promTypes.linode_sd_config) ''
415 List of Linode service discovery configurations.
418 marathon_sd_configs = mkOpt (types.listOf promTypes.marathon_sd_config) ''
419 List of Marathon service discovery configurations.
422 nerve_sd_configs = mkOpt (types.listOf promTypes.nerve_sd_config) ''
423 List of AirBnB's Nerve service discovery configurations.
426 openstack_sd_configs = mkOpt (types.listOf promTypes.openstack_sd_config) ''
427 List of OpenStack service discovery configurations.
430 puppetdb_sd_configs = mkOpt (types.listOf promTypes.puppetdb_sd_config) ''
431 List of PuppetDB service discovery configurations.
434 scaleway_sd_configs = mkOpt (types.listOf promTypes.scaleway_sd_config) ''
435 List of Scaleway service discovery configurations.
438 serverset_sd_configs = mkOpt (types.listOf promTypes.serverset_sd_config) ''
439 List of Zookeeper Serverset service discovery configurations.
442 triton_sd_configs = mkOpt (types.listOf promTypes.triton_sd_config) ''
443 List of Triton Serverset service discovery configurations.
446 uyuni_sd_configs = mkOpt (types.listOf promTypes.uyuni_sd_config) ''
447 List of Uyuni Serverset service discovery configurations.
450 static_configs = mkOpt (types.listOf promTypes.static_config) ''
451 List of labeled target groups for this job.
454 relabel_configs = mkOpt (types.listOf promTypes.relabel_config) ''
455 List of relabel configurations.
458 metric_relabel_configs = mkOpt (types.listOf promTypes.relabel_config) ''
459 List of metric relabel configurations.
462 body_size_limit = mkDefOpt types.str "0" ''
463 An uncompressed response body larger than this many bytes will cause the
464 scrape to fail. 0 means no limit. Example: 100MB.
465 This is an experimental feature, this behaviour could
466 change or be removed in the future.
469 sample_limit = mkDefOpt types.int "0" ''
470 Per-scrape limit on number of scraped samples that will be accepted.
471 If more than this number of samples are present after metric relabelling
472 the entire scrape will be treated as failed. 0 means no limit.
475 label_limit = mkDefOpt types.int "0" ''
476 Per-scrape limit on number of labels that will be accepted for a sample. If
477 more than this number of labels are present post metric-relabeling, the
478 entire scrape will be treated as failed. 0 means no limit.
481 label_name_length_limit = mkDefOpt types.int "0" ''
482 Per-scrape limit on length of labels name that will be accepted for a sample.
483 If a label name is longer than this number post metric-relabeling, the entire
484 scrape will be treated as failed. 0 means no limit.
487 label_value_length_limit = mkDefOpt types.int "0" ''
488 Per-scrape limit on length of labels value that will be accepted for a sample.
489 If a label value is longer than this number post metric-relabeling, the
490 entire scrape will be treated as failed. 0 means no limit.
493 target_limit = mkDefOpt types.int "0" ''
494 Per-scrape config limit on number of unique targets that will be
495 accepted. If more than this number of targets are present after target
496 relabeling, Prometheus will mark the targets as failed without scraping them.
497 0 means no limit. This is an experimental feature, this behaviour could
498 change in the future.
504 # Config types: service discovery
507 # For this one, the docs actually define all types needed to use mkSdConfigModule, but a bunch
508 # of them are marked with 'currently not support by Azure' so we don't bother adding them in
510 promTypes.azure_sd_config = types.submodule {
512 environment = mkDefOpt types.str "AzurePublicCloud" ''
513 The Azure environment.
516 authentication_method = mkDefOpt (types.enum [ "OAuth" "ManagedIdentity" ]) "OAuth" ''
517 The authentication method, either OAuth or ManagedIdentity.
518 See https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview
521 subscription_id = mkOption {
528 tenant_id = mkOpt types.str ''
529 Optional tenant ID. Only required with authentication_method OAuth.
532 client_id = mkOpt types.str ''
533 Optional client ID. Only required with authentication_method OAuth.
536 client_secret = mkOpt types.str ''
537 Optional client secret. Only required with authentication_method OAuth.
540 refresh_interval = mkDefOpt types.str "300s" ''
541 Refresh interval to re-read the instance list.
544 port = mkDefOpt types.port "80" ''
545 The port to scrape metrics from. If using the public IP
546 address, this must instead be specified in the relabeling
550 proxy_url = mkOpt types.str ''
554 follow_redirects = mkDefOpt types.bool "true" ''
555 Configure whether HTTP requests follow HTTP 3xx redirects.
558 tls_config = mkOpt promTypes.tls_config ''
564 promTypes.consul_sd_config = mkSdConfigModule {
565 server = mkDefOpt types.str "localhost:8500" ''
566 Consul server to query.
569 token = mkOpt types.str "Consul token";
571 datacenter = mkOpt types.str "Consul datacenter";
573 scheme = mkDefOpt types.str "http" "Consul scheme";
575 username = mkOpt types.str "Consul username";
577 password = mkOpt types.str "Consul password";
579 tls_config = mkOpt promTypes.tls_config ''
580 Configures the Consul request's TLS settings.
583 services = mkOpt (types.listOf types.str) ''
584 A list of services for which targets are retrieved.
587 tags = mkOpt (types.listOf types.str) ''
588 An optional list of tags used to filter nodes for a given
589 service. Services must contain all tags in the list.
592 node_meta = mkOpt (types.attrsOf types.str) ''
593 Node metadata used to filter nodes for a given service.
596 tag_separator = mkDefOpt types.str "," ''
597 The string by which Consul tags are joined into the tag label.
600 allow_stale = mkOpt types.bool ''
601 Allow stale Consul results
602 (see <https://www.consul.io/api/index.html#consistency-modes>).
604 Will reduce load on Consul.
607 refresh_interval = mkDefOpt types.str "30s" ''
608 The time after which the provided names are refreshed.
610 On large setup it might be a good idea to increase this value
611 because the catalog will change all the time.
615 promTypes.digitalocean_sd_config = mkSdConfigModule {
616 port = mkDefOpt types.port "80" ''
617 The port to scrape metrics from.
620 refresh_interval = mkDefOpt types.str "60s" ''
621 The time after which the droplets are refreshed.
625 mkDockerSdConfigModule = extraOptions: mkSdConfigModule ({
629 Address of the Docker daemon.
633 port = mkDefOpt types.port "80" ''
634 The port to scrape metrics from, when `role` is nodes, and for discovered
635 tasks and services that don't have published ports.
639 (types.listOf (types.submodule {
644 Name of the filter. The available filters are listed in the upstream documentation:
645 Services: <https://docs.docker.com/engine/api/v1.40/#operation/ServiceList>
646 Tasks: <https://docs.docker.com/engine/api/v1.40/#operation/TaskList>
647 Nodes: <https://docs.docker.com/engine/api/v1.40/#operation/NodeList>
653 Value for the filter.
658 Optional filters to limit the discovery process to a subset of available resources.
661 refresh_interval = mkDefOpt types.str "60s" ''
662 The time after which the containers are refreshed.
666 promTypes.docker_sd_config = mkDockerSdConfigModule {
667 host_networking_host = mkDefOpt types.str "localhost" ''
668 The host to use if the container is in host networking mode.
672 promTypes.dockerswarm_sd_config = mkDockerSdConfigModule {
674 type = types.enum [ "services" "tasks" "nodes" ];
676 Role of the targets to retrieve. Must be `services`, `tasks`, or `nodes`.
681 promTypes.dns_sd_config = types.submodule {
684 type = types.listOf types.str;
686 A list of DNS SRV record names to be queried.
690 type = mkDefOpt (types.enum [ "SRV" "A" "AAAA" ]) "SRV" ''
691 The type of DNS query to perform. One of SRV, A, or AAAA.
694 port = mkOpt types.port ''
695 The port number used if the query type is not SRV.
698 refresh_interval = mkDefOpt types.str "30s" ''
699 The time after which the provided names are refreshed.
704 promTypes.ec2_sd_config = types.submodule {
709 The AWS Region. If blank, the region from the instance metadata is used.
712 endpoint = mkOpt types.str ''
713 Custom endpoint to be used.
716 access_key = mkOpt types.str ''
717 The AWS API key id. If blank, the environment variable
718 `AWS_ACCESS_KEY_ID` is used.
721 secret_key = mkOpt types.str ''
722 The AWS API key secret. If blank, the environment variable
723 `AWS_SECRET_ACCESS_KEY` is used.
726 profile = mkOpt types.str ''
727 Named AWS profile used to connect to the API.
730 role_arn = mkOpt types.str ''
731 AWS Role ARN, an alternative to using AWS API keys.
734 refresh_interval = mkDefOpt types.str "60s" ''
735 Refresh interval to re-read the instance list.
738 port = mkDefOpt types.port "80" ''
739 The port to scrape metrics from. If using the public IP
740 address, this must instead be specified in the relabeling
745 (types.listOf (types.submodule {
750 See [this list](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html)
751 for the available filters.
756 type = types.listOf types.str;
764 Filters can be used optionally to filter the instance list by other criteria.
769 promTypes.eureka_sd_config = mkSdConfigModule {
773 The URL to connect to the Eureka server.
778 promTypes.file_sd_config = types.submodule {
781 type = types.listOf types.str;
783 Patterns for files from which target groups are extracted. Refer
784 to the Prometheus documentation for permitted filename patterns
789 refresh_interval = mkDefOpt types.str "5m" ''
790 Refresh interval to re-read the files.
795 promTypes.gce_sd_config = types.submodule {
797 # Use `mkOption` instead of `mkOpt` for project and zone because they are
798 # required configuration values for `gce_sd_config`.
809 The zone of the scrape targets. If you need multiple zones use multiple
814 filter = mkOpt types.str ''
815 Filter can be used optionally to filter the instance list by other
816 criteria Syntax of this filter string is described here in the filter
817 query parameter section: <https://cloud.google.com/compute/docs/reference/latest/instances/list>.
820 refresh_interval = mkDefOpt types.str "60s" ''
821 Refresh interval to re-read the cloud instance list.
824 port = mkDefOpt types.port "80" ''
825 The port to scrape metrics from. If using the public IP address, this
826 must instead be specified in the relabeling rule.
829 tag_separator = mkDefOpt types.str "," ''
830 The tag separator used to separate concatenated GCE instance network tags.
832 See the GCP documentation on network tags for more information:
833 <https://cloud.google.com/vpc/docs/add-remove-network-tags>
838 promTypes.hetzner_sd_config = mkSdConfigModule {
840 type = types.enum [ "robot" "hcloud" ];
842 The Hetzner role of entities that should be discovered.
843 One of `robot` or `hcloud`.
847 port = mkDefOpt types.port "80" ''
848 The port to scrape metrics from.
851 refresh_interval = mkDefOpt types.str "60s" ''
852 The time after which the servers are refreshed.
856 promTypes.http_sd_config = types.submodule {
861 URL from which the targets are fetched.
865 refresh_interval = mkDefOpt types.str "60s" ''
866 Refresh interval to re-query the endpoint.
869 basic_auth = mkOpt promTypes.basic_auth ''
870 Authentication information used to authenticate to the API server.
871 password and password_file are mutually exclusive.
874 proxy_url = mkOpt types.str ''
878 follow_redirects = mkDefOpt types.bool "true" ''
879 Configure whether HTTP requests follow HTTP 3xx redirects.
882 tls_config = mkOpt promTypes.tls_config ''
883 Configures the scrape request's TLS settings.
888 promTypes.kubernetes_sd_config = mkSdConfigModule {
889 api_server = mkOpt types.str ''
890 The API server addresses. If left empty, Prometheus is assumed to run inside
891 of the cluster and will discover API servers automatically and use the pod's
892 CA certificate and bearer token file at /var/run/secrets/kubernetes.io/serviceaccount/.
896 type = types.enum [ "endpoints" "service" "pod" "node" "ingress" ];
898 The Kubernetes role of entities that should be discovered.
899 One of endpoints, service, pod, node, or ingress.
903 kubeconfig_file = mkOpt types.str ''
904 Optional path to a kubeconfig file.
905 Note that api_server and kube_config are mutually exclusive.
912 names = mkOpt (types.listOf types.str) ''
918 Optional namespace discovery. If omitted, all namespaces are used.
933 label = mkOpt types.str ''
937 field = mkOpt types.str ''
944 Optional label and field selectors to limit the discovery process to a subset of available resources.
945 See https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/
946 and https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ to learn more about the possible
947 filters that can be used. Endpoints role supports pod, service and endpoints selectors, other roles
948 only support selectors matching the role itself (e.g. node role can only contain node selectors).
950 Note: When making decision about using field/label selector make sure that this
951 is the best approach - it will prevent Prometheus from reusing single list/watch
952 for all scrape configs. This might result in a bigger load on the Kubernetes API,
953 because per each selector combination there will be additional LIST/WATCH. On the other hand,
954 if you just want to monitor small subset of pods in large cluster it's recommended to use selectors.
955 Decision, if selectors should be used or not depends on the particular situation.
959 promTypes.kuma_sd_config = mkSdConfigModule {
963 Address of the Kuma Control Plane's MADS xDS server.
967 refresh_interval = mkDefOpt types.str "30s" ''
968 The time to wait between polling update requests.
971 fetch_timeout = mkDefOpt types.str "2m" ''
972 The time after which the monitoring assignments are refreshed.
976 promTypes.lightsail_sd_config = types.submodule {
978 region = mkOpt types.str ''
979 The AWS region. If blank, the region from the instance metadata is used.
982 endpoint = mkOpt types.str ''
983 Custom endpoint to be used.
986 access_key = mkOpt types.str ''
987 The AWS API keys. If blank, the environment variable `AWS_ACCESS_KEY_ID` is used.
990 secret_key = mkOpt types.str ''
991 The AWS API keys. If blank, the environment variable `AWS_SECRET_ACCESS_KEY` is used.
994 profile = mkOpt types.str ''
995 Named AWS profile used to connect to the API.
998 role_arn = mkOpt types.str ''
999 AWS Role ARN, an alternative to using AWS API keys.
1002 refresh_interval = mkDefOpt types.str "60s" ''
1003 Refresh interval to re-read the instance list.
1006 port = mkDefOpt types.port "80" ''
1007 The port to scrape metrics from. If using the public IP address, this must
1008 instead be specified in the relabeling rule.
1013 promTypes.linode_sd_config = mkSdConfigModule {
1014 port = mkDefOpt types.port "80" ''
1015 The port to scrape metrics from.
1018 tag_separator = mkDefOpt types.str "," ''
1019 The string by which Linode Instance tags are joined into the tag label.
1022 refresh_interval = mkDefOpt types.str "60s" ''
1023 The time after which the linode instances are refreshed.
1027 promTypes.marathon_sd_config = mkSdConfigModule {
1028 servers = mkOption {
1029 type = types.listOf types.str;
1031 List of URLs to be used to contact Marathon servers. You need to provide at least one server URL.
1035 refresh_interval = mkDefOpt types.str "30s" ''
1039 auth_token = mkOpt types.str ''
1040 Optional authentication information for token-based authentication:
1041 <https://docs.mesosphere.com/1.11/security/ent/iam-api/#passing-an-authentication-token>
1042 It is mutually exclusive with `auth_token_file` and other authentication mechanisms.
1045 auth_token_file = mkOpt types.str ''
1046 Optional authentication information for token-based authentication:
1047 <https://docs.mesosphere.com/1.11/security/ent/iam-api/#passing-an-authentication-token>
1048 It is mutually exclusive with `auth_token` and other authentication mechanisms.
1052 promTypes.nerve_sd_config = types.submodule {
1054 servers = mkOption {
1055 type = types.listOf types.str;
1057 The Zookeeper servers.
1062 type = types.listOf types.str;
1064 Paths can point to a single service, or the root of a tree of services.
1068 timeout = mkDefOpt types.str "10s" ''
1074 promTypes.openstack_sd_config = types.submodule {
1077 userDescription = ''
1078 username is required if using Identity V2 API. Consult with your provider's
1079 control panel to discover your account's username. In Identity V3, either
1080 userid or a combination of username and domain_id or domain_name are needed.
1083 domainDescription = ''
1084 At most one of domain_id and domain_name must be provided if using username
1085 with Identity V3. Otherwise, either are optional.
1088 projectDescription = ''
1089 The project_id and project_name fields are optional for the Identity V2 API.
1090 Some providers allow you to specify a project_name instead of the project_id.
1091 Some require both. Your provider's authentication policies will determine
1092 how these fields influence authentication.
1095 applicationDescription = ''
1096 The application_credential_id or application_credential_name fields are
1097 required if using an application credential to authenticate. Some providers
1098 allow you to create an application credential to authenticate rather than a
1106 The OpenStack role of entities that should be discovered.
1113 The OpenStack Region.
1117 identity_endpoint = mkOpt types.str ''
1118 identity_endpoint specifies the HTTP endpoint that is required to work with
1119 the Identity API of the appropriate version. While it's ultimately needed by
1120 all of the identity services, it will often be populated by a provider-level
1124 username = mkOpt types.str userDescription;
1125 userid = mkOpt types.str userDescription;
1127 password = mkOpt types.str ''
1128 password for the Identity V2 and V3 APIs. Consult with your provider's
1129 control panel to discover your account's preferred method of authentication.
1132 domain_name = mkOpt types.str domainDescription;
1133 domain_id = mkOpt types.str domainDescription;
1135 project_name = mkOpt types.str projectDescription;
1136 project_id = mkOpt types.str projectDescription;
1138 application_credential_name = mkOpt types.str applicationDescription;
1139 application_credential_id = mkOpt types.str applicationDescription;
1141 application_credential_secret = mkOpt types.str ''
1142 The application_credential_secret field is required if using an application
1143 credential to authenticate.
1146 all_tenants = mkDefOpt types.bool "false" ''
1147 Whether the service discovery should list all instances for all projects.
1148 It is only relevant for the 'instance' role and usually requires admin permissions.
1151 refresh_interval = mkDefOpt types.str "60s" ''
1152 Refresh interval to re-read the instance list.
1155 port = mkDefOpt types.port "80" ''
1156 The port to scrape metrics from. If using the public IP address, this must
1157 instead be specified in the relabeling rule.
1160 availability = mkDefOpt (types.enum [ "public" "admin" "internal" ]) "public" ''
1161 The availability of the endpoint to connect to. Must be one of public, admin or internal.
1164 tls_config = mkOpt promTypes.tls_config ''
1170 promTypes.puppetdb_sd_config = mkSdConfigModule {
1174 The URL of the PuppetDB root query endpoint.
1181 Puppet Query Language (PQL) query. Only resources are supported.
1182 https://puppet.com/docs/puppetdb/latest/api/query/v4/pql.html
1186 include_parameters = mkDefOpt types.bool "false" ''
1187 Whether to include the parameters as meta labels.
1188 Due to the differences between parameter types and Prometheus labels,
1189 some parameters might not be rendered. The format of the parameters might
1190 also change in future releases.
1192 Note: Enabling this exposes parameters in the Prometheus UI and API. Make sure
1193 that you don't have secrets exposed as parameters if you enable this.
1196 refresh_interval = mkDefOpt types.str "60s" ''
1197 Refresh interval to re-read the resources list.
1200 port = mkDefOpt types.port "80" ''
1201 The port to scrape metrics from.
1205 promTypes.scaleway_sd_config = types.submodule {
1207 access_key = mkOption {
1210 Access key to use. https://console.scaleway.com/project/credentials
1214 secret_key = mkOpt types.str ''
1215 Secret key to use when listing targets. https://console.scaleway.com/project/credentials
1216 It is mutually exclusive with `secret_key_file`.
1219 secret_key_file = mkOpt types.str ''
1220 Sets the secret key with the credentials read from the configured file.
1221 It is mutually exclusive with `secret_key`.
1224 project_id = mkOption {
1227 Project ID of the targets.
1232 type = types.enum [ "instance" "baremetal" ];
1234 Role of the targets to retrieve. Must be `instance` or `baremetal`.
1238 port = mkDefOpt types.port "80" ''
1239 The port to scrape metrics from.
1242 api_url = mkDefOpt types.str "https://api.scaleway.com" ''
1243 API URL to use when doing the server listing requests.
1246 zone = mkDefOpt types.str "fr-par-1" ''
1247 Zone is the availability zone of your targets (e.g. fr-par-1).
1250 name_filter = mkOpt types.str ''
1251 Specify a name filter (works as a LIKE) to apply on the server listing request.
1254 tags_filter = mkOpt (types.listOf types.str) ''
1255 Specify a tag filter (a server needs to have all defined tags to be listed) to apply on the server listing request.
1258 refresh_interval = mkDefOpt types.str "60s" ''
1259 Refresh interval to re-read the managed targets list.
1262 proxy_url = mkOpt types.str ''
1266 follow_redirects = mkDefOpt types.bool "true" ''
1267 Configure whether HTTP requests follow HTTP 3xx redirects.
1270 tls_config = mkOpt promTypes.tls_config ''
1276 # These are exactly the same.
1277 promTypes.serverset_sd_config = promTypes.nerve_sd_config;
1279 promTypes.triton_sd_config = types.submodule {
1281 account = mkOption {
1284 The account to use for discovering new targets.
1288 role = mkDefOpt (types.enum [ "container" "cn" ]) "container" ''
1289 The type of targets to discover, can be set to:
1290 - "container" to discover virtual machines (SmartOS zones, lx/KVM/bhyve branded zones) running on Triton
1291 - "cn" to discover compute nodes (servers/global zones) making up the Triton infrastructure
1294 dns_suffix = mkOption {
1297 The DNS suffix which should be applied to target.
1301 endpoint = mkOption {
1304 The Triton discovery endpoint (e.g. `cmon.us-east-3b.triton.zone`). This is
1305 often the same value as dns_suffix.
1309 groups = mkOpt (types.listOf types.str) ''
1310 A list of groups for which targets are retrieved, only supported when targeting the `container` role.
1311 If omitted all containers owned by the requesting account are scraped.
1314 port = mkDefOpt types.port "9163" ''
1315 The port to use for discovery and metric scraping.
1318 refresh_interval = mkDefOpt types.str "60s" ''
1319 The interval which should be used for refreshing targets.
1322 version = mkDefOpt types.int "1" ''
1323 The Triton discovery API version.
1326 tls_config = mkOpt promTypes.tls_config ''
1332 promTypes.uyuni_sd_config = mkSdConfigModule {
1336 The URL to connect to the Uyuni server.
1340 username = mkOption {
1343 Credentials are used to authenticate the requests to Uyuni API.
1347 password = mkOption {
1350 Credentials are used to authenticate the requests to Uyuni API.
1354 entitlement = mkDefOpt types.str "monitoring_entitled" ''
1355 The entitlement string to filter eligible systems.
1358 separator = mkDefOpt types.str "," ''
1359 The string by which Uyuni group names are joined into the groups label
1362 refresh_interval = mkDefOpt types.str "60s" ''
1363 Refresh interval to re-read the managed targets list.
1367 promTypes.static_config = types.submodule {
1369 targets = mkOption {
1370 type = types.listOf types.str;
1372 The targets specified by the target group.
1376 type = types.attrsOf types.str;
1379 Labels assigned to all metrics scraped from the targets.
1386 # Config types: relabling
1389 promTypes.relabel_config = types.submodule {
1391 source_labels = mkOpt (types.listOf types.str) ''
1392 The source labels select values from existing labels. Their content
1393 is concatenated using the configured separator and matched against
1394 the configured regular expression.
1397 separator = mkDefOpt types.str ";" ''
1398 Separator placed between concatenated source label values.
1401 target_label = mkOpt types.str ''
1402 Label to which the resulting value is written in a replace action.
1403 It is mandatory for replace actions.
1406 regex = mkDefOpt types.str "(.*)" ''
1407 Regular expression against which the extracted value is matched.
1410 modulus = mkOpt types.int ''
1411 Modulus to take of the hash of the source label values.
1414 replacement = mkDefOpt types.str "$1" ''
1415 Replacement value against which a regex replace is performed if the
1416 regular expression matches.
1420 mkDefOpt (types.enum [ "replace" "lowercase" "uppercase" "keep" "drop" "hashmod" "labelmap" "labeldrop" "labelkeep" ]) "replace" ''
1421 Action to perform based on regex matching.
1427 # Config types : remote read / write
1430 promTypes.remote_write = types.submodule {
1435 ServerName extension to indicate the name of the server.
1436 http://tools.ietf.org/html/rfc4366#section-3.1
1439 remote_timeout = mkOpt types.str ''
1440 Timeout for requests to the remote write endpoint.
1442 headers = mkOpt (types.attrsOf types.str) ''
1443 Custom HTTP headers to be sent along with each remote write request.
1444 Be aware that headers that are set by Prometheus itself can't be overwritten.
1446 write_relabel_configs = mkOpt (types.listOf promTypes.relabel_config) ''
1447 List of remote write relabel configurations.
1449 name = mkOpt types.str ''
1450 Name of the remote write config, which if specified must be unique among remote write configs.
1451 The name will be used in metrics and logging in place of a generated value to help users distinguish between
1452 remote write configs.
1454 basic_auth = mkOpt promTypes.basic_auth ''
1455 Sets the `Authorization` header on every remote write request with the
1456 configured username and password.
1457 password and password_file are mutually exclusive.
1459 bearer_token = mkOpt types.str ''
1460 Sets the `Authorization` header on every remote write request with
1461 the configured bearer token. It is mutually exclusive with `bearer_token_file`.
1463 bearer_token_file = mkOpt types.str ''
1464 Sets the `Authorization` header on every remote write request with the bearer token
1465 read from the configured file. It is mutually exclusive with `bearer_token`.
1467 tls_config = mkOpt promTypes.tls_config ''
1468 Configures the remote write request's TLS settings.
1470 proxy_url = mkOpt types.str "Optional Proxy URL.";
1471 queue_config = mkOpt
1474 capacity = mkOpt types.int ''
1475 Number of samples to buffer per shard before we block reading of more
1476 samples from the WAL. It is recommended to have enough capacity in each
1477 shard to buffer several requests to keep throughput up while processing
1478 occasional slow remote requests.
1480 max_shards = mkOpt types.int ''
1481 Maximum number of shards, i.e. amount of concurrency.
1483 min_shards = mkOpt types.int ''
1484 Minimum number of shards, i.e. amount of concurrency.
1486 max_samples_per_send = mkOpt types.int ''
1487 Maximum number of samples per send.
1489 batch_send_deadline = mkOpt types.str ''
1490 Maximum time a sample will wait in buffer.
1492 min_backoff = mkOpt types.str ''
1493 Initial retry delay. Gets doubled for every retry.
1495 max_backoff = mkOpt types.str ''
1496 Maximum retry delay.
1500 Configures the queue used to write to remote storage.
1502 metadata_config = mkOpt
1505 send = mkOpt types.bool ''
1506 Whether metric metadata is sent to remote storage or not.
1508 send_interval = mkOpt types.str ''
1509 How frequently metric metadata is sent to remote storage.
1513 Configures the sending of series metadata to remote storage.
1514 Metadata configuration is subject to change at any point
1515 or be removed in future releases.
1520 promTypes.remote_read = types.submodule {
1525 ServerName extension to indicate the name of the server.
1526 http://tools.ietf.org/html/rfc4366#section-3.1
1529 name = mkOpt types.str ''
1530 Name of the remote read config, which if specified must be unique among remote read configs.
1531 The name will be used in metrics and logging in place of a generated value to help users distinguish between
1532 remote read configs.
1534 required_matchers = mkOpt (types.attrsOf types.str) ''
1535 An optional list of equality matchers which have to be
1536 present in a selector to query the remote read endpoint.
1538 remote_timeout = mkOpt types.str ''
1539 Timeout for requests to the remote read endpoint.
1541 headers = mkOpt (types.attrsOf types.str) ''
1542 Custom HTTP headers to be sent along with each remote read request.
1543 Be aware that headers that are set by Prometheus itself can't be overwritten.
1545 read_recent = mkOpt types.bool ''
1546 Whether reads should be made for queries for time ranges that
1547 the local storage should have complete data for.
1549 basic_auth = mkOpt promTypes.basic_auth ''
1550 Sets the `Authorization` header on every remote read request with the
1551 configured username and password.
1552 password and password_file are mutually exclusive.
1554 bearer_token = mkOpt types.str ''
1555 Sets the `Authorization` header on every remote read request with
1556 the configured bearer token. It is mutually exclusive with `bearer_token_file`.
1558 bearer_token_file = mkOpt types.str ''
1559 Sets the `Authorization` header on every remote read request with the bearer token
1560 read from the configured file. It is mutually exclusive with `bearer_token`.
1562 tls_config = mkOpt promTypes.tls_config ''
1563 Configures the remote read request's TLS settings.
1565 proxy_url = mkOpt types.str "Optional Proxy URL.";
1573 (mkRenamedOptionModule [ "services" "prometheus2" ] [ "services" "prometheus" ])
1574 (mkRemovedOptionModule [ "services" "prometheus" "environmentFile" ]
1575 "It has been removed since it was causing issues (https://github.com/NixOS/nixpkgs/issues/126083) and Prometheus now has native support for secret files, i.e. `basic_auth.password_file` and `authorization.credentials_file`.")
1576 (mkRemovedOptionModule [ "services" "prometheus" "alertmanagerTimeout" ]
1577 "Deprecated upstream and no longer had any effect")
1580 options.services.prometheus = {
1582 enable = mkEnableOption "Prometheus monitoring daemon";
1584 package = mkPackageOption pkgs "prometheus" { };
1594 listenAddress = mkOption {
1596 default = "0.0.0.0";
1598 Address to listen on for the web interface, API, and telemetry.
1602 stateDir = mkOption {
1604 default = "prometheus2";
1606 Directory below `/var/lib` to store Prometheus metrics data.
1607 This directory will be created automatically using systemd's StateDirectory mechanism.
1611 extraFlags = mkOption {
1612 type = types.listOf types.str;
1615 Extra commandline options when launching Prometheus.
1619 enableReload = mkOption {
1623 Reload prometheus when configuration file changes (instead of restart).
1625 The following property holds: switching to a configuration
1626 (`switch-to-configuration`) that changes the prometheus
1627 configuration only finishes successfully when prometheus has finished
1628 loading the new configuration.
1632 enableAgentMode = mkEnableOption "agent mode";
1634 configText = mkOption {
1635 type = types.nullOr types.lines;
1638 If non-null, this option defines the text that is written to
1639 prometheus.yml. If null, the contents of prometheus.yml is generated
1640 from the structured config options.
1644 globalConfig = mkOption {
1645 type = promTypes.globalConfig;
1648 Parameters that are valid in all configuration contexts. They
1649 also serve as defaults for other configuration sections
1653 remoteRead = mkOption {
1654 type = types.listOf promTypes.remote_read;
1657 Parameters of the endpoints to query from.
1658 See [the official documentation](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#remote_read) for more information.
1662 remoteWrite = mkOption {
1663 type = types.listOf promTypes.remote_write;
1666 Parameters of the endpoints to send samples to.
1667 See [the official documentation](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#remote_write) for more information.
1672 type = types.listOf types.str;
1675 Alerting and/or Recording rules to evaluate at runtime.
1679 ruleFiles = mkOption {
1680 type = types.listOf types.path;
1683 Any additional rules files to include in this configuration.
1687 scrapeConfigs = mkOption {
1688 type = types.listOf promTypes.scrape_config;
1691 A list of scrape configurations.
1695 alertmanagers = mkOption {
1696 type = types.listOf types.attrs;
1697 example = literalExpression ''
1700 path_prefix = "/alertmanager";
1701 static_configs = [ {
1703 "prometheus.domain.tld"
1710 A list of alertmanagers to send alerts to.
1711 See [the official documentation](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#alertmanager_config) for more information.
1715 alertmanagerNotificationQueueCapacity = mkOption {
1719 The capacity of the queue for pending alert manager notifications.
1723 webExternalUrl = mkOption {
1724 type = types.nullOr types.str;
1726 example = "https://example.com/";
1728 The URL under which Prometheus is externally reachable (for example,
1729 if Prometheus is served via a reverse proxy).
1733 webConfigFile = mkOption {
1734 type = types.nullOr types.path;
1737 Specifies which file should be used as web.config.file and be passed on startup.
1738 See https://prometheus.io/docs/prometheus/latest/configuration/https/ for valid options.
1742 checkConfig = mkOption {
1743 type = with types; either bool (enum [ "syntax-only" ]);
1745 example = "syntax-only";
1747 Check configuration with `promtool check`. The call to `promtool` is
1748 subject to sandboxing by Nix.
1750 If you use credentials stored in external files
1751 (`password_file`, `bearer_token_file`, etc),
1752 they will not be visible to `promtool`
1753 and it will report errors, despite a correct configuration.
1754 To resolve this, you may set this option to `"syntax-only"`
1755 in order to only syntax check the Prometheus configuration.
1759 retentionTime = mkOption {
1760 type = types.nullOr types.str;
1764 How long to retain samples in storage.
1769 config = mkIf cfg.enable {
1773 # Match something with dots (an IPv4 address) or something ending in
1774 # a square bracket (an IPv6 addresses) followed by a port number.
1775 legacy = builtins.match "(.*\\..*|.*]):([[:digit:]]+)" cfg.listenAddress;
1778 assertion = legacy == null;
1780 Do not specify the port for Prometheus to listen on in the
1781 listenAddress option; use the port option instead:
1782 services.prometheus.listenAddress = ${builtins.elemAt legacy 0};
1783 services.prometheus.port = ${builtins.elemAt legacy 1};
1789 users.groups.prometheus.gid = config.ids.gids.prometheus;
1790 users.users.prometheus = {
1791 description = "Prometheus daemon user";
1792 uid = config.ids.uids.prometheus;
1793 group = "prometheus";
1795 environment.etc."prometheus/prometheus.yaml" = mkIf cfg.enableReload {
1796 source = prometheusYml;
1798 systemd.services.prometheus = {
1799 wantedBy = [ "multi-user.target" ];
1800 after = [ "network.target" ];
1802 ExecStart = "${cfg.package}/bin/prometheus" +
1803 optionalString (length cmdlineArgs != 0) (" \\\n " +
1804 concatStringsSep " \\\n " cmdlineArgs);
1805 ExecReload = mkIf cfg.enableReload "+${reload}/bin/reload-prometheus";
1806 User = "prometheus";
1808 RuntimeDirectory = "prometheus";
1809 RuntimeDirectoryMode = "0700";
1810 WorkingDirectory = workingDir;
1811 StateDirectory = cfg.stateDir;
1812 StateDirectoryMode = "0700";
1814 AmbientCapabilities = lib.mkIf (cfg.port < 1024) [ "CAP_NET_BIND_SERVICE" ];
1815 CapabilityBoundingSet = if (cfg.port < 1024) then [ "CAP_NET_BIND_SERVICE" ] else [ "" ];
1816 DeviceAllow = [ "/dev/null rw" ];
1817 DevicePolicy = "strict";
1818 LockPersonality = true;
1819 MemoryDenyWriteExecute = true;
1820 NoNewPrivileges = true;
1821 PrivateDevices = true;
1823 PrivateUsers = true;
1824 ProtectClock = true;
1825 ProtectControlGroups = true;
1827 ProtectHostname = true;
1828 ProtectKernelLogs = true;
1829 ProtectKernelModules = true;
1830 ProtectKernelTunables = true;
1831 ProtectProc = "invisible";
1832 ProtectSystem = "full";
1834 RestrictAddressFamilies = [ "AF_INET" "AF_INET6" "AF_UNIX" ];
1835 RestrictNamespaces = true;
1836 RestrictRealtime = true;
1837 RestrictSUIDSGID = true;
1838 SystemCallArchitectures = "native";
1839 SystemCallFilter = [ "@system-service" "~@privileged" ];
1842 # prometheus-config-reload will activate after prometheus. However, what we
1843 # don't want is that on startup it immediately reloads prometheus because
1844 # prometheus itself might have just started.
1846 # Instead we only want to reload prometheus when the config file has
1847 # changed. So on startup prometheus-config-reload will just output a
1848 # harmless message and then stay active (RemainAfterExit).
1850 # Then, when the config file has changed, switch-to-configuration notices
1851 # that this service has changed (restartTriggers) and needs to be reloaded
1852 # (reloadIfChanged). The reload command then reloads prometheus.
1853 systemd.services.prometheus-config-reload = mkIf cfg.enableReload {
1854 wantedBy = [ "prometheus.service" ];
1855 after = [ "prometheus.service" ];
1856 reloadIfChanged = true;
1857 restartTriggers = [ prometheusYml ];
1860 RemainAfterExit = true;
1862 ExecStart = "${pkgs.logger}/bin/logger 'prometheus-config-reload will only reload prometheus when reloaded itself.'";
1863 ExecReload = [ "${triggerReload}/bin/trigger-reload-prometheus" ];