#!/usr/bin/env bash # # migrate.sh - Copy all shares from one or more QNAP NAS devices to TrueNAS SCALE. # Run this script ON the TrueNAS box (as root) - it pulls data from each QNAP. # # Supports three transfer methods per NAS entry: # ssh - rsync over SSH directly against the QNAP (no mount needed, QNAP SSH service must be on) # smb - mounts the QNAP share over CIFS/SMB, then rsyncs locally # nfs - mounts the QNAP share over NFS, then rsyncs locally # # NAS devices + shares are declared in a config file (see nas_list.conf.example). # # Usage: # ./migrate.sh [--config FILE] [--dest DIR] [--only NAME] [--jobs N] # [--dry-run] [--list-only] [-h|--help] # set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" CONFIG_FILE="${SCRIPT_DIR}/nas_list.conf" DEST_ROOT="/mnt/stor0/qnap" ONLY_NAME="" JOBS=1 DRY_RUN=0 LIST_ONLY=0 # QNAP system/internal folders that must never be copied or treated as real shares. SYSTEM_SHARE_EXCLUDES=( ".system" ".system_trash" ".qsync_trash" ".@__thumb" ".@__thumb_mobile" "@Recycle" ".@Recycle" "@Recently-Snapshot" "@Transcode" ".streams" ".acronis_mms" "Usage" "Network Recycle Bin" "homes" ) # Junk left inside shares themselves, excluded from every rsync transfer. RSYNC_EXCLUDES=( "@Recycle/" ".@__thumb/" ".@__thumb_mobile/" "@Transcode/" ".streams/" ".qsync_trash/" "Thumbs.db" ".DS_Store" "lost+found/" ) MOUNTED_POINTS=() SSH_CONTROL_PATHS=() usage() { grep '^#' "$0" | sed -n '2,20p' | sed 's/^# \{0,1\}//' exit 1 } log() { printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"; } die() { log "ERROR: $*" >&2; exit 1; } cleanup() { for mp in "${MOUNTED_POINTS[@]:-}"; do [ -n "$mp" ] || continue umount "$mp" 2>/dev/null || umount -l "$mp" 2>/dev/null || true rmdir "$mp" 2>/dev/null || true done close_ssh_mux } trap cleanup EXIT kill_tree() { local pid="$1" c for c in $(pgrep -P "$pid" 2>/dev/null); do kill_tree "$c"; done kill -TERM "$pid" 2>/dev/null || true } # Background jobs ignore SIGINT, so stop every descendant (rsync, ssh, smbclient) explicitly. on_interrupt() { trap - INT TERM log "Interrupted, stopping all transfers..." local c for c in $(pgrep -P $$ 2>/dev/null); do kill_tree "$c"; done wait 2>/dev/null || true exit 130 } trap on_interrupt INT TERM is_system_share() { local share="$1" s for s in "${SYSTEM_SHARE_EXCLUDES[@]}"; do [ "$share" = "$s" ] && return 0 done return 1 } rsync_exclude_args() { local a=() local e for e in "${RSYNC_EXCLUDES[@]}"; do a+=(--exclude="$e"); done printf '%s\n' "${a[@]}" } run_rsync() { # run_rsync [ssh command] local src="$1" dst="$2" logfile="$3" ssh_cmd="${4:-}" mkdir -p "$dst" local -a excludes=() mapfile -t excludes < <(rsync_exclude_args) local -a flags=(-aAXH --partial "${excludes[@]}") [ -n "$ssh_cmd" ] && flags+=(-e "$ssh_cmd") [ "$DRY_RUN" -eq 1 ] && flags+=(--dry-run) log "rsync: $src -> $dst" # Plain output when not on a terminal, parallel jobs share the screen, or dry-run. if [ ! -t 1 ] || [ "$JOBS" -gt 1 ] || [ "$DRY_RUN" -eq 1 ]; then rsync "${flags[@]}" --info=progress2 "$src" "$dst" 2>&1 | tee -a "$logfile" return fi log "scanning $src ..." local total_bytes total_bytes="$(rsync "${flags[@]}" --dry-run --stats "$src" "$dst" 2>/dev/null \ | awk -F': ' '/^Total transferred file size/{gsub(/[^0-9]/,"",$2); print $2}')" total_bytes="${total_bytes:-0}" rsync "${flags[@]}" --progress "$src" "$dst" 2>&1 | progress_ui "$total_bytes" "$logfile" } # Reads rsync --progress output; draws current-file bar, total bar and the rolling filename. progress_ui() { local total="$1" logfile="$2" cols cols="$(tput cols 2>/dev/null || echo 80)" awk -v total="$total" -v logf="$logfile" -v cols="$cols" ' function human(b, u, i) { split("B KB MB GB TB", u, " "); i = 1 while (b >= 1024 && i < 5) { b /= 1024; i++ } return sprintf("%.1f%s", b, u[i]) } function bar(p, w, n, s, i) { if (p > 100) p = 100 n = int(p * w / 100); s = "" for (i = 0; i < w; i++) s = s (i < n ? "#" : "-") return "[" s "]" } function render( tp, shown) { tp = (total > 0) ? (done + curb) * 100 / total : 0 shown = substr(name, 1, cols - 4) printf "\033[3A\r\033[2K File %s %3d%% %s\n", bar(cp, 30), cp, rate printf "\033[2K Total %s %3d%% %s / %s, %d files\n", bar(tp, 30), tp, human(done + curb), human(total), files printf "\033[2K > %s\n", shown } BEGIN { RS = "[\r\n]"; printf "\n\n\n" } /^[ \t]+[0-9,]+[ \t]+[0-9]+%/ { b = $1; gsub(",", "", b); curb = b + 0; cp = $2 + 0; rate = $3 if (cp >= 100 && !counted) { done += curb; counted = 1; curb = 0 } render(); next } /^(sending|building|receiving|sent |total size|created)/ || $0 == "" { next } { name = $0; print name >> logf; counted = 0; curb = 0; cp = 0; files++; render() } END { if (total > 0) { done = total; curb = 0 } cp = 100; render() } ' } # ---------- SSH method ---------- # Shared connection options so every ssh/rsync call for a NAS reuses one # multiplexed master connection (avoids re-prompting for the key passphrase # on every share/directory instead of asking once per NAS). ssh_mux_opts() { local host="$1" user="$2" identity="$3" port="${4:-22}" local ctrl_path="/tmp/.ssh_mux_${user}@${host}:${port}" local -a opts=( -o StrictHostKeyChecking=accept-new -o BatchMode=yes -p "$port" -o ControlMaster=auto -o "ControlPath=${ctrl_path}" -o ControlPersist=10m ) [ "$identity" != "-" ] && opts+=(-i "$identity") SSH_CONTROL_PATHS+=("${ctrl_path}|${user}@${host}|${port}") printf '%s\n' "${opts[@]}" } close_ssh_mux() { local entry hostport port ctrl_path for entry in "${SSH_CONTROL_PATHS[@]:-}"; do [ -n "$entry" ] || continue IFS='|' read -r ctrl_path hostport port <<< "$entry" ssh -o ControlPath="$ctrl_path" -O exit "$hostport" -p "$port" 2>/dev/null || true done } discover_shares_ssh() { local host="$1" user="$2" identity="$3" port="22" local -a ssh_opts=() mapfile -t ssh_opts < <(ssh_mux_opts "$host" "$user" "$identity" "$port") ssh "${ssh_opts[@]}" "${user}@${host}" \ 'for d in /share/CACHEDEV*_DATA/*/; do b=$(basename "$d"); echo "$b"; done' 2>/dev/null \ | sort -u } sync_ssh() { local name="$1" host="$2" user="$3" identity="$4" shares_csv="$5" logdir="$6" local -a ssh_opts=() mapfile -t ssh_opts < <(ssh_mux_opts "$host" "$user" "$identity" 22) local ssh_cmd printf -v ssh_cmd '%q ' ssh "${ssh_opts[@]}" ssh_cmd="${ssh_cmd% }" local -a shares=() if [ "$shares_csv" = "ALL" ]; then while IFS= read -r s; do is_system_share "$s" || shares+=("$s") done < <(discover_shares_ssh "$host" "$user" "$identity") else IFS=',' read -r -a shares <<< "$shares_csv" fi [ "${#shares[@]}" -eq 0 ] && { log "[$name] no shares found/selected"; return; } for share in "${shares[@]}"; do [ "$LIST_ONLY" -eq 1 ] && { log "[$name] share: $share"; continue; } local dest="${DEST_ROOT}/${name}/${share}" local logfile="${logdir}/${name}_${share}.log" mkdir -p "$dest" run_rsync "${user}@${host}:/share/CACHEDEV*_DATA/${share}/" "${dest}/" "$logfile" "$ssh_cmd" \ || log "[$name/$share] rsync reported errors (see $logfile)" done } # ---------- SMB method ---------- discover_shares_smb() { local host="$1" credsopt="$2" smbclient -L "//${host}" "$credsopt" -g 2>/dev/null \ | awk -F'|' '$1=="Disk"{print $2}' \ | grep -Ev '^(IPC\$|ADMIN\$|print\$)$' } smb_creds_opt() { # Prints the smbclient/mount.cifs auth option(s), prompting if needed. local creds_path="$1" if [ "$creds_path" != "-" ]; then echo "credentials=${creds_path}" else echo "__PROMPT__" fi } sync_smb() { local name="$1" host="$2" user="$3" creds="$4" shares_csv="$5" logdir="$6" local creds_file="$creds" local tmp_creds="" if [ "$creds" = "-" ]; then read -r -p "SMB password for ${user}@${host}: " -s smb_pass; echo tmp_creds="$(mktemp)" printf 'username=%s\npassword=%s\n' "$user" "$smb_pass" > "$tmp_creds" chmod 600 "$tmp_creds" creds_file="$tmp_creds" fi local -a shares=() if [ "$shares_csv" = "ALL" ]; then while IFS= read -r s; do is_system_share "$s" || shares+=("$s") done < <(discover_shares_smb "$host" "-A${creds_file}") else IFS=',' read -r -a shares <<< "$shares_csv" fi for share in "${shares[@]}"; do [ "$LIST_ONLY" -eq 1 ] && { log "[$name] share: $share"; continue; } local mountpoint; mountpoint="$(mktemp -d "/mnt/.qnap_${name}_XXXXXX")" MOUNTED_POINTS+=("$mountpoint") if ! mount -t cifs "//${host}/${share}" "$mountpoint" \ -o "credentials=${creds_file},vers=3.0,ro,iocharset=utf8"; then log "[$name/$share] mount failed, skipping" rmdir "$mountpoint" 2>/dev/null || true continue fi local dest="${DEST_ROOT}/${name}/${share}" local logfile="${logdir}/${name}_${share}.log" run_rsync "${mountpoint}/" "${dest}/" "$logfile" \ || log "[$name/$share] rsync reported errors (see $logfile)" umount "$mountpoint" || umount -l "$mountpoint" || true rmdir "$mountpoint" 2>/dev/null || true MOUNTED_POINTS=("${MOUNTED_POINTS[@]/$mountpoint}") done [ -n "$tmp_creds" ] && shred -u "$tmp_creds" 2>/dev/null || rm -f "$tmp_creds" 2>/dev/null || true } # ---------- NFS method ---------- discover_shares_nfs() { local host="$1" showmount -e "$host" 2>/dev/null | tail -n +2 | awk '{print $1}' | xargs -n1 basename } sync_nfs() { local name="$1" host="$2" shares_csv="$3" logdir="$4" local -a shares=() if [ "$shares_csv" = "ALL" ]; then while IFS= read -r s; do is_system_share "$s" || shares+=("$s") done < <(discover_shares_nfs "$host") else IFS=',' read -r -a shares <<< "$shares_csv" fi for share in "${shares[@]}"; do [ "$LIST_ONLY" -eq 1 ] && { log "[$name] share: $share"; continue; } local mountpoint; mountpoint="$(mktemp -d "/mnt/.qnap_${name}_XXXXXX")" MOUNTED_POINTS+=("$mountpoint") if ! mount -t nfs -o ro "${host}:/share/${share}" "$mountpoint" 2>/dev/null \ && ! mount -t nfs -o ro "${host}:${share}" "$mountpoint"; then log "[$name/$share] mount failed, skipping" rmdir "$mountpoint" 2>/dev/null || true continue fi local dest="${DEST_ROOT}/${name}/${share}" local logfile="${logdir}/${name}_${share}.log" run_rsync "${mountpoint}/" "${dest}/" "$logfile" \ || log "[$name/$share] rsync reported errors (see $logfile)" umount "$mountpoint" || umount -l "$mountpoint" || true rmdir "$mountpoint" 2>/dev/null || true MOUNTED_POINTS=("${MOUNTED_POINTS[@]/$mountpoint}") done } # ---------- arg parsing ---------- while [ $# -gt 0 ]; do case "$1" in --config) CONFIG_FILE="$2"; shift 2 ;; --dest) DEST_ROOT="$2"; shift 2 ;; --only) ONLY_NAME="$2"; shift 2 ;; --jobs) JOBS="$2"; shift 2 ;; --dry-run) DRY_RUN=1; shift ;; --list-only) LIST_ONLY=1; shift ;; -h|--help) usage ;; *) die "unknown argument: $1" ;; esac done [ "$(id -u)" -eq 0 ] || die "must run as root (needed for mount/umount)" [ -f "$CONFIG_FILE" ] || die "config file not found: $CONFIG_FILE (copy nas_list.conf.example)" command -v rsync >/dev/null || die "rsync not found" LOG_DIR="${DEST_ROOT}/_logs" mkdir -p "$LOG_DIR" "$DEST_ROOT" log "Starting migration. dest=$DEST_ROOT dry_run=$DRY_RUN list_only=$LIST_ONLY" running=0 while IFS= read -r -u 3 line || [ -n "$line" ]; do line="${line%%#*}" line="${line//$'\r'/}" [ -z "${line// /}" ] && continue read -r name method host user auth shares <<< "$line" [ -n "$name" ] || continue [ -n "$ONLY_NAME" ] && [ "$ONLY_NAME" != "$name" ] && continue ( case "$method" in ssh) sync_ssh "$name" "$host" "$user" "$auth" "$shares" "$LOG_DIR" ;; smb) sync_smb "$name" "$host" "$user" "$auth" "$shares" "$LOG_DIR" ;; nfs) sync_nfs "$name" "$host" "$shares" "$LOG_DIR" ;; *) log "[$name] unknown method '$method', skipping" ;; esac ) & running=$((running + 1)) if [ "$running" -ge "$JOBS" ]; then wait -n running=$((running - 1)) fi done 3< "$CONFIG_FILE" wait log "Migration complete. Logs in $LOG_DIR"