1{
2 config,
3 lib,
4 pkgs,
5 ...
6}:
7let
8 cfg = config.services.telegraf;
9
10 settingsFormat = pkgs.formats.toml { };
11 configFile = settingsFormat.generate "config.toml" cfg.extraConfig;
12in
13{
14 ###### interface
15 options = {
16 services.telegraf = {
17 enable = lib.mkEnableOption "telegraf server";
18
19 package = lib.mkPackageOption pkgs "telegraf" { };
20
21 environmentFiles = lib.mkOption {
22 type = lib.types.listOf lib.types.path;
23 default = [ ];
24 example = [ "/run/keys/telegraf.env" ];
25 description = ''
26 File to load as environment file. Environment variables from this file
27 will be interpolated into the config file using envsubst with this
28 syntax: `$ENVIRONMENT` or `''${VARIABLE}`.
29 This is useful to avoid putting secrets into the nix store.
30 '';
31 };
32
33 extraConfig = lib.mkOption {
34 default = { };
35 description = "Extra configuration options for telegraf";
36 type = settingsFormat.type;
37 example = {
38 outputs.influxdb = {
39 urls = [ "http://localhost:8086" ];
40 database = "telegraf";
41 };
42 inputs.statsd = {
43 service_address = ":8125";
44 delete_timings = true;
45 };
46 };
47 };
48 };
49 };
50
51 ###### implementation
52 config = lib.mkIf config.services.telegraf.enable {
53 services.telegraf.extraConfig = {
54 inputs = { };
55 outputs = { };
56 };
57 systemd.services.telegraf =
58 let
59 finalConfigFile =
60 if config.services.telegraf.environmentFiles == [ ] then
61 configFile
62 else
63 "/var/run/telegraf/config.toml";
64 in
65 {
66 description = "Telegraf Agent";
67 wantedBy = [ "multi-user.target" ];
68 wants = [ "network-online.target" ];
69 after = [ "network-online.target" ];
70 path =
71 lib.optional (config.services.telegraf.extraConfig.inputs ? procstat) pkgs.procps
72 ++ lib.optional (config.services.telegraf.extraConfig.inputs ? ping) pkgs.iputils;
73 serviceConfig = {
74 EnvironmentFile = config.services.telegraf.environmentFiles;
75 ExecStartPre = lib.optional (config.services.telegraf.environmentFiles != [ ]) (
76 pkgs.writeShellScript "pre-start" ''
77 umask 077
78 ${pkgs.envsubst}/bin/envsubst -i "${configFile}" > /var/run/telegraf/config.toml
79 ''
80 );
81 ExecStart = "${cfg.package}/bin/telegraf -config ${finalConfigFile}";
82 ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
83 RuntimeDirectory = "telegraf";
84 User = "telegraf";
85 Group = "telegraf";
86 Restart = "on-failure";
87 # for ping probes
88 AmbientCapabilities = [ "CAP_NET_RAW" ];
89 };
90 };
91
92 users.users.telegraf = {
93 uid = config.ids.uids.telegraf;
94 group = "telegraf";
95 description = "telegraf daemon user";
96 };
97
98 users.groups.telegraf = { };
99 };
100}