Files
ProxmoxVE/tools/pve/fstrim.sh
CanbiZ (MickLesk) 5dc244a8c1 core: standardize exit codes and add mappings (#12467)
* Standardize exit codes and add mappings

Replace generic exit 1 usages with specific numeric exit codes and add corresponding explanations to the error lookup. This commit updates multiple misc/* scripts to return distinct codes for validation, Proxmox/LXC, networking, download and curl errors (e.g. 103-123, 64, 107-120, 206, 0 for explicit user cancels). It also updates curl error handling to propagate the original curl exit code and adds new entries in explain_exit_code and the error handler to improve diagnostics.

* Set exit code 115 for update_os errors

Change exit status from 6 to 115 in misc/alpine-install.func's update_os() error handlers when failing to download tools.func or when the expected functions are missing. This gives a distinct exit code for these specific failure cases.

* Add tools/addon exit codes and use them

Introduce exit codes 232-238 for Tools & Addon scripts in misc/api.func and misc/error_handler.func. Update addon scripts (tools/addon/adguardhome-sync.sh, tools/addon/copyparty.sh, tools/addon/cronmaster.sh) to return specific codes instead of generic exit 1: 238 for unsupported OS and 233 when the application is not installed/upgrade prerequisites are missing. This makes failures more descriptive and aligns scripts with the central error explanations.

* Standardize exit codes in exporter addons

Unify exit codes across exporter addon scripts: return 238 for unsupported OS detections and 233 when an update is requested but the exporter is not installed. Applied to nextcloud-exporter.sh, pihole-exporter.sh, prometheus-paperless-ngx-exporter.sh, and qbittorrent-exporter.sh to make failure modes distinguishable for callers/automation.

* Use specific exit codes in addon scripts

Replace generic exit 1 with distinct exit codes across multiple addon scripts to enable finer-grained error handling in automation. Exit codes introduced: 10 for Docker/Compose missing or user-declined Docker install, 233 for "nothing to update" cases, and 238 for unsupported OS cases. Affected files: tools/addon/arcane.sh, coolify.sh, dockge.sh, dokploy.sh, filebrowser-quantum.sh, filebrowser.sh, immich-public-proxy.sh, jellystat.sh, runtipi.sh.

* Use specific exit codes in addon scripts

Replace generic exit 1 with specific exit codes across multiple addon scripts to improve error signaling and handling. Files updated: tools/addon/add-netbird-lxc.sh (exit 238 on unsupported distro), tools/addon/add-tailscale-lxc.sh (treat user cancel as exit 0), tools/addon/glances.sh (exit 233 when not installed), tools/addon/komodo.sh (distinct exits for missing compose, legacy DB, backup/download failures, docker checks), tools/addon/netdata.sh (distinct exits for unsupported PVE versions, OS/codename detection, repo lookups), and tools/addon/phpmyadmin.sh (distinct exits for unsupported OS, network/download issues, package install/start failures, and invalid input). These changes make failures easier to identify and automate recovery or reporting.

* Use specific exit codes in PVE scripts

Replace generic exit 1 with distinct exit codes across tools/pve scripts to provide clearer failure signals for callers. post-pve-install.sh now returns 105 for unsupported Proxmox versions; pve-privilege-converter.sh uses 104 for non-root, 234 when no containers, and 235 for backup/conversion failures; update-apps.sh maps backup failures to 235, missing containers/selections to 234 (and UI cancellations to 0), missing backup storage to 119, and returns the actual container update exit code on failure. These changes improve diagnostics and allow external tooling to react to specific error conditions.

* Standardize exit codes and behaviors

Adjust exit codes and abort handling across multiple PVE helper scripts to provide clearer outcomes for automation and interactive flows. Changes include:

- container-restore-from-backup.sh, core-restore-from-backup.sh: return 235 when no backups found (was 1).
- fstrim.sh: treat user cancellation of non-ext4 warning as non-error (exit 0 instead of 1).
- kernel-clean.sh: treat no selection or user abort as non-error (exit 0 instead of 1).
- lxc-delete.sh: return 234 when no containers are present; treat no selection as non-error (exit 0).
- nic-offloading-fix.sh: use specific non-zero codes for root check and tool install failures (exit 104, 237) and 236 when no matching interfaces (was 1).
- pbs_microcode.sh, post-pmg-install.sh, post-pbs-install.sh: use distinct exit codes (232 and 105) for detected VM/PVE/unsupported distro conditions instead of generic 1.

These modifications make scripts return distinct codes for different failure modes and ensure user-initiated aborts or benign conditions exit with 0 where appropriate.

* Use exit 105 for unsupported PVE versions

Standardize error handling by replacing generic exit 1 with exit 105 in pve_check() across multiple VM template scripts to indicate unsupported Proxmox VE versions. Also add API exit code 226 message for "Proxmox: VM disk import or post-creation setup failed" in misc/api.func. Affected files include misc/api.func and various vm/*-vm.sh scripts.

* Use specific exit codes in VM scripts

Replace generic exit 1 with distinct exit codes across vm/*.sh to make failures more actionable for callers. Changes include: use 226 for missing imported-disk references, 237 for pv installation failures, 115 for download/extract/ISO-related failures, 214 for insufficient disk space during FreeBSD decompression, and 119 for missing storage detection. Updated scripts: archlinux-vm.sh, docker-vm.sh, haos-vm.sh, openwrt-vm.sh, opnsense-vm.sh, truenas-vm.sh, umbrel-os-vm.sh.
2026-03-02 10:55:20 +01:00

194 lines
6.5 KiB
Bash

#!/usr/bin/env bash
set -eEuo pipefail
function header_info() {
clear
cat <<"EOF"
_______ __ __ ______ _
/ ____(_) /__ _______ _______/ /____ ____ ___ /_ __/____(_)___ ___
/ /_ / / / _ \/ ___/ / / / ___/ __/ _ \/ __ `__ \ / / / ___/ / __ `__ \
/ __/ / / / __(__ ) /_/ (__ ) /_/ __/ / / / / / / / / / / / / / / / /
/_/ /_/_/\___/____/\__, /____/\__/\___/_/ /_/ /_/ /_/ /_/ /_/_/ /_/ /_/
/____/
EOF
}
BL="\033[36m"
RD="\033[01;31m"
GN="\033[1;92m"
CL="\033[m"
# Telemetry
source <(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/api.func) 2>/dev/null || true
declare -f init_tool_telemetry &>/dev/null && init_tool_telemetry "fstrim" "pve"
LOGFILE="/var/log/fstrim.log"
touch "$LOGFILE"
chmod 600 "$LOGFILE"
echo -e "\n----- $(date '+%Y-%m-%d %H:%M:%S') | fstrim Run by $(whoami) on $(hostname) -----" >>"$LOGFILE"
header_info
echo "Loading..."
whiptail --backtitle "Proxmox VE Helper Scripts" \
--title "About fstrim (LXC)" \
--msgbox "The 'fstrim' command releases unused blocks back to the storage device. This only makes sense for containers on SSD, NVMe, Thin-LVM, or storage with discard/TRIM support.\n\nIf your root filesystem or container disks are on classic HDDs, thick LVM, or unsupported storage types, running fstrim will have no effect.\n\nRecommended:\n- Use fstrim only on SSD, NVMe, or thin-provisioned storage with discard enabled.\n- For ZFS, ensure 'autotrim=on' is set on your pool.\n" 16 88
ROOT_FS=$(df -Th "/" | awk 'NR==2 {print $2}')
if [ "$ROOT_FS" != "ext4" ]; then
whiptail --backtitle "Proxmox VE Helper Scripts" \
--title "Warning" \
--yesno "Root filesystem is not ext4 ($ROOT_FS).\nContinue anyway?" 12 80 || exit 0
fi
NODE=$(hostname)
EXCLUDE_MENU=()
STOPPED_MENU=()
MAX_NAME_LEN=0
MAX_STAT_LEN=0
# Build arrays with one pct list
mapfile -t CTLINES < <(pct list | awk 'NR>1')
for LINE in "${CTLINES[@]}"; do
CTID=$(awk '{print $1}' <<<"$LINE")
STATUS=$(awk '{print $2}' <<<"$LINE")
NAME=$(awk '{print $3}' <<<"$LINE")
((${#NAME} > MAX_NAME_LEN)) && MAX_NAME_LEN=${#NAME}
((${#STATUS} > MAX_STAT_LEN)) && MAX_STAT_LEN=${#STATUS}
done
FMT="%-${MAX_NAME_LEN}s | %-${MAX_STAT_LEN}s"
for LINE in "${CTLINES[@]}"; do
CTID=$(awk '{print $1}' <<<"$LINE")
STATUS=$(awk '{print $2}' <<<"$LINE")
NAME=$(awk '{print $3}' <<<"$LINE")
DESC=$(printf "$FMT" "$NAME" "$STATUS")
EXCLUDE_MENU+=("$CTID" "$DESC" "OFF")
if [[ "$STATUS" == "stopped" ]]; then
STOPPED_MENU+=("$CTID" "$DESC" "OFF")
fi
done
excluded_containers_raw=$(whiptail --backtitle "Proxmox VE Helper Scripts" \
--title "Containers on $NODE" \
--checklist "\nSelect containers to skip from trimming:\n" \
20 $((MAX_NAME_LEN + MAX_STAT_LEN + 20)) 12 "${EXCLUDE_MENU[@]}" 3>&1 1>&2 2>&3)
[ $? -ne 0 ] && exit
read -ra EXCLUDED <<<$(echo "$excluded_containers_raw" | tr -d '"')
TO_START=()
if [ ${#STOPPED_MENU[@]} -gt 0 ]; then
for ((i = 0; i < ${#STOPPED_MENU[@]}; i += 3)); do
CTID="${STOPPED_MENU[i]}"
DESC="${STOPPED_MENU[i + 1]}"
if [[ " ${EXCLUDED[*]} " =~ " $CTID " ]]; then
continue
fi
header_info
echo -e "${BL}[Info]${GN} Container $CTID ($DESC) is currently stopped.${CL}"
read -rp "Temporarily start for fstrim? [y/N]: " answer
if [[ "$answer" =~ ^[Yy]$ ]]; then
TO_START+=("$CTID")
fi
done
fi
declare -A WAS_STOPPED
for ct in "${TO_START[@]}"; do
WAS_STOPPED["$ct"]=1
done
function trim_container() {
local container="$1"
local name="$2"
header_info
echo -e "${BL}[Info]${GN} Trimming ${BL}$container${CL} \n"
local before_trim after_trim
local lv_name="vm-${container}-disk-0"
if lvs --noheadings -o lv_name 2>/dev/null | grep -qw "$lv_name"; then
before_trim=$(lvs --noheadings -o lv_name,data_percent 2>/dev/null | awk -v ctid="$lv_name" '$1 == ctid {gsub(/%/, "", $2); print $2}')
[[ -n "$before_trim" ]] && echo -e "${RD}Data before trim $before_trim%${CL}" || echo -e "${RD}Data before trim: not available${CL}"
else
before_trim=""
echo -e "${RD}Data before trim: not available (non-LVM storage)${CL}"
fi
local fstrim_output
fstrim_output=$(pct fstrim "$container" 2>&1)
if echo "$fstrim_output" | grep -qi "not supported"; then
echo -e "${RD}fstrim isnt supported on this storage!${CL}"
elif echo "$fstrim_output" | grep -Eq '([0-9]+(\.[0-9]+)?\s*[KMGT]?B)'; then
echo -e "${GN}fstrim result: $fstrim_output${CL}"
else
echo -e "${RD}fstrim result: $fstrim_output${CL}"
fi
if lvs --noheadings -o lv_name 2>/dev/null | grep -qw "$lv_name"; then
after_trim=$(lvs --noheadings -o lv_name,data_percent 2>/dev/null | awk -v ctid="$lv_name" '$1 == ctid {gsub(/%/, "", $2); print $2}')
[[ -n "$after_trim" ]] && echo -e "${GN}Data after trim $after_trim%${CL}" || echo -e "${GN}Data after trim: not available${CL}"
else
after_trim=""
echo -e "${GN}Data after trim: not available (non-LVM storage)${CL}"
fi
# Logging
echo "$(date '+%Y-%m-%d %H:%M:%S') | CTID=$container | Name=$name | Before=${before_trim:-N/A}% | After=${after_trim:-N/A}% | fstrim: $fstrim_output" >>"$LOGFILE"
sleep 0.5
}
for LINE in "${CTLINES[@]}"; do
CTID=$(awk '{print $1}' <<<"$LINE")
STATUS=$(awk '{print $2}' <<<"$LINE")
NAME=$(awk '{print $3}' <<<"$LINE")
if [[ " ${EXCLUDED[*]} " =~ " $CTID " ]]; then
header_info
echo -e "${BL}[Info]${GN} Skipping $CTID ($NAME, excluded)${CL}"
sleep 0.5
continue
fi
if pct config "$CTID" | grep -q "template:"; then
header_info
echo -e "${BL}[Info]${GN} Skipping $CTID ($NAME, template)${CL}\n"
sleep 0.5
continue
fi
if [[ "$STATUS" != "running" ]]; then
if [[ -n "${WAS_STOPPED[$CTID]:-}" ]]; then
header_info
echo -e "${BL}[Info]${GN} Starting $CTID ($NAME) for trim...${CL}"
pct start "$CTID"
sleep 2
else
header_info
echo -e "${BL}[Info]${GN} Skipping $CTID ($NAME, not running, not selected)${CL}"
sleep 0.5
continue
fi
fi
trim_container "$CTID" "$NAME"
if [[ -n "${WAS_STOPPED[$CTID]:-}" ]]; then
read -rp "Stop LXC $CTID ($NAME) again after trim? [Y/n]: " answer
if [[ ! "$answer" =~ ^[Nn]$ ]]; then
header_info
echo -e "${BL}[Info]${GN} Stopping $CTID ($NAME) again...${CL}"
pct stop "$CTID"
sleep 1
else
header_info
echo -e "${BL}[Info]${GN} Leaving $CTID ($NAME) running as requested.${CL}"
sleep 1
fi
fi
done
header_info
echo -e "${GN}Finished, LXC Containers Trimmed.${CL} \n"
echo -e "${BL}If you want to see the complete log: cat $LOGFILE${CL}"
exit 0