summaryrefslogtreecommitdiff
path: root/custom/libvirtd-guests.nix
blob: 36ffa3c9ea50f13a2c0433cc6c4c138cf51c2e85 (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
{ config, pkgs, lib, utils, ... }:

with utils;
with lib;

let
  cfg = virtualisation.libvirtd;

  textfile = with types; coercedTo str (pkgs.writeText "spec.xml") path;

  domain = {
    options = {
      xml = mkOption {
        type = 
      };

      autostart = mkOption {
        type = types.bool;
        default = true;
      };
    };
  };

  define = let
    python = pkgs.python27.withPackages (ps: with ps; [ libvirt ]);
  in dCfg: ''
    #!${python}/bin/python

    import libvirt
    import sys

    conn = libvirt.open(None);
    if conn == None:
      print('Failed to open connection to hypervisor', file=sys.stderr)
      sys.exit(1)

    xmlFile = open(${escapeShellArg dCfg.xml}, 'r')
    dom = conn.defineXML(xmlFile.read(), 0)
    xmlFile.close()
    if dom == None:
      print('Failed to define domain', file=sys.stderr)
      sys.exit(1)

    dom.setAutostart(${if dCfg.autostart then "1" else "0"})

    conn.close()
    sys.exit(0)
  '';
in {
  options = {
    virtualisation.libvirtd = {
      domains = mkOption {
        type = with types; attrsOf (submodule guest);
        default = {};
      };
    };
  };

  config = mkIf (cfg.domains != {}) {
    systemd.services."libvirtd-guest@" = {
      after = [ "libvirtd.service" ];
      bindsTo = [ "libvirtd.service" ];

      before = [ "libvirt-guests.service" ];

      serviceConfig = {
        Type = "oneshot";
        RemainAfterExit = true;
      };

      path = with pkgs; [ libvirtd ];
    };

    systemd.services = mapAttrs' (dName: dCfg: nameValuePair ("libvirtd-guest@" + escapeSystemdPath dName + ".service") {
      serviceConfig = {
        ExecStart = pkgs.writeScript (dName + ".py") (define dCfg);
      };
    }) cfg.domains;

    systemd.services."libvirt-guests.service" = {
      wants = mapAttrsToList (dName: dCfg: "libvirtd-guest@" + escapeSystemdPath dName + ".service") cfg.domains;
    };
  };
}