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