summaryrefslogtreecommitdiffstats
path: root/nixos/modules/services/databases/victoriametrics.nix
blob: 3ff94c3d4b96efdf3d77b3976692a91417480a67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
{
  config,
  pkgs,
  lib,
  ...
}:
with lib;
let
  cfg = config.services.victoriametrics;
  settingsFormat = pkgs.formats.yaml { };

  startCLIList = [
    "${cfg.package}/bin/victoria-metrics"
    "-storageDataPath=/var/lib/${cfg.stateDir}"
    "-httpListenAddr=${cfg.listenAddress}"

  ]
  ++ lib.optionals (cfg.retentionPeriod != null) [ "-retentionPeriod=${cfg.retentionPeriod}" ]
  ++ cfg.extraOptions;
  prometheusConfigYml = checkedConfig (
    settingsFormat.generate "prometheusConfig.yaml" cfg.prometheusConfig
  );

  checkedConfig =
    file:
    if cfg.checkConfig then
      pkgs.runCommand "checked-config" { nativeBuildInputs = [ cfg.package ]; } ''
        ln -s ${file} $out
        ${lib.escapeShellArgs startCLIList} -promscrape.config=${file} -dryRun
      ''
    else
      file;
in
{
  options.services.victoriametrics = {
    enable = lib.mkOption {
      type = lib.types.bool;
      default = false;
      description = ''
        Whether to enable VictoriaMetrics in single-node mode.

        VictoriaMetrics is a fast, cost-effective and scalable monitoring solution and time series database.
      '';
    };
    package = mkPackageOption pkgs "victoriametrics" { };

    listenAddress = mkOption {
      default = ":8428";
      type = types.str;
      description = ''
        TCP address to listen for incoming http requests.
      '';
    };

    stateDir = mkOption {
      type = types.str;
      default = "victoriametrics";
      description = ''
        Directory below `/var/lib` to store VictoriaMetrics metrics data.
        This directory will be created automatically using systemd's StateDirectory mechanism.
      '';
    };

    retentionPeriod = mkOption {
      type = types.nullOr types.str;
      default = null;
      example = "15d";
      description = ''
        How long to retain samples in storage.
        The minimum retentionPeriod is 24h or 1d. See also -retentionFilter
        The following optional suffixes are supported: s (second), h (hour), d (day), w (week), y (year).
        If suffix isn't set, then the duration is counted in months (default 1)
      '';
    };

    basicAuthUsername = lib.mkOption {
      default = null;
      type = lib.types.nullOr lib.types.str;
      description = ''
        Basic Auth username used to protect VictoriaMetrics instance by authorization
      '';
    };

    basicAuthPasswordFile = lib.mkOption {
      default = null;
      type = lib.types.nullOr lib.types.path;
      description = ''
        File that contains the Basic Auth password used to protect VictoriaMetrics instance by authorization
      '';
    };

    prometheusConfig = lib.mkOption {
      type = lib.types.submodule { freeformType = settingsFormat.type; };
      default = { };
      example = literalExpression ''
        {
          scrape_configs = [
            {
              job_name = "postgres-exporter";
              metrics_path = "/metrics";
              static_configs = [
                {
                  targets = ["1.2.3.4:9187"];
                  labels.type = "database";
                }
              ];
            }
            {
              job_name = "node-exporter";
              metrics_path = "/metrics";
              static_configs = [
                {
                  targets = ["1.2.3.4:9100"];
                  labels.type = "node";
                }
                {
                  targets = ["5.6.7.8:9100"];
                  labels.type = "node";
                }
              ];
            }
          ];
        }
      '';
      description = ''
        Config for prometheus style metrics.
        See the docs: <https://docs.victoriametrics.com/vmagent/#how-to-collect-metrics-in-prometheus-format>
        for more information.
      '';
    };

    extraOptions = mkOption {
      type = types.listOf types.str;
      default = [ ];
      example = literalExpression ''
        [
          "-loggerLevel=WARN"
        ]
      '';
      description = ''
        Extra options to pass to VictoriaMetrics. See the docs:
        <https://docs.victoriametrics.com/single-server-victoriametrics/#list-of-command-line-flags>
        or {command}`victoriametrics -help` for more information.
      '';
    };

    checkConfig = lib.mkOption {
      type = lib.types.bool;
      default = true;
      description = ''
        Check configuration.

        If you use credentials stored in external files (`environmentFile`, etc),
        they will not be visible  and it will report errors, despite a correct configuration.
      '';
    };
  };

  config = lib.mkIf cfg.enable {

    assertions = [
      {
        assertion =
          (cfg.basicAuthUsername == null && cfg.basicAuthPasswordFile == null)
          || (cfg.basicAuthUsername != null && cfg.basicAuthPasswordFile != null);
        message = "Both basicAuthUsername and basicAuthPasswordFile must be set together to enable basicAuth functionality, or neither should be set.";
      }
    ];

    systemd.services.victoriametrics = {
      description = "VictoriaMetrics time series database";
      wantedBy = [ "multi-user.target" ];
      after = [ "network.target" ];
      startLimitBurst = 5;

      serviceConfig = {
        ExecStart = lib.escapeShellArgs (
          startCLIList
          ++ lib.optionals (cfg.prometheusConfig != { }) [ "-promscrape.config=${prometheusConfigYml}" ]
          ++ lib.optional (cfg.basicAuthUsername != null) "-httpAuth.username=${cfg.basicAuthUsername}"
          ++ lib.optional (
            cfg.basicAuthPasswordFile != null
          ) "-httpAuth.password=file://%d/basic_auth_password"
        );

        DynamicUser = true;
        LoadCredential = lib.optionals (cfg.basicAuthPasswordFile != null) [
          "basic_auth_password:${cfg.basicAuthPasswordFile}"
        ];

        RestartSec = 1;
        Restart = "on-failure";
        RuntimeDirectory = "victoriametrics";
        RuntimeDirectoryMode = "0700";
        StateDirectory = cfg.stateDir;
        StateDirectoryMode = "0700";

        # Increase the limit to avoid errors like 'too many open files'  when merging small parts
        LimitNOFILE = 1048576;

        # Hardening
        DeviceAllow = [ "/dev/null rw" ];
        DevicePolicy = "strict";
        LockPersonality = true;
        MemoryDenyWriteExecute = true;
        NoNewPrivileges = true;
        PrivateDevices = true;
        PrivateTmp = true;
        PrivateUsers = true;
        ProtectClock = true;
        ProtectControlGroups = true;
        ProtectHome = true;
        ProtectHostname = true;
        ProtectKernelLogs = true;
        ProtectKernelModules = true;
        ProtectKernelTunables = true;
        ProtectProc = "invisible";
        ProtectSystem = "full";
        RemoveIPC = true;
        RestrictAddressFamilies = [
          "AF_INET"
          "AF_INET6"
          "AF_UNIX"
        ];
        RestrictNamespaces = true;
        RestrictRealtime = true;
        RestrictSUIDSGID = true;
        SystemCallArchitectures = "native";
        SystemCallFilter = [
          "@system-service"
          "~@privileged"
          "mincore"
        ];
      };

      postStart =
        let
          bindAddr =
            (lib.optionalString (lib.hasPrefix ":" cfg.listenAddress) "127.0.0.1") + cfg.listenAddress;
        in
        lib.mkBefore ''
          until ${lib.getBin pkgs.curl}/bin/curl -s -o /dev/null http://${bindAddr}/ping; do
            sleep 1;
          done
        '';
    };
  };
}