Apply nixpkgs-fmt

This commit is contained in:
Jack O'Sullivan 2022-02-13 13:10:21 +00:00
parent 0f2c3b1f36
commit 7627395222
10 changed files with 603 additions and 585 deletions

View File

@ -1,29 +1,29 @@
{ lib, pkgs, inputs, ... }: { lib, pkgs, inputs, ... }:
{ {
fileSystems = { fileSystems = {
"/persist" = { "/persist" = {
device = "/dev/disk/by-label/persist"; device = "/dev/disk/by-label/persist";
fsType = "ext4"; fsType = "ext4";
neededForBoot = true; neededForBoot = true;
};
};
networking = { };
my = {
firewall = {
trustedInterfaces = [ "blah" ];
nat = {
externalInterface = "eth0";
forwardPorts = [
{
proto = "tcp";
sourcePort = 2222;
destination = "127.0.0.1:22";
}
];
}; };
}; };
server.enable = true;
networking = {}; };
}
my = {
firewall = {
trustedInterfaces = [ "blah" ];
nat = {
externalInterface = "eth0";
forwardPorts = [
{
proto = "tcp";
sourcePort = 2222;
destination = "127.0.0.1:22";
}
];
};
};
server.enable = true;
};
}

View File

@ -55,27 +55,32 @@
lib = pkgsFlakes.unstable.lib; lib = pkgsFlakes.unstable.lib;
pkgs' = mapAttrs (_: path: lib.my.mkPkgs path { overlays = [ libOverlay ]; }) pkgsFlakes; pkgs' = mapAttrs (_: path: lib.my.mkPkgs path { overlays = [ libOverlay ]; }) pkgsFlakes;
in { in
{
inherit lib; inherit lib;
nixosModules = mapAttrs (_: path: let path' = ./. + "/modules/${path}"; in { nixosModules = mapAttrs
_file = path'; (_: path:
imports = [ (import path') ]; let path' = ./. + "/modules/${path}"; in
}) { {
common = "common.nix"; _file = path';
build = "build.nix"; imports = [ (import path') ];
dynamic-motd = "dynamic-motd.nix"; })
tmproot = "tmproot.nix"; {
firewall = "firewall.nix"; common = "common.nix";
server = "server.nix"; build = "build.nix";
}; dynamic-motd = "dynamic-motd.nix";
tmproot = "tmproot.nix";
firewall = "firewall.nix";
server = "server.nix";
};
nixosConfigurations = import ./systems.nix { inherit lib pkgsFlakes inputs; modules = self.nixosModules; }; nixosConfigurations = import ./systems.nix { inherit lib pkgsFlakes inputs; modules = self.nixosModules; };
systems = mapAttrs (_: system: system.config.system.build.toplevel) self.nixosConfigurations; systems = mapAttrs (_: system: system.config.system.build.toplevel) self.nixosConfigurations;
vms = mapAttrs (_: system: system.config.my.build.devVM) self.nixosConfigurations; vms = mapAttrs (_: system: system.config.my.build.devVM) self.nixosConfigurations;
apps = apps =
let apps' = {} let apps' = { }
// addPrefix "vms/" (mapAttrs (name: vm: { type = "app"; program = "${vm}/bin/run-${name}-vm"; }) self.vms); // addPrefix "vms/" (mapAttrs (name: vm: { type = "app"; program = "${vm}/bin/run-${name}-vm"; }) self.vms);
in { x86_64-linux = apps'; }; in { x86_64-linux = apps'; };
@ -83,12 +88,13 @@
let let
pkgs = pkgs'.unstable.${system}; pkgs = pkgs'.unstable.${system};
flakePkg = f: f.defaultPackage.${system}; flakePkg = f: f.defaultPackage.${system};
in pkgs.mkShell { in
packages = map flakePkg [ pkgs.mkShell {
agenix packages = map flakePkg [
deploy-rs agenix
]; deploy-rs
} ];
); }
);
}; };
} }

View File

@ -1,32 +1,33 @@
{ lib, extendModules, modulesPath, baseModules, options, config, ... }: { lib, extendModules, modulesPath, baseModules, options, config, ... }:
let let
inherit (lib) mkOption; inherit (lib) mkOption;
inherit (lib.my) mkBoolOpt; inherit (lib.my) mkBoolOpt;
cfg = config.my.build; cfg = config.my.build;
asDevVM = extendModules { asDevVM = extendModules {
# TODO: Hack because this is kinda broken on 21.11 (https://github.com/NixOS/nixpkgs/issues/148343) # TODO: Hack because this is kinda broken on 21.11 (https://github.com/NixOS/nixpkgs/issues/148343)
specialArgs = { inherit baseModules; }; specialArgs = { inherit baseModules; };
modules = [ modules = [
"${modulesPath}/virtualisation/qemu-vm.nix" "${modulesPath}/virtualisation/qemu-vm.nix"
({ ... }: { ({ ... }: {
my.boot.isDevVM = true; my.boot.isDevVM = true;
}) })
]; ];
}; };
in { in
options.my = with lib.types; { {
boot.isDevVM = mkBoolOpt false; options.my = with lib.types; {
build = options.system.build; boot.isDevVM = mkBoolOpt false;
asDevVM = mkOption { build = options.system.build;
inherit (asDevVM) type; asDevVM = mkOption {
default = {}; inherit (asDevVM) type;
visible = "shallow"; default = { };
}; visible = "shallow";
}; };
};
config.my.build = { config.my.build = {
devVM = config.my.asDevVM.system.build.vm; devVM = config.my.asDevVM.system.build.vm;
}; };
} }

View File

@ -1,93 +1,95 @@
{ lib, pkgs, inputs, system, config, options, ... }: { lib, pkgs, inputs, system, config, options, ... }:
let let
inherit (lib) mkIf mkDefault mkAliasDefinitions; inherit (lib) mkIf mkDefault mkAliasDefinitions;
inherit (lib.my) mkOpt; inherit (lib.my) mkOpt;
in { in
options.my = with lib.types; { {
user = mkOpt (attrsOf anything) {}; options.my = with lib.types; {
}; user = mkOpt (attrsOf anything) { };
};
config = config =
let let
defaultUsername = "dev"; defaultUsername = "dev";
uname = config.my.user.name; uname = config.my.user.name;
in { in
my = { {
user = { my = {
name = mkDefault defaultUsername; user = {
isNormalUser = true; name = mkDefault defaultUsername;
uid = mkDefault 1000; isNormalUser = true;
extraGroups = mkDefault [ "wheel" ]; uid = mkDefault 1000;
password = mkDefault "hunter2"; # TODO: secrets... extraGroups = mkDefault [ "wheel" ];
}; password = mkDefault "hunter2"; # TODO: secrets...
};
time.timeZone = mkDefault "Europe/Dublin";
users = {
mutableUsers = false;
users.${uname} = mkAliasDefinitions options.my.user;
};
security = {
sudo.enable = mkDefault false;
doas = {
enable = mkDefault true;
wheelNeedsPassword = mkDefault false;
};
};
nix = {
package = inputs.nix.defaultPackage.${system};
extraOptions =
''
experimental-features = nix-command flakes ca-derivations
'';
};
nixpkgs = {
config = {
allowUnfree = true;
};
};
boot = {
# Use latest LTS release by default
kernelPackages = mkDefault pkgs.linuxKernel.packages.linux_5_15;
loader = {
efi = {
efiSysMountPoint = mkDefault "/boot";
canTouchEfiVariables = mkDefault false;
};
systemd-boot = {
enable = mkDefault true;
editor = mkDefault true;
consoleMode = mkDefault "max";
configurationLimit = mkDefault 10;
memtest86.enable = mkDefault true;
};
};
};
networking = {
useDHCP = mkDefault false;
enableIPv6 = mkDefault true;
};
environment.systemPackages = with pkgs; [
bash-completion
tree
vim
htop
iperf3
];
services.openssh = {
enable = true;
};
system = {
stateVersion = "21.11";
configurationRevision = with inputs; mkIf (self ? rev) self.rev;
}; };
}; };
}
time.timeZone = mkDefault "Europe/Dublin";
users = {
mutableUsers = false;
users.${uname} = mkAliasDefinitions options.my.user;
};
security = {
sudo.enable = mkDefault false;
doas = {
enable = mkDefault true;
wheelNeedsPassword = mkDefault false;
};
};
nix = {
package = inputs.nix.defaultPackage.${system};
extraOptions =
''
experimental-features = nix-command flakes ca-derivations
'';
};
nixpkgs = {
config = {
allowUnfree = true;
};
};
boot = {
# Use latest LTS release by default
kernelPackages = mkDefault pkgs.linuxKernel.packages.linux_5_15;
loader = {
efi = {
efiSysMountPoint = mkDefault "/boot";
canTouchEfiVariables = mkDefault false;
};
systemd-boot = {
enable = mkDefault true;
editor = mkDefault true;
consoleMode = mkDefault "max";
configurationLimit = mkDefault 10;
memtest86.enable = mkDefault true;
};
};
};
networking = {
useDHCP = mkDefault false;
enableIPv6 = mkDefault true;
};
environment.systemPackages = with pkgs; [
bash-completion
tree
vim
htop
iperf3
];
services.openssh = {
enable = true;
};
system = {
stateVersion = "21.11";
configurationRevision = with inputs; mkIf (self ? rev) self.rev;
};
};
}

View File

@ -1,24 +1,25 @@
{ lib, pkgs, config, ... }: { lib, pkgs, config, ... }:
let let
inherit (lib) optionalAttrs filterAttrs genAttrs mkIf mkDefault; inherit (lib) optionalAttrs filterAttrs genAttrs mkIf mkDefault;
inherit (lib.my) mkOpt mkBoolOpt; inherit (lib.my) mkOpt mkBoolOpt;
cfg = config.my.dynamic-motd; cfg = config.my.dynamic-motd;
scriptBin = pkgs.writeShellScript "dynamic-motd-script" cfg.script; scriptBin = pkgs.writeShellScript "dynamic-motd-script" cfg.script;
in { in
options.my.dynamic-motd = with lib.types; { {
enable = mkBoolOpt true; options.my.dynamic-motd = with lib.types; {
services = mkOpt (listOf str) [ "login" "ssh" ]; enable = mkBoolOpt true;
script = mkOpt (nullOr lines) null; services = mkOpt (listOf str) [ "login" "ssh" ];
}; script = mkOpt (nullOr lines) null;
};
config = mkIf (cfg.enable && cfg.script != null) { config = mkIf (cfg.enable && cfg.script != null) {
security.pam.services = genAttrs cfg.services (s: { security.pam.services = genAttrs cfg.services (s: {
text = mkDefault text = mkDefault
'' ''
session optional ${pkgs.pam}/lib/security/pam_exec.so stdout quiet ${scriptBin} session optional ${pkgs.pam}/lib/security/pam_exec.so stdout quiet ${scriptBin}
''; '';
}); });
}; };
} }

View File

@ -1,166 +1,167 @@
{ lib, options, config, ... }: { lib, options, config, ... }:
let let
inherit (lib) optionalString concatStringsSep concatMapStringsSep optionalAttrs mkIf mkDefault mkMerge mkOverride; inherit (lib) optionalString concatStringsSep concatMapStringsSep optionalAttrs mkIf mkDefault mkMerge mkOverride;
inherit (lib.my) parseIPPort mkOpt mkBoolOpt dummyOption; inherit (lib.my) parseIPPort mkOpt mkBoolOpt dummyOption;
cfg = config.my.firewall; cfg = config.my.firewall;
in { in
options.my.firewall = with lib.types; { {
enable = mkBoolOpt true; options.my.firewall = with lib.types; {
trustedInterfaces = options.networking.firewall.trustedInterfaces; enable = mkBoolOpt true;
tcp = { trustedInterfaces = options.networking.firewall.trustedInterfaces;
allowed = mkOpt (listOf (either port str)) [ "ssh" ]; tcp = {
}; allowed = mkOpt (listOf (either port str)) [ "ssh" ];
udp = {
allowed = mkOpt (listOf (either port str)) [];
};
extraRules = mkOpt lines "";
nat = with options.networking.nat; {
enable = mkBoolOpt true;
inherit externalInterface forwardPorts;
};
}; };
udp = {
allowed = mkOpt (listOf (either port str)) [ ];
};
extraRules = mkOpt lines "";
config = mkIf cfg.enable (mkMerge [ nat = with options.networking.nat; {
{ enable = mkBoolOpt true;
networking = { inherit externalInterface forwardPorts;
firewall.enable = false; };
nftables = { };
enable = true;
ruleset =
let
trusted' = "{ ${concatStringsSep ", " cfg.trustedInterfaces} }";
in
''
table inet filter {
chain wan-tcp {
${concatMapStringsSep "\n " (p: "tcp dport ${toString p} accept") cfg.tcp.allowed}
}
chain wan-udp {
${concatMapStringsSep "\n " (p: "udp dport ${toString p} accept") cfg.udp.allowed}
}
chain wan { config = mkIf cfg.enable (mkMerge [
ip6 nexthdr icmpv6 icmpv6 type { {
destination-unreachable, networking = {
packet-too-big, firewall.enable = false;
time-exceeded, nftables = {
parameter-problem, enable = true;
mld-listener-query, ruleset =
mld-listener-report, let
mld-listener-reduction, trusted' = "{ ${concatStringsSep ", " cfg.trustedInterfaces} }";
nd-router-solicit, in
nd-router-advert, ''
nd-neighbor-solicit, table inet filter {
nd-neighbor-advert, chain wan-tcp {
ind-neighbor-solicit, ${concatMapStringsSep "\n " (p: "tcp dport ${toString p} accept") cfg.tcp.allowed}
ind-neighbor-advert, }
mld2-listener-report, chain wan-udp {
echo-request ${concatMapStringsSep "\n " (p: "udp dport ${toString p} accept") cfg.udp.allowed}
} accept
ip protocol icmp icmp type {
destination-unreachable,
router-solicitation,
router-advertisement,
time-exceeded,
parameter-problem,
echo-request
} accept
ip protocol igmp accept
ip protocol tcp tcp flags & (fin|syn|rst|ack) == syn ct state new jump wan-tcp
ip protocol udp ct state new jump wan-udp
}
chain input {
type filter hook input priority 0; policy drop;
ct state established,related accept
ct state invalid drop
iif lo accept
${optionalString (cfg.trustedInterfaces != []) "iifname ${trusted'} accept\n"}
jump wan
}
chain forward {
type filter hook forward priority 0; policy drop;
${optionalString (cfg.trustedInterfaces != []) "\n iifname ${trusted'} accept\n"}
ct state related,established accept
}
chain output {
type filter hook output priority 0; policy accept;
}
} }
table nat { chain wan {
chain prerouting { ip6 nexthdr icmpv6 icmpv6 type {
type nat hook prerouting priority 0; destination-unreachable,
} packet-too-big,
time-exceeded,
parameter-problem,
mld-listener-query,
mld-listener-report,
mld-listener-reduction,
nd-router-solicit,
nd-router-advert,
nd-neighbor-solicit,
nd-neighbor-advert,
ind-neighbor-solicit,
ind-neighbor-advert,
mld2-listener-report,
echo-request
} accept
ip protocol icmp icmp type {
destination-unreachable,
router-solicitation,
router-advertisement,
time-exceeded,
parameter-problem,
echo-request
} accept
ip protocol igmp accept
chain postrouting { ip protocol tcp tcp flags & (fin|syn|rst|ack) == syn ct state new jump wan-tcp
type nat hook postrouting priority 100; ip protocol udp ct state new jump wan-udp
}
} }
${cfg.extraRules} chain input {
''; type filter hook input priority 0; policy drop;
};
ct state established,related accept
ct state invalid drop
iif lo accept
${optionalString (cfg.trustedInterfaces != []) "iifname ${trusted'} accept\n"}
jump wan
}
chain forward {
type filter hook forward priority 0; policy drop;
${optionalString (cfg.trustedInterfaces != []) "\n iifname ${trusted'} accept\n"}
ct state related,established accept
}
chain output {
type filter hook output priority 0; policy accept;
}
}
table nat {
chain prerouting {
type nat hook prerouting priority 0;
}
chain postrouting {
type nat hook postrouting priority 100;
}
}
${cfg.extraRules}
'';
}; };
} };
(mkIf cfg.nat.enable { }
assertions = [ (mkIf cfg.nat.enable {
{ assertions = [
assertion = (cfg.nat.forwardPorts != []) -> (cfg.nat.externalInterface != null); {
message = "my.firewall.nat.forwardPorts requires my.firewall.nat.externalInterface"; assertion = (cfg.nat.forwardPorts != [ ]) -> (cfg.nat.externalInterface != null);
message = "my.firewall.nat.forwardPorts requires my.firewall.nat.externalInterface";
}
];
# Yoinked from nixpkgs/nixos/modules/services/networking/nat.nix
boot = {
kernel.sysctl = {
"net.ipv4.conf.all.forwarding" = mkOverride 99 true;
"net.ipv4.conf.default.forwarding" = mkOverride 99 true;
} // optionalAttrs config.networking.enableIPv6 {
# Do not prevent IPv6 autoconfiguration.
# See <http://strugglers.net/~andy/blog/2011/09/04/linux-ipv6-router-advertisements-and-forwarding/>.
"net.ipv6.conf.all.accept_ra" = mkOverride 99 2;
"net.ipv6.conf.default.accept_ra" = mkOverride 99 2;
# Forward IPv6 packets.
"net.ipv6.conf.all.forwarding" = mkOverride 99 true;
"net.ipv6.conf.default.forwarding" = mkOverride 99 true;
};
};
my.firewall.extraRules =
let
makeFilter = f:
let
ipp = parseIPPort f.destination;
in
"ip${optionalString ipp.v6 "6"} daddr ${ipp.ip} ${f.proto} dport ${toString f.sourcePort} accept";
makeForward = f: "${f.proto} dport ${toString f.sourcePort} dnat to ${f.destination}";
in
''
table inet filter {
chain filter-port-forwards {
${concatMapStringsSep "\n " makeFilter cfg.nat.forwardPorts}
}
chain forward {
iifname ${cfg.nat.externalInterface} jump filter-port-forwards
}
} }
];
# Yoinked from nixpkgs/nixos/modules/services/networking/nat.nix table nat {
boot = { chain port-forward {
kernel.sysctl = { ${concatMapStringsSep "\n " makeForward cfg.nat.forwardPorts}
"net.ipv4.conf.all.forwarding" = mkOverride 99 true;
"net.ipv4.conf.default.forwarding" = mkOverride 99 true;
} // optionalAttrs config.networking.enableIPv6 {
# Do not prevent IPv6 autoconfiguration.
# See <http://strugglers.net/~andy/blog/2011/09/04/linux-ipv6-router-advertisements-and-forwarding/>.
"net.ipv6.conf.all.accept_ra" = mkOverride 99 2;
"net.ipv6.conf.default.accept_ra" = mkOverride 99 2;
# Forward IPv6 packets.
"net.ipv6.conf.all.forwarding" = mkOverride 99 true;
"net.ipv6.conf.default.forwarding" = mkOverride 99 true;
};
};
my.firewall.extraRules =
let
makeFilter = f:
let
ipp = parseIPPort f.destination;
in
"ip${optionalString ipp.v6 "6"} daddr ${ipp.ip} ${f.proto} dport ${toString f.sourcePort} accept";
makeForward = f: "${f.proto} dport ${toString f.sourcePort} dnat to ${f.destination}";
in
''
table inet filter {
chain filter-port-forwards {
${concatMapStringsSep "\n " makeFilter cfg.nat.forwardPorts}
}
chain forward {
iifname ${cfg.nat.externalInterface} jump filter-port-forwards
}
} }
chain prerouting {
table nat { iifname ${cfg.nat.externalInterface} jump port-forward
chain port-forward {
${concatMapStringsSep "\n " makeForward cfg.nat.forwardPorts}
}
chain prerouting {
iifname ${cfg.nat.externalInterface} jump port-forward
}
} }
''; }
}) '';
]); })
} ]);
}

View File

@ -1,10 +1,11 @@
{ config, lib, ... }: { config, lib, ... }:
let let
inherit (lib) mkIf; inherit (lib) mkIf;
inherit (lib.my) mkBoolOpt; inherit (lib.my) mkBoolOpt;
in { in
options.my.server.enable = mkBoolOpt false; {
config = mkIf config.my.server.enable { options.my.server.enable = mkBoolOpt false;
services.getty.autologinUser = config.my.user.name; config = mkIf config.my.server.enable {
}; services.getty.autologinUser = config.my.user.name;
} };
}

View File

@ -1,205 +1,206 @@
{ lib, pkgs, inputs, config, ... }: { lib, pkgs, inputs, config, ... }:
let let
inherit (builtins) elem; inherit (builtins) elem;
inherit (lib) concatStringsSep concatMap concatMapStringsSep mkIf mkDefault mkMerge mkForce mkVMOverride; inherit (lib) concatStringsSep concatMap concatMapStringsSep mkIf mkDefault mkMerge mkForce mkVMOverride;
inherit (lib.my) mkOpt mkBoolOpt mkVMOverride' dummyOption; inherit (lib.my) mkOpt mkBoolOpt mkVMOverride' dummyOption;
cfg = config.my.tmproot; cfg = config.my.tmproot;
showUnsaved = showUnsaved =
'' ''
#!${pkgs.python310}/bin/python #!${pkgs.python310}/bin/python
import stat import stat
import sys import sys
import os import os
ignored = [ ignored = [
${concatStringsSep ",\n " (map (p: "'${p}'") cfg.unsaved.ignore)} ${concatStringsSep ",\n " (map (p: "'${p}'") cfg.unsaved.ignore)}
] ]
base = '/' base = '/'
base_dev = os.stat(base).st_dev base_dev = os.stat(base).st_dev
def recurse(p, link=None): def recurse(p, link=None):
try: try:
for ignore in ignored: for ignore in ignored:
if p.startswith(ignore): if p.startswith(ignore):
return
st = os.lstat(p)
if st.st_dev != base_dev:
return return
if stat.S_ISLNK(st.st_mode): st = os.lstat(p)
target = os.path.realpath(p, strict=False) if st.st_dev != base_dev:
if os.access(target, os.F_OK): return
recurse(target, link=p)
return if stat.S_ISLNK(st.st_mode):
elif stat.S_ISDIR(st.st_mode): target = os.path.realpath(p, strict=False)
for e in os.listdir(p): if os.access(target, os.F_OK):
recurse(os.path.join(p, e)) recurse(target, link=p)
return return
elif stat.S_ISDIR(st.st_mode):
for e in os.listdir(p):
recurse(os.path.join(p, e))
return
print(link or p) print(link or p)
except PermissionError as ex: except PermissionError as ex:
print(f'{p}: {ex.strerror}', file=sys.stderr) print(f'{p}: {ex.strerror}', file=sys.stderr)
recurse(base) recurse(base)
''; '';
rootDef = { rootDef = {
device = "yeet"; device = "yeet";
fsType = "tmpfs"; fsType = "tmpfs";
options = [ "size=${cfg.size}" ]; options = [ "size=${cfg.size}" ];
};
in
{
imports = [ inputs.impermanence.nixosModule ];
options = with lib.types; {
my.tmproot = {
enable = mkBoolOpt true;
persistDir = mkOpt str "/persist";
size = mkOpt str "2G";
unsaved = {
showMotd = mkBoolOpt true;
ignore = mkOpt (listOf str) [ ];
};
}; };
in {
imports = [ inputs.impermanence.nixosModule ];
options = with lib.types; { # Forward declare options that won't exist until the VM module is actually imported
my.tmproot = { virtualisation = {
enable = mkBoolOpt true; diskImage = dummyOption;
persistDir = mkOpt str "/persist"; };
size = mkOpt str "2G"; };
unsaved = {
showMotd = mkBoolOpt true; config = mkIf cfg.enable (mkMerge [
ignore = mkOpt (listOf str) []; {
}; assertions = [
{
assertion = config.fileSystems ? "${cfg.persistDir}";
message = "The 'fileSystems' option does not specify your persistence file system (${cfg.persistDir}).";
}
{
# I mean you probably _could_, but if you're doing tmproot... come on
assertion = !config.users.mutableUsers;
message = "users.mutableUsers is incompatible with tmproot";
}
];
my.tmproot.unsaved.ignore = [
"/tmp"
# setup-etc.pl will create this for us
"/etc/NIXOS"
# Once mutableUsers is disabled, we should be all clear here
"/etc/passwd"
"/etc/group"
"/etc/shadow"
"/etc/subuid"
"/etc/subgid"
# Lock file for /etc/{passwd,shadow}
"/etc/.pwd.lock"
# systemd last updated? I presume they'll get updated on boot...
"/etc/.updated"
"/var/.updated"
# Specifies obsolete files that should be deleted on activation - we'll never have those!
"/etc/.clean"
];
environment.systemPackages = [
(pkgs.writeScriptBin "tmproot-unsaved" showUnsaved)
];
# Catch non-existent source directories that are needed for boot (see `pathsNeededForBoot` in
# nixos/lib/util.nix). We do this by monkey-patching the `waitDevice` function that would otherwise hang.
boot.initrd.postDeviceCommands =
''
ensurePersistSource() {
[ -e "/mnt-root$1" ] && return
echo "Persistent source directory $1 does not exist, creating..."
install -dm "$2" "/mnt-root$1" || fail
}
_waitDevice() {
local device="$1"
${concatMapStringsSep " || \\\n " (d:
let
sourceDir = "${d.persistentStoragePath}${d.directory}";
in
''([ "$device" = "/mnt-root${sourceDir}" ] && ensurePersistSource "${sourceDir}" "${d.mode}")'')
config.environment.persistence."${cfg.persistDir}".directories}
waitDevice "$@"
}
type waitDevice > /dev/null || (echo "waitDevice is missing!"; fail)
alias waitDevice=_waitDevice
'';
environment.persistence."${cfg.persistDir}" = {
hideMounts = mkDefault true;
directories = [
"/var/log"
# In theory we'd include only the files needed individually (i.e. the {U,G}ID map files that track deleted
# users and groups), but `update-users-groups.pl` actually deletes the original files for "atomic update".
# Also the script runs before impermanence does.
"/var/lib/nixos"
"/var/lib/systemd"
];
files = [
"/etc/machine-id"
];
}; };
# Forward declare options that won't exist until the VM module is actually imported my.dynamic-motd.script = mkIf cfg.unsaved.showMotd
''
tmprootUnsaved() {
local count="$(tmproot-unsaved | wc -l)"
[ $count -eq 0 ] && return
echo
echo -e "\t\e[31;1;4mWarning:\e[0m $count file(s) on / will be lost on shutdown!"
echo -e '\tTo see them, run `tmproot-unsaved` as root.'
echo -e '\tAdd these files to `environment.persistence."${cfg.persistDir}"` to keep them!'
echo -e '\tOtherwise, they can be ignored by adding to `my.tmproot.unsaved.ignore`.'
echo
}
tmprootUnsaved
'';
fileSystems."/" = rootDef;
virtualisation = { virtualisation = {
diskImage = dummyOption; diskImage = "./.vms/${config.system.name}-persist.qcow2";
}; };
}; }
(mkIf config.services.openssh.enable {
environment.persistence."${cfg.persistDir}".files =
concatMap (k: [ k.path "${k.path}.pub" ]) config.services.openssh.hostKeys;
})
(mkIf config.networking.resolvconf.enable {
my.tmproot.unsaved.ignore = [ "/etc/resolv.conf" ];
})
(mkIf config.security.doas.enable {
my.tmproot.unsaved.ignore = [ "/etc/doas.conf" ];
})
(mkIf config.my.boot.isDevVM {
my.tmproot.unsaved.ignore = [ "/nix" ];
config = mkIf cfg.enable (mkMerge [ fileSystems = mkVMOverride {
{ "/" = mkVMOverride' rootDef;
assertions = [ # Hijack the "root" device for persistence in the VM
{ "${cfg.persistDir}" = {
assertion = config.fileSystems ? "${cfg.persistDir}"; device = config.virtualisation.bootDevice;
message = "The 'fileSystems' option does not specify your persistence file system (${cfg.persistDir})."; neededForBoot = true;
}
{
# I mean you probably _could_, but if you're doing tmproot... come on
assertion = !config.users.mutableUsers;
message = "users.mutableUsers is incompatible with tmproot";
}
];
my.tmproot.unsaved.ignore = [
"/tmp"
# setup-etc.pl will create this for us
"/etc/NIXOS"
# Once mutableUsers is disabled, we should be all clear here
"/etc/passwd"
"/etc/group"
"/etc/shadow"
"/etc/subuid"
"/etc/subgid"
# Lock file for /etc/{passwd,shadow}
"/etc/.pwd.lock"
# systemd last updated? I presume they'll get updated on boot...
"/etc/.updated"
"/var/.updated"
# Specifies obsolete files that should be deleted on activation - we'll never have those!
"/etc/.clean"
];
environment.systemPackages = [
(pkgs.writeScriptBin "tmproot-unsaved" showUnsaved)
];
# Catch non-existent source directories that are needed for boot (see `pathsNeededForBoot` in
# nixos/lib/util.nix). We do this by monkey-patching the `waitDevice` function that would otherwise hang.
boot.initrd.postDeviceCommands =
''
ensurePersistSource() {
[ -e "/mnt-root$1" ] && return
echo "Persistent source directory $1 does not exist, creating..."
install -dm "$2" "/mnt-root$1" || fail
}
_waitDevice() {
local device="$1"
${concatMapStringsSep " || \\\n " (d:
let
sourceDir = "${d.persistentStoragePath}${d.directory}";
in
''([ "$device" = "/mnt-root${sourceDir}" ] && ensurePersistSource "${sourceDir}" "${d.mode}")'')
config.environment.persistence."${cfg.persistDir}".directories}
waitDevice "$@"
}
type waitDevice > /dev/null || (echo "waitDevice is missing!"; fail)
alias waitDevice=_waitDevice
'';
environment.persistence."${cfg.persistDir}" = {
hideMounts = mkDefault true;
directories = [
"/var/log"
# In theory we'd include only the files needed individually (i.e. the {U,G}ID map files that track deleted
# users and groups), but `update-users-groups.pl` actually deletes the original files for "atomic update".
# Also the script runs before impermanence does.
"/var/lib/nixos"
"/var/lib/systemd"
];
files = [
"/etc/machine-id"
];
}; };
};
my.dynamic-motd.script = mkIf cfg.unsaved.showMotd })
'' ]);
tmprootUnsaved() { }
local count="$(tmproot-unsaved | wc -l)"
[ $count -eq 0 ] && return
echo
echo -e "\t\e[31;1;4mWarning:\e[0m $count file(s) on / will be lost on shutdown!"
echo -e '\tTo see them, run `tmproot-unsaved` as root.'
echo -e '\tAdd these files to `environment.persistence."${cfg.persistDir}"` to keep them!'
echo -e '\tOtherwise, they can be ignored by adding to `my.tmproot.unsaved.ignore`.'
echo
}
tmprootUnsaved
'';
fileSystems."/" = rootDef;
virtualisation = {
diskImage = "./.vms/${config.system.name}-persist.qcow2";
};
}
(mkIf config.services.openssh.enable {
environment.persistence."${cfg.persistDir}".files =
concatMap (k: [ k.path "${k.path}.pub" ]) config.services.openssh.hostKeys;
})
(mkIf config.networking.resolvconf.enable {
my.tmproot.unsaved.ignore = [ "/etc/resolv.conf" ];
})
(mkIf config.security.doas.enable {
my.tmproot.unsaved.ignore = [ "/etc/doas.conf" ];
})
(mkIf config.my.boot.isDevVM {
my.tmproot.unsaved.ignore = [ "/nix" ];
fileSystems = mkVMOverride {
"/" = mkVMOverride' rootDef;
# Hijack the "root" device for persistence in the VM
"${cfg.persistDir}" = {
device = config.virtualisation.bootDevice;
neededForBoot = true;
};
};
})
]);
}

View File

@ -1,35 +1,38 @@
{ lib, pkgsFlakes, inputs, modules }: { lib, pkgsFlakes, inputs, modules }:
let let
inherit (builtins) attrValues mapAttrs; inherit (builtins) attrValues mapAttrs;
inherit (lib) mkDefault; inherit (lib) mkDefault;
mkSystem = name: { mkSystem =
name: {
system, system,
nixpkgs ? "unstable", nixpkgs ? "unstable",
config, config,
}: }:
let let
pkgsFlake = pkgsFlakes.${nixpkgs}; pkgsFlake = pkgsFlakes.${nixpkgs};
lib = pkgsFlake.lib; lib = pkgsFlake.lib;
# TODO: This is mostly yoinked from nixpkgs/flake.nix master (as of 2022/02/11) since 21.11's version has hacky # TODO: This is mostly yoinked from nixpkgs/flake.nix master (as of 2022/02/11) since 21.11's version has hacky
# vm build stuff that breaks our impl. REMOVE WHEN 22.05 IS OUT! # vm build stuff that breaks our impl. REMOVE WHEN 22.05 IS OUT!
nixosSystem' = args: nixosSystem' = args:
import "${pkgsFlake}/nixos/lib/eval-config.nix" (args // { import "${pkgsFlake}/nixos/lib/eval-config.nix" (args // {
modules = args.modules ++ [ { modules = args.modules ++ [{
system.nixos.versionSuffix = system.nixos.versionSuffix =
".${lib.substring 0 8 pkgsFlake.lastModifiedDate}.${pkgsFlake.shortRev}"; ".${lib.substring 0 8 pkgsFlake.lastModifiedDate}.${pkgsFlake.shortRev}";
system.nixos.revision = pkgsFlake.rev; system.nixos.revision = pkgsFlake.rev;
} ]; }];
}); });
in nixosSystem' { in
inherit lib system; nixosSystem' {
specialArgs = { inherit inputs system; }; inherit lib system;
modules = attrValues modules ++ [ { networking.hostName = mkDefault name; } config ]; specialArgs = { inherit inputs system; };
}; modules = attrValues modules ++ [ { networking.hostName = mkDefault name; } config ];
in mapAttrs mkSystem {
colony = {
system = "x86_64-linux";
nixpkgs = "stable";
config = boxes/colony.nix;
}; };
} in
mapAttrs mkSystem {
colony = {
system = "x86_64-linux";
nixpkgs = "stable";
config = boxes/colony.nix;
};
}

View File

@ -1,32 +1,34 @@
{ lib }: { lib }:
let let
inherit (builtins) replaceStrings elemAt; inherit (builtins) replaceStrings elemAt;
inherit (lib) genAttrs mapAttrs' types mkOption mkOverride; inherit (lib) genAttrs mapAttrs' types mkOption mkOverride;
inherit (lib.flake) defaultSystems; inherit (lib.flake) defaultSystems;
in rec { in
addPrefix = prefix: mapAttrs' (n: v: { name = "${prefix}${n}"; value = v; }); rec {
# Yoinked from nixpkgs/nixos/modules/services/networking/nat.nix addPrefix = prefix: mapAttrs' (n: v: { name = "${prefix}${n}"; value = v; });
isIPv6 = ip: builtins.length (lib.splitString ":" ip) > 2; # Yoinked from nixpkgs/nixos/modules/services/networking/nat.nix
parseIPPort = ipp: isIPv6 = ip: builtins.length (lib.splitString ":" ip) > 2;
let parseIPPort = ipp:
v6 = isIPv6 ipp; let
matchIP = if v6 then "[[]([0-9a-fA-F:]+)[]]" else "([0-9.]+)"; v6 = isIPv6 ipp;
m = builtins.match "${matchIP}:([0-9-]+)" ipp; matchIP = if v6 then "[[]([0-9a-fA-F:]+)[]]" else "([0-9.]+)";
checked = v: if m == null then throw "bad ip:ports `${ipp}'" else v; m = builtins.match "${matchIP}:([0-9-]+)" ipp;
in { checked = v: if m == null then throw "bad ip:ports `${ipp}'" else v;
inherit v6; in
ip = checked (elemAt m 0); {
ports = checked (replaceStrings ["-"] [":"] (elemAt m 1)); inherit v6;
}; ip = checked (elemAt m 0);
ports = checked (replaceStrings ["-"] [":"] (elemAt m 1));
mkPkgs = path: args: genAttrs defaultSystems (system: import path (args // { inherit system; }));
mkOpt = type: default: mkOption { inherit type default; };
mkBoolOpt = default: mkOption {
inherit default;
type = types.bool;
example = true;
}; };
mkVMOverride' = mkOverride 9;
dummyOption = mkOption {}; mkPkgs = path: args: genAttrs defaultSystems (system: import path (args // { inherit system; }));
}
mkOpt = type: default: mkOption { inherit type default; };
mkBoolOpt = default: mkOption {
inherit default;
type = types.bool;
example = true;
};
mkVMOverride' = mkOverride 9;
dummyOption = mkOption { };
}