Skip to content

Commit c410022

Browse files
committed
Provide consistent MAC addresses for macvlans
This gives DHCP a consistent handle so the address won't change every time I reboot.
1 parent bd5c22f commit c410022

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

lib/define-host.nix

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,19 @@ let
1313
inherit (config.lab) domain datacenter;
1414
home = config.home-manager.users.root;
1515

16+
# Chunk a list into sublists of a specified size.
17+
#
18+
# chunkBy 2 [ 1 2 3 4 ] -> [ [ 1 2 ] [ 3 4 ] ]
19+
chunkBy =
20+
size: list:
21+
if list == [ ] then
22+
[ ]
23+
else
24+
[
25+
(lib.take size list)
26+
]
27+
++ chunkBy size (lib.drop size list);
28+
1629
# Proxy all network traffic through a macvlan interface. This allows the
1730
# host to communicate with containers using macvlans and vice versa.
1831
#
@@ -28,6 +41,40 @@ let
2841
mode = "bridge";
2942
interface = config.lab.host.interface;
3043
};
44+
45+
# Provide a stable MAC address to preserve the DHCP lease.
46+
interfaces.mv-primary.macAddress = lib.pipe config.networking.hostName [
47+
# Use the hostname hash to derive the MAC address.
48+
(builtins.hashString "md5")
49+
50+
# [ "" "f" "0" .. "1" "e" "" ]
51+
(lib.splitString "")
52+
53+
# [ "f" "0" .. "1" "e" ]
54+
(lib.filter (char: char != ""))
55+
56+
# Take the first 12 characters (for a 6-byte MAC address).
57+
(lib.take 12)
58+
59+
# [ 15 0 .. 1 14 ]
60+
(map lib.fromHexString)
61+
62+
# Make sure the last bits of the first byte are `0b10` to indicate
63+
# a locally-administered unicast MAC address.
64+
(lib.imap0 (index: value: if index == 1 then lib.bitAnd (-2) (lib.bitOr value 2) else value))
65+
66+
# [ "F" "2" .. "1" "E" ]
67+
(map lib.toHexString)
68+
69+
# [ [ 15 2 ] .. [ 1 14 ] ]
70+
(chunkBy 2)
71+
72+
# [ "F2" .. "1E" ]
73+
(lib.map (lib.concatStringsSep ""))
74+
75+
# "F2:<...>:1E"
76+
(lib.concatStringsSep ":")
77+
];
3178
};
3279
};
3380

0 commit comments

Comments
 (0)