aboutsummaryrefslogtreecommitdiff
path: root/modules/private/system/dilion/vms.nix
blob: 8d5a57bcb712ca615b57b07c17c97a0993d8e4fd (plain) (blame)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# inspired from https://nixos.wiki/wiki/Virtualization_in_NixOS
{ config, pkgs, lib, ... }@args:
let
  networks = {
    immae = {
      bridgeNumber = "1";
      ipRange = "192.168.100";
    };
  };
  guests = {
    caldance = {
      pool = "zfspool";
      cpus = "1";
      memory = "2";
      network = "immae";
      diskSize = "10GiB";
      extraDevicesXML = ''
        <filesystem type="mount">
          <source dir="/var/lib/caldance"/>
          <target dir="home"/>
        </filesystem>
      '';
    };
    buildbot = {
      pool = "zfspool";
      cpus = "1";
      memory = "3";
      network = "immae";
      diskSize = "10GiB";
      destroyVolumeOnExit = true;
      preStart = ''
        if ! ${pkgs.libvirt}/bin/virsh pool-info --pool niximages &> /dev/null; then
          pool-create-as --name niximages --type dir --target /etc/libvirtd/base-images/
        fi
        if ! ${pkgs.libvirt}/bin/virsh pool-info --pool buildbot-disks &> /dev/null; then
          mkdir -p /var/lib/libvirt/images/buildbot-disks
          pool-create-as --name buildbot-disks --type dir --target /var/lib/libvirt/images/buildbot-disks
        fi
      '';
    };
  };
  toImage = f: "${import ./vms/base_image.nix f (args // { myEnv = config.myEnv; })}/nixos.qcow2";
in
{
  environment.etc."libvirtd/base-images/nixos.qcow2".source = toImage ./vms/base_configuration.nix;
  environment.etc."libvirtd/base-images/buildbot.qcow2".source = toImage ./vms/buildbot_configuration.nix;
  systemd.services = lib.mapAttrs' (name: guest: lib.nameValuePair "libvirtd-guest-${name}" {
    after = [ "libvirtd.service" "libvirtd-network-${guest.network}.service" ];
    requires = [ "libvirtd.service" "libvirtd-network-${guest.network}.service" ];
    wantedBy = [ "multi-user.target" ];
    serviceConfig = {
      Type = "oneshot";
      RemainAfterExit = "yes";
    };
    script =
      let
        xml = pkgs.writeText "libvirt-guest-${name}.xml"
        ''
          <domain type="kvm">
            <name>${name}</name>
            <uuid>UUID</uuid>
            <memory unit="GiB">${guest.memory}</memory>
            <vcpu>${guest.cpus}</vcpu>
            <os>
              <type arch="x86_64">hvm</type>
            </os>
            <devices>
              <emulator>/run/current-system/sw/bin/qemu-system-x86_64</emulator>
              <disk type="volume">
                <source pool="${guest.pool}" volume="guest-${name}" />
                <target dev="vda" bus="virtio"/>
              </disk>
              ${guest.extraDevicesXML or ""}
              <input type="keyboard" bus="usb"/>
              <graphics type="vnc" port="-1" autoport="yes"/>
              <interface type="network">
                <source network="${guest.network}" />
              </interface>
            </devices>
            <features>
              <acpi/>
            </features>
          </domain>
        '';
      in
      guest.preStart or "" + ''
        if ! ${pkgs.libvirt}/bin/virsh vol-key 'guest-${name}' --pool ${guest.pool} &> /dev/null; then
          ${pkgs.libvirt}/bin/virsh vol-create-as --pool ${guest.pool} --name 'guest-${name}' --capacity '${guest.diskSize}'
          volume_path=$(${pkgs.libvirt}/bin/virsh vol-path --pool ${guest.pool} --vol 'guest-${name}')
          ${pkgs.qemu}/bin/qemu-img convert /etc/libvirtd/base-images/nixos.qcow2 $volume_path
        fi
        uuid="$(${pkgs.libvirt}/bin/virsh domuuid '${name}' || true)"
        ${pkgs.libvirt}/bin/virsh define <(sed "s/UUID/$uuid/" '${xml}')
        ${pkgs.libvirt}/bin/virsh start '${name}'
      '';
    preStop = ''
      ${pkgs.libvirt}/bin/virsh shutdown '${name}'
      let "timeout = $(date +%s) + 10"
      while [ "$(${pkgs.libvirt}/bin/virsh list --name | grep --count '^${name}$')" -gt 0 ]; do
        if [ "$(date +%s)" -ge "$timeout" ]; then
          # Meh, we warned it...
          ${pkgs.libvirt}/bin/virsh destroy '${name}'
        else
          # The machine is still running, let's give it some time to shut down
          sleep 0.5
        fi
      done
    '' + lib.optionalString (guest.destroyVolumeOnExit or false) ''
        if ${pkgs.libvirt}/bin/virsh vol-key 'guest-${name}' --pool ${guest.pool} &> /dev/null; then
          ${pkgs.libvirt}/bin/virsh vol-wipe --pool ${guest.pool} --vol 'guest-${name}' || true
          ${pkgs.libvirt}/bin/virsh vol-delete --pool ${guest.pool} --vol 'guest-${name}'
        fi
    '';
  }) guests // (lib.mapAttrs' (name: network: lib.nameValuePair "libvirtd-network-${name}" {
    after = [ "libvirtd.service" ];
    requires = [ "libvirtd.service" ];
    wantedBy = [ "multi-user.target" ];
    serviceConfig = {
      Type = "oneshot";
      RemainAfterExit = "yes";
    };
    script = let
      xml = pkgs.writeText "libvirt-network-${name}.xml" ''
        <network>
          <name>${name}</name>
          <uuid>UUID</uuid>
          <forward mode='nat' />
          <bridge name='virbr${network.bridgeNumber}' />
          <domain name='${name}' localOnly='yes'/>
          <ip address='${network.ipRange}.1' netmask='255.255.255.0'>
            <dhcp>
              <range start='${network.ipRange}.2' end='${network.ipRange}.254'/>
            </dhcp>
          </ip>
        </network>
      '';
    in ''
      uuid="$(${pkgs.libvirt}/bin/virsh net-uuid '${name}' || true)"
      ${pkgs.libvirt}/bin/virsh net-define <(sed "s/UUID/$uuid/" '${xml}')
      ${pkgs.libvirt}/bin/virsh net-start '${name}'
    '';
    preStop = ''
      ${pkgs.libvirt}/bin/virsh net-destroy '${name}'
    '';
  }) networks);
}