#!/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] [--no-ui] [-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 NO_UI=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=() UI_ACTIVE=0 UI_NAMES=() UI_PID="" STATUS_DIR="" MAIN_LOG="/dev/null" CUR_NAS=""; CUR_SHARE=""; CUR_POS="" usage() { grep '^#' "$0" | sed -n '2,20p' | sed 's/^# \{0,1\}//' exit 1 } log() { local m m="$(printf '[%s] %s' "$(date '+%Y-%m-%d %H:%M:%S')" "$*")" if [ "$UI_ACTIVE" -eq 1 ]; then echo "$m" >> "$MAIN_LOG"; else echo "$m"; fi } die() { UI_ACTIVE=0; 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 [ -n "$UI_PID" ] && kill "$UI_PID" 2>/dev/null || true [ -n "$STATUS_DIR" ] && rm -rf "$STATUS_DIR" } 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 unless the dashboard is running (needs a terminal, no dry-run). if [ "$UI_ACTIVE" -ne 1 ]; then rsync "${flags[@]}" --info=progress2 "$src" "$dst" 2>&1 | tee -a "$logfile" return fi # Size scan runs alongside the transfer so large shares start copying right away. local totfile="${STATUS_DIR}/${CUR_NAS}.total" scan_pid rm -f "$totfile" ( rsync "${flags[@]}" --dry-run --stats "$src" "$dst" 2>/dev/null "${totfile}.tmp" \ && mv -f "${totfile}.tmp" "$totfile" ) & scan_pid=$! echo copying > "${STATUS_DIR}/${CUR_NAS}.state" local rc=0 rsync "${flags[@]}" --progress "$src" "$dst" 2>&1 | progress_ui "$totfile" "$logfile" || rc=$? kill_tree "$scan_pid" wait "$scan_pid" 2>/dev/null || true return "$rc" } # Parses rsync --progress output and writes the NAS status file the dashboard reads. progress_ui() { local totfile="$1" logfile="$2" awk -v totfile="$totfile" -v logf="$logfile" -v sf="${STATUS_DIR}/${CUR_NAS}.status" \ -v share="$CUR_SHARE" -v pos="$CUR_POS" ' 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 render( tp, tmp, n, line) { if (total == 0 && (getline line < totfile) > 0) total = line + 0 close(totfile) tp = (total > 0) ? (done + curb) * 100 / total : 0 n = name; gsub(/\|/, "/", n) tmp = sf ".tmp" printf "%s|%s|%d|%s|%d|%s|%s|%d|%s\n", share, pos, cp, rate, tp, human(done + curb), (total > 0 ? human(total) : "sizing..."), files, n > tmp close(tmp) system("mv -f \047" tmp "\047 \047" sf "\047") } BEGIN { RS = "[\r\n]"; render() } /^[ \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 && (getline line < totfile) > 0) total = line + 0; if (total > 0) { done = total; curb = 0 } cp = 100; render() } ' } ui_bar() { local p="$1" w=30 n i s="" [ "$p" -gt 100 ] && p=100 n=$((p * w / 100)) for ((i = 0; i < w; i++)); do [ "$i" -lt "$n" ] && s+="#" || s+="-"; done printf '[%s]' "$s" } # Draws one 4-line block per NAS, overwriting the previous frame. render_dashboard() { local nm share pos cp rate tp dn total files fname st cols cols="$(tput cols 2>/dev/null || echo 80)" printf '\033[%dA' "$(( ${#UI_NAMES[@]} * 4 ))" for nm in "${UI_NAMES[@]}"; do share="-"; pos=""; cp=0; rate=""; tp=0; dn="0.0B"; total="0.0B"; files=0; fname=""; st="waiting" [ -f "${STATUS_DIR}/${nm}.status" ] \ && { IFS='|' read -r share pos cp rate tp dn total files fname < "${STATUS_DIR}/${nm}.status" || true; } [ -f "${STATUS_DIR}/${nm}.state" ] && st="$(cat "${STATUS_DIR}/${nm}.state")" printf '\033[2K\r\033[1m%s\033[0m share %s %s (%s)\n' "$nm" "$share" "$pos" "$st" printf '\033[2K File %s %3d%% %s\n' "$(ui_bar "${cp:-0}")" "${cp:-0}" "$rate" printf '\033[2K Total %s %3d%% %s / %s, %s files\n' "$(ui_bar "${tp:-0}")" "${tp:-0}" "$dn" "$total" "${files:-0}" printf '\033[2K > %s\n' "${fname:0:$((cols - 6))}" done } dashboard_loop() { while :; do render_dashboard; sleep 1; done } # ---------- 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; } local _i=0 for share in "${shares[@]}"; do [ "$LIST_ONLY" -eq 1 ] && { log "[$name] share: $share"; continue; } _i=$((_i + 1)); CUR_SHARE="$share"; CUR_POS="${_i}/${#shares[@]}" 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 local _i=0 for share in "${shares[@]}"; do [ "$LIST_ONLY" -eq 1 ] && { log "[$name] share: $share"; continue; } _i=$((_i + 1)); CUR_SHARE="$share"; CUR_POS="${_i}/${#shares[@]}" 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 local _i=0 for share in "${shares[@]}"; do [ "$LIST_ONLY" -eq 1 ] && { log "[$name] share: $share"; continue; } _i=$((_i + 1)); CUR_SHARE="$share"; CUR_POS="${_i}/${#shares[@]}" 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 ;; --no-ui) NO_UI=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" # Dashboard needs a terminal, no dry/list run, and no interactive SMB password prompt. if [ -t 1 ] && [ "$NO_UI" -eq 0 ] && [ "$DRY_RUN" -eq 0 ] && [ "$LIST_ONLY" -eq 0 ]; then ui_ok=1 while IFS= read -r -u 4 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 [ "$method" = "smb" ] && [ "$auth" = "-" ] && ui_ok=0 UI_NAMES+=("$name") done 4< "$CONFIG_FILE" if [ "$ui_ok" -eq 1 ] && [ "${#UI_NAMES[@]}" -gt 0 ]; then STATUS_DIR="$(mktemp -d)" MAIN_LOG="${LOG_DIR}/migrate.log" UI_ACTIVE=1 for _ in "${UI_NAMES[@]}"; do printf '\n\n\n\n'; done dashboard_loop & UI_PID=$! fi fi running=0 JOB_PIDS=() 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 ( CUR_NAS="$name" 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 [ "$UI_ACTIVE" -eq 1 ] && echo finished > "${STATUS_DIR}/${name}.state" ) & JOB_PIDS+=($!) running=$((running + 1)) if [ "$running" -ge "$JOBS" ]; then wait -n running=$((running - 1)) fi done 3< "$CONFIG_FILE" for pid in "${JOB_PIDS[@]:-}"; do [ -n "$pid" ] && { wait "$pid" || true; } done if [ "$UI_ACTIVE" -eq 1 ]; then kill "$UI_PID" 2>/dev/null || true wait "$UI_PID" 2>/dev/null || true UI_PID="" render_dashboard UI_ACTIVE=0 fi log "Migration complete. Logs in $LOG_DIR"