Fixed for truenas 27+

This commit is contained in:
2026-10-22 19:12:27 +03:00
parent d142b97cbf
commit 8cb32b799f
3 changed files with 595 additions and 718 deletions
+182 -219
View File
@@ -1,41 +1,50 @@
#!/bin/bash
# =============================================================================
# Nginx Proxy Manager Backup Script for TrueNAS App -> Docker Migration
# Nginx Proxy Manager Backup Script for TrueNAS 27+ App -> Docker Migration
# =============================================================================
# This script backs up an Nginx Proxy Manager instance running as a TrueNAS App
# to a TrueNAS dataset/share, ready for restoration to a Docker container.
#
# TrueNAS 27 (Electric Eel) stores app data directly in datasets accessible
# from the host filesystem. No kubectl/k3s required.
#
# Run this script ON the TrueNAS host (via SSH or TrueNAS Shell).
#
# Requirements:
# - TrueNAS with Nginx Proxy Manager app installed
# - Access to k3s/kubectl (usually via /usr/local/bin/k3s kubectl)
# - SQLite3 or MariaDB/MySQL client tools (for database dump)
# - TrueNAS 27+ with Nginx Proxy Manager app installed
# - SQLite3 (for SQLite DB) or MariaDB/MySQL client (for MariaDB)
# - Write access to backup destination dataset
# - Read access to NPM app datasets (configured in app settings)
# =============================================================================
set -euo pipefail
# =============================================================================
# CONFIGURATION
# CONFIGURATION - Adjust these values for your environment
# =============================================================================
APP_NAMESPACE="${APP_NAMESPACE:-nginx-proxy-manager}"
# Backup destination (TrueNAS dataset path)
BACKUP_DEST="${BACKUP_DEST:-/mnt/tank/backups/npm}"
# Database details (auto-detected if not set)
# ---- Database Configuration ----
DB_TYPE="${DB_TYPE:-sqlite}" # sqlite or mariadb
DB_HOST="${DB_HOST:-}"
DB_PORT="${DB_PORT:-}"
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-}" # Auto: 3306 for MariaDB
DB_NAME="${DB_NAME:-npm}"
DB_USER="${DB_USER:-npm}"
DB_PASS="${DB_PASS:-}"
DB_PASS="${DB_PASS:-}" # Required for MariaDB only
# NPM persistent volume claim names (auto-detected if not set)
PVC_DATA="${PVC_DATA:-}"
PVC_LETS_ENCRYPT="${PVC_LETS_ENCRYPT:-}"
# ---- NPM Data Paths (Host filesystem paths) ----
# These are the dataset paths you configured in the NPM app settings
# Example: /mnt/tank/apps/npm/data
# Example: /mnt/tank/apps/npm/letsencrypt
NPM_DATA_PATH="${NPM_DATA_PATH:-}"
NPM_LETSENCRYPT_PATH="${NPM_LETSENCRYPT_PATH:-}"
# Retention: keep last N backups
RETENTION_COUNT="${RETENTION_COUNT:-7}"
# Compression level (1-9, higher = smaller but slower)
COMPRESSION_LEVEL="${COMPRESSION_LEVEL:-6}"
# =============================================================================
@@ -45,9 +54,9 @@ COMPRESSION_LEVEL="${COMPRESSION_LEVEL:-6}"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="${BACKUP_DEST}/npm_backup_${TIMESTAMP}"
mkdir -p "${BACKUP_DIR}"
KUBECTL_CMD="${KUBECTL_CMD:-/usr/local/bin/k3s kubectl}"
LOG_FILE="${BACKUP_DIR}/backup.log"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
@@ -77,135 +86,161 @@ die() {
}
# =============================================================================
# DETECTION FUNCTIONS
# VALIDATION FUNCTIONS
# =============================================================================
detect_kubectl() {
if [[ ! -x "${KUBECTL_CMD}" ]]; then
for cmd in /usr/local/bin/k3s /usr/bin/k3s /usr/local/bin/kubectl /usr/bin/kubectl; do
if [[ -x "${cmd}" ]]; then
if [[ "${cmd}" == *k3s ]]; then
KUBECTL_CMD="${cmd} kubectl"
else
KUBECTL_CMD="${cmd}"
fi
info "Found kubectl at: ${KUBECTL_CMD}"
validate_paths() {
info "Validating data paths..."
local has_paths=false
if [[ -n "${NPM_DATA_PATH}" ]] && [[ -d "${NPM_DATA_PATH}" ]]; then
info "Found data path: ${NPM_DATA_PATH}"
has_paths=true
elif [[ -n "${NPM_DATA_PATH}" ]]; then
warn "Data path does not exist: ${NPM_DATA_PATH}"
fi
if [[ -n "${NPM_LETSENCRYPT_PATH}" ]] && [[ -d "${NPM_LETSENCRYPT_PATH}" ]]; then
info "Found letsencrypt path: ${NPM_LETSENCRYPT_PATH}"
has_paths=true
elif [[ -n "${NPM_LETSENCRYPT_PATH}" ]]; then
warn "Letsencrypt path does not exist: ${NPM_LETSENCRYPT_PATH}"
fi
if [[ "${has_paths}" == "false" ]]; then
info "No explicit paths set, trying to auto-detect..."
detect_paths
fi
if [[ "${has_paths}" == "false" ]]; then
die "No valid NPM data paths found. Please set NPM_DATA_PATH, NPM_LETSENCRYPT_PATH environment variables to the dataset paths configured in your NPM app."
fi
}
detect_paths() {
local common_bases=(
"/mnt/tank/apps/nginx-proxy-manager"
"/mnt/tank/apps/npm"
"/mnt/pool/apps/nginx-proxy-manager"
"/mnt/pool/apps/npm"
"/mnt/data/apps/nginx-proxy-manager"
"/mnt/data/apps/npm"
"/mnt/storage/apps/nginx-proxy-manager"
"/mnt/storage/apps/npm"
"/mnt/apps/nginx-proxy-manager"
"/mnt/apps/npm"
)
for base in "${common_bases[@]}"; do
if [[ -d "${base}" ]]; then
info "Found potential base path: ${base}"
if [[ -d "${base}/data" ]] && [[ -z "${NPM_DATA_PATH}" ]]; then
NPM_DATA_PATH="${base}/data"
info "Auto-detected data: ${NPM_DATA_PATH}"
fi
if [[ -d "${base}/letsencrypt" ]] && [[ -z "${NPM_LETSENCRYPT_PATH}" ]]; then
NPM_LETSENCRYPT_PATH="${base}/letsencrypt"
info "Auto-detected letsencrypt: ${NPM_LETSENCRYPT_PATH}"
fi
if [[ -n "${NPM_DATA_PATH}" ]] || [[ -n "${NPM_LETSENCRYPT_PATH}" ]]; then
return 0
fi
done
die "kubectl not found. Please install k3s or kubectl."
fi
info "Using kubectl: ${KUBECTL_CMD}"
fi
done
}
detect_namespace() {
if [[ -z "${APP_NAMESPACE}" ]]; then
info "Auto-detecting Nginx Proxy Manager namespace..."
local ns=$(${KUBECTL_CMD} get pods --all-namespaces -l app=nginx-proxy-manager -o jsonpath='{.items[0].metadata.namespace}' 2>/dev/null || true)
if [[ -n "${ns}" ]]; then
APP_NAMESPACE="${ns}"
info "Detected namespace: ${APP_NAMESPACE}"
else
for ns in nginx-proxy-manager npm apps-npm; do
if ${KUBECTL_CMD} get namespace "${ns}" >/dev/null 2>&1; then
APP_NAMESPACE="${ns}"
info "Found namespace: ${APP_NAMESPACE}"
return 0
fi
done
die "Could not detect NPM namespace. Set APP_NAMESPACE manually."
fi
fi
}
validate_database() {
info "Validating database connection..."
detect_database() {
info "Detecting database configuration..."
local secret_name=$(${KUBECTL_CMD} get secrets -n "${APP_NAMESPACE}" -o name 2>/dev/null | grep -E '(mariadb|mysql|database|npm)' | head -1 | cut -d/ -f2 || true)
if [[ -n "${secret_name}" ]]; then
info "Found database secret: ${secret_name}"
if [[ "${DB_TYPE}" == "sqlite" ]]; then
# SQLite doesn't need host/port/user/pass typically
DB_TYPE="sqlite"
else
DB_HOST="${DB_HOST:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.host}' 2>/dev/null | base64 -d || echo "")}"
DB_PORT="${DB_PORT:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.port}' 2>/dev/null | base64 -d || echo "3306")}"
DB_NAME="${DB_NAME:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.database}' 2>/dev/null | base64 -d || echo "npm")}"
DB_USER="${DB_USER:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.username}' 2>/dev/null | base64 -d || echo "npm")}"
DB_PASS="${DB_PASS:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.password}' 2>/dev/null | base64 -d || echo "")}"
if [[ -z "${DB_PASS}" ]]; then
DB_PASS=$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.mariadb-root-password}' 2>/dev/null | base64 -d || true)
if [[ "${DB_TYPE}" == "sqlite" ]]; then
# SQLite database is typically in the data path
local sqlite_db="${NPM_DATA_PATH}/database.sqlite"
if [[ -f "${sqlite_db}" ]]; then
info "Found SQLite database: ${sqlite_db}"
if ! sqlite3 "${sqlite_db}" "SELECT 1;" >/dev/null 2>&1; then
die "Cannot read SQLite database at ${sqlite_db}. Check permissions."
fi
success "SQLite database validated"
else
warn "SQLite database not found at ${sqlite_db} (will be backed up with data path)"
fi
return 0
fi
# Try to detect from NPM config if running
if [[ -z "${DB_HOST}" ]] && [[ "${DB_TYPE}" == "mariadb" ]]; then
info "Trying to detect from NPM pod config..."
local npm_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -l app=nginx-proxy-manager -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)
if [[ -n "${npm_pod}" ]]; then
local config=$(${KUBECTL_CMD} exec -n "${APP_NAMESPACE}" "${npm_pod}" -- cat /app/config/production.json 2>/dev/null || true)
if [[ -n "${config}" ]]; then
if echo "${config}" | grep -q "sqlite"; then
DB_TYPE="sqlite"
else
DB_TYPE="mariadb"
DB_HOST="${DB_HOST:-$(echo "${config}" | grep -oP '"host"\s*:\s*"\K[^"]+' || true)}"
DB_USER="${DB_USER:-$(echo "${config}" | grep -oP '"user"\s*:\s*"\K[^"]+' || true)}"
DB_PASS="${DB_PASS:-$(echo "${config}" | grep -oP '"password"\s*:\s*"\K[^"]+' || true)}"
DB_NAME="${DB_NAME:-$(echo "${config}" | grep -oP '"database"\s*:\s*"\K[^"]+' || true)}"
fi
fi
fi
# MariaDB
if [[ -z "${DB_PORT}" ]]; then
DB_PORT="3306"
fi
# Check for SQLite database file in PVC
if [[ "${DB_TYPE}" == "sqlite" ]] || [[ -z "${DB_HOST}" ]]; then
DB_TYPE="sqlite"
info "Using SQLite database (default for NPM)"
if [[ -z "${DB_PASS}" ]]; then
warn "DB_PASS not set. Trying to find it..."
find_db_password
fi
if [[ "${DB_TYPE}" == "mariadb" ]] && [[ -z "${DB_HOST}" ]]; then
local db_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -o name 2>/dev/null | grep -E '(mariadb|mysql)' | head -1 | cut -d/ -f2 || true)
if [[ -n "${db_pod}" ]]; then
DB_HOST="${db_pod}"
info "Detected database pod: ${DB_HOST}"
fi
if [[ -z "${DB_PASS}" ]]; then
die "Database password (DB_PASS) is required for MariaDB. Please set it or ensure it can be auto-detected."
fi
if [[ "${DB_TYPE}" == "mariadb" ]] && [[ -z "${DB_HOST}" ]] && [[ -z "${DB_PASS}" ]]; then
warn "Could not fully auto-detect MariaDB credentials."
warn "Please set DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASS environment variables."
local dump_cmd=""
if command -v mariadb-dump >/dev/null 2>&1; then
dump_cmd="mariadb-dump"
elif command -v mysqldump >/dev/null 2>&1; then
dump_cmd="mysqldump"
else
info "Database: ${DB_TYPE} ${DB_NAME}"
die "Neither mariadb-dump nor mysqldump found. Install mariadb-client or mysql-client."
fi
export MYSQL_PWD="${DB_PASS}"
if ! ${dump_cmd} -h "${DB_HOST}" -P "${DB_PORT}" -u "${DB_USER}" -e "SELECT 1" >/dev/null 2>&1; then
unset MYSQL_PWD
die "Cannot connect to MariaDB/MySQL at ${DB_HOST}:${DB_PORT} as ${DB_USER}. Check credentials and ensure database is accessible from host."
fi
unset MYSQL_PWD
success "MariaDB database connection validated"
}
detect_pvcs() {
info "Detecting persistent volume claims..."
find_db_password() {
local possible_files=(
"/mnt/tank/apps/nginx-proxy-manager/.env"
"/mnt/tank/apps/npm/.env"
"/mnt/pool/apps/nginx-proxy-manager/.env"
"/mnt/pool/apps/npm/.env"
"/mnt/data/apps/nginx-proxy-manager/.env"
"/mnt/data/apps/npm/.env"
"/mnt/storage/apps/nginx-proxy-manager/.env"
"/mnt/storage/apps/npm/.env"
"/mnt/apps/nginx-proxy-manager/.env"
"/mnt/apps/npm/.env"
"/etc/npm/db_password"
"/root/.npm_db_password"
)
local pvcs=$(${KUBECTL_CMD} get pvc -n "${APP_NAMESPACE}" -o jsonpath='{range .items[*]}{.metadata.name}{" "}{.spec.volumeName}{"\n"}{end}' 2>/dev/null || true)
for file in "${possible_files[@]}"; do
if [[ -f "${file}" ]]; then
local pass=$(grep -iE '(password|passwd)' "${file}" 2>/dev/null | head -1 | sed -E 's/.*[=:]\s*//' | sed -E 's/["\'"'"']//g' | xargs)
if [[ -n "${pass}" ]]; then
DB_PASS="${pass}"
info "Found database password in ${file}"
return 0
fi
fi
done
if [[ -n "${pvcs}" ]]; then
echo "${pvcs}" | while read -r name volume; do
info "Found PVC: ${name} -> ${volume}"
case "${name}" in
*data*|*npm*)
PVC_DATA="${PVC_DATA:-${name}}"
;;
*lets*|*encrypt*|*ssl*|*cert*)
PVC_LETS_ENCRYPT="${PVC_LETS_ENCRYPT:-${name}}"
;;
esac
done
if command -v docker >/dev/null 2>&1; then
local db_container=$(docker ps --format '{{.Names}}' | grep -iE '(mariadb|mysql|npm.*db)' | head -1 || true)
if [[ -n "${db_container}" ]]; then
info "Found potential DB container: ${db_container}"
local pass=$(docker inspect "${db_container}" 2>/dev/null | grep -iE '(MYSQL_PASSWORD|MARIADB_PASSWORD)' | head -1 | sed -E 's/.*"([^"]+)".*/\1/' || true)
if [[ -n "${pass}" ]]; then
DB_PASS="${pass}"
info "Found database password from container env"
return 0
fi
fi
fi
PVC_DATA="${PVC_DATA:-nginx-proxy-manager-data}"
PVC_LETS_ENCRYPT="${PVC_LETS_ENCRYPT:-nginx-proxy-manager-letsencrypt}"
info "Using PVCs: data=${PVC_DATA}, letsencrypt=${PVC_LETS_ENCRYPT}"
}
# =============================================================================
@@ -213,17 +248,15 @@ detect_pvcs() {
# =============================================================================
backup_database() {
info "Backing up ${DB_TYPE} database..."
mkdir -p "${BACKUP_DIR}/database"
if [[ "${DB_TYPE}" == "sqlite" ]]; then
# For SQLite, we'll copy the database file from the data PVC
info "SQLite database will be backed up as part of data PVC"
info "SQLite database will be backed up as part of data directory"
return 0
fi
info "Backing up MariaDB database..."
local db_dump="${BACKUP_DIR}/database/npm_${TIMESTAMP}.sql"
mkdir -p "${BACKUP_DIR}/database"
local dump_cmd=""
if command -v mariadb-dump >/dev/null 2>&1; then
@@ -253,6 +286,7 @@ backup_database() {
export MYSQL_PWD="${DB_PASS}"
if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then
unset MYSQL_PWD
die "Database dump failed"
fi
unset MYSQL_PWD
@@ -265,101 +299,30 @@ backup_database() {
success "Database backup complete: ${db_dump} (${size})"
}
backup_pvc() {
local pvc_name="$1"
backup_directory() {
local src_path="$1"
local dest_subdir="$2"
local description="$3"
info "Backing up ${description} (PVC: ${pvc_name})..."
info "Backing up ${description}..."
local dest_dir="${BACKUP_DIR}/${dest_subdir}"
mkdir -p "${dest_dir}"
if ! ${KUBECTL_CMD} get pvc "${pvc_name}" -n "${APP_NAMESPACE}" >/dev/null 2>&1; then
warn "PVC ${pvc_name} not found in namespace ${APP_NAMESPACE}, skipping..."
if [[ ! -d "${src_path}" ]]; then
warn "Source path does not exist: ${src_path}"
return 0
fi
local volume_name=$(${KUBECTL_CMD} get pvc "${pvc_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.spec.volumeName}' 2>/dev/null || true)
if [[ -z "${volume_name}" ]]; then
warn "PVC ${pvc_name} is not bound to a volume, skipping..."
return 0
fi
info "PVC ${pvc_name} bound to volume ${volume_name}"
local pod_name="npm-backup-${pvc_name}-${TIMESTAMP}"
local yaml_file="/tmp/${pod_name}.yaml"
cat > "${yaml_file}" <<EOF
apiVersion: v1
kind: Pod
metadata:
name: ${pod_name}
namespace: ${APP_NAMESPACE}
spec:
restartPolicy: Never
containers:
- name: backup
image: alpine:latest
command: ["/bin/sh", "-c", "sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: ${pvc_name}
EOF
info "Creating temporary pod to access PVC..."
${KUBECTL_CMD} apply -f "${yaml_file}" >>"${LOG_FILE}" 2>&1
local retries=30
while [[ ${retries} -gt 0 ]]; do
local phase=$(${KUBECTL_CMD} get pod "${pod_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.status.phase}' 2>/dev/null || echo "Unknown")
if [[ "${phase}" == "Running" ]]; then
break
fi
sleep 2
((retries--))
done
if [[ ${retries} -eq 0 ]]; then
warn "Timeout waiting for backup pod, cleaning up..."
${KUBECTL_CMD} delete pod "${pod_name}" -n "${APP_NAMESPACE}" --ignore-not-found=true >>"${LOG_FILE}" 2>&1
rm -f "${yaml_file}"
info "Copying from ${src_path} to ${dest_dir}..."
if ! rsync -av "${src_path}/" "${dest_dir}/" 2>&1 | tee -a "${LOG_FILE}"; then
warn "Failed to copy data from ${src_path}"
return 1
fi
info "Copying data from PVC..."
if ! ${KUBECTL_CMD} cp "${APP_NAMESPACE}/${pod_name}:/data/." "${dest_dir}/" >>"${LOG_FILE}" 2>&1; then
warn "Failed to copy data from PVC ${pvc_name}"
else
local count=$(find "${dest_dir}" -type f | wc -l)
local size=$(du -sh "${dest_dir}" | cut -f1)
success "${description} backup complete: ${count} files, ${size}"
fi
info "Cleaning up temporary pod..."
${KUBECTL_CMD} delete pod "${pod_name}" -n "${APP_NAMESPACE}" --ignore-not-found=true >>"${LOG_FILE}" 2>&1
rm -f "${yaml_file}"
}
backup_manifests() {
info "Backing up Kubernetes manifests..."
local manifest_dir="${BACKUP_DIR}/manifests"
mkdir -p "${manifest_dir}"
${KUBECTL_CMD} get all,configmap,secret,pvc,ingress,serviceaccount,role,rolebinding -n "${APP_NAMESPACE}" -o yaml > "${manifest_dir}/all-resources.yaml" 2>>"${LOG_FILE}" || true
for resource in deployment statefulset service configmap secret pvc ingress; do
${KUBECTL_CMD} get "${resource}" -n "${APP_NAMESPACE}" -o yaml > "${manifest_dir}/${resource}s.yaml" 2>>"${LOG_FILE}" || true
done
success "Manifests backed up to ${manifest_dir}"
local count=$(find "${dest_dir}" -type f | wc -l)
local size=$(du -sh "${dest_dir}" | cut -f1)
success "${description} backup complete: ${count} files, ${size}"
}
create_archive() {
@@ -402,14 +365,13 @@ Nginx Proxy Manager Backup Restore Information
==============================================
Backup Date: $(date)
Backup Timestamp: ${TIMESTAMP}
Source: TrueNAS App (namespace: ${APP_NAMESPACE})
Source: TrueNAS 27+ App (direct dataset access)
Database: ${DB_TYPE} ${DB_NAME}
Backup Contents:
- database/npm_${TIMESTAMP}.sql.gz - Full database dump (if MariaDB)
- data/ - NPM data directory (config, certificates, etc.)
- letsencrypt/ - Let's Encrypt certificates (if separate PVC)
- manifests/ - Kubernetes resource definitions
- data/ - NPM data directory (config, certificates, SQLite DB)
- letsencrypt/ - Let's Encrypt certificates (if separate path)
To restore to Docker:
1. Copy the backup archive to your Docker host
@@ -437,6 +399,10 @@ Important NPM-specific notes:
4. Check /data/config/production.json for database settings
5. Default admin email: admin@example.com / password: changeme (change on first login!)
Source Paths Used:
- Data: ${NPM_DATA_PATH:-<not set>}
- Let's Encrypt: ${NPM_LETSENCRYPT_PATH:-<not set>}
EOF
success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt"
@@ -448,22 +414,19 @@ EOF
main() {
info "======================================"
info "Nginx Proxy Manager TrueNAS App Backup Started"
info "Nginx Proxy Manager TrueNAS 27+ App Backup Started"
info "======================================"
info "Timestamp: ${TIMESTAMP}"
info "Backup destination: ${BACKUP_DEST}"
info "Backup directory: ${BACKUP_DIR}"
detect_kubectl
detect_namespace
detect_database
detect_pvcs
validate_paths
validate_database
backup_manifests
backup_database
backup_pvc "${PVC_DATA}" "data" "Data directory"
backup_pvc "${PVC_LETS_ENCRYPT}" "letsencrypt" "Let's Encrypt certificates"
backup_directory "${NPM_DATA_PATH}" "data" "Data directory"
backup_directory "${NPM_LETSENCRYPT_PATH}" "letsencrypt" "Let's Encrypt certificates"
local archive=$(create_archive)
cleanup_old_backups