Repository navigation
Expand file tree
/
Copy pathmsldhcp
More file actions
executable file
·1558 lines (1323 loc) · 51.4 KB
/
Copy pathmsldhcp
File metadata and controls
executable file
·1558 lines (1323 loc) · 51.4 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
################################################################################
# Zelogx™ Multi-Project Secure Lab Setup
#
# © 2025 Zelogx. Zelogx™ and the Zelogx logo are trademarks
# of the Zelogx Project. All other marks are property of their respective owners.
#
# Filename: msldhcp
# Purpose: Deploy a dedicated DHCP-only LXC container for a Proxmox SDN VNet
# (opt-in; Proxmox SDN VXLAN zones have no built-in DHCP)
#
# Main functions/commands used:
# - pct / pvesh: Create the CT and read SDN subnet DHCP ranges
# - systemd path unit: Re-export DHCP settings when SDN subnets change
# - dnsmasq (inside the CT): DHCP server
#
# Dependencies:
# - Proxmox VE 9.x; pvesh, pct, qm, pveam, pvesm, jq, python3, systemctl
# - A Debian 13 standard CT template (pveam)
#
# Usage:
# msldhcp [--vmid ID] [--vnet VNET] [options] (see --help)
# Installed to /usr/local/bin/msldhcp by 0102_setupNetwork.sh.
#
# Notes:
# - Standalone command: does not source lib/ and logs to the console only
# - DHCP source: Datacenter > SDN > VNets > Subnets. The host extracts only
# the selected VNet's DHCP settings into
# /var/lib/mslsetup/dhcp/<vnet>/dhcp.env, mounted read-only inside the CT.
# /etc/pve is used only as the Proxmox SDN source and is not bind-mounted.
# - A systemd path unit watches Proxmox SDN subnet configuration and
# refreshes the exported DHCP state when the GUI settings change.
# The CT watches the read-only dhcp.env and restarts dnsmasq itself.
# - Not part of tenant isolation; stopping it only stops DHCP updates.
################################################################################
set -Eeuo pipefail
PROG="${0##*/}"
VMID=""
VNET=""
BRIDGE=""
NODE="$(hostname -s)"
ROOTFS_STORAGE=""
TEMPLATE_STORAGE=""
TEMPLATE_REGEX='debian-13-standard_.*_amd64\.tar\.(zst|xz|gz)$'
HOSTNAME_CT=""
CT_IP=""
CT_PREFIX=""
CT_GATEWAY=""
CT_USER=""
CT_USER_SPECIFIED="no"
CT_PASSWORD_ARG=""
ROOTFS_SIZE_GB="1"
MEMORY_MB="256"
SWAP_MB="128"
CORES="1"
DNS_SERVER=""
START_CT="yes"
UNPRIVILEGED="1"
FORCE="no"
usage() {
cat <<EOF
Usage:
$PROG [--vmid ID] [--vnet VNET] [options]
Main options:
--vmid ID LXC VMID. If omitted, prompt after VNet selection.
--vnet NAME SDN VNet name, e.g. vnetpj05 (optional)
Authentication / console:
--user NAME Optional debug console user.
If omitted, no user/password is created
(debug with 'pct exec' only).
--password PASS Required only when --user is specified.
Can also be provided via CT_PASSWORD environment variable.
Network:
--bridge NAME CT bridge (default: same as --vnet)
--ct-ip IP[/PREFIX] Static CT IP. If omitted, select a usable address
outside the DHCP pool.
--gateway IP Override subnet gateway
--dns-server IPS CT resolver list for package install.
Accepts one IP or a quoted space-separated list.
(default: MSL_HOST_DNS_SERVERS or host
/etc/resolv.conf nameservers)
--node NAME Deployment node (default: local node)
Storage / template:
--rootfs-storage NAME CT rootfs storage. If omitted, auto/prompt select
from storages supporting 'rootdir'.
--template-storage NAME Template storage.
If omitted, auto/prompt select from storages
supporting 'vztmpl'.
--template-regex REGEX pveam template filename regex
(default: latest Debian 13 standard amd64)
--rootfs-size GB Rootfs size in GB (default: 2)
Resources:
--memory MB RAM (default: 256)
--swap MB Swap (default: 128)
--cores N CPU cores (default: 1)
Behavior:
--no-start Create/configure but leave stopped
--privileged Create a privileged CT (default: unprivileged)
--force Destroy an existing CT with the same VMID
-h, --help Show this help
Example:
CT_PASSWORD='temporary-console-password' $PROG \
--vmid 905 \
--vnet vnetpj05 \
--rootfs-storage local-lvm \
--template-storage local \
--user dhcpdebug
EOF
}
log() { printf '[%s] %s\n' "$(date '+%F %T')" "$*"; }
warn() { printf '[%s] WARNING: %s\n' "$(date '+%F %T')" "$*" >&2; }
die() { printf '[%s] ERROR: %s\n' "$(date '+%F %T')" "$*" >&2; exit 1; }
need_cmd() {
command -v "$1" >/dev/null 2>&1 || die "Required command not found: $1"
}
is_uint() { [[ "$1" =~ ^[0-9]+$ ]]; }
vmid_resource_type() {
local vmid="$1"
if pct status "$vmid" >/dev/null 2>&1; then
printf '%s\n' "lxc"
return 0
fi
if qm status "$vmid" >/dev/null 2>&1; then
printf '%s\n' "qemu"
return 0
fi
return 1
}
vmid_is_available() {
local vmid="$1"
! vmid_resource_type "$vmid" >/dev/null 2>&1
}
prompt_available_vmid() {
local sel sel_normalized sel_num vmid_type
while true; do
printf 'Enter VMID for DHCP CT: ' >&2
if ! IFS= read -r sel < /dev/tty; then
die "Unable to read VMID from terminal. Specify --vmid explicitly."
fi
# Normalize full-width digits (e.g., 2) to ASCII before numeric checks.
sel_normalized=$(printf '%s' "$sel" | sed 'y/0123456789/0123456789/')
if ! [[ "$sel_normalized" =~ ^[0-9]+$ ]]; then
warn "Invalid VMID. Enter digits only."
continue
fi
sel_num=$((10#$sel_normalized))
if vmid_is_available "$sel_num"; then
printf '%s\n' "$sel_num"
return 0
fi
vmid_type="$(vmid_resource_type "$sel_num" || true)"
warn "VMID ${sel_num} is already in use${vmid_type:+ by ${vmid_type}}. Please choose another VMID."
done
}
storage_supports_content() {
local storage_name="$1"
local content_type="$2"
local storage_json content
storage_json=$(pvesh get /storage --output-format json 2>/dev/null) || return 1
content=$(printf '%s\n' "$storage_json" | jq -r --arg s "$storage_name" '.[] | select(.storage == $s) | (.content // "")' | head -n1)
[[ -n "$content" ]] || return 1
[[ ",$content," =~ ,${content_type}, ]]
}
select_storage_for_content() {
local content_type="$1"
local storage_role="$2"
local storage_json
local choices=()
local i sel
printf '[%s] Querying selectable storages for %s (content: %s)...\n' "$(date '+%F %T')" "$storage_role" "$content_type" >&2
storage_json=$(pvesh get /storage --output-format json 2>/dev/null) || true
[[ -n "$storage_json" ]] || die "Failed to query storage list via pvesh for ${storage_role}."
mapfile -t choices < <(printf '%s\n' "$storage_json" | jq -r --arg c "$content_type" '.[] | select((.enabled==1) or (.enabled? == null)) | select((.content // "") | test("(^|,)" + $c + "(,|$)")) | .storage' 2>/dev/null || true)
if [[ ${#choices[@]} -eq 0 ]]; then
die "No available storage found for ${storage_role} (required content type: ${content_type})."
elif [[ ${#choices[@]} -eq 1 ]]; then
printf '[%s] Auto-selected %s: %s\n' "$(date '+%F %T')" "$storage_role" "${choices[0]}" >&2
printf '%s\n' "${choices[0]}"
return 0
fi
echo "Multiple storages are available for ${storage_role} (${content_type}):" >&2
i=1
for s in "${choices[@]}"; do
echo " ${i}) ${s}" >&2
i=$((i + 1))
done
while true; do
local sel_normalized sel_num
printf 'Select %s storage (1-%s): ' "${storage_role}" "${#choices[@]}" >&2
if ! IFS= read -r sel < /dev/tty; then
warn "Unable to read from terminal for ${storage_role} selection."
return 1
fi
# Normalize full-width digits (e.g., 2) to ASCII before numeric checks.
sel_normalized=$(printf '%s' "$sel" | sed 'y/0123456789/0123456789/')
if [[ "$sel_normalized" =~ ^[0-9]+$ ]]; then
sel_num=$((10#$sel_normalized))
if (( sel_num >= 1 && sel_num <= ${#choices[@]} )); then
printf '%s\n' "${choices[$((sel_num - 1))]}"
return 0
fi
fi
warn "Invalid selection. Please select 1-${#choices[@]}."
done
}
validate_ipv4() {
python3 - "$1" <<'PY'
import ipaddress, sys
try:
ipaddress.IPv4Address(sys.argv[1])
except Exception:
raise SystemExit(1)
PY
}
validate_nameserver_list() {
local nameserver_list="$1"
local nameserver
read -r -a nameservers <<<"$nameserver_list"
((${#nameservers[@]} > 0)) || return 1
for nameserver in "${nameservers[@]}"; do
validate_ipv4 "$nameserver" || return 1
done
}
load_host_dns_servers() {
local resolv_file="/etc/resolv.conf"
local host_dns
[[ -r "$resolv_file" ]] || return 1
host_dns=$(awk '/^[[:space:]]*nameserver[[:space:]]+/ {print $2}' "$resolv_file" 2>/dev/null | awk 'NF' | xargs || true)
[[ -n "$host_dns" ]] || return 1
printf '%s\n' "$host_dns"
}
resolve_vnet_selection() {
local requested_vnet="$1"
python3 - "$requested_vnet" <<'PY'
import json
import subprocess
import sys
requested = sys.argv[1].strip()
def run_json(path):
p = subprocess.run(
["pvesh", "get", path, "--output-format", "json"],
check=True, text=True, encoding="utf-8", errors="replace", stdout=subprocess.PIPE
)
return json.loads(p.stdout)
def as_rows(data):
if isinstance(data, list):
return data
if data is None:
return []
return [data]
def first_non_empty(row, keys):
for key in keys:
value = row.get(key)
if value not in (None, ""):
return str(value)
return ""
def parse_dhcp_ranges(row, vnet_name):
if "dhcp-range" not in row or row.get("dhcp-range") in (None, []):
return []
value = row.get("dhcp-range")
subnet_id = first_non_empty(row, ("subnet", "id")) or "unknown-subnet"
if not isinstance(value, list):
raise ValueError(
f"Unsupported DHCP range format on {vnet_name}/{subnet_id}: expected dhcp-range to be a list of objects."
)
out = []
for idx, item in enumerate(value, start=1):
if not isinstance(item, dict):
raise ValueError(
f"Unsupported DHCP range item on {vnet_name}/{subnet_id} at index {idx}: expected object with start-address and end-address."
)
start = item.get("start-address")
end = item.get("end-address")
if not isinstance(start, str) or not isinstance(end, str) or not start or not end:
raise ValueError(
f"Unsupported DHCP range item on {vnet_name}/{subnet_id} at index {idx}: expected string start-address and end-address."
)
out.append((start, end))
return out
def load_catalog():
vnet_rows = as_rows(run_json("/cluster/sdn/vnets"))
zone_rows = as_rows(run_json("/cluster/sdn/zones"))
zones = {}
for row in zone_rows:
if not isinstance(row, dict):
continue
zone_name = first_non_empty(row, ("zone", "zoneid", "id"))
if zone_name:
zones[zone_name] = row
catalog = []
for row in vnet_rows:
if not isinstance(row, dict):
continue
name = first_non_empty(row, ("vnet", "vnetid", "id"))
if not name:
continue
zone_name = first_non_empty(row, ("zone", "zoneid", "zone-name"))
zone_row = zones.get(zone_name, {})
zone_type = first_non_empty(zone_row, ("type", "zone_type", "zone-type"))
dhcp_subnet_count = 0
try:
subnet_rows = as_rows(run_json(f"/cluster/sdn/vnets/{name}/subnets"))
except Exception:
subnet_rows = []
for subnet_row in subnet_rows:
if isinstance(subnet_row, dict) and parse_dhcp_ranges(subnet_row, name):
dhcp_subnet_count += 1
catalog.append({
"name": name,
"zone_type": zone_type,
"dhcp_subnet_count": dhcp_subnet_count,
"managed": zone_type == "vxlan" and name.startswith("vnetpj"),
})
return catalog
catalog = load_catalog()
requested_entry = None
managed = []
dhcp_ready = []
for entry in catalog:
if requested and entry["name"] == requested:
requested_entry = entry
if entry["managed"]:
managed.append(entry)
if entry["dhcp_subnet_count"] > 0:
dhcp_ready.append(entry)
if requested:
if requested_entry is None or not requested_entry["managed"]:
raise SystemExit(
f"Selected VNet '{requested}' is not an MSL Setup-managed VXLAN zone."
)
if requested_entry["dhcp_subnet_count"] == 0:
raise SystemExit(
f"Selected VNet '{requested}' is managed by MSL Setup, but DHCP Range is not configured. Please check Datacenter > SDN and set the DHCP Range."
)
print(requested_entry["name"])
raise SystemExit(0)
if not managed:
raise SystemExit(
"No VNet matched the MSL Setup VXLAN filter (zone type must be vxlan and VNet name must start with vnetpj). This VNet is not an MSL Setup-managed VXLAN zone."
)
if not dhcp_ready:
raise SystemExit(
"No MSL Setup-managed VXLAN VNet has a configured DHCP range. This VNet is managed by MSL Setup, but DHCP Range is not configured. Please check Datacenter > SDN and set the DHCP Range."
)
if len(dhcp_ready) == 1:
print(dhcp_ready[0]["name"])
raise SystemExit(0)
print("Multiple VNets match the MSL Setup filter:", file=sys.stderr)
for idx, entry in enumerate(dhcp_ready, start=1):
print(f" {idx}) {entry['name']}", file=sys.stderr)
while True:
print(f"Select a VNet (1-{len(dhcp_ready)}): ", end="", file=sys.stderr, flush=True)
try:
with open("/dev/tty", "r", encoding="utf-8", errors="ignore") as tty:
choice = tty.readline().strip()
except EOFError:
raise SystemExit(1)
except OSError:
raise SystemExit(1)
if choice.isdigit():
selected = int(choice)
if 1 <= selected <= len(dhcp_ready):
print(dhcp_ready[selected - 1]["name"])
raise SystemExit(0)
print(f"Invalid selection. Please choose 1-{len(dhcp_ready)}.", file=sys.stderr)
PY
}
while (($#)); do
case "$1" in
--vmid) VMID="${2:?}"; shift 2 ;;
--vnet) VNET="${2:?}"; shift 2 ;;
--bridge) BRIDGE="${2:?}"; shift 2 ;;
--node) NODE="${2:?}"; shift 2 ;;
--rootfs-storage) ROOTFS_STORAGE="${2:?}"; shift 2 ;;
--template-storage) TEMPLATE_STORAGE="${2:?}"; shift 2 ;;
--template-regex) TEMPLATE_REGEX="${2:?}"; shift 2 ;;
--hostname) HOSTNAME_CT="${2:?}"; shift 2 ;;
--ct-ip) CT_IP="${2:?}"; shift 2 ;;
--gateway) CT_GATEWAY="${2:?}"; shift 2 ;;
--dns-server) DNS_SERVER="${2:?}"; shift 2 ;;
--user) CT_USER="${2:?}"; CT_USER_SPECIFIED="yes"; shift 2 ;;
--password) CT_PASSWORD_ARG="${2:?}"; shift 2 ;;
--rootfs-size) ROOTFS_SIZE_GB="${2:?}"; shift 2 ;;
--memory) MEMORY_MB="${2:?}"; shift 2 ;;
--swap) SWAP_MB="${2:?}"; shift 2 ;;
--cores) CORES="${2:?}"; shift 2 ;;
--no-start) START_CT="no"; shift ;;
--privileged) UNPRIVILEGED="0"; shift ;;
--force) FORCE="yes"; shift ;;
-h|--help) usage; exit 0 ;;
*) die "Unknown argument: $1" ;;
esac
done
[[ $EUID -eq 0 ]] || die "Run as root on a Proxmox VE node."
CT_PASSWORD_EFFECTIVE="${CT_PASSWORD_ARG:-${CT_PASSWORD:-}}"
if [[ "$CT_USER_SPECIFIED" == "yes" ]]; then
[[ -n "$CT_PASSWORD_EFFECTIVE" ]] || die "--user requires --password or CT_PASSWORD environment variable."
[[ "$CT_USER" =~ ^[a-z_][a-z0-9_-]*$ ]] || die "Invalid user name."
fi
if [[ -n "$VMID" ]]; then
is_uint "$VMID" || die "Invalid VMID: $VMID"
VMID="$((10#$VMID))"
fi
is_uint "$ROOTFS_SIZE_GB" || die "Invalid --rootfs-size."
is_uint "$MEMORY_MB" || die "Invalid --memory."
is_uint "$SWAP_MB" || die "Invalid --swap."
is_uint "$CORES" || die "Invalid --cores."
if [[ -n "$VNET" ]]; then
[[ "$VNET" =~ ^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$ ]] || die "Invalid VNet name."
fi
for cmd in pvesh pct qm pveam pvesm jq python3 systemctl; do
need_cmd "$cmd"
done
VNET="$(resolve_vnet_selection "$VNET")"
if [[ -z "$VMID" ]]; then
log "--vmid was not specified; prompting for an available VMID after VNet selection."
VMID="$(prompt_available_vmid)"
fi
BRIDGE="${BRIDGE:-$VNET}"
HOSTNAME_CT="${HOSTNAME_CT:-dhcp-${VNET}}"
if [[ -z "$ROOTFS_STORAGE" ]]; then
ROOTFS_STORAGE="$(select_storage_for_content "rootdir" "rootfs")"
else
storage_supports_content "$ROOTFS_STORAGE" "rootdir" \
|| die "Storage '${ROOTFS_STORAGE}' cannot be used for rootfs (required content type: rootdir)."
fi
if [[ -z "$TEMPLATE_STORAGE" ]]; then
TEMPLATE_STORAGE="$(select_storage_for_content "vztmpl" "template")"
else
storage_supports_content "$TEMPLATE_STORAGE" "vztmpl" \
|| die "Storage '${TEMPLATE_STORAGE}' cannot be used for template (required content type: vztmpl)."
fi
pvesm status --storage "$ROOTFS_STORAGE" >/dev/null 2>&1 \
|| die "Rootfs storage not found or unavailable: $ROOTFS_STORAGE"
pvesm status --storage "$TEMPLATE_STORAGE" >/dev/null 2>&1 \
|| die "Template storage not found or unavailable: $TEMPLATE_STORAGE"
# Verify VNet exists.
pvesh get "/cluster/sdn/vnets/${VNET}" --output-format json >/dev/null 2>&1 \
|| die "SDN VNet not found: $VNET"
if pct status "$VMID" >/dev/null 2>&1; then
if [[ "$FORCE" != "yes" ]]; then
die "CT $VMID already exists. Use --force to replace it."
fi
log "Removing existing CT $VMID..."
pct stop "$VMID" --skiplock 1 >/dev/null 2>&1 || true
pct destroy "$VMID" --purge 1
fi
STATE_BASE="/var/lib/mslsetup/dhcp"
STATE_DIR="${STATE_BASE}/${VNET}"
STATE_FILE="${STATE_DIR}/dhcp.env"
OVERRIDE_DIR="${STATE_BASE}/overrides"
OVERRIDE_FILE="${OVERRIDE_DIR}/${VNET}.env"
# Host-side export is singleton and CT-ID-free.
# It watches Proxmox SDN subnet configuration once and exports dhcp.env for all
# VNets that have DHCP ranges. Each DHCP CT watches only its own mounted dhcp.env.
EXPORTER_SCRIPT="/usr/local/sbin/msl-dhcp-export-all"
SERVICE_NAME="msl-dhcp-export-all.service"
PATH_NAME="msl-dhcp-export-all.path"
mkdir -p "$STATE_DIR" "$OVERRIDE_DIR"
chown root:root /var/lib/mslsetup "$STATE_BASE" "$STATE_DIR" "$OVERRIDE_DIR" 2>/dev/null || true
chmod 0755 /var/lib/mslsetup "$STATE_BASE" "$STATE_DIR" "$OVERRIDE_DIR"
write_override_file() {
local file="$1"
local ct_ip_value="$2"
local gw_value="$3"
local dns_value="$4"
tmp="$(mktemp "${file}.XXXXXX")"
{
printf '# Generated by %s. Used by msl-dhcp-export-all.\n' "$PROG"
printf 'CT_IP_OVERRIDE=%q\n' "$ct_ip_value"
printf 'GW_OVERRIDE=%q\n' "$gw_value"
printf 'DHCP_DNS_OVERRIDE=%q\n' "$dns_value"
} >"$tmp"
chmod 0644 "$tmp"
if [[ -f "$file" ]] && cmp -s "$tmp" "$file"; then
rm -f "$tmp"
else
mv -f "$tmp" "$file"
fi
}
# Select the CT address before installing the singleton exporter.
# The exporter itself does not choose CT addresses; it only renders dhcp.env
# for VNets that already have an override file. This keeps host-side runtime
# sync deterministic and prevents later DHCP edits from moving the CT address.
select_tmp="$(mktemp "${STATE_FILE}.select.XXXXXX")"
trap 'rm -f "$select_tmp"' EXIT
python3 - "$VNET" "$CT_IP" "$CT_GATEWAY" "$DNS_SERVER" >"$select_tmp" <<'PY_SELECT'
import ipaddress
import json
import subprocess
import sys
vnet, ct_override, gw_override, dhcp_dns_override = sys.argv[1:5]
def run_json(path):
p = subprocess.run(
["pvesh", "get", path, "--output-format", "json"],
check=True, text=True, stdout=subprocess.PIPE
)
return json.loads(p.stdout)
def parse_dhcp_ranges(row, vnet):
if "dhcp-range" not in row or row.get("dhcp-range") in (None, []):
return []
value = row.get("dhcp-range")
subnet_id = str(row.get("subnet") or row.get("id") or "unknown-subnet")
if not isinstance(value, list):
raise SystemExit(
f"Unsupported DHCP range format on {vnet}/{subnet_id}: "
"expected dhcp-range to be a list of objects."
)
out = []
for idx, item in enumerate(value, start=1):
if not isinstance(item, dict):
raise SystemExit(
f"Unsupported DHCP range item on {vnet}/{subnet_id} at index {idx}: "
"expected object with start-address and end-address."
)
start = item.get("start-address")
end = item.get("end-address")
if not isinstance(start, str) or not isinstance(end, str) or not start or not end:
raise SystemExit(
f"Unsupported DHCP range item on {vnet}/{subnet_id} at index {idx}: "
"expected string start-address and end-address."
)
out.append((start, end))
return out
def quote(value):
return repr(str(value))
data = run_json(f"/cluster/sdn/vnets/{vnet}/subnets")
if not isinstance(data, list):
raise SystemExit(
f"Unsupported Proxmox SDN subnet API format for {vnet}: expected a JSON array."
)
candidates = []
for row in data:
if not isinstance(row, dict):
raise SystemExit(
f"Unsupported Proxmox SDN subnet API format for {vnet}: expected each array item to be an object."
)
ranges = parse_dhcp_ranges(row, vnet)
if not ranges:
continue
cidr = row.get("cidr")
if not isinstance(cidr, str) or not cidr:
subnet_id = str(row.get("subnet") or row.get("id") or "unknown-subnet")
raise SystemExit(
f"Unsupported Proxmox SDN subnet API format on {vnet}/{subnet_id}: expected non-empty string cidr."
)
candidates.append((row, cidr, ranges))
if not candidates:
raise SystemExit(
f"No DHCP range was found for VNet {vnet}. Configure Datacenter > SDN > VNets > Subnets > DHCP Ranges first."
)
if len(candidates) > 1:
raise SystemExit(
f"Multiple IPv4 subnets with DHCP ranges exist on {vnet}; this deployer currently requires exactly one."
)
row, cidr, ranges = candidates[0]
net = ipaddress.ip_network(cidr, strict=False)
if net.version != 4:
raise SystemExit("Only IPv4 DHCP is supported by this script.")
gateway = gw_override or row.get("gateway") or row.get("gateway4")
if not gateway:
raise SystemExit(f"No gateway is configured for subnet {cidr}.")
gateway_ip = ipaddress.ip_address(str(gateway).split("/", 1)[0])
if gateway_ip not in net:
raise SystemExit(f"Gateway {gateway_ip} is outside {net}.")
dhcp_dns = dhcp_dns_override or str(gateway_ip)
dhcp_dns_ip = ipaddress.ip_address(str(dhcp_dns).split("/", 1)[0])
if dhcp_dns_ip.version != 4:
raise SystemExit("Only IPv4 DNS server is supported by this script.")
normalized = []
for start, end in ranges:
a, b = ipaddress.ip_address(start), ipaddress.ip_address(end)
if a.version != 4 or b.version != 4 or a not in net or b not in net or int(a) > int(b):
raise SystemExit(f"Invalid DHCP range: {start}-{end}")
normalized.append((a, b))
def in_pool(ip):
return any(int(a) <= int(ip) <= int(b) for a, b in normalized)
if ct_override:
iface = ipaddress.ip_interface(
ct_override if "/" in ct_override else f"{ct_override}/{net.prefixlen}"
)
ct_ip = iface.ip
prefix = iface.network.prefixlen
if iface.network.network_address != net.network_address or prefix != net.prefixlen:
raise SystemExit(f"CT address {iface} does not belong to {net}.")
else:
ct_ip = None
# Prefer high usable addresses. Many operators place infrastructure IPs
# such as gateways and static services near the end of the subnet.
for ip in reversed(list(net.hosts())):
if ip != gateway_ip and not in_pool(ip):
ct_ip = ip
break
if ct_ip is None:
raise SystemExit(f"No address outside DHCP pools is available in {net}.")
prefix = net.prefixlen
if ct_ip == gateway_ip:
raise SystemExit("CT IP conflicts with the subnet gateway.")
if in_pool(ct_ip):
# Not fatal: the CT-side renderer excludes CT_IP from the effective
# dnsmasq range and posts a motd warning. Surface it here too so it is
# visible at deploy time, not only inside the CT later.
print(
f"warning: CT_IP {ct_ip} is inside a DHCP allocation range; "
"the CT will exclude it from the effective range at render time.",
file=sys.stderr,
)
print(f"VNET={quote(vnet)}")
print(f"CIDR={quote(str(net))}")
print(f"PREFIX={quote(str(prefix))}")
print(f"NETMASK={quote(str(net.netmask))}")
print(f"GATEWAY={quote(str(gateway_ip))}")
print(f"DHCP_DNS={quote(str(dhcp_dns_ip))}")
print(f"CT_IP={quote(str(ct_ip))}")
print("DHCP_RANGES=" + quote(",".join(f"{a}-{b}" for a, b in normalized)))
PY_SELECT
chmod 0644 "$select_tmp"
mv -f "$select_tmp" "$STATE_FILE"
trap - EXIT
# shellcheck disable=SC1090
source "$STATE_FILE"
if [[ -z "$DNS_SERVER" ]]; then
if [[ -n "${MSL_HOST_DNS_SERVERS:-}" ]]; then
INSTALL_NAMESERVERS="$MSL_HOST_DNS_SERVERS"
log "Using DNS servers from environment (MSL_HOST_DNS_SERVERS): $INSTALL_NAMESERVERS"
else
INSTALL_NAMESERVERS="$(load_host_dns_servers)" || die "No nameserver found in /etc/resolv.conf. Set --dns-server or MSL_HOST_DNS_SERVERS."
export MSL_HOST_DNS_SERVERS="$INSTALL_NAMESERVERS"
log "Using DNS servers from host /etc/resolv.conf: $INSTALL_NAMESERVERS"
fi
else
INSTALL_NAMESERVERS="$DNS_SERVER"
log "Using DNS servers from --dns-server: $INSTALL_NAMESERVERS"
fi
validate_nameserver_list "$INSTALL_NAMESERVERS" || die "Invalid DNS server list: $INSTALL_NAMESERVERS"
DHCP_DNS_SERVER="${INSTALL_NAMESERVERS%% *}"
write_override_file "$OVERRIDE_FILE" "$CT_IP" "$CT_GATEWAY" "$DHCP_DNS_SERVER"
cat >"$EXPORTER_SCRIPT" <<'EOF_EXPORTER'
#!/usr/bin/env bash
set -Eeuo pipefail
STATE_BASE='/var/lib/mslsetup/dhcp'
OVERRIDE_DIR="${STATE_BASE}/overrides"
REQUIRE_VNET="${REQUIRE_VNET:-}"
mkdir -p "$STATE_BASE" "$OVERRIDE_DIR"
chmod 0755 "$STATE_BASE" "$OVERRIDE_DIR" 2>/dev/null || true
python3 - "$STATE_BASE" "$OVERRIDE_DIR" "$REQUIRE_VNET" <<'PY_EXPORTER'
import ipaddress
import json
import os
import pathlib
import shlex
import subprocess
import sys
import tempfile
state_base = pathlib.Path(sys.argv[1])
override_dir = pathlib.Path(sys.argv[2])
require_vnet = sys.argv[3]
def run_json(path):
p = subprocess.run(
["pvesh", "get", path, "--output-format", "json"],
check=True, text=True, stdout=subprocess.PIPE
)
return json.loads(p.stdout)
def parse_dhcp_ranges(row, vnet):
"""Parse the exact Proxmox API shape observed on PVE 9.x.
Supported shape only:
"dhcp-range": [
{"start-address": "x.x.x.x", "end-address": "x.x.x.x"},
...
]
Missing or empty dhcp-range means this subnet is not served by this
DHCP exporter. Any other shape is treated as an unsupported API format.
"""
if "dhcp-range" not in row or row.get("dhcp-range") in (None, []):
return []
value = row.get("dhcp-range")
subnet_id = str(row.get("subnet") or row.get("id") or "unknown-subnet")
if not isinstance(value, list):
raise ValueError(
f"Unsupported DHCP range format on {vnet}/{subnet_id}: "
"expected dhcp-range to be a list of objects."
)
out = []
for idx, item in enumerate(value, start=1):
if not isinstance(item, dict):
raise ValueError(
f"Unsupported DHCP range item on {vnet}/{subnet_id} at index {idx}: "
"expected object with start-address and end-address."
)
start = item.get("start-address")
end = item.get("end-address")
if not isinstance(start, str) or not isinstance(end, str) or not start or not end:
raise ValueError(
f"Unsupported DHCP range item on {vnet}/{subnet_id} at index {idx}: "
"expected string start-address and end-address."
)
out.append((start, end))
return out
def load_override(vnet):
path = override_dir / f"{vnet}.env"
data = {
"CT_IP_OVERRIDE": "",
"GW_OVERRIDE": "",
"DHCP_DNS_OVERRIDE": "",
}
if not path.exists():
return data
for raw in path.read_text(encoding="utf-8").splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
if key not in data:
continue
try:
parsed = shlex.split(value, posix=True)
data[key] = parsed[0] if parsed else ""
except ValueError:
data[key] = value.strip().strip("'\"")
return data
def quote(value):
return repr(str(value))
def discover_vnets():
data = run_json("/cluster/sdn/vnets")
rows = data if isinstance(data, list) else [data]
names = set()
for row in rows:
if isinstance(row, dict):
for key in ("vnet", "vnetid", "id"):
value = row.get(key)
if value:
names.add(str(value))
break
elif isinstance(row, str):
names.add(row)
return sorted(names)
def collect_candidates(vnet):
data = run_json(f"/cluster/sdn/vnets/{vnet}/subnets")
if not isinstance(data, list):
raise ValueError(
f"Unsupported Proxmox SDN subnet API format for {vnet}: "
"expected a JSON array."
)
candidates = []
for row in data:
if not isinstance(row, dict):
raise ValueError(
f"Unsupported Proxmox SDN subnet API format for {vnet}: "
"expected each array item to be an object."
)
ranges = parse_dhcp_ranges(row, vnet)
if not ranges:
continue
cidr = row.get("cidr")
if not isinstance(cidr, str) or not cidr:
subnet_id = str(row.get("subnet") or row.get("id") or "unknown-subnet")
raise ValueError(
f"Unsupported Proxmox SDN subnet API format on {vnet}/{subnet_id}: "
"expected non-empty string cidr."
)
candidates.append((row, cidr, ranges))
return candidates
def render_env(vnet, row, cidr, ranges, overrides):
net = ipaddress.ip_network(cidr, strict=False)
if net.version != 4:
raise ValueError("Only IPv4 DHCP is supported by this script.")
gateway = overrides["GW_OVERRIDE"] or row.get("gateway") or row.get("gateway4")
if not gateway:
raise ValueError(f"No gateway is configured for subnet {cidr}.")
gateway_ip = ipaddress.ip_address(str(gateway).split("/", 1)[0])
if gateway_ip not in net:
raise ValueError(f"Gateway {gateway_ip} is outside {net}.")
dhcp_dns = overrides["DHCP_DNS_OVERRIDE"] or str(gateway_ip)
dhcp_dns_ip = ipaddress.ip_address(str(dhcp_dns).split("/", 1)[0])
if dhcp_dns_ip.version != 4:
raise ValueError("Only IPv4 DNS server is supported by this script.")
normalized = []
for start, end in ranges:
a, b = ipaddress.ip_address(start), ipaddress.ip_address(end)
if a.version != 4 or b.version != 4 or a not in net or b not in net or int(a) > int(b):
raise ValueError(f"Invalid DHCP range: {start}-{end}")
normalized.append((a, b))
def in_pool(ip):
return any(int(a) <= int(ip) <= int(b) for a, b in normalized)
ct_override = overrides["CT_IP_OVERRIDE"]
if not ct_override:
raise ValueError(
f"No CT_IP_OVERRIDE is configured for {vnet}. "
"Create the DHCP CT for this VNet before exporting dhcp.env."
)
iface = ipaddress.ip_interface(
ct_override if "/" in ct_override else f"{ct_override}/{net.prefixlen}"
)
ct_ip = iface.ip
prefix = iface.network.prefixlen
if iface.network.network_address != net.network_address or prefix != net.prefixlen:
raise ValueError(f"CT address {iface} does not belong to {net}.")
if ct_ip == gateway_ip:
raise ValueError("CT IP conflicts with the subnet gateway.")
if in_pool(ct_ip):
# Not fatal: export continues with the current DHCP ranges as-is.
# The CT-side renderer excludes CT_IP from the effective dnsmasq
# range and posts its own motd warning. Aborting the export here
# would instead leave this VNet's dhcp.env silently stale after a
# later GUI DHCP-range edit.
print(
f"warning: {vnet}: CT_IP {ct_ip} is inside a DHCP allocation "
"range; exporting anyway, the CT will exclude it at render time.",
file=sys.stderr,
)
lines = [
f"VNET={quote(vnet)}",
f"CIDR={quote(str(net))}",
f"PREFIX={quote(str(prefix))}",
f"NETMASK={quote(str(net.netmask))}",
f"GATEWAY={quote(str(gateway_ip))}",
f"DHCP_DNS={quote(str(dhcp_dns_ip))}",
f"CT_IP={quote(str(ct_ip))}",
"DHCP_RANGES=" + quote(",".join(f"{a}-{b}" for a, b in normalized)),
"",
]
return "\n".join(lines)
def write_if_changed(vnet, content):
state_dir = state_base / vnet
state_dir.mkdir(parents=True, exist_ok=True)
os.chmod(state_dir, 0o755)
state_file = state_dir / "dhcp.env"
old = state_file.read_text(encoding="utf-8") if state_file.exists() else None
if old == content:
print(f"unchanged: {vnet}")
return False
fd, tmp_name = tempfile.mkstemp(prefix="dhcp.env.", dir=str(state_dir), text=True)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(content)
os.chmod(tmp_name, 0o644)
os.replace(tmp_name, state_file)
print(f"updated: {vnet}")
return True
finally:
try:
os.unlink(tmp_name)
except FileNotFoundError:
pass
errors = []
exported = set()
for vnet in discover_vnets():