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 = mkOption {
17 default = pkgs.telegraf;
18 defaultText = "pkgs.telegraf";
19 description = "Which telegraf derivation to use";
20 type = types.package;
21 };
22
23 environmentFiles = mkOption {
24 type = types.listOf types.path;
25 default = [];
26 example = "/run/keys/telegraf.env";
27 description = ''
28 File to load as environment file. Environment variables
29 from this file will be interpolated into the config file
30 using envsubst with this syntax:
31 <literal>$ENVIRONMENT ''${VARIABLE}</literal>
32 This is useful to avoid putting secrets into the nix store.
33 '';
34 };
35
36 extraConfig = mkOption {
37 default = {};
38 description = "Extra configuration options for telegraf";
39 type = settingsFormat.type;
40 example = {
41 outputs.influxdb = {
42 urls = ["http://localhost:8086"];
43 database = "telegraf";
44 };
45 inputs.statsd = {
46 service_address = ":8125";
47 delete_timings = true;
48 };
49 };
50 };
51 };
52 };
53
54
55 ###### implementation
56 config = mkIf config.services.telegraf.enable {
57 systemd.services.telegraf = let
58 finalConfigFile = if config.services.telegraf.environmentFiles == []
59 then configFile
60 else "/var/run/telegraf/config.toml";
61 in {
62 description = "Telegraf Agent";
63 wantedBy = [ "multi-user.target" ];
64 after = [ "network-online.target" ];
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 Restart = "on-failure";
77 # for ping probes
78 AmbientCapabilities = [ "CAP_NET_RAW" ];
79 };
80 };
81
82 users.users.telegraf = {
83 uid = config.ids.uids.telegraf;
84 description = "telegraf daemon user";
85 };
86 };
87}