1{ config, lib, pkgs, options }:
2
3with lib;
4
5let
6 cfg = config.services.prometheus.exporters.postgres;
7in
8{
9 port = 9187;
10 extraOpts = {
11 telemetryPath = mkOption {
12 type = types.str;
13 default = "/metrics";
14 description = lib.mdDoc ''
15 Path under which to expose metrics.
16 '';
17 };
18 dataSourceName = mkOption {
19 type = types.str;
20 default = "user=postgres database=postgres host=/run/postgresql sslmode=disable";
21 example = "postgresql://username:password@localhost:5432/postgres?sslmode=disable";
22 description = lib.mdDoc ''
23 Accepts PostgreSQL URI form and key=value form arguments.
24 '';
25 };
26 runAsLocalSuperUser = mkOption {
27 type = types.bool;
28 default = false;
29 description = lib.mdDoc ''
30 Whether to run the exporter as the local 'postgres' super user.
31 '';
32 };
33
34 # TODO perhaps LoadCredential would be more appropriate
35 environmentFile = mkOption {
36 type = types.nullOr types.path;
37 default = null;
38 example = "/root/prometheus-postgres-exporter.env";
39 description = lib.mdDoc ''
40 Environment file as defined in {manpage}`systemd.exec(5)`.
41
42 Secrets may be passed to the service without adding them to the
43 world-readable Nix store, by specifying placeholder variables as
44 the option value in Nix and setting these variables accordingly in the
45 environment file.
46
47 Environment variables from this file will be interpolated into the
48 config file using envsubst with this syntax:
49 `$ENVIRONMENT ''${VARIABLE}`
50
51 The main use is to set the DATA_SOURCE_NAME that contains the
52 postgres password
53
54 note that contents from this file will override dataSourceName
55 if you have set it from nix.
56
57 ```
58 # Content of the environment file
59 DATA_SOURCE_NAME=postgresql://username:password@localhost:5432/postgres?sslmode=disable
60 ```
61
62 Note that this file needs to be available on the host on which
63 this exporter is running.
64 '';
65 };
66
67 };
68 serviceOpts = {
69 environment.DATA_SOURCE_NAME = cfg.dataSourceName;
70 serviceConfig = {
71 DynamicUser = false;
72 User = mkIf cfg.runAsLocalSuperUser (mkForce "postgres");
73 EnvironmentFile = mkIf (cfg.environmentFile != null) [ cfg.environmentFile ];
74 ExecStart = ''
75 ${pkgs.prometheus-postgres-exporter}/bin/postgres_exporter \
76 --web.listen-address ${cfg.listenAddress}:${toString cfg.port} \
77 --web.telemetry-path ${cfg.telemetryPath} \
78 ${concatStringsSep " \\\n " cfg.extraFlags}
79 '';
80 RestrictAddressFamilies = [
81 # Need AF_UNIX to collect data
82 "AF_UNIX"
83 ];
84 };
85 };
86}