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
+224 -258
View File
@@ -1,17 +1,20 @@
#!/bin/bash #!/bin/bash
# ============================================================================= # =============================================================================
# Nextcloud Backup Script for TrueNAS App -> Docker Migration # Nextcloud Backup Script for TrueNAS 27+ App -> Docker Migration
# ============================================================================= # =============================================================================
# This script backs up a Nextcloud instance running as a TrueNAS App (k3s/Kubernetes) # This script backs up a Nextcloud instance running as a TrueNAS App
# to a TrueNAS dataset/share, ready for restoration to a Docker container. # 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). # Run this script ON the TrueNAS host (via SSH or TrueNAS Shell).
# #
# Requirements: # Requirements:
# - TrueNAS with Nextcloud app installed # - TrueNAS 27+ with Nextcloud app installed
# - Access to k3s/kubectl (usually via /usr/local/bin/k3s kubectl) # - PostgreSQL client (pg_dump) or MariaDB/MySQL client (mariadb-dump/mysqldump)
# - PostgreSQL client tools (pg_dump) or MariaDB/MySQL client tools
# - Write access to backup destination dataset # - Write access to backup destination dataset
# - Read access to Nextcloud app datasets (configured in app settings)
# ============================================================================= # =============================================================================
set -euo pipefail set -euo pipefail
@@ -20,24 +23,25 @@ set -euo pipefail
# CONFIGURATION - Adjust these values for your environment # CONFIGURATION - Adjust these values for your environment
# ============================================================================= # =============================================================================
# TrueNAS App namespace (usually the app name)
APP_NAMESPACE="${APP_NAMESPACE:-nextcloud}"
# Backup destination (TrueNAS dataset path) # Backup destination (TrueNAS dataset path)
BACKUP_DEST="${BACKUP_DEST:-/mnt/tank/backups/nextcloud}" BACKUP_DEST="${BACKUP_DEST:-/mnt/tank/backups/nextcloud}"
# Database details (auto-detected if not set) # ---- Database Configuration ----
DB_TYPE="${DB_TYPE:-postgresql}" # postgresql or mariadb DB_TYPE="${DB_TYPE:-postgresql}" # postgresql or mariadb
DB_HOST="${DB_HOST:-}" DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-}" DB_PORT="${DB_PORT:-}" # Auto: 5432 for PG, 3306 for MariaDB
DB_NAME="${DB_NAME:-nextcloud}" DB_NAME="${DB_NAME:-nextcloud}"
DB_USER="${DB_USER:-nextcloud}" DB_USER="${DB_USER:-nextcloud}"
DB_PASS="${DB_PASS:-}" DB_PASS="${DB_PASS:-}" # Required!
# Nextcloud persistent volume claim names (auto-detected if not set) # ---- Nextcloud Data Paths (Host filesystem paths) ----
PVC_DATA="${PVC_DATA:-}" # These are the dataset paths you configured in the Nextcloud app settings
PVC_CONFIG="${PVC_CONFIG:-}" # Example: /mnt/tank/apps/nextcloud/data
PVC_APPS="${PVC_APPS:-}" # Example: /mnt/tank/apps/nextcloud/config
# Example: /mnt/tank/apps/nextcloud/custom_apps
NEXTCLOUD_DATA_PATH="${NEXTCLOUD_DATA_PATH:-}"
NEXTCLOUD_CONFIG_PATH="${NEXTCLOUD_CONFIG_PATH:-}"
NEXTCLOUD_APPS_PATH="${NEXTCLOUD_APPS_PATH:-}"
# Retention: keep last N backups # Retention: keep last N backups
RETENTION_COUNT="${RETENTION_COUNT:-7}" RETENTION_COUNT="${RETENTION_COUNT:-7}"
@@ -55,7 +59,6 @@ MAINTENANCE_MODE="${MAINTENANCE_MODE:-true}"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S") TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="${BACKUP_DEST}/nextcloud_backup_${TIMESTAMP}" BACKUP_DIR="${BACKUP_DEST}/nextcloud_backup_${TIMESTAMP}"
mkdir -p "${BACKUP_DIR}" mkdir -p "${BACKUP_DIR}"
KUBECTL_CMD="${KUBECTL_CMD:-/usr/local/bin/k3s kubectl}"
LOG_FILE="${BACKUP_DIR}/backup.log" LOG_FILE="${BACKUP_DIR}/backup.log"
# Colors for output # Colors for output
@@ -87,160 +90,166 @@ die() {
exit 1 exit 1
} }
run_cmd() { # =============================================================================
info "Running: $*" # VALIDATION FUNCTIONS
if ! "$@" 2>&1 | tee -a "${LOG_FILE}"; then # =============================================================================
die "Command failed: $*"
validate_paths() {
info "Validating data paths..."
local has_paths=false
if [[ -n "${NEXTCLOUD_DATA_PATH}" ]] && [[ -d "${NEXTCLOUD_DATA_PATH}" ]]; then
info "Found data path: ${NEXTCLOUD_DATA_PATH}"
has_paths=true
elif [[ -n "${NEXTCLOUD_DATA_PATH}" ]]; then
warn "Data path does not exist: ${NEXTCLOUD_DATA_PATH}"
fi
if [[ -n "${NEXTCLOUD_CONFIG_PATH}" ]] && [[ -d "${NEXTCLOUD_CONFIG_PATH}" ]]; then
info "Found config path: ${NEXTCLOUD_CONFIG_PATH}"
has_paths=true
elif [[ -n "${NEXTCLOUD_CONFIG_PATH}" ]]; then
warn "Config path does not exist: ${NEXTCLOUD_CONFIG_PATH}"
fi
if [[ -n "${NEXTCLOUD_APPS_PATH}" ]] && [[ -d "${NEXTCLOUD_APPS_PATH}" ]]; then
info "Found apps path: ${NEXTCLOUD_APPS_PATH}"
has_paths=true
elif [[ -n "${NEXTCLOUD_APPS_PATH}" ]]; then
warn "Apps path does not exist: ${NEXTCLOUD_APPS_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 Nextcloud data paths found. Please set NEXTCLOUD_DATA_PATH, NEXTCLOUD_CONFIG_PATH, NEXTCLOUD_APPS_PATH environment variables to the dataset paths configured in your Nextcloud app."
fi fi
} }
# ============================================================================= detect_paths() {
# DETECTION FUNCTIONS local common_bases=(
# ============================================================================= "/mnt/tank/apps/nextcloud"
"/mnt/pool/apps/nextcloud"
"/mnt/data/apps/nextcloud"
"/mnt/storage/apps/nextcloud"
"/mnt/apps/nextcloud"
)
detect_kubectl() { for base in "${common_bases[@]}"; do
if [[ ! -x "${KUBECTL_CMD}" ]]; then if [[ -d "${base}" ]]; then
for cmd in /usr/local/bin/k3s /usr/bin/k3s /usr/local/bin/kubectl /usr/bin/kubectl; do info "Found potential base path: ${base}"
if [[ -x "${cmd}" ]]; then
if [[ "${cmd}" == *k3s ]]; then if [[ -d "${base}/data" ]] && [[ -z "${NEXTCLOUD_DATA_PATH}" ]]; then
KUBECTL_CMD="${cmd} kubectl" NEXTCLOUD_DATA_PATH="${base}/data"
else info "Auto-detected data: ${NEXTCLOUD_DATA_PATH}"
KUBECTL_CMD="${cmd}" fi
fi if [[ -d "${base}/config" ]] && [[ -z "${NEXTCLOUD_CONFIG_PATH}" ]]; then
info "Found kubectl at: ${KUBECTL_CMD}" NEXTCLOUD_CONFIG_PATH="${base}/config"
info "Auto-detected config: ${NEXTCLOUD_CONFIG_PATH}"
fi
if [[ -d "${base}/custom_apps" ]] && [[ -z "${NEXTCLOUD_APPS_PATH}" ]]; then
NEXTCLOUD_APPS_PATH="${base}/custom_apps"
info "Auto-detected custom apps: ${NEXTCLOUD_APPS_PATH}"
fi
if [[ -d "${base}/apps" ]] && [[ -z "${NEXTCLOUD_APPS_PATH}" ]]; then
NEXTCLOUD_APPS_PATH="${base}/apps"
info "Auto-detected apps: ${NEXTCLOUD_APPS_PATH}"
fi
if [[ -n "${NEXTCLOUD_DATA_PATH}" ]] || [[ -n "${NEXTCLOUD_CONFIG_PATH}" ]] || [[ -n "${NEXTCLOUD_APPS_PATH}" ]]; then
return 0 return 0
fi fi
done fi
die "kubectl not found. Please install k3s or kubectl." done
fi
info "Using kubectl: ${KUBECTL_CMD}"
} }
detect_namespace() { validate_database() {
if [[ -z "${APP_NAMESPACE}" ]]; then info "Validating database connection..."
info "Auto-detecting Nextcloud namespace..."
local ns=$(${KUBECTL_CMD} get pods --all-namespaces -l app=nextcloud -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 nextcloud nextcloud-app apps-nextcloud; 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 Nextcloud namespace. Set APP_NAMESPACE manually."
fi
fi
}
detect_database() {
info "Detecting database configuration..."
# Try to get database credentials from Kubernetes secrets
local secret_name=$(${KUBECTL_CMD} get secrets -n "${APP_NAMESPACE}" -o name 2>/dev/null | grep -E '(postgres|mariadb|mysql|database|nextcloud)' | head -1 | cut -d/ -f2 || true)
if [[ -n "${secret_name}" ]]; then
info "Found database secret: ${secret_name}"
if [[ -z "${DB_PORT}" ]]; then
if [[ "${DB_TYPE}" == "postgresql" ]]; then if [[ "${DB_TYPE}" == "postgresql" ]]; then
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="5432"
DB_PORT="${DB_PORT:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.port}' 2>/dev/null | base64 -d || echo "5432")}"
DB_NAME="${DB_NAME:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.database}' 2>/dev/null | base64 -d || echo "nextcloud")}"
DB_USER="${DB_USER:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.username}' 2>/dev/null | base64 -d || echo "nextcloud")}"
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.postgres-password}' 2>/dev/null | base64 -d || true)
fi
else 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="3306"
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 "nextcloud")}"
DB_USER="${DB_USER:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.username}' 2>/dev/null | base64 -d || echo "nextcloud")}"
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
if [[ -z "${DB_PASS}" ]]; then
DB_PASS=$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.mysql-root-password}' 2>/dev/null | base64 -d || true)
fi
fi fi
fi fi
# Try to detect from Nextcloud config.php if running if [[ -z "${DB_PASS}" ]]; then
if [[ -z "${DB_HOST}" ]] || [[ -z "${DB_PASS}" ]]; then warn "DB_PASS not set. Trying to find it..."
info "Trying to detect from Nextcloud pod config..." find_db_password
local nc_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -l app=nextcloud -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)
if [[ -n "${nc_pod}" ]]; then
local config=$(${KUBECTL_CMD} exec -n "${APP_NAMESPACE}" "${nc_pod}" -- cat /var/www/html/config/config.php 2>/dev/null || true)
if [[ -n "${config}" ]]; then
if [[ "${config}" == *"pgsql"* ]] || [[ "${config}" == *"postgresql"* ]]; then
DB_TYPE="postgresql"
DB_PORT="${DB_PORT:-5432}"
else
DB_TYPE="mariadb"
DB_PORT="${DB_PORT:-3306}"
fi
DB_HOST="${DB_HOST:-$(echo "${config}" | grep -oP \"'dbhost'\s*=>\s*'\K[^']+\" | head -1 || true)}"
DB_USER="${DB_USER:-$(echo "${config}" | grep -oP \"'dbuser'\s*=>\s*'\K[^']+\" | head -1 || true)}"
DB_PASS="${DB_PASS:-$(echo "${config}" | grep -oP \"'dbpassword'\s*=>\s*'\K[^']+\" | head -1 || true)}"
DB_NAME="${DB_NAME:-$(echo "${config}" | grep -oP \"'dbname'\s*=>\s*'\K[^']+\" | head -1 || true)}"
fi
fi
fi fi
# Fallback: check for database pod in same namespace if [[ -z "${DB_PASS}" ]]; then
if [[ -z "${DB_HOST}" ]]; then die "Database password (DB_PASS) is required. Please set it or ensure it can be auto-detected."
if [[ "${DB_TYPE}" == "postgresql" ]]; then
local db_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -o name 2>/dev/null | grep -E '(postgres|postgresql)' | head -1 | cut -d/ -f2 || true)
else
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)
fi
if [[ -n "${db_pod}" ]]; then
DB_HOST="${db_pod}"
info "Detected database pod: ${DB_HOST}"
fi
fi fi
if [[ -z "${DB_HOST}" ]] || [[ -z "${DB_PASS}" ]]; then if [[ "${DB_TYPE}" == "postgresql" ]]; then
warn "Could not fully auto-detect database credentials." if ! command -v pg_dump >/dev/null 2>&1; then
warn "Please set DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASS, DB_TYPE environment variables." die "pg_dump not found. Install postgresql-client."
fi
export PGPASSWORD="${DB_PASS}"
if ! pg_dump -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" --no-owner --no-privileges --clean --if-exists >/dev/null 2>&1; then
unset PGPASSWORD
die "Cannot connect to PostgreSQL at ${DB_HOST}:${DB_PORT} as ${DB_USER}. Check credentials and ensure database is accessible from host."
fi
unset PGPASSWORD
else else
info "Database: ${DB_TYPE} ${DB_USER}@${DB_HOST}:${DB_PORT}/${DB_NAME}" 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
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."
fi
unset MYSQL_PWD
fi fi
success "Database connection validated"
} }
detect_pvcs() { find_db_password() {
info "Detecting persistent volume claims..." local possible_files=(
"/mnt/tank/apps/nextcloud/.env"
"/mnt/pool/apps/nextcloud/.env"
"/mnt/data/apps/nextcloud/.env"
"/mnt/storage/apps/nextcloud/.env"
"/mnt/apps/nextcloud/.env"
"/etc/nextcloud/db_password"
"/root/.nextcloud_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 if command -v docker >/dev/null 2>&1; then
echo "${pvcs}" | while read -r name volume; do local db_container=$(docker ps --format '{{.Names}}' | grep -iE '(postgres|mariadb|mysql|nextcloud.*db)' | head -1 || true)
info "Found PVC: ${name} -> ${volume}" if [[ -n "${db_container}" ]]; then
case "${name}" in info "Found potential DB container: ${db_container}"
*data*|*nextcloud*) local pass=$(docker inspect "${db_container}" 2>/dev/null | grep -iE '(POSTGRES_PASSWORD|MYSQL_PASSWORD|MARIADB_PASSWORD)' | head -1 | sed -E 's/.*"([^"]+)".*/\1/' || true)
PVC_DATA="${PVC_DATA:-${name}}" if [[ -n "${pass}" ]]; then
;; DB_PASS="${pass}"
*config*) info "Found database password from container env"
PVC_CONFIG="${PVC_CONFIG:-${name}}" return 0
;; fi
*app*|*custom*) fi
PVC_APPS="${PVC_APPS:-${name}}"
;;
esac
done
fi fi
PVC_DATA="${PVC_DATA:-nextcloud-data}"
PVC_CONFIG="${PVC_CONFIG:-nextcloud-config}"
PVC_APPS="${PVC_APPS:-nextcloud-apps}"
info "Using PVCs: data=${PVC_DATA}, config=${PVC_CONFIG}, apps=${PVC_APPS}"
} }
# ============================================================================= # =============================================================================
@@ -252,13 +261,25 @@ enable_maintenance_mode() {
return 0 return 0
fi fi
info "Enabling Nextcloud maintenance mode..." info "Enabling Nextcloud maintenance mode..."
local nc_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -l app=nextcloud -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)
if [[ -n "${nc_pod}" ]]; then # Try to find Nextcloud container and run occ
${KUBECTL_CMD} exec -n "${APP_NAMESPACE}" "${nc_pod}" -- \ if command -v docker >/dev/null 2>&1; then
php occ maintenance:mode --on 2>>"${LOG_FILE}" || warn "Failed to enable maintenance mode" local nc_container=$(docker ps --format '{{.Names}}' | grep -iE 'nextcloud' | grep -vE '(db|redis|cron)' | head -1 || true)
success "Maintenance mode enabled" if [[ -n "${nc_container}" ]]; then
else if docker exec "${nc_container}" php occ maintenance:mode --on 2>>"${LOG_FILE}"; then
warn "No Nextcloud pod found, skipping maintenance mode" success "Maintenance mode enabled"
return 0
else
warn "Failed to enable maintenance mode via container"
fi
fi
fi
# Fallback: write .maintenance file if we have config path
if [[ -n "${NEXTCLOUD_CONFIG_PATH}" ]] && [[ -f "${NEXTCLOUD_CONFIG_PATH}/config.php" ]]; then
# Use sed to enable maintenance mode in config.php
sed -i "s/'maintenance' => false/'maintenance' => true/" "${NEXTCLOUD_CONFIG_PATH}/config.php" 2>/dev/null || true
info "Attempted to enable maintenance mode via config.php"
fi fi
} }
@@ -267,11 +288,18 @@ disable_maintenance_mode() {
return 0 return 0
fi fi
info "Disabling Nextcloud maintenance mode..." info "Disabling Nextcloud maintenance mode..."
local nc_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -l app=nextcloud -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)
if [[ -n "${nc_pod}" ]]; then if command -v docker >/dev/null 2>&1; then
${KUBECTL_CMD} exec -n "${APP_NAMESPACE}" "${nc_pod}" -- \ local nc_container=$(docker ps --format '{{.Names}}' | grep -iE 'nextcloud' | grep -vE '(db|redis|cron)' | head -1 || true)
php occ maintenance:mode --off 2>>"${LOG_FILE}" || warn "Failed to disable maintenance mode" if [[ -n "${nc_container}" ]]; then
success "Maintenance mode disabled" docker exec "${nc_container}" php occ maintenance:mode --off 2>>"${LOG_FILE}" || warn "Failed to disable maintenance mode via container"
return 0
fi
fi
if [[ -n "${NEXTCLOUD_CONFIG_PATH}" ]] && [[ -f "${NEXTCLOUD_CONFIG_PATH}/config.php" ]]; then
sed -i "s/'maintenance' => true/'maintenance' => false/" "${NEXTCLOUD_CONFIG_PATH}/config.php" 2>/dev/null || true
info "Attempted to disable maintenance mode via config.php"
fi fi
} }
@@ -279,19 +307,15 @@ backup_database() {
info "Backing up ${DB_TYPE} database..." info "Backing up ${DB_TYPE} database..."
local db_dump="${BACKUP_DIR}/database/nextcloud_${TIMESTAMP}.sql" local db_dump="${BACKUP_DIR}/database/nextcloud_${TIMESTAMP}.sql"
mkdir -p "${BACKUP_DIR}/database" mkdir -p "${BACKUP_DIR}/database"
if [[ "${DB_TYPE}" == "postgresql" ]]; then if [[ "${DB_TYPE}" == "postgresql" ]]; then
if ! command -v pg_dump >/dev/null 2>&1; then
die "pg_dump not found. Install postgresql-client."
fi
info "Using pg_dump for database dump" info "Using pg_dump for database dump"
export PGPASSWORD="${DB_PASS}" export PGPASSWORD="${DB_PASS}"
if ! pg_dump -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" \ if ! pg_dump -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" \
--no-owner --no-privileges --clean --if-exists \ --no-owner --no-privileges --clean --if-exists \
> "${db_dump}" 2>>"${LOG_FILE}"; then > "${db_dump}" 2>>"${LOG_FILE}"; then
unset PGPASSWORD
die "PostgreSQL dump failed" die "PostgreSQL dump failed"
fi fi
unset PGPASSWORD unset PGPASSWORD
@@ -323,115 +347,55 @@ backup_database() {
export MYSQL_PWD="${DB_PASS}" export MYSQL_PWD="${DB_PASS}"
if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then
unset MYSQL_PWD
die "MariaDB/MySQL dump failed" die "MariaDB/MySQL dump failed"
fi fi
unset MYSQL_PWD unset MYSQL_PWD
fi fi
# Compress the dump
info "Compressing database dump..." info "Compressing database dump..."
gzip -${COMPRESSION_LEVEL} "${db_dump}" gzip -${COMPRESSION_LEVEL} "${db_dump}"
db_dump="${db_dump}.gz" db_dump="${db_dump}.gz"
local size=$(du -h "${db_dump}" | cut -f1) local size=$(du -h "${db_dump}" | cut -f1)
success "Database backup complete: ${db_dump} (${size})" success "Database backup complete: ${db_dump} (${size})"
# Schema-only dump
if [[ "${DB_TYPE}" == "postgresql" ]]; then
export PGPASSWORD="${DB_PASS}"
pg_dump -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" --no-owner --no-privileges --clean --if-exists --schema-only | gzip -${COMPRESSION_LEVEL} > "${BACKUP_DIR}/database/nextcloud_schema_${TIMESTAMP}.sql.gz"
unset PGPASSWORD
else
export MYSQL_PWD="${DB_PASS}"
${dump_cmd} "${conn_params[@]}" --no-data "${DB_NAME}" | gzip -${COMPRESSION_LEVEL} > "${BACKUP_DIR}/database/nextcloud_schema_${TIMESTAMP}.sql.gz"
unset MYSQL_PWD
fi
} }
backup_pvc() { backup_directory() {
local pvc_name="$1" local src_path="$1"
local dest_subdir="$2" local dest_subdir="$2"
local description="$3" local description="$3"
info "Backing up ${description} (PVC: ${pvc_name})..." info "Backing up ${description}..."
local dest_dir="${BACKUP_DIR}/${dest_subdir}" local dest_dir="${BACKUP_DIR}/${dest_subdir}"
mkdir -p "${dest_dir}" mkdir -p "${dest_dir}"
if ! ${KUBECTL_CMD} get pvc "${pvc_name}" -n "${APP_NAMESPACE}" >/dev/null 2>&1; then if [[ ! -d "${src_path}" ]]; then
warn "PVC ${pvc_name} not found in namespace ${APP_NAMESPACE}, skipping..." warn "Source path does not exist: ${src_path}"
return 0 return 0
fi fi
local volume_name=$(${KUBECTL_CMD} get pvc "${pvc_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.spec.volumeName}' 2>/dev/null || true) info "Copying from ${src_path} to ${dest_dir}..."
if ! rsync -av "${src_path}/" "${dest_dir}/" 2>&1 | tee -a "${LOG_FILE}"; then
if [[ -z "${volume_name}" ]]; then warn "Failed to copy data from ${src_path}"
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="nextcloud-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 return 1
fi fi
info "Copying data from PVC..." local count=$(find "${dest_dir}" -type f | wc -l)
if ! ${KUBECTL_CMD} cp "${APP_NAMESPACE}/${pod_name}:/data/." "${dest_dir}/" >>"${LOG_FILE}" 2>&1; then local size=$(du -sh "${dest_dir}" | cut -f1)
warn "Failed to copy data from PVC ${pvc_name}" success "${description} backup complete: ${count} files, ${size}"
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,networkpolicy -n "${APP_NAMESPACE}" -o yaml > "${manifest_dir}/all-resources.yaml" 2>>"${LOG_FILE}" || true
for resource in deployment statefulset service configmap secret pvc ingress cronjob job; 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() { create_archive() {
@@ -474,15 +438,15 @@ Nextcloud Backup Restore Information
==================================== ====================================
Backup Date: $(date) Backup Date: $(date)
Backup Timestamp: ${TIMESTAMP} Backup Timestamp: ${TIMESTAMP}
Source: TrueNAS App (namespace: ${APP_NAMESPACE}) Source: TrueNAS 27+ App (direct dataset access)
Database: ${DB_TYPE} ${DB_NAME} on ${DB_HOST}:${DB_PORT} as ${DB_USER} Database: ${DB_TYPE} ${DB_NAME} on ${DB_HOST}:${DB_PORT} as ${DB_USER}
Backup Contents: Backup Contents:
- database/nextcloud_${TIMESTAMP}.sql.gz - Full database dump - database/nextcloud_${TIMESTAMP}.sql.gz - Full database dump
- database/nextcloud_schema_${TIMESTAMP}.sql.gz - Schema only
- data/ - Nextcloud data directory (user files) - data/ - Nextcloud data directory (user files)
- config/ - Nextcloud config directory (config.php) - config/ - Nextcloud config directory (config.php)
- apps/ - Nextcloud custom apps (if separate PVC) - apps/ - Nextcloud custom apps (if separate path)
- manifests/ - Kubernetes resource definitions
To restore to Docker: To restore to Docker:
1. Copy the backup archive to your Docker host 1. Copy the backup archive to your Docker host
@@ -509,6 +473,11 @@ Important Nextcloud-specific notes:
4. If using Redis, configure in docker-compose 4. If using Redis, configure in docker-compose
5. If using Cron, set up cron job in Docker 5. If using Cron, set up cron job in Docker
Source Paths Used:
- Data: ${NEXTCLOUD_DATA_PATH:-<not set>}
- Config: ${NEXTCLOUD_CONFIG_PATH:-<not set>}
- Apps: ${NEXTCLOUD_APPS_PATH:-<not set>}
EOF EOF
success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt" success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt"
@@ -520,24 +489,21 @@ EOF
main() { main() {
info "======================================" info "======================================"
info "Nextcloud TrueNAS App Backup Started" info "Nextcloud TrueNAS 27+ App Backup Started"
info "======================================" info "======================================"
info "Timestamp: ${TIMESTAMP}" info "Timestamp: ${TIMESTAMP}"
info "Backup destination: ${BACKUP_DEST}" info "Backup destination: ${BACKUP_DEST}"
info "Backup directory: ${BACKUP_DIR}" info "Backup directory: ${BACKUP_DIR}"
detect_kubectl validate_paths
detect_namespace validate_database
detect_database
detect_pvcs
enable_maintenance_mode enable_maintenance_mode
backup_manifests
backup_database backup_database
backup_pvc "${PVC_DATA}" "data" "Data directory" backup_directory "${NEXTCLOUD_DATA_PATH}" "data" "Data directory"
backup_pvc "${PVC_CONFIG}" "config" "Configuration" backup_directory "${NEXTCLOUD_CONFIG_PATH}" "config" "Configuration"
backup_pvc "${PVC_APPS}" "apps" "Custom apps" backup_directory "${NEXTCLOUD_APPS_PATH}" "apps" "Custom apps"
disable_maintenance_mode disable_maintenance_mode
local archive=$(create_archive) local archive=$(create_archive)
+182 -219
View File
@@ -1,41 +1,50 @@
#!/bin/bash #!/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 # 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. # 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). # Run this script ON the TrueNAS host (via SSH or TrueNAS Shell).
# #
# Requirements: # Requirements:
# - TrueNAS with Nginx Proxy Manager app installed # - TrueNAS 27+ with Nginx Proxy Manager app installed
# - Access to k3s/kubectl (usually via /usr/local/bin/k3s kubectl) # - SQLite3 (for SQLite DB) or MariaDB/MySQL client (for MariaDB)
# - SQLite3 or MariaDB/MySQL client tools (for database dump)
# - Write access to backup destination dataset # - Write access to backup destination dataset
# - Read access to NPM app datasets (configured in app settings)
# ============================================================================= # =============================================================================
set -euo pipefail 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}" 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_TYPE="${DB_TYPE:-sqlite}" # sqlite or mariadb
DB_HOST="${DB_HOST:-}" DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-}" DB_PORT="${DB_PORT:-}" # Auto: 3306 for MariaDB
DB_NAME="${DB_NAME:-npm}" DB_NAME="${DB_NAME:-npm}"
DB_USER="${DB_USER:-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) # ---- NPM Data Paths (Host filesystem paths) ----
PVC_DATA="${PVC_DATA:-}" # These are the dataset paths you configured in the NPM app settings
PVC_LETS_ENCRYPT="${PVC_LETS_ENCRYPT:-}" # 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}" RETENTION_COUNT="${RETENTION_COUNT:-7}"
# Compression level (1-9, higher = smaller but slower)
COMPRESSION_LEVEL="${COMPRESSION_LEVEL:-6}" COMPRESSION_LEVEL="${COMPRESSION_LEVEL:-6}"
# ============================================================================= # =============================================================================
@@ -45,9 +54,9 @@ COMPRESSION_LEVEL="${COMPRESSION_LEVEL:-6}"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S") TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="${BACKUP_DEST}/npm_backup_${TIMESTAMP}" BACKUP_DIR="${BACKUP_DEST}/npm_backup_${TIMESTAMP}"
mkdir -p "${BACKUP_DIR}" mkdir -p "${BACKUP_DIR}"
KUBECTL_CMD="${KUBECTL_CMD:-/usr/local/bin/k3s kubectl}"
LOG_FILE="${BACKUP_DIR}/backup.log" LOG_FILE="${BACKUP_DIR}/backup.log"
# Colors for output
RED='\033[0;31m' RED='\033[0;31m'
GREEN='\033[0;32m' GREEN='\033[0;32m'
YELLOW='\033[1;33m' YELLOW='\033[1;33m'
@@ -77,135 +86,161 @@ die() {
} }
# ============================================================================= # =============================================================================
# DETECTION FUNCTIONS # VALIDATION FUNCTIONS
# ============================================================================= # =============================================================================
detect_kubectl() { validate_paths() {
if [[ ! -x "${KUBECTL_CMD}" ]]; then info "Validating data paths..."
for cmd in /usr/local/bin/k3s /usr/bin/k3s /usr/local/bin/kubectl /usr/bin/kubectl; do
if [[ -x "${cmd}" ]]; then local has_paths=false
if [[ "${cmd}" == *k3s ]]; then
KUBECTL_CMD="${cmd} kubectl" if [[ -n "${NPM_DATA_PATH}" ]] && [[ -d "${NPM_DATA_PATH}" ]]; then
else info "Found data path: ${NPM_DATA_PATH}"
KUBECTL_CMD="${cmd}" has_paths=true
fi elif [[ -n "${NPM_DATA_PATH}" ]]; then
info "Found kubectl at: ${KUBECTL_CMD}" 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 return 0
fi fi
done fi
die "kubectl not found. Please install k3s or kubectl." done
fi
info "Using kubectl: ${KUBECTL_CMD}"
} }
detect_namespace() { validate_database() {
if [[ -z "${APP_NAMESPACE}" ]]; then info "Validating database connection..."
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() { if [[ "${DB_TYPE}" == "sqlite" ]]; then
info "Detecting database configuration..." # SQLite database is typically in the data path
local sqlite_db="${NPM_DATA_PATH}/database.sqlite"
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 [[ -f "${sqlite_db}" ]]; then
info "Found SQLite database: ${sqlite_db}"
if [[ -n "${secret_name}" ]]; then if ! sqlite3 "${sqlite_db}" "SELECT 1;" >/dev/null 2>&1; then
info "Found database secret: ${secret_name}" die "Cannot read SQLite database at ${sqlite_db}. Check permissions."
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
success "SQLite database validated"
else
warn "SQLite database not found at ${sqlite_db} (will be backed up with data path)"
fi fi
return 0
fi fi
# Try to detect from NPM config if running # MariaDB
if [[ -z "${DB_HOST}" ]] && [[ "${DB_TYPE}" == "mariadb" ]]; then if [[ -z "${DB_PORT}" ]]; then
info "Trying to detect from NPM pod config..." DB_PORT="3306"
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 fi
# Check for SQLite database file in PVC if [[ -z "${DB_PASS}" ]]; then
if [[ "${DB_TYPE}" == "sqlite" ]] || [[ -z "${DB_HOST}" ]]; then warn "DB_PASS not set. Trying to find it..."
DB_TYPE="sqlite" find_db_password
info "Using SQLite database (default for NPM)"
fi fi
if [[ "${DB_TYPE}" == "mariadb" ]] && [[ -z "${DB_HOST}" ]]; then if [[ -z "${DB_PASS}" ]]; 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) die "Database password (DB_PASS) is required for MariaDB. Please set it or ensure it can be auto-detected."
if [[ -n "${db_pod}" ]]; then
DB_HOST="${db_pod}"
info "Detected database pod: ${DB_HOST}"
fi
fi fi
if [[ "${DB_TYPE}" == "mariadb" ]] && [[ -z "${DB_HOST}" ]] && [[ -z "${DB_PASS}" ]]; then local dump_cmd=""
warn "Could not fully auto-detect MariaDB credentials." if command -v mariadb-dump >/dev/null 2>&1; then
warn "Please set DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASS environment variables." dump_cmd="mariadb-dump"
elif command -v mysqldump >/dev/null 2>&1; then
dump_cmd="mysqldump"
else else
info "Database: ${DB_TYPE} ${DB_NAME}" die "Neither mariadb-dump nor mysqldump found. Install mariadb-client or mysql-client."
fi 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() { find_db_password() {
info "Detecting persistent volume claims..." 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 if command -v docker >/dev/null 2>&1; then
echo "${pvcs}" | while read -r name volume; do local db_container=$(docker ps --format '{{.Names}}' | grep -iE '(mariadb|mysql|npm.*db)' | head -1 || true)
info "Found PVC: ${name} -> ${volume}" if [[ -n "${db_container}" ]]; then
case "${name}" in info "Found potential DB container: ${db_container}"
*data*|*npm*) local pass=$(docker inspect "${db_container}" 2>/dev/null | grep -iE '(MYSQL_PASSWORD|MARIADB_PASSWORD)' | head -1 | sed -E 's/.*"([^"]+)".*/\1/' || true)
PVC_DATA="${PVC_DATA:-${name}}" if [[ -n "${pass}" ]]; then
;; DB_PASS="${pass}"
*lets*|*encrypt*|*ssl*|*cert*) info "Found database password from container env"
PVC_LETS_ENCRYPT="${PVC_LETS_ENCRYPT:-${name}}" return 0
;; fi
esac fi
done
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() { backup_database() {
info "Backing up ${DB_TYPE} database..."
mkdir -p "${BACKUP_DIR}/database"
if [[ "${DB_TYPE}" == "sqlite" ]]; then 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 directory"
info "SQLite database will be backed up as part of data PVC"
return 0 return 0
fi fi
info "Backing up MariaDB database..."
local db_dump="${BACKUP_DIR}/database/npm_${TIMESTAMP}.sql" local db_dump="${BACKUP_DIR}/database/npm_${TIMESTAMP}.sql"
mkdir -p "${BACKUP_DIR}/database"
local dump_cmd="" local dump_cmd=""
if command -v mariadb-dump >/dev/null 2>&1; then if command -v mariadb-dump >/dev/null 2>&1; then
@@ -253,6 +286,7 @@ backup_database() {
export MYSQL_PWD="${DB_PASS}" export MYSQL_PWD="${DB_PASS}"
if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then
unset MYSQL_PWD
die "Database dump failed" die "Database dump failed"
fi fi
unset MYSQL_PWD unset MYSQL_PWD
@@ -265,101 +299,30 @@ backup_database() {
success "Database backup complete: ${db_dump} (${size})" success "Database backup complete: ${db_dump} (${size})"
} }
backup_pvc() { backup_directory() {
local pvc_name="$1" local src_path="$1"
local dest_subdir="$2" local dest_subdir="$2"
local description="$3" local description="$3"
info "Backing up ${description} (PVC: ${pvc_name})..." info "Backing up ${description}..."
local dest_dir="${BACKUP_DIR}/${dest_subdir}" local dest_dir="${BACKUP_DIR}/${dest_subdir}"
mkdir -p "${dest_dir}" mkdir -p "${dest_dir}"
if ! ${KUBECTL_CMD} get pvc "${pvc_name}" -n "${APP_NAMESPACE}" >/dev/null 2>&1; then if [[ ! -d "${src_path}" ]]; then
warn "PVC ${pvc_name} not found in namespace ${APP_NAMESPACE}, skipping..." warn "Source path does not exist: ${src_path}"
return 0 return 0
fi fi
local volume_name=$(${KUBECTL_CMD} get pvc "${pvc_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.spec.volumeName}' 2>/dev/null || true) info "Copying from ${src_path} to ${dest_dir}..."
if ! rsync -av "${src_path}/" "${dest_dir}/" 2>&1 | tee -a "${LOG_FILE}"; then
if [[ -z "${volume_name}" ]]; then warn "Failed to copy data from ${src_path}"
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 return 1
fi fi
info "Copying data from PVC..." local count=$(find "${dest_dir}" -type f | wc -l)
if ! ${KUBECTL_CMD} cp "${APP_NAMESPACE}/${pod_name}:/data/." "${dest_dir}/" >>"${LOG_FILE}" 2>&1; then local size=$(du -sh "${dest_dir}" | cut -f1)
warn "Failed to copy data from PVC ${pvc_name}" success "${description} backup complete: ${count} files, ${size}"
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() { create_archive() {
@@ -402,14 +365,13 @@ Nginx Proxy Manager Backup Restore Information
============================================== ==============================================
Backup Date: $(date) Backup Date: $(date)
Backup Timestamp: ${TIMESTAMP} Backup Timestamp: ${TIMESTAMP}
Source: TrueNAS App (namespace: ${APP_NAMESPACE}) Source: TrueNAS 27+ App (direct dataset access)
Database: ${DB_TYPE} ${DB_NAME} Database: ${DB_TYPE} ${DB_NAME}
Backup Contents: Backup Contents:
- database/npm_${TIMESTAMP}.sql.gz - Full database dump (if MariaDB) - database/npm_${TIMESTAMP}.sql.gz - Full database dump (if MariaDB)
- data/ - NPM data directory (config, certificates, etc.) - data/ - NPM data directory (config, certificates, SQLite DB)
- letsencrypt/ - Let's Encrypt certificates (if separate PVC) - letsencrypt/ - Let's Encrypt certificates (if separate path)
- manifests/ - Kubernetes resource definitions
To restore to Docker: To restore to Docker:
1. Copy the backup archive to your Docker host 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 4. Check /data/config/production.json for database settings
5. Default admin email: admin@example.com / password: changeme (change on first login!) 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 EOF
success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt" success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt"
@@ -448,22 +414,19 @@ EOF
main() { main() {
info "======================================" info "======================================"
info "Nginx Proxy Manager TrueNAS App Backup Started" info "Nginx Proxy Manager TrueNAS 27+ App Backup Started"
info "======================================" info "======================================"
info "Timestamp: ${TIMESTAMP}" info "Timestamp: ${TIMESTAMP}"
info "Backup destination: ${BACKUP_DEST}" info "Backup destination: ${BACKUP_DEST}"
info "Backup directory: ${BACKUP_DIR}" info "Backup directory: ${BACKUP_DIR}"
detect_kubectl validate_paths
detect_namespace validate_database
detect_database
detect_pvcs
backup_manifests
backup_database backup_database
backup_pvc "${PVC_DATA}" "data" "Data directory" backup_directory "${NPM_DATA_PATH}" "data" "Data directory"
backup_pvc "${PVC_LETS_ENCRYPT}" "letsencrypt" "Let's Encrypt certificates" backup_directory "${NPM_LETSENCRYPT_PATH}" "letsencrypt" "Let's Encrypt certificates"
local archive=$(create_archive) local archive=$(create_archive)
cleanup_old_backups cleanup_old_backups
+189 -241
View File
@@ -1,17 +1,20 @@
#!/bin/bash #!/bin/bash
# ============================================================================= # =============================================================================
# Piwigo Backup Script for TrueNAS App -> Docker Migration # Piwigo Backup Script for TrueNAS 27+ App -> Docker Migration
# ============================================================================= # =============================================================================
# This script backs up a Piwigo instance running as a TrueNAS App (k3s/Kubernetes) # This script backs up a Piwigo instance running as a TrueNAS App
# to a TrueNAS dataset/share, ready for restoration to a Docker container. # 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). # Run this script ON the TrueNAS host (via SSH or TrueNAS Shell).
# #
# Requirements: # Requirements:
# - TrueNAS with Piwigo app installed # - TrueNAS 27+ with Piwigo app installed
# - Access to k3s/kubectl (usually via /usr/local/bin/k3s kubectl) # - MariaDB/MySQL client tools (mariadb-dump/mysqldump) for database dump
# - MariaDB/MySQL client tools (mariadb-dump/mysqldump)
# - Write access to backup destination dataset # - Write access to backup destination dataset
# - Read access to Piwigo app datasets (configured in app settings)
# ============================================================================= # =============================================================================
set -euo pipefail set -euo pipefail
@@ -20,23 +23,29 @@ set -euo pipefail
# CONFIGURATION - Adjust these values for your environment # CONFIGURATION - Adjust these values for your environment
# ============================================================================= # =============================================================================
# TrueNAS App namespace (usually the app name)
APP_NAMESPACE="${APP_NAMESPACE:-piwigo}"
# Backup destination (TrueNAS dataset path) # Backup destination (TrueNAS dataset path)
BACKUP_DEST="${BACKUP_DEST:-/mnt/tank/backups/piwigo}" BACKUP_DEST="${BACKUP_DEST:-/mnt/tank/backups/piwigo}"
# Database details (auto-detected if not set) # ---- Database Configuration ----
DB_HOST="${DB_HOST:-}" # If the database is running as a separate container/app, provide connection details
# If using the built-in MariaDB from the Piwigo app chart, it might be accessible via localhost
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-3306}" DB_PORT="${DB_PORT:-3306}"
DB_NAME="${DB_NAME:-piwigo}" DB_NAME="${DB_NAME:-piwigo}"
DB_USER="${DB_USER:-piwigo}" DB_USER="${DB_USER:-piwigo}"
DB_PASS="${DB_PASS:-}" DB_PASS="${DB_PASS:-}" # Required! Get from app config or secret
# Piwigo persistent volume claim names (auto-detected if not set) # ---- Piwigo Data Paths (Host filesystem paths) ----
PVC_UPLOADS="${PVC_UPLOADS:-}" # These are the dataset paths you configured in the Piwigo app settings
PVC_CONFIG="${PVC_CONFIG:-}" # Example: /mnt/tank/apps/piwigo/uploads
PVC_GALLERIES="${PVC_GALLERIES:-}" # Example: /mnt/tank/apps/piwigo/config
# Example: /mnt/tank/apps/piwigo/galleries
PIWIGO_UPLOADS_PATH="${PIWIGO_UPLOADS_PATH:-}"
PIWIGO_CONFIG_PATH="${PIWIGO_CONFIG_PATH:-}"
PIWIGO_GALLERIES_PATH="${PIWIGO_GALLERIES_PATH:-}"
# Alternative: Single base path if all data is under one dataset
# PIWIGO_BASE_PATH="${PIWIGO_BASE_PATH:-/mnt/tank/apps/piwigo}"
# Retention: keep last N backups # Retention: keep last N backups
RETENTION_COUNT="${RETENTION_COUNT:-7}" RETENTION_COUNT="${RETENTION_COUNT:-7}"
@@ -51,7 +60,6 @@ COMPRESSION_LEVEL="${COMPRESSION_LEVEL:-6}"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S") TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="${BACKUP_DEST}/piwigo_backup_${TIMESTAMP}" BACKUP_DIR="${BACKUP_DEST}/piwigo_backup_${TIMESTAMP}"
mkdir -p "${BACKUP_DIR}" mkdir -p "${BACKUP_DIR}"
KUBECTL_CMD="${KUBECTL_CMD:-/usr/local/bin/k3s kubectl}"
LOG_FILE="${BACKUP_DIR}/backup.log" LOG_FILE="${BACKUP_DIR}/backup.log"
# Colors for output # Colors for output
@@ -91,135 +99,157 @@ run_cmd() {
} }
# ============================================================================= # =============================================================================
# DETECTION FUNCTIONS # VALIDATION FUNCTIONS
# ============================================================================= # =============================================================================
detect_kubectl() { validate_paths() {
if [[ ! -x "${KUBECTL_CMD}" ]]; then info "Validating data paths..."
# Try common locations
for cmd in /usr/local/bin/k3s /usr/bin/k3s /usr/local/bin/kubectl /usr/bin/kubectl; do local has_paths=false
if [[ -x "${cmd}" ]]; then
if [[ "${cmd}" == *k3s ]]; then # Check individual paths
KUBECTL_CMD="${cmd} kubectl" if [[ -n "${PIWIGO_UPLOADS_PATH}" ]] && [[ -d "${PIWIGO_UPLOADS_PATH}" ]]; then
else info "Found uploads path: ${PIWIGO_UPLOADS_PATH}"
KUBECTL_CMD="${cmd}" has_paths=true
fi elif [[ -n "${PIWIGO_UPLOADS_PATH}" ]]; then
info "Found kubectl at: ${KUBECTL_CMD}" warn "Uploads path does not exist: ${PIWIGO_UPLOADS_PATH}"
fi
if [[ -n "${PIWIGO_CONFIG_PATH}" ]] && [[ -d "${PIWIGO_CONFIG_PATH}" ]]; then
info "Found config path: ${PIWIGO_CONFIG_PATH}"
has_paths=true
elif [[ -n "${PIWIGO_CONFIG_PATH}" ]]; then
warn "Config path does not exist: ${PIWIGO_CONFIG_PATH}"
fi
if [[ -n "${PIWIGO_GALLERIES_PATH}" ]] && [[ -d "${PIWIGO_GALLERIES_PATH}" ]]; then
info "Found galleries path: ${PIWIGO_GALLERIES_PATH}"
has_paths=true
elif [[ -n "${PIWIGO_GALLERIES_PATH}" ]]; then
warn "Galleries path does not exist: ${PIWIGO_GALLERIES_PATH}"
fi
# If no individual paths set, try to auto-detect from common locations
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 Piwigo data paths found. Please set PIWIGO_UPLOADS_PATH, PIWIGO_CONFIG_PATH, PIWIGO_GALLERIES_PATH environment variables to the dataset paths configured in your Piwigo app."
fi
}
detect_paths() {
# Common TrueNAS app dataset locations
local common_bases=(
"/mnt/tank/apps/piwigo"
"/mnt/pool/apps/piwigo"
"/mnt/data/apps/piwigo"
"/mnt/storage/apps/piwigo"
"/mnt/apps/piwigo"
)
for base in "${common_bases[@]}"; do
if [[ -d "${base}" ]]; then
info "Found potential base path: ${base}"
if [[ -d "${base}/uploads" ]] && [[ -z "${PIWIGO_UPLOADS_PATH}" ]]; then
PIWIGO_UPLOADS_PATH="${base}/uploads"
info "Auto-detected uploads: ${PIWIGO_UPLOADS_PATH}"
fi
if [[ -d "${base}/config" ]] && [[ -z "${PIWIGO_CONFIG_PATH}" ]]; then
PIWIGO_CONFIG_PATH="${base}/config"
info "Auto-detected config: ${PIWIGO_CONFIG_PATH}"
fi
if [[ -d "${base}/galleries" ]] && [[ -z "${PIWIGO_GALLERIES_PATH}" ]]; then
PIWIGO_GALLERIES_PATH="${base}/galleries"
info "Auto-detected galleries: ${PIWIGO_GALLERIES_PATH}"
fi
# Also check for 'data' as uploads
if [[ -d "${base}/data" ]] && [[ -z "${PIWIGO_UPLOADS_PATH}" ]]; then
PIWIGO_UPLOADS_PATH="${base}/data"
info "Auto-detected uploads (as data): ${PIWIGO_UPLOADS_PATH}"
fi
# If we found at least one, break
if [[ -n "${PIWIGO_UPLOADS_PATH}" ]] || [[ -n "${PIWIGO_CONFIG_PATH}" ]] || [[ -n "${PIWIGO_GALLERIES_PATH}" ]]; then
return 0 return 0
fi fi
done fi
die "kubectl not found. Please install k3s or kubectl." done
fi
info "Using kubectl: ${KUBECTL_CMD}"
} }
detect_namespace() { validate_database() {
if [[ -z "${APP_NAMESPACE}" ]]; then info "Validating database connection..."
info "Auto-detecting Piwigo namespace..."
local ns=$(${KUBECTL_CMD} get pods --all-namespaces -l app=piwigo -o jsonpath='{.items[0].metadata.namespace}' 2>/dev/null || true) if [[ -z "${DB_PASS}" ]]; then
if [[ -n "${ns}" ]]; then warn "DB_PASS not set. Trying to find it from common locations..."
APP_NAMESPACE="${ns}" find_db_password
info "Detected namespace: ${APP_NAMESPACE}"
else
# Try common namespaces
for ns in piwigo piwigo-app apps-piwigo; 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 Piwigo namespace. Set APP_NAMESPACE manually."
fi
fi fi
if [[ -z "${DB_PASS}" ]]; then
die "Database password (DB_PASS) is required. Please set it or ensure it can be auto-detected."
fi
# Test connection
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
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 database at ${DB_HOST}:${DB_PORT} as ${DB_USER}. Check credentials and ensure database is accessible from host."
fi
unset MYSQL_PWD
success "Database connection validated"
} }
detect_database() { find_db_password() {
info "Detecting database configuration..." # Try to find password from common locations
local possible_files=(
"/mnt/tank/apps/piwigo/.env"
"/mnt/pool/apps/piwigo/.env"
"/mnt/data/apps/piwigo/.env"
"/mnt/storage/apps/piwigo/.env"
"/mnt/apps/piwigo/.env"
"/etc/piwigo/db_password"
"/root/.piwigo_db_password"
)
# Try to get database credentials from Kubernetes secrets for file in "${possible_files[@]}"; do
local secret_name=$(${KUBECTL_CMD} get secrets -n "${APP_NAMESPACE}" -o name 2>/dev/null | grep -E '(mariadb|mysql|database|piwigo)' | head -1 | cut -d/ -f2 || true) if [[ -f "${file}" ]]; then
# Try to extract password from file
if [[ -n "${secret_name}" ]]; then local pass=$(grep -iE '(password|passwd)' "${file}" 2>/dev/null | head -1 | sed -E 's/.*[=:]\s*//' | sed -E 's/["\'\'']//g' | xargs)
info "Found database secret: ${secret_name}" if [[ -n "${pass}" ]]; then
DB_HOST="${DB_HOST:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.host}' 2>/dev/null | base64 -d || echo "")}" DB_PASS="${pass}"
DB_PORT="${DB_PORT:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.port}' 2>/dev/null | base64 -d || echo "3306")}" info "Found database password in ${file}"
DB_NAME="${DB_NAME:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.database}' 2>/dev/null | base64 -d || echo "piwigo")}" return 0
DB_USER="${DB_USER:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.username}' 2>/dev/null | base64 -d || echo "piwigo")}" fi
DB_PASS="${DB_PASS:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.password}' 2>/dev/null | base64 -d || echo "")}"
# Also check for mariadb-root-password or similar
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
if [[ -z "${DB_PASS}" ]]; then done
DB_PASS=$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.mysql-root-password}' 2>/dev/null | base64 -d || true)
fi
fi
# Try to detect from Piwigo config if running # Check if there's a MariaDB container running that we can get password from
if [[ -z "${DB_HOST}" ]] || [[ -z "${DB_PASS}" ]]; then if command -v docker >/dev/null 2>&1; then
info "Trying to detect from Piwigo pod config..." local mariadb_container=$(docker ps --format '{{.Names}}' | grep -iE '(mariadb|mysql|piwigo.*db)' | head -1 || true)
local piwigo_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -l app=piwigo -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true) if [[ -n "${mariadb_container}" ]]; then
if [[ -n "${piwigo_pod}" ]]; then info "Found potential MariaDB container: ${mariadb_container}"
# Try to read config from the pod # Try to get password from container env
local config=$(${KUBECTL_CMD} exec -n "${APP_NAMESPACE}" "${piwigo_pod}" -- cat /var/www/html/local/config/config.inc.php 2>/dev/null || true) local pass=$(docker inspect "${mariadb_container}" 2>/dev/null | grep -iE '(MYSQL_PASSWORD|MARIADB_PASSWORD)' | head -1 | sed -E 's/.*"([^"]+)".*/\1/' || true)
if [[ -n "${config}" ]]; then if [[ -n "${pass}" ]]; then
DB_HOST="${DB_HOST:-$(echo "${config}" | grep -oP \"'db_host'\s*=>\s*'\K[^']+\" || true)}" DB_PASS="${pass}"
DB_USER="${DB_USER:-$(echo "${config}" | grep -oP \"'db_user'\s*=>\s*'\K[^']+\" || true)}" info "Found database password from container env"
DB_PASS="${DB_PASS:-$(echo "${config}" | grep -oP \"'db_password'\s*=>\s*'\K[^']+\" || true)}" return 0
DB_NAME="${DB_NAME:-$(echo "${config}" | grep -oP \"'db_name'\s*=>\s*'\K[^']+\" || true)}"
fi fi
fi fi
fi fi
# Fallback: check for MariaDB/MySQL pod in same namespace
if [[ -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
# Final validation
if [[ -z "${DB_HOST}" ]] || [[ -z "${DB_PASS}" ]]; then
warn "Could not fully auto-detect database credentials."
warn "Please set DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASS environment variables."
warn "Or ensure the database secret is labeled correctly in Kubernetes."
else
info "Database: ${DB_USER}@${DB_HOST}:${DB_PORT}/${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
*upload*|*gallery*|*image*|*photo*)
PVC_UPLOADS="${PVC_UPLOADS:-${name}}"
;;
*config*|*data*)
PVC_CONFIG="${PVC_CONFIG:-${name}}"
;;
*gallery*)
PVC_GALLERIES="${PVC_GALLERIES:-${name}}"
;;
esac
done
fi
# If not detected, try common names
PVC_UPLOADS="${PVC_UPLOADS:-piwigo-uploads}"
PVC_CONFIG="${PVC_CONFIG:-piwigo-config}"
PVC_GALLERIES="${PVC_GALLERIES:-piwigo-galleries}"
info "Using PVCs: uploads=${PVC_UPLOADS}, config=${PVC_CONFIG}, galleries=${PVC_GALLERIES}"
} }
# ============================================================================= # =============================================================================
@@ -233,7 +263,6 @@ backup_database() {
mkdir -p "${BACKUP_DIR}/database" mkdir -p "${BACKUP_DIR}/database"
# Check if we have mariadb-dump or mysqldump
local dump_cmd="" local dump_cmd=""
if command -v mariadb-dump >/dev/null 2>&1; then if command -v mariadb-dump >/dev/null 2>&1; then
dump_cmd="mariadb-dump" dump_cmd="mariadb-dump"
@@ -245,7 +274,6 @@ backup_database() {
info "Using ${dump_cmd} for database dump" info "Using ${dump_cmd} for database dump"
# Build connection parameters
local conn_params=( local conn_params=(
"-h" "${DB_HOST}" "-h" "${DB_HOST}"
"-P" "${DB_PORT}" "-P" "${DB_PORT}"
@@ -261,16 +289,12 @@ backup_database() {
"--lock-tables=false" "--lock-tables=false"
) )
# Use password from environment or prompt export MYSQL_PWD="${DB_PASS}"
if [[ -n "${DB_PASS}" ]]; then
export MYSQL_PWD="${DB_PASS}"
fi
info "Dumping database ${DB_NAME} from ${DB_HOST}:${DB_PORT}..." info "Dumping database ${DB_NAME} from ${DB_HOST}:${DB_PORT}..."
if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then
unset MYSQL_PWD
die "Database dump failed. Check credentials and connectivity." die "Database dump failed. Check credentials and connectivity."
fi fi
unset MYSQL_PWD unset MYSQL_PWD
# Compress the dump # Compress the dump
@@ -282,112 +306,35 @@ backup_database() {
success "Database backup complete: ${db_dump} (${size})" success "Database backup complete: ${db_dump} (${size})"
# Also create a schema-only dump for reference # Also create a schema-only dump for reference
export MYSQL_PWD="${DB_PASS}"
${dump_cmd} "${conn_params[@]}" --no-data "${DB_NAME}" | gzip -${COMPRESSION_LEVEL} > "${BACKUP_DIR}/database/piwigo_schema_${TIMESTAMP}.sql.gz" ${dump_cmd} "${conn_params[@]}" --no-data "${DB_NAME}" | gzip -${COMPRESSION_LEVEL} > "${BACKUP_DIR}/database/piwigo_schema_${TIMESTAMP}.sql.gz"
unset MYSQL_PWD
} }
backup_pvc() { backup_directory() {
local pvc_name="$1" local src_path="$1"
local dest_subdir="$2" local dest_subdir="$2"
local description="$3" local description="$3"
info "Backing up ${description} (PVC: ${pvc_name})..." info "Backing up ${description}..."
local dest_dir="${BACKUP_DIR}/${dest_subdir}" local dest_dir="${BACKUP_DIR}/${dest_subdir}"
mkdir -p "${dest_dir}" mkdir -p "${dest_dir}"
# Check if PVC exists if [[ ! -d "${src_path}" ]]; then
if ! ${KUBECTL_CMD} get pvc "${pvc_name}" -n "${APP_NAMESPACE}" >/dev/null 2>&1; then warn "Source path does not exist: ${src_path}"
warn "PVC ${pvc_name} not found in namespace ${APP_NAMESPACE}, skipping..."
return 0 return 0
fi fi
# Get the volume name info "Copying from ${src_path} to ${dest_dir}..."
local volume_name=$(${KUBECTL_CMD} get pvc "${pvc_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.spec.volumeName}' 2>/dev/null || true) if ! rsync -av "${src_path}/" "${dest_dir}/" 2>&1 | tee -a "${LOG_FILE}"; then
warn "Failed to copy data from ${src_path}"
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}"
# Create a temporary pod to access the volume
local pod_name="piwigo-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
# Wait for pod to be ready
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 return 1
fi fi
# Copy data from pod local count=$(find "${dest_dir}" -type f | wc -l)
info "Copying data from PVC..." local size=$(du -sh "${dest_dir}" | cut -f1)
if ! ${KUBECTL_CMD} cp "${APP_NAMESPACE}/${pod_name}:/data/." "${dest_dir}/" >>"${LOG_FILE}" 2>&1; then success "${description} backup complete: ${count} files, ${size}"
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
# Cleanup
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}"
# Export all resources in the namespace
${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
# Also export individually for easier reading
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() { create_archive() {
@@ -433,7 +380,7 @@ Piwigo Backup Restore Information
================================= =================================
Backup Date: $(date) Backup Date: $(date)
Backup Timestamp: ${TIMESTAMP} Backup Timestamp: ${TIMESTAMP}
Source: TrueNAS App (namespace: ${APP_NAMESPACE}) Source: TrueNAS 27+ App (direct dataset access)
Database: ${DB_NAME} on ${DB_HOST}:${DB_PORT} as ${DB_USER} Database: ${DB_NAME} on ${DB_HOST}:${DB_PORT} as ${DB_USER}
Backup Contents: Backup Contents:
@@ -441,8 +388,7 @@ Backup Contents:
- database/piwigo_schema_${TIMESTAMP}.sql.gz - Schema only - database/piwigo_schema_${TIMESTAMP}.sql.gz - Schema only
- uploads/ - Piwigo uploads directory - uploads/ - Piwigo uploads directory
- config/ - Piwigo configuration (local/config/) - config/ - Piwigo configuration (local/config/)
- galleries/ - Piwigo galleries (if separate PVC) - galleries/ - Piwigo galleries (if separate path)
- manifests/ - Kubernetes resource definitions
To restore to Docker: To restore to Docker:
1. Copy the backup archive to your Docker host 1. Copy the backup archive to your Docker host
@@ -462,6 +408,11 @@ Volume Mounts for Docker:
- config/ -> /var/www/html/local/config/ - config/ -> /var/www/html/local/config/
- galleries/ -> /var/www/html/galleries/ (if used) - galleries/ -> /var/www/html/galleries/ (if used)
Source Paths Used:
- Uploads: ${PIWIGO_UPLOADS_PATH:-<not set>}
- Config: ${PIWIGO_CONFIG_PATH:-<not set>}
- Galleries: ${PIWIGO_GALLERIES_PATH:-<not set>}
EOF EOF
success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt" success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt"
@@ -473,25 +424,22 @@ EOF
main() { main() {
info "======================================" info "======================================"
info "Piwigo TrueNAS App Backup Started" info "Piwigo TrueNAS 27+ App Backup Started"
info "======================================" info "======================================"
info "Timestamp: ${TIMESTAMP}" info "Timestamp: ${TIMESTAMP}"
info "Backup destination: ${BACKUP_DEST}" info "Backup destination: ${BACKUP_DEST}"
info "Backup directory: ${BACKUP_DIR}" info "Backup directory: ${BACKUP_DIR}"
# Detection phase # Validate prerequisites
detect_kubectl validate_paths
detect_namespace validate_database
detect_database
detect_pvcs
# Backup phase # Backup phase
backup_manifests
backup_database backup_database
backup_pvc "${PVC_UPLOADS}" "uploads" "Uploads" backup_directory "${PIWIGO_UPLOADS_PATH}" "uploads" "Uploads"
backup_pvc "${PVC_CONFIG}" "config" "Configuration" backup_directory "${PIWIGO_CONFIG_PATH}" "config" "Configuration"
backup_pvc "${PVC_GALLERIES}" "galleries" "Galleries" backup_directory "${PIWIGO_GALLERIES_PATH}" "galleries" "Galleries"
# Archive and cleanup # Archive and cleanup
local archive=$(create_archive) local archive=$(create_archive)