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
# =============================================================================
# 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.
#
# 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 Nextcloud app installed
# - Access to k3s/kubectl (usually via /usr/local/bin/k3s kubectl)
# - PostgreSQL client tools (pg_dump) or MariaDB/MySQL client tools
# - TrueNAS 27+ with Nextcloud app installed
# - PostgreSQL client (pg_dump) or MariaDB/MySQL client (mariadb-dump/mysqldump)
# - Write access to backup destination dataset
# - Read access to Nextcloud app datasets (configured in app settings)
# =============================================================================
set -euo pipefail
@@ -20,24 +23,25 @@ set -euo pipefail
# 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_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_HOST="${DB_HOST:-}"
DB_PORT="${DB_PORT:-}"
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-}" # Auto: 5432 for PG, 3306 for MariaDB
DB_NAME="${DB_NAME:-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)
PVC_DATA="${PVC_DATA:-}"
PVC_CONFIG="${PVC_CONFIG:-}"
PVC_APPS="${PVC_APPS:-}"
# ---- Nextcloud Data Paths (Host filesystem paths) ----
# These are the dataset paths you configured in the Nextcloud app settings
# Example: /mnt/tank/apps/nextcloud/data
# 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_COUNT="${RETENTION_COUNT:-7}"
@@ -55,7 +59,6 @@ MAINTENANCE_MODE="${MAINTENANCE_MODE:-true}"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="${BACKUP_DEST}/nextcloud_backup_${TIMESTAMP}"
mkdir -p "${BACKUP_DIR}"
KUBECTL_CMD="${KUBECTL_CMD:-/usr/local/bin/k3s kubectl}"
LOG_FILE="${BACKUP_DIR}/backup.log"
# Colors for output
@@ -87,160 +90,166 @@ die() {
exit 1
}
run_cmd() {
info "Running: $*"
if ! "$@" 2>&1 | tee -a "${LOG_FILE}"; then
die "Command failed: $*"
# =============================================================================
# VALIDATION FUNCTIONS
# =============================================================================
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
}
# =============================================================================
# DETECTION FUNCTIONS
# =============================================================================
detect_paths() {
local common_bases=(
"/mnt/tank/apps/nextcloud"
"/mnt/pool/apps/nextcloud"
"/mnt/data/apps/nextcloud"
"/mnt/storage/apps/nextcloud"
"/mnt/apps/nextcloud"
)
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}"
for base in "${common_bases[@]}"; do
if [[ -d "${base}" ]]; then
info "Found potential base path: ${base}"
if [[ -d "${base}/data" ]] && [[ -z "${NEXTCLOUD_DATA_PATH}" ]]; then
NEXTCLOUD_DATA_PATH="${base}/data"
info "Auto-detected data: ${NEXTCLOUD_DATA_PATH}"
fi
if [[ -d "${base}/config" ]] && [[ -z "${NEXTCLOUD_CONFIG_PATH}" ]]; then
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
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 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
}
validate_database() {
info "Validating database connection..."
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
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 "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
DB_PORT="5432"
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 "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
DB_PORT="3306"
fi
fi
# Try to detect from Nextcloud config.php if running
if [[ -z "${DB_HOST}" ]] || [[ -z "${DB_PASS}" ]]; then
info "Trying to detect from Nextcloud pod config..."
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
if [[ -z "${DB_PASS}" ]]; then
warn "DB_PASS not set. Trying to find it..."
find_db_password
fi
# Fallback: check for database pod in same namespace
if [[ -z "${DB_HOST}" ]]; then
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
if [[ -z "${DB_PASS}" ]]; then
die "Database password (DB_PASS) is required. Please set it or ensure it can be auto-detected."
fi
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, DB_TYPE environment variables."
if [[ "${DB_TYPE}" == "postgresql" ]]; then
if ! command -v pg_dump >/dev/null 2>&1; then
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
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
success "Database connection validated"
}
detect_pvcs() {
info "Detecting persistent volume claims..."
find_db_password() {
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
echo "${pvcs}" | while read -r name volume; do
info "Found PVC: ${name} -> ${volume}"
case "${name}" in
*data*|*nextcloud*)
PVC_DATA="${PVC_DATA:-${name}}"
;;
*config*)
PVC_CONFIG="${PVC_CONFIG:-${name}}"
;;
*app*|*custom*)
PVC_APPS="${PVC_APPS:-${name}}"
;;
esac
done
if command -v docker >/dev/null 2>&1; then
local db_container=$(docker ps --format '{{.Names}}' | grep -iE '(postgres|mariadb|mysql|nextcloud.*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 '(POSTGRES_PASSWORD|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:-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
fi
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
${KUBECTL_CMD} exec -n "${APP_NAMESPACE}" "${nc_pod}" -- \
php occ maintenance:mode --on 2>>"${LOG_FILE}" || warn "Failed to enable maintenance mode"
success "Maintenance mode enabled"
else
warn "No Nextcloud pod found, skipping maintenance mode"
# Try to find Nextcloud container and run occ
if command -v docker >/dev/null 2>&1; then
local nc_container=$(docker ps --format '{{.Names}}' | grep -iE 'nextcloud' | grep -vE '(db|redis|cron)' | head -1 || true)
if [[ -n "${nc_container}" ]]; then
if docker exec "${nc_container}" php occ maintenance:mode --on 2>>"${LOG_FILE}"; then
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
}
@@ -267,11 +288,18 @@ disable_maintenance_mode() {
return 0
fi
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
${KUBECTL_CMD} exec -n "${APP_NAMESPACE}" "${nc_pod}" -- \
php occ maintenance:mode --off 2>>"${LOG_FILE}" || warn "Failed to disable maintenance mode"
success "Maintenance mode disabled"
if command -v docker >/dev/null 2>&1; then
local nc_container=$(docker ps --format '{{.Names}}' | grep -iE 'nextcloud' | grep -vE '(db|redis|cron)' | head -1 || true)
if [[ -n "${nc_container}" ]]; then
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
}
@@ -279,19 +307,15 @@ backup_database() {
info "Backing up ${DB_TYPE} database..."
local db_dump="${BACKUP_DIR}/database/nextcloud_${TIMESTAMP}.sql"
mkdir -p "${BACKUP_DIR}/database"
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"
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 \
> "${db_dump}" 2>>"${LOG_FILE}"; then
unset PGPASSWORD
die "PostgreSQL dump failed"
fi
unset PGPASSWORD
@@ -323,115 +347,55 @@ backup_database() {
export MYSQL_PWD="${DB_PASS}"
if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then
unset MYSQL_PWD
die "MariaDB/MySQL dump failed"
fi
unset MYSQL_PWD
fi
# Compress the dump
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})"
# 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() {
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="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}"
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,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}"
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() {
@@ -474,15 +438,15 @@ Nextcloud 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} on ${DB_HOST}:${DB_PORT} as ${DB_USER}
Backup Contents:
- database/nextcloud_${TIMESTAMP}.sql.gz - Full database dump
- database/nextcloud_schema_${TIMESTAMP}.sql.gz - Schema only
- data/ - Nextcloud data directory (user files)
- config/ - Nextcloud config directory (config.php)
- apps/ - Nextcloud custom apps (if separate PVC)
- manifests/ - Kubernetes resource definitions
- apps/ - Nextcloud custom apps (if separate path)
To restore to Docker:
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
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
success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt"
@@ -520,24 +489,21 @@ EOF
main() {
info "======================================"
info "Nextcloud TrueNAS App Backup Started"
info "Nextcloud 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
enable_maintenance_mode
backup_manifests
backup_database
backup_pvc "${PVC_DATA}" "data" "Data directory"
backup_pvc "${PVC_CONFIG}" "config" "Configuration"
backup_pvc "${PVC_APPS}" "apps" "Custom apps"
backup_directory "${NEXTCLOUD_DATA_PATH}" "data" "Data directory"
backup_directory "${NEXTCLOUD_CONFIG_PATH}" "config" "Configuration"
backup_directory "${NEXTCLOUD_APPS_PATH}" "apps" "Custom apps"
disable_maintenance_mode
local archive=$(create_archive)