1{
2 lib,
3 pkgs,
4 config,
5 ...
6}:
7let
8 cfg = config.services.alloy;
9in
10{
11 meta = {
12 maintainers = with lib.maintainers; [
13 flokli
14 hbjydev
15 ];
16 };
17
18 options.services.alloy = {
19 enable = lib.mkEnableOption "Grafana Alloy";
20
21 package = lib.mkPackageOption pkgs "grafana-alloy" { };
22
23 configPath = lib.mkOption {
24 type = lib.types.path;
25 default = "/etc/alloy";
26 description = ''
27 Alloy configuration file/directory path.
28
29 We default to `/etc/alloy` here, and expect the user to configure a
30 configuration file via `environment.etc."alloy/config.alloy"`.
31
32 This allows config reload, contrary to specifying a store path.
33
34 All `.alloy` files in the same directory (ignoring subdirs) are also
35 honored and are added to `systemd.services.alloy.reloadTriggers` to
36 enable config reload during nixos-rebuild switch.
37
38 This can also point to another directory containing `*.alloy` files, or
39 a single Alloy file in the Nix store (at the cost of reload).
40
41 Component names must be unique across all Alloy configuration files, and
42 configuration blocks must not be repeated.
43
44 Alloy will continue to run if subsequent reloads of the configuration
45 file fail, potentially marking components as unhealthy depending on
46 the nature of the failure. When this happens, Alloy will continue
47 functioning in the last valid state.
48 '';
49 };
50
51 extraFlags = lib.mkOption {
52 type = with lib.types; listOf str;
53 default = [ ];
54 example = [
55 "--server.http.listen-addr=127.0.0.1:12346"
56 "--disable-reporting"
57 ];
58 description = ''
59 Extra command-line flags passed to {command}`alloy run`.
60
61 See <https://grafana.com/docs/alloy/latest/reference/cli/run/>
62 '';
63 };
64 };
65
66 config = lib.mkIf cfg.enable {
67 systemd.services.alloy = {
68 after = [ "network.target" ];
69 wantedBy = [ "multi-user.target" ];
70 reloadTriggers = lib.mapAttrsToList (_: v: v.source or null) (
71 lib.filterAttrs (n: _: lib.hasPrefix "alloy/" n && lib.hasSuffix ".alloy" n) config.environment.etc
72 );
73 serviceConfig = {
74 Restart = "always";
75 DynamicUser = true;
76 RestartSec = 2;
77 SupplementaryGroups = [
78 # allow to read the systemd journal for loki log forwarding
79 "systemd-journal"
80 ];
81 ExecStart = "${lib.getExe cfg.package} run ${cfg.configPath} ${lib.escapeShellArgs cfg.extraFlags}";
82 ExecReload = "${pkgs.coreutils}/bin/kill -SIGHUP $MAINPID";
83 ConfigurationDirectory = "alloy";
84 StateDirectory = "alloy";
85 WorkingDirectory = "%S/alloy";
86 Type = "simple";
87 };
88 };
89 };
90}