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 (lib.mdDoc "telegraf server");
15
16 package = mkOption {
17 default = pkgs.telegraf;
18 defaultText = literalExpression "pkgs.telegraf";
19 description = lib.mdDoc "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 = lib.mdDoc ''
28 File to load as environment file. Environment variables from this file
29 will be interpolated into the config file using envsubst with this
30 syntax: `$ENVIRONMENT` or `''${VARIABLE}`.
31 This is useful to avoid putting secrets into the nix store.
32 '';
33 };
34
35 extraConfig = mkOption {
36 default = {};
37 description = lib.mdDoc "Extra configuration options for telegraf";
38 type = settingsFormat.type;
39 example = {
40 outputs.influxdb = {
41 urls = ["http://localhost:8086"];
42 database = "telegraf";
43 };
44 inputs.statsd = {
45 service_address = ":8125";
46 delete_timings = true;
47 };
48 };
49 };
50 };
51 };
52
53
54 ###### implementation
55 config = mkIf config.services.telegraf.enable {
56 systemd.services.telegraf = let
57 finalConfigFile = if config.services.telegraf.environmentFiles == []
58 then configFile
59 else "/var/run/telegraf/config.toml";
60 in {
61 description = "Telegraf Agent";
62 wantedBy = [ "multi-user.target" ];
63 after = [ "network-online.target" ];
64 serviceConfig = {
65 EnvironmentFile = config.services.telegraf.environmentFiles;
66 ExecStartPre = lib.optional (config.services.telegraf.environmentFiles != [])
67 (pkgs.writeShellScript "pre-start" ''
68 umask 077
69 ${pkgs.envsubst}/bin/envsubst -i "${configFile}" > /var/run/telegraf/config.toml
70 '');
71 ExecStart="${cfg.package}/bin/telegraf -config ${finalConfigFile}";
72 ExecReload="${pkgs.coreutils}/bin/kill -HUP $MAINPID";
73 RuntimeDirectory = "telegraf";
74 User = "telegraf";
75 Group = "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 group = "telegraf";
85 description = "telegraf daemon user";
86 };
87
88 users.groups.telegraf = {};
89 };
90}