1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
{ nixpkgs, pkgs, ... }:

let
  nestedCgroupsExpr = config: pkgs.writeText "nested.nix" ''
    let utils = builtins.storePath ${config.system.build.extraUtils}; in
    derivation {
      name = "nested-cgroups";
      system = builtins.currentSystem;
      requiredSystemFeatures = [ "uid-range" ];
      PATH = "''${utils}/bin";
      builder = "''${utils}/bin/sh";
      args = [ "-c" "mount -t cgroup2 none /sys/fs/cgroup; mkdir -p /sys/fs/cgroup/demo; touch $out" ];
    }
  '';
in
{
  name = "cgroups";

  nodes =
    {
      host =
        { config, pkgs, ... }:
        { virtualisation.additionalPaths = [ pkgs.stdenvNoCC config.system.build.extraUtils ];
          virtualisation.writableStore = true;
          nix.extraOptions =
            ''
              extra-experimental-features = nix-command auto-allocate-uids cgroups
              auto-allocate-uids = true
              extra-system-features = uid-range
            '';
          nix.settings = {
            download-attempts = 1;
            use-cgroups = true;
          };
          nix.nixPath = [ "nixpkgs=${nixpkgs}" ];
        };
    };

  testScript = { nodes }: ''
    start_all()

    host.wait_for_unit("multi-user.target")

    # Start build in background
    host.execute("nix build --use-cgroups --auto-allocate-uids --file ${./hang.nix} >&2 &")
    pid = int(host.succeed("pgrep nix"))
    service = "/sys/fs/cgroup/system.slice/system-nix\\\\x2ddaemon.slice/nix-daemon@*.service"

    # Wait for cgroups to be created
    host.succeed(f"until [ -e {service}/supervisor ]; do sleep 1; done", timeout=30)
    host.succeed(f"until [ -e {service}/nix-build@* ]; do sleep 1; done", timeout=30)

    # Check that there aren't processes where there shouldn't be, and that there are where there should be
    host.succeed(f'[ -z "$(cat {service}/cgroup.procs)" ]')
    host.succeed(f'[ -n "$(cat {service}/supervisor/cgroup.procs)" ]')
    host.succeed(f'[ -n "$(cat {service}/nix-build@*/cgroup.procs)" ]')

    # Perform an interrupt
    host.execute(f"kill -SIGINT {pid}")

    # Check that there aren't any cgroups anymore, neither any state records
    host.succeed(f"until [ ! -e {service}/nix-build@* ]; do sleep 1; done", timeout=30)
    host.succeed("until [ ! -e /nix/var/nix/cgroups/nix-build@* ]; do sleep 1; done", timeout=30)

    # Check nested cgroup cleanup
    logs = host.succeed("nix-build ${nestedCgroupsExpr nodes.host} 2>&1 | tee /dev/stderr")
    assert "error: deleting cgroup" not in logs
  '';

}