1 { config, lib, pkgs, ... }:
4 cfg = config.virtualisation.lxd.agent;
6 # the lxd agent is provided by the lxd daemon through a virtiofs or 9p mount
7 # this is a port of the distrobuilder lxd-agent generator
8 # https://github.com/lxc/distrobuilder/blob/f77300bf7d7d5707b08eaf8a434d647d1ba81b5d/generators/lxd-agent.go#L18-L55
10 PREFIX="/run/lxd_agent"
13 mount -t virtiofs config "$PREFIX/.mnt" >/dev/null 2>&1
17 modprobe 9pnet_virtio >/dev/null 2>&1 || true
18 mount -t 9p config "$PREFIX/.mnt" -o access=0,trans=virtio,size=1048576 >/dev/null 2>&1
22 umount -l "$PREFIX" >/dev/null 2>&1 || true
23 rmdir "$PREFIX" >/dev/null 2>&1 || true
28 # Setup the mount target.
29 umount -l "$PREFIX" >/dev/null 2>&1 || true
31 mount -t tmpfs tmpfs "$PREFIX" -o mode=0700,size=50M
32 mkdir -p "$PREFIX/.mnt"
35 mount_virtiofs || mount_9p || fail "Couldn't mount virtiofs or 9p, failing."
38 cp -Ra "$PREFIX/.mnt/"* "$PREFIX"
40 # Unmount the temporary mount.
45 chown -R root:root "$PREFIX"
49 virtualisation.lxd.agent.enable = lib.mkEnableOption "LXD agent";
52 config = lib.mkIf cfg.enable {
53 # https://github.com/lxc/distrobuilder/blob/f77300bf7d7d5707b08eaf8a434d647d1ba81b5d/generators/lxd-agent.go#L108-L125
54 systemd.services.lxd-agent = {
56 wantedBy = [ "multi-user.target" ];
57 before = [ "shutdown.target" ] ++ lib.optionals config.services.cloud-init.enable [
58 "cloud-init.target" "cloud-init.service" "cloud-init-local.service"
60 conflicts = [ "shutdown.target" ];
65 # allow `incus exec` to find system binaries
66 "/run/current-system/sw"
69 preStart = preStartScript;
71 # avoid killing nixos-rebuild switch when executed through lxc exec
72 restartIfChanged = false;
73 stopIfChanged = false;
76 Description = "LXD - agent";
77 Documentation = "https://documentation.ubuntu.com/lxd/en/latest";
78 ConditionPathExists = "/dev/virtio-ports/org.linuxcontainers.lxd";
79 DefaultDependencies = "no";
80 StartLimitInterval = "60";
81 StartLimitBurst = "10";
86 WorkingDirectory = "-/run/lxd_agent";
87 ExecStart = "/run/lxd_agent/lxd-agent";
88 Restart = "on-failure";
93 systemd.paths.lxd-agent = {
95 wantedBy = [ "multi-user.target" ];
96 pathConfig.PathExists = "/dev/virtio-ports/org.linuxcontainers.lxd";