487 lines
17 KiB
Bash
487 lines
17 KiB
Bash
#!/bin/bash
|
|
# =============================================================================
|
|
# Nginx Proxy Manager Backup Script for TrueNAS 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.
|
|
#
|
|
# 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)
|
|
# - Write access to backup destination dataset
|
|
# =============================================================================
|
|
|
|
set -euo pipefail
|
|
|
|
# =============================================================================
|
|
# CONFIGURATION
|
|
# =============================================================================
|
|
|
|
APP_NAMESPACE="${APP_NAMESPACE:-nginx-proxy-manager}"
|
|
BACKUP_DEST="${BACKUP_DEST:-/mnt/tank/backups/npm}"
|
|
|
|
# Database details (auto-detected if not set)
|
|
DB_TYPE="${DB_TYPE:-sqlite}" # sqlite or mariadb
|
|
DB_HOST="${DB_HOST:-}"
|
|
DB_PORT="${DB_PORT:-}"
|
|
DB_NAME="${DB_NAME:-npm}"
|
|
DB_USER="${DB_USER:-npm}"
|
|
DB_PASS="${DB_PASS:-}"
|
|
|
|
# NPM persistent volume claim names (auto-detected if not set)
|
|
PVC_DATA="${PVC_DATA:-}"
|
|
PVC_LETS_ENCRYPT="${PVC_LETS_ENCRYPT:-}"
|
|
|
|
RETENTION_COUNT="${RETENTION_COUNT:-7}"
|
|
COMPRESSION_LEVEL="${COMPRESSION_LEVEL:-6}"
|
|
|
|
# =============================================================================
|
|
# INTERNAL VARIABLES
|
|
# =============================================================================
|
|
|
|
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"
|
|
|
|
RED='\033[0;31m'
|
|
GREEN='\033[0;32m'
|
|
YELLOW='\033[1;33m'
|
|
BLUE='\033[0;34m'
|
|
NC='\033[0m'
|
|
|
|
# =============================================================================
|
|
# HELPER FUNCTIONS
|
|
# =============================================================================
|
|
|
|
log() {
|
|
local level="$1"
|
|
shift
|
|
local msg="$*"
|
|
local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
|
|
echo -e "${timestamp} [${level}] ${msg}" | tee -a "${LOG_FILE}"
|
|
}
|
|
|
|
info() { log "INFO" "${BLUE}$*${NC}"; }
|
|
warn() { log "WARN" "${YELLOW}$*${NC}"; }
|
|
error() { log "ERROR" "${RED}$*${NC}"; }
|
|
success() { log "SUCCESS" "${GREEN}$*${NC}"; }
|
|
|
|
die() {
|
|
error "$*"
|
|
exit 1
|
|
}
|
|
|
|
# =============================================================================
|
|
# DETECTION 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}"
|
|
return 0
|
|
fi
|
|
done
|
|
die "kubectl not found. Please install k3s or kubectl."
|
|
fi
|
|
info "Using kubectl: ${KUBECTL_CMD}"
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
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)
|
|
fi
|
|
fi
|
|
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
|
|
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)"
|
|
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
|
|
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."
|
|
else
|
|
info "Database: ${DB_TYPE} ${DB_NAME}"
|
|
fi
|
|
}
|
|
|
|
detect_pvcs() {
|
|
info "Detecting persistent volume claims..."
|
|
|
|
local pvcs=$(${KUBECTL_CMD} get pvc -n "${APP_NAMESPACE}" -o jsonpath='{range .items[*]}{.metadata.name}{" "}{.spec.volumeName}{"\n"}{end}' 2>/dev/null || true)
|
|
|
|
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
|
|
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}"
|
|
}
|
|
|
|
# =============================================================================
|
|
# BACKUP FUNCTIONS
|
|
# =============================================================================
|
|
|
|
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"
|
|
return 0
|
|
fi
|
|
|
|
local db_dump="${BACKUP_DIR}/database/npm_${TIMESTAMP}.sql"
|
|
|
|
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
|
|
die "Neither mariadb-dump nor mysqldump found. Install mariadb-client or mysql-client."
|
|
fi
|
|
|
|
info "Using ${dump_cmd} for database dump"
|
|
|
|
local conn_params=(
|
|
"-h" "${DB_HOST}"
|
|
"-P" "${DB_PORT}"
|
|
"-u" "${DB_USER}"
|
|
"--single-transaction"
|
|
"--routines"
|
|
"--triggers"
|
|
"--events"
|
|
"--hex-blob"
|
|
"--complete-insert"
|
|
"--extended-insert"
|
|
"--quick"
|
|
"--lock-tables=false"
|
|
)
|
|
|
|
export MYSQL_PWD="${DB_PASS}"
|
|
if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then
|
|
die "Database dump failed"
|
|
fi
|
|
unset MYSQL_PWD
|
|
|
|
info "Compressing database dump..."
|
|
gzip -${COMPRESSION_LEVEL} "${db_dump}"
|
|
db_dump="${db_dump}.gz"
|
|
|
|
local size=$(du -h "${db_dump}" | cut -f1)
|
|
success "Database backup complete: ${db_dump} (${size})"
|
|
}
|
|
|
|
backup_pvc() {
|
|
local pvc_name="$1"
|
|
local dest_subdir="$2"
|
|
local description="$3"
|
|
|
|
info "Backing up ${description} (PVC: ${pvc_name})..."
|
|
|
|
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..."
|
|
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}"
|
|
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}"
|
|
}
|
|
|
|
create_archive() {
|
|
info "Creating compressed archive..."
|
|
|
|
local archive_name="npm_backup_${TIMESTAMP}.tar.gz"
|
|
local archive_path="${BACKUP_DEST}/${archive_name}"
|
|
|
|
tar -czf "${archive_path}" -C "${BACKUP_DEST}" "npm_backup_${TIMESTAMP}" 2>>"${LOG_FILE}"
|
|
|
|
local size=$(du -h "${archive_path}" | cut -f1)
|
|
success "Archive created: ${archive_path} (${size})"
|
|
|
|
sha256sum "${archive_path}" > "${archive_path}.sha256"
|
|
info "SHA256: $(cat "${archive_path}.sha256")"
|
|
|
|
info "Cleaning up uncompressed backup directory..."
|
|
rm -rf "${BACKUP_DIR}"
|
|
|
|
echo "${archive_path}"
|
|
}
|
|
|
|
cleanup_old_backups() {
|
|
info "Cleaning up old backups (keeping last ${RETENTION_COUNT})..."
|
|
|
|
cd "${BACKUP_DEST}"
|
|
ls -1t npm_backup_*.tar.gz 2>/dev/null | tail -n +$((RETENTION_COUNT + 1)) | while read -r file; do
|
|
info "Removing old backup: ${file}"
|
|
rm -f "${file}" "${file}.sha256"
|
|
done
|
|
|
|
success "Cleanup complete"
|
|
}
|
|
|
|
generate_restore_info() {
|
|
info "Generating restore information..."
|
|
|
|
cat > "${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt" <<EOF
|
|
Nginx Proxy Manager Backup Restore Information
|
|
==============================================
|
|
Backup Date: $(date)
|
|
Backup Timestamp: ${TIMESTAMP}
|
|
Source: TrueNAS App (namespace: ${APP_NAMESPACE})
|
|
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
|
|
|
|
To restore to Docker:
|
|
1. Copy the backup archive to your Docker host
|
|
2. Run the restore script: ./restore-nginx-proxy-manager-docker.sh <backup_archive.tar.gz>
|
|
3. Follow the prompts
|
|
|
|
Database Connection for Docker:
|
|
- SQLite (default): No extra config needed, database file in data/
|
|
- MariaDB:
|
|
- Host: <your-docker-db-host> (usually 'db' in docker-compose)
|
|
- Port: 3306
|
|
- Database: npm
|
|
- User: npm
|
|
- Password: <set in docker-compose .env>
|
|
|
|
Volume Mounts for Docker:
|
|
- ./npm-data:/data
|
|
- data/ -> /data/ (config, database, custom SSL)
|
|
- letsencrypt/ -> /etc/letsencrypt/ (SSL certificates)
|
|
|
|
Important NPM-specific notes:
|
|
1. NPM runs as root in container (UID 0) - permissions are less strict
|
|
2. After restore, you may need to update IP addresses in proxy hosts if changed
|
|
3. SSL certificates in letsencrypt/ should work automatically
|
|
4. Check /data/config/production.json for database settings
|
|
5. Default admin email: admin@example.com / password: changeme (change on first login!)
|
|
|
|
EOF
|
|
|
|
success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt"
|
|
}
|
|
|
|
# =============================================================================
|
|
# MAIN EXECUTION
|
|
# =============================================================================
|
|
|
|
main() {
|
|
info "======================================"
|
|
info "Nginx Proxy Manager TrueNAS 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
|
|
|
|
backup_manifests
|
|
backup_database
|
|
backup_pvc "${PVC_DATA}" "data" "Data directory"
|
|
backup_pvc "${PVC_LETS_ENCRYPT}" "letsencrypt" "Let's Encrypt certificates"
|
|
|
|
local archive=$(create_archive)
|
|
cleanup_old_backups
|
|
generate_restore_info
|
|
|
|
info "======================================"
|
|
success "Backup completed successfully!"
|
|
info "======================================"
|
|
info "Archive: ${archive}"
|
|
info "Checksum: ${archive}.sha256"
|
|
info "Restore info: ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt"
|
|
info ""
|
|
info "Next steps:"
|
|
info "1. Copy ${archive} to your Docker host"
|
|
info "2. Run the restore script on the Docker host"
|
|
info "3. Verify the restored Nginx Proxy Manager instance"
|
|
}
|
|
|
|
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
|
main "$@"
|
|
fi |