git.iko.soy/typeable/nixpkgs
on master help sign in
Merge pull request #58255 from jbgi/prometheus2

Add Prometheus 2 service in parallel with 1.x version (continuation)

commit2f2e2971d6ccdd42165a23905ba9dc2aa11b3554 authorBas van Dijk <v.dijk.bas@gmail.com> dateTue 9 Apr 2019, 14:14 (8 years ago) parent14105fdb423b73
4 files changed+352−32
nixos/doc/manual/release-notes/rl-1909.xml+46−1 nixos/modules/services/monitoring/prometheus/default.nix+271−31 nixos/tests/all-tests.nix+1 nixos/tests/prometheus-2.nix+34
nixos/doc/manual/release-notes/rl-1909.xml+46−1
@@ -37,7 +37,52 @@
3737
3838 <itemizedlist>
3939 <listitem>
40− <para />
40+ <para>
41+ Besides the existing <option>services.prometheus</option> module which
42+ targets Prometheus-1 a new <option>services.prometheus2</option> module
43+ has been added which targets Prometheus-2.
44+ </para>
45+ <para>
46+ Both modules can be enabled at the same time. In fact
47+ <link xlink:href="https://prometheus.io/docs/prometheus/latest/migration/#storage">
48+ this is needed for upgrading existing Prometheus-1 data to Prometheus-2
49+ </link>.
50+ </para>
51+ </listitem>
52+ </itemizedlist>
53+ </section>
54+
55+ <section xmlns="http://docbook.org/ns/docbook"
56+ xmlns:xlink="http://www.w3.org/1999/xlink"
57+ xmlns:xi="http://www.w3.org/2001/XInclude"
58+ version="5.0"
59+ xml:id="sec-release-19.09-incompatibilities">
60+ <title>Backward Incompatibilities</title>
61+
62+ <para>
63+ When upgrading from a previous release, please be aware of the following
64+ incompatible changes:
65+ </para>
66+
67+ <itemizedlist>
68+ <listitem>
69+ <para>
70+ The directory where Prometheus will store its metric data is now
71+ managed by systemd's StateDirectory mechanism. It still defaults
72+ to <literal>/var/lib/prometheus</literal>.
73+ </para>
74+ <para>
75+ Its location can be specified by the new
76+ <option>services.prometheus.stateDir</option> option which
77+ defaults to <literal>prometheus</literal>. Note that this should
78+ be a directory relative to <literal>/var/lib/</literal>.
79+ </para>
80+ <para>
81+ The option <option>services.prometheus.dataDir</option> has been
82+ deprecated. You can still set it but it's now required to have
83+ <literal>/var/lib/</literal> as a prefix and you can't set
84+ <option>services.prometheus.stateDir</option> at the same time.
85+ </para>
4186 </listitem>
4287 </itemizedlist>
4388 </section>
nixos/modules/services/monitoring/prometheus/default.nix+271−31
@@ -4,9 +4,24 @@ with lib;
44
55let
66 cfg = config.services.prometheus;
7+ cfg2 = config.services.prometheus2;
78 promUser = "prometheus";
89 promGroup = "prometheus";
910
11+ stateDir =
12+ if cfg.stateDir != null
13+ then cfg.stateDir
14+ else
15+ if cfg.dataDir != null
16+ then
17+ # This assumes /var/lib/ is a prefix of cfg.dataDir.
18+ # This is checked as an assertion below.
19+ removePrefix stateDirBase cfg.dataDir
20+ else "prometheus";
21+ stateDirBase = "/var/lib/";
22+ workingDir = stateDirBase + stateDir;
23+ workingDir2 = stateDirBase + cfg2.stateDir;
24+
1025 # Get a submodule without any embedded metadata:
1126 _filter = x: filterAttrs (k: v: k != "_module") x;
1227
@@ -17,13 +32,23 @@ let
1732 promtool ${what} $out
1833 '';
1934
35+ # a wrapper that verifies that the configuration is valid for
36+ # prometheus 2
37+ prom2toolCheck = what: name: file:
38+ pkgs.runCommand
39+ "${name}-${replaceStrings [" "] [""] what}-checked"
40+ { buildInputs = [ cfg2.package ]; } ''
41+ ln -s ${file} $out
42+ promtool ${what} $out
43+ '';
44+
2045 # Pretty-print JSON to a file
2146 writePrettyJSON = name: x:
2247 pkgs.runCommand name { preferLocalBuild = true; } ''
2348 echo '${builtins.toJSON x}' | ${pkgs.jq}/bin/jq . > $out
2449 '';
2550
26− # This becomes the main config file
51+ # This becomes the main config file for Prometheus 1
2752 promConfig = {
2853 global = cfg.globalConfig;
2954 rule_files = map (promtoolCheck "check-rules" "rules") (cfg.ruleFiles ++ [
@@ -35,20 +60,53 @@ let
3560 generatedPrometheusYml = writePrettyJSON "prometheus.yml" promConfig;
3661
3762 prometheusYml = let
38− yml = if cfg.configText != null then
63+ yml = if cfg.configText != null then
3964 pkgs.writeText "prometheus.yml" cfg.configText
4065 else generatedPrometheusYml;
4166 in promtoolCheck "check-config" "prometheus.yml" yml;
4267
4368 cmdlineArgs = cfg.extraFlags ++ [
44− "-storage.local.path=${cfg.dataDir}/metrics"
69+ "-storage.local.path=${workingDir}/metrics"
4570 "-config.file=${prometheusYml}"
4671 "-web.listen-address=${cfg.listenAddress}"
4772 "-alertmanager.notification-queue-capacity=${toString cfg.alertmanagerNotificationQueueCapacity}"
4873 "-alertmanager.timeout=${toString cfg.alertmanagerTimeout}s"
49− (optionalString (cfg.alertmanagerURL != []) "-alertmanager.url=${concatStringsSep "," cfg.alertmanagerURL}")
50− (optionalString (cfg.webExternalUrl != null) "-web.external-url=${cfg.webExternalUrl}")
51− ];
74+ ] ++
75+ optional (cfg.alertmanagerURL != []) "-alertmanager.url=${concatStringsSep "," cfg.alertmanagerURL}" ++
76+ optional (cfg.webExternalUrl != null) "-web.external-url=${cfg.webExternalUrl}";
77+
78+ # This becomes the main config file for Prometheus 2
79+ promConfig2 = {
80+ global = cfg2.globalConfig;
81+ rule_files = map (prom2toolCheck "check rules" "rules") (cfg2.ruleFiles ++ [
82+ (pkgs.writeText "prometheus.rules" (concatStringsSep "\n" cfg2.rules))
83+ ]);
84+ scrape_configs = cfg2.scrapeConfigs;
85+ alerting = optionalAttrs (cfg2.alertmanagerURL != []) {
86+ alertmanagers = [{
87+ static_configs = [{
88+ targets = cfg2.alertmanagerURL;
89+ }];
90+ }];
91+ };
92+ };
93+
94+ generatedPrometheus2Yml = writePrettyJSON "prometheus.yml" promConfig2;
95+
96+ prometheus2Yml = let
97+ yml = if cfg2.configText != null then
98+ pkgs.writeText "prometheus.yml" cfg2.configText
99+ else generatedPrometheus2Yml;
100+ in prom2toolCheck "check config" "prometheus.yml" yml;
101+
102+ cmdlineArgs2 = cfg2.extraFlags ++ [
103+ "--storage.tsdb.path=${workingDir2}/data/"
104+ "--config.file=${prometheus2Yml}"
105+ "--web.listen-address=${cfg2.listenAddress}"
106+ "--alertmanager.notification-queue-capacity=${toString cfg2.alertmanagerNotificationQueueCapacity}"
107+ "--alertmanager.timeout=${toString cfg2.alertmanagerTimeout}s"
108+ ] ++
109+ optional (cfg2.webExternalUrl != null) "--web.external-url=${cfg2.webExternalUrl}";
52110
53111 promTypes.globalConfig = types.submodule {
54112 options = {
@@ -403,10 +461,21 @@ in {
403461 };
404462
405463 dataDir = mkOption {
406− type = types.path;
407− default = "/var/lib/prometheus";
464+ type = types.nullOr types.path;
465+ default = null;
408466 description = ''
409467 Directory to store Prometheus metrics data.
468+ This option is deprecated, please use <option>services.prometheus.stateDir</option>.
469+ '';
470+ };
471+
472+ stateDir = mkOption {
473+ type = types.nullOr types.str;
474+ default = null;
475+ description = ''
476+ Directory below <literal>${stateDirBase}</literal> to store Prometheus metrics data.
477+ This directory will be created automatically using systemd's StateDirectory mechanism.
478+ Defaults to <literal>prometheus</literal>.
410479 '';
411480 };
412481
@@ -497,30 +566,201 @@ in {
497566 '';
498567 };
499568 };
500− };
569+ services.prometheus2 = {
501570
502− config = mkIf cfg.enable {
503− users.groups.${promGroup}.gid = config.ids.gids.prometheus;
504− users.users.${promUser} = {
505− description = "Prometheus daemon user";
506− uid = config.ids.uids.prometheus;
507− group = promGroup;
508− home = cfg.dataDir;
509− createHome = true;
510− };
511− systemd.services.prometheus = {
512− wantedBy = [ "multi-user.target" ];
513− after = [ "network.target" ];
514− script = ''
515− #!/bin/sh
516− exec ${cfg.package}/bin/prometheus \
517− ${concatStringsSep " \\\n " cmdlineArgs}
518− '';
519− serviceConfig = {
520− User = promUser;
521− Restart = "always";
522− WorkingDirectory = cfg.dataDir;
571+ enable = mkOption {
572+ type = types.bool;
573+ default = false;
574+ description = ''
575+ Enable the Prometheus 2 monitoring daemon.
576+ '';
577+ };
578+
579+ package = mkOption {
580+ type = types.package;
581+ default = pkgs.prometheus_2;
582+ defaultText = "pkgs.prometheus_2";
583+ description = ''
584+ The prometheus2 package that should be used.
585+ '';
586+ };
587+
588+ listenAddress = mkOption {
589+ type = types.str;
590+ default = "0.0.0.0:9090";
591+ description = ''
592+ Address to listen on for the web interface, API, and telemetry.
593+ '';
594+ };
595+
596+ stateDir = mkOption {
597+ type = types.str;
598+ default = "prometheus2";
599+ description = ''
600+ Directory below <literal>${stateDirBase}</literal> to store Prometheus metrics data.
601+ This directory will be created automatically using systemd's StateDirectory mechanism.
602+ Defaults to <literal>prometheus2</literal>.
603+ '';
604+ };
605+
606+ extraFlags = mkOption {
607+ type = types.listOf types.str;
608+ default = [];
609+ description = ''
610+ Extra commandline options when launching Prometheus 2.
611+ '';
612+ };
613+
614+ configText = mkOption {
615+ type = types.nullOr types.lines;
616+ default = null;
617+ description = ''
618+ If non-null, this option defines the text that is written to
619+ prometheus.yml. If null, the contents of prometheus.yml is generated
620+ from the structured config options.
621+ '';
622+ };
623+
624+ globalConfig = mkOption {
625+ type = promTypes.globalConfig;
626+ default = {};
627+ apply = _filter;
628+ description = ''
629+ Parameters that are valid in all configuration contexts. They
630+ also serve as defaults for other configuration sections
631+ '';
632+ };
633+
634+ rules = mkOption {
635+ type = types.listOf types.str;
636+ default = [];
637+ description = ''
638+ Alerting and/or Recording rules to evaluate at runtime.
639+ '';
640+ };
641+
642+ ruleFiles = mkOption {
643+ type = types.listOf types.path;
644+ default = [];
645+ description = ''
646+ Any additional rules files to include in this configuration.
647+ '';
648+ };
649+
650+ scrapeConfigs = mkOption {
651+ type = types.listOf promTypes.scrape_config;
652+ default = [];
653+ apply = x: map _filter x;
654+ description = ''
655+ A list of scrape configurations.
656+ '';
657+ };
658+
659+ alertmanagerURL = mkOption {
660+ type = types.listOf types.str;
661+ default = [];
662+ description = ''
663+ List of Alertmanager URLs to send notifications to.
664+ '';
665+ };
666+
667+ alertmanagerNotificationQueueCapacity = mkOption {
668+ type = types.int;
669+ default = 10000;
670+ description = ''
671+ The capacity of the queue for pending alert manager notifications.
672+ '';
673+ };
674+
675+ alertmanagerTimeout = mkOption {
676+ type = types.int;
677+ default = 10;
678+ description = ''
679+ Alert manager HTTP API timeout (in seconds).
680+ '';
681+ };
682+
683+ webExternalUrl = mkOption {
684+ type = types.nullOr types.str;
685+ default = null;
686+ example = "https://example.com/";
687+ description = ''
688+ The URL under which Prometheus is externally reachable (for example,
689+ if Prometheus is served via a reverse proxy).
690+ '';
523691 };
524692 };
525− };
693+ };
694+
695+ config = mkMerge [
696+ (mkIf (cfg.enable || cfg2.enable) {
697+ users.groups.${promGroup}.gid = config.ids.gids.prometheus;
698+ users.users.${promUser} = {
699+ description = "Prometheus daemon user";
700+ uid = config.ids.uids.prometheus;
701+ group = promGroup;
702+ };
703+ })
704+ (mkIf cfg.enable {
705+ warnings =
706+ optional (cfg.dataDir != null) ''
707+ The option services.prometheus.dataDir is deprecated, please use
708+ services.prometheus.stateDir.
709+ '';
710+ assertions = [
711+ {
712+ assertion = !(cfg.dataDir != null && cfg.stateDir != null);
713+ message =
714+ "The options services.prometheus.dataDir and services.prometheus.stateDir" +
715+ " can't both be set at the same time! It's recommended to only set the latter" +
716+ " since the former is deprecated.";
717+ }
718+ {
719+ assertion = cfg.dataDir != null -> hasPrefix stateDirBase cfg.dataDir;
720+ message =
721+ "The option services.prometheus.dataDir should have ${stateDirBase} as a prefix!";
722+ }
723+ {
724+ assertion = cfg.stateDir != null -> !hasPrefix "/" cfg.stateDir;
725+ message =
726+ "The option services.prometheus.stateDir shouldn't be an absolute directory." +
727+ " It should be a directory relative to ${stateDirBase}.";
728+ }
729+ {
730+ assertion = cfg2.stateDir != null -> !hasPrefix "/" cfg2.stateDir;
731+ message =
732+ "The option services.prometheus2.stateDir shouldn't be an absolute directory." +
733+ " It should be a directory relative to ${stateDirBase}.";
734+ }
735+ ];
736+ systemd.services.prometheus = {
737+ wantedBy = [ "multi-user.target" ];
738+ after = [ "network.target" ];
739+ serviceConfig = {
740+ ExecStart = "${cfg.package}/bin/prometheus" +
741+ optionalString (length cmdlineArgs != 0) (" \\\n " +
742+ concatStringsSep " \\\n " cmdlineArgs);
743+ User = promUser;
744+ Restart = "always";
745+ WorkingDirectory = workingDir;
746+ StateDirectory = stateDir;
747+ };
748+ };
749+ })
750+ (mkIf cfg2.enable {
751+ systemd.services.prometheus2 = {
752+ wantedBy = [ "multi-user.target" ];
753+ after = [ "network.target" ];
754+ serviceConfig = {
755+ ExecStart = "${cfg2.package}/bin/prometheus" +
756+ optionalString (length cmdlineArgs2 != 0) (" \\\n " +
757+ concatStringsSep " \\\n " cmdlineArgs2);
758+ User = promUser;
759+ Restart = "always";
760+ WorkingDirectory = workingDir2;
761+ StateDirectory = cfg2.stateDir;
762+ };
763+ };
764+ })
765+ ];
526766}
nixos/tests/all-tests.nix+1
@@ -194,6 +194,7 @@ in
194194 predictable-interface-names = handleTest ./predictable-interface-names.nix {};
195195 printing = handleTest ./printing.nix {};
196196 prometheus = handleTest ./prometheus.nix {};
197+ prometheus2 = handleTest ./prometheus-2.nix {};
197198 prometheus-exporters = handleTest ./prometheus-exporters.nix {};
198199 prosody = handleTest ./prosody.nix {};
199200 proxy = handleTest ./proxy.nix {};
nixos/tests/prometheus-2.nixnew file+34
@@ -0,0 +1,34 @@
1+import ./make-test.nix {
2+ name = "prometheus-2";
3+
4+ nodes = {
5+ one = { pkgs, ... }: {
6+ services.prometheus2 = {
7+ enable = true;
8+ scrapeConfigs = [{
9+ job_name = "prometheus";
10+ static_configs = [{
11+ targets = [ "127.0.0.1:9090" ];
12+ labels = { instance = "localhost"; };
13+ }];
14+ }];
15+ rules = [
16+ ''
17+ groups:
18+ - name: test
19+ rules:
20+ - record: testrule
21+ expr: count(up{job="prometheus"})
22+ ''
23+ ];
24+ };
25+ };
26+ };
27+
28+ testScript = ''
29+ startAll;
30+ $one->waitForUnit("prometheus2.service");
31+ $one->waitForOpenPort(9090);
32+ $one->succeed("curl -s http://127.0.0.1:9090/metrics");
33+ '';
34+}