about summary refs log tree commit diff
path: root/nix/modules/vm/default.nix
blob: 6352c8045f5f8f2f76ef52cfa681273f6ae358d6 (plain)
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
{
  config,
  lib,
  pkgs,
  ...
}:

let
  cfg = config.services.emile.r2wars-web;
in
with lib;
{
  options.services.emile.r2wars-web = {
    enable = mkEnableOption "Enable r2wars-web";

    # ip and port to listen on
    guest = mkOption {
      type = types.str;
      default = "vmnameone";
      example = "vmnameone";
      description = "The name of the vm";
    };
  };

  config = mkIf cfg.enable {
    systemd.services = lib.mapAttrs' (
      name: guest:
      lib.nameValuePair "libvirtd-guest-${name}" {
        after = [ "libvirtd.service" ];
        requires = [ "libvirtd.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>
                <os>
                  <type>hvm</type>
                </os>
                <memory unit="GiB">${guest.memory}</memory>
                <devices>
                  <disk type="volume">
                    <source volume="guest-${name}"/>
                    <target dev="vda" bus="virtio"/>
                  </disk>
                  <graphics type="spice" autoport="yes"/>
                  <input type="keyboard" bus="usb"/>
                  <interface type="direct">
                    <source dev="${hostNic}" mode="bridge"/>
                    <mac address="${guest.mac}"/>
                    <model type="virtio"/>
                  </interface>
                </devices>
                <features>
                  <acpi/>
                </features>
              </domain>
            '';
          in
          ''
            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
        '';
      }
    ) guests;
  };
}