diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 index 3829610..0000000 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,93 +0,0 @@ -# Cross-compile static binaries (CGO_ENABLED=0, same as `make build`). -# -# Push and pull requests to main upload three Actions artifacts: -# migration-linux-amd64 -# migration-linux-arm64 -# migration-windows-amd64.exe -# A tag v* also attaches those files to the GitHub Release for that tag. - -name: build - -on: - push: - branches: [main] - tags: ["v*"] - pull_request: - branches: [main] - -permissions: - contents: read - -jobs: - build: - name: ${{ matrix.artifact }} - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - include: - - goos: linux - goarch: amd64 - artifact: migration-linux-amd64 - - goos: linux - goarch: arm64 - artifact: migration-linux-arm64 - - goos: windows - goarch: amd64 - artifact: migration-windows-amd64.exe - steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-go@v5 - with: - go-version-file: go.mod - cache: true - - - name: Build - env: - CGO_ENABLED: "0" - GOOS: ${{ matrix.goos }} - GOARCH: ${{ matrix.goarch }} - run: | - mkdir -p dist - go build -o "dist/${{ matrix.artifact }}" . - - - uses: actions/upload-artifact@v4 - with: - name: ${{ matrix.artifact }} - path: dist/${{ matrix.artifact }} - if-no-files-found: error - - release: - name: attach release binaries - if: startsWith(github.ref, 'refs/tags/v') - needs: build - runs-on: ubuntu-latest - permissions: - contents: write - steps: - - uses: actions/download-artifact@v4 - with: - path: dist - merge-multiple: true - - - name: Publish binaries to the GitHub Release - env: - GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - run: | - set -euo pipefail - shopt -s nullglob - files=(dist/*) - if [ "${#files[@]}" -eq 0 ]; then - echo "no binaries downloaded" >&2 - exit 1 - fi - ls -l dist - if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then - gh release upload "$GITHUB_REF_NAME" "${files[@]}" --clobber - else - gh release create "$GITHUB_REF_NAME" "${files[@]}" \ - --title "$GITHUB_REF_NAME" \ - --generate-notes - fi diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml new file mode 100644 index 0000000..0bba469 --- /dev/null +++ b/.github/workflows/ci-cd.yml @@ -0,0 +1,261 @@ +# Unified CI & CD pipeline: +# - CI: static checks, race-enabled unit/integration tests, Python tests, and MinIO -> RustFS E2E tests. +# - Package verification: builds and verifies Linux (amd64/arm64) binaries, .tar.gz archives, .deb and .rpm +# packages, plus Windows (amd64) .exe and .zip packages. +# - CD Release: on version tags (v* or X.Y*) or manual dispatch with release_tag, publishes all verified +# binaries, archives, DEB/RPM packages, and SHA256SUMS to GitHub Releases. + +name: CI/CD + +on: + push: + branches: [main] + tags: + - "v*" + - "[0-9]*.[0-9]*" + pull_request: + branches: [main] + workflow_dispatch: + inputs: + release_tag: + description: "Optional existing Git tag to publish/update a GitHub Release (leave empty for CI/package run only)" + required: false + default: "" + type: string + +permissions: + contents: read + +jobs: + ci-regression: + name: Regression & Race Tests + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ inputs.release_tag || '' }} + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version-file: go.mod + cache: true + - name: Run static analysis + run: go vet -tags real_s3 ./... + - name: Run Go race test suite + run: go test -race -count=1 ./... + - name: Run Python script unit tests + run: python3 -m unittest discover -s scripts -v + + ci-e2e: + name: E2E (MinIO to RustFS) + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ inputs.release_tag || '' }} + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version-file: go.mod + cache: true + - name: Run CLI against MinIO and RustFS containers + run: | + python3 -m venv "$RUNNER_TEMP/e2e" + "$RUNNER_TEMP/e2e/bin/pip" install boto3==1.42.97 + "$RUNNER_TEMP/e2e/bin/python" tests/e2e.py + + package-linux: + name: Package (${{ matrix.target }} bin/tar.gz/deb/rpm) + strategy: + fail-fast: false + matrix: + include: + - target: linux-amd64 + runner: ubuntu-24.04 + deb_arch: amd64 + rpm_arch: x86_64 + - target: linux-arm64 + runner: ubuntu-24.04-arm + deb_arch: arm64 + rpm_arch: aarch64 + runs-on: ${{ matrix.runner }} + timeout-minutes: 20 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ inputs.release_tag || '' }} + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version-file: go.mod + cache: true + - name: Exercise SQLite state store on ${{ matrix.target }} + run: go test -count=1 ./internal/store + - name: Install rpmbuild tooling + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends rpm + - name: Build binary, archive, DEB, and RPM packages + env: + MIGRATION_VERSION: ${{ inputs.release_tag || (github.ref_type == 'tag' && github.ref_name || '') }} + run: python3 scripts/package.py "${{ matrix.target }}" dist --linux-packages + - name: Verify checksums, binary, archive, DEB install, and RPM metadata + run: | + set -euo pipefail + cd dist + ls -lh + sha256sum -c *.sha256 + + # Verify standalone binary + ./migration-${{ matrix.target }} --version + + # Verify .tar.gz binary package + mkdir -p verify-tar + tar -xzf "migration-${{ matrix.target }}.tar.gz" -C verify-tar + ./verify-tar/migration --version + rm -rf verify-tar + + # Verify .deb package installation and removal + deb_file=(rustfs-migration_*_${{ matrix.deb_arch }}.deb) + test -f "${deb_file[0]}" + dpkg-deb --info "${deb_file[0]}" + sudo dpkg -i "${deb_file[0]}" + /usr/bin/migration --version + test -f /etc/rustfs-migration/config.example.yaml + sudo dpkg -r rustfs-migration + + # Verify .rpm package metadata and file list + rpm_file=(rustfs-migration-*.${{ matrix.rpm_arch }}.rpm) + test -f "${rpm_file[0]}" + rpm -qip "${rpm_file[0]}" + rpm -qlp "${rpm_file[0]}" | grep -qx '/usr/bin/migration' + rpm -qlp "${rpm_file[0]}" | grep -qx '/etc/rustfs-migration/config.example.yaml' + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: packages-${{ matrix.target }} + path: | + dist/migration-${{ matrix.target }} + dist/migration-${{ matrix.target }}.tar.gz + dist/rustfs-migration_*_${{ matrix.deb_arch }}.deb + dist/rustfs-migration-*.${{ matrix.rpm_arch }}.rpm + dist/*.sha256 + if-no-files-found: error + compression-level: 0 + + package-windows: + name: Package (windows-amd64 exe/zip) + runs-on: windows-2025 + timeout-minutes: 20 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ inputs.release_tag || '' }} + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version-file: go.mod + cache: true + - name: Exercise SQLite state store on windows-amd64 + run: go test -count=1 ./internal/store + - name: Build Windows executable and zip package + env: + MIGRATION_VERSION: ${{ inputs.release_tag || (github.ref_type == 'tag' && github.ref_name || '') }} + run: python scripts/package.py windows-amd64 dist + - name: Verify checksums, standalone exe, and zip package + shell: bash + run: | + set -euo pipefail + cd dist + ls -lh + sha256sum -c *.sha256 + ./migration-windows-amd64.exe --version + mkdir -p verify-zip + unzip -q migration-windows-amd64.zip -d verify-zip + ./verify-zip/migration.exe --version + rm -rf verify-zip + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: packages-windows-amd64 + path: | + dist/migration-windows-amd64.exe + dist/migration-windows-amd64.zip + dist/*.sha256 + if-no-files-found: error + compression-level: 0 + + cd-release: + name: Publish GitHub Release + if: startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.release_tag != '') + needs: [ci-regression, ci-e2e, package-linux, package-windows] + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: write + steps: + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + path: release-assets + merge-multiple: true + - name: Verify complete asset set and publish GitHub Release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TARGET_TAG: ${{ inputs.release_tag || github.ref_name }} + run: | + set -euo pipefail + shopt -s nullglob + cd release-assets + + # Ensure every required deliverable is present before publishing + test -f migration-linux-amd64 + test -f migration-linux-amd64.tar.gz + test -f migration-linux-arm64 + test -f migration-linux-arm64.tar.gz + test -f migration-windows-amd64.exe + test -f migration-windows-amd64.zip + + deb_amd64=(rustfs-migration_*_amd64.deb) + deb_arm64=(rustfs-migration_*_arm64.deb) + rpm_amd64=(rustfs-migration-*.x86_64.rpm) + rpm_arm64=(rustfs-migration-*.aarch64.rpm) + test -f "${deb_amd64[0]}" + test -f "${deb_arm64[0]}" + test -f "${rpm_amd64[0]}" + test -f "${rpm_arm64[0]}" + + sha256sum -c *.sha256 + sha256sum \ + migration-linux-amd64 \ + migration-linux-amd64.tar.gz \ + "${deb_amd64[0]}" \ + "${rpm_amd64[0]}" \ + migration-linux-arm64 \ + migration-linux-arm64.tar.gz \ + "${deb_arm64[0]}" \ + "${rpm_arm64[0]}" \ + migration-windows-amd64.exe \ + migration-windows-amd64.zip \ + > SHA256SUMS + sha256sum -c SHA256SUMS + + files=( + migration-linux-amd64 + migration-linux-amd64.tar.gz + "${deb_amd64[0]}" + "${rpm_amd64[0]}" + migration-linux-arm64 + migration-linux-arm64.tar.gz + "${deb_arm64[0]}" + "${rpm_arm64[0]}" + migration-windows-amd64.exe + migration-windows-amd64.zip + SHA256SUMS + *.sha256 + ) + ls -lh "${files[@]}" + + if gh release view "$TARGET_TAG" >/dev/null 2>&1; then + gh release upload "$TARGET_TAG" "${files[@]}" --clobber + else + gh release create "$TARGET_TAG" "${files[@]}" \ + --title "$TARGET_TAG" \ + --generate-notes + fi diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml deleted file mode 100644 index e764b75..0000000 --- a/.github/workflows/packages.yml +++ /dev/null @@ -1,57 +0,0 @@ -name: Build packages - -on: - push: - branches: [main] - tags: ['v*'] - pull_request: - workflow_dispatch: - -permissions: - contents: read - -jobs: - build: - name: ${{ matrix.target }} - strategy: - fail-fast: false - matrix: - include: - - target: linux-amd64 - runner: ubuntu-24.04 - - target: linux-arm64 - runner: ubuntu-24.04-arm - - target: windows-amd64 - runner: windows-2025 - runs-on: ${{ matrix.runner }} - timeout-minutes: 20 - steps: - - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 - with: - go-version: stable - - name: Exercise the state database on this platform - run: go test -count=1 ./internal/store - - name: Build archive and checksum - run: python scripts/package.py ${{ matrix.target }} dist - - name: Verify and launch the packaged executable - shell: bash - run: | - cd dist - sha256sum -c *.sha256 - if [[ "$RUNNER_OS" == Windows ]]; then - unzip -q migration-*.zip - ./migration.exe --version - else - tar -xzf migration-*.tar.gz - ./migration --version - fi - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: migration-${{ matrix.target }} - path: | - dist/*.tar.gz - dist/*.zip - dist/*.sha256 - if-no-files-found: error - compression-level: 0 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml deleted file mode 100644 index 1ccaa6c..0000000 --- a/.github/workflows/tests.yml +++ /dev/null @@ -1,37 +0,0 @@ -name: Tests - -on: - push: - branches: [main] - pull_request: - workflow_dispatch: - -permissions: - contents: read - -jobs: - regression: - runs-on: ubuntu-24.04 - timeout-minutes: 20 - steps: - - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 - with: - go-version-file: go.mod - - run: go vet ./... - - run: go test -race -count=1 ./... - - e2e: - name: MinIO to RustFS - runs-on: ubuntu-24.04 - timeout-minutes: 20 - steps: - - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 - - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 - with: - go-version-file: go.mod - - name: Run the CLI against two S3 servers - run: | - python3 -m venv "$RUNNER_TEMP/e2e" - "$RUNNER_TEMP/e2e/bin/pip" install boto3==1.42.97 - "$RUNNER_TEMP/e2e/bin/python" tests/e2e.py diff --git a/Makefile b/Makefile index fa478bb..164709a 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,9 @@ .PHONY: build test help +VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo 0.2.0) + build: - CGO_ENABLED=0 go build -o bin/migration . + CGO_ENABLED=0 go build -trimpath -ldflags="-X github.com/rustfs/migration/cmd.Version=$(VERSION)" -o bin/migration . test: go test ./... diff --git a/README.md b/README.md index 15bfd5d..f4c5a67 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,7 @@ Leave `bucket` empty to select every source bucket; set it or use `--bucket phot ## Install -Choose the archive for your platform under **Artifacts** in a successful [Build packages run](https://github.com/rustfs/migration/actions/workflows/packages.yml). Verify the archive against its included SHA-256 digest before extracting it. Linux packages use `.tar.gz` (amd64 or arm64); Windows uses `.zip` (amd64) and the executable is `migration.exe`. +Choose the archive or Linux system package (`.deb` / `.rpm`) for your platform under **Artifacts** in a successful [CI/CD run](https://github.com/rustfs/migration/actions/workflows/ci-cd.yml) or from [GitHub Releases](https://github.com/rustfs/migration/releases). Verify the download against its SHA-256 digest before extracting or installing it. Linux releases include standalone binaries (`migration-linux-amd64`, `migration-linux-arm64`), `.tar.gz` archives, Debian `.deb` packages (`amd64` / `arm64`) and RPM packages (`x86_64` / `aarch64`); Windows uses `.zip` / `.exe` (`amd64`). Protect configuration credentials and state files. The process logs endpoints and object keys; endpoint URLs cannot contain credentials, query strings or fragments. Use HTTPS across untrusted networks. diff --git a/README_DE.md b/README_DE.md index a2683e6..8c26efe 100644 --- a/README_DE.md +++ b/README_DE.md @@ -2,7 +2,7 @@ [English](README.md) | [简体中文](README_ZH.md) | **Deutsch** | [Español](README_ES.md) | [Français](README_FR.md) | [日本語](README_JA.md) | [한국어](README_KO.md) | [Português](README_PT.md) | [Русский](README_RU.md) -**Wichtig: Diese Übersetzung ist veraltet.** Für den Betrieb gelten die [aktuelle Anleitung](docs/USAGE.md) und [Sicherheitsvoraussetzungen](README.md): Quelle ab dem Scan bis zur Abnahme extern einfrieren; Löschungen am Ziel koordinieren. `--source-frozen` friert nichts automatisch ein. Zielseitige bedingte Schreibvorgänge müssen geprüft werden. Nicht allein auf Rückgabecode 0 vertrauen. +**Wichtig: Diese Übersetzung ist veraltet.** Für den Betrieb gelten die [aktuelle Anleitung](docs/USAGE.md) und [Sicherheitsvoraussetzungen](README.md): Quelle ab dem Scan bis zur Abnahme extern einfrieren; Löschungen am Ziel koordinieren. `run` und `migrate` erfordern `--source-frozen` (friert S3 nicht automatisch ein), und `diff` liest beide Objektinhalte vollständig für SHA-256 (nicht durch `--rate-limit` begrenzt). Zielseitige bedingte Schreibvorgänge müssen geprüft werden. Nicht allein auf Rückgabecode 0 vertrauen. `migration` kopiert die aktuelle Version jedes Objekts von einem S3-kompatiblen Cluster auf einen anderen. So lassen sich etwa Bestandsdaten aus RustFS oder MinIO übertragen, während Anwendungen bereits in den neuen Cluster schreiben. In der Konfiguration steht `old` für die Quelle und `new` für das Ziel. Beide Endpunkte werden per Pfad angesprochen (Path-Style). diff --git a/README_ES.md b/README_ES.md index 8736568..c53a749 100644 --- a/README_ES.md +++ b/README_ES.md @@ -2,7 +2,7 @@ [English](README.md) | [简体中文](README_ZH.md) | [Deutsch](README_DE.md) | **Español** | [Français](README_FR.md) | [日本語](README_JA.md) | [한국어](README_KO.md) | [Português](README_PT.md) | [Русский](README_RU.md) -**Importante: esta traducción está desactualizada.** Use la [guía actual](docs/USAGE.md) y los [requisitos de seguridad](README.md): congele externamente el origen desde el escaneo hasta la validación y coordine los borrados en el destino. `--source-frozen` no congela nada por sí solo. Verifique las escrituras condicionales y no dé por completa la migración solo por un código de salida 0. +**Importante: esta traducción está desactualizada.** Use la [guía actual](docs/USAGE.md) y los [requisitos de seguridad](README.md): congele externamente el origen desde el escaneo hasta la validación y coordine los borrados en el destino. `run` y `migrate` requieren `--source-frozen` (no congela S3 por sí solo), y `diff` lee los cuerpos completos en ambos extremos para verificar SHA-256 (sin límite de `--rate-limit`). Verifique las escrituras condicionales y no dé por completa la migración solo por un código de salida 0. `migration` copia la versión actual de los objetos de un clúster compatible con S3 a otro. Por ejemplo, permite recuperar los datos históricos de un clúster RustFS o MinIO mientras las aplicaciones ya escriben en el nuevo. En la configuración, `old` identifica el origen y `new` el destino. Ambos usan direcciones S3 con el nombre del bucket en la ruta. diff --git a/README_FR.md b/README_FR.md index 6a6cd00..752d63e 100644 --- a/README_FR.md +++ b/README_FR.md @@ -2,7 +2,7 @@ [English](README.md) | [简体中文](README_ZH.md) | [Deutsch](README_DE.md) | [Español](README_ES.md) | **Français** | [日本語](README_JA.md) | [한국어](README_KO.md) | [Português](README_PT.md) | [Русский](README_RU.md) -**Important : cette traduction est obsolète.** Suivez le [guide actuel](docs/USAGE.md) et les [conditions de sécurité](README.md) : geler la source à partir du scan jusqu’à la validation et coordonner les suppressions sur la destination. `--source-frozen` ne gèle rien automatiquement. Vérifiez les écritures conditionnelles et ne concluez pas au succès sur le seul code de sortie 0. +**Important : cette traduction est obsolète.** Suivez le [guide actuel](docs/USAGE.md) et les [conditions de sécurité](README.md) : geler la source à partir du scan jusqu’à la validation et coordonner les suppressions sur la destination. `run` et `migrate` exigent `--source-frozen` (ne gèle rien automatiquement), et `diff` lit l’intégralité des objets des deux côtés pour vérifier SHA-256 (sans `--rate-limit`). Vérifiez les écritures conditionnelles et ne concluez pas au succès sur le seul code de sortie 0. `migration` copie la version courante des objets d’un cluster compatible S3 vers un autre. Vous pouvez ainsi transférer les données historiques d’un cluster RustFS ou MinIO pendant que les applications écrivent déjà sur le nouveau cluster. Dans la configuration, `old` désigne la source et `new` la destination. Les deux utilisent des URL S3 où le nom du bucket figure dans le chemin. diff --git a/README_JA.md b/README_JA.md index 7316f6c..75c428d 100644 --- a/README_JA.md +++ b/README_JA.md @@ -2,7 +2,7 @@ [English](README.md) | [简体中文](README_ZH.md) | [Deutsch](README_DE.md) | [Español](README_ES.md) | [Français](README_FR.md) | **日本語** | [한국어](README_KO.md) | [Português](README_PT.md) | [Русский](README_RU.md) -**重要:この翻訳は古い情報を含みます。** 運用時は[最新ガイド](docs/USAGE.md)と[安全要件](README.md)を参照してください。スキャン開始から最終検証まで移行元の書き込み・削除を外部で停止し、移行先の削除も調整してください。`--source-frozen` 自体は停止処理を行いません。条件付き書き込みを確認し、終了コード 0 のみで完了と判断しないでください。 +**重要:この翻訳は古い情報を含みます。** 運用時は[最新ガイド](docs/USAGE.md)と[安全要件](README.md)を参照してください。スキャン開始から最終検証まで移行元の書き込み・削除を外部で停止し、移行先の削除も調整してください。`run` と `migrate` には `--source-frozen` が必須であり(自動停止は行いません)、`diff` は SHA-256 検証のため両端のオブジェクト本文をすべて読み取ります(`--rate-limit` 対象外)。条件付き書き込みを確認し、終了コード 0 のみで完了と判断しないでください。 `migration` は、S3 互換クラスター間でオブジェクトの現行バージョンをコピーするツールです。たとえば、アプリケーションの書き込み先を新しいクラスターに切り替えた後、旧 RustFS や MinIO クラスターに残ったデータを移行できます。設定では `old` が移行元、`new` が移行先です。どちらもバケット名をパスに含める形式でアクセスします。 diff --git a/README_KO.md b/README_KO.md index f663b15..53a4be8 100644 --- a/README_KO.md +++ b/README_KO.md @@ -2,7 +2,7 @@ [English](README.md) | [简体中文](README_ZH.md) | [Deutsch](README_DE.md) | [Español](README_ES.md) | [Français](README_FR.md) | [日本語](README_JA.md) | **한국어** | [Português](README_PT.md) | [Русский](README_RU.md) -**중요: 이 번역은 오래되었습니다.** 운영 시 [최신 안내](docs/USAGE.md)와 [안전 요구사항](README.md)을 따르세요. 스캔부터 최종 검증까지 원본 쓰기와 삭제를 외부에서 동결하고 대상 삭제도 조율해야 합니다. `--source-frozen`은 자동으로 동결하지 않습니다. 조건부 쓰기를 확인하고 종료 코드 0만으로 완료를 판단하지 마세요. +**중요: 이 번역은 오래되었습니다.** 운영 시 [최신 안내](docs/USAGE.md)와 [안전 요구사항](README.md)을 따르세요. 스캔부터 최종 검증까지 원본 쓰기와 삭제를 외부에서 동결하고 대상 삭제도 조율해야 합니다. `run`과 `migrate`에는 `--source-frozen`이 필수이며(자동 동결 아님), `diff`는 SHA-256 검증을 위해 양쪽 객체 본문 전체를 읽습니다(`--rate-limit` 미적용). 조건부 쓰기를 확인하고 종료 코드 0만으로 완료를 판단하지 마세요. `migration`은 S3 호환 클러스터 간에 객체의 현재 버전을 복사하는 도구입니다. 애플리케이션의 쓰기 요청을 새 클러스터로 전환한 뒤에도 기존 RustFS 또는 MinIO 클러스터에 남은 데이터를 옮길 수 있습니다. 설정에서 `old`는 원본, `new`는 대상을 가리킵니다. 두 클러스터 모두 URL 경로에 버킷 이름을 넣는 방식을 사용합니다. diff --git a/README_PT.md b/README_PT.md index 46da0cd..1b9765b 100644 --- a/README_PT.md +++ b/README_PT.md @@ -2,7 +2,7 @@ [English](README.md) | [简体中文](README_ZH.md) | [Deutsch](README_DE.md) | [Español](README_ES.md) | [Français](README_FR.md) | [日本語](README_JA.md) | [한국어](README_KO.md) | **Português** | [Русский](README_RU.md) -**Importante: esta tradução está desatualizada.** Siga o [guia atual](docs/USAGE.md) e os [requisitos de segurança](README.md): congele externamente as escritas e eliminações na origem desde a leitura do inventário até à validação e coordene as eliminações no destino. `--source-frozen` não congela nada automaticamente. Verifique as escritas condicionais e não aceite apenas o código de saída 0 como prova de conclusão. +**Importante: esta tradução está desatualizada.** Siga o [guia atual](docs/USAGE.md) e os [requisitos de segurança](README.md): congele externamente as escritas e eliminações na origem desde a leitura do inventário até à validação e coordene as eliminações no destino. `run` e `migrate` exigem `--source-frozen` (não congela nada automaticamente), e `diff` lê o corpo completo dos objetos em ambos os lados para verificar SHA-256 (sem `--rate-limit`). Verifique as escritas condicionais e não aceite apenas o código de saída 0 como prova de conclusão. O `migration` copia a versão atual dos objetos entre dois clusters compatíveis com S3. Por exemplo, pode transferir o histórico de um cluster RustFS ou MinIO enquanto a aplicação já escreve no novo cluster. Na configuração, `old` identifica a origem e `new` o destino. Ambos usam endereços S3 com o nome do bucket no caminho. diff --git a/README_RU.md b/README_RU.md index af08b89..f39b515 100644 --- a/README_RU.md +++ b/README_RU.md @@ -2,7 +2,7 @@ [English](README.md) | [简体中文](README_ZH.md) | [Deutsch](README_DE.md) | [Español](README_ES.md) | [Français](README_FR.md) | [日本語](README_JA.md) | [한국어](README_KO.md) | [Português](README_PT.md) | **Русский** -**Важно: этот перевод устарел.** Используйте [актуальное руководство](docs/USAGE.md) и [условия безопасности](README.md): внешним образом заморозьте запись и удаление на источнике от сканирования до проверки и согласуйте удаления на приёмнике. `--source-frozen` не выполняет заморозку. Проверьте условную запись и не считайте код выхода 0 доказательством завершения. +**Важно: этот перевод устарел.** Используйте [актуальное руководство](docs/USAGE.md) и [условия безопасности](README.md): внешним образом заморозьте запись и удаление на источнике от сканирования до проверки и согласуйте удаления на приёмнике. Для `run` и `migrate` обязателен флаг `--source-frozen` (он не выполняет заморозку сам по себе), а `diff` полностью читает тела объектов с обеих сторон для проверки SHA-256 (без ограничения `--rate-limit`). Проверьте условную запись и не считайте код выхода 0 доказательством завершения. Утилита `migration` копирует текущие версии объектов из одного S3-совместимого кластера в другой. Например, с её помощью можно перенести архив из RustFS или MinIO, когда приложение уже пишет в новый кластер. В конфигурации `old` обозначает источник, а `new` — приёмник. Имя бакета указывается в пути запроса к S3. diff --git a/README_ZH.md b/README_ZH.md index 6a914cb..c8fd72c 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -16,19 +16,19 @@ ## 快速开始 -以下命令在仓库根目录运行,需要 Go 1.22 或更高版本。复制配置模板后,请先编辑 `config.yaml`,填入两端的地址和凭据。 +以下命令在仓库根目录运行,需要 Go 1.26 或更高版本(`go.mod` 自动选用 `go1.26.10`)。复制配置模板后,请先编辑 `config.yaml`,填入两端的地址、凭据与独立的状态目录,并在外部冻结源端写入和删除、协调目标端删除。 ```bash git clone https://github.com/rustfs/migration.git cd migration CGO_ENABLED=0 go build -o bin/migration . # 或:make build -cp config.example.yaml config.yaml # 填写来源和目标的地址、密钥 +cp config.example.yaml config.yaml # 填写来源和目标的地址、密钥与独立状态目录 ``` ```bash ./bin/migration list -c config.yaml -./bin/migration run -c config.yaml --workers 16 --rate-limit 20M +./bin/migration run -c config.yaml --source-frozen --workers 16 --rate-limit 20M ./bin/migration status -c config.yaml ./bin/migration diff -c config.yaml ``` @@ -41,7 +41,7 @@ cp config.example.yaml config.yaml # 填写来源和目标的地址、密钥 ## 使用预编译包 -打开 [Build packages](https://github.com/rustfs/migration/actions/workflows/packages.yml),在成功运行的 **Artifacts** 中选择对应平台。解压下载文件,用随附的 SHA-256 校验值核对软件包,再解开软件包。Linux amd64 和 arm64 使用 `.tar.gz`,Windows amd64 使用 `.zip`,可执行文件为 `migration.exe`。 +打开 [CI/CD 工作流](https://github.com/rustfs/migration/actions/workflows/ci-cd.yml) 的 **Artifacts** 或 [GitHub Releases](https://github.com/rustfs/migration/releases),选择对应平台的构建产物,并用随附的 SHA-256 校验值核对后再解压或安装。Linux 平台提供独立二进制(`migration-linux-amd64`、`migration-linux-arm64`)、`.tar.gz` 压缩包、Debian `.deb` 包(`amd64` / `arm64`)以及 `.rpm` 包(`x86_64` / `aarch64`);Windows amd64 提供独立可执行文件与 `.zip` 包(可执行文件为 `migration.exe`)。 ```bash ./migration --version @@ -153,11 +153,11 @@ rate_limit: 0 # 源读取合计上限;0 或省略 = 不限 | 命令 | 作用 | 是否写目标 | 并发与限额 | | --- | --- | --- | --- | | `migration list -c config.yaml` | 列出源上全部桶 | 否 | 无 | -| `migration run -c config.yaml` | **推荐。** 先扫描再复制 | 是,但不覆盖 | 扫描单线程。复制使用 `workers`、`multipart_concurrency` 和 `rate_limit` | +| `migration run -c config.yaml --source-frozen` | **推荐。** 先扫描再复制 | 是,但不覆盖 | 扫描单线程。复制使用 `workers`、`multipart_concurrency` 和 `rate_limit` | | `migration scan -c config.yaml` | 把源清单写入 SQLite | 否 | 单线程。不限速 | -| `migration migrate -c config.yaml` | 只复制 SQLite 里 `pending` 或 `failed` 的行 | 是,但不覆盖 | `workers`、`multipart_concurrency` 和 `rate_limit` | +| `migration migrate -c config.yaml --source-frozen` | 只复制已完成扫描清单中 `pending` 或 `failed` 的行 | 是,但不覆盖 | `workers`、`multipart_concurrency` 和 `rate_limit` | | `migration status -c config.yaml` | 打印本地计数 | 否 | 无。不访问 S3 | -| `migration diff -c config.yaml` | 列举源端对象,逐个在目标端执行 `HEAD` | 否 | `workers` 控制并行 HEAD。不限速 | +| `migration diff -c config.yaml` | 列举源端对象,读取双端完整正文核对 SHA-256 与保留元数据 | 否 | `workers` 控制并行校验。读取全部数据,不受 `rate_limit` 限制 | | `migration diff --extra -c config.yaml` | 同上,并列出只在目标上的 key | 否 | `workers` | 所有命令共用的参数: @@ -182,7 +182,7 @@ rate_limit: 0 # 源读取合计上限;0 或省略 = 不限 ```bash ./bin/migration list -c config.yaml -./bin/migration run -c config.yaml --workers 16 --rate-limit 20M +./bin/migration run -c config.yaml --source-frozen --workers 16 --rate-limit 20M ./bin/migration status -c config.yaml ./bin/migration diff -c config.yaml --workers 32 ``` @@ -194,24 +194,24 @@ rate_limit: 0 # 源读取合计上限;0 或省略 = 不限 3. 目标上没有该桶就创建。已有的桶不动。 4. 最多同时复制 `workers` 个对象。如果业务恰好在目标检查后创建同名对象,条件写入会保护该对象。工具会重新核对目标,将结果记为 `done` 或 `conflict`。 5. 对象大小达到 `multipart_threshold` 时采用分片上传。每个对象最多并行传输 `multipart_concurrency` 个分片,所有源端读取共享同一带宽上限。 -6. 核对目标上的大小。普通上传的对象在 ETag 可比时再比 ETag。见 [对象状态](#resume-and-object-state)。 +6. 从目标完整读回对象核对大小、保留的元数据与全文 SHA-256。见 [对象状态](#resume-and-object-state)。 桶按顺序迁移,所以 `rate_limit` 就是整个进程的上限。 ### 只迁一个桶 ```bash -./bin/migration run -c config.yaml \ +./bin/migration run -c config.yaml --source-frozen \ --bucket photos --workers 8 --multipart-concurrency 8 --rate-limit 30M ``` ### 源上后来写入的对象 -`ListObjectsV2` 不能在服务端按修改时间过滤。要补齐新增对象,需要重新列举整个源桶。新发现的对象会标记为 `pending`。再次被列出的 `failed` 或 `skipped` 行回到 `pending`。`done` 和 `conflict` 保持不变,所以第二遍不会重传,也不会覆盖目标。 +`ListObjectsV2` 不能在服务端按修改时间过滤。本工具设计用于冻结源端后的单次迁移,而非持续同步;若在重新冻结后补齐新增对象,需要重新列举整个源桶。新发现或源身份变化的对象会标记为 `pending`;再次被列出的 `failed` 或 `skipped` 行回到 `pending`;源端已删除的历史行会在完整重扫结束时移出清单。目标已有不同内容时记录 `conflict`,不会覆盖目标。 ```bash ./bin/migration scan -c config.yaml -./bin/migration migrate -c config.yaml --workers 16 +./bin/migration migrate -c config.yaml --source-frozen --workers 16 ./bin/migration diff -c config.yaml ``` @@ -220,9 +220,9 @@ rate_limit: 0 # 源读取合计上限;0 或省略 = 不限 ### 先建立清单,再复制 ```bash -./bin/migration scan -c config.yaml -./bin/migration status -c config.yaml # 对象计数,不访问 S3 -./bin/migration migrate -c config.yaml --workers 16 +./bin/migration scan -c config.yaml +./bin/migration status -c config.yaml # 对象计数,不访问 S3 +./bin/migration migrate -c config.yaml --source-frozen --workers 16 ``` ## 并发 @@ -293,9 +293,9 @@ rate_limit: 20M ``` ```bash -RATE_LIMIT=30M ./bin/migration run -c config.yaml -./bin/migration migrate -c config.yaml --rate-limit 50M -./bin/migration run -c config.yaml --rate-limit 0 # 明确不限速 +RATE_LIMIT=30M ./bin/migration run -c config.yaml --source-frozen +./bin/migration migrate -c config.yaml --source-frozen --rate-limit 50M +./bin/migration run -c config.yaml --source-frozen --rate-limit 0 # 明确不限速 ``` @@ -322,7 +322,7 @@ RATE_LIMIT=30M ./bin/migration run -c config.yaml | `done` | 已复制并校验,或目标上已有与清单一致的对象 | 不动 | | `conflict` | 目标已有该 key,且与清单不一致。未覆盖 | 不动 | -目标端已有同名对象时,只有大小相同,且两端 ETag 均非空、完全相同,才会记为 `done`。其余情况均记为 `conflict`,保留目标对象。分片边界不同,即便内容相同也可能产生不同的 ETag。若在上传成功后、状态落盘前中断,恢复时请人工核实这类冲突。 +目标端已有同名对象时,只有大小相同、保留的元数据一致,且读取双端完整正文计算出的 SHA-256 完全相同,才会记为 `done`(不依赖跨端 ETag 比较)。其余情况均记为 `conflict`,保留目标对象。 每条冲突在冲突日志里占一行 TSV,时间是 RFC3339 UTC: @@ -330,30 +330,31 @@ RATE_LIMIT=30M ./bin/migration run -c config.yaml ``` -键名若包含控制字符或以双引号开头,日志会按 Go 字符串字面量的规则加引号并转义。 +键名若包含控制字符、反斜杠或以双引号开头,日志会按 Go 字符串字面量的规则加引号并转义。 -只配置了一个桶时,使用写下的 `db_path` 和 `conflict_log`。全桶模式在旁边生成: +只配置了一个桶时,使用写下的 `db_path` 和 `conflict_log`。全桶模式保留配置的基础文件名并在旁边生成: -- `migration-<桶名>.db` -- `conflict-<桶名>.log` +- `<基础文件名>-<桶名>.db`(默认 `migration-<桶名>.db`) +- `<基础文件名>-<桶名>.log`(默认 `conflict-<桶名>.log`) -执行 `migrate` 前须先用 `scan` 或 `run` 建立清单。状态库会绑定桶名和两端地址。使用旧版本的状态库前,请先核实它对应的集群。升级后的首次扫描会记录源地址,首次迁移会记录目标地址。扫描失败或中断后,请先重新执行 `scan` 或 `run`,再使用 `migrate`。旧版本的状态库没有扫描完成标记。如果无法确认清单完整,请重新扫描。 +执行 `migrate` 前须先用 `scan` 或 `run` 建立完整清单。状态库会绑定桶名和两端规范化地址。扫描失败或中断后,请先重新执行 `scan` 或 `run`,再使用 `migrate`。旧版无身份绑定且已有处理记录的状态库会被拒绝接管,请使用新的独立状态目录重新扫描。 ## 用 diff 核对目标 -`diff` 通过大小和可比较的 ETag 核对对象,不下载正文。`ok` 中仅校验了大小的对象另计入 `size_only`。添加 `--extra` 会建立临时索引,列出仅存在于目标端的对象。源桶为空时,`diff` 仍会检查目标桶是否存在。目标桶缺失会返回退出码 1。 +`diff` 检查两端桶是否存在,并对每个同大小对象**完整读取源端与目标端正文**校验 SHA-256 及保留的元数据(需要双端 `GetObject` 权限与读带宽,且不受 `--rate-limit` 限制)。添加 `--extra` 会建立临时索引(优先使用 `spool_dir`),列出仅存在于目标端的对象;`--strict` 还会对目标独有对象返回非零退出码;`--issues-jsonl <新文件路径>` 可流式导出全部差异记录。 ```bash ./bin/migration diff -c config.yaml --workers 32 ./bin/migration diff -c config.yaml --extra +./bin/migration diff -c config.yaml --strict --issues-jsonl ./issues.jsonl ``` ```text === diff photos === -ok=1000 missing=2 size_mismatch=0 etag_mismatch=1 extra_on_target=0 size_only=3 -一致=1000 缺失=2 大小不一致=0 ETag不一致=1 仅目标有=0 仅比大小=3 - missing a.txt not on target - etag b.txt src=abc dst=def +ok=1000 missing=2 size_mismatch=0 etag_mismatch=0 content_mismatch=1 metadata_mismatch=0 extra_on_target=0 +一致=1000 缺失=2 大小不一致=0 内容SHA256不一致=1 元数据不一致=0 仅目标有=0 + missing "a.txt" not on target + content "b.txt" sha256 src=... dst=... ``` 第二行汇总是中文,因为命令本身就会打印这一行。最多打印 50 条问题,其余记在末尾的 “and N more” 里。 @@ -376,7 +377,7 @@ ok=1000 missing=2 size_mismatch=0 etag_mismatch=1 extra_on_target=0 size_on | 迁移中源被删除 | 完整返回的源 404 记 `skipped`。取消和超时记 `failed`,下次会重试 | | 中断后恢复 | 每个对象的状态在 SQLite WAL 里。第一次信号取消 worker;下次 `migrate` 继续 | | 内存有上限 | 小对象落盘。大对象按分片读。任务队列有上限 | -| 复制后校验 | 总是比大小。普通上传的对象在两边 ETag 可比时再比 ETag | +| 复制后校验 | 总是核对大小、保留的元数据,并完整读回核对正文 SHA-256 | 不做:版本历史、删除标记、Object Lock、桶策略、生命周期规则、双向同步,以及服务端 `CopyObject`(两个集群是分开的,字节经过本进程)。 diff --git a/cmd/audit_fixes_regression_test.go b/cmd/audit_fixes_regression_test.go new file mode 100644 index 0000000..adf1ca9 --- /dev/null +++ b/cmd/audit_fixes_regression_test.go @@ -0,0 +1,562 @@ +package cmd + +import ( + "bytes" + "context" + "database/sql" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/aws/retry" + "github.com/aws/aws-sdk-go-v2/service/s3" + + "github.com/rustfs/migration/internal/config" + "github.com/rustfs/migration/internal/differ" + "github.com/rustfs/migration/internal/fakes3" + "github.com/rustfs/migration/internal/migrator" + "github.com/rustfs/migration/internal/s3client" + "github.com/rustfs/migration/internal/scanner" + "github.com/rustfs/migration/internal/store" +) + +func TestWhitespaceEnvVarsPreserveYAMLAndTrimSessionTokens(t *testing.T) { + now := time.Date(2026, 11, 25, 0, 0, 0, 0, time.UTC) + src := fakes3.NewWithObjects(t, "production-photos", map[string][]byte{"a.jpg": []byte("photo")}, now) + defer src.Close() + src.Put("secret-hr-bucket", "payroll.csv", []byte("sensitive"), now, fakes3.Metadata{}) + + dst := fakes3.New(t) + defer dst.Close() + + dir := t.TempDir() + cfgPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, cfgPath, src.URL, dst.URL, filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, "bucket: production-photos\nworkers: 1\n") + + t.Setenv("BUCKET", " ") + t.Setenv("DB_PATH", " ") + t.Setenv("OLD_SESSION_TOKEN", " sts-token-with-newline\n") + t.Setenv("NEW_SESSION_TOKEN", "\tnew-sts-token\r\n") + + cfg, err := config.Load(cfgPath) + if err != nil { + t.Fatalf("Load failed: %v", err) + } + if cfg.Bucket != "production-photos" || cfg.AllBuckets() { + t.Fatalf("whitespace BUCKET env overwrote YAML bucket: got %q", cfg.Bucket) + } + if cfg.Old.SessionToken != "sts-token-with-newline" || cfg.New.SessionToken != "new-sts-token" { + t.Fatalf("session tokens were not trimmed: old=%q new=%q", cfg.Old.SessionToken, cfg.New.SessionToken) + } + + listOut, err := execRootStdout(t, "list", "-c", cfgPath) + if err != nil { + t.Fatalf("list failed with trimmed session token: %v", err) + } + if !strings.Contains(listOut, "production-photos") || !strings.Contains(listOut, "2 bucket(s)") { + t.Fatalf("unexpected list output:\n%s", listOut) + } + + if _, err := execRoot(t, "run", "-c", cfgPath); err != nil { + t.Fatalf("run failed: %v", err) + } + if _, ok := dst.Object("production-photos", "a.jpg"); !ok { + t.Fatal("expected production-photos/a.jpg to be migrated") + } + if _, leaked := dst.Object("secret-hr-bucket", "payroll.csv"); leaked { + t.Fatal("secret-hr-bucket was migrated despite YAML specifying bucket: production-photos") + } + + // Also exercise empty-cluster list output. + emptySrc := fakes3.New(t) + defer emptySrc.Close() + emptyCfg := filepath.Join(dir, "empty.yaml") + writeClusterConfig(t, emptyCfg, emptySrc.URL, dst.URL, filepath.Join(dir, "empty.db"), filepath.Join(dir, "empty.log"), dir, "") + emptyListOut, err := execRootStdout(t, "list", "-c", emptyCfg) + if err != nil || !strings.Contains(emptyListOut, "source has no buckets") { + t.Fatalf("empty list: err=%v out=%q", err, emptyListOut) + } +} + +func TestEmptySourceContentTypeMigratesAndDiffsCleanly(t *testing.T) { + body := []byte("raw object without content-type on source") + src := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodHead && (r.URL.Path == "/photos" || r.URL.Path == "/photos/"): + w.WriteHeader(http.StatusOK) + case r.Method == http.MethodGet && r.URL.Query().Get("list-type") == "2": + w.Header().Set("Content-Type", "application/xml") + fmt.Fprintf(w, `photosfalseurllegacy.bin2026-11-25T00:00:00Z"etag1"%d`, len(body)) + case r.Method == http.MethodHead && r.URL.Path == "/photos/legacy.bin": + w.Header()["Content-Type"] = nil + w.Header().Set("Content-Length", fmt.Sprint(len(body))) + w.Header().Set("ETag", `"etag1"`) + w.Header().Set("Last-Modified", "Wed, 25 Nov 2026 00:00:00 GMT") + w.WriteHeader(http.StatusOK) + case r.Method == http.MethodGet && r.URL.Path == "/photos/legacy.bin": + w.Header()["Content-Type"] = nil + w.Header().Set("Content-Length", fmt.Sprint(len(body))) + w.Header().Set("ETag", `"etag1"`) + w.Header().Set("Last-Modified", "Wed, 25 Nov 2026 00:00:00 GMT") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(body) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + defer src.Close() + + dst := fakes3.New(t) + defer dst.Close() + + dir := t.TempDir() + dbPath := filepath.Join(dir, "migration.db") + cfgPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, cfgPath, src.URL, dst.URL, dbPath, filepath.Join(dir, "conflict.log"), dir, "bucket: photos\nworkers: 1\n") + + if _, err := execRoot(t, "run", "-c", cfgPath, "--strict"); err != nil { + t.Fatalf("run --strict failed for empty source Content-Type: %v", err) + } + if _, err := execRoot(t, "migrate", "-c", cfgPath, "--strict"); err != nil { + t.Fatalf("idempotent migrate --strict failed: %v", err) + } + diffOut, err := execRootStdout(t, "diff", "-c", cfgPath, "--strict") + if err != nil || !strings.Contains(diffOut, "ok=1") || !strings.Contains(diffOut, "metadata_mismatch=0") { + t.Fatalf("diff failed: err=%v\n%s", err, diffOut) + } +} + +func TestRawNonRFC1123ExpiresHeaderPreservedAndVerified(t *testing.T) { + body := []byte("asset with Expires: 0") + var targetReceivedExpires atomic.Value + targetReceivedExpires.Store("") + + src := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodHead && r.URL.Path == "/photos": + w.WriteHeader(http.StatusOK) + case r.Method == http.MethodGet && r.URL.Query().Get("list-type") == "2": + w.Header().Set("Content-Type", "application/xml") + fmt.Fprintf(w, `photosfalseapp.js2026-11-25T00:00:00Z"e1"%d`, len(body)) + case r.URL.Path == "/photos/app.js": + w.Header().Set("Content-Type", "application/javascript") + w.Header().Set("Content-Length", fmt.Sprint(len(body))) + w.Header().Set("ETag", `"e1"`) + w.Header().Set("Expires", "0") + w.Header().Set("Last-Modified", "Wed, 25 Nov 2026 00:00:00 GMT") + w.WriteHeader(http.StatusOK) + if r.Method == http.MethodGet { + _, _ = w.Write(body) + } + } + })) + defer src.Close() + + dstBackend := fakes3.New(t) + defer dstBackend.Close() + dst := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPut && r.URL.Path == "/photos/app.js" { + targetReceivedExpires.Store(r.Header.Get("Expires")) + } + dstBackend.Config.Handler.ServeHTTP(w, r) + })) + defer dst.Close() + + dir := t.TempDir() + cfgPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, cfgPath, src.URL, dst.URL, filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, "bucket: photos\nworkers: 1\n") + + if _, err := execRoot(t, "run", "-c", cfgPath, "--strict"); err != nil { + t.Fatalf("run failed: %v", err) + } + if got := targetReceivedExpires.Load(); got != "0" { + t.Fatalf("target received Expires=%q, want %q", got, "0") + } + diffOut, err := execRootStdout(t, "diff", "-c", cfgPath, "--strict") + if err != nil || !strings.Contains(diffOut, "ok=1") { + t.Fatalf("diff failed: err=%v\n%s", err, diffOut) + } +} + +func TestIsCanceledDoesNotMisclassify404EchoingSensitiveKeyWords(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/photos" && r.Method == http.MethodHead { + w.WriteHeader(http.StatusOK) + return + } + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(http.StatusNotFound) + fmt.Fprintf(w, `NoSuchKeyThe key %s does not exist`, r.URL.Path) + })) + defer srv.Close() + + ctx := context.Background() + cli, err := s3client.New(ctx, config.Endpoint{Endpoint: srv.URL, Region: "us-east-1", AccessKey: "a", SecretKey: "b"}) + if err != nil { + t.Fatal(err) + } + for _, key := range []string{ + "recordings/interrupted-session.mp4", + "logs/deadline exceeded/report.txt", + "jobs/request canceled.json", + } { + _, getErr := cli.GetObject(ctx, &s3.GetObjectInput{ + Bucket: aws.String("photos"), + Key: aws.String(key), + }) + if s3client.IsCanceled(getErr) { + t.Fatalf("key %q: HTTP 404 NoSuchKey misclassified as canceled: %v", key, getErr) + } + if !s3client.IsNotFound(getErr) { + t.Fatalf("key %q: HTTP 404 NoSuchKey not recognized as NotFound: %v", key, getErr) + } + } +} + +func TestRescanPrunesDeletedSourceRowsAndUnblocksStrictMode(t *testing.T) { + now := time.Date(2026, 11, 25, 0, 0, 0, 0, time.UTC) + src := fakes3.NewWithObjects(t, "photos", map[string][]byte{ + "keep.txt": []byte("keep"), + "temp.txt": []byte("ephemeral"), + }, now) + defer src.Close() + dst := fakes3.New(t) + defer dst.Close() + + dir := t.TempDir() + dbPath := filepath.Join(dir, "migration.db") + cfgPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, cfgPath, src.URL, dst.URL, dbPath, filepath.Join(dir, "conflict.log"), dir, "bucket: photos\nworkers: 1\n") + + if _, err := execRoot(t, "scan", "-c", cfgPath); err != nil { + t.Fatal(err) + } + src.DeleteKey("photos", "temp.txt") + + if _, err := execRoot(t, "run", "-c", cfgPath, "--strict"); err != nil { + t.Fatalf("run --strict failed after rescanning post-deletion source: %v", err) + } + st, err := store.OpenExisting(dbPath) + if err != nil { + t.Fatal(err) + } + counts, err := st.Counts() + _ = st.Close() + if err != nil { + t.Fatal(err) + } + if counts.Total != 1 || counts.Done != 1 || counts.Skipped != 0 { + t.Fatalf("unexpected counts after pruning deleted source row: %+v", counts) + } +} + +func TestStatusSucceedsOnReadOnlyDirectoryAfterCleanClose(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("POSIX directory permissions test") + } + now := time.Date(2026, 11, 25, 0, 0, 0, 0, time.UTC) + src := fakes3.NewWithObjects(t, "photos", map[string][]byte{"a.txt": []byte("ok")}, now) + defer src.Close() + dst := fakes3.New(t) + defer dst.Close() + + base := t.TempDir() + stateDir := filepath.Join(base, "readonly-snapshot") + dbPath := filepath.Join(stateDir, "migration.db") + cfgPath := filepath.Join(base, "config.yaml") + writeClusterConfig(t, cfgPath, src.URL, dst.URL, dbPath, filepath.Join(base, "conflict.log"), base, "bucket: photos\nworkers: 1\n") + + if _, err := execRoot(t, "scan", "-c", cfgPath); err != nil { + t.Fatal(err) + } + if err := os.Chmod(stateDir, 0o555); err != nil { + t.Fatal(err) + } + defer os.Chmod(stateDir, 0o755) + + out, err := execRootStdout(t, "status", "-c", cfgPath) + if err != nil { + t.Fatalf("status failed on read-only directory: %v", err) + } + if !strings.Contains(out, "photos") { + t.Fatalf("unexpected status output:\n%s", out) + } +} + +func TestStatusTargetsHandlesBracketDirectoriesAndDeduplicatesBuckets(t *testing.T) { + now := time.Date(2026, 11, 25, 0, 0, 0, 0, time.UTC) + src := fakes3.NewWithObjects(t, "photos", map[string][]byte{"a.txt": []byte("ok")}, now) + defer src.Close() + dst := fakes3.New(t) + defer dst.Close() + + base := t.TempDir() + for _, sub := range []string{"[2026-11]", "[2026]"} { + stateDir := filepath.Join(base, sub) + dbPath := filepath.Join(stateDir, "migration.db") + cfgPath := filepath.Join(base, "cfg-"+sub+".yaml") + writeClusterConfig(t, cfgPath, src.URL, dst.URL, dbPath, filepath.Join(stateDir, "conflict.log"), base, "workers: 1\n") + if _, err := execRoot(t, "scan", "-c", cfgPath); err != nil { + t.Fatalf("%s scan: %v", sub, err) + } + out, err := execRootStdout(t, "status", "-c", cfgPath) + if err != nil || !strings.Contains(out, "photos") { + t.Fatalf("%s status failed: err=%v out=%q", sub, err, out) + } + } + + dupDir := filepath.Join(base, "dup") + dupDB := filepath.Join(dupDir, "migration.db") + cfgPath := filepath.Join(base, "dup.yaml") + writeClusterConfig(t, cfgPath, src.URL, dst.URL, dupDB, filepath.Join(dupDir, "conflict.log"), base, "workers: 1\n") + if _, err := execRoot(t, "scan", "-c", cfgPath, "--bucket", "photos"); err != nil { + t.Fatal(err) + } + if _, err := execRoot(t, "scan", "-c", cfgPath); err != nil { + t.Fatal(err) + } + out, err := execRootStdout(t, "status", "-c", cfgPath) + if err != nil { + t.Fatal(err) + } + if got := strings.Count(out, "photos"); got != 1 { + t.Fatalf("expected 1 photos row in status output, got %d:\n%s", got, out) + } +} + +func TestDefaultPortsNormalizedInValidatePairAndBindMigration(t *testing.T) { + for _, pair := range [][2]string{ + {"http://s3.internal.local", "http://s3.internal.local:80"}, + {"https://S3.INTERNAL.LOCAL:443/", "https://s3.internal.local"}, + {"http://[::1]:80", "http://[::1]"}, + } { + cfg := &config.Config{ + Old: config.Endpoint{Endpoint: pair[0], AccessKey: "a", SecretKey: "b"}, + New: config.Endpoint{Endpoint: pair[1], AccessKey: "a", SecretKey: "b"}, + } + if err := cfg.ValidatePair(); err == nil { + t.Fatalf("ValidatePair accepted identical endpoints %q and %q", pair[0], pair[1]) + } + } + + st, err := store.Open(filepath.Join(t.TempDir(), "state.db"), "photos") + if err != nil { + t.Fatal(err) + } + defer st.Close() + if err := st.BindMigration("https://s3.internal.local:443", "http://dst.internal.local:80"); err != nil { + t.Fatal(err) + } + if err := st.BindMigration("https://s3.internal.local/", "http://dst.internal.local/"); err != nil { + t.Fatalf("BindMigration rejected equivalent default-port URLs: %v", err) + } +} + +func TestDiffIssuesJSONLNotCreatedOnInvalidConfig(t *testing.T) { + dir := t.TempDir() + jsonl := filepath.Join(dir, "issues.jsonl") + if _, err := execRoot(t, "diff", "-c", filepath.Join(dir, "missing.yaml"), "--issues-jsonl", jsonl); err == nil { + t.Fatal("expected missing config to fail") + } + if _, err := os.Stat(jsonl); !os.IsNotExist(err) { + t.Fatalf("invalid config invocation created JSONL file prematurely: %v", err) + } +} + +func TestSQLitePendingQueryPlanUsesCompositeIndexAndDiffRespectsTempDir(t *testing.T) { + dbPath := filepath.Join(t.TempDir(), "plan.db") + st, err := store.Open(dbPath, "photos") + if err != nil { + t.Fatal(err) + } + _ = st.Close() + + rawDB, err := sql.Open("sqlite", dbPath) + if err != nil { + t.Fatal(err) + } + defer rawDB.Close() + query := ` +SELECT key, size, last_modified, etag, status FROM ( + SELECT key, size, last_modified, etag, status FROM ( + SELECT key, size, last_modified, etag, status FROM objects + WHERE status = 'pending' AND key > ? ORDER BY key LIMIT ? + ) + UNION ALL + SELECT key, size, last_modified, etag, status FROM ( + SELECT key, size, last_modified, etag, status FROM objects + WHERE status = 'failed' AND key > ? ORDER BY key LIMIT ? + ) +) ORDER BY key LIMIT ?` + rows, err := rawDB.Query("EXPLAIN QUERY PLAN "+query, "", 1000, "", 1000, 1000) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var plans []string + for rows.Next() { + var id, parent, notused int + var detail string + if err := rows.Scan(&id, &parent, ¬used, &detail); err != nil { + t.Fatal(err) + } + plans = append(plans, detail) + } + joined := strings.Join(plans, " | ") + if !strings.Contains(joined, "idx_objects_status_key") { + t.Fatalf("expected composite index idx_objects_status_key in query plan, got: %s", joined) + } + + osTmp := filepath.Join(t.TempDir(), "os-tmp") + spoolTmp := filepath.Join(t.TempDir(), "spool-tmp") + _ = os.MkdirAll(osTmp, 0o700) + _ = os.MkdirAll(spoolTmp, 0o700) + t.Setenv("TMPDIR", osTmp) + + var sawOSTmp, sawSpoolTmp atomic.Bool + src := fakes3.NewWithObjects(t, "photos", map[string][]byte{"a.txt": []byte("hello")}, time.Now()) + defer src.Close() + dstBackend := fakes3.NewWithObjects(t, "photos", map[string][]byte{"a.txt": []byte("hello")}, time.Now()) + defer dstBackend.Close() + dst := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if entries, _ := os.ReadDir(osTmp); len(entries) > 0 { + sawOSTmp.Store(true) + } + if entries, _ := os.ReadDir(spoolTmp); len(entries) > 0 { + sawSpoolTmp.Store(true) + } + dstBackend.Config.Handler.ServeHTTP(w, r) + })) + defer dst.Close() + + ctx := context.Background() + oldCli, _ := s3client.New(ctx, config.Endpoint{Endpoint: src.URL, Region: "us-east-1", AccessKey: "a", SecretKey: "b"}) + newCli, _ := s3client.New(ctx, config.Endpoint{Endpoint: dst.URL, Region: "us-east-1", AccessKey: "a", SecretKey: "b"}) + + if _, err := differ.Run(ctx, oldCli, newCli, "photos", differ.Options{Workers: 1, ReportExtra: false, TempDir: spoolTmp, Writer: io.Discard}); err != nil { + t.Fatal(err) + } + if sawOSTmp.Load() || sawSpoolTmp.Load() { + t.Fatalf("differ.Run(ReportExtra=false) should not create a temp DB: osTmp=%v spoolTmp=%v", sawOSTmp.Load(), sawSpoolTmp.Load()) + } + + if _, err := differ.Run(ctx, oldCli, newCli, "photos", differ.Options{Workers: 1, ReportExtra: true, TempDir: spoolTmp, Writer: io.Discard}); err != nil { + t.Fatal(err) + } + if sawOSTmp.Load() || !sawSpoolTmp.Load() { + t.Fatalf("differ.Run(ReportExtra=true) should use TempDir (spool_dir): osTmp=%v spoolTmp=%v", sawOSTmp.Load(), sawSpoolTmp.Load()) + } +} + +func TestLostMultipartCommitResponseReturningNoSuchUploadReconcilesOnFirstRun(t *testing.T) { + const partSize = 5 * 1024 * 1024 + payload := bytes.Repeat([]byte("M"), partSize+16) + now := time.Date(2026, 11, 25, 0, 0, 0, 0, time.UTC) + src := fakes3.NewWithObjects(t, "photos", map[string][]byte{"big.bin": payload}, now) + defer src.Close() + dstBackend := fakes3.New(t) + defer dstBackend.Close() + + var completeAttempts, abortCalls atomic.Int32 + dst := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete && r.URL.Query().Get("uploadId") != "" { + abortCalls.Add(1) + } + if r.Method == http.MethodPost && r.URL.Query().Get("uploadId") != "" { + if completeAttempts.Add(1) == 1 { + rec := httptest.NewRecorder() + dstBackend.Config.Handler.ServeHTTP(rec, r) + conn, _, err := w.(http.Hijacker).Hijack() + if err == nil { + _ = conn.Close() + return + } + } + } + dstBackend.Config.Handler.ServeHTTP(w, r) + })) + defer dst.Close() + + ctx := context.Background() + dir := t.TempDir() + dbPath := filepath.Join(dir, "state.db") + st, err := store.Open(dbPath, "photos") + if err != nil { + t.Fatal(err) + } + defer st.Close() + oldCli, _ := s3client.New(ctx, config.Endpoint{Endpoint: src.URL, Region: "us-east-1", AccessKey: "a", SecretKey: "b"}) + newCli, _ := s3client.New(ctx, config.Endpoint{Endpoint: dst.URL, Region: "us-east-1", AccessKey: "a", SecretKey: "b"}) + newCli = s3.New(newCli.Options(), func(o *s3.Options) { + o.Retryer = retry.NewStandard(func(ro *retry.StandardOptions) { ro.MaxAttempts = 2; ro.MaxBackoff = time.Millisecond }) + }) + if _, err := scanner.Run(ctx, oldCli, "photos", st); err != nil { + t.Fatal(err) + } + cfg := &config.Config{ + SourceFrozen: true, Bucket: "photos", DBPath: dbPath, ConflictLog: filepath.Join(dir, "conflict.log"), + SpoolDir: dir, Workers: 1, MultipartThreshold: partSize, MultipartPartSize: partSize, MultipartConcurrency: 1, + } + m, err := migrator.New(cfg, oldCli, newCli, st) + if err != nil { + t.Fatal(err) + } + defer m.Close() + + if err := m.Run(ctx); err != nil { + t.Fatalf("expected lost-response multipart commit to reconcile on first run, got: %v", err) + } + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if completeAttempts.Load() != 2 || abortCalls.Load() != 0 || counts.Done != 1 || counts.Failed != 0 || counts.Conflict != 0 { + t.Fatalf("unexpected state: completeAttempts=%d aborts=%d counts=%+v", completeAttempts.Load(), abortCalls.Load(), counts) + } +} + +func TestMultipartOversizedForSpoolBudgetFailsBeforeRemoteCreate(t *testing.T) { + const partSize = 5 * 1024 * 1024 + payload := bytes.Repeat([]byte("P"), partSize+10) + src := fakes3.NewWithObjects(t, "photos", map[string][]byte{"large.bin": payload}, time.Now()) + defer src.Close() + dstBackend := fakes3.New(t) + defer dstBackend.Close() + + var createMultipartCalls, abortCalls atomic.Int32 + dst := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && r.URL.Query().Has("uploads") { + createMultipartCalls.Add(1) + } + if r.Method == http.MethodDelete && r.URL.Query().Get("uploadId") != "" { + abortCalls.Add(1) + } + dstBackend.Config.Handler.ServeHTTP(w, r) + })) + defer dst.Close() + + dir := t.TempDir() + cfgPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, cfgPath, src.URL, dst.URL, filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, ` +bucket: photos +workers: 1 +multipart_threshold: 5242880 +multipart_part_size: 5242880 +spool_max_bytes: 1048576 +`) + if _, err := execRoot(t, "run", "-c", cfgPath); err == nil { + t.Fatal("expected run to fail when spool_max_bytes < multipart_part_size + 1") + } + if createMultipartCalls.Load() != 0 || abortCalls.Load() != 0 { + t.Fatalf("expected 0 remote CreateMultipartUpload/Abort calls, got create=%d abort=%d", createMultipartCalls.Load(), abortCalls.Load()) + } +} diff --git a/cmd/helptext.go b/cmd/helptext.go index 00b79db..20ff386 100644 --- a/cmd/helptext.go +++ b/cmd/helptext.go @@ -1,6 +1,6 @@ package cmd -const Version = "0.2.0" +var Version = "0.2.0" const rootShort = `Safe one-way S3 migration / 安全的单向 S3 迁移` diff --git a/cmd/root.go b/cmd/root.go index bd124e9..a2f5dfe 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -259,21 +259,7 @@ func diffCmd() *cobra.Command { Long: diffLong, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - var jsonl *os.File - if jsonlPath != "" { - var err error - jsonl, err = os.OpenFile(jsonlPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) - if err != nil { - return fmt.Errorf("create diff JSONL: %w", err) - } - } - runErr := runDiffBuckets(cmd, diffExtra, strict, jsonl) - if jsonl != nil { - if err := jsonl.Close(); err != nil { - return errors.Join(runErr, fmt.Errorf("close diff JSONL: %w", err)) - } - } - return runErr + return runDiffBuckets(cmd, diffExtra, strict, jsonlPath) }, } c.Flags().StringVar(&jsonlPath, "issues-jsonl", "", "write all differences to a new JSONL file / 将全部差异写入新的 JSONL 文件") @@ -282,7 +268,7 @@ func diffCmd() *cobra.Command { return c } -func runDiffBuckets(cmd *cobra.Command, diffExtra, strict bool, jsonl *os.File) error { +func runDiffBuckets(cmd *cobra.Command, diffExtra, strict bool, jsonlPath string) error { cfg, err := loadConfig(cmd) if err != nil { return err @@ -290,6 +276,21 @@ func runDiffBuckets(cmd *cobra.Command, diffExtra, strict bool, jsonl *os.File) if err := cfg.ValidatePair(); err != nil { return err } + var jsonl *os.File + if jsonlPath != "" { + if dir := filepath.Dir(jsonlPath); dir != "" && dir != "." { + if err := os.MkdirAll(dir, 0o755); err != nil { + return fmt.Errorf("create diff JSONL dir %s: %w", dir, err) + } + } + jsonl, err = os.OpenFile(jsonlPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return fmt.Errorf("create diff JSONL: %w", err) + } + defer func() { + _ = jsonl.Close() + }() + } ctx, cancel := signalCtx(cmd.Context()) defer cancel() pool := cfg.MaxInFlight() @@ -337,6 +338,7 @@ func runDiffBuckets(cmd *cobra.Command, diffExtra, strict bool, jsonl *os.File) res, err := differ.Run(ctx, oldCli, newCli, name, differ.Options{ Workers: cfg.Workers, ReportExtra: reportExtra, + TempDir: cfg.SpoolDir, Writer: os.Stdout, IssuesJSONL: issueWriter, }) @@ -359,6 +361,7 @@ func runDiffBuckets(cmd *cobra.Command, diffExtra, strict bool, jsonl *os.File) res, err := differ.RunExtraBucket(ctx, newCli, name, differ.Options{ Workers: cfg.Workers, ReportExtra: true, + TempDir: cfg.SpoolDir, Writer: os.Stdout, IssuesJSONL: issueWriter, }) @@ -374,10 +377,19 @@ func runDiffBuckets(cmd *cobra.Command, diffExtra, strict bool, jsonl *os.File) failed = append(failed, name) } } + var runErr error if len(failed) > 0 { - return fmt.Errorf("failed buckets / 失败的桶: %s", strings.Join(failed, ", ")) + runErr = fmt.Errorf("failed buckets / 失败的桶: %s", strings.Join(failed, ", ")) } - return nil + if jsonl != nil { + if err := jsonl.Sync(); err != nil { + return errors.Join(runErr, fmt.Errorf("sync diff JSONL: %w", err)) + } + if err := jsonl.Close(); err != nil { + return errors.Join(runErr, fmt.Errorf("close diff JSONL: %w", err)) + } + } + return runErr } func statusCmd() *cobra.Command { @@ -571,35 +583,77 @@ func statusTargets(cfg *config.Config) ([]dbTarget, error) { if !cfg.AllBuckets() { return []dbTarget{{bucket: cfg.Bucket, path: cfg.DBPath}}, nil } - matches, err := filepath.Glob(cfg.DBPathFor("*")) - if err != nil { - return nil, err + rawDir := filepath.Dir(cfg.DBPath) + readDir := rawDir + if readDir == "" { + readDir = "." + } + ext := filepath.Ext(cfg.DBPath) + stem := strings.TrimSuffix(filepath.Base(cfg.DBPath), ext) + if ext == "" { + ext = ".db" } - if _, err := os.Stat(cfg.DBPath); err == nil { - matches = append(matches, cfg.DBPath) - } else if !os.IsNotExist(err) { + prefix := stem + "-" + + entries, err := os.ReadDir(readDir) + if err != nil && !os.IsNotExist(err) { return nil, err } - var out []dbTarget - seen := make(map[string]bool) - for _, path := range matches { - if seen[path] { + var matches []string + for _, entry := range entries { + if entry.IsDir() { continue } - seen[path] = true + name := entry.Name() + if strings.HasPrefix(name, prefix) && strings.HasSuffix(name, ext) && len(name) > len(prefix)+len(ext) { + if rawDir == "" || rawDir == "." { + matches = append(matches, name) + } else { + matches = append(matches, filepath.Join(rawDir, name)) + } + } + } + + var out []dbTarget + seenPaths := make(map[string]bool) + seenBuckets := make(map[string]bool) + inspect := func(path string, skipDuplicateBucket bool) error { + clean := filepath.Clean(path) + if seenPaths[clean] { + return nil + } + seenPaths[clean] = true st, err := store.OpenExisting(path) if err != nil { - return nil, fmt.Errorf("read state %s: %w", path, err) + return fmt.Errorf("read state %s: %w", path, err) } name, readErr := st.BoundBucket() closeErr := st.Close() if err := errors.Join(readErr, closeErr); err != nil { - return nil, err + return err } if name == "" { - return nil, fmt.Errorf("state %s has no bound bucket", path) + return fmt.Errorf("state %s has no bound bucket", path) } + if skipDuplicateBucket && seenBuckets[name] { + return nil + } + seenBuckets[name] = true out = append(out, dbTarget{bucket: name, path: path}) + return nil + } + + for _, path := range matches { + if err := inspect(path, false); err != nil { + return nil, err + } + } + if info, err := os.Stat(cfg.DBPath); err == nil && !info.IsDir() { + if err := inspect(cfg.DBPath, true); err != nil { + return nil, err + } + } else if err != nil && !os.IsNotExist(err) { + return nil, err } return out, nil } diff --git a/internal/cluster/objects.go b/internal/cluster/objects.go index cec1e9a..585fda8 100644 --- a/internal/cluster/objects.go +++ b/internal/cluster/objects.go @@ -16,6 +16,9 @@ func WalkObjects(ctx context.Context, cli *s3.Client, bucket string, visit func( input := &s3.ListObjectsV2Input{Bucket: aws.String(bucket), EncodingType: types.EncodingTypeUrl} seenTokens := make(map[string]struct{}) for { + if err := ctx.Err(); err != nil { + return err + } page, err := cli.ListObjectsV2(ctx, input) if err != nil { return err @@ -26,6 +29,13 @@ func WalkObjects(ctx context.Context, cli *s3.Client, bucket string, visit func( if page.IsTruncated == nil { return fmt.Errorf("incomplete listing for bucket %q: missing IsTruncated", bucket) } + if aws.ToBool(page.IsTruncated) { + next := aws.ToString(page.NextContinuationToken) + if _, exists := seenTokens[next]; next == "" || exists { + return fmt.Errorf("truncated listing for bucket %q has a missing or repeated continuation token", bucket) + } + seenTokens[next] = struct{}{} + } for i := range page.Contents { obj := &page.Contents[i] if aws.ToString(obj.Key) == "" || obj.Size == nil || *obj.Size < 0 { @@ -47,11 +57,6 @@ func WalkObjects(ctx context.Context, cli *s3.Client, bucket string, visit func( if !aws.ToBool(page.IsTruncated) { return nil } - next := aws.ToString(page.NextContinuationToken) - if _, exists := seenTokens[next]; next == "" || exists { - return fmt.Errorf("truncated listing for bucket %q has a missing or repeated continuation token", bucket) - } - seenTokens[next] = struct{}{} input.ContinuationToken = page.NextContinuationToken } } diff --git a/internal/config/config.go b/internal/config/config.go index dff398e..b439bbc 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -122,6 +122,7 @@ func LoadForCLI(path string, opt CLIReadOptions) (*Config, error) { if err := c.applyEnvWithOptions(opt); err != nil { return nil, err } + c.normalize() c.applyDefaults() c.normalize() if err := c.validateMultipartPartSize(); err != nil { @@ -130,10 +131,6 @@ func LoadForCLI(path string, opt CLIReadOptions) (*Config, error) { return c, nil } -func (c *Config) applyEnv() error { - return c.applyEnvWithOptions(CLIReadOptions{}) -} - func (c *Config) applyEnvWithOptions(opt CLIReadOptions) error { c.Old.Endpoint = envOr(c.Old.Endpoint, "OLD_ENDPOINT") c.Old.AccessKey = envOr(c.Old.AccessKey, "OLD_AK") @@ -154,12 +151,12 @@ func (c *Config) applyEnvWithOptions(opt CLIReadOptions) error { c.SourceFrozen = v } } - sharedRegion := os.Getenv("REGION") + sharedRegion := strings.TrimSpace(os.Getenv("REGION")) if sharedRegion != "" { - if c.Old.Region == "" { + if strings.TrimSpace(c.Old.Region) == "" { c.Old.Region = sharedRegion } - if c.New.Region == "" { + if strings.TrimSpace(c.New.Region) == "" { c.New.Region = sharedRegion } } @@ -221,7 +218,7 @@ func applyByteRateEnv(dst *ByteRate, key string) error { } func envOr(current, key string) string { - if value := os.Getenv(key); value != "" { + if value := strings.TrimSpace(os.Getenv(key)); value != "" { return value } return current @@ -265,12 +262,17 @@ func (c *Config) applyDefaults() { func (c *Config) normalize() { c.Bucket = strings.TrimSpace(c.Bucket) + c.DBPath = strings.TrimSpace(c.DBPath) + c.ConflictLog = strings.TrimSpace(c.ConflictLog) + c.SpoolDir = strings.TrimSpace(c.SpoolDir) c.Old.Endpoint = strings.TrimRight(strings.TrimSpace(c.Old.Endpoint), "/") c.New.Endpoint = strings.TrimRight(strings.TrimSpace(c.New.Endpoint), "/") c.Old.AccessKey = strings.TrimSpace(c.Old.AccessKey) c.Old.SecretKey = strings.TrimSpace(c.Old.SecretKey) + c.Old.SessionToken = strings.TrimSpace(c.Old.SessionToken) c.New.AccessKey = strings.TrimSpace(c.New.AccessKey) c.New.SecretKey = strings.TrimSpace(c.New.SecretKey) + c.New.SessionToken = strings.TrimSpace(c.New.SessionToken) c.Old.Region = strings.TrimSpace(c.Old.Region) c.New.Region = strings.TrimSpace(c.New.Region) } @@ -329,12 +331,41 @@ func (c *Config) ValidatePair() error { if err := validateEndpoint(c.New.Endpoint); err != nil { return err } - if strings.EqualFold(c.Old.Endpoint, c.New.Endpoint) { + if NormalizeEndpoint(c.Old.Endpoint) == NormalizeEndpoint(c.New.Endpoint) { return fmt.Errorf("source and target endpoints must be different") } return nil } +// NormalizeEndpoint canonicalizes scheme, host casing, default HTTP/HTTPS ports, +// and trailing slashes so equivalent URLs compare and bind identically. +func NormalizeEndpoint(endpoint string) string { + endpoint = strings.TrimRight(strings.TrimSpace(endpoint), "/") + u, err := url.Parse(endpoint) + if err != nil || u.Host == "" { + return endpoint + } + u.Scheme = strings.ToLower(u.Scheme) + host := strings.ToLower(u.Hostname()) + port := u.Port() + if (u.Scheme == "http" && port == "80") || (u.Scheme == "https" && port == "443") { + port = "" + } + if strings.Contains(host, ":") { + host = "[" + host + "]" + } + if port != "" { + u.Host = host + ":" + port + } else { + u.Host = host + } + u.User = nil + if u.Path == "/" { + u.Path = "" + } + return strings.TrimRight(u.String(), "/") +} + func validateEndpoint(endpoint string) error { u, err := url.Parse(endpoint) if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") { diff --git a/internal/differ/differ.go b/internal/differ/differ.go index 81e456f..b50cb1c 100644 --- a/internal/differ/differ.go +++ b/internal/differ/differ.go @@ -9,8 +9,6 @@ import ( "io" "net/url" "os" - "path/filepath" - "runtime" "strings" "sync" @@ -21,6 +19,7 @@ import ( "github.com/rustfs/migration/internal/cluster" "github.com/rustfs/migration/internal/config" "github.com/rustfs/migration/internal/s3client" + "github.com/rustfs/migration/internal/store" _ "modernc.org/sqlite" ) @@ -51,7 +50,10 @@ func (r Result) HasGaps() bool { type Options struct { Workers int ReportExtra bool - Writer io.Writer + // TempDir overrides the directory for the temporary SQLite index used when + // ReportExtra is true (e.g. spool_dir). Empty uses the OS temp directory. + TempDir string + Writer io.Writer // IssuesJSONL receives every issue, one JSON object per line. The caller owns it. IssuesJSONL io.Writer } @@ -82,37 +84,68 @@ func Run(ctx context.Context, oldCli, newCli *s3.Client, bucket string, opt Opti return res, fmt.Errorf("head target bucket %q: %w", bucket, err) } - file, err := os.CreateTemp("", "migration-diff-*.db") - if err != nil { - return res, err - } - tmp := file.Name() - defer func() { - _ = os.Remove(tmp) - _ = os.Remove(tmp + "-wal") - _ = os.Remove(tmp + "-shm") - }() - if err := file.Chmod(0o600); err != nil { - _ = file.Close() - return res, err - } - if err := file.Close(); err != nil { - return res, err - } - db, err := sql.Open("sqlite", sqliteURI(tmp, "rwc", "journal_mode(WAL)", "busy_timeout(5000)")) - if err != nil { - return res, err - } - defer db.Close() - db.SetMaxOpenConns(1) - if _, err := db.ExecContext(ctx, `CREATE TABLE src (key TEXT PRIMARY KEY, size INTEGER NOT NULL, etag TEXT)`); err != nil { - return res, err + var db *sql.DB + var keyBatch []string + flushKeys := func(ctx context.Context) error { + if db == nil || len(keyBatch) == 0 { + return nil + } + tx, err := db.BeginTx(ctx, nil) + if err != nil { + return err + } + stmt, err := tx.PrepareContext(ctx, `INSERT OR IGNORE INTO src(key) VALUES(?)`) + if err != nil { + _ = tx.Rollback() + return err + } + defer stmt.Close() + for _, k := range keyBatch { + if _, err := stmt.ExecContext(ctx, k); err != nil { + _ = tx.Rollback() + return err + } + } + if err := tx.Commit(); err != nil { + return err + } + keyBatch = keyBatch[:0] + return nil } - insert, err := db.PrepareContext(ctx, `INSERT OR IGNORE INTO src(key, size, etag) VALUES(?,?,?)`) - if err != nil { - return res, err + if opt.ReportExtra { + if opt.TempDir != "" { + if err := os.MkdirAll(opt.TempDir, 0o755); err != nil { + return res, fmt.Errorf("create diff temp dir %s: %w", opt.TempDir, err) + } + } + file, err := os.CreateTemp(opt.TempDir, "migration-diff-*.db") + if err != nil { + return res, err + } + tmp := file.Name() + defer func() { + _ = os.Remove(tmp) + _ = os.Remove(tmp + "-wal") + _ = os.Remove(tmp + "-shm") + }() + if err := file.Chmod(0o600); err != nil { + _ = file.Close() + return res, err + } + if err := file.Close(); err != nil { + return res, err + } + db, err = sql.Open("sqlite", store.SQLiteURI(tmp, "rwc", "journal_mode(WAL)", "busy_timeout(5000)")) + if err != nil { + return res, err + } + defer db.Close() + db.SetMaxOpenConns(1) + if _, err := db.ExecContext(ctx, `CREATE TABLE src (key TEXT PRIMARY KEY) WITHOUT ROWID`); err != nil { + return res, err + } + keyBatch = make([]string, 0, 500) } - defer insert.Close() ctx, cancel := context.WithCancel(ctx) defer cancel() @@ -198,44 +231,32 @@ func Run(ctx context.Context, oldCli, newCli *s3.Client, bucket string, opt Opti }() } - p := s3.NewListObjectsV2Paginator(oldCli, &s3.ListObjectsV2Input{Bucket: awsv2.String(bucket), EncodingType: types.EncodingTypeUrl}) - seenTokens := make(map[string]struct{}) -feed: - for p.HasMorePages() { - page, err := p.NextPage(ctx) - if err != nil { - fail(fmt.Errorf("list source: %w", err)) - break - } - if name := awsv2.ToString(page.Name); name != "" && name != bucket { - fail(fmt.Errorf("list source bucket mismatch: requested %q, returned %q", bucket, name)) - break - } - if err := validatePageToken(page, seenTokens); err != nil { - fail(err) - break - } - for _, obj := range page.Contents { - key, err := decodeKey(awsv2.ToString(obj.Key), page.EncodingType) - if err != nil { - fail(err) - break feed - } - if key == "" || obj.Size == nil || *obj.Size < 0 { - fail(fmt.Errorf("source listing has empty key or invalid size: key=%q", key)) - break feed - } + walkErr := cluster.WalkObjects(ctx, oldCli, bucket, func(contents []types.Object) error { + for _, obj := range contents { + key := awsv2.ToString(obj.Key) item := listed{key: key, size: *obj.Size, etag: awsv2.ToString(obj.ETag)} - if _, err := insert.ExecContext(ctx, item.key, item.size, item.etag); err != nil { - fail(fmt.Errorf("record source %q: %w", key, err)) - break feed + if opt.ReportExtra { + keyBatch = append(keyBatch, item.key) + if len(keyBatch) >= 500 { + if err := flushKeys(ctx); err != nil { + return fmt.Errorf("record source %q: %w", key, err) + } + } } select { case <-ctx.Done(): - break feed + return ctx.Err() case jobs <- item: } } + return nil + }) + if walkErr != nil { + fail(fmt.Errorf("list source: %w", walkErr)) + } else if opt.ReportExtra { + if err := flushKeys(ctx); err != nil { + fail(fmt.Errorf("record source batch: %w", err)) + } } close(jobs) wg.Wait() @@ -247,37 +268,23 @@ feed: } if opt.ReportExtra { - tp := s3.NewListObjectsV2Paginator(newCli, &s3.ListObjectsV2Input{Bucket: awsv2.String(bucket), EncodingType: types.EncodingTypeUrl}) - seenTokens := make(map[string]struct{}) - for tp.HasMorePages() { - page, err := tp.NextPage(ctx) - if err != nil { - return res, fmt.Errorf("list target: %w", err) - } - if name := awsv2.ToString(page.Name); name != "" && name != bucket { - return res, fmt.Errorf("list target bucket mismatch: requested %q, returned %q", bucket, name) - } - if err := validatePageToken(page, seenTokens); err != nil { - return res, err - } - for _, obj := range page.Contents { - key, err := decodeKey(awsv2.ToString(obj.Key), page.EncodingType) - if err != nil { - return res, err - } - if key == "" { - return res, fmt.Errorf("target listing contains empty key") - } + err := cluster.WalkObjects(ctx, newCli, bucket, func(contents []types.Object) error { + for _, obj := range contents { + key := awsv2.ToString(obj.Key) var n int if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM src WHERE key = ?`, key).Scan(&n); err != nil { - return res, err + return err } if n == 0 { if err := record(&mu, &res, opt.IssuesJSONL, Issue{Key: key, Kind: "extra", Detail: "only on target"}); err != nil { - return res, err + return err } } } + return nil + }) + if err != nil { + return res, fmt.Errorf("list target: %w", err) } } return res, printResult(opt.Writer, res) @@ -294,31 +301,17 @@ func RunExtraBucket(ctx context.Context, newCli *s3.Client, bucket string, opt O return res, fmt.Errorf("head target bucket %q: %w", bucket, err) } var mu sync.Mutex - tp := s3.NewListObjectsV2Paginator(newCli, &s3.ListObjectsV2Input{Bucket: awsv2.String(bucket), EncodingType: types.EncodingTypeUrl}) - seenTokens := make(map[string]struct{}) - for tp.HasMorePages() { - page, err := tp.NextPage(ctx) - if err != nil { - return res, fmt.Errorf("list target: %w", err) - } - if name := awsv2.ToString(page.Name); name != "" && name != bucket { - return res, fmt.Errorf("list target bucket mismatch: requested %q, returned %q", bucket, name) - } - if err := validatePageToken(page, seenTokens); err != nil { - return res, err - } - for _, obj := range page.Contents { - key, err := decodeKey(awsv2.ToString(obj.Key), page.EncodingType) - if err != nil { - return res, err - } - if key == "" { - return res, fmt.Errorf("target listing contains empty key") - } + err := cluster.WalkObjects(ctx, newCli, bucket, func(contents []types.Object) error { + for _, obj := range contents { + key := awsv2.ToString(obj.Key) if err := record(&mu, &res, opt.IssuesJSONL, Issue{Key: key, Kind: "extra", Detail: "only on target (bucket missing on source)"}); err != nil { - return res, err + return err } } + return nil + }) + if err != nil { + return res, fmt.Errorf("list target: %w", err) } if res.Extra == 0 { if err := record(&mu, &res, opt.IssuesJSONL, Issue{Key: "", Kind: "extra", Detail: "bucket only on target"}); err != nil { @@ -328,41 +321,6 @@ func RunExtraBucket(ctx context.Context, newCli *s3.Client, bucket string, opt O return res, printResult(opt.Writer, res) } -func sqliteURI(path, mode string, pragmas ...string) string { - abs, err := filepath.Abs(path) - if err == nil { - path = abs - } - u := url.URL{Scheme: "file", Path: sqliteURIPath(filepath.ToSlash(path), runtime.GOOS == "windows")} - q := url.Values{"mode": {mode}} - for _, pragma := range pragmas { - q.Add("_pragma", pragma) - } - u.RawQuery = q.Encode() - return u.String() -} - -func sqliteURIPath(path string, windows bool) string { - if windows && len(path) >= 2 && path[1] == ':' && !strings.HasPrefix(path, "/") { - return "/" + path - } - return path -} - -func validatePageToken(page *s3.ListObjectsV2Output, seenTokens map[string]struct{}) error { - if page.IsTruncated == nil { - return fmt.Errorf("incomplete object listing: missing IsTruncated") - } - if awsv2.ToBool(page.IsTruncated) { - next := awsv2.ToString(page.NextContinuationToken) - if _, exists := seenTokens[next]; next == "" || exists { - return fmt.Errorf("incomplete object listing: truncated page has missing or repeated continuation token") - } - seenTokens[next] = struct{}{} - } - return nil -} - func decodeKey(key string, encoding types.EncodingType) (string, error) { if encoding != types.EncodingTypeUrl { return key, nil diff --git a/internal/fakes3/fakes3.go b/internal/fakes3/fakes3.go index 117a405..2648564 100644 --- a/internal/fakes3/fakes3.go +++ b/internal/fakes3/fakes3.go @@ -19,9 +19,13 @@ import ( ) type Metadata struct { - ContentEncoding string - ContentType string - Metadata map[string]string + CacheControl string + ContentDisposition string + ContentEncoding string + ContentLanguage string + ContentType string + Expires string + Metadata map[string]string } type object struct { @@ -677,12 +681,24 @@ func md5hex(value []byte) string { } func writeMetadataHeaders(w http.ResponseWriter, meta Metadata) { + if meta.CacheControl != "" { + w.Header().Set("Cache-Control", meta.CacheControl) + } + if meta.ContentDisposition != "" { + w.Header().Set("Content-Disposition", meta.ContentDisposition) + } if meta.ContentEncoding != "" { w.Header().Set("Content-Encoding", meta.ContentEncoding) } + if meta.ContentLanguage != "" { + w.Header().Set("Content-Language", meta.ContentLanguage) + } if meta.ContentType != "" { w.Header().Set("Content-Type", meta.ContentType) } + if meta.Expires != "" { + w.Header().Set("Expires", meta.Expires) + } for key, value := range meta.Metadata { w.Header().Set("X-Amz-Meta-"+key, value) } @@ -690,9 +706,13 @@ func writeMetadataHeaders(w http.ResponseWriter, meta Metadata) { func readMetadataHeaders(r *http.Request) Metadata { meta := Metadata{ - ContentType: r.Header.Get("Content-Type"), - ContentEncoding: r.Header.Get("Content-Encoding"), - Metadata: map[string]string{}, + CacheControl: r.Header.Get("Cache-Control"), + ContentDisposition: r.Header.Get("Content-Disposition"), + ContentEncoding: r.Header.Get("Content-Encoding"), + ContentLanguage: r.Header.Get("Content-Language"), + ContentType: r.Header.Get("Content-Type"), + Expires: r.Header.Get("Expires"), + Metadata: map[string]string{}, } if meta.ContentType == "" { meta.ContentType = "application/octet-stream" diff --git a/internal/migrator/migrator.go b/internal/migrator/migrator.go index 22e72f1..042026c 100644 --- a/internal/migrator/migrator.go +++ b/internal/migrator/migrator.go @@ -7,7 +7,6 @@ import ( "fmt" "io" "log" - "maps" "math" "os" "path/filepath" @@ -22,6 +21,7 @@ import ( "github.com/aws/aws-sdk-go-v2/service/s3" s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" "github.com/aws/smithy-go" + smithyhttp "github.com/aws/smithy-go/transport/http" "github.com/rustfs/migration/internal/config" "github.com/rustfs/migration/internal/ratelimit" @@ -61,9 +61,37 @@ type objectAttrs struct { ContentLanguage *string ContentType *string Expires *time.Time + ExpiresString *string Metadata map[string]string } +func (a objectAttrs) effectiveContentType() *string { + return awsv2.String(s3client.EffectiveContentType(a.ContentType)) +} + +func (a objectAttrs) expiresAPIOptions() []func(*s3.Options) { + if a.Expires != nil || strings.TrimSpace(awsv2.ToString(a.ExpiresString)) == "" { + return nil + } + raw := strings.TrimSpace(*a.ExpiresString) + return []func(*s3.Options){func(o *s3.Options) { + o.APIOptions = append(o.APIOptions, smithyhttp.SetHeaderValue("Expires", raw)) + }} +} + +func (a objectAttrs) toHeadOutput() *s3.HeadObjectOutput { + return &s3.HeadObjectOutput{ + CacheControl: a.CacheControl, + ContentDisposition: a.ContentDisposition, + ContentEncoding: a.ContentEncoding, + ContentLanguage: a.ContentLanguage, + ContentType: a.ContentType, + Expires: a.Expires, + ExpiresString: a.ExpiresString, + Metadata: a.Metadata, + } +} + func New(cfg *config.Config, oldCli, newCli *s3.Client, st *store.Store) (*Migrator, error) { return NewForBucket(cfg, cfg.Bucket, oldCli, newCli, st) } @@ -237,6 +265,13 @@ type persistenceError struct{ err error } func (e *persistenceError) Error() string { return e.err.Error() } func (e *persistenceError) Unwrap() error { return e.err } +// completeMultipartError marks errors returned specifically by CompleteMultipartUpload, +// distinguishing a consumed upload ID on commit retry from an earlier part failure. +type completeMultipartError struct{ err error } + +func (e *completeMultipartError) Error() string { return e.err.Error() } +func (e *completeMultipartError) Unwrap() error { return e.err } + type sourceSnapshot struct { attrs objectAttrs etag string @@ -292,9 +327,13 @@ func (m *Migrator) migrateObject(ctx context.Context, obj store.Object) error { } if err != nil { var api smithy.APIError - if errors.As(err, &api) && api.ErrorCode() == "PreconditionFailed" { - // A concurrent writer won the atomic create. Only classify a - // destination conditional write, never a source If-Match failure. + var completeErr *completeMultipartError + isPreconditionFailed := errors.As(err, &api) && api.ErrorCode() == "PreconditionFailed" + isLostComplete := errors.As(err, &completeErr) && errors.As(err, &api) && api.ErrorCode() == "NoSuchUpload" + if isPreconditionFailed || isLostComplete { + // A concurrent writer won the atomic create, or a successful commit + // lost its response and its SDK retry received 412 / NoSuchUpload. + // Never classify a source If-Match failure here. var source *sourceReadError if !errors.As(err, &source) { target, herr := m.NewCli.HeadObject(ctx, &s3.HeadObjectInput{Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key)}) @@ -302,8 +341,6 @@ func (m *Migrator) migrateObject(ctx context.Context, obj store.Object) error { if checkErr := m.checkSourceBeforeCommit(ctx, obj, snapshot); checkErr != nil { return checkErr } - // A successful commit may have lost its response. The SDK - // retries If-None-Match and receives 412 for our own bytes. return m.reconcileExistingTarget(ctx, obj, snapshot, target) } } @@ -395,7 +432,8 @@ func (m *Migrator) sourceSnapshot(ctx context.Context, obj store.Object) (source } return sourceSnapshot{etag: etag, versionID: out.VersionId, size: obj.Size, attrs: objectAttrs{ CacheControl: out.CacheControl, ContentDisposition: out.ContentDisposition, ContentEncoding: out.ContentEncoding, - ContentLanguage: out.ContentLanguage, ContentType: out.ContentType, Expires: out.Expires, Metadata: copyMetadata(out.Metadata), + ContentLanguage: out.ContentLanguage, ContentType: out.ContentType, Expires: out.Expires, ExpiresString: out.ExpiresString, + Metadata: copyMetadata(out.Metadata), }}, nil } @@ -470,8 +508,8 @@ func (m *Migrator) copySingle(ctx context.Context, obj store.Object, snap source _, err = m.NewCli.PutObject(ctx, &s3.PutObjectInput{ Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key), Body: tmp, ContentLength: awsv2.Int64(obj.Size), IfNoneMatch: awsv2.String("*"), CacheControl: attrs.CacheControl, ContentDisposition: attrs.ContentDisposition, ContentEncoding: attrs.ContentEncoding, - ContentLanguage: attrs.ContentLanguage, ContentType: attrs.ContentType, Expires: attrs.Expires, Metadata: attrs.Metadata, - }) + ContentLanguage: attrs.ContentLanguage, ContentType: attrs.effectiveContentType(), Expires: attrs.Expires, Metadata: attrs.Metadata, + }, attrs.expiresAPIOptions()...) if err != nil { return fmt.Errorf("put target: %w", err) } @@ -479,25 +517,7 @@ func (m *Migrator) copySingle(ctx context.Context, obj store.Object, snap source } func attributesEqual(attrs objectAttrs, head *s3.HeadObjectOutput) bool { - if head == nil { - return false - } - for _, pair := range [][2]*string{ - {attrs.CacheControl, head.CacheControl}, {attrs.ContentDisposition, head.ContentDisposition}, - {attrs.ContentEncoding, head.ContentEncoding}, {attrs.ContentLanguage, head.ContentLanguage}, - {attrs.ContentType, head.ContentType}, - } { - if awsv2.ToString(pair[0]) != awsv2.ToString(pair[1]) { - return false - } - } - if (attrs.Expires == nil) != (head.Expires == nil) { - return false - } - if attrs.Expires != nil && !attrs.Expires.Equal(*head.Expires) { - return false - } - return maps.Equal(attrs.Metadata, head.Metadata) + return s3client.MetadataEqual(attrs.toHeadOutput(), head) } func (m *Migrator) verifyTarget(ctx context.Context, obj store.Object, sourceDigest [32]byte, attrs objectAttrs) error { @@ -534,11 +554,18 @@ func (m *Migrator) copyMultipart(ctx context.Context, obj store.Object, snap sou if partSize > 5<<30 { return fmt.Errorf("multipart part size exceeds S3 maximum of 5 GiB") } + firstPartLen := partSize + if firstPartLen > obj.Size { + firstPartLen = obj.Size + } + if firstPartLen+1 > m.spoolBudget.limit { + return fmt.Errorf("spool reservation %d exceeds spool_max_bytes %d; increase budget or reduce part size", firstPartLen+1, m.spoolBudget.limit) + } attrs := snap.attrs create, err := m.NewCli.CreateMultipartUpload(ctx, &s3.CreateMultipartUploadInput{ Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key), CacheControl: attrs.CacheControl, ContentDisposition: attrs.ContentDisposition, - ContentEncoding: attrs.ContentEncoding, ContentLanguage: attrs.ContentLanguage, ContentType: attrs.ContentType, Expires: attrs.Expires, Metadata: attrs.Metadata, - }) + ContentEncoding: attrs.ContentEncoding, ContentLanguage: attrs.ContentLanguage, ContentType: attrs.effectiveContentType(), Expires: attrs.Expires, Metadata: attrs.Metadata, + }, attrs.expiresAPIOptions()...) if err != nil { return fmt.Errorf("create multipart target: %w", err) } @@ -640,7 +667,13 @@ partLoop: } _, err = m.NewCli.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key), UploadId: awsv2.String(uploadID), MultipartUpload: &s3types.CompletedMultipartUpload{Parts: parts}, IfNoneMatch: awsv2.String("*")}) if err != nil { - return fmt.Errorf("complete multipart target: %w", err) + var api smithy.APIError + if errors.As(err, &api) && api.ErrorCode() == "NoSuchUpload" { + // Upload session no longer exists on server (typically consumed by a prior + // attempt whose response was lost); skip redundant AbortMultipartUpload. + committed = true + } + return &completeMultipartError{fmt.Errorf("complete multipart target: %w", err)} } committed = true return m.verifyTarget(ctx, obj, digest, snap.attrs) diff --git a/internal/ratelimit/limiter.go b/internal/ratelimit/limiter.go index bf914d9..e41f16f 100644 --- a/internal/ratelimit/limiter.go +++ b/internal/ratelimit/limiter.go @@ -30,14 +30,6 @@ func New(bytesPerSecond int64) *Limiter { return &Limiter{bps: bytesPerSecond} } -// Limit reports the configured bytes per second. Nil is unlimited (0). -func (l *Limiter) Limit() int64 { - if l == nil { - return 0 - } - return l.bps -} - // WaitN blocks until n bytes fit on the shared timeline, or until ctx ends. // The wait is "until the previous bytes have been paid"; this call's own // cost is what delays the next caller. Cancelling gives the unused tail diff --git a/internal/s3client/client.go b/internal/s3client/client.go index c1b2c59..6b50c2b 100644 --- a/internal/s3client/client.go +++ b/internal/s3client/client.go @@ -5,12 +5,12 @@ import ( "fmt" "net" "net/http" - "os" "time" awsv2 "github.com/aws/aws-sdk-go-v2/aws" awsconfig "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/rustfs/migration/internal/config" @@ -30,14 +30,11 @@ func New(ctx context.Context, ep config.Endpoint) (*s3.Client, error) { // reconnecting on every object when MaxIdleConnsPerHost would otherwise // stay at the Go default of 2. func NewWithPool(ctx context.Context, ep config.Endpoint, idlePerHost int) (*s3.Client, error) { - // Self-hosted clusters have no EC2 IMDS; disable it so LoadDefaultConfig - // does not hang for several seconds on a missing metadata service. - if os.Getenv("AWS_EC2_METADATA_DISABLED") == "" { - _ = os.Setenv("AWS_EC2_METADATA_DISABLED", "true") - } - + // Self-hosted clusters have no EC2 IMDS; disable it on the config loader + // without mutating process-wide environment variables across goroutines. cfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(ep.Region), + awsconfig.WithEC2IMDSClientEnableState(imds.ClientDisabled), awsconfig.WithCredentialsProvider( credentials.NewStaticCredentialsProvider(ep.AccessKey, ep.SecretKey, ep.SessionToken), ), diff --git a/internal/s3client/errors.go b/internal/s3client/errors.go index 599376c..12fa1b5 100644 --- a/internal/s3client/errors.go +++ b/internal/s3client/errors.go @@ -31,6 +31,16 @@ func IsCanceled(err error) bool { if errors.As(err, &timeout) && timeout.Timeout() { return true } + // A completed HTTP/S3 response whose message echoes an object key or bucket + // name (e.g. "recordings/interrupted.mp4") is not a canceled client call. + var ae smithy.APIError + if errors.As(err, &ae) { + return false + } + var response interface{ HTTPStatusCode() int } + if errors.As(err, &response) && response.HTTPStatusCode() > 0 { + return false + } msg := strings.ToLower(err.Error()) switch { case strings.Contains(msg, "context canceled"), @@ -40,8 +50,7 @@ func IsCanceled(err error) bool { strings.Contains(msg, "request canceled"), strings.Contains(msg, "request cancelled"), strings.Contains(msg, "operation was canceled"), - strings.Contains(msg, "operation was cancelled"), - strings.Contains(msg, "interrupted"): + strings.Contains(msg, "operation was cancelled"): return true default: return false diff --git a/internal/s3client/metadata.go b/internal/s3client/metadata.go index 8547909..fa1c1b0 100644 --- a/internal/s3client/metadata.go +++ b/internal/s3client/metadata.go @@ -1,10 +1,28 @@ package s3client import ( + "net/http" + "strings" + "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" ) +// DefaultContentType is the standard S3 default MIME type assigned by servers +// when an object is stored without an explicit Content-Type header. +const DefaultContentType = "application/octet-stream" + +// EffectiveContentType normalizes an empty or missing Content-Type to the S3 +// server default so objects uploaded without a Content-Type header do not fail +// post-commit readback or diff against servers that populate the default. +func EffectiveContentType(ct *string) string { + v := strings.TrimSpace(aws.ToString(ct)) + if v == "" { + return DefaultContentType + } + return v +} + // MetadataEqual compares the object headers and user metadata preserved by // migration. ETags and LastModified are representation identifiers, not // preserved metadata, and may legitimately differ between endpoints. @@ -13,13 +31,13 @@ func MetadataEqual(a, b *s3.HeadObjectOutput) bool { return false } if aws.ToString(a.CacheControl) != aws.ToString(b.CacheControl) || - aws.ToString(a.ContentType) != aws.ToString(b.ContentType) || + EffectiveContentType(a.ContentType) != EffectiveContentType(b.ContentType) || aws.ToString(a.ContentEncoding) != aws.ToString(b.ContentEncoding) || aws.ToString(a.ContentDisposition) != aws.ToString(b.ContentDisposition) || aws.ToString(a.ContentLanguage) != aws.ToString(b.ContentLanguage) { return false } - if (a.Expires == nil) != (b.Expires == nil) || (a.Expires != nil && !a.Expires.Equal(*b.Expires)) { + if !expiresEqual(a, b) { return false } if len(a.Metadata) != len(b.Metadata) { @@ -32,3 +50,28 @@ func MetadataEqual(a, b *s3.HeadObjectOutput) bool { } return true } + +func expiresEqual(a, b *s3.HeadObjectOutput) bool { + aHas := a.Expires != nil || strings.TrimSpace(aws.ToString(a.ExpiresString)) != "" + bHas := b.Expires != nil || strings.TrimSpace(aws.ToString(b.ExpiresString)) != "" + if aHas != bHas { + return false + } + if !aHas { + return true + } + if a.Expires != nil && b.Expires != nil { + return a.Expires.Equal(*b.Expires) + } + return strings.TrimSpace(rawExpires(a)) == strings.TrimSpace(rawExpires(b)) +} + +func rawExpires(h *s3.HeadObjectOutput) string { + if s := strings.TrimSpace(aws.ToString(h.ExpiresString)); s != "" { + return s + } + if h.Expires != nil { + return h.Expires.UTC().Format(http.TimeFormat) + } + return "" +} diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go index 18ce4bc..8fde573 100644 --- a/internal/scanner/scanner.go +++ b/internal/scanner/scanner.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "log" - "net/url" "time" awsv2 "github.com/aws/aws-sdk-go-v2/aws" @@ -43,11 +42,6 @@ func Run(ctx context.Context, cli *s3.Client, bucket string, st *store.Store) (i return 0, err } - p := s3.NewListObjectsV2Paginator(cli, &s3.ListObjectsV2Input{ - Bucket: awsv2.String(bucket), - EncodingType: s3types.EncodingTypeUrl, - }) - var total int64 start := time.Now() buf := make([]store.Object, 0, batchSize) @@ -64,43 +58,10 @@ func Run(ctx context.Context, cli *s3.Client, bucket string, st *store.Store) (i return nil } - seenTokens := make(map[string]struct{}) - for p.HasMorePages() { - if err := ctx.Err(); err != nil { - _ = flush() - return total, err - } - page, err := p.NextPage(ctx) - if err != nil { - return total, fmt.Errorf("list page: %w", err) - } - if page.IsTruncated == nil { - return total, fmt.Errorf("list page omitted IsTruncated; inventory completeness is unknown") - } - if name := awsv2.ToString(page.Name); name != "" && name != bucket { - return total, fmt.Errorf("list page bucket mismatch: requested %q, server returned %q", bucket, name) - } - if awsv2.ToBool(page.IsTruncated) { - next := awsv2.ToString(page.NextContinuationToken) - if _, exists := seenTokens[next]; next == "" || exists { - return total, fmt.Errorf("list page is truncated without a new continuation token") - } - seenTokens[next] = struct{}{} - } - for _, obj := range page.Contents { - key := awsv2.ToString(obj.Key) - if page.EncodingType == s3types.EncodingTypeUrl { - var err error - key, err = url.QueryUnescape(key) - if err != nil { - return total, fmt.Errorf("decode listed key: %w", err) - } - } - if key == "" || obj.Size == nil || *obj.Size < 0 { - return total, fmt.Errorf("invalid listed object key=%q size=%v", key, obj.Size) - } + walkErr := cluster.WalkObjects(ctx, cli, bucket, func(contents []s3types.Object) error { + for _, obj := range contents { o := store.Object{ - Key: key, + Key: awsv2.ToString(obj.Key), Size: deref(obj.Size), ETag: awsv2.ToString(obj.ETag), } @@ -110,11 +71,18 @@ func Run(ctx context.Context, cli *s3.Client, bucket string, st *store.Store) (i buf = append(buf, o) if len(buf) >= batchSize { if err := flush(); err != nil { - return total, err + return err } log.Printf("scan %s: %d objects (elapsed %s)", bucket, total, time.Since(start).Truncate(time.Second)) } } + return nil + }) + if walkErr != nil { + if ctx.Err() != nil { + _ = flush() + } + return total, fmt.Errorf("list page: %w", walkErr) } if err := flush(); err != nil { return total, err diff --git a/internal/store/store.go b/internal/store/store.go index c0d3fe3..9762a69 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -8,10 +8,12 @@ import ( "os" "path/filepath" "runtime" + "strconv" "strings" "sync" "time" + "github.com/rustfs/migration/internal/config" "modernc.org/sqlite" ) @@ -74,7 +76,7 @@ func open(path, bucket, mode string) (*Store, error) { // A separate SQLite pager lock is held for the whole writer lifetime. It // protects the migration task, not just individual status transactions, // and the OS releases it automatically if the process crashes. - lock, err := sql.Open("sqlite", sqliteURI(path+".lock", "rwc", "busy_timeout(0)")) + lock, err := sql.Open("sqlite", SQLiteURI(path+".lock", "rwc", "busy_timeout(0)")) if err != nil { return nil, err } @@ -88,7 +90,7 @@ func open(path, bucket, mode string) (*Store, error) { return nil, fmt.Errorf("acquire state DB lock %s: %w", path, err) } unlock := func() { _, _ = lock.Exec(`ROLLBACK`); _ = lock.Close() } - db, err := sql.Open("sqlite", sqliteURI(path, mode, "journal_mode(WAL)", "synchronous(FULL)", "busy_timeout(5000)")) + db, err := sql.Open("sqlite", SQLiteURI(path, mode, "journal_mode(WAL)", "synchronous(FULL)", "busy_timeout(5000)")) if err != nil { unlock() return nil, err @@ -105,6 +107,11 @@ func open(path, bucket, mode string) (*Store, error) { unlock() return nil, fmt.Errorf("init schema: %w", err) } + if err := ensureSeenGenerationColumn(db); err != nil { + db.Close() + unlock() + return nil, fmt.Errorf("upgrade schema: %w", err) + } if existingSchema == 0 { if _, err := db.Exec(`INSERT INTO meta(key,value) VALUES('state_format','2')`); err != nil { db.Close() @@ -120,13 +127,35 @@ func open(path, bucket, mode string) (*Store, error) { return &Store{db: db, lock: lock}, nil } -func sqliteURI(path, mode string, pragmas ...string) string { +func ensureSeenGenerationColumn(db *sql.DB) error { + var hasCol int + if err := db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('objects') WHERE name='seen_generation'`).Scan(&hasCol); err != nil { + return err + } + if hasCol == 0 { + if _, err := db.Exec(`ALTER TABLE objects ADD COLUMN seen_generation INTEGER NOT NULL DEFAULT 0`); err != nil { + return err + } + } + return nil +} + +// SQLiteURI builds a file: URI that safely escapes special characters (#, ?, %, spaces) +// and handles Windows drive letters and UNC paths. +func SQLiteURI(path, mode string, pragmas ...string) string { + return sqliteURIWithOptions(path, mode, false, pragmas...) +} + +func sqliteURIWithOptions(path, mode string, immutable bool, pragmas ...string) string { abs, err := filepath.Abs(path) if err == nil { path = abs } u := url.URL{Scheme: "file", Path: sqliteURIPath(filepath.ToSlash(path), runtime.GOOS == "windows")} q := url.Values{"mode": {mode}} + if immutable { + q.Set("immutable", "1") + } for _, pragma := range pragmas { q.Add("_pragma", pragma) } @@ -183,8 +212,14 @@ func tuneSQLite(db *sql.DB) { } // OpenExisting opens a state DB read-only without taking the writer lock. +// If the parent directory or snapshot is read-only after a clean writer close +// (so WAL header flags remain set but no uncheckpointed -wal exists), it falls +// back to immutable read-only mode instead of failing to create -shm. func OpenExisting(path string) (*Store, error) { - db, err := sql.Open("sqlite", sqliteURI(path, "ro", "busy_timeout(5000)")) + if _, err := os.Stat(path); err != nil { + return nil, fmt.Errorf("open existing %s: %w", path, err) + } + db, err := sql.Open("sqlite", SQLiteURI(path, "ro", "busy_timeout(5000)")) if err != nil { return nil, err } @@ -192,11 +227,40 @@ func OpenExisting(path string) (*Store, error) { s := &Store{db: db} if _, err := s.BoundBucket(); err != nil { db.Close() + if isReadOnlyWALInitError(err) && hasNoUncheckpointedWAL(path) { + immDB, immErr := sql.Open("sqlite", sqliteURIWithOptions(path, "ro", true)) + if immErr == nil { + tuneSQLite(immDB) + immStore := &Store{db: immDB} + if _, bErr := immStore.BoundBucket(); bErr == nil { + return immStore, nil + } + immDB.Close() + } + } return nil, fmt.Errorf("open existing %s: %w", path, err) } return s, nil } +func isReadOnlyWALInitError(err error) bool { + var sqliteErr *sqlite.Error + if !errors.As(err, &sqliteErr) { + return false + } + primary := sqliteErr.Code() & 0xff + // SQLITE_READONLY (8, e.g. SQLITE_READONLY_CANTINIT=1544) or SQLITE_CANTOPEN (14). + return primary == 8 || primary == 14 +} + +func hasNoUncheckpointedWAL(path string) bool { + info, err := os.Stat(path + "-wal") + if os.IsNotExist(err) { + return true + } + return err == nil && info.Size() == 0 +} + // BindMigration prevents a checkpoint being reused against another source or // target. A source-only scan may omit target and bind it on the first copy. // Credentials are deliberately not persisted in the state database. @@ -259,14 +323,7 @@ func (s *Store) BindMigration(source, target string) error { } func normalizeEndpoint(endpoint string) string { - endpoint = strings.TrimRight(strings.TrimSpace(endpoint), "/") - if u, err := url.Parse(endpoint); err == nil && u.Host != "" { - u.Scheme = strings.ToLower(u.Scheme) - u.Host = strings.ToLower(u.Host) - u.User = nil - endpoint = u.String() - } - return endpoint + return config.NormalizeEndpoint(endpoint) } // BeginScan invalidates the previous completeness certificate before any @@ -277,16 +334,26 @@ func (s *Store) BeginScan() error { } func (s *Store) CompleteScan() error { - result, err := s.db.Exec(`INSERT INTO meta(key,value) SELECT 'scan_complete_generation',value FROM meta WHERE key='scan_generation' AND CAST(value AS INTEGER)>0 ON CONFLICT(key) DO UPDATE SET value=excluded.value`) + tx, err := s.db.Begin() if err != nil { return err } - if n, err := result.RowsAffected(); err != nil { - return err - } else if n == 0 { + defer tx.Rollback() + var gen int64 + err = tx.QueryRow(`SELECT CAST(value AS INTEGER) FROM meta WHERE key='scan_generation'`).Scan(&gen) + if err == sql.ErrNoRows || (err == nil && gen <= 0) { return fmt.Errorf("cannot complete a scan that was never started") } - return nil + if err != nil { + return err + } + if _, err := tx.Exec(`DELETE FROM objects WHERE seen_generation < ?`, gen); err != nil { + return fmt.Errorf("prune stale inventory rows: %w", err) + } + if _, err := tx.Exec(`INSERT INTO meta(key,value) VALUES('scan_complete_generation',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`, strconv.FormatInt(gen, 10)); err != nil { + return err + } + return tx.Commit() } func (s *Store) RequireCompleteScan() error { @@ -309,16 +376,18 @@ func (s *Store) BoundBucket() (string, error) { const schema = ` CREATE TABLE IF NOT EXISTS objects ( - key TEXT PRIMARY KEY, - size INTEGER NOT NULL, - last_modified INTEGER NOT NULL, - etag TEXT, - status TEXT NOT NULL DEFAULT 'pending', - attempts INTEGER NOT NULL DEFAULT 0, - last_error TEXT, - updated_at INTEGER NOT NULL DEFAULT 0 + key TEXT PRIMARY KEY, + size INTEGER NOT NULL, + last_modified INTEGER NOT NULL, + etag TEXT, + status TEXT NOT NULL DEFAULT 'pending', + attempts INTEGER NOT NULL DEFAULT 0, + last_error TEXT, + updated_at INTEGER NOT NULL DEFAULT 0, + seen_generation INTEGER NOT NULL DEFAULT 0 ); -CREATE INDEX IF NOT EXISTS idx_objects_status ON objects(status); +DROP INDEX IF EXISTS idx_objects_status; +CREATE INDEX IF NOT EXISTS idx_objects_status_key ON objects(status, key); CREATE TABLE IF NOT EXISTS meta ( key TEXT PRIMARY KEY, value TEXT NOT NULL @@ -336,20 +405,43 @@ func (s *Store) BatchUpsertScanned(objs []Object) error { if err != nil { return err } + var gen int64 + if err := tx.QueryRow(`SELECT CAST(value AS INTEGER) FROM meta WHERE key='scan_generation'`).Scan(&gen); err != nil && err != sql.ErrNoRows { + tx.Rollback() + return err + } stmt, err := tx.Prepare(` - INSERT INTO objects(key, size, last_modified, etag, status, updated_at) - VALUES(?, ?, ?, ?, 'pending', ?) + INSERT INTO objects(key, size, last_modified, etag, status, updated_at, seen_generation) + VALUES(?, ?, ?, ?, 'pending', ?, ?) ON CONFLICT(key) DO UPDATE SET + seen_generation = excluded.seen_generation, + status = CASE + WHEN objects.status IN ('pending','failed','skipped') + OR objects.size != excluded.size + OR objects.last_modified != excluded.last_modified + OR COALESCE(objects.etag,'') != COALESCE(excluded.etag,'') + THEN 'pending' + ELSE objects.status + END, + last_error = CASE + WHEN objects.status IN ('pending','failed','skipped') + OR objects.size != excluded.size + OR objects.last_modified != excluded.last_modified + OR COALESCE(objects.etag,'') != COALESCE(excluded.etag,'') + THEN '' + ELSE objects.last_error + END, + updated_at = CASE + WHEN objects.status IN ('pending','failed','skipped') + OR objects.size != excluded.size + OR objects.last_modified != excluded.last_modified + OR COALESCE(objects.etag,'') != COALESCE(excluded.etag,'') + THEN excluded.updated_at + ELSE objects.updated_at + END, size = excluded.size, last_modified = excluded.last_modified, - etag = excluded.etag, - updated_at = excluded.updated_at, - status = 'pending', - last_error = '' - WHERE objects.status IN ('pending','failed','skipped') - OR objects.size != excluded.size - OR objects.last_modified != excluded.last_modified - OR COALESCE(objects.etag,'') != COALESCE(excluded.etag,'') + etag = excluded.etag `) if err != nil { tx.Rollback() @@ -358,7 +450,7 @@ func (s *Store) BatchUpsertScanned(objs []Object) error { defer stmt.Close() now := time.Now().Unix() for _, o := range objs { - if _, err := stmt.Exec(o.Key, o.Size, o.LastModified.Unix(), o.ETag, now); err != nil { + if _, err := stmt.Exec(o.Key, o.Size, o.LastModified.Unix(), o.ETag, now, gen); err != nil { tx.Rollback() return err } @@ -366,10 +458,20 @@ func (s *Store) BatchUpsertScanned(objs []Object) error { return tx.Commit() } +// pendingBatch merges the top-K keys from the ordered (status, key) index for +// 'pending' and 'failed' separately, avoiding a full-table TEMP B-TREE sort. const pendingBatch = ` -SELECT key, size, last_modified, etag, status FROM objects - WHERE status IN ('pending','failed') AND key > ? - ORDER BY key LIMIT ? +SELECT key, size, last_modified, etag, status FROM ( + SELECT key, size, last_modified, etag, status FROM ( + SELECT key, size, last_modified, etag, status FROM objects + WHERE status = 'pending' AND key > ? ORDER BY key LIMIT ? + ) + UNION ALL + SELECT key, size, last_modified, etag, status FROM ( + SELECT key, size, last_modified, etag, status FROM objects + WHERE status = 'failed' AND key > ? ORDER BY key LIMIT ? + ) +) ORDER BY key LIMIT ? ` // BatchPendingAfter returns up to limit objects still needing work, strictly @@ -378,7 +480,7 @@ func (s *Store) BatchPendingAfter(afterKey string, limit int) ([]Object, error) if limit <= 0 { limit = 1000 } - rows, err := s.db.Query(pendingBatch, afterKey, limit) + rows, err := s.db.Query(pendingBatch, afterKey, limit, afterKey, limit, limit) if err != nil { return nil, err } @@ -443,12 +545,6 @@ func (s *Store) Counts() (Counts, error) { return c, rows.Err() } -func (s *Store) CountWork() (int64, error) { - var n int64 - err := s.db.QueryRow(`SELECT COUNT(*) FROM objects WHERE status IN ('pending','failed')`).Scan(&n) - return n, err -} - // OpenInventory opens an existing, completed inventory under the writer lock. func OpenInventory(path, bucket string) (*Store, error) { if _, err := os.Stat(path); err != nil { @@ -465,9 +561,6 @@ func OpenInventory(path, bucket string) (*Store, error) { return st, nil } -// BindEndpoints is retained for callers using the upstream name. -func (s *Store) BindEndpoints(source, target string) error { return s.BindMigration(source, target) } - // SetScanComplete is a compatibility wrapper for the generation-based certificate. func (s *Store) SetScanComplete(complete bool) error { if complete { diff --git a/scripts/audit-local-rustfs.py b/scripts/audit-local-rustfs.py index d3204d0..026528c 100644 --- a/scripts/audit-local-rustfs.py +++ b/scripts/audit-local-rustfs.py @@ -20,13 +20,23 @@ GO_TIMEOUT_SECONDS = 360 # Includes compilation; the test binary gets five minutes. -def clean_rustfs_env(): +def clean_rustfs_env(tmpdir=None): """Do not inherit unrelated RustFS or cloud credentials/settings.""" env = {key: os.environ[key] for key in ("PATH", "HOME", "TMPDIR") if key in os.environ} + if tmpdir is not None: + env["TMPDIR"] = str(tmpdir) env["RUSTFS_CONSOLE_ENABLE"] = "false" return env +def supports_server_subcommand(binary_path): + """Detect whether this RustFS release uses `rustfs server ...` or `rustfs `.""" + result = subprocess.run([str(binary_path), "--help"], env=clean_rustfs_env(), + capture_output=True, text=True, timeout=15, check=False) + output = result.stdout + result.stderr + return bool(re.search(r"(?m)^\s+server\b", output)) + + def parse_version(output): match = re.search(r"(?im)^\s*rustfs(?:\s+version)?[\s:=]+v?(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?)(?=\s|$)", output) if not match: @@ -111,21 +121,28 @@ def main(argv=None): processes, logs, endpoints = [], [], [] deadline = time.monotonic() + TOTAL_TIMEOUT_SECONDS go_proc = None + use_server_subcmd = supports_server_subcommand(metadata["binary_path"]) try: with tempfile.TemporaryDirectory(prefix="migration-audit-rustfs-") as base: try: for name in ("source", "target"): data = Path(base) / name data.mkdir() + node_tmp = Path(base) / f"{name}-tmp" + node_tmp.mkdir() port = free_port() endpoint = f"http://127.0.0.1:{port}" log = (output / f"rustfs-{name}.log").open("w") logs.append(log) - proc = subprocess.Popen([ - metadata["binary_path"], "server", "--address", f"127.0.0.1:{port}", + cmd = [metadata["binary_path"]] + if use_server_subcmd: + cmd.append("server") + cmd.extend([ + "--address", f"127.0.0.1:{port}", "--access-key", "audit-local", "--secret-key", "audit-local-secret", str(data), - ], cwd=base, env=clean_rustfs_env(), stdout=log, - stderr=subprocess.STDOUT, start_new_session=True) + ]) + proc = subprocess.Popen(cmd, cwd=base, env=clean_rustfs_env(tmpdir=node_tmp), stdout=log, + stderr=subprocess.STDOUT, start_new_session=True) processes.append(proc) start_deadline = min(deadline, time.monotonic() + 45) while True: diff --git a/scripts/package.py b/scripts/package.py index 4302482..1d8635b 100644 --- a/scripts/package.py +++ b/scripts/package.py @@ -1,42 +1,254 @@ -"""Build one standalone migration archive and its SHA-256 checksum.""" +#!/usr/bin/env python3 +"""Build standalone binaries, tar/zip archives, DEB and RPM packages, and SHA-256 checksums.""" import argparse import hashlib +import math import os from pathlib import Path +import re +import shutil import subprocess import tarfile import tempfile import zipfile ROOT = Path(__file__).resolve().parents[1] +TARGETS = ("linux-amd64", "linux-arm64", "darwin-amd64", "darwin-arm64", "windows-amd64") +DEB_ARCH = {"amd64": "amd64", "arm64": "arm64"} +RPM_ARCH = {"amd64": "x86_64", "arm64": "aarch64"} -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("target", choices=["linux-amd64", "linux-arm64", "windows-amd64"]) - parser.add_argument("output", type=Path, help="directory for the archive and checksum") - args = parser.parse_args() - goos, goarch = args.target.split("-") +def default_version(): + helptext = (ROOT / "cmd" / "helptext.go").read_text(encoding="utf-8") + match = re.search(r'\bVersion\s*=\s*"([^"]+)"', helptext) + return match.group(1) if match else "0.2.0" + + +def resolve_version(): + for key in ("MIGRATION_VERSION", "GITHUB_REF_NAME"): + val = os.environ.get(key, "").strip() + if val and (key == "MIGRATION_VERSION" or os.environ.get("GITHUB_REF_TYPE") == "tag"): + if val.startswith("v") and len(val) > 1 and val[1].isdigit(): + return val[1:] + return val + return default_version() + + +def sanitize_pkg_version(version): + """Normalize a version string so both dpkg-deb and rpmbuild accept it.""" + cleaned = version.strip() + if cleaned.startswith("v") and len(cleaned) > 1 and cleaned[1].isdigit(): + cleaned = cleaned[1:] + cleaned = cleaned.replace("-", "~") + cleaned = re.sub(r"[^0-9A-Za-z.+~]", ".", cleaned).strip(".") + if not cleaned or not cleaned[0].isdigit(): + cleaned = f"0.0.0~{cleaned}" if cleaned else "0.0.0" + return cleaned + + +def write_sha256(artifact): + checksum = hashlib.sha256(artifact.read_bytes()).hexdigest() + artifact.with_name(artifact.name + ".sha256").write_bytes( + f"{checksum} {artifact.name}\n".encode("utf-8") + ) + + +def render_deb_control(pkg_version, deb_arch, installed_kib): + return ( + f"Package: rustfs-migration\n" + f"Version: {pkg_version}\n" + f"Section: utils\n" + f"Priority: optional\n" + f"Architecture: {deb_arch}\n" + f"Installed-Size: {installed_kib}\n" + f"Maintainer: RustFS Developers \n" + f"Homepage: https://github.com/rustfs/migration\n" + f"Provides: migration\n" + f"Description: Safe one-way S3 object storage migration tool\n" + f" Copies current objects from one S3-compatible cluster to another with\n" + f" atomic conditional writes, SQLite progress checkpoints, and full-body\n" + f" SHA-256 plus metadata verification.\n" + ) + + +def render_rpm_spec(pkg_version): + return ( + "%global debug_package %{nil}\n" + "%define __strip /bin/true\n" + "%define _build_id_links none\n" + "%define _binary_payload w9.gzdio\n" + "\n" + "Name: rustfs-migration\n" + f"Version: {pkg_version}\n" + "Release: 1\n" + "Summary: Safe one-way S3 object storage migration tool\n" + "License: Apache-2.0\n" + "URL: https://github.com/rustfs/migration\n" + "Provides: migration = %{version}-%{release}\n" + "\n" + "%description\n" + "Copies current objects from one S3-compatible cluster to another with\n" + "atomic conditional writes, SQLite progress checkpoints, and full-body\n" + "SHA-256 plus metadata verification.\n" + "\n" + "%prep\n" + "\n" + "%build\n" + "\n" + "%install\n" + "rm -rf %{buildroot}\n" + "install -D -m 0755 %{_sourcedir}/migration %{buildroot}/usr/bin/migration\n" + "install -D -m 0644 %{_sourcedir}/config.example.yaml %{buildroot}/etc/rustfs-migration/config.example.yaml\n" + "install -D -m 0644 %{_sourcedir}/LICENSE %{buildroot}/usr/share/doc/rustfs-migration/LICENSE\n" + "install -D -m 0644 %{_sourcedir}/README.md %{buildroot}/usr/share/doc/rustfs-migration/README.md\n" + "\n" + "%files\n" + "%defattr(-,root,root,-)\n" + "/usr/bin/migration\n" + "%dir /etc/rustfs-migration\n" + "%config(noreplace) /etc/rustfs-migration/config.example.yaml\n" + "%dir /usr/share/doc/rustfs-migration\n" + "%doc /usr/share/doc/rustfs-migration/LICENSE\n" + "%doc /usr/share/doc/rustfs-migration/README.md\n" + ) + + +def build_deb(binary, goarch, pkg_version, output_dir): + if shutil.which("dpkg-deb") is None: + raise RuntimeError("dpkg-deb is required to build .deb packages") + deb_arch = DEB_ARCH[goarch] + deb_path = output_dir / f"rustfs-migration_{pkg_version}_{deb_arch}.deb" + with tempfile.TemporaryDirectory(prefix="migration-deb-") as temp: + root = Path(temp) / "pkg" + (root / "DEBIAN").mkdir(parents=True) + (root / "usr" / "bin").mkdir(parents=True) + (root / "etc" / "rustfs-migration").mkdir(parents=True) + (root / "usr" / "share" / "doc" / "rustfs-migration").mkdir(parents=True) + + bin_dst = root / "usr" / "bin" / "migration" + shutil.copy2(binary, bin_dst) + bin_dst.chmod(0o755) + + cfg_dst = root / "etc" / "rustfs-migration" / "config.example.yaml" + shutil.copy2(ROOT / "config.example.yaml", cfg_dst) + cfg_dst.chmod(0o644) + + total_bytes = bin_dst.stat().st_size + cfg_dst.stat().st_size + for doc_name in ("LICENSE", "README.md"): + dst = root / "usr" / "share" / "doc" / "rustfs-migration" / doc_name + shutil.copy2(ROOT / doc_name, dst) + dst.chmod(0o644) + total_bytes += dst.stat().st_size + + for dirpath, dirnames, _ in os.walk(root): + Path(dirpath).chmod(0o755) + for d in dirnames: + (Path(dirpath) / d).chmod(0o755) + + installed_kib = max(1, math.ceil(total_bytes / 1024)) + control = root / "DEBIAN" / "control" + control.write_text(render_deb_control(pkg_version, deb_arch, installed_kib), encoding="utf-8") + control.chmod(0o644) + + subprocess.run( + ["dpkg-deb", "--root-owner-group", "-Zgzip", "--build", str(root), str(deb_path)], + check=True, + ) + write_sha256(deb_path) + return deb_path + + +def build_rpm(binary, goarch, pkg_version, output_dir): + if shutil.which("rpmbuild") is None: + raise RuntimeError("rpmbuild is required to build .rpm packages") + rpm_arch = RPM_ARCH[goarch] + rpm_path = output_dir / f"rustfs-migration-{pkg_version}-1.{rpm_arch}.rpm" + with tempfile.TemporaryDirectory(prefix="migration-rpm-") as temp: + topdir = Path(temp) / "rpmbuild" + for sub in ("BUILD", "BUILDROOT", "RPMS", "SOURCES", "SPECS", "SRPMS"): + (topdir / sub).mkdir(parents=True) + + shutil.copy2(binary, topdir / "SOURCES" / "migration") + for asset in ("config.example.yaml", "LICENSE", "README.md"): + shutil.copy2(ROOT / asset, topdir / "SOURCES" / asset) + + spec = topdir / "SPECS" / "rustfs-migration.spec" + spec.write_text(render_rpm_spec(pkg_version), encoding="utf-8") + + subprocess.run( + [ + "rpmbuild", + "--define", f"_topdir {topdir}", + "--target", f"{rpm_arch}-linux", + "-bb", str(spec), + ], + check=True, + ) + built = list((topdir / "RPMS").rglob("*.rpm")) + if len(built) != 1: + raise RuntimeError(f"expected 1 built RPM, found {built}") + shutil.copy2(built[0], rpm_path) + write_sha256(rpm_path) + return rpm_path + + +def build_target(target, output_dir, linux_packages=False): + goos, goarch = target.split("-") windows = goos == "windows" + version = resolve_version() + pkg_version = sanitize_pkg_version(version) env = {**os.environ, "CGO_ENABLED": "0", "GOOS": goos, "GOARCH": goarch} - args.output.mkdir(parents=True, exist_ok=True) - suffix = ".zip" if windows else ".tar.gz" - archive = args.output / f"migration-{args.target}{suffix}" - with tempfile.TemporaryDirectory() as temp: + output_dir.mkdir(parents=True, exist_ok=True) + + ldflags = f"-s -w -X github.com/rustfs/migration/cmd.Version={version}" + standalone_name = f"migration-{target}.exe" if windows else f"migration-{target}" + standalone_path = output_dir / standalone_name + archive_suffix = ".zip" if windows else ".tar.gz" + archive_path = output_dir / f"migration-{target}{archive_suffix}" + + with tempfile.TemporaryDirectory(prefix="migration-build-") as temp: binary = Path(temp) / ("migration.exe" if windows else "migration") - subprocess.run(["go", "build", "-trimpath", "-ldflags=-s -w", "-o", binary, "."], - cwd=ROOT, env=env, check=True) - files = [binary, ROOT / "LICENSE", ROOT / "config.example.yaml"] + subprocess.run( + ["go", "build", "-trimpath", f"-ldflags={ldflags}", "-o", str(binary), "."], + cwd=ROOT, env=env, check=True, + ) + if not windows: + binary.chmod(0o755) + + shutil.copy2(binary, standalone_path) + if not windows: + standalone_path.chmod(0o755) + write_sha256(standalone_path) + + files = [binary, ROOT / "LICENSE", ROOT / "README.md", ROOT / "config.example.yaml"] if windows: - with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as package: + with zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED) as package: for file in files: package.write(file, file.name) else: - with tarfile.open(archive, "w:gz") as package: + with tarfile.open(archive_path, "w:gz") as package: for file in files: package.add(file, arcname=file.name) - checksum = hashlib.sha256(archive.read_bytes()).hexdigest() - archive.with_name(archive.name + ".sha256").write_bytes(f"{checksum} {archive.name}\n".encode()) + write_sha256(archive_path) + + if linux_packages: + if goos != "linux" or goarch not in DEB_ARCH: + raise ValueError(f"--linux-packages is only supported for linux-amd64/linux-arm64, got {target}") + build_deb(binary, goarch, pkg_version, output_dir) + build_rpm(binary, goarch, pkg_version, output_dir) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("target", choices=TARGETS) + parser.add_argument("output", type=Path, help="directory for built binaries, packages, and checksums") + parser.add_argument( + "--linux-packages", + action="store_true", + help="also build .deb and .rpm packages (requires dpkg-deb and rpmbuild)", + ) + args = parser.parse_args(argv) + build_target(args.target, args.output, linux_packages=args.linux_packages) if __name__ == "__main__": diff --git a/scripts/test_audit_local_rustfs.py b/scripts/test_audit_local_rustfs.py index 0acb8d1..7f72f9d 100644 --- a/scripts/test_audit_local_rustfs.py +++ b/scripts/test_audit_local_rustfs.py @@ -53,6 +53,21 @@ def test_node_environment_excludes_external_credentials(self): "RUSTFS_VOLUMES": "/external/data", "RUSTFS_CONSOLE_ENABLE": "true", }, clear=True): self.assertEqual(launcher.clean_rustfs_env(), {"PATH": "/bin", "RUSTFS_CONSOLE_ENABLE": "false"}) + self.assertEqual( + launcher.clean_rustfs_env(tmpdir="/isolated/node-tmp"), + {"PATH": "/bin", "TMPDIR": "/isolated/node-tmp", "RUSTFS_CONSOLE_ENABLE": "false"}, + ) + + def test_supports_server_subcommand_detection(self): + with tempfile.TemporaryDirectory() as directory: + modern = Path(directory) / "rustfs-modern" + modern.write_text("#!/bin/sh\nprintf 'Commands:\\n server Start server\\n'\n") + modern.chmod(0o700) + legacy = Path(directory) / "rustfs-legacy" + legacy.write_text("#!/bin/sh\nprintf 'Usage: rustfs [OPTIONS] ...\\n'\n") + legacy.chmod(0o700) + self.assertTrue(launcher.supports_server_subcommand(modern)) + self.assertFalse(launcher.supports_server_subcommand(legacy)) def test_unrecognized_version_output_is_rejected(self): for output in ("1.0.4", "unrelated 1.0.4", "rustfs development"): diff --git a/scripts/test_package.py b/scripts/test_package.py new file mode 100644 index 0000000..5bc7630 --- /dev/null +++ b/scripts/test_package.py @@ -0,0 +1,72 @@ +"""Unit tests for multi-format release packaging (binaries, archives, DEB, RPM).""" +import importlib.util +import os +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +SPEC = importlib.util.spec_from_file_location("package", Path(__file__).with_name("package.py")) +packager = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(packager) + + +class PackageScriptTests(unittest.TestCase): + def test_sanitize_pkg_version_handles_tags_and_prereleases(self): + self.assertEqual(packager.sanitize_pkg_version("v0.2.0"), "0.2.0") + self.assertEqual(packager.sanitize_pkg_version("0.1"), "0.1") + self.assertEqual(packager.sanitize_pkg_version("v1.0.4-rc.1"), "1.0.4~rc.1") + self.assertEqual(packager.sanitize_pkg_version("nightly"), "0.0.0~nightly") + + def test_resolve_version_prefers_explicit_env_and_tags(self): + with mock.patch.dict(os.environ, {"MIGRATION_VERSION": "v0.3.1"}, clear=True): + self.assertEqual(packager.resolve_version(), "0.3.1") + with mock.patch.dict(os.environ, {"GITHUB_REF_TYPE": "tag", "GITHUB_REF_NAME": "0.2"}, clear=True): + self.assertEqual(packager.resolve_version(), "0.2") + with mock.patch.dict(os.environ, {"GITHUB_REF_TYPE": "branch", "GITHUB_REF_NAME": "main"}, clear=True): + self.assertEqual(packager.resolve_version(), packager.default_version()) + + def test_deb_control_and_rpm_spec_metadata(self): + control = packager.render_deb_control("0.2.0~rc.1", "arm64", 12345) + self.assertIn("Package: rustfs-migration\n", control) + self.assertIn("Version: 0.2.0~rc.1\n", control) + self.assertIn("Architecture: arm64\n", control) + + spec = packager.render_rpm_spec("0.2.0~rc.1") + self.assertIn("Name: rustfs-migration\n", spec) + self.assertIn("Version: 0.2.0~rc.1\n", spec) + self.assertNotIn("Version: 0.2.0-", spec) + self.assertIn("/usr/bin/migration\n", spec) + + def test_build_deb_and_rpm_invocations_with_mocked_tools(self): + with tempfile.TemporaryDirectory() as temp: + tmp = Path(temp) + fake_bin = tmp / "migration" + fake_bin.write_bytes(b"ELF-binary-placeholder") + fake_bin.chmod(0o755) + out = tmp / "dist" + out.mkdir() + + def fake_run(cmd, **kwargs): + if cmd[0] == "dpkg-deb": + Path(cmd[-1]).write_bytes(b"fake-deb-payload") + elif cmd[0] == "rpmbuild": + topdir = Path(cmd[2].split(" ", 1)[1]) + arch = cmd[4].split("-", 1)[0] + rpm_dir = topdir / "RPMS" / arch + rpm_dir.mkdir(parents=True, exist_ok=True) + (rpm_dir / f"rustfs-migration-0.2.0-1.{arch}.rpm").write_bytes(b"fake-rpm-payload") + + with mock.patch("shutil.which", return_value="/usr/bin/mock-tool"), \ + mock.patch("subprocess.run", side_effect=fake_run): + for goarch, deb_arch, rpm_arch in (("amd64", "amd64", "x86_64"), ("arm64", "arm64", "aarch64")): + deb = packager.build_deb(fake_bin, goarch, "0.2.0", out) + rpm = packager.build_rpm(fake_bin, goarch, "0.2.0", out) + self.assertEqual(deb.name, f"rustfs-migration_0.2.0_{deb_arch}.deb") + self.assertEqual(rpm.name, f"rustfs-migration-0.2.0-1.{rpm_arch}.rpm") + self.assertTrue(deb.with_name(deb.name + ".sha256").is_file()) + self.assertTrue(rpm.with_name(rpm.name + ".sha256").is_file()) + + +if __name__ == "__main__": + unittest.main()