Files
thuanleandClaude Code b49d51e225 cleanup-server: fix AI tool PATH detection + add Orphan Chrome step
- step_ai_tools: shell ssh non-interactive không load bashrc nên tool cài
  qua npm/nvm bị miss — tự thêm ~/.local/bin, ~/.npm-global/bin vào PATH
  và nạp nvm.sh nếu có
- Bước 7 mới: kill chrome/chromium headless mồ côi (PPID=1 hoặc
  systemd --user) kèm crashpad, xóa --user-data-dir dưới /tmp của chúng

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-18 07:32:38 +07:00

535 lines
19 KiB
Bash
Executable File

#!/bin/bash
# cleanup-server - Dọn dẹp + nâng cấp server (Ubuntu/Arch), interactive, tuần tự.
# Cách dùng:
# cleanup-server # hiện menu chọn target (local hoặc server alias)
# cleanup-server --run-steps # (nội bộ) chạy thẳng 8 bước trên máy hiện tại
# -----------------------------
# Color helpers (tự tắt khi không phải TTY)
# -----------------------------
if [ -t 1 ]; then
C_RESET=$'\033[0m'
C_TITLE=$'\033[1;36m' # tiêu đề
C_OK=$'\033[1;32m' # thành công
C_DEL=$'\033[1;31m' # sẽ xóa / lỗi
C_WARN=$'\033[1;33m' # cảnh báo
else
C_RESET=""; C_TITLE=""; C_OK=""; C_DEL=""; C_WARN=""
fi
# -----------------------------
# Banner rainbow (ASCII art figlet, per-line gradient)
# -----------------------------
print_banner() {
local -a lines=(
'▗▄▄▄▖▗▖ ▗▄▄▖▗▄▄▄▖▗▄▄▖ ▗▖ ▗▖▗▄▄▄▖▗▄▄▖ ▗▄▄▖▗▖ ▗▄▄▄▖ ▗▄▖ ▗▖ ▗▖▗▄▄▄▖▗▄▖ '
' █ ▐▌ ▐▌ ▐▌ ▐▌ ▐▌▐▌ ▐▌▐▌ ▐▌ ▐▌ ▐▌ ▐▌ ▐▌ ▐▌ ▐▌▐▛▚▖▐▌▐▌ ▐▌ ▐▌'
' █ ▐▌ ▝▀▚▖▐▛▀▀▘▐▛▀▚▖▐▌ ▐▌▐▛▀▀▘▐▛▀▚▖ ▐▌ ▐▌ ▐▛▀▀▘▐▛▀▜▌▐▌ ▝▜▌▐▛▀▀▘▐▛▀▚▖'
' █ ▐▙▄▄▖ ▗▄▄▞▘▐▙▄▄▖▐▌ ▐▌ ▝▚▞▘ ▐▙▄▄▖▐▌ ▐▌ ▝▚▄▄▖▐▙▄▄▖▐▙▄▄▖▐▌ ▐▌▐▌ ▐▌▐▙▄▄▖▐▌ ▐▌'
)
local -a colors=()
if [ -t 1 ]; then
colors=(
$'\033[1;38;5;51m' # cyan
$'\033[1;38;5;120m' # xanh lá
$'\033[1;38;5;220m' # vàng gold
$'\033[1;38;5;209m' # cam-đỏ
)
fi
echo ""
local i
for ((i = 0; i < ${#lines[@]}; i++)); do
if [ -t 1 ]; then
printf '%s%s%s\n' "${colors[$i]}" "${lines[$i]}" "$C_RESET"
else
printf '%s\n' "${lines[$i]}"
fi
done
printf ' %sDọn dẹp + nâng cấp server (Ubuntu / Arch)%s\n' "$C_WARN" "$C_RESET"
echo ""
}
# -----------------------------
# Host đang chạy (đặt ở main; hiển thị lại trong mỗi header bước)
# -----------------------------
CURRENT_TARGET="local"
# In header bước kèm host: --- [Label] on <host> ---
step_header() {
echo "${C_TITLE}--- [$1] on ${CURRENT_TARGET} ---${C_RESET}"
}
# -----------------------------
# Phát hiện distro qua /etc/os-release → debian | arch | unknown
# -----------------------------
detect_distro() {
[ -r /etc/os-release ] || { echo unknown; return; }
local id id_like
. /etc/os-release 2>/dev/null
id="${ID:-}"; id_like="${ID_LIKE:-}"
case "$id $id_like" in
*arch*) echo arch ;;
*debian*) echo debian ;;
*ubuntu*) echo debian ;;
*) echo unknown ;;
esac
}
# -----------------------------
# Hỏi Y/n (Enter = Yes). Trả về 0 = đồng ý, 1 = hủy.
# -----------------------------
confirm_yn() {
local prompt="$1" confirm
read -r -p " ${prompt} (Y/n): " confirm
if [[ -n "$confirm" && ! "$confirm" =~ ^([yY]|[yY][eE][sS])$ ]]; then
echo " Đã hủy."
return 1
fi
return 0
}
# -----------------------------
# Danh sách target fix cứng (alias từ ~/.ssh/config)
# -----------------------------
TARGETS=("local" "ta" "toc" "oc" "cse" "vrc" "aws-vanhoa" "tk" "od")
TARGET_CURSOR=0
TARGET=""
# Vẽ menu single-select
draw_target_menu() {
if [ "$1" = "redraw" ]; then
printf '\033[%dA' "$(( ${#TARGETS[@]} + 2 ))"
fi
echo " Chọn target (↑↓: di chuyển | Enter: chọn):"
echo ""
local i
for ((i = 0; i < ${#TARGETS[@]}; i++)); do
local prefix=" "
if [ "$i" -eq "$TARGET_CURSOR" ]; then
prefix="${C_TITLE}▸ ${C_RESET}"
fi
printf '\r\033[K%s%s\n' "$prefix" "${TARGETS[$i]}"
done
}
# Chạy menu, đặt biến toàn cục TARGET
select_target() {
draw_target_menu
while true; do
IFS= read -rsn1 key
case "$key" in
$'\x1b')
read -rsn2 seq
case "$seq" in
'[A') TARGET_CURSOR=$(( (TARGET_CURSOR - 1 + ${#TARGETS[@]}) % ${#TARGETS[@]} ));;
'[B') TARGET_CURSOR=$(( (TARGET_CURSOR + 1) % ${#TARGETS[@]} ));;
esac
;;
'') # Enter
echo ""
TARGET="${TARGETS[$TARGET_CURSOR]}"
return
;;
esac
draw_target_menu "redraw"
done
}
# -----------------------------
# Bước 1: Nâng cấp hệ thống theo distro
# -----------------------------
step_upgrade() {
step_header "System Upgrade"
local distro
distro=$(detect_distro)
case "$distro" in
debian)
echo " Distro: Debian/Ubuntu (apt)."
sudo apt-get update || { echo "${C_DEL} ✗ apt-get update thất bại.${C_RESET}"; echo ""; return; }
local upgradable
upgradable=$(apt list --upgradable 2>/dev/null | grep -c 'upgradable')
echo " ${C_WARN}✗ ${upgradable} package có thể nâng cấp.${C_RESET}"
if confirm_yn "Upgrade + autoremove?"; then
sudo apt-get upgrade -y
sudo apt-get autoremove --purge -y
echo "${C_OK} ✓ Đã nâng cấp xong.${C_RESET}"
fi
;;
arch)
echo " Distro: Arch (pacman)."
local helper=""
command -v paru >/dev/null 2>&1 && helper="paru"
[ -z "$helper" ] && command -v yay >/dev/null 2>&1 && helper="yay"
[ -z "$helper" ] && helper="sudo pacman"
echo " Helper: $helper"
if confirm_yn "Chạy $helper -Syu?"; then
$helper -Syu
echo "${C_OK} ✓ Đã nâng cấp xong.${C_RESET}"
fi
;;
*)
echo "${C_WARN} ⚠ Distro không hỗ trợ upgrade, bỏ qua.${C_RESET}"
;;
esac
echo ""
}
# -----------------------------
# Bước 2: AI CLI Tools — nếu detect thấy tool thì upgrade
# claude → claude update
# codex → codex update
# agy → agy update
# kiro → binary là kiro-cli → kiro-cli update -y
# paseo → cài qua npm (@getpaseo/cli) → npm install -g @getpaseo/cli@latest
# -----------------------------
step_ai_tools() {
step_header "AI CLI Tools"
local found=0
local -a found_names=()
# Shell này chạy qua ssh non-interactive nên bashrc không được load:
# tự thêm các bin dir thông dụng + nạp nvm để thấy được tool cài qua npm/nvm.
export PATH="$HOME/.local/bin:$HOME/.npm-global/bin:$PATH"
if [ -s "$HOME/.nvm/nvm.sh" ]; then
export NVM_DIR="$HOME/.nvm"
. "$NVM_DIR/nvm.sh" >/dev/null 2>&1
fi
if command -v claude >/dev/null 2>&1; then
found=1; found_names+=("claude")
echo " ${C_OK}✓ claude: $(claude --version 2>/dev/null | head -1)${C_RESET}"
if confirm_yn "claude update?"; then
claude update
fi
echo ""
fi
if command -v codex >/dev/null 2>&1; then
found=1; found_names+=("codex")
echo " ${C_OK}✓ codex: $(codex --version 2>/dev/null | head -1)${C_RESET}"
if confirm_yn "codex update?"; then
codex update
fi
echo ""
fi
if command -v agy >/dev/null 2>&1; then
found=1; found_names+=("agy")
echo " ${C_OK}✓ agy: $(agy --version 2>/dev/null | head -1)${C_RESET}"
if confirm_yn "agy update?"; then
agy update
fi
echo ""
fi
if command -v kiro-cli >/dev/null 2>&1; then
found=1; found_names+=("kiro")
echo " ${C_OK}✓ kiro (kiro-cli): $(kiro-cli --version 2>/dev/null | head -1)${C_RESET}"
if confirm_yn "kiro-cli update?"; then
kiro-cli update -y
fi
echo ""
fi
if command -v paseo >/dev/null 2>&1; then
found=1; found_names+=("paseo")
echo " ${C_OK}✓ paseo: $(paseo --version 2>/dev/null | head -1)${C_RESET}"
if confirm_yn "npm install -g @getpaseo/cli@latest?"; then
npm install -g @getpaseo/cli@latest
fi
echo ""
fi
if [ "$found" -eq 0 ]; then
echo "${C_OK} ✓ Không tìm thấy AI CLI tool nào (claude/codex/agy/kiro/paseo).${C_RESET}"
echo ""
else
echo "${C_OK} ✓ AI CLI Tools xong: ${found_names[*]}.${C_RESET}"
echo ""
fi
}
# -----------------------------
# Chọn 'docker' hoặc 'sudo docker' tùy permission
# -----------------------------
docker_cmd() {
if docker info >/dev/null 2>&1; then
echo "docker"
elif sudo -n docker info >/dev/null 2>&1; then
echo "sudo docker"
else
echo ""
fi
}
# -----------------------------
# Bước 2: Docker — df rồi prune từng loại
# -----------------------------
step_docker() {
step_header "Docker"
if ! command -v docker >/dev/null 2>&1; then
echo "${C_WARN} ⚠ docker command not found.${C_RESET}"
echo ""
return
fi
local DC
DC=$(docker_cmd)
if [ -z "$DC" ]; then
echo "${C_WARN} ⚠ Không có quyền truy cập docker (cần group docker hoặc sudo).${C_RESET}"
echo ""
return
fi
echo " Lệnh: $DC"
$DC system df
echo ""
confirm_yn "Prune images (-a)?" && $DC image prune -a -f
confirm_yn "Prune containers?" && $DC container prune -f
confirm_yn "Prune volumes?" && $DC volume prune -f
confirm_yn "Prune build cache?" && $DC builder prune -f
confirm_yn "Prune networks?" && $DC network prune -f
echo "${C_OK} ✓ Docker cleanup xong.${C_RESET}"
echo ""
}
# -----------------------------
# Bước 3: Journal logs — vacuum log cũ hơn 7 ngày
# -----------------------------
step_journal() {
step_header "Journal Logs"
if ! command -v journalctl >/dev/null 2>&1; then
echo "${C_WARN} ⚠ journalctl not found.${C_RESET}"
echo ""
return
fi
sudo journalctl --disk-usage
if confirm_yn "Vacuum log cũ hơn 7 ngày (--vacuum-time=7d)?"; then
sudo journalctl --vacuum-time=7d
echo "${C_OK} ✓ Đã dọn journal.${C_RESET}"
fi
echo ""
}
# -----------------------------
# Bước 4: Package cache — apt clean+autoremove hoặc paccache/pacman -Sc
# -----------------------------
step_pkg_cache() {
step_header "Package Cache"
local distro
distro=$(detect_distro)
case "$distro" in
debian)
local d="/var/cache/apt/archives"
[ -d "$d" ] && sudo du -sh "$d"
if confirm_yn "apt clean + autoremove?"; then
sudo apt-get clean
sudo apt-get autoremove -y
echo "${C_OK} ✓ Đã dọn apt cache.${C_RESET}"
fi
;;
arch)
local d="/var/cache/pacman/pkg"
[ -d "$d" ] && sudo du -sh "$d"
# Xóa file download tạm (incomplete) — pacman -Sc báo lỗi fd 7 với chúng.
local partial pcount
partial=$(sudo find "$d" -maxdepth 1 -type f -name 'download-*' 2>/dev/null)
if [ -n "$partial" ]; then
pcount=$(printf '%s\n' "$partial" | grep -c .)
echo " ${C_WARN}✗ ${pcount} file download tạm (incomplete).${C_RESET}"
if confirm_yn "Xóa file download-* tạm?"; then
printf '%s\n' "$partial" | xargs sudo rm -f --
echo "${C_OK} ✓ Đã xóa file tạm.${C_RESET}"
fi
fi
if command -v paccache >/dev/null 2>&1; then
sudo paccache -dk2 # dry-run xem trước
if confirm_yn "paccache -rk2 (giữ 2 bản)?"; then
sudo paccache -rk2
echo "${C_OK} ✓ Đã dọn pacman cache.${C_RESET}"
fi
else
if confirm_yn "Không có paccache, chạy pacman -Sc?"; then
sudo pacman -Sc --noconfirm
echo "${C_OK} ✓ Đã dọn pacman cache.${C_RESET}"
fi
fi
;;
*)
echo "${C_WARN} ⚠ Distro không hỗ trợ dọn package cache.${C_RESET}"
;;
esac
echo ""
}
# -----------------------------
# Bước 5: Snap — forget từng snapshot
# -----------------------------
step_snap() {
step_header "Snap"
if ! command -v snap >/dev/null 2>&1; then
echo "${C_WARN} ⚠ snap not found.${C_RESET}"
echo ""
return
fi
local saved
# Cột đầu (Set) là id cần forget; một Set có thể có nhiều Snap → dedupe.
saved=$(sudo snap saved 2>/dev/null | awk 'NR>1{print $1}' | awk '!seen[$0]++')
if [ -z "$saved" ]; then
echo "${C_OK} ✓ Không có snap snapshot nào.${C_RESET}"
echo ""
return
fi
local id
for id in $saved; do
if confirm_yn "Forget snap snapshot (Set $id)?"; then
sudo snap forget "$id"
fi
done
echo "${C_OK} ✓ Snap cleanup xong.${C_RESET}"
echo ""
}
# -----------------------------
# Bước 7: Chrome headless mồ côi — kill browser Playwright sót lại (PPID=1)
# rồi xóa profile /tmp của chúng
# -----------------------------
step_orphan_chrome() {
step_header "Orphan Chrome"
# Process mồ côi được nhận nuôi bởi init (PPID=1) hoặc systemd --user
# của từng user — driver (node/playwright) đã chết, browser bị bỏ quên.
# Browser còn cha đang sống thì KHÔNG đụng.
local adopters out
adopters=$(ps -eo pid=,args= 2>/dev/null | awk '/systemd --user/ {print $1}')
out=$(ps -eo pid=,ppid=,user=,etimes=,args= 2>/dev/null | awk -v ok="1 $adopters" '
BEGIN { n = split(ok, a, " "); for (i = 1; i <= n; i++) adopt[a[i]] = 1 }
!($2 in adopt) { next }
$5 ~ /\/headless_shell$/ { print; next }
/--headless/ && $5 ~ /\/(chrome|chromium|chromium-browser)$/ { print }
')
if [ -z "$out" ]; then
echo "${C_OK} ✓ Không có chrome headless mồ côi.${C_RESET}"
echo ""
return
fi
echo " ${C_WARN}⚠ Chrome headless mồ côi (PPID=1):${C_RESET}"
local pids="" dirs="" pid ppid user etimes args age_d age_h dir
while read -r pid ppid user etimes args; do
[ -z "$pid" ] && continue
age_d=$(( etimes / 86400 )); age_h=$(( (etimes % 86400) / 3600 ))
echo " ${C_DEL}- pid $pid ($user, sống ${age_d}d${age_h}h): ${args%% --*}${C_RESET}"
pids="$pids $pid"
dir=$(printf '%s\n' "$args" | sed -n 's/.*--user-data-dir=\([^ ]*\).*/\1/p')
# chỉ nhận profile dir dưới /tmp
case "$dir" in /tmp/*) [ -d "$dir" ] && dirs="$dirs $dir" ;; esac
done <<< "$out"
dirs=$(printf '%s\n' $dirs | sed '/^$/d' | sort -u | tr '\n' ' ')
local killed=0
if confirm_yn "Kill $(wc -w <<< "$pids" | tr -d ' ') process?"; then
killed=1
sudo kill $pids 2>/dev/null
sleep 2
sudo kill -9 $pids 2>/dev/null
# crashpad_handler mồ côi đi kèm
ps -eo pid=,ppid=,args= 2>/dev/null | awk -v ok="1 $adopters" '
BEGIN { n = split(ok, a, " "); for (i = 1; i <= n; i++) adopt[a[i]] = 1 }
($2 in adopt) && $3 ~ /crashpad/ {print $1}' | xargs -r sudo kill 2>/dev/null
echo "${C_OK} ✓ Đã kill.${C_RESET}"
fi
if [ "$killed" -eq 1 ] && [ -n "${dirs// /}" ]; then
echo " Profile /tmp của browser trên:"
for dir in $dirs; do
echo " ${C_DEL}- $dir${C_RESET}"
done
if confirm_yn "Xóa các profile dir này?"; then
sudo rm -rf -- $dirs
echo "${C_OK} ✓ Đã xóa profile.${C_RESET}"
fi
fi
echo ""
}
# -----------------------------
# Bước 8: /tmp & cache cũ — liệt kê file >7 ngày, xác nhận rồi xóa
# -----------------------------
step_tmp_cache() {
step_header "/tmp & Cache cũ"
local days=7
echo " Tìm file cũ hơn ${days} ngày trong /tmp /var/tmp:"
local old_files
old_files=$(sudo find /tmp /var/tmp -type f -mtime +"$days" 2>/dev/null)
if [ -z "$old_files" ]; then
echo "${C_OK} ✓ Không có file cũ >${days} ngày.${C_RESET}"
echo ""
return
fi
local count total_kb total_mib
count=$(printf '%s\n' "$old_files" | grep -c .)
total_kb=$(printf '%s\n' "$old_files" | xargs sudo du -ck 2>/dev/null | tail -1 | cut -f1)
total_mib=$(( total_kb / 1024 ))
echo "${C_DEL} ✗ ${count} file, ~${total_mib} MiB.${C_RESET}"
printf '%s\n' "$old_files" | head -20 | sed 's/^/ - /'
[ "$count" -gt 20 ] && echo " ... (và $((count - 20)) file nữa)"
if confirm_yn "Xóa các file cũ >${days} ngày?"; then
printf '%s\n' "$old_files" | xargs sudo rm -f --
echo "${C_OK} ✓ Đã xóa.${C_RESET}"
fi
echo ""
}
# -----------------------------
# Chạy tuần tự 8 bước
# -----------------------------
run_all_steps() {
step_upgrade
step_ai_tools
step_docker
step_journal
step_pkg_cache
step_snap
step_orphan_chrome
step_tmp_cache
}
# -----------------------------
# Chạy trên target đã chọn.
# local → chạy tại chỗ.
# alias → self-bootstrap: base64 script qua argv, giữ stdin=terminal
# để read/màu tương tác hoạt động qua PTY của `ssh -t`.
# -----------------------------
run_on_target() {
local target="$1"
if [ "$target" = "local" ]; then
CURRENT_TARGET="local"
run_all_steps
return $?
fi
local b64
b64=$(base64 < "$0" | tr -d '\n') || {
echo "${C_DEL} ✗ Không mã hóa được script.${C_RESET}"
return 1
}
# Giải mã ra file tạm trên remote rồi chạy; stdin không bị redirect → read OK.
# Truyền target làm argv[2] để remote biết host (hiển thị lại trong header).
ssh -t "$target" \
"umask 077; t=\$(mktemp); printf '%s' '$b64' | base64 -d > \"\$t\" && bash \"\$t\" --run-steps \"$target\"; r=\$?; rm -f \"\$t\"; exit \$r" \
|| { echo "${C_DEL} ✗ ssh tới $target thất bại.${C_RESET}"; return 1; }
}
# -----------------------------
# Main (phân nhánh theo argv)
# -----------------------------
main() {
if [ "${1:-}" = "--run-steps" ]; then
CURRENT_TARGET="${2:-local}"
echo "${C_TITLE}===== 🧹 Cleanup-server on ${CURRENT_TARGET} =====${C_RESET}"
echo ""
run_all_steps
echo ""
echo "${C_OK}===== ✅ Cleanup-server hoàn tất =====${C_RESET}"
return
fi
print_banner
echo "${C_TITLE}===== 🧹 Cleanup-server =====${C_RESET}"
echo ""
select_target
echo ""
run_on_target "$TARGET"
}
main "$@"