# inspired from https://nixos.wiki/wiki/Virtualization_in_NixOS
{ config, pkgs, lib, ... }@args:
let
+ pools = {
+ niximages = {
+ type = "dir";
+ target = "/etc/libvirtd/base-images";
+ };
+ buildbot-disks = rec {
+ preStart = ''
+ mkdir -p ${target}
+ '';
+ type = "dir";
+ target = "/var/lib/libvirt/images/buildbot-disks";
+ };
+ zfspool = {
+ # pool-define-as --name zfspool --source-name zpool/libvirt --type zfs
+ type = "zfs";
+ xml = ''
+ <source>
+ <name>zpool/libvirt</name>
+ </source>
+ '';
+ };
+ };
networks = {
immae = {
bridgeNumber = "1";
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";
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" ];
+ after = [ "libvirtd.service" "libvirtd-pool-${guest.pool}.service" "libvirtd-network-${guest.network}.service" ];
+ requires = [ "libvirtd.service" "libvirtd-pool-${guest.pool}.service" "libvirtd-network-${guest.network}.service" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "oneshot";
preStop = ''
${pkgs.libvirt}/bin/virsh net-destroy '${name}'
'';
- }) networks);
+ }) networks) // (lib.mapAttrs' (name: pool: lib.nameValuePair "libvirtd-pool-${name}" {
+ after = [ "libvirtd.service" ];
+ requires = [ "libvirtd.service" ];
+ wantedBy = [ "multi-user.target" ];
+ serviceConfig = {
+ Type = "oneshot";
+ RemainAfterExit = "yes";
+ };
+ script = let
+ xml = pkgs.writeText "libvirt-pool-${name}.xml" ''
+ <pool type="${pool.type}">
+ <name>${name}</name>
+ <uuid>UUID</uuid>
+ ${pool.xml or ""}
+ ${if pool ? target then ''
+ <target>
+ <path>${pool.target}</path>
+ </target>
+ '' else ""}
+ </pool>
+ '';
+ in pool.preStart or "" + ''
+ uuid="$(${pkgs.libvirt}/bin/virsh pool-uuid '${name}' || true)"
+ ${pkgs.libvirt}/bin/virsh pool-define <(sed "s/UUID/$uuid/" '${xml}')
+ ${pkgs.libvirt}/bin/virsh pool-start '${name}' || true
+ '';
+ }) pools);
}