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