diff --git a/README.md b/README.md index 4e90376..2070202 100644 --- a/README.md +++ b/README.md @@ -71,13 +71,20 @@ The SSH method reuses one multiplexed connection per NAS, so a key passphrase is | `--config FILE`| Use a different NAS list (default `./nas_list.conf`) | | `--dest DIR` | Destination root (default `/mnt/stor0/qnap`) | | `--only NAME` | Only process one NAS entry by name | -| `--jobs N` | Number of NAS devices to process in parallel (default 1) | -| `--dry-run` | Pass `--dry-run` to rsync, no changes made | +| `--jobs N` | Number of NAS devices to process in parallel (default 1) | +| `--retries N` | Retries after a failed network operation (default 3) | +| `--retry-delay SEC` | Seconds between retries (default 5) | +| `--dry-run` | Pass `--dry-run` to rsync, no changes made | | `--list-only` | Only discover and print shares, don't transfer | | `--no-ui` | Disable the progress dashboard, use plain rsync output | -QNAP system folders (`@Recycle`, `.@__thumb`, `.system`, snapshots, etc.) are skipped automatically. -Re-running the script is safe/idempotent — rsync only copies new or changed files. +QNAP system folders (`@Recycle`, `.@__thumb`, `.system`, snapshots, etc.) are skipped automatically. +Network discovery, mounts, and each rsync transfer are retried (three retries by default); SSH +connections also use keepalives and timeouts. Interrupted file data is kept in rsync's +`.rsync-partial` directories. If all retries fail, the script exits with an error but retains +completed files and partial data. Fix the connection and run the script again: rsync skips files +that already match and resumes/re-copies incomplete or changed files. Per-share logs identify +transfers that still need attention. If the files were edited on Windows, strip CRLF line endings on TrueNAS before running: `sed -i 's/\r$//' migrate.sh generate_ssh_keys.sh nas_list.conf` diff --git a/migrate.sh b/migrate.sh index 487ccb4..cc1022a 100644 --- a/migrate.sh +++ b/migrate.sh @@ -12,6 +12,7 @@ # # Usage: # ./migrate.sh [--config FILE] [--dest DIR] [--only NAME] [--jobs N] +# [--retries N] [--retry-delay SEC] # [--dry-run] [--list-only] [--no-ui] [-h|--help] # set -euo pipefail @@ -22,6 +23,8 @@ CONFIG_FILE="${SCRIPT_DIR}/nas_list.conf" DEST_ROOT="/mnt/stor0/qnap" ONLY_NAME="" JOBS=1 +RETRIES=3 +RETRY_DELAY=5 DRY_RUN=0 LIST_ONLY=0 NO_UI=0 @@ -109,32 +112,54 @@ run_rsync() { mkdir -p "$dst" local -a excludes=() mapfile -t excludes < <(rsync_exclude_args) - local -a flags=(-aAXH --partial "${excludes[@]}") + # Keep interrupted data out of the destination tree. rsync will use these + # files as a basis on the next attempt or a later invocation of this script. + local -a flags=(-aAXH --partial --partial-dir=.rsync-partial --timeout=60 "${excludes[@]}") [ -n "$ssh_cmd" ] && flags+=(-e "$ssh_cmd") [ "$DRY_RUN" -eq 1 ] && flags+=(--dry-run) - log "rsync: $src -> $dst" + local attempt=1 max_attempts=$((RETRIES + 1)) rc=0 + local totfile scan_pid - # 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 + while [ "$attempt" -le "$max_attempts" ]; do + log "rsync (attempt ${attempt}/${max_attempts}): $src -> $dst" - # 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" + # Plain output unless the dashboard is running (needs a terminal, no dry-run). + if [ "$UI_ACTIVE" -ne 1 ]; then + if rsync "${flags[@]}" --info=progress2 "$src" "$dst" 2>&1 | tee -a "$logfile"; then + return 0 + else + rc=$? + fi + else + # Size scan runs alongside the transfer so large shares start copying right away. + totfile="${STATUS_DIR}/${CUR_NAS}.total" + 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 + if rsync "${flags[@]}" --progress "$src" "$dst" 2>&1 | progress_ui "$totfile" "$logfile"; then + rc=0 + else + rc=$? + fi + kill_tree "$scan_pid" + wait "$scan_pid" 2>/dev/null || true + [ "$rc" -eq 0 ] && return 0 + fi + + if [ "$attempt" -lt "$max_attempts" ]; then + log "rsync failed with exit code $rc; retrying in ${RETRY_DELAY}s (partial files are kept)" + sleep "$RETRY_DELAY" + fi + attempt=$((attempt + 1)) + done + + log "rsync failed after ${max_attempts} attempts (exit code $rc)" return "$rc" } @@ -170,6 +195,23 @@ progress_ui() { ' } +# Retry short network operations (share discovery and remote mounts) as well as +# rsync transfers. Arguments after the label are executed as a command. +retry_command() { + local label="$1"; shift + local attempt=1 max_attempts=$((RETRIES + 1)) rc=0 + while [ "$attempt" -le "$max_attempts" ]; do + if "$@"; then return 0; else rc=$?; fi + if [ "$attempt" -lt "$max_attempts" ]; then + log "$label failed (attempt ${attempt}/${max_attempts}); retrying in ${RETRY_DELAY}s" >&2 + sleep "$RETRY_DELAY" + fi + attempt=$((attempt + 1)) + done + log "$label failed after ${max_attempts} attempts (exit code $rc)" >&2 + return "$rc" +} + ui_bar() { local p="$1" w=30 n i s="" [ "$p" -gt 100 ] && p=100 @@ -208,7 +250,8 @@ 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 StrictHostKeyChecking=accept-new -o BatchMode=yes -o ConnectTimeout=15 + -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -p "$port" -o ControlMaster=auto -o "ControlPath=${ctrl_path}" -o ControlPersist=10m ) [ "$identity" != "-" ] && opts+=(-i "$identity") @@ -243,10 +286,15 @@ sync_ssh() { ssh_cmd="${ssh_cmd% }" local -a shares=() + local failures=0 if [ "$shares_csv" = "ALL" ]; then + local discovered + if ! discovered="$(retry_command "[$name] SSH share discovery" discover_shares_ssh "$host" "$user" "$identity")"; then + return 1 + fi while IFS= read -r s; do is_system_share "$s" || shares+=("$s") - done < <(discover_shares_ssh "$host" "$user" "$identity") + done <<< "$discovered" else IFS=',' read -r -a shares <<< "$shares_csv" fi @@ -261,17 +309,19 @@ sync_ssh() { 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)" + || { log "[$name/$share] rsync failed (see $logfile)"; failures=$((failures + 1)); } done + [ "$failures" -eq 0 ] } # ---------- 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\$)$' + local output + output="$(smbclient -L "//${host}" "$credsopt" -g 2>/dev/null)" || return $? + printf '%s\n' "$output" \ + | awk -F'|' '$1=="Disk" && $2 !~ /^(IPC\$|ADMIN\$|print\$)$/ {print $2}' } smb_creds_opt() { @@ -298,10 +348,16 @@ sync_smb() { fi local -a shares=() + local failures=0 if [ "$shares_csv" = "ALL" ]; then + local discovered + if ! discovered="$(retry_command "[$name] SMB share discovery" discover_shares_smb "$host" "-A${creds_file}")"; then + [ -n "$tmp_creds" ] && shred -u "$tmp_creds" 2>/dev/null || rm -f "$tmp_creds" 2>/dev/null || true + return 1 + fi while IFS= read -r s; do is_system_share "$s" || shares+=("$s") - done < <(discover_shares_smb "$host" "-A${creds_file}") + done <<< "$discovered" else IFS=',' read -r -a shares <<< "$shares_csv" fi @@ -312,38 +368,53 @@ sync_smb() { _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" \ + if ! retry_command "[$name/$share] SMB mount" mount -t cifs "//${host}/${share}" "$mountpoint" \ -o "credentials=${creds_file},vers=3.0,ro,iocharset=utf8"; then log "[$name/$share] mount failed, skipping" + failures=$((failures + 1)) 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)" + || { log "[$name/$share] rsync failed (see $logfile)"; failures=$((failures + 1)); } 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 + [ "$failures" -eq 0 ] } # ---------- NFS method ---------- discover_shares_nfs() { local host="$1" - showmount -e "$host" 2>/dev/null | tail -n +2 | awk '{print $1}' | xargs -n1 basename + local exports + exports="$(showmount -e "$host" 2>/dev/null)" || return $? + printf '%s\n' "$exports" | tail -n +2 | awk '{n=$1; sub(/^.*\//,"",n); if (n != "") print n}' +} + +mount_nfs_share() { + local host="$1" share="$2" mountpoint="$3" + mount -t nfs -o ro "${host}:/share/${share}" "$mountpoint" 2>/dev/null \ + || mount -t nfs -o ro "${host}:${share}" "$mountpoint" } sync_nfs() { local name="$1" host="$2" shares_csv="$3" logdir="$4" local -a shares=() + local failures=0 if [ "$shares_csv" = "ALL" ]; then + local discovered + if ! discovered="$(retry_command "[$name] NFS share discovery" discover_shares_nfs "$host")"; then + return 1 + fi while IFS= read -r s; do is_system_share "$s" || shares+=("$s") - done < <(discover_shares_nfs "$host") + done <<< "$discovered" else IFS=',' read -r -a shares <<< "$shares_csv" fi @@ -354,20 +425,21 @@ sync_nfs() { _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 + if ! retry_command "[$name/$share] NFS mount" mount_nfs_share "$host" "$share" "$mountpoint"; then log "[$name/$share] mount failed, skipping" + failures=$((failures + 1)) 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)" + || { log "[$name/$share] rsync failed (see $logfile)"; failures=$((failures + 1)); } umount "$mountpoint" || umount -l "$mountpoint" || true rmdir "$mountpoint" 2>/dev/null || true MOUNTED_POINTS=("${MOUNTED_POINTS[@]/$mountpoint}") done + [ "$failures" -eq 0 ] } # ---------- arg parsing ---------- @@ -378,6 +450,8 @@ while [ $# -gt 0 ]; do --dest) DEST_ROOT="$2"; shift 2 ;; --only) ONLY_NAME="$2"; shift 2 ;; --jobs) JOBS="$2"; shift 2 ;; + --retries) RETRIES="$2"; shift 2 ;; + --retry-delay) RETRY_DELAY="$2"; shift 2 ;; --dry-run) DRY_RUN=1; shift ;; --list-only) LIST_ONLY=1; shift ;; --no-ui) NO_UI=1; shift ;; @@ -386,6 +460,10 @@ while [ $# -gt 0 ]; do esac done +[[ "$JOBS" =~ ^[1-9][0-9]*$ ]] || die "--jobs must be a positive integer" +[[ "$RETRIES" =~ ^[0-9]+$ ]] || die "--retries must be a non-negative integer" +[[ "$RETRY_DELAY" =~ ^[0-9]+$ ]] || die "--retry-delay must be a non-negative integer" + [ "$(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" @@ -418,7 +496,7 @@ if [ -t 1 ] && [ "$NO_UI" -eq 0 ] && [ "$DRY_RUN" -eq 0 ] && [ "$LIST_ONLY" -eq fi running=0 -JOB_PIDS=() +migration_failed=0 while IFS= read -r -u 3 line || [ -n "$line" ]; do line="${line%%#*}" line="${line//$'\r'/}" @@ -429,25 +507,29 @@ while IFS= read -r -u 3 line || [ -n "$line" ]; do ( CUR_NAS="$name" + rc=0 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" ;; + ssh) sync_ssh "$name" "$host" "$user" "$auth" "$shares" "$LOG_DIR" || rc=$? ;; + smb) sync_smb "$name" "$host" "$user" "$auth" "$shares" "$LOG_DIR" || rc=$? ;; + nfs) sync_nfs "$name" "$host" "$shares" "$LOG_DIR" || rc=$? ;; + *) log "[$name] unknown method '$method', skipping"; rc=1 ;; esac - [ "$UI_ACTIVE" -eq 1 ] && echo finished > "${STATUS_DIR}/${name}.state" + if [ "$UI_ACTIVE" -eq 1 ]; then + if [ "$rc" -eq 0 ]; then echo finished > "${STATUS_DIR}/${name}.state"; else echo failed > "${STATUS_DIR}/${name}.state"; fi + fi + exit "$rc" ) & - JOB_PIDS+=($!) running=$((running + 1)) if [ "$running" -ge "$JOBS" ]; then - wait -n + wait -n || migration_failed=1 running=$((running - 1)) fi done 3< "$CONFIG_FILE" -for pid in "${JOB_PIDS[@]:-}"; do - [ -n "$pid" ] && { wait "$pid" || true; } +while [ "$running" -gt 0 ]; do + wait -n || migration_failed=1 + running=$((running - 1)) done if [ "$UI_ACTIVE" -eq 1 ]; then @@ -457,4 +539,8 @@ if [ "$UI_ACTIVE" -eq 1 ]; then render_dashboard UI_ACTIVE=0 fi +if [ "$migration_failed" -ne 0 ]; then + log "ERROR: one or more NAS transfers failed. Fix the connection and rerun; completed files will be skipped and partial files resumed." + exit 1 +fi log "Migration complete. Logs in $LOG_DIR"