1{ config, pkgs, lib, ... }:
2with lib;
3let
4 cfg = config.services.vmagent;
5 settingsFormat = pkgs.formats.json { };
6in {
7 options.services.vmagent = {
8 enable = mkEnableOption (lib.mdDoc "vmagent");
9
10 user = mkOption {
11 default = "vmagent";
12 type = types.str;
13 description = lib.mdDoc ''
14 User account under which vmagent runs.
15 '';
16 };
17
18 group = mkOption {
19 type = types.str;
20 default = "vmagent";
21 description = lib.mdDoc ''
22 Group under which vmagent runs.
23 '';
24 };
25
26 package = mkOption {
27 default = pkgs.vmagent;
28 defaultText = lib.literalMD "pkgs.vmagent";
29 type = types.package;
30 description = lib.mdDoc ''
31 vmagent package to use.
32 '';
33 };
34
35 dataDir = mkOption {
36 type = types.str;
37 default = "/var/lib/vmagent";
38 description = lib.mdDoc ''
39 The directory where vmagent stores its data files.
40 '';
41 };
42
43 remoteWriteUrl = mkOption {
44 default = "http://localhost:8428/api/v1/write";
45 type = types.str;
46 description = lib.mdDoc ''
47 The storage endpoint such as VictoriaMetrics
48 '';
49 };
50
51 prometheusConfig = mkOption {
52 type = lib.types.submodule { freeformType = settingsFormat.type; };
53 description = lib.mdDoc ''
54 Config for prometheus style metrics
55 '';
56 };
57
58 openFirewall = mkOption {
59 type = types.bool;
60 default = false;
61 description = lib.mdDoc ''
62 Whether to open the firewall for the default ports.
63 '';
64 };
65
66 extraArgs = mkOption {
67 type = types.listOf types.str;
68 default = [];
69 description = lib.mdDoc ''
70 Extra args to pass to `vmagent`. See the docs:
71 <https://docs.victoriametrics.com/vmagent.html#advanced-usage>
72 or {command}`vmagent -help` for more information.
73 '';
74 };
75 };
76
77 config = mkIf cfg.enable {
78 users.groups = mkIf (cfg.group == "vmagent") { vmagent = { }; };
79
80 users.users = mkIf (cfg.user == "vmagent") {
81 vmagent = {
82 group = cfg.group;
83 description = "vmagent daemon user";
84 home = cfg.dataDir;
85 isSystemUser = true;
86 };
87 };
88
89 networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ 8429 ];
90
91 systemd.services.vmagent = let
92 prometheusConfig = settingsFormat.generate "prometheusConfig.yaml" cfg.prometheusConfig;
93 in {
94 wantedBy = [ "multi-user.target" ];
95 after = [ "network.target" ];
96 description = "vmagent system service";
97 serviceConfig = {
98 User = cfg.user;
99 Group = cfg.group;
100 Type = "simple";
101 Restart = "on-failure";
102 WorkingDirectory = cfg.dataDir;
103 ExecStart = "${cfg.package}/bin/vmagent -remoteWrite.url=${cfg.remoteWriteUrl} -promscrape.config=${prometheusConfig} ${escapeShellArgs cfg.extraArgs}";
104 };
105 };
106
107 systemd.tmpfiles.rules =
108 [ "d '${cfg.dataDir}' 0755 ${cfg.user} ${cfg.group} -" ];
109 };
110}