-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.func
More file actions
1718 lines (1564 loc) · 57.6 KB
/
Copy pathinstall.func
File metadata and controls
1718 lines (1564 loc) · 57.6 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
# Author: tteck (tteckster)
# Co-Author: MickLesk
# Co-Author: michelroegl-brunner
# License: MIT | https://github.com/community-scripts/ProxmoxVED/raw/main/LICENSE
# ==============================================================================
# INSTALL.FUNC - UNIFIED CONTAINER INSTALLATION & SETUP
# ==============================================================================
# All-in-One install.func supporting official Proxmox LXC templates:
# - Debian, Ubuntu, Devuan (apt, systemd/sysvinit)
# - Alpine (apk, OpenRC)
# - Fedora, Rocky, AlmaLinux, CentOS Stream (dnf, systemd)
# - openSUSE (zypper, systemd)
# - Gentoo (emerge, OpenRC)
# - openEuler (dnf, systemd)
#
# Supported templates (pveam available):
# almalinux-9/10, alpine-3.x, centos-9-stream, debian-12/13,
# devuan-5, fedora-42, gentoo-current, openeuler-25,
# opensuse-15.x, rockylinux-9/10, ubuntu-22.04/24.04/25.04
#
# Features:
# - Automatic OS detection
# - Unified package manager abstraction
# - Init system abstraction (systemd/OpenRC/sysvinit)
# - Network connectivity verification
# - MOTD and SSH configuration
# - Container customization
#
# ==============================================================================
# ==============================================================================
# SECTION 1: INITIALIZATION & OS DETECTION
# ==============================================================================
# Global variables for OS detection
# ── Engine URL (container side) ───────────────────────────────────────────────
# Inside the container there is no _cs_source_func resolver, so names are
# folder-qualified paths relative to the repo root, same as on the host.
_cs_core_url() {
echo "${COMMUNITY_SCRIPTS_CORE_URL:-https://raw.githubusercontent.com/community-scripts/core/main}/${1:?func path}"
}
# The engine reaches a container in nine pieces. The host's prefetch cannot
# help here — a container has its own filesystem — so fetch them concurrently
# on this side too. verify-split-files.yml checks the list is complete.
_CS_CT_ENGINE_FILES=(
core/core.func core/error_handler.func
lib/tools.func lib/alpine.func lib/db.func lib/forge.func
lib/hwaccel.func lib/runtime.func lib/system.func
)
_cs_ct_prefetch_engine() {
[[ -n "${COMMUNITY_SCRIPTS_CORE_DIR:-}" ]] && return 0
[[ "${COMMUNITY_SCRIPTS_NO_PREFETCH:-0}" == "1" ]] && return 1
command -v curl >/dev/null 2>&1 || return 1
local ver major minor
ver="$(curl --version 2>/dev/null | head -1 | awk '{print $2}')" || return 1
major="${ver%%.*}"
minor="${ver#*.}"
minor="${minor%%.*}"
[[ "$major" =~ ^[0-9]+$ && "$minor" =~ ^[0-9]+$ ]] || return 1
((major > 7 || (major == 7 && minor >= 66))) || return 1
local base dir=""
for base in /dev/shm "${TMPDIR:-/tmp}" /tmp; do
[[ -d "$base" && -w "$base" ]] || continue
dir="$(mktemp -d "${base}/cs-engine.XXXXXX" 2>/dev/null)" && break
dir=""
done
[[ -z "$dir" ]] && return 1
local args=() rel core_base
core_base="${COMMUNITY_SCRIPTS_CORE_URL:-https://raw.githubusercontent.com/community-scripts/core/main}"
mkdir -p "${dir}/core" "${dir}/lib" 2>/dev/null || true
for rel in "${_CS_CT_ENGINE_FILES[@]}"; do
args+=(-o "${dir}/${rel}" "${core_base}/${rel}")
done
curl -fsSL --parallel --parallel-immediate --parallel-max 16 \
--connect-timeout 10 --max-time 60 "${args[@]}" 2>/dev/null
local kept=0
for rel in "${_CS_CT_ENGINE_FILES[@]}"; do
if [[ -s "${dir}/${rel}" ]]; then
kept=$((kept + 1))
else
rm -f "${dir}/${rel}" 2>/dev/null
fi
done
if ((kept == 0)); then
rm -rf "$dir" 2>/dev/null
return 1
fi
COMMUNITY_SCRIPTS_CORE_DIR="$dir"
export COMMUNITY_SCRIPTS_CORE_DIR
return 0
}
# Prefetched copy when there is one, network otherwise.
_cs_engine_read() {
local name="${1:?func path}"
local copy="${COMMUNITY_SCRIPTS_CORE_DIR:-}/${name}"
if [[ -n "${COMMUNITY_SCRIPTS_CORE_DIR:-}" && -s "$copy" ]]; then
cat "$copy"
return 0
fi
if command -v curl >/dev/null 2>&1; then
curl -fsSL "$(_cs_core_url "$name")"
else
wget -qO- "$(_cs_core_url "$name")"
fi
}
OS_TYPE="" # debian, ubuntu, devuan, alpine, fedora, rocky, alma, centos, opensuse, gentoo, openeuler
OS_FAMILY="" # debian, alpine, rhel, suse, gentoo, arch
OS_VERSION="" # Version number
PKG_MANAGER="" # apt, apk, dnf, yum, zypper, emerge
INIT_SYSTEM="" # systemd, openrc, sysvinit
# ------------------------------------------------------------------------------
# detect_os()
#
# Detects the operating system and sets global variables:
# OS_TYPE, OS_FAMILY, OS_VERSION, PKG_MANAGER, INIT_SYSTEM
# ------------------------------------------------------------------------------
detect_os() {
if [[ -f /etc/os-release ]]; then
# shellcheck disable=SC1091
. /etc/os-release
OS_TYPE="${ID:-unknown}"
# Normalize to lowercase: some distros ship mixed-case IDs (e.g. openEuler ID="openEuler")
OS_TYPE="${OS_TYPE,,}"
OS_VERSION="${VERSION_ID:-unknown}"
elif [[ -f /etc/alpine-release ]]; then
OS_TYPE="alpine"
OS_VERSION=$(cat /etc/alpine-release)
elif [[ -f /etc/debian_version ]]; then
OS_TYPE="debian"
OS_VERSION=$(cat /etc/debian_version)
elif [[ -f /etc/redhat-release ]]; then
OS_TYPE="centos"
OS_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release | head -1)
elif [[ -f /etc/arch-release ]]; then
OS_TYPE="arch"
OS_VERSION="rolling"
elif [[ -f /etc/gentoo-release ]]; then
OS_TYPE="gentoo"
OS_VERSION=$(cat /etc/gentoo-release | grep -oE '[0-9.]+')
else
OS_TYPE="unknown"
OS_VERSION="unknown"
fi
# Normalize OS type and determine family
case "$OS_TYPE" in
debian)
OS_FAMILY="debian"
PKG_MANAGER="apt"
;;
ubuntu)
OS_FAMILY="debian"
PKG_MANAGER="apt"
;;
devuan)
OS_FAMILY="debian"
PKG_MANAGER="apt"
;;
alpine)
OS_FAMILY="alpine"
PKG_MANAGER="apk"
;;
fedora)
OS_FAMILY="rhel"
PKG_MANAGER="dnf"
;;
rocky | rockylinux)
OS_TYPE="rocky"
OS_FAMILY="rhel"
PKG_MANAGER="dnf"
;;
alma | almalinux)
OS_TYPE="alma"
OS_FAMILY="rhel"
PKG_MANAGER="dnf"
;;
centos)
OS_FAMILY="rhel"
# CentOS 7 uses yum, 8+ uses dnf
if [[ "${OS_VERSION%%.*}" -ge 8 ]]; then
PKG_MANAGER="dnf"
else
PKG_MANAGER="yum"
fi
;;
rhel)
OS_FAMILY="rhel"
PKG_MANAGER="dnf"
;;
openeuler)
OS_FAMILY="rhel"
PKG_MANAGER="dnf"
;;
opensuse* | sles)
OS_TYPE="opensuse"
OS_FAMILY="suse"
PKG_MANAGER="zypper"
;;
arch | archlinux)
OS_TYPE="arch"
OS_FAMILY="arch"
PKG_MANAGER="pacman"
;;
gentoo)
OS_FAMILY="gentoo"
PKG_MANAGER="emerge"
;;
*)
OS_FAMILY="unknown"
PKG_MANAGER="unknown"
;;
esac
# Detect init system
if command -v systemctl &>/dev/null && [[ -d /run/systemd/system ]]; then
INIT_SYSTEM="systemd"
elif command -v rc-service &>/dev/null || [[ -d /etc/init.d && -f /sbin/openrc ]]; then
INIT_SYSTEM="openrc"
elif [[ -f /etc/inittab ]]; then
INIT_SYSTEM="sysvinit"
else
INIT_SYSTEM="unknown"
fi
}
# ------------------------------------------------------------------------------
# Bootstrap: Ensure curl is available and source core functions
# ------------------------------------------------------------------------------
_bootstrap() {
# Minimal bootstrap to get curl installed
if ! command -v curl &>/dev/null; then
printf "\r\e[2K%b" '\033[93m Setup Source \033[m' >&2
if command -v apt-get &>/dev/null; then
apt-get update &>/dev/null && apt-get install -y curl &>/dev/null
elif command -v apk &>/dev/null; then
apk update &>/dev/null && apk add curl &>/dev/null
elif command -v dnf &>/dev/null; then
dnf install -y curl &>/dev/null
elif command -v yum &>/dev/null; then
yum install -y curl &>/dev/null
elif command -v zypper &>/dev/null; then
zypper install -y curl &>/dev/null
elif command -v pacman &>/dev/null; then
pacman -Sy --noconfirm curl &>/dev/null
elif command -v emerge &>/dev/null; then
# Gentoo stage3 has no curl and no portage tree on first boot.
# Sync portage (webrsync = fast snapshot) then prefer binary package.
emerge-webrsync --quiet &>/dev/null || emerge --sync --quiet &>/dev/null
emerge --quiet --getbinpkg --usepkg net-misc/curl &>/dev/null ||
emerge --quiet net-misc/curl &>/dev/null
fi
fi
# Last resort: if curl still missing but wget is available (Gentoo stage3),
# use wget for the bootstrap source fetch so we don't fail immediately.
local _fetch
if command -v curl &>/dev/null; then
_fetch="curl -fsSL"
elif command -v wget &>/dev/null; then
_fetch="wget -qO-"
else
echo "ERROR: neither curl nor wget available — cannot bootstrap" >&2
exit 1
fi
# Two roots: the engine (core) and the scripts live in separate repos, and
# inside the container there is no resolver — the host exports both bases.
# Override either independently for fork/branch testing.
COMMUNITY_SCRIPTS_URL="${COMMUNITY_SCRIPTS_URL:-https://raw.githubusercontent.com/community-scripts/ProxmoxVED/main}"
COMMUNITY_SCRIPTS_CORE_URL="${COMMUNITY_SCRIPTS_CORE_URL:-https://raw.githubusercontent.com/community-scripts/core/main}"
# Mark container context BEFORE error handling starts: error_handler/on_exit
# must write local failure artifacts instead of talking to the telemetry API
# (the host is the single telemetry reporter).
export TELEMETRY_CONTEXT="container"
# Source core functions
_cs_ct_prefetch_engine || true
source <(_cs_engine_read core/core.func)
source <(_cs_engine_read core/error_handler.func)
# The dev helpers are worth a round trip only when a flag is set: core.func's
# timing hooks no-op without them, and error_handler's exit path asks for the
# summary with declare -f. The host exports the parsed DEV_MODE_* flags, so
# there is nothing to re-parse on this side.
if [[ -n "${dev_mode:-}" ]]; then
source <(_cs_engine_read core/dev-mode.func)
fi
load_functions
catch_errors
get_lxc_ip
}
# Run bootstrap and OS detection
_bootstrap
detect_os
# Persist diagnostics setting inside container (exported from build.func)
# so addon scripts running later can find the user's choice
if [[ ! -f /usr/local/community-scripts/diagnostics ]]; then
mkdir -p /usr/local/community-scripts
echo "DIAGNOSTICS=${DIAGNOSTICS:-no}" >/usr/local/community-scripts/diagnostics
fi
# ------------------------------------------------------------------------------
# post_progress_to_api()
#
# - Lightweight progress ping from inside the container
# - Updates the existing telemetry record status
# - Arguments:
# * $1: status (optional, default: "configuring")
# - Signals that the installation is actively progressing (not stuck)
# - Fire-and-forget: never blocks or fails the script
# - Only executes if DIAGNOSTICS=yes and RANDOM_UUID is set
# ------------------------------------------------------------------------------
post_progress_to_api() {
command -v curl &>/dev/null || return 0
[[ "${DIAGNOSTICS:-no}" == "no" ]] && return 0
[[ -z "${RANDOM_UUID:-}" ]] && return 0
local progress_status="${1:-configuring}"
# Progress pings are the ONLY telemetry a container sends (terminal statuses
# are reported by the host). Include execution_id + repo attribution
# (exported by the host) so the server can correlate and filter these rows.
curl -fsS -m 5 -X POST "https://telemetry.community-scripts.org/telemetry" \
-H "Content-Type: application/json" \
-d "{\"random_id\":\"${RANDOM_UUID}\",\"execution_id\":\"${EXECUTION_ID:-${RANDOM_UUID}}\",\"type\":\"lxc\",\"nsapp\":\"${app:-unknown}\",\"status\":\"${progress_status}\",\"platform\":\"${TELEMETRY_PLATFORM:-}\",\"repo_source\":\"${REPO_SOURCE:-}\",\"repo_slug\":\"${REPO_SLUG:-}\"}" &>/dev/null || true
}
# ==============================================================================
# SECTION 2: PACKAGE MANAGER ABSTRACTION
# ==============================================================================
# ------------------------------------------------------------------------------
# pkg_update()
#
# Updates package manager cache/database
# ------------------------------------------------------------------------------
pkg_update() {
# Safety: re-detect if PKG_MANAGER doesn't match available commands
if [[ "$PKG_MANAGER" == "apt" ]] && ! command -v apt-get &>/dev/null; then
msg_warn "PKG_MANAGER='apt' but apt-get not found (OS: ${OS_TYPE:-unknown}) — re-detecting"
detect_os
fi
if [[ "$PKG_MANAGER" == "apk" ]] && ! command -v apk &>/dev/null; then
msg_warn "PKG_MANAGER='apk' but apk not found (OS: ${OS_TYPE:-unknown}) — re-detecting"
detect_os
fi
case "$PKG_MANAGER" in
apt)
if ! $STD apt-get update; then
local failed_mirror
failed_mirror=$(grep -m1 -oP '(?<=URIs: https?://)[^/]+' /etc/apt/sources.list.d/debian.sources 2>/dev/null || grep -m1 -oP '(?<=deb https?://)[^/]+' /etc/apt/sources.list 2>/dev/null || echo "unknown")
msg_warn "apt-get update failed (${failed_mirror}), trying alternate mirrors..."
local distro
distro=$(. /etc/os-release 2>/dev/null && echo "$ID" || echo "debian")
local eu_mirrors us_mirrors ap_mirrors
if [[ "$distro" == "ubuntu" ]]; then
eu_mirrors="de.archive.ubuntu.com fr.archive.ubuntu.com se.archive.ubuntu.com nl.archive.ubuntu.com it.archive.ubuntu.com ch.archive.ubuntu.com mirrors.xtom.de"
us_mirrors="us.archive.ubuntu.com archive.ubuntu.com mirrors.edge.kernel.org mirror.csclub.uwaterloo.ca mirrors.ocf.berkeley.edu mirror.math.princeton.edu"
ap_mirrors="au.archive.ubuntu.com jp.archive.ubuntu.com kr.archive.ubuntu.com tw.archive.ubuntu.com mirror.aarnet.edu.au"
else
eu_mirrors="ftp.de.debian.org ftp.fr.debian.org ftp.nl.debian.org ftp.uk.debian.org ftp.ch.debian.org ftp.se.debian.org ftp.it.debian.org ftp.fau.de ftp.halifax.rwth-aachen.de debian.mirror.lrz.de mirror.init7.net debian.ethz.ch mirrors.dotsrc.org debian.mirrors.ovh.net"
us_mirrors="ftp.us.debian.org ftp.ca.debian.org debian.csail.mit.edu mirrors.ocf.berkeley.edu mirrors.wikimedia.org debian.osuosl.org mirror.cogentco.com"
ap_mirrors="ftp.au.debian.org ftp.jp.debian.org ftp.tw.debian.org ftp.kr.debian.org ftp.hk.debian.org ftp.sg.debian.org mirror.aarnet.edu.au mirror.nitc.ac.in"
fi
local tz regional others
tz=$(cat /etc/timezone 2>/dev/null || echo "UTC")
case "$tz" in
Europe/* | Arctic/*)
regional="$eu_mirrors"
others="$us_mirrors $ap_mirrors"
;;
America/*)
regional="$us_mirrors"
others="$eu_mirrors $ap_mirrors"
;;
Asia/* | Australia/* | Pacific/*)
regional="$ap_mirrors"
others="$eu_mirrors $us_mirrors"
;;
*)
regional=""
others="$eu_mirrors $us_mirrors $ap_mirrors"
;;
esac
echo 'Acquire::By-Hash "no";' >/etc/apt/apt.conf.d/99no-by-hash
_try_apt_mirror() {
local m=$1
for src in /etc/apt/sources.list.d/debian.sources /etc/apt/sources.list; do
[[ -f "$src" ]] && sed -i "s|URIs: http[s]*://[^/]*/|URIs: http://${m}/|g; s|deb http[s]*://[^/]*/|deb http://${m}/|g" "$src"
done
rm -rf /var/lib/apt/lists/*
local out
out=$(apt-get update 2>&1)
if echo "$out" | grep -qi "hashsum\|hash sum"; then
msg_warn "Mirror ${m} failed (hash mismatch)"
return 1
elif echo "$out" | grep -qi "SSL\|certificate"; then
msg_warn "Mirror ${m} failed (SSL/certificate error)"
return 1
elif echo "$out" | grep -q "^E:"; then
msg_warn "Mirror ${m} failed (apt-get update error)"
return 1
else
msg_ok "CDN set to ${m}: tests passed"
return 0
fi
}
_scan_reachable() {
local result=""
for m in $1; do
if timeout 2 bash -c "echo >/dev/tcp/$m/80" 2>/dev/null; then
result="$result $m"
fi
done
echo "$result" | xargs
}
local apt_ok=false
# Phase 1: Scan global mirrors first (independent of local CDN issues)
local others_ok
others_ok=$(_scan_reachable "$others")
local others_pick
others_pick=$(printf '%s\n' $others_ok | shuf | head -3 | xargs)
for mirror in $others_pick; do
msg_custom "${INFO}" "${YW}" "Attempting mirror: ${mirror}"
if _try_apt_mirror "$mirror"; then
apt_ok=true
break
fi
done
# Phase 2: Try primary mirror
if [[ "$apt_ok" != true ]]; then
local primary
if [[ "$distro" == "ubuntu" ]]; then
primary="archive.ubuntu.com"
else
primary="ftp.debian.org"
fi
if timeout 2 bash -c "echo >/dev/tcp/$primary/80" 2>/dev/null; then
msg_custom "${INFO}" "${YW}" "Attempting mirror: ${primary}"
if _try_apt_mirror "$primary"; then
apt_ok=true
fi
fi
fi
# Phase 3: Fall back to regional mirrors
if [[ "$apt_ok" != true ]]; then
local regional_ok
regional_ok=$(_scan_reachable "$regional")
local regional_pick
regional_pick=$(printf '%s\n' $regional_ok | shuf | head -3 | xargs)
for mirror in $regional_pick; do
msg_custom "${INFO}" "${YW}" "Attempting mirror: ${mirror}"
if _try_apt_mirror "$mirror"; then
apt_ok=true
break
fi
done
fi
# Phase 4: All auto mirrors failed, prompt user
if [[ "$apt_ok" != true ]]; then
msg_warn "Multiple mirrors failed (possible CDN synchronization issue)."
if [[ "$distro" == "ubuntu" ]]; then
msg_warn "Find Ubuntu mirrors at: https://launchpad.net/ubuntu/+archivemirrors"
else
msg_warn "Find Debian mirrors at: https://www.debian.org/mirror/list"
fi
while true; do
read -rp " Enter a mirror hostname (or 'skip' to abort): " custom_mirror </dev/tty
[[ -z "$custom_mirror" ]] && continue
[[ "$custom_mirror" == "skip" ]] && break
[[ ! "$custom_mirror" =~ ^[a-zA-Z0-9._-]+$ ]] && {
msg_warn "Invalid hostname format."
continue
}
if _try_apt_mirror "$custom_mirror"; then
apt_ok=true
break
fi
msg_warn "Mirror '${custom_mirror}' also failed. Try another or type 'skip'."
done
fi
if [[ "$apt_ok" != true ]]; then
msg_error "All mirrors failed. Check network or try again later."
return 1
fi
fi
;;
apk)
if ! $STD apk update; then
msg_warn "apk update failed (dl-cdn.alpinelinux.org), trying alternate mirrors..."
local alpine_mirrors="mirror.init7.net ftp.halifax.rwth-aachen.de mirrors.edge.kernel.org alpine.mirror.wearetriple.com mirror.leaseweb.com uk.alpinelinux.org dl-2.alpinelinux.org dl-4.alpinelinux.org"
local apk_ok=false
for m in $(printf '%s\n' $alpine_mirrors | shuf); do
if timeout 2 bash -c "echo >/dev/tcp/$m/80" 2>/dev/null; then
msg_custom "${INFO}" "${YW}" "Attempting mirror: ${m}"
cat <<EOF >/etc/apk/repositories
http://$m/alpine/latest-stable/main
http://$m/alpine/latest-stable/community
EOF
if $STD apk update; then
msg_ok "CDN set to ${m}: tests passed"
apk_ok=true
break
else
msg_warn "Mirror ${m} failed"
fi
fi
done
if [[ "$apk_ok" != true ]]; then
msg_error "All Alpine mirrors failed. Check network or try again later."
return 1
fi
fi
;;
dnf)
# Speed up DNF: enable parallel downloads if not already configured
if [[ -f /etc/dnf/dnf.conf ]] && ! grep -q 'max_parallel_downloads' /etc/dnf/dnf.conf; then
echo 'max_parallel_downloads=10' >>/etc/dnf/dnf.conf
fi
# openEuler: default repos point to repo.openeuler.org (China).
# Pick the fastest reachable mirror based on timezone to avoid cross-continent latency.
if [[ "${OS_TYPE:-}" == "openeuler" ]] && ls /etc/yum.repos.d/*.repo &>/dev/null 2>&1; then
if grep -ql 'repo\.openeuler\.org\|repo\.openeuler\.openatom\.cn' /etc/yum.repos.d/*.repo 2>/dev/null; then
local _oe_tz _oe_mirror _oe_candidates=()
_oe_tz=$(cat /etc/timezone 2>/dev/null || timedatectl show --property=Timezone --value 2>/dev/null || echo "UTC")
# Build candidate list, best-first for the region
case "$_oe_tz" in
Europe/* | Arctic/*)
_oe_candidates=(
"https://ftp.agdsn.de/openeuler/" # Germany (TU Dresden)
"https://mirrors.dotsrc.org/openeuler/" # Denmark
"https://mirror.accum.se/mirror/openeuler.org/" # Sweden
"https://ftp.belnet.be/mirror/openeuler/" # Belgium
)
;;
America/*)
# No dedicated Americas mirror yet — European mirrors still beat China
_oe_candidates=(
"https://ftp.agdsn.de/openeuler/"
"https://mirrors.dotsrc.org/openeuler/"
"https://ftp.belnet.be/mirror/openeuler/"
)
;;
Asia/Singapore | Asia/Kuala_Lumpur | Asia/Jakarta | Asia/Bangkok | Asia/Ho_Chi_Minh)
_oe_candidates=(
"https://mirror.freedif.org/openEuler/" # Singapore
"https://linux.domainesia.com/openeuler/" # Indonesia
"https://mirrors.aliyun.com/openeuler/" # China (fast in SEA)
)
;;
Asia/* | Australia/* | Pacific/*)
_oe_candidates=(
"https://mirrors.aliyun.com/openeuler/"
"https://mirrors.huaweicloud.com/openeuler/"
"https://mirror.freedif.org/openEuler/"
)
;;
*)
# Unknown timezone — try EU mirrors before falling back to origin
_oe_candidates=(
"https://ftp.agdsn.de/openeuler/"
"https://mirrors.dotsrc.org/openeuler/"
)
;;
esac
# Pick first mirror that responds within 3 s
_oe_mirror=""
for _m in "${_oe_candidates[@]}"; do
if curl -sf --head --max-time 3 "$_m" &>/dev/null; then
_oe_mirror="$_m"
break
fi
done
if [[ -n "$_oe_mirror" ]]; then
sed -i -E \
"s|https?://repo\.openeuler\.org/|${_oe_mirror}|g;
s|https?://repo\.openeuler\.openatom\.cn/|${_oe_mirror}|g" \
/etc/yum.repos.d/*.repo
fi
fi
fi
$STD dnf makecache
;;
yum)
$STD yum makecache
;;
zypper)
$STD zypper refresh
;;
pacman)
$STD pacman -Sy --noconfirm
;;
emerge)
$STD emerge --sync
;;
*)
msg_error "Unknown package manager: $PKG_MANAGER"
return 1
;;
esac
}
# ------------------------------------------------------------------------------
# pkg_upgrade()
#
# Upgrades all installed packages
# ------------------------------------------------------------------------------
pkg_upgrade() {
# Safety: re-detect if PKG_MANAGER doesn't match available commands
if [[ "$PKG_MANAGER" == "apt" ]] && ! command -v apt-get &>/dev/null; then
msg_warn "PKG_MANAGER='apt' but apt-get not found (OS: ${OS_TYPE:-unknown}) — re-detecting"
detect_os
fi
case "$PKG_MANAGER" in
apt)
$STD apt-get -o Dpkg::Options::="--force-confold" -y dist-upgrade
;;
apk)
$STD apk -U upgrade
;;
dnf)
$STD dnf -y upgrade
;;
yum)
$STD yum -y update
;;
zypper)
$STD zypper -n update
;;
pacman)
$STD pacman -Su --noconfirm
;;
emerge)
# A full source-based @world rebuild fails under the unprivileged-LXC emerge
# sandbox ("Operation not permitted") and OOMs a base container. The stage3
# template is recent enough; the portage tree is already synced in pkg_update.
# Skip the world rebuild so the base container provisions reliably.
:
;;
*)
msg_error "Unknown package manager: $PKG_MANAGER"
return 1
;;
esac
}
# ------------------------------------------------------------------------------
# pkg_install(packages...)
#
# Installs one or more packages
# Arguments:
# packages - List of packages to install
# ------------------------------------------------------------------------------
pkg_install() {
local packages=("$@")
[[ ${#packages[@]} -eq 0 ]] && return 0
case "$PKG_MANAGER" in
apt)
$STD apt-get install -y "${packages[@]}"
;;
apk)
$STD apk add --no-cache "${packages[@]}"
;;
dnf)
$STD dnf install -y "${packages[@]}"
;;
yum)
$STD yum install -y "${packages[@]}"
;;
zypper)
$STD zypper install -y "${packages[@]}"
;;
pacman)
$STD pacman -S --noconfirm "${packages[@]}"
;;
emerge)
$STD emerge --quiet "${packages[@]}"
;;
*)
msg_error "Unknown package manager: $PKG_MANAGER"
return 1
;;
esac
}
# ------------------------------------------------------------------------------
# pkg_remove(packages...)
#
# Removes one or more packages
# ------------------------------------------------------------------------------
pkg_remove() {
local packages=("$@")
[[ ${#packages[@]} -eq 0 ]] && return 0
case "$PKG_MANAGER" in
apt)
$STD apt-get remove -y "${packages[@]}"
;;
apk)
$STD apk del "${packages[@]}"
;;
dnf)
$STD dnf remove -y "${packages[@]}"
;;
yum)
$STD yum remove -y "${packages[@]}"
;;
zypper)
$STD zypper remove -y "${packages[@]}"
;;
pacman)
$STD pacman -R --noconfirm "${packages[@]}"
;;
emerge)
$STD emerge --quiet --unmerge "${packages[@]}"
;;
*)
msg_error "Unknown package manager: $PKG_MANAGER"
return 1
;;
esac
}
# ------------------------------------------------------------------------------
# pkg_clean()
#
# Cleans package manager cache to free space
# ------------------------------------------------------------------------------
pkg_clean() {
case "$PKG_MANAGER" in
apt)
$STD apt-get autoremove -y
$STD apt-get autoclean
;;
apk)
$STD apk cache clean
;;
dnf)
$STD dnf clean all
$STD dnf autoremove -y
;;
yum)
$STD yum clean all
;;
zypper)
$STD zypper clean
;;
pacman)
$STD pacman -Sc --noconfirm
;;
emerge)
# Skip depclean on a base container: it requires a full @world update first
# (which we skip) and can unmerge needed packages or fail ("Operation not
# permitted") under the unprivileged-LXC emerge sandbox.
:
;;
*)
return 0
;;
esac
}
# ==============================================================================
# SECTION 3: SERVICE/INIT SYSTEM ABSTRACTION
# ==============================================================================
# ------------------------------------------------------------------------------
# svc_enable(service)
#
# Enables a service to start at boot
# ------------------------------------------------------------------------------
svc_enable() {
local service="$1"
[[ -z "$service" ]] && return 1
case "$INIT_SYSTEM" in
systemd)
$STD systemctl enable "$service"
;;
openrc)
$STD rc-update add "$service" default
;;
sysvinit)
if command -v update-rc.d &>/dev/null; then
$STD update-rc.d "$service" defaults
elif command -v chkconfig &>/dev/null; then
$STD chkconfig "$service" on
fi
;;
*)
msg_warn "Unknown init system, cannot enable $service"
return 1
;;
esac
}
# ------------------------------------------------------------------------------
# svc_disable(service)
#
# Disables a service from starting at boot
# ------------------------------------------------------------------------------
svc_disable() {
local service="$1"
[[ -z "$service" ]] && return 1
case "$INIT_SYSTEM" in
systemd)
$STD systemctl disable "$service"
;;
openrc)
$STD rc-update del "$service" default 2>/dev/null || true
;;
sysvinit)
if command -v update-rc.d &>/dev/null; then
$STD update-rc.d "$service" remove
elif command -v chkconfig &>/dev/null; then
$STD chkconfig "$service" off
fi
;;
*)
return 1
;;
esac
}
# ------------------------------------------------------------------------------
# svc_start(service)
#
# Starts a service immediately
# ------------------------------------------------------------------------------
svc_start() {
local service="$1"
[[ -z "$service" ]] && return 1
case "$INIT_SYSTEM" in
systemd)
$STD systemctl start "$service"
;;
openrc)
$STD rc-service "$service" start
;;
sysvinit)
$STD /etc/init.d/"$service" start
;;
*)
return 1
;;
esac
}
# ------------------------------------------------------------------------------
# svc_stop(service)
#
# Stops a running service
# ------------------------------------------------------------------------------
svc_stop() {
local service="$1"
[[ -z "$service" ]] && return 1
case "$INIT_SYSTEM" in
systemd)
$STD systemctl stop "$service"
;;
openrc)
$STD rc-service "$service" stop
;;
sysvinit)
$STD /etc/init.d/"$service" stop
;;
*)
return 1
;;
esac
}
# ------------------------------------------------------------------------------
# svc_restart(service)
#
# Restarts a service
# ------------------------------------------------------------------------------
svc_restart() {
local service="$1"
[[ -z "$service" ]] && return 1
case "$INIT_SYSTEM" in
systemd)
$STD systemctl restart "$service"
;;
openrc)
$STD rc-service "$service" restart
;;
sysvinit)
$STD /etc/init.d/"$service" restart
;;
*)
return 1
;;
esac
}
# ------------------------------------------------------------------------------
# svc_status(service)
#
# Gets service status (returns 0 if running)
# ------------------------------------------------------------------------------
svc_status() {
local service="$1"
[[ -z "$service" ]] && return 1
case "$INIT_SYSTEM" in
systemd)
systemctl is-active --quiet "$service"
;;
openrc)
rc-service "$service" status &>/dev/null
;;
sysvinit)
/etc/init.d/"$service" status &>/dev/null
;;
*)
return 1
;;
esac
}
# ------------------------------------------------------------------------------
# svc_reload_daemon()
#
# Reloads init system daemon configuration (for systemd)
# ------------------------------------------------------------------------------
svc_reload_daemon() {
case "$INIT_SYSTEM" in
systemd)
$STD systemctl daemon-reload
;;
*)
# Other init systems don't need this
return 0
;;
esac
}
# ==============================================================================
# SECTION 4: NETWORK & CONNECTIVITY
# ==============================================================================
# ------------------------------------------------------------------------------
# get_ip()
#
# Gets the primary IPv4 address of the container
# Returns: IP address string
# ------------------------------------------------------------------------------
get_ip() {
local ip=""
# Try hostname -I first (most common)
if command -v hostname &>/dev/null; then
ip=$(hostname -I 2>/dev/null | awk '{print $1}' || true)
fi
# Fallback to ip command
if [[ -z "$ip" ]] && command -v ip &>/dev/null; then
ip=$(ip -4 addr show scope global | awk '/inet /{print $2}' | cut -d/ -f1 | head -1)
fi