Repository navigation
Expand file tree
/
Copy pathbackend.func
More file actions
1520 lines (1388 loc) · 61.8 KB
/
Copy pathbackend.func
File metadata and controls
1520 lines (1388 loc) · 61.8 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
# Copyright (c) 2021-2026 community-scripts ORG
# License: MIT | https://github.com/community-scripts/core/raw/main/LICENSE
# ==============================================================================
# INCUS-BACKEND.FUNC - FULL PARITY BACKEND FOR INCUS CONTAINER CREATION
# ==============================================================================
# Mirrors core/build.func build_container / create_lxc_container flow for Incus.
# Requires incus/build.func hooks and UI functions to be loaded first.
# ==============================================================================
[[ -n "${_INCUS_BACKEND_LOADED:-}" ]] && return
_INCUS_BACKEND_LOADED=1
incus_ct_exec() {
incus exec "${CT_NAME}" -- "$@"
}
_incus_device_set() {
# usage: _incus_device_set <key> <value> [warn-msg]
local key="$1" val="$2" warn="${3:-}"
if ! incus config device set "${CT_NAME}" eth0 "${key}=${val}" >>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1; then
[[ -n "$warn" ]] && msg_warn "$warn"
return 1
fi
return 0
}
# Soft-fail helper: never trips set -e / ERR traps from intentional best-effort cmds.
_incus_soft() {
"$@" || return 0
}
_incus_nic_supports_ip() {
# Takes the network name, not the type: managed-ness matters as much as the
# type does. ipv4.address on a NIC is a reservation in the DHCP server Incus
# itself runs, and that server only exists for managed networks. On a bridge
# the operator built by hand there is nothing to reserve in, so the address
# is quietly ignored and the container comes up on the LAN's own DHCP while
# the summary claims a static address. Better to say so than to pretend.
#
# physical / sriov: skip either way (host NIC ownership; keys often rejected).
local net="${1:-}" cfg type
[[ -z "$net" ]] && return 1
cfg=$(LC_ALL=C incus network show "$net" 2>/dev/null) || return 1
grep -qE '^managed:[[:space:]]*true$' <<<"$cfg" || return 1
type=$(awk '/^type:/ {print $2; exit}' <<<"$cfg")
case "$type" in
bridge | ovn | macvlan) return 0 ;;
*) return 1 ;;
esac
}
# A system container takes only a plain address (a DHCP reservation) and no
# gateway; CIDR and ipv4/ipv6.gateway are OCI-only and stop it from starting.
_incus_apply_addresses() {
local changed=1 addr gw net_gw
if [[ -n "${NET:-}" && "${NET}" != "dhcp" ]]; then
addr="${NET%%/*}"
_incus_device_set ipv4.address "$addr" "Could not reserve ${addr} on '${BRG}' (see the log); the container keeps a DHCP address" && changed=0 || true
fi
gw="${GATE:-}"
gw="${gw#,gw=}"
if [[ -n "$gw" ]]; then
net_gw="$(incus network get "$BRG" ipv4.dhcp.gateway 2>/dev/null || true)"
if [[ -z "$net_gw" ]]; then
net_gw="$(incus network get "$BRG" ipv4.address 2>/dev/null || true)"
net_gw="${net_gw%%/*}"
fi
if [[ "$gw" != "$net_gw" ]]; then
msg_warn "Gateway ${gw} is not applied: Incus DHCP on '${BRG}' hands out ${net_gw:-its own}"
fi
fi
if [[ "${IPV6_METHOD:-}" == "static" && -n "${IPV6_ADDR:-}" && "${IPV6_ADDR}" != "auto" ]]; then
addr="${IPV6_ADDR%%/*}"
_incus_device_set ipv6.address "$addr" "Could not reserve ${addr} on '${BRG}' (see the log); IPv6 stays as the network assigns it" && changed=0 || true
if [[ -n "${IPV6_GATE:-}" ]]; then
msg_warn "IPv6 gateway ${IPV6_GATE} is not applied: Incus sets a gateway only for OCI containers"
fi
fi
return "$changed"
}
# Restart the container, tolerating optional boot-time configs (e.g.
# linux.sysctl.kernel.keys.maxkeys) that some hosts/kernels reject for the
# container's privilege level. Such configs pass 'config set' but abort the
# container at *start* time, so a plain restart would leave it stopped. On
# failure, roll those configs back and retry so the container is never left
# dead. Returns non-zero only if it still cannot start.
_incus_restart_ct() {
local logf="${LOGFILE:-$INCUS_BUILD_LOG}"
if incus restart "${CT_NAME}" >>"$logf" 2>&1; then
return 0
fi
msg_warn "Container failed to start with current config — rolling back optional sysctls"
_incus_soft incus config unset "${CT_NAME}" linux.sysctl.kernel.keys.maxkeys >>"$logf" 2>&1
_incus_soft incus stop -f "${CT_NAME}" >>"$logf" 2>&1
_incus_soft incus start "${CT_NAME}" >>"$logf" 2>&1
# A failed restart leaves incus disagreeing with itself - the same recovery
# logged "already stopped" from stop and "already running" from start - so
# the exit code proves nothing here. Ask what the state actually is.
[[ "$(incus_instance_field "${CT_NAME}" s)" == "RUNNING" ]]
}
_incus_resolve_launch_image() {
# Tries images:OS/VER (+ /cloud, codename alias, local cache). Sets INCUS_LAUNCH_IMAGE.
local os="${IMAGE_OS:-debian}" ver="${IMAGE_VERSION:-13}" alias=""
os="${os,,}"
alias="$(incus_get_image_alias "$os" "$ver" 2>/dev/null || true)"
local candidates=()
candidates+=("images:${os}/${ver}")
candidates+=("images:${os}/${ver}/cloud")
if [[ -n "$alias" && "$alias" != "$ver" ]]; then
candidates+=("images:${os}/${alias}")
candidates+=("images:${os}/${alias}/cloud")
fi
# Ubuntu often published as 24.04 even when UI stores "24"
if [[ "$os" == "ubuntu" && "$ver" =~ ^[0-9]+$ ]]; then
candidates+=("images:ubuntu/${ver}.04" "images:ubuntu/${ver}.04/cloud")
fi
local cand local_aliases
# Local first: no round-trip, and works without internet.
local_aliases=$(incus image list -f csv,noheader -c l 2>/dev/null || true)
for cand in "${candidates[@]}"; do
if [[ -n "$local_aliases" ]] &&
grep -qxF "${cand#images:}" <<<"$local_aliases" &&
incus image info "${cand#images:}" &>/dev/null; then
INCUS_LAUNCH_IMAGE="${cand#images:}"
return 0
fi
done
for cand in "${candidates[@]}"; do
if incus image info "$cand" &>/dev/null; then
INCUS_LAUNCH_IMAGE="$cand"
return 0
fi
done
# Not on the image server under any name we know: take its newest version.
local newest
newest=$(incus image alias list images: "${os}/" -f csv 2>/dev/null | cut -d, -f1 |
awk -F/ 'NF == 2 && $2 ~ /^[0-9][0-9.]*$/ {print $2}' | sort -uV | tail -n1 || true)
if [[ -n "$newest" ]] && incus image info "images:${os}/${newest}" &>/dev/null; then
msg_warn "${os} ${ver} is not on the image server; using ${os} ${newest}"
INCUS_LAUNCH_IMAGE="images:${os}/${newest}"
return 0
fi
# Last resort: try remote launch of primary (incus may pull on demand)
INCUS_LAUNCH_IMAGE="images:${os}/${ver}"
return 1
}
_incus_parse_size_to_bytes() {
# Integer arithmetic only: BusyBox awk truncates printf "%d" to 32 bit.
local raw="${1:-}" int frac unit mult scale=1 i
raw="${raw// /}"
[[ "$raw" =~ ^([0-9]+)(\.([0-9]+))?([A-Za-z]*)$ ]] || return 1
int="${BASH_REMATCH[1]}"
frac="${BASH_REMATCH[3]}"
unit="${BASH_REMATCH[4]^^}"
case "$unit" in
B | "") mult=1 ;;
KB | KIB | K) mult=1024 ;;
MB | MIB | M) mult=$((1024 * 1024)) ;;
GB | GIB | G) mult=$((1024 * 1024 * 1024)) ;;
TB | TIB | T) mult=$((1024 * 1024 * 1024 * 1024)) ;;
*) return 1 ;;
esac
for ((i = 0; i < ${#frac}; i++)); do scale=$((scale * 10)); done
echo $((10#$int * mult + 10#${frac:-0} * mult / scale))
}
incus_storage_pool_free_gb() {
local pool="${1:-}"
local info free_bytes total_bytes used_bytes free_raw total_raw used_raw
# Prefer machine-readable bytes when available (Incus --bytes).
# LC_ALL=C: incus translates this output. A German host reports "Gesamter
# Speicherplatz" and "Speicherplatz in Benutzung", so the awk below matched
# nothing and a 357GB pool looked unmeasurable.
# Incus reports total and used only; with --bytes they are plain integers, so
# the subtraction stays in bash and never goes through awk floats (BusyBox awk
# truncates those to 32 bit).
info=$(LC_ALL=C incus storage info --bytes "$pool" 2>/dev/null || true)
free_raw=$(echo "$info" | awk -F': *' '/space free:/ {gsub(/"/, "", $2); print $2; exit}')
total_raw=$(echo "$info" | awk -F': *' '/total space:/ {gsub(/"/, "", $2); print $2; exit}')
used_raw=$(echo "$info" | awk -F': *' '/space used:/ {gsub(/"/, "", $2); print $2; exit}')
if [[ "$free_raw" =~ ^[0-9]+$ ]]; then
free_bytes="$free_raw"
elif [[ "$total_raw" =~ ^[0-9]+$ && "$used_raw" =~ ^[0-9]+$ && "$total_raw" -ge "$used_raw" ]]; then
free_bytes=$((total_raw - used_raw))
fi
# Older/human output often has only "space used" + "total space" (no free line).
if [[ -z "${free_bytes:-}" ]]; then
info=$(LC_ALL=C incus storage info "$pool" 2>/dev/null || true)
free_raw=$(echo "$info" | awk -F': *' '/space free:/ {gsub(/"/, "", $2); print $2; exit}')
total_raw=$(echo "$info" | awk -F': *' '/total space:/ {gsub(/"/, "", $2); print $2; exit}')
used_raw=$(echo "$info" | awk -F': *' '/space used:/ {gsub(/"/, "", $2); print $2; exit}')
if [[ -n "$free_raw" ]]; then
free_bytes="$(_incus_parse_size_to_bytes "$free_raw" 2>/dev/null || true)"
elif [[ -n "$total_raw" && -n "$used_raw" ]]; then
total_bytes="$(_incus_parse_size_to_bytes "$total_raw" 2>/dev/null || true)"
used_bytes="$(_incus_parse_size_to_bytes "$used_raw" 2>/dev/null || true)"
if [[ -n "${total_bytes:-}" && -n "${used_bytes:-}" && "$total_bytes" -ge "$used_bytes" ]]; then
free_bytes=$((total_bytes - used_bytes))
fi
fi
fi
# A dir pool is just a path, so ask the filesystem when incus says nothing.
# Does not help lvm or zfs, where source is not a path.
if [[ -z "${free_bytes:-}" ]]; then
local src
src="$(LC_ALL=C incus storage get "$pool" source 2>/dev/null || true)"
if [[ "${INCUS_REMOTE:-local}" == "local" && -n "$src" && -d "$src" ]]; then
free_bytes="$(df -PB1 "$src" 2>/dev/null | awk 'NR==2 {print $4}')"
fi
fi
[[ -z "${free_bytes:-}" || "$free_bytes" -le 0 ]] && return 1
echo $((free_bytes / 1024 / 1024 / 1024))
}
incus_validate_storage_space() {
local pool="${1:-$CONTAINER_STORAGE}"
local need_gb="${2:-${DISK_SIZE:-4}}"
local free_gb
free_gb=$(incus_storage_pool_free_gb "$pool" 2>/dev/null || echo "")
if [[ -z "$free_gb" ]]; then
msg_warn "Could not determine free space on pool '${pool}' (continuing)"
return 0
fi
if [[ "$free_gb" -lt "$need_gb" ]]; then
# Match PVE behavior: warn, do not hard-abort (pool/dir drivers can still grow).
msg_warn "Pool '${pool}' reports ~${free_gb}GB free, container wants ${need_gb}GB"
msg_custom "ℹ️" "${YW}" "Source: incus storage info '${pool}' (pool free space, not full host disk)"
msg_custom "ℹ️" "${YW}" "Grow: incus storage set ${pool} size=50GiB | Or pick another pool"
return 0
fi
msg_ok "Storage space validated (${pool}: ~${free_gb}GB free)"
}
resolve_storage_preselect() {
local _class="${1:-container}"
local preselect="${2:-}"
[[ -z "$preselect" ]] && return 1
incus storage info "$preselect" &>/dev/null || return 1
STORAGE_RESULT="$preselect"
local free_gb
free_gb=$(incus_storage_pool_free_gb "$preselect" 2>/dev/null || true)
# "Free: ~?GB" reads like a broken template. Say what is actually known.
if [[ -n "$free_gb" ]]; then
STORAGE_INFO="Free: ~${free_gb}GB"
else
STORAGE_INFO="Free: unknown"
fi
return 0
}
check_storage_support() {
local _content="${1:-rootdir}"
case "$_content" in
vztmpl | template)
getent hosts images.linuxcontainers.org &>/dev/null
;;
*)
[[ "$(incus storage list -f csv,noheader 2>/dev/null | wc -l)" -gt 0 ]]
;;
esac
}
validate_storage_space() {
local pool="${1:-$CONTAINER_STORAGE}"
local need_gb="${2:-${DISK_SIZE:-4}}"
local show_dialog="${3:-no}"
local free_gb
free_gb=$(incus_storage_pool_free_gb "$pool" 2>/dev/null || echo "")
if [[ -z "$free_gb" ]]; then
[[ "$show_dialog" == "yes" ]] && whiptail --msgbox "⚠️ Warning: Could not determine free space on pool '${pool}'.\n\n(Checked via: incus storage info ${pool})" 12 64 2>/dev/null || true
return 0
fi
if [[ "$free_gb" -lt "$need_gb" ]]; then
if [[ "$show_dialog" == "yes" ]]; then
whiptail --msgbox "⚠️ Warning: Not enough space on Incus pool '${pool}'.\n\nRequired: ${need_gb}GB\nPool free: ~${free_gb}GB\n\nThis is pool free space (incus storage info),\nNOT your full host disk. Default/loop pools are often small.\n\nGrow pool: incus storage set ${pool} size=50GiB\nOr pick another pool in Advanced settings." 16 72 2>/dev/null || true
fi
return 1
fi
return 0
}
_incus_prepare_install_exports() {
# One bootstrap for every OS — see pve/backend.func for why the Alpine split
# went away.
export FUNCTIONS_FILE_PATH="$(_cs_fetch_text "lxc/install.func")"
export DIAGNOSTICS="${DIAGNOSTICS:-yes}"
export RANDOM_UUID="${RANDOM_UUID}"
export EXECUTION_ID="${EXECUTION_ID}"
export SESSION_ID="${SESSION_ID}"
export CACHER="${APT_CACHER:-}"
export CACHER_IP="${APT_CACHER_IP:-}"
export tz="${timezone:-UTC}"
export APPLICATION="$APP"
export app="$NSAPP"
export PASSWORD="$PW"
export VERBOSE="${VERBOSE:-no}"
export SSH_ROOT="${SSH:-no}"
export SSH_AUTHORIZED_KEY="${SSH_AUTHORIZED_KEY:-}"
export CTID="$CT_NAME"
export CTTYPE="${CT_TYPE:-1}"
export ENABLE_FUSE="${ENABLE_FUSE:-no}"
export ENABLE_TUN="${ENABLE_TUN:-no}"
export PCT_OSTYPE="${var_os:-debian}"
export PCT_OSVERSION="${var_version:-13}"
export PCT_DISK_SIZE="${DISK_SIZE}"
export IPV6_METHOD="${IPV6_METHOD:-auto}"
export ENABLE_GPU="${ENABLE_GPU:-no}"
export APPLICATION_VERSION="${var_appversion:-}"
# The container writes its own MOTD, so it has to know whether this is a
# testing build. Incus is not the testing repository, so this is normally
# empty here -- which is the point: it used to warn unconditionally.
declare -f cs_testing_state >/dev/null 2>&1 && cs_testing_state
export BUILD_LOG="${BUILD_LOG:-$INCUS_BUILD_LOG}"
export INSTALL_LOG="/root/.install-${SESSION_ID}.log"
export COMMUNITY_SCRIPTS_URL="${INCUS_COMMUNITY_SCRIPTS_URL}"
export COMMUNITY_SCRIPTS_CORE_URL="${COMMUNITY_SCRIPTS_CORE_URL}"
export MODE="${METHOD:-default}"
_HOST_LOGFILE="${BUILD_LOG:-$INCUS_BUILD_LOG}"
}
incus_create_lxc_container() {
LOGFILE="${INCUS_BUILD_LOG}"
[[ "${CT_NAME:-}" ]] || { msg_error "Container name not set"; exit 203; }
post_to_api 2>/dev/null || true
post_progress_to_api "validation" 2>/dev/null || true
check_storage_support "rootdir" || { msg_error "No Incus storage pools found"; exit 1; }
if resolve_storage_preselect container "${CONTAINER_STORAGE:-}"; then
STORAGE_POOL="$STORAGE_RESULT"
msg_ok "Storage ${BL}${STORAGE_POOL}${CL} (${STORAGE_INFO}) [Container]"
elif [[ -z "${CONTAINER_STORAGE:-}" ]]; then
select_storage container && STORAGE_POOL="$CONTAINER_STORAGE"
msg_ok "Storage ${BL}${STORAGE_POOL}${CL} [Container]"
else
STORAGE_POOL="${CONTAINER_STORAGE}"
fi
msg_info "Validating storage '${STORAGE_POOL}'"
incus storage info "$STORAGE_POOL" &>/dev/null || { msg_error "Storage pool '${STORAGE_POOL}' invalid"; exit 213; }
msg_ok "Storage '${STORAGE_POOL}' validated"
if ! incus network show "${BRG}" >/dev/null 2>&1; then
msg_warn "Network '${BRG}' not found, auto-selecting fallback"
BRG="$(incus_pick_default_network)"
msg_ok "Using network '${BRG}'"
fi
msg_info "Resolving container image"
local image_name=""
if _incus_resolve_launch_image; then
image_name="${INCUS_LAUNCH_IMAGE}"
msg_ok "Image ${BL}${image_name}${CL}"
else
image_name="${INCUS_LAUNCH_IMAGE:-images:${IMAGE_OS}/${IMAGE_VERSION}}"
msg_custom "ℹ️" "${YW}" "Image not cached yet — will try pull: ${image_name}"
fi
msg_info "Creating LXC Container"
incus_log_section "Container Creation: ${CT_NAME}"
local launch_args=()
launch_args+=("--config" "limits.cpu=${CORE_COUNT}")
launch_args+=("--config" "limits.memory=${RAM_SIZE}MiB")
launch_args+=("--config" "boot.autostart=true")
[[ -n "${PROFILE:-}" && "${PROFILE}" != "default" ]] && launch_args+=("--profile" "${PROFILE}")
launch_args+=("--network" "${BRG}")
[[ "${ENABLE_NESTING:-1}" == "1" ]] && launch_args+=("--config" "security.nesting=true")
# Settings the shared wizard already collects but that were dropped here.
# mknod maps onto the syscall interception Incus offers; protection maps onto
# the delete guard. keyctl has no Incus equivalent -- unprivileged containers
# get their own keyring session -- so it is deliberately not faked.
[[ "${ENABLE_MKNOD:-no}" == "yes" || "${ENABLE_MKNOD:-0}" == "1" ]] &&
launch_args+=("--config" "security.syscalls.intercept.mknod=true")
[[ "${PROTECTION:-no}" == "yes" || "${PROTECTION:-0}" == "1" ]] &&
launch_args+=("--config" "security.protection.delete=true")
# Container-only per the host's own /1.0/metadata/configuration. A core count
# caps how many CPUs are visible, an allowance caps how much of them may be
# used; both are cgroup constructs and do nothing on a VM.
[[ -n "${CPU_ALLOWANCE:-}" ]] &&
launch_args+=("--config" "limits.cpu.allowance=${CPU_ALLOWANCE}")
[[ -n "${CPU_PRIORITY:-}" ]] &&
launch_args+=("--config" "limits.cpu.priority=${CPU_PRIORITY}")
[[ -n "${MEMORY_SWAP:-}" ]] &&
launch_args+=("--config" "limits.memory.swap=${MEMORY_SWAP}")
[[ -n "${KERNEL_MODULES:-}" ]] &&
launch_args+=("--config" "linux.kernel_modules=${KERNEL_MODULES}")
if [[ "${CT_TYPE:-1}" != "1" ]]; then
launch_args+=("--config" "security.privileged=true")
fi
launch_args+=("--storage" "${STORAGE_POOL}")
launch_args+=("--device" "root,size=${DISK_SIZE}GiB")
# Prefer a unique name if the chosen one already exists.
if incus_container_exists "${CT_NAME}"; then
local alt
alt="$(incus_get_next_name "${CT_NAME}")"
msg_warn "Instance '${CT_NAME}' already exists — using '${alt}'"
CT_NAME="$alt"
CTID="$CT_NAME"
fi
{
echo "=== incus launch ${image_name} ${CT_NAME} ==="
echo "args: ${launch_args[*]}"
echo "user: $(id -un) uid=$(id -u)"
} >>"$LOGFILE"
if ! incus launch "${image_name}" "${CT_NAME}" "${launch_args[@]}" >>"$LOGFILE" 2>&1; then
# Retry alternate candidates once if primary pull failed
local retry_img="" launched=0
for retry_img in "images:${IMAGE_OS}/${IMAGE_VERSION}/cloud" \
"images:${IMAGE_OS}/$(incus_get_image_alias "${IMAGE_OS}" "${IMAGE_VERSION}" 2>/dev/null || true)" \
"images:${IMAGE_OS}/$(incus_get_image_alias "${IMAGE_OS}" "${IMAGE_VERSION}" 2>/dev/null || true)/cloud"; do
[[ -z "$retry_img" || "$retry_img" == "$image_name" || "$retry_img" == */ ]] && continue
msg_warn "Launch failed with ${image_name} — retrying ${retry_img}"
if incus launch "${retry_img}" "${CT_NAME}" "${launch_args[@]}" >>"$LOGFILE" 2>&1; then
image_name="$retry_img"
launched=1
break
fi
done
if [[ "$launched" -ne 1 ]]; then
msg_error "Failed to create container ${CT_NAME}"
echo -e "${YW}Last launch errors:${CL}"
tail -n 30 "$LOGFILE" 2>/dev/null | sed 's/^/ /' || true
echo -e "${YW}Log: ${BL}${LOGFILE}${CL}"
echo -e "${YW}Try manually:${CL} incus image copy images:${IMAGE_OS}/${IMAGE_VERSION} local: --alias ${IMAGE_OS}/${IMAGE_VERSION}"
exit 1
fi
fi
# Track for orphan cleanup on mid-create / mid-configure failures (EXIT trap).
# Reset handled/ok so a rebuild after install-recovery can prompt again if needed.
INCUS_CT_CREATED=1
INCUS_ORPHAN_HANDLED=0
INCUS_BUILD_OK=0
export INCUS_CT_CREATED INCUS_ORPHAN_HANDLED INCUS_BUILD_OK CT_NAME CTID
# Optional boot-time configs that some hosts/kernels reject for this
# container type. They fail when the container *starts*, not at 'config set'
# (e.g. kernel.keys.maxkeys is not writable from an unprivileged user
# namespace), so a plain set can silently persist a config that aborts the
# next boot. Apply best-effort and verify with a self-healing restart below.
# kernel.keys.maxkeys cannot be written from an unprivileged user namespace -
# lxc aborts the start with "Permission denied - Failed to setup sysctl
# parameters kernel.keys.maxkeys to 2000". This was set for CT_TYPE=1, which
# IS the unprivileged case, so every unprivileged create paid a failed start
# plus a rollback to reach the state it would have had anyway. Privileged
# only, and only when the host default is actually below what we want.
local optional_sysctl_pending=0
# The sysctl probe reads this machine; against a remote, just try the setting.
if [[ "${CT_TYPE:-1}" == "0" ]] &&
{ [[ "${INCUS_REMOTE:-local}" != "local" ]] || (($(cat /proc/sys/kernel/keys/maxkeys 2>/dev/null || echo 2000) < 2000)); }; then
if incus config set "${CT_NAME}" linux.sysctl.kernel.keys.maxkeys=2000 >>"$LOGFILE" 2>&1; then
optional_sysctl_pending=1
fi
fi
msg_ok "LXC Container ${CT_NAME} was successfully created."
msg_info "Waiting for container to initialize"
local waited=0
while ! incus_ct_exec true &>/dev/null; do
sleep 2
waited=$((waited + 2))
[[ "$waited" -ge 60 ]] && { msg_error "Container not ready"; exit 1; }
done
msg_ok "Container ${CT_NAME} is ready"
incus_set_container_hostname
local net_type="" net_reconfigure=0
net_type=$(incus network show "${BRG}" 2>/dev/null | awk '/^type:/ {print $2; exit}')
local nic_supports_ip=0
_incus_nic_supports_ip "$BRG" && nic_supports_ip=1
if [[ -n "${MAC:-}" ]]; then
_incus_device_set hwaddr "${MAC}" "Could not apply MAC (${MAC})" && net_reconfigure=1 || true
fi
if [[ -n "${VLAN_TAG:-}" ]]; then
_incus_device_set vlan "${VLAN_TAG}" "Could not apply VLAN (${VLAN_TAG})" && net_reconfigure=1 || true
fi
if [[ -n "${MTU:-}" ]]; then
_incus_device_set mtu "${MTU}" "Could not apply MTU (${MTU})" && net_reconfigure=1 || true
fi
if [[ "$nic_supports_ip" -eq 1 ]]; then
_incus_apply_addresses && net_reconfigure=1 || true
else
# An unmanaged bridge is the ordinary case here and not an error: the
# container simply takes an address from the LAN's own DHCP. Worth saying
# out loud though, because a static address typed into the wizard will not
# be applied and the summary would otherwise imply that it was.
if [[ -n "${NET:-}" && "${NET}" != "dhcp" ]]; then
msg_warn "Network '${BRG}' is not managed by Incus - ${NET} cannot be reserved there. The container will use DHCP from your LAN; set the address inside the container or reserve it on your router."
else
msg_info "Network '${BRG}' is not managed by Incus (type=${net_type:-unknown}) - addressing is left to your LAN"
fi
if [[ -n "${NET:-}" && "${NET}" != "dhcp" ]]; then
msg_custom "ℹ️" "${YW}" "Static IPv4 ${NET} was requested but cannot be set as device key on ${net_type:-this} network"
fi
fi
if [[ -n "${TAGS:-}" ]]; then
_incus_soft incus config set "${CT_NAME}" "user.tags=${TAGS}" >>"$LOGFILE" 2>&1
fi
# Restart when network devices changed, or to verify an optional boot-time
# sysctl we set above (so a rejected one is rolled back now rather than
# bricking a later reboot with boot.autostart=true).
if [[ "$net_reconfigure" -eq 1 || "$optional_sysctl_pending" -eq 1 ]]; then
if [[ "$net_reconfigure" -eq 1 ]]; then
msg_info "Reconfiguring network settings"
else
msg_info "Verifying container configuration"
fi
if _incus_restart_ct; then
if [[ "$net_reconfigure" -eq 1 ]]; then
msg_ok "Network settings applied"
else
msg_ok "Container configuration verified"
fi
else
# Everything past this point needs incus exec. Warning and carrying on
# over a stopped container is what turned one failed restart into three
# unrelated-looking errors further down.
msg_error "Container ${CT_NAME} is not running after configuration changes"
msg_custom "ℹ️" "${YW}" "See: incus info --show-log ${CT_NAME}"
return 1
fi
fi
}
incus_set_container_hostname() {
local hn="${CT_NAME}"
[[ -n "${HN:-}" ]] && hn="${HN}"
hn=$(echo "$hn" | tr '[:upper:]' '[:lower:]' | tr -d ' ' | tr '_' '-')
[[ -z "$hn" ]] && return 0
msg_info "Setting hostname to ${hn}"
_incus_soft incus config set "${CT_NAME}" "user.hostname=${hn}" >>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1
# Prefer instance name for system hostname when UI used CT_ID as name
local sys_hn="${CT_NAME}"
# sh: a fresh Alpine image has no bash yet.
if incus_ct_exec sh -c "
echo '${sys_hn}' >/etc/hostname
hostname '${sys_hn}' 2>/dev/null || true
if command -v hostnamectl >/dev/null 2>&1; then
hostnamectl set-hostname '${sys_hn}' 2>/dev/null || true
fi
if [ -f /etc/hosts ]; then
if grep -qE '^127\\.0\\.1\\.1' /etc/hosts; then
sed -i 's/^127\\.0\\.1\\.1.*/127.0.1.1 ${sys_hn}/' /etc/hosts
else
echo '127.0.1.1 ${sys_hn}' >>/etc/hosts
fi
fi
" >>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1; then
msg_ok "Hostname set to ${sys_hn}"
else
msg_warn "Could not set the hostname inside ${CT_NAME} (see the log)"
fi
}
incus_is_gpu_app() {
[[ "${var_gpu:-no}" == "yes" || "${ENABLE_GPU:-no}" == "yes" ]]
}
# Populate INTEL_GPUS/AMD_GPUS/NVIDIA_GPUS as "pci=<addr>|id=<n>|vendorid=<id>" selectors
# per https://linuxcontainers.org/incus/docs/main/reference/devices_gpu/
incus_detect_gpu_devices() {
INTEL_GPUS=()
AMD_GPUS=()
NVIDIA_GPUS=()
NVIDIA_CHAR_DEVS=()
local line pci vendor
# Prefer domain:bus:slot.func from lspci -D
while IFS= read -r line; do
[[ -z "$line" ]] && continue
pci=$(awk '{print $1}' <<<"$line")
[[ "$pci" =~ ^[0-9a-fA-F]+:[0-9a-fA-F]+:[0-9a-fA-F]+\.[0-9a-fA-F]+$ ]] || continue
if grep -q '\[8086:' <<<"$line"; then
INTEL_GPUS+=("pci=${pci}")
elif grep -qE '\[1002:|\[1022:' <<<"$line"; then
AMD_GPUS+=("pci=${pci}")
elif grep -q '\[10de:' <<<"$line"; then
NVIDIA_GPUS+=("pci=${pci}")
fi
done < <(lspci -nn -D 2>/dev/null | grep -E 'VGA|Display|3D' || true)
# DRM sysfs fallback (useful on ARM / non-PCI GPUs)
if [[ ${#INTEL_GPUS[@]} -eq 0 && ${#AMD_GPUS[@]} -eq 0 && ${#NVIDIA_GPUS[@]} -eq 0 && -d /sys/class/drm ]]; then
local card base drm_id vendor_hex
for card in /sys/class/drm/card[0-9]*; do
base=$(basename "$card")
[[ "$base" == *-* ]] && continue
drm_id="${base#card}"
vendor_hex=$(cat "$card/device/vendor" 2>/dev/null || true)
pci=$(basename "$(readlink -f "$card/device" 2>/dev/null)" 2>/dev/null || true)
local sel=""
if [[ -n "$pci" && "$pci" =~ ^[0-9a-fA-F]+:[0-9a-fA-F]+:[0-9a-fA-F]+\.[0-9a-fA-F]+$ ]]; then
sel="pci=${pci}"
elif [[ -n "$drm_id" ]]; then
sel="id=${drm_id}"
fi
[[ -z "$sel" ]] && continue
case "$vendor_hex" in
0x8086) INTEL_GPUS+=("$sel") ;;
0x1002 | 0x1022) AMD_GPUS+=("$sel") ;;
0x10de) NVIDIA_GPUS+=("$sel") ;;
esac
done
fi
# NVIDIA char devices as optional extra (driver nodes inside CT)
local d
for d in /dev/nvidia*; do
[[ -c "$d" ]] && NVIDIA_CHAR_DEVS+=("$d")
done
if [[ -d /dev/nvidia-caps ]]; then
for d in /dev/nvidia-caps/*; do
[[ -c "$d" ]] && NVIDIA_CHAR_DEVS+=("$d")
done
fi
if [[ ${#INTEL_GPUS[@]} -gt 0 ]]; then
msg_custom "🎮" "${BL}" "Detected Intel GPU (${#INTEL_GPUS[@]})"
fi
if [[ ${#AMD_GPUS[@]} -gt 0 ]]; then
msg_custom "🎮" "${RD}" "Detected AMD GPU (${#AMD_GPUS[@]})"
fi
if [[ ${#NVIDIA_GPUS[@]} -gt 0 ]]; then
msg_custom "🎮" "${GN}" "Detected NVIDIA GPU (${#NVIDIA_GPUS[@]})"
fi
return 0
}
_incus_add_gpu_physical() {
# $1 device name, $2 selector like pci=0000:00:02.0 or id=0 or vendorid=8086
local dev_name="$1" selector="$2"
local -a args=(gpu "gputype=physical")
args+=("$selector")
local video_gid
video_gid=$(getent group video 2>/dev/null | cut -d: -f3 || true)
[[ -n "$video_gid" ]] && args+=("gid=${video_gid}")
if incus config device add "${CT_NAME}" "$dev_name" "${args[@]}" >>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1; then
return 0
fi
# Retry without gid (some hosts reject host GIDs for unprivileged CTs)
args=(gpu "gputype=physical" "$selector")
if incus config device add "${CT_NAME}" "$dev_name" "${args[@]}" >>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1; then
return 0
fi
return 1
}
incus_configure_device_passthrough() {
if incus_is_gpu_app; then
incus_detect_gpu_devices
local selected_gpu="" gpu_count=0
local -a available_gpus=()
if [[ ${#INTEL_GPUS[@]} -gt 0 ]]; then
available_gpus+=("INTEL")
gpu_count=$((gpu_count + 1))
fi
if [[ ${#AMD_GPUS[@]} -gt 0 ]]; then
available_gpus+=("AMD")
gpu_count=$((gpu_count + 1))
fi
if [[ ${#NVIDIA_GPUS[@]} -gt 0 || ${#NVIDIA_CHAR_DEVS[@]} -gt 0 ]]; then
available_gpus+=("NVIDIA")
gpu_count=$((gpu_count + 1))
fi
if [[ "$gpu_count" -gt 0 ]]; then
# Several types can be attached together, and picking exactly one used to
# default to the first -- always INTEL, by collection order. On a host with
# an iGPU beside a discrete card that silently attached the iGPU only.
local -a selected_types=("${available_gpus[@]}")
if [[ "$gpu_count" -gt 1 ]]; then
echo -e "\n${INFO} Multiple GPU types detected:"
local gi
for gi in "${!available_gpus[@]}"; do
echo " $((gi + 1))) ${available_gpus[$gi]}"
done
echo " A) Pass through ALL of them"
local type_selection=""
read -r -t 60 -p "Select GPU type(s) (1-${gpu_count}, comma-separated, A=all) [timeout 60s, default=all]: " type_selection </dev/tty || type_selection=""
type_selection="${type_selection^^}"
if [[ -n "$type_selection" && "$type_selection" != "A" ]]; then
local -a gnums=()
local gnum
IFS=',' read -ra gnums <<<"$type_selection"
selected_types=()
for gnum in "${gnums[@]}"; do
gnum="${gnum// /}"
if [[ "$gnum" =~ ^[0-9]+$ ]] && ((gnum >= 1 && gnum <= gpu_count)); then
selected_types+=("${available_gpus[$((gnum - 1))]}")
fi
done
# A spare device is harmless; a missing one is the bug being fixed.
if [[ ${#selected_types[@]} -eq 0 ]]; then
msg_warn "No valid selection - passing through all detected GPUs"
selected_types=("${available_gpus[@]}")
fi
fi
fi
# idx is shared across types so the device names stay unique.
local sel added failed idx=0
local -a configured_types=()
for selected_gpu in "${selected_types[@]}"; do
added=0
failed=0
case "$selected_gpu" in
INTEL)
for sel in "${INTEL_GPUS[@]}"; do
if _incus_add_gpu_physical "gpu${idx}" "$sel"; then
added=$((added + 1))
else
failed=$((failed + 1))
msg_warn "Could not add Intel GPU (${sel})"
fi
idx=$((idx + 1))
done
# Vendor fallback if PCI/id adds failed entirely
if [[ "$added" -eq 0 ]]; then
_incus_add_gpu_physical "gpu0" "vendorid=8086" && added=1 || true
fi
if [[ "$added" -gt 0 ]]; then
configured_types+=("INTEL")
msg_ok "Intel GPU passthrough configured (${added})"
fi
;;
AMD)
for sel in "${AMD_GPUS[@]}"; do
if _incus_add_gpu_physical "gpu${idx}" "$sel"; then
added=$((added + 1))
else
failed=$((failed + 1))
msg_warn "Could not add AMD GPU (${sel})"
fi
idx=$((idx + 1))
done
if [[ "$added" -eq 0 ]]; then
_incus_add_gpu_physical "gpu0" "vendorid=1002" && added=1 || true
fi
if [[ "$added" -gt 0 ]]; then
configured_types+=("AMD")
msg_ok "AMD GPU passthrough configured (${added})"
fi
;;
NVIDIA)
for sel in "${NVIDIA_GPUS[@]}"; do
if _incus_add_gpu_physical "gpu${idx}" "$sel"; then
added=$((added + 1))
else
failed=$((failed + 1))
msg_warn "Could not add NVIDIA GPU (${sel})"
fi
idx=$((idx + 1))
done
if [[ "$added" -eq 0 ]]; then
_incus_add_gpu_physical "gpu0" "vendorid=10de" && added=1 || true
fi
# Optional NVIDIA char nodes (driver interface)
local ndev nidx=0
for ndev in "${NVIDIA_CHAR_DEVS[@]}"; do
local nname
nname=$(basename "$ndev" | tr -c 'A-Za-z0-9' '_')
incus config device add "${CT_NAME}" "nvidia_${nname}_${nidx}" unix-char "source=${ndev}" "path=${ndev}" >>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1 || true
nidx=$((nidx + 1))
done
if [[ "$added" -gt 0 || "$nidx" -gt 0 ]]; then
configured_types+=("NVIDIA")
msg_ok "NVIDIA GPU passthrough configured (gpu=${added}, char=${nidx})"
fi
;;
esac
done
# Space separated, so a reader can test for one type without caring how
# many others came with it.
export GPU_TYPE="${configured_types[*]}"
if [[ -z "${GPU_TYPE:-}" ]]; then
msg_warn "GPU passthrough requested but no device could be attached (check permissions / incus info --resources)"
fi
else
msg_custom "ℹ️" "${YW}" "No GPU devices found for passthrough (lspci/DRM empty)"
fi
fi
# USB serial (privileged / optional bind) — mirrors PVE passthrough.func
if [[ "${CT_TYPE:-1}" == "0" || "${ENABLE_USB:-no}" == "yes" ]]; then
local usb_dev usb_idx=0
for usb_dev in /dev/ttyUSB0 /dev/ttyUSB1 /dev/ttyACM0; do
[[ -e "$usb_dev" ]] || continue
local usb_name="usbchar${usb_idx}"
if incus config device add "${CT_NAME}" "$usb_name" unix-char "source=${usb_dev}" "path=${usb_dev}" \
>>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1; then
msg_ok "USB device ${usb_dev} attached as ${usb_name}"
else
msg_warn "Could not attach ${usb_dev} (need privileged CT or device permissions)"
fi
usb_idx=$((usb_idx + 1))
done
fi
# Optional extra disk: INCUS_EXTRA_DISK=/path/or/pool/volume INCUS_EXTRA_DISK_PATH=/mnt/data
if [[ -n "${INCUS_EXTRA_DISK:-${var_extra_disk:-}}" ]]; then
local edisk="${INCUS_EXTRA_DISK:-$var_extra_disk}"
local epath="${INCUS_EXTRA_DISK_PATH:-${var_extra_disk_path:-/mnt/extra}}"
msg_info "Adding extra disk device"
if incus config device add "${CT_NAME}" extradata disk "source=${edisk}" "path=${epath}" \
>>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1; then
msg_ok "Extra disk mounted at ${epath}"
else
msg_warn "Could not add extra disk (source=${edisk})"
fi
fi
if [[ "${ENABLE_TUN:-no}" == "yes" ]] && ! incus_ct_exec test -c /dev/net/tun 2>/dev/null; then
if incus config device add "${CT_NAME}" tun unix-char source=/dev/net/tun path=/dev/net/tun \
>>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1; then
msg_ok "TUN device attached"
else
msg_warn "Could not add TUN device"
echo -e "${TAB}${INFO} Nesting/Docker apps: also enable nesting (security.nesting=true)."
fi
fi
if [[ "${ENABLE_FUSE:-no}" == "yes" ]] && ! incus_ct_exec test -c /dev/fuse 2>/dev/null; then
if incus config device add "${CT_NAME}" fuse unix-char source=/dev/fuse path=/dev/fuse \
>>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1; then
msg_ok "FUSE device attached"
else
msg_warn "Could not add FUSE device"
fi
fi
if [[ -e /dev/apex_0 ]]; then
msg_custom "🔌" "${BL}" "Detected Coral TPU - configuring passthrough"
_incus_soft incus config device add "${CT_NAME}" apex0 unix-char source=/dev/apex_0 path=/dev/apex_0 >>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1
fi
return 0
}
incus_wait_for_network() {
msg_info "Waiting for network in LXC container"
local net_type="" max_wait=40
net_type=$(incus network show "${BRG:-}" 2>/dev/null | awk '/^type:/ {print $2; exit}')
case "${net_type}" in
physical | macvlan | sriov) max_wait=90 ;;
esac
local ip_in_lxc="" i
for ((i = 1; i <= max_wait; i++)); do
ip_in_lxc=$(incus_ct_exec ip -4 addr show dev eth0 2>/dev/null | awk '/inet / {print $2}' | cut -d/ -f1)
[[ -z "$ip_in_lxc" ]] && ip_in_lxc=$(incus_ct_exec ip -6 addr show dev eth0 scope global 2>/dev/null | awk '/inet6 / {print $2}' | cut -d/ -f1 | head -n1)
[[ -z "$ip_in_lxc" ]] && ip_in_lxc=$(incus_instance_field "${CT_NAME}" 4 | tr -d '"' | awk '{print $1}' | cut -d/ -f1)
[[ -n "$ip_in_lxc" && "$ip_in_lxc" != "-" ]] && break
sleep 1
done
if [[ -z "$ip_in_lxc" || "$ip_in_lxc" == "-" ]]; then
msg_warn "No IP assigned to ${CT_NAME} after ${max_wait}s — continuing anyway"
echo -e "${YW}Troubleshooting:${CL}"
echo " • Verify network ${BRG} exists and has connectivity"
echo " • Check DHCP server (physical/macvlan often needs >20s)"
echo " • Verify static IP configuration"
echo -e "${YW}Installation will continue; network-dependent steps may fail.${CL}"
export IP=""
return 0
fi
local ping_success=false retry
for retry in {1..3}; do
if incus_ct_exec ping -c 1 -W 2 1.1.1.1 &>/dev/null ||
incus_ct_exec ping -c 1 -W 2 8.8.8.8 &>/dev/null ||
incus_ct_exec ping6 -c 1 -W 2 2606:4700:4700::1111 &>/dev/null; then
ping_success=true
break
fi
sleep 2
done
if [[ "$ping_success" == "false" ]]; then
msg_warn "Network configured (IP: $ip_in_lxc) but connectivity test failed"
echo -e "${YW}Container may have limited internet access. Installation will continue...${CL}"
else
msg_ok "Network in LXC is reachable (ping)"
fi
msg_ok "IP set to ${ip_in_lxc}"
export IP="$ip_in_lxc"
}
fix_gpu_gids() {
[[ -z "${GPU_TYPE:-}" ]] && return 0
msg_info "Detecting and setting correct GPU group IDs"
local video_gid render_gid
video_gid=$(incus_ct_exec getent group video 2>/dev/null | cut -d: -f3)
render_gid=$(incus_ct_exec getent group render 2>/dev/null | cut -d: -f3)
[[ -z "$video_gid" ]] && incus_ct_exec groupadd -r video 2>/dev/null || true
[[ -z "$render_gid" ]] && incus_ct_exec groupadd -r render 2>/dev/null || true
video_gid=$(incus_ct_exec getent group video 2>/dev/null | cut -d: -f3)
render_gid=$(incus_ct_exec getent group render 2>/dev/null | cut -d: -f3)
[[ -z "$video_gid" ]] && video_gid="44"
[[ -z "$render_gid" ]] && render_gid="104"
# Incus gpu devices support gid= (container ownership) — docs: devices_gpu
local dev_name
while IFS= read -r dev_name; do
[[ -z "$dev_name" || "$dev_name" != gpu* ]] && continue
_incus_soft incus config device set "${CT_NAME}" "$dev_name" "gid=${video_gid}" "mode=0660" >>"${LOGFILE:-$INCUS_BUILD_LOG}" 2>&1
done < <(incus config device list "${CT_NAME}" 2>/dev/null || true)
# Best-effort permissions inside the CT when /dev/dri is visible
incus_ct_exec bash -c "
if [[ -d /dev/dri ]]; then
for dev in /dev/dri/*; do
[[ -e \"\$dev\" ]] || continue
case \"\$dev\" in
*renderD*) chgrp ${render_gid} \"\$dev\" 2>/dev/null || true ;;
*) chgrp ${video_gid} \"\$dev\" 2>/dev/null || true ;;
esac
chmod 660 \"\$dev\" 2>/dev/null || true
done
fi
" &>/dev/null || true
msg_ok "GPU passthrough configured (video:${video_gid}, render:${render_gid})"
}
incus_fix_debian13_root_ownership() {
[[ "${var_os:-}" == "debian" && "${var_version:-}" == "13" ]] || return 0
incus_ct_exec chown root:root / 2>/dev/null || true
}
incus_set_root_password() {
[[ -z "${PW:-}" ]] && return 0
local pw_raw="${PW#--password }"
[[ -z "$pw_raw" ]] && return 0
msg_info "Setting root password"
printf 'root:%s\n' "$pw_raw" | incus exec "${CT_NAME}" -- chpasswd &>/dev/null && msg_ok "Set root password" || msg_warn "Could not set root password"
}
incus_customize_container() {
msg_info "Customizing LXC Container"
ARCH="$(_cs_host_arch)"
if [[ "${var_os:-debian}" == "alpine" ]]; then
sleep 2
local alpine_rel="v${IMAGE_VERSION:-${var_version:-3.21}}"
[[ "$alpine_rel" != v3.* ]] && alpine_rel="latest-stable"
incus_ct_exec /bin/sh -c "cat <<EOF >/etc/apk/repositories
http://dl-cdn.alpinelinux.org/alpine/${alpine_rel}/main
http://dl-cdn.alpinelinux.org/alpine/${alpine_rel}/community
EOF"
incus_ct_exec ash -c "apk add bash newt curl openssh nano mc ncurses jq >/dev/null" || msg_warn "Alpine base package install had issues"
elif [[ "${var_os:-debian}" =~ ^(debian|ubuntu|devuan)$ ]]; then
sleep 2
local _ct_env='export LC_ALL=C.UTF-8 LANG=C.UTF-8 DEBIAN_FRONTEND=noninteractive;'
[[ "${var_os}" == "devuan" ]] && incus_ct_exec bash -c "${_ct_env} apt-get update >/dev/null && apt-get install -y locales >/dev/null" || true
local tz_val="${timezone:-UTC}"
[[ -z "$tz_val" ]] && tz_val=$(timedatectl show --property=Timezone --value 2>/dev/null || echo "UTC")