diff --git a/.gitignore b/.gitignore index fbcb5e4..1d3d35c 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,9 @@ conflict.log conflict-*.log config.yaml + +/audit-results/ +/scripts/__pycache__/ +*.db.lock +*.db.lock-journal /dist/ diff --git a/README.md b/README.md index 1007d92..129a850 100644 --- a/README.md +++ b/README.md @@ -1,412 +1,136 @@ # migration -**English** | [简体中文](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) | [Русский](README_RU.md) +[English guide](docs/USAGE.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) | [Русский](README_RU.md) -`migration` copies the current objects from one S3-compatible cluster to another. Use it to backfill an older RustFS or MinIO cluster into a new one while applications continue writing to the destination. In the configuration, `old` is the source and `new` is the destination. Both use path-style S3 URLs. +在两个 S3 兼容集群之间执行可恢复的单向对象迁移。源端必须在迁移和验收期间冻结写入与删除;目标端必须支持 `PutObject` 和 `CompleteMultipartUpload` 的原子 `If-None-Match: *` 条件写。 -The tool copies missing keys, records conflicts in `conflict.log` and tracks progress in local SQLite files. It never deletes objects. The destination must honor `If-None-Match: *` on both `PutObject` and `CompleteMultipartUpload`. This lets a live application create a key even after the migration has checked it, without losing that write. +迁移不调用 DeleteObject 或 CopyObject。已有目标只在两端内容 SHA-256 一致时记为完成,否则报告冲突;不会主动覆盖冲突对象。此保证依赖目标端正确实现 S3 条件写语义,部署前必须验证对应服务版本。**不支持未经协调的在线双端删除**。迁移清单对象在目标端的业务删除也必须暂停或通过删除墓碑协调;仅禁止旧集群删除不能阻止历史对象被重新写入目标。客户端无法在两个独立集群之间建立原子删除事务。 -The copy preserves the current object body, `Content-Type`, `Cache-Control`, `Content-Disposition`, `Content-Encoding`, `Content-Language`, `Expires` and `x-amz-meta-*`. Version history, delete markers, Object Lock, bucket policies and lifecycle rules are outside the scope of a migration. +中文手册:[docs/使用手册.md](docs/使用手册.md) · English guide: [docs/USAGE.md](docs/USAGE.md) · Design: [docs/DESIGN.md](docs/DESIGN.md) -## Documentation +## 构建 -[Command reference](docs/USAGE.md) · [Operator handbook (Chinese)](docs/使用手册.md) · [Design](docs/DESIGN.md) - -## Quick start - -The commands below build the tool with Go 1.22 or later and run it from the repository root. After copying `config.example.yaml`, edit `config.yaml` to enter the endpoints and credentials for your clusters. - -```bash -git clone https://github.com/rustfs/migration.git -cd migration -CGO_ENABLED=0 go build -o bin/migration . -# or: make build -cp config.example.yaml config.yaml # source and target endpoints and keys -``` - -```bash -./bin/migration list -c config.yaml -./bin/migration run -c config.yaml --workers 16 --rate-limit 20M -./bin/migration status -c config.yaml -./bin/migration diff -c config.yaml +```sh +go build -o bin/migration . +# 或 make build ``` -Leave `bucket:` empty to migrate every bucket on the source. Set `bucket: photos`, or pass `--bucket photos`, to pin one bucket. +需要 Go 1.26 或更高版本;go.mod 指定已修补的 `go1.26.10` 工具链。SQLite 为纯 Go 实现,不需要 CGO。 -Use `--bucket ""` to select all source buckets even when YAML or `BUCKET` specifies one. +## 安全使用 -`--rate-limit 20M` lets all workers together read 20,000,000 bytes per second from the source. See [Rate limit](#rate-limit) for binary units and the scope of the limit. +1. 在应用、权限策略或存储快照层冻结源桶的写入和删除,包括生命周期删除,保持到最终验收完成。 +2. 为每次迁移使用独立状态目录;确认目标实现原子条件写,配置两端地址、区域和最小必要权限。 +3. 执行 `run --source-frozen`;该参数只是确认外部已冻结源端,**不会自动冻结 S3**。 +4. 检查失败、冲突和跳过记录,执行 `diff` 完整读回校验,再按业务切换方案处理流量。 -## Install - -Choose the archive for your platform under **Artifacts** in a successful [Build packages run](https://github.com/rustfs/migration/actions/workflows/packages.yml). Unpack the downloaded artifact, check the archive against the included SHA-256 digest, then extract the archive. Linux packages use `.tar.gz` (amd64 or arm64). Windows uses `.zip` (amd64) and the executable is `migration.exe`. - -```bash -./migration --version -``` - -```powershell -.\migration.exe --version -``` - -Protect `config.yaml` (`chmod 600` is a reasonable default). The process logs endpoints and object keys. It does not log credentials. - -## Configuration - -```bash +```sh cp config.example.yaml config.yaml -``` - -Set the HTTP or HTTPS endpoint and credentials for each cluster. Keep credentials in the dedicated fields. An endpoint URL cannot contain credentials, a query string or a fragment. The destination account needs `s3:CreateBucket` if a bucket must be created. - -```yaml -old: # source, read-only - endpoint: "http://10.0.0.1:9000" - access_key: "OLD_AK" - secret_key: "OLD_SK" - region: "us-east-1" -new: # target, read and write - endpoint: "http://haproxy.new.local:9000" - access_key: "NEW_AK" - secret_key: "NEW_SK" - region: "us-east-1" - -bucket: "" # empty = every bucket on the source -db_path: "./migration.db" -conflict_log: "./conflict.log" -spool_dir: "" # small-object temp dir; default is the db directory - -workers: 16 # objects at once; 0 or omit = 16 -multipart_threshold: 52428800 # >= 50 MiB uses multipart upload -multipart_part_size: 16777216 # 16 MiB; must be >= 5 MiB (5242880) -multipart_concurrency: 4 # parts of one large object; 0 or omit = 4 -rate_limit: 0 # aggregate source-read cap; 0 or omit = unlimited -``` - -`list` and `scan` need the source endpoint and keys. `run`, `migrate`, and `diff` need both sides. - -### Precedence - -Highest priority wins: - -1. CLI: `--bucket`, `--workers`, `--multipart-concurrency`, `--rate-limit` -2. Environment variables -3. YAML -4. Built-in defaults - -| Setting | Default when omitted | -| --- | --- | -| `workers` | 16 | -| `multipart_concurrency` | 4 | -| `multipart_threshold` | 50 MiB (52428800) | -| `multipart_part_size` | 16 MiB (16777216) | -| `rate_limit` | unlimited | -| `db_path` | `./migration.db` | -| `conflict_log` | `./conflict.log` | -| `spool_dir` | directory of `db_path` | -| `region` | `us-east-1` | - -Example: YAML `workers: 8`, environment `WORKERS=32`, and `--workers 4` together use **4**. - -### What zero means - -`0` is not the same knob on every field. - -| Field | YAML `0` or omitted | Environment `0` | CLI `0` | -| --- | --- | --- | --- | -| `workers` | default 16 | error | error (`--workers 0`) | -| `multipart_concurrency` | default 4 | error | error | -| `multipart_threshold` | default 50 MiB | no env var | no flag | -| `multipart_part_size` | default 16 MiB | no env var | no flag | -| `rate_limit` | unlimited | unlimited (`RATE_LIMIT=0`) | unlimited (`--rate-limit 0`) | - -A negative concurrency or size fails at startup. `WORKERS` and `MULTIPART_CONCURRENCY` must be plain integers. Put size suffixes on `RATE_LIMIT` only: `RATE_LIMIT=20M` is valid, `WORKERS=20M` is not. - -Set `multipart_part_size` between 5 MiB and 5 GiB (default 16 MiB). Objects over 5 GiB always use multipart upload. The tool increases part size as needed to stay within 10,000 parts and fails if that would exceed 5 GiB per part. - -A bucket name must not contain whitespace or `/`. - -### Environment variables - -Set variables override the YAML values. Unset variables leave the file alone. - -| Variable | Overrides | -| --- | --- | -| `OLD_ENDPOINT` `OLD_AK` `OLD_SK` `OLD_REGION` | source endpoint | -| `NEW_ENDPOINT` `NEW_AK` `NEW_SK` `NEW_REGION` | target endpoint | -| `REGION` | either side whose region is still empty after the specific variables | -| `BUCKET` | `bucket` | -| `DB_PATH` `CONFLICT_LOG` `SPOOL_DIR` | local paths | -| `WORKERS` `MULTIPART_CONCURRENCY` | concurrency (integer ≥ 1) | -| `RATE_LIMIT` | aggregate source-read cap (`20M`, `20MiB`, `0`, …) | - -## Commands - -```bash -./bin/migration --help -./bin/migration run --help -./bin/migration diff --help -``` - -| Command | What it does | Writes to the target | Concurrency and cap | -| --- | --- | --- | --- | -| `migration list -c config.yaml` | List every bucket on the source | No | None | -| `migration run -c config.yaml` | **Recommended.** Scan, then copy | Yes, without overwriting | Scan is single-threaded. Copy uses `workers`, `multipart_concurrency`, and `rate_limit` | -| `migration scan -c config.yaml` | Inventory the source into SQLite | No | Single-threaded. No rate limit | -| `migration migrate -c config.yaml` | Copy SQLite rows in `pending` or `failed` | Yes, without overwriting | `workers`, `multipart_concurrency`, and `rate_limit` | -| `migration status -c config.yaml` | Print local counters | No | None. No S3 calls | -| `migration diff -c config.yaml` | List the source and `HEAD` each key on the target | No | `workers` for parallel HEAD. No rate limit | -| `migration diff --extra -c config.yaml` | Same, and list keys that exist only on the target | No | `workers` | - -Flags shared by every command: - -| Flag | Meaning | -| --- | --- | -| `-c`, `--config` | Config file. Default `config.yaml` | -| `--bucket NAME` | Pin one bucket. Overrides YAML and `BUCKET` | -| `--workers N` | Objects copied at once for `run` / `migrate`, and parallel HEAD for `diff`. Must be ≥ 1 | -| `--multipart-concurrency N` | Parts uploaded at once inside one large object. Must be ≥ 1. Ignored by `list`, `scan`, `status`, and `diff` | -| `--rate-limit SIZE` | Aggregate source-read cap for object bodies in `run` / `migrate`. `0` is unlimited | -| `--version` | Print the version | -| `--help` | Bilingual help | - -`diff` also accepts `--extra`. - -`status` prints `BUCKET`, `TOTAL`, `PENDING`, `DONE`, `CONFLICT`, `SKIPPED`, and `FAILED`. With no bucket pinned, it reads `migration-*.db` next to `db_path`, and the configured database itself when that file is already bound to a bucket. If nothing is there yet, it says so and exits 0. Run `scan` or `run` first. - -## Workflows - -### Migrate every bucket - -```bash -./bin/migration list -c config.yaml -./bin/migration run -c config.yaml --workers 16 --rate-limit 20M +# 编辑 endpoint/凭证/独立 db_path,并在应用或存储端冻结源写入及删除 +./bin/migration list -c config.yaml +./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 +./bin/migration diff -c config.yaml ``` -For each bucket, `run` does the following: - -1. `HeadBucket` on the source. -2. `ListObjectsV2` the source into SQLite. This step is single-threaded. -3. Create the bucket on the target when it is missing. An existing bucket is not modified. -4. Copy missing keys with up to `workers` object transfers at a time. If another writer creates a key after the initial HEAD, the conditional write protects that object. The migrator checks the key again to decide between `done` and `conflict`. -5. At `multipart_threshold` and above, each object uses up to `multipart_concurrency` parallel parts. All source reads share the same bandwidth limit. -6. Check the size on the target. A single-part object is also checked by ETag when the ETags are comparable. See [Object state](#resume-and-object-state). - -Buckets are copied one after another, so `rate_limit` is the cap for the whole process. - -### One bucket - -```bash -./bin/migration run -c config.yaml \ - --bucket photos --workers 8 --multipart-concurrency 8 --rate-limit 30M -``` - -### Objects added on the source later - -`ListObjectsV2` cannot filter by modification time on the server. Catch-up is another full listing. New keys become `pending`. Rows that were `failed` or `skipped` return to `pending` when they are listed again. Rows that are `done` or `conflict` stay as they are, so a second pass does not re-upload them and does not overwrite the target. - -```bash -./bin/migration scan -c config.yaml -./bin/migration migrate -c config.yaml --workers 16 -./bin/migration diff -c config.yaml -``` - -`run` again is the same two steps in one command. - -### Inventory first - -```bash -./bin/migration scan -c config.yaml -./bin/migration status -c config.yaml # object counts, no S3 calls -./bin/migration migrate -c config.yaml --workers 16 -``` - -## Concurrency - -Use `workers` to adjust the number of objects copied at once. For large objects, `multipart_concurrency` also controls the number of parts read and uploaded in parallel. The defaults allow up to 16 objects with four parts each, or about 64 requests to one cluster. Size the worker pool for your disks, proxy and available memory. - -`scan` ignores `workers` and `rate_limit`. Listing is one page after another because each page needs the previous continuation token, and the rows land in one SQLite file. A slow scan is not fixed by `--workers`. `list`, `diff`, and `status` do not read object bodies, so the byte cap does not apply to them. `diff` does use `--workers` for HEAD. - -```text -workers = 4 objects at once - object A (small) ── one GET + PUT - object B (small) ── one GET + PUT - object C (large) ── multipart_concurrency ranged GETs + UploadPart - object D (large) ── the same -``` +最小配置: -Each active multipart transfer buffers up to one part per active part worker. The job queue holds at most 2,048 object descriptors. HTTP connections can be reused across requests, with at most 1,024 idle connections per host. - -Starting points: - -| Workload | Suggestion | -| --- | --- | -| Many small objects (kilobytes to a few megabytes), link has room | `workers` 16–64, leave `multipart_concurrency` at 4 | -| Mixed sizes | `workers` 8–32, `multipart_concurrency` 4–8 | -| A few very large objects | `workers` 2–8, `multipart_concurrency` 4–16 | -| One object failing and the log is hard to read | `--workers 1` | -| Proxy returns 503, timeouts, or the source disk is full | Lower `workers` first. If the slow objects are large, lower `multipart_concurrency` as well | -| Keep production bandwidth | `--rate-limit 20M`, then `30M` or `50M` after the source looks healthy. `0` removes the cap | -| Faster small objects | Raise `workers` | -| Faster one large object | Raise `multipart_concurrency`, or lower `multipart_part_size` (bytes, minimum 5 MiB) | - -During a copy, a progress line is logged about every 10 seconds: processed, copied, conflicts, skipped, failed, and bytes. - -Each small object in flight has one temp file in `spool_dir`, up to about `multipart_threshold` bytes, because `PutObject` needs a seekable body. If `/tmp` is a memory disk, point `spool_dir` at a real disk. More workers means more of those files at once. - -Use one process per database file. SQLite is opened in WAL mode with a single connection inside the process, so status updates stay serialized while object bytes stay on the worker pool. A second process on the same file still reports `database is locked`. - -## Rate limit - -Source reads share `rate_limit` across all workers and all parts. Listing keys, checking headers and uploading to the destination do not count towards that limit. +```yaml +old: + endpoint: https://old.example.com + access_key: OLD_AK + secret_key: OLD_SK + region: us-east-1 +new: + endpoint: https://new.example.com + access_key: NEW_AK + secret_key: NEW_SK + region: us-east-1 +bucket: photos # 空表示所有源桶;未知 YAML 字段会报错 +source_frozen: false # 已在外部冻结源写入/删除后才可设 true +# 每个迁移任务使用独立目录 +db_path: ./state/job-1/migration.db +conflict_log: ./state/job-1/conflict.log +spool_dir: ./state/job-1/spool +spool_max_bytes: 1073741824 +workers: 16 +multipart_threshold: 52428800 +multipart_part_size: 16777216 +multipart_concurrency: 4 +rate_limit: 0 +``` + +YAML、环境变量、命令行优先级:CLI > 环境变量 > YAML > 默认值。`source_frozen` 可由 `SOURCE_FROZEN=true` 或 `--source-frozen` 覆盖。两端支持 `session_token`,环境变量为 `OLD_SESSION_TOKEN` / `NEW_SESSION_TOKEN`。 + +其他环境变量:`OLD_ENDPOINT` `OLD_AK` `OLD_SK` `OLD_REGION`,`NEW_ENDPOINT` `NEW_AK` `NEW_SK` `NEW_REGION`,`REGION`,`BUCKET` `DB_PATH` `CONFLICT_LOG` `SPOOL_DIR` `WORKERS` `MULTIPART_CONCURRENCY` `RATE_LIMIT`。 + +## 命令和退出状态 + +| 命令 | 行为 | 目标写入 | +| --- | --- | --- | +| list | 列出源桶 | 无 | +| scan | 完整扫描源清单到 SQLite | 无 | +| run | 扫描完成后迁移 | 条件创建对象和必要的桶 | +| migrate | 使用已有完整清单重试 pending/failed | 条件创建对象和必要的桶 | +| status | 只读本地状态,不创建缺失 DB | 无 | +| diff | 检查两端桶,并完整读取等尺寸对象计算 SHA-256 | 无 | +| diff --extra | 另外报告仅目标存在的 key | 无 | -A small object is first read to disk and then uploaded. If both transfers use the same network interface, leave room for both reads and writes when setting the source-read limit. +`run` / `migrate` 未确认 source_frozen 时拒绝执行。对象传输失败、取消、持久化失败、未完成扫描和状态读取错误都返回非零退出码。`diff` 对缺失、大小差异、SHA-256 差异或无法验证返回失败;`--extra` 报告的目标独有对象允许存在,不单独令命令失败。 -### Units +conflict 表示保留目标现有数据,skipped 表示源返回明确 NoSuchKey;它们需要操作员审核,不能仅凭 `run` 退出 0 判定全部数据已迁移。未做完整扫描的 `migrate` 不再当作空任务成功。 -Suffixes are case-insensitive. A trailing `/s` is accepted and ignored. A bare number is bytes per second. `1.5M` is 1,500,000 bytes/s. +自动化验收可使用 `run --strict` 或 `migrate --strict`:只要状态库中仍有 pending、failed、conflict 或 skipped,命令就返回非零,包括前次运行遗留的状态。`diff --strict` 同时检查目标独有对象,并在发现时返回非零。严格模式仍不能代替冻结窗口和最终内容验收。 -| Written as | Bytes per second | -| --- | --- | -| `20M`, `20MB` | 20×1000×1000 = 20000000 | -| `30M` | 30000000 | -| `50M`, `50MB` | 50000000 | -| `20Mi`, `20MiB` | 20×1024×1024 = 20971520 | -| `2K`, `2KB` | 2000 | -| `2Ki`, `2KiB` | 2048 | -| `1G`, `1GB` | 1000000000 | -| `1Gi`, `1GiB` | 1073741824 | -| `1T`, `1TB` / `1Ti`, `1TiB` | 1000⁴ / 1024⁴ | -| `1048576` | 1048576 | -| `0`, `0M`, or omit | unlimited | +`diff --issues-jsonl /path/to/new-file.jsonl` 将全部差异逐条写入新文件,字段为 bucket、key、kind 和 detail;文件已存在时拒绝覆盖。目标独有 key 需要同时使用 `--extra` 或 `--strict` 才会记录。任务出错或中断时文件可能只包含部分结果,必须结合命令退出状态判断是否完整。 -`M` is decimal. `Mi` is binary. `20M` is about 5% under `20MiB` (20000000 versus 20971520). A negative value or an unknown suffix fails at startup. +## 完整性与恢复 -```yaml -rate_limit: 20M -``` +- 清单记录源大小、ETag 和时间;迁移重新检查源身份,并用 If-Match 和可用的 VersionId 固定读取。ETag 是并发条件,不被当作通用 MD5。 +- 小对象先落临时文件;大对象按范围读取并校验 Content-Range、ETag 和精确长度,每片也落临时文件,避免将整个分片保留在内存。 +- 新对象提交后从目标读回并比较 SHA-256。已有同尺寸目标也完整读取两端校验,不再把 multipart ETag 或缺失 ETag 降级为“大小一致即完成”。 +- 分片对象额外顺序读取一遍源以计算完整摘要。单对象正常复制约读取源一遍、目标一遍;分片复制约读取源两遍、目标一遍。源摘要读取也受 rate-limit 限制。 +- SQLite 绑定源/目标 endpoint 和 bucket;不允许更换 endpoint 复用清单。扫描记录 generation,中断扫描使完成凭证失效。 +- 有已处理记录而无身份的旧库拒绝自动接管。升级时使用新状态目录重新扫描;已有目标将重新完整验证,无须删除目标对象。 +- 单写者锁拒绝多进程同时使用同一个状态库;只读 status 可以并行运行。保留 `.db`、`-wal`、`-shm` 及 `.lock` 文件,不要在任务运行时手工删除锁文件。 +- 全桶模式保留任务文件名:`job-a.db` 派生 `job-a-photos.db`,不会和 `job-b.db` 的桶清单混用。 +- 源同 key 的身份变化会重新进入待验证状态;已有目标仍不被覆盖。这不是持续同步工具。 -```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 # unlimited, on purpose -``` +恢复是对象级重试。kill -9 后未完成分片可能留在服务端,应配置清理未完成分片的生命周期;工具不持久化分片 uploadId。不能在最后一次校验后允许数据任意变化、再把旧校验当成切换依据。 -## Resume and object state +## 并发与限速 -The first Ctrl-C or `SIGTERM` cancels the worker pool. Objects that have not started stay `pending`. An in-flight multipart upload is aborted, which releases that upload and does not delete a committed object. State already written to SQLite is kept. A second signal exits immediately with code 130. +`workers` 默认 16,控制同时处理的对象;`multipart_concurrency` 默认 4,控制单个大对象分片数。workers 上限 1024,分片并发上限 64,乘积上限 4096。不要用最大值作为生产默认。 -If the source ETag changes between inventory and transfer, the copy fails. Run `scan` to refresh its row before retrying `migrate`, or repeat `migration run`. +`rate_limit` 是 run/migrate 的所有源正文读取共享速率,不限制目标上传/读回,也不限制 diff。`20M` / `20MB` 为 20,000,000 B/s;`20MiB` 为 20×1024×1024 B/s;`0` 为不限速。**diff 会完整读取两端数据**,需要安排网络和读负载窗口。 -A canceled request, a deadline, and `request canceled` are `failed`, including when the error text also contains `NotFound` or `StatusCode: 404`. A multipart abort often reports `NoSuchUpload`. That is not a missing source object. `skipped` means the source request finished and the object was really gone. +分片大小为 5MiB 到 5GiB;工具可为超过 10,000 片的对象增大片大小,并拒绝超出分片限制的对象。`spool_max_bytes` 默认 1 GiB,限制当前迁移任务并发临时文件预留总量(含每个文件用于检测超长正文的 1 字节);超过预算的单个对象或分片会失败,需提高预算或降低分片大小/分片阈值。该限制不包含异常退出遗留文件、其他进程和目录内容,也不保证磁盘剩余空间。独立目录中断后确认没有运行中的任务,再人工清理残留文件;监控磁盘并使用目标端分片生命周期清理。 -```bash -./bin/migration migrate -c config.yaml -``` +客户端使用 HTTP/1,响应头等待上限 30 秒,单次阻塞正文读取和连接写入上限 90 秒;限速造成的两次读取之间等待不会触发该超时。网络失败按失败对象保留以便重试。 -`migrate` retries `pending` and `failed` only. +## 能力边界 -| State | Meaning | A later scan | -| --- | --- | --- | -| `pending` | Waiting to copy | Refreshes size and ETag | -| `failed` | Last attempt failed. `migrate` retries it. `last_error` has the message | Returns the row to `pending` | -| `skipped` | The source request finished with 404 / `NoSuchKey` | Returns the row to `pending` if the key is listed again | -| `done` | Copied and checked, or the target already matched the inventory | Left unchanged | -| `conflict` | The target has the key and it does not match the inventory. Not overwritten | Left unchanged | +迁移当前对象内容、常见内容头和用户 metadata。不会复制版本历史、删除标记、桶策略、生命周期、对象 tags、ACL、Object Lock/retention/legal hold、存储等级或源 SSE 配置。目标自身默认加密策略仍生效。使用这些功能的业务需要独立迁移方案,不应直接以本工具完成桶级功能迁移。 -When the key already exists, the migrator records `done` only if the size and both nonempty ETags match. Otherwise it records `conflict` and leaves the destination untouched. Identical bytes uploaded with different part boundaries can have different ETags. If an upload finished just before a crash, check such conflicts before retiring the source. +目标端不支持条件写、无法返回稳定对象身份、或不能读回内容时不得作为可靠迁移目标。不要通过取消 checksum 校验或改成只比较大小绕过问题。 -Each conflict is one TSV line in the conflict log, with RFC3339 UTC timestamps: +## 测试 -```text - +```sh +go test ./... +go test -race ./... +go vet ./... +# 可选:显式选择 RustFS 1.0.4 二进制,启动两个临时回环实例 +python3 scripts/audit-local-rustfs.py \ + --rustfs-binary /absolute/path/rustfs --expect-version 1.0.4 ``` -Keys containing control characters or beginning with a double quote are written as Go-quoted strings. - -One configured bucket uses `db_path` and `conflict_log` as written. Every-bucket mode derives sibling files: +将 `/absolute/path/rustfs` 替换为待测二进制的绝对路径。启动器先执行该文件的 `--version`,版本必须与 `1.0.4` 精确一致,否则在启动实例前退出;不会从 PATH 自动选择另一个 RustFS。它记录二进制路径、版本输出和 SHA-256,使用同一文件启动两个临时回环实例,结束后清理进程与临时数据。默认证据目录为 `audit-results/rustfs-1.0.4/`,其中 `rustfs-binary.json` 标识实际受测二进制;可用 `--output-dir` 指定其他目录。 -- `migration-.db` -- `conflict-.log` +审计发现的确定性场景现已纳入默认回归测试,不再需要 audit build tag。`real_s3` 测试保持独立,必须实际执行后才能得出对应服务版本的结论。旧 RustFS `1.0.0-alpha.61` 的分片 ETag 失败仅保留为历史记录,不能当作 `1.0.4` 的通过或失败结果;上线前应对拟部署版本运行真实服务测试。 -`migrate` requires an inventory created by `scan` or `run`. State is bound to the bucket and cluster endpoints. Before reopening a database from an older release, check that it belongs to these endpoints. The first scan records the source and the first migration records the destination. If a scan is interrupted or fails, rerun `scan` or `run` before using `migrate`. Older databases have no scan-completion marker. Rescan if you cannot confirm their inventory is complete. +历史审计:[2026-10-29 审计](docs/AUDIT-2026-10-29.md)。修复验证结果见 [修复记录](docs/FIXES-2026-10-29.md)。 -## Checking the target with `diff` - -`diff` checks sizes and comparable ETags without downloading objects. `size_only` counts keys included in `ok` for which only size was checked. Use `--extra` to build a temporary index and report keys found only on the destination. For an empty source bucket, `diff` checks that the destination bucket exists and exits 1 if it is missing. - -```bash -./bin/migration diff -c config.yaml --workers 32 -./bin/migration diff -c config.yaml --extra -``` - -```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 -``` +## English summary -The second summary line repeats the counters in Chinese, because that is what the command prints. At most 50 issue lines are shown; the rest are counted in a trailing “and N more” line. - -| Result | Meaning | -| --- | --- | -| `missing` | Present on the source and absent on the destination | -| `size` / `etag` | Same key, contents do not match. Often a live write on the target. This tool will not overwrite it | -| `extra` | Only on the target. Reported with `--extra`. Usually a write that already landed on the new cluster. Not a failure | - -Exit code is 1 when any key is missing or mismatched in size or ETag. `extra_on_target` does not fail the command. With several buckets, a gap fails that bucket and the command continues with the rest, then exits 1 if any bucket failed. - -## Safety - -| Guarantee | How | -| --- | --- | -| No overwrite of a target object | `HeadObject` → `PutObject` / `CompleteMultipartUpload` (`If-None-Match: *`) | -| No delete | No `DeleteObject`. A failed multipart upload is aborted only | -| No cross-bucket mix-up | `HeadBucket`, a bucket-name check on each list page, and a bucket name stored in the SQLite file | -| Source deletes during the run | A finished source 404 is `skipped`. Cancel and timeout are `failed` and will be retried | -| Crash and cancel resume | Per-object state is in a SQLite WAL file. The first signal cancels workers; the next `migrate` continues | -| Bounded memory | Small objects spool to disk. Large objects are read by part. The job queue is capped | -| Check after copy | Size always. ETag as well for a single-part object when both ETags are comparable | - -Out of scope: version history, delete markers, Object Lock, bucket policies, lifecycle rules, two-way sync, and server-side `CopyObject` (the clusters are separate, so the bytes go through this process). - -## Troubleshooting - -| What you see | What to do | -| --- | --- | -| `read config … copy config.example.yaml first` | The `-c` path is missing. Copy `config.example.yaml` | -| `old.endpoint is required` | Set `old.endpoint` or `OLD_ENDPOINT`. The target side reports `new.endpoint is required` the same way. Keys report `access_key` / `secret_key` | -| `workers must be >= 1` | `--workers`, `WORKERS`, or YAML `workers` is below 1. YAML `0` means “default 16”. `0` on the CLI or in the environment is an error | -| `multipart_concurrency must be >= 1` | Same rule, for part concurrency. YAML `0` means “default 4” | -| `env WORKERS="…" is not an integer` | `WORKERS` must be a bare integer. Bandwidth belongs in `RATE_LIMIT=20M` | -| `multipart_part_size must be >= 5242880` | Non-final parts must be at least 5 MiB. The default 16 MiB is already valid. The value is not raised automatically | -| `unknown size suffix` or `rate limit` | `rate_limit`, `RATE_LIMIT`, or `--rate-limit` was not recognized. Decimal is `20M`. Binary is `20Mi` or `20MiB` | -| `head bucket "…"` | The bucket is missing, the endpoint is wrong, or the key cannot read it. On the target, a create failure says `create bucket "…" on target (need s3:CreateBucket)` | -| Source still busy at `20M` | `20M` is 20000000 bytes/s of source body reads. The upload is outside that cap. On a shared NIC, lower the number | -| `scan` or `diff` did not slow down | Expected. The cap applies while `run` / `migrate` read object bodies | -| Scan stays slow after raising `--workers` | Expected. `scan` is single-threaded. Concurrency starts at the copy, and at `diff` HEAD | -| Many 503s or timeouts | Lower `workers`. For large objects, lower `multipart_concurrency` so `workers × multipart_concurrency` fits the proxy `maxconn` | -| Many `etag mismatch` results | Check the content of the affected key independently. Multipart layout or server-side encryption can change ETags. | -| `db_path is bound to bucket "…"` | That file already belongs to another bucket. Use a different `db_path` | -| `database is locked` | Two processes are writing the same database. Use one process per file | -| Disk fills with temp files | Move `spool_dir` to a large disk, or lower `workers` | -| Ctrl-C does not return | Wait for the current request, or press it again (exit 130) | -| `diff` still reports `missing` | For `failed` rows, check `last_error` and retry. If the key was already `done` or `conflict`, use a separate state directory for a fresh inventory. In all-bucket mode, changing only the database filename is insufficient. | - -## Exit codes - -| Code | Meaning | -| --- | --- | -| 0 | Completed. Conflicts and skipped source keys are reported separately. | -| 1 | Invalid configuration, an interrupted or failed operation, one or more failed object transfers, or `diff` found missing or mismatched keys. | -| 130 | A second `SIGINT` or `SIGTERM`. The process exits immediately | - -Errors from the command are printed as `error: …` on stderr. - -## License - -Apache License 2.0. Copyright 2024-2026 RustFS, Inc. +This is a resumable one-way migration tool for a **frozen source**. Freeze source writes and deletes externally, then acknowledge with `--source-frozen`. The destination must implement atomic `If-None-Match: *` for both PutObject and CompleteMultipartUpload. Existing objects are read and compared with full SHA-256; mismatches remain conflicts. Copy failures and cancellation return errors. `diff` reads full bodies on both clusters and requires GetObject permissions and bandwidth. See the [English guide](docs/USAGE.md) for migration and upgrade steps. diff --git a/README_DE.md b/README_DE.md index c33c1e0..a2683e6 100644 --- a/README_DE.md +++ b/README_DE.md @@ -2,6 +2,8 @@ [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. + `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). Fehlende Objekte werden kopiert, Konflikte in `conflict.log` protokolliert. Den Fortschritt speichert das Programm lokal in SQLite. Es löscht keine Objekte. Das Ziel muss `If-None-Match: *` bei `PutObject` und `CompleteMultipartUpload` auswerten. So bleiben auch Objekte erhalten, die eine Anwendung erst nach der Prüfung angelegt hat. diff --git a/README_ES.md b/README_ES.md index 24c41b2..8736568 100644 --- a/README_ES.md +++ b/README_ES.md @@ -2,6 +2,8 @@ [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. + `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. La herramienta copia las claves que faltan, anota los conflictos en `conflict.log` y guarda el progreso en una base de datos SQLite local. No elimina objetos. El destino debe respetar `If-None-Match: *` tanto en `PutObject` como en `CompleteMultipartUpload`. Así se conservan incluso los objetos que otra aplicación cree después de la comprobación inicial. diff --git a/README_FR.md b/README_FR.md index d32b8cc..6a6cd00 100644 --- a/README_FR.md +++ b/README_FR.md @@ -2,6 +2,8 @@ [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. + `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. L’outil copie les clés manquantes, consigne les conflits dans `conflict.log` et enregistre sa progression dans une base SQLite locale. Il ne supprime aucun objet. La destination doit prendre en charge `If-None-Match: *` pour `PutObject` et `CompleteMultipartUpload`. Un objet créé par une application après la vérification initiale reste ainsi intact. diff --git a/README_JA.md b/README_JA.md index faf20da..7316f6c 100644 --- a/README_JA.md +++ b/README_JA.md @@ -2,6 +2,8 @@ [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 のみで完了と判断しないでください。 + `migration` は、S3 互換クラスター間でオブジェクトの現行バージョンをコピーするツールです。たとえば、アプリケーションの書き込み先を新しいクラスターに切り替えた後、旧 RustFS や MinIO クラスターに残ったデータを移行できます。設定では `old` が移行元、`new` が移行先です。どちらもバケット名をパスに含める形式でアクセスします。 移行先にないキーをコピーし、競合は `conflict.log` に、進捗はローカルの SQLite に記録します。オブジェクトを削除する操作はありません。移行先は `PutObject` と `CompleteMultipartUpload` の両方で `If-None-Match: *` に対応している必要があります。これにより、存在確認の直後にアプリケーションが同じキーで書き込んだ場合も、そのオブジェクトを保護できます。 diff --git a/README_KO.md b/README_KO.md index 8f703a4..f663b15 100644 --- a/README_KO.md +++ b/README_KO.md @@ -2,6 +2,8 @@ [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만으로 완료를 판단하지 마세요. + `migration`은 S3 호환 클러스터 간에 객체의 현재 버전을 복사하는 도구입니다. 애플리케이션의 쓰기 요청을 새 클러스터로 전환한 뒤에도 기존 RustFS 또는 MinIO 클러스터에 남은 데이터를 옮길 수 있습니다. 설정에서 `old`는 원본, `new`는 대상을 가리킵니다. 두 클러스터 모두 URL 경로에 버킷 이름을 넣는 방식을 사용합니다. 대상에 없는 키만 복사하고 충돌은 `conflict.log`에, 진행 상황은 로컬 SQLite 데이터베이스에 기록합니다. 객체는 삭제하지 않습니다. 대상에서는 `PutObject`와 `CompleteMultipartUpload` 모두 `If-None-Match: *` 조건을 지원해야 합니다. 그래야 존재 여부를 확인한 직후 애플리케이션이 같은 키로 쓴 객체도 보호할 수 있습니다. diff --git a/README_PT.md b/README_PT.md index 77193ff..46da0cd 100644 --- a/README_PT.md +++ b/README_PT.md @@ -2,6 +2,8 @@ [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. + 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. A ferramenta copia as chaves em falta, regista os conflitos em `conflict.log` e guarda o progresso numa base de dados SQLite local. Nenhum objeto é eliminado. O destino tem de respeitar `If-None-Match: *` nas operações `PutObject` e `CompleteMultipartUpload`. Assim, mesmo que a aplicação crie a chave depois da verificação inicial, o objeto fica protegido. diff --git a/README_RU.md b/README_RU.md index ec820b9..af08b89 100644 --- a/README_RU.md +++ b/README_RU.md @@ -2,6 +2,8 @@ [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 доказательством завершения. + Утилита `migration` копирует текущие версии объектов из одного S3-совместимого кластера в другой. Например, с её помощью можно перенести архив из RustFS или MinIO, когда приложение уже пишет в новый кластер. В конфигурации `old` обозначает источник, а `new` — приёмник. Имя бакета указывается в пути запроса к S3. Утилита копирует недостающие объекты, записывает конфликты в `conflict.log` и сохраняет ход переноса в локальной базе SQLite. Объекты не удаляются. Приёмник должен учитывать условие `If-None-Match: *` для `PutObject` и `CompleteMultipartUpload`. Тогда объект, созданный приложением после проверки ключа, также будет сохранён. diff --git a/README_ZH.md b/README_ZH.md index 01549a1..6a914cb 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -2,6 +2,8 @@ [English](README.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) | [Русский](README_RU.md) +**重要:本翻译包含过时内容。** 请以[最新使用手册](docs/使用手册.md)和[安全要求](README.md)为准:从扫描到最终验收必须在外部冻结源端写入和删除,并协调目标端删除。`--source-frozen` 不会自动冻结;请验证目标条件写,不能仅凭退出码 0 判定完成。 + `migration` 用于将当前对象从一个兼容 S3 的集群复制到另一个集群。例如,业务已切换到新集群写入,但仍需从旧的 RustFS 或 MinIO 集群补齐历史数据。配置中的 `old` 为源集群,`new` 为目标集群,两端均采用路径式寻址。 工具会补齐缺失的对象,将同名冲突记入 `conflict.log`,并用本地 SQLite 数据库保存进度。迁移不会删除对象。目标端的 `PutObject` 和 `CompleteMultipartUpload` 都必须支持 `If-None-Match: *` 条件写入。这样,即使业务在迁移检查之后才写入同名对象,也能保留该对象。 diff --git a/cmd/audit_test.go b/cmd/audit_test.go new file mode 100644 index 0000000..6001419 --- /dev/null +++ b/cmd/audit_test.go @@ -0,0 +1,265 @@ +package cmd + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/rustfs/migration/internal/config" + "github.com/rustfs/migration/internal/fakes3" + "github.com/rustfs/migration/internal/s3client" + "github.com/rustfs/migration/internal/store" +) + +// A permanently denied source read leaves the destination incomplete. The +// real CLI must return an error so a shell migration gate cannot approve it. +func TestAuditRunReportsObjectFailure(t *testing.T) { + source := fakes3.NewWithObjects(t, "photos", map[string][]byte{"key": []byte("body")}, time.Now()) + defer source.Close() + deniedSource := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && r.URL.Path == "/photos/key" { + w.WriteHeader(http.StatusForbidden) + return + } + source.Config.Handler.ServeHTTP(w, r) + })) + defer deniedSource.Close() + target := fakes3.New(t) + defer target.Close() + dir := t.TempDir() + dbPath := filepath.Join(dir, "migration.db") + configPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, configPath, deniedSource.URL, target.URL, dbPath, filepath.Join(dir, "conflict.log"), dir, "bucket: photos\nworkers: 1\n") + _, runErr := execRoot(t, "run", "-c", configPath) + st, err := store.Open(dbPath, "photos") + if err != nil { + t.Fatal(err) + } + defer st.Close() + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if counts.Failed != 1 || counts.Done != 0 { + t.Fatalf("fixture must leave one failed object: %+v", counts) + } + if _, exists := target.Object("photos", "key"); exists { + t.Fatal("fixture unexpectedly copied the denied object") + } + if runErr == nil { + t.Fatalf("run returned success with a missing target object and failed=%d", counts.Failed) + } +} + +func TestAuditStatusReportsCorruptState(t *testing.T) { + dir := t.TempDir() + dbPath := filepath.Join(dir, "migration.db") + if err := os.WriteFile(dbPath, []byte("this is not a SQLite database"), 0600); err != nil { + t.Fatal(err) + } + configPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, configPath, "http://unused-source", "http://unused-target", dbPath, filepath.Join(dir, "conflict.log"), dir, "bucket: photos\n") + if _, err := execRoot(t, "status", "-c", configPath); err == nil { + t.Fatal("status returned success although its only state DB could not be read") + } +} + +func TestAuditMigrateRequiresScannedInventory(t *testing.T) { + source := fakes3.NewWithObjects(t, "photos", map[string][]byte{"key": []byte("body")}, time.Now()) + defer source.Close() + target := fakes3.New(t) + defer target.Close() + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, configPath, source.URL, target.URL, filepath.Join(dir, "never-scanned.db"), filepath.Join(dir, "conflict.log"), dir, "bucket: photos\nworkers: 1\n") + _, err := execRoot(t, "migrate", "-c", configPath) + if _, exists := target.Object("photos", "key"); exists { + t.Fatal("fixture unexpectedly migrated unscanned object") + } + if err == nil { + t.Fatal("migrate silently created a fresh empty inventory and returned success without copying any source keys") + } +} + +func TestAuditMigrateReturnsCancellation(t *testing.T) { + source := fakes3.NewWithObjects(t, "photos", map[string][]byte{"key": []byte("body")}, time.Now()) + defer source.Close() + started := make(chan struct{}) + source.BlockGetsUntilCancel(started) + target := fakes3.New(t) + defer target.Close() + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, configPath, source.URL, target.URL, filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, "bucket: photos\nworkers: 1\n") + cfg, err := config.Load(configPath) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + oldCli, err := s3client.New(ctx, cfg.Old) + if err != nil { + t.Fatal(err) + } + newCli, err := s3client.New(ctx, cfg.New) + if err != nil { + t.Fatal(err) + } + if err := scanOne(ctx, cfg, oldCli, "photos"); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { done <- migrateOne(ctx, cfg, oldCli, newCli, "photos") }() + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("copy did not reach blocked GET") + } + cancel() + select { + case err := <-done: + if err == nil { + t.Fatal("migration returned success after cancellation with an incomplete object") + } + case <-time.After(5 * time.Second): + t.Fatal("migration did not return after cancellation") + } +} + +// Unlike the existing 40 ms sleep assertion, this barrier waits for the second +// part to reach UploadPart. It checks real parallelism without assuming a +// 5 MiB download and race-instrumented hashing complete in less than 40 ms. +func TestAuditMultipartConcurrencyWithBarrier(t *testing.T) { + const partSize = 5 * 1024 * 1024 + body := bytes.Repeat([]byte("z"), partSize+32) + source := fakes3.NewWithObjects(t, "photos", map[string][]byte{"large.bin": body}, time.Now()) + defer source.Close() + target := fakes3.New(t) + defer target.Close() + var started atomic.Int32 + both := make(chan struct{}) + barrierTarget := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPut && r.URL.Query().Get("partNumber") != "" { + if started.Add(1) == 2 { + close(both) + } + select { + case <-both: + case <-r.Context().Done(): + return + } + } + target.Config.Handler.ServeHTTP(w, r) + })) + defer barrierTarget.Close() + dir := t.TempDir() + configPath := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, configPath, source.URL, barrierTarget.URL, filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, "bucket: photos\nworkers: 1\nmultipart_concurrency: 2\n") + cfg, err := config.Load(configPath) + if err != nil { + t.Fatal(err) + } + cfg.MultipartThreshold = partSize + cfg.MultipartPartSize = partSize + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + oldCli, err := s3client.New(ctx, cfg.Old) + if err != nil { + t.Fatal(err) + } + newCli, err := s3client.New(ctx, cfg.New) + if err != nil { + t.Fatal(err) + } + if err := scanOne(ctx, cfg, oldCli, "photos"); err != nil { + t.Fatal(err) + } + if err := migrateOne(ctx, cfg, oldCli, newCli, "photos"); err != nil { + t.Fatal(err) + } + if ctx.Err() != nil || started.Load() != 2 { + t.Fatalf("expected two simultaneous part uploads: started=%d ctx=%v", started.Load(), ctx.Err()) + } + copied, ok := target.Object("photos", "large.bin") + if !ok || !bytes.Equal(copied, body) { + t.Fatal("multipart fixture was not copied intact") + } +} + +func TestSourceFrozenCLIOverride(t *testing.T) { + path := writeTestConfig(t) + for _, value := range []string{"true", "false"} { + cfg, err := withStatusConfig(t, []string{"status", "-c", path, "--source-frozen=" + value}) + if err != nil || cfg.SourceFrozen != (value == "true") { + t.Fatalf("--source-frozen=%s: cfg=%+v err=%v", value, cfg, err) + } + } +} + +func TestWritesRequireFrozenSourceBeforeAnyRemoteRequest(t *testing.T) { + var requests atomic.Int32 + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + http.Error(w, "no remote requests expected", http.StatusForbidden) + }) + source, target := httptest.NewServer(handler), httptest.NewServer(handler) + defer source.Close() + defer target.Close() + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, path, source.URL, target.URL, filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, "bucket: photos\n") + for _, command := range []string{"run", "migrate"} { + _, err := execRoot(t, command, "-c", path, "--source-frozen=false") + if err == nil || !strings.Contains(err.Error(), "source_frozen") { + t.Fatalf("unfrozen %s should fail explicitly: %v", command, err) + } + } + if got := requests.Load(); got != 0 { + t.Fatalf("unfrozen migration issued %d remote requests", got) + } +} + +func TestStatusDoesNotCreateMissingInventory(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + dbPath := filepath.Join(dir, "missing.db") + writeClusterConfig(t, path, "http://unused-source", "http://unused-target", dbPath, filepath.Join(dir, "conflict.log"), dir, "bucket: photos\n") + if _, err := execRoot(t, "status", "-c", path); err == nil { + t.Fatal("status succeeded without inventory") + } + if _, err := os.Stat(dbPath); !os.IsNotExist(err) { + t.Fatalf("status created a state database: %v", err) + } +} + +func TestStatusTargetsUsesConfiguredBasename(t *testing.T) { + cfg := &config.Config{DBPath: filepath.Join(t.TempDir(), "custom.db")} + path := cfg.DBPathFor("photos") + st, err := store.Open(path, "photos") + if err != nil { + t.Fatal(err) + } + if err := st.Close(); err != nil { + t.Fatal(err) + } + targets, err := statusTargets(cfg) + if err != nil || len(targets) != 1 || targets[0].path != path || targets[0].bucket != "photos" { + t.Fatalf("custom state files were not found: targets=%+v err=%v", targets, err) + } +} + +func TestAllBucketStatusRejectsMissingInventory(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, path, "http://unused-source", "http://unused-target", filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, "") + if _, err := execRoot(t, "status", "-c", path); err == nil || !strings.Contains(err.Error(), "no state DBs") { + t.Fatalf("empty all-bucket status must report missing inventory: %v", err) + } +} diff --git a/cmd/cli_regression_test.go b/cmd/cli_regression_test.go index 7f978db..3bdb6e2 100644 --- a/cmd/cli_regression_test.go +++ b/cmd/cli_regression_test.go @@ -2,6 +2,7 @@ package cmd import ( "bytes" + "encoding/json" "io" "net/http" "net/http/httptest" @@ -150,11 +151,29 @@ func TestCLIMigrateMultipartAndCleanDiff(t *testing.T) { defer oldS3.Close() newS3 := fakes3.New(t) defer newS3.Close() - newS3.RequireConcurrentParts(2) + var started atomic.Int32 + both := make(chan struct{}) + barrier := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPut && r.URL.Query().Get("partNumber") != "" { + if started.Add(1) == 2 { + close(both) + } + select { + case <-both: + case <-time.After(10 * time.Second): + http.Error(w, "parts did not overlap", http.StatusRequestTimeout) + return + case <-r.Context().Done(): + return + } + } + newS3.Config.Handler.ServeHTTP(w, r) + })) + defer barrier.Close() dir := t.TempDir() cfgPath := filepath.Join(dir, "config.yaml") - writeClusterConfig(t, cfgPath, oldS3.URL, newS3.URL, filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, ` + writeClusterConfig(t, cfgPath, oldS3.URL, barrier.URL, filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, ` bucket: photos workers: 1 multipart_concurrency: 1 @@ -169,9 +188,8 @@ multipart_part_size: 5242880 if err != nil { t.Fatalf("migrate: %v\n%s", err, out) } - got := newS3.MaxPartInFlight() - if got != 2 { - t.Fatalf("--multipart-concurrency 2 max in-flight parts=%d", got) + if got := started.Load(); got != 2 { + t.Fatalf("--multipart-concurrency 2 must reach two concurrent uploads, got=%d", got) } body, ok := newS3.Object("photos", "large.bin") if !ok || !bytes.Equal(body, payload) { @@ -192,7 +210,7 @@ multipart_part_size: 5242880 func writeClusterConfig(t *testing.T, path, oldURL, newURL, dbPath, conflictPath, spool, extra string) { t.Helper() - body := "old: {endpoint: " + quote(oldURL) + ", access_key: a, secret_key: b}\n" + + body := "source_frozen: true\n" + "old: {endpoint: " + quote(oldURL) + ", access_key: a, secret_key: b}\n" + "new: {endpoint: " + quote(newURL) + ", access_key: c, secret_key: d}\n" + "db_path: " + quote(dbPath) + "\n" + "conflict_log: " + quote(conflictPath) + "\n" + @@ -245,107 +263,44 @@ func assertNoUnsafeCalls(t *testing.T, oldS3, newS3 *fakes3.Server) { } } -func TestMigrateRequiresCompletedScanAndRejectsNewTarget(t *testing.T) { - source := fakes3.New(t) - defer source.Close() - target := fakes3.New(t) - defer target.Close() - dir := t.TempDir() - cfg := filepath.Join(dir, "config.yaml") - dbPath := filepath.Join(dir, "inventory.db") - configure := func(dst string) { - writeClusterConfig(t, cfg, source.URL, dst, dbPath, filepath.Join(dir, "conflict.log"), dir, "bucket: photos\n") - } - configure(target.URL) - if _, err := execRoot(t, "migrate", "-c", cfg); err == nil { - t.Fatal("migrate succeeded without a scan") - } - if _, err := os.Stat(dbPath); !os.IsNotExist(err) { - t.Fatalf("missing inventory was created: stat=%v", err) - } - if _, err := execRoot(t, "scan", "-c", cfg); err == nil { - t.Fatal("scan of nonexistent source bucket succeeded") - } - source.Put("photos", "k", []byte("data"), time.Now(), fakes3.Metadata{}) - if _, err := execRoot(t, "migrate", "-c", cfg); err == nil { - t.Fatal("migrate accepted an incomplete scan") - } - if _, err := execRoot(t, "run", "-c", cfg); err != nil { - t.Fatalf("run after failed scan: %v", err) - } - - replacement := fakes3.New(t) - defer replacement.Close() - configure(replacement.URL) - if _, err := execRoot(t, "migrate", "-c", cfg); err == nil { - t.Fatal("migrate silently reused terminal rows for another target") - } - resp, err := http.Head(replacement.URL + "/photos") - if err != nil { - t.Fatal(err) - } - resp.Body.Close() - if resp.StatusCode != http.StatusNotFound { - t.Fatalf("target bucket created before state validation: %s", resp.Status) - } -} - -func TestStatusReportsInvalidStateFile(t *testing.T) { - dir := t.TempDir() - cfg := filepath.Join(dir, "config.yaml") - path := filepath.Join(dir, "migration-photos.db") - if err := os.WriteFile(path, []byte("unrelated file"), 0o600); err != nil { - t.Fatal(err) - } - writeClusterConfig(t, cfg, "", "", filepath.Join(dir, "migration.db"), filepath.Join(dir, "conflict.log"), dir, "") - if _, err := execRoot(t, "status", "-c", cfg); err == nil { - t.Fatal("status silently accepted corrupt inventory") - } -} - -func TestFailedRescanBlocksCopyAndBadTargetCanBeCorrected(t *testing.T) { - src := fakes3.NewWithObjects(t, "photos", map[string][]byte{"data": []byte("ok")}, time.Now()) +func TestDiffCLIExportsIssuesJSONLWithoutOverwriting(t *testing.T) { + src := fakes3.NewWithObjects(t, "photos", map[string][]byte{"missing\nkey": []byte("source")}, time.Now()) defer src.Close() - dst := fakes3.New(t) + dst := fakes3.NewWithObjects(t, "photos", map[string][]byte{"extra": []byte("target")}, time.Now()) defer dst.Close() - var denyList atomic.Bool - source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if denyList.Load() && r.URL.Query().Has("list-type") { - w.WriteHeader(http.StatusForbidden) - return - } - src.Config.Handler.ServeHTTP(w, r) - })) - defer source.Close() - denied := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusForbidden) - })) - defer denied.Close() dir := t.TempDir() cfg := filepath.Join(dir, "config.yaml") - configure := func(target string) { - writeClusterConfig(t, cfg, source.URL, target, filepath.Join(dir, "state.db"), filepath.Join(dir, "conflict.log"), dir, "bucket: photos\n") + writeClusterConfig(t, cfg, src.URL, dst.URL, filepath.Join(dir, "db"), filepath.Join(dir, "conflicts"), dir, "\nbucket: photos\nworkers: 2\nmultipart_concurrency: 1\n") + output := filepath.Join(dir, "issues.jsonl") + _, err := execRootStdout(t, "diff", "-c", cfg, "--extra", "--issues-jsonl", output) + if err == nil { + t.Fatal("missing key must fail diff") } - configure(denied.URL) - if _, err := execRoot(t, "scan", "-c", cfg); err != nil { + data, err := os.ReadFile(output) + if err != nil { t.Fatal(err) } - if _, err := execRoot(t, "migrate", "-c", cfg); err == nil { - t.Fatal("inaccessible target reported success") - } - configure(dst.URL) - denyList.Store(true) - if _, err := execRoot(t, "scan", "-c", cfg); err == nil { - t.Fatal("injected listing failure reported success") + decoder := json.NewDecoder(bytes.NewReader(data)) + entries := map[string]string{} + for decoder.More() { + var entry struct{ Bucket, Key, Kind string } + if err := decoder.Decode(&entry); err != nil { + t.Fatal(err) + } + if entry.Bucket != "photos" { + t.Fatalf("bucket: %+v", entry) + } + entries[entry.Key] = entry.Kind } - if _, err := execRoot(t, "migrate", "-c", cfg); err == nil { - t.Fatal("failed rescan left inventory usable") + if len(entries) != 2 || entries["missing\nkey"] != "missing" || entries["extra"] != "extra" { + t.Fatalf("entries=%v", entries) } - denyList.Store(false) - if _, err := execRoot(t, "run", "-c", cfg); err != nil { - t.Fatal(err) + _, err = execRootStdout(t, "diff", "-c", cfg, "--issues-jsonl", output) + if err == nil || !strings.Contains(err.Error(), "create diff JSONL") { + t.Fatalf("existing report accepted: %v", err) } - if data, _ := dst.Object("photos", "data"); string(data) != "ok" { - t.Fatalf("corrected migration copied %q", data) + after, err := os.ReadFile(output) + if err != nil || !bytes.Equal(data, after) { + t.Fatalf("report overwritten: %v", err) } } diff --git a/cmd/concurrency_test.go b/cmd/concurrency_test.go index a823a95..d921c9e 100644 --- a/cmd/concurrency_test.go +++ b/cmd/concurrency_test.go @@ -57,6 +57,15 @@ func withStatusConfig(t *testing.T, args []string) (*config.Config, error) { return got, err } +func TestExplicitEmptyBucketSelectsAll(t *testing.T) { + t.Setenv("BUCKET", "photos") + path := writeTestConfig(t) + got, err := withStatusConfig(t, []string{"status", "-c", path, "--bucket", ""}) + if err != nil || got == nil || !got.AllBuckets() { + t.Fatalf("empty bucket flag must override BUCKET: config=%+v err=%v", got, err) + } +} + func TestCLIOverridesConcurrency(t *testing.T) { path := writeTestConfig(t) got, err := withStatusConfig(t, []string{"status", "-c", path, "--workers", "9", "--multipart-concurrency", "5"}) diff --git a/cmd/helptext.go b/cmd/helptext.go index 7529313..00b79db 100644 --- a/cmd/helptext.go +++ b/cmd/helptext.go @@ -5,25 +5,24 @@ const Version = "0.2.0" const rootShort = `Safe one-way S3 migration / 安全的单向 S3 迁移` const rootLong = `migration copies objects from a source S3-compatible cluster to a target. -Never overwrites on targets that support If-None-Match for PUT and multipart completion. -Never deletes objects. Resume after Ctrl-C via local SQLite. +Never overwrites. Never deletes. Resume after Ctrl-C via local SQLite. migration 把对象从来源 S3 兼容集群复制到目标集群。 -目标须支持普通上传和完成分片上传时的条件写入,以保证永不覆盖。 -迁移不会删除对象。进度保存在本地 SQLite 中,按 Ctrl-C 停止后可继续。 +永不覆盖、永不删除;用本地 SQLite 记录进度,Ctrl-C 后续跑即可。 Quick start / 快速开始: 1. cp config.example.yaml config.yaml 2. Fill in old/new endpoints and keys (填写来源/目标地址和密钥) - 3. migration run -c config.yaml # scan + copy / 扫描并复制 + 3. Freeze source writes/deletes, then confirm --source-frozen / 冻结源写入和删除后确认 + migration run -c config.yaml --source-frozen 4. migration diff -c config.yaml # verify no gaps / 核对有无遗漏 Leave bucket empty in YAML to migrate every bucket on the source. YAML 里 bucket 留空,就会迁移来源上的每一个桶。 Concurrency / 并发: - workers objects copied or HEADed at once (default 16) - 同时复制(diff 时则是同时 HEAD)的对象数,默认 16 + workers objects copied or verified at once (default 16) + 同时复制(diff 时读取两端正文校验)的对象数,默认 16 multipart_concurrency parts of one large object in parallel (default 4) 单个大对象同时上传的分片数,默认 4 Scan is single-threaded. Peak HTTP is about workers × multipart_concurrency. @@ -58,6 +57,9 @@ does not yet exist on the target. Resumable. Never overwrites. 一步完成迁移:先扫描来源清单,再把目标上还不存在的对象复制过去。 可断点续传,永不覆盖。 +Freeze source writes and deletes before run/migrate; explicitly set --source-frozen. +执行 run/migrate 前须在外部冻结来源写入和删除,并明确设置 --source-frozen。 + --workers controls how many objects are copied at once. --multipart-concurrency controls parts inside one large object. --rate-limit caps the total bytes/sec those workers read from the source. @@ -70,10 +72,10 @@ Scan itself stays single-threaded and is not rate limited. 20M = 20×1000×1000 B/s;20MiB = 20×1024×1024 B/s;0 = 不限速。 Examples: - migration run -c config.yaml - migration run -c config.yaml --bucket photos --workers 32 - migration run -c config.yaml --multipart-concurrency 8 - migration run -c config.yaml --workers 16 --rate-limit 20M` + migration run -c config.yaml --source-frozen + migration run -c config.yaml --source-frozen --bucket photos --workers 32 + migration run -c config.yaml --source-frozen --multipart-concurrency 8 + migration run -c config.yaml --source-frozen --workers 16 --rate-limit 20M` const scanShort = `Inventory source objects into SQLite / 扫描源对象到本地 SQLite` const scanLong = `Walk ListObjectsV2 on the source and upsert {key,size,mtime,etag} locally. @@ -81,7 +83,7 @@ Re-running scan picks up new keys and retries skipped/failed rows. Does not write to the target. 对来源做 ListObjectsV2,把 {key,size,mtime,etag} 写入本地 SQLite。 -再次扫描会收录新对象,并将之前跳过或失败的对象重新标记为 pending。 +再次扫描会收录新对象,并让 previously skipped/failed 的行重新进入 pending。 不会对目标写入。 Scan is single-threaded. --workers does not speed up listing. @@ -91,12 +93,14 @@ Example: migration scan -c config.yaml` const migrateShort = `Copy pending objects (never overwrites) / 复制待迁移对象(永不覆盖)` -const migrateLong = `Copy pending/failed rows from a completed scan. Existing keys are marked done -only if the size and a nonempty ETag both match. All other existing keys are -logged as conflicts. A failed copy or an interrupted run exits nonzero. +const migrateLong = `Copy every SQLite row in pending/failed. If the key already exists on +the target and its full SHA-256 and preserved metadata match the source, it is marked done. +An existing complete scan and --source-frozen are required. A different object is logged to +conflict.log and left untouched. -复制已扫描清单中待处理或失败的对象。目标上已有同名对象时,只有大小和非空 ETag -均相同才记为 done,否则记入冲突日志。复制失败或运行中断时,命令以非零状态退出。 +复制已有完整扫描清单中 pending/failed 的对象,执行前确认 --source-frozen。 +目标已有同名 key 且两端正文 SHA-256 和保留的元数据一致则记为 done。不一致则写入 +conflict.log,不覆盖。 --workers is the object pool. --multipart-concurrency is per large object. --rate-limit is the shared source-read cap across that pool (0 = unlimited). @@ -105,7 +109,7 @@ logged as conflicts. A failed copy or an interrupted run exits nonzero. 20M = 20×1000×1000 B/s;20MiB = 20×1024×1024 B/s。 Example: - migration migrate -c config.yaml --workers 8 --rate-limit 30M` + migration migrate -c config.yaml --source-frozen --workers 8 --rate-limit 30M` const statusShort = `Show local progress counters / 显示本地进度` const statusLong = `Print per-bucket counters from the local state DB(s). No S3 calls. @@ -115,15 +119,17 @@ Example: migration status -c config.yaml` const diffShort = `Compare source vs target / 对比源与目标` -const diffLong = `List the source and HEAD each key on the target. Reports missing objects -and size/ETag mismatches. size_only counts keys compared by size alone. -Exit code 1 for missing keys, mismatches or errors. +const diffLong = `List the source, HEAD the target, and read both object bodies to compare SHA-256. +Reports missing objects and size/content/preserved-metadata mismatches; gaps or read errors exit 1. +Keep both clusters quiescent during final verification. This reads all data, +requires GetObject on both endpoints, and is not subject to --rate-limit. -列出源对象并对目标做 HEAD:报告缺失、大小/ETag 不一致。 -size_only 表示仅通过大小检查的对象数。缺失、不匹配或出错时退出码为 1。 +列出源对象、对目标做 HEAD,并读取两端完整正文进行 SHA-256 校验。 +缺失、大小/内容/保留元数据不一致或读取错误时退出码为 1。最终验收期间两端须保持静止。 +需要两端 GetObject 权限,会读取全部数据,当前不受 --rate-limit 限制。 ---workers controls parallel HEAD requests. It does not upload anything. ---workers 控制并行 HEAD 的数量,diff 不会上传对象。 +--workers controls parallel object verification. It does not upload anything. +--workers 控制同时校验的对象数,diff 不会上传对象。 Examples: migration diff -c config.yaml @@ -153,4 +159,5 @@ Env overrides / 环境变量覆盖: OLD_ENDPOINT OLD_AK OLD_SK OLD_REGION NEW_ENDPOINT NEW_AK NEW_SK NEW_REGION BUCKET DB_PATH CONFLICT_LOG SPOOL_DIR REGION - WORKERS MULTIPART_CONCURRENCY RATE_LIMIT` + WORKERS MULTIPART_CONCURRENCY RATE_LIMIT SOURCE_FROZEN + OLD_SESSION_TOKEN NEW_SESSION_TOKEN` diff --git a/cmd/root.go b/cmd/root.go index a44fac4..d3ad514 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "io" "log" "os" "os/signal" @@ -21,6 +22,7 @@ import ( "github.com/rustfs/migration/internal/differ" "github.com/rustfs/migration/internal/migrator" "github.com/rustfs/migration/internal/s3client" + "github.com/rustfs/migration/internal/safeoutput" "github.com/rustfs/migration/internal/scanner" "github.com/rustfs/migration/internal/store" ) @@ -43,6 +45,7 @@ func NewRoot() *cobra.Command { root.PersistentFlags().Int("workers", 0, "concurrent objects for run/migrate/diff, overrides YAML (must be >= 1) / 对象并发数,覆盖配置,须 >= 1") root.PersistentFlags().Int("multipart-concurrency", 0, "parallel parts per large object, overrides YAML (must be >= 1) / 单个大对象的分片并发,覆盖配置,须 >= 1") root.PersistentFlags().String("rate-limit", "", "aggregate source-read cap for run/migrate, e.g. 20M or 20MiB; 0 = unlimited / 所有 worker 从源读取的合计上限,例如 20M 或 20MiB;0 表示不限速") + root.PersistentFlags().Bool("source-frozen", false, "confirm source writes and deletes are externally frozen for run/migrate / 确认来源的写入和删除已在外部冻结") root.CompletionOptions.DisableDefaultCmd = true root.AddCommand(listCmd()) @@ -57,27 +60,33 @@ func NewRoot() *cobra.Command { func signalCtx(parent context.Context) (context.Context, context.CancelFunc) { ctx, cancel := context.WithCancel(parent) ch := make(chan os.Signal, 1) + stop := make(chan struct{}) + var once sync.Once signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) - done := make(chan struct{}) go func() { + var s os.Signal select { - case <-done: + case s = <-ch: + case <-stop: return - case sig := <-ch: - log.Printf("received %s, stopping (send another signal to force exit) / 收到信号,正在停止", sig) - cancel() } + log.Printf("received signal %s, shutting down gracefully... / 收到信号,正在优雅退出(再按一次强制退出)", s) + cancel() select { - case <-done: - case <-ch: - os.Exit(130) + case s = <-ch: + case <-stop: + return } + log.Printf("received second signal %s, forcing exit / 第二次信号,强制退出", s) + os.Exit(130) }() - return ctx, sync.OnceFunc(func() { - signal.Stop(ch) - close(done) - cancel() - }) + return ctx, func() { + once.Do(func() { + signal.Stop(ch) + close(stop) + cancel() + }) + } } func loadConfig(cmd *cobra.Command) (*config.Config, error) { @@ -108,6 +117,9 @@ func loadConfig(cmd *cobra.Command) (*config.Config, error) { if err := cfg.ApplyRateLimitOverride(rateLimitFlag, cmd.Flags().Changed("rate-limit")); err != nil { return nil, err } + if cmd.Flags().Changed("source-frozen") { + cfg.SourceFrozen, _ = flags.GetBool("source-frozen") + } return cfg, nil } @@ -153,7 +165,8 @@ func listCmd() *cobra.Command { } func runCmd() *cobra.Command { - return &cobra.Command{ + var strict bool + c := &cobra.Command{ Use: "run", Short: runShort, Long: runLong, @@ -162,10 +175,12 @@ func runCmd() *cobra.Command { if err := scanOne(ctx, cfg, oldCli, bucket); err != nil { return err } - return migrateOne(ctx, cfg, oldCli, newCli, bucket) + return migrateOne(ctx, cfg, oldCli, newCli, bucket, strict) }) }, } + c.Flags().BoolVar(&strict, "strict", false, "fail if any objects remain pending, failed, conflicted or skipped / 未完成、冲突或跳过时返回失败") + return c } func scanCmd() *cobra.Command { @@ -205,43 +220,69 @@ func scanCmd() *cobra.Command { } func migrateCmd() *cobra.Command { - return &cobra.Command{ + var strict bool + c := &cobra.Command{ Use: "migrate", Short: migrateShort, Long: migrateLong, RunE: func(cmd *cobra.Command, args []string) error { return forEachBucket(cmd, true, func(ctx context.Context, cfg *config.Config, oldCli, newCli *s3.Client, bucket string) error { - return migrateOne(ctx, cfg, oldCli, newCli, bucket) + return migrateOne(ctx, cfg, oldCli, newCli, bucket, strict) }) }, } + c.Flags().BoolVar(&strict, "strict", false, "fail if any objects remain pending, failed, conflicted or skipped / 未完成、冲突或跳过时返回失败") + return c } func diffCmd() *cobra.Command { + var strict bool + var jsonlPath string var diffExtra bool c := &cobra.Command{ Use: "diff", Short: diffShort, Long: diffLong, RunE: func(cmd *cobra.Command, args []string) error { - return forEachBucket(cmd, true, func(ctx context.Context, cfg *config.Config, oldCli, newCli *s3.Client, bucket 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 := forEachBucket(cmd, true, func(ctx context.Context, cfg *config.Config, oldCli, newCli *s3.Client, bucket string) error { + var issueWriter io.Writer + if jsonl != nil { + issueWriter = jsonl + } res, err := differ.Run(ctx, oldCli, newCli, bucket, differ.Options{ Workers: cfg.Workers, - ReportExtra: diffExtra, + ReportExtra: diffExtra || strict, Writer: os.Stdout, + IssuesJSONL: issueWriter, }) if err != nil { return err } - if res.HasGaps() { - return fmt.Errorf("diff found gaps / 对比发现缺失或不一致: missing=%d size=%d etag=%d", - res.Missing, res.SizeMismatch, res.ETagMismatch) + if res.HasGaps() || (strict && res.Extra > 0) { + return fmt.Errorf("diff found gaps / 对比发现缺失或不一致: missing=%d size=%d content=%d metadata=%d extra=%d", + res.Missing, res.SizeMismatch, res.ContentMismatch, res.MetadataMismatch, res.Extra) } return nil }) + if jsonl != nil { + if err := jsonl.Close(); err != nil { + return errors.Join(runErr, fmt.Errorf("close diff JSONL: %w", err)) + } + } + return runErr }, } + c.Flags().StringVar(&jsonlPath, "issues-jsonl", "", "write all differences to a new JSONL file / 将全部差异写入新的 JSONL 文件") c.Flags().BoolVar(&diffExtra, "extra", false, "also report keys that exist only on the target / 同时报告仅目标上存在的 key") + c.Flags().BoolVar(&strict, "strict", false, "also fail on target-only keys / 目标多余 key 也返回失败") return c } @@ -260,19 +301,35 @@ func statusCmd() *cobra.Command { return err } if len(targets) == 0 { - fmt.Println("no state DBs found — run `migration run` or `migration scan` first") - fmt.Println("没有找到状态库 — 请先执行 migration run 或 migration scan") - return nil + return fmt.Errorf("no state DBs found; run scan first / 没有找到状态库,请先执行 scan") } fmt.Printf("%-30s %9s %9s %9s %9s %9s %9s\n", "BUCKET", "TOTAL", "PENDING", "DONE", "CONFLICT", "SKIPPED", "FAILED") - var errs []error - for _, path := range targets { - if err := printStatus(path, cfg.Bucket); err != nil { - errs = append(errs, fmt.Errorf("%s: %w", path, err)) + var failures []error + for _, t := range targets { + st, err := store.OpenExisting(t.path) + if err != nil { + fmt.Printf("%s: %s\n", t.bucket, safeoutput.Escape(err.Error())) + failures = append(failures, fmt.Errorf("status %s: %w", t.bucket, err)) + continue + } + bound, err := st.BoundBucket() + if err != nil || bound != t.bucket { + _ = st.Close() + failures = append(failures, fmt.Errorf("state %s bound to %q, expected %q: %v", t.path, bound, t.bucket, err)) + continue } + c, err := st.Counts() + _ = st.Close() + if err != nil { + fmt.Printf("%s: %s\n", t.bucket, safeoutput.Escape(err.Error())) + failures = append(failures, fmt.Errorf("status %s: %w", t.bucket, err)) + continue + } + fmt.Printf("%-30s %9d %9d %9d %9d %9d %9d\n", + truncate(t.bucket, 30), c.Total, c.Pending, c.Done, c.Conflict, c.Skipped, c.Failed) } - return errors.Join(errs...) + return errors.Join(failures...) }, } } @@ -289,6 +346,11 @@ func forEachBucket(cmd *cobra.Command, needTarget bool, fn func(ctx context.Cont } else if err := cfg.ValidateSource(); err != nil { return err } + if cmd.Name() == "run" || cmd.Name() == "migrate" { + if err := cfg.ValidateMigration(); err != nil { + return err + } + } ctx, cancel := signalCtx(cmd.Context()) defer cancel() pool := cfg.MaxInFlight() @@ -314,7 +376,7 @@ func forEachBucket(cmd *cobra.Command, needTarget bool, fn func(ctx context.Cont return err } if err := fn(ctx, cfg, oldCli, newCli, name); err != nil { - log.Printf("bucket %s: %v", name, err) + log.Printf("bucket %s: %s", name, safeoutput.Escape(err.Error())) failed = append(failed, name) continue } @@ -335,10 +397,9 @@ func resolveBuckets(ctx context.Context, cfg *config.Config, oldCli *s3.Client) } names := make([]string, 0, len(list)) for _, b := range list { - if err := config.ValidateBucketName(b.Name); err != nil { - return nil, fmt.Errorf("list source buckets: %w", err) + if b.Name != "" { + names = append(names, b.Name) } - names = append(names, b.Name) } if len(names) == 0 { return nil, fmt.Errorf("source instance has no buckets / 源集群没有桶") @@ -347,15 +408,12 @@ func resolveBuckets(ctx context.Context, cfg *config.Config, oldCli *s3.Client) } func scanOne(ctx context.Context, cfg *config.Config, oldCli *s3.Client, bucket string) error { - if err := cluster.HeadBucket(ctx, oldCli, bucket); err != nil { - return err - } st, err := store.Open(cfg.DBPathFor(bucket), bucket) if err != nil { return err } defer st.Close() - if err := st.BindEndpoints(cfg.Old.Endpoint, ""); err != nil { + if err := st.BindMigration(cfg.Old.Endpoint, cfg.New.Endpoint); err != nil { return err } log.Printf("scan: bucket=%s db=%s (single-threaded list; --workers applies to copy and diff)", bucket, cfg.DBPathFor(bucket)) @@ -363,27 +421,29 @@ func scanOne(ctx context.Context, cfg *config.Config, oldCli *s3.Client, bucket return err } -func migrateOne(ctx context.Context, cfg *config.Config, oldCli, newCli *s3.Client, bucket string) error { - st, err := store.OpenInventory(cfg.DBPathFor(bucket), bucket) - if err != nil { +func migrateOne(ctx context.Context, cfg *config.Config, oldCli, newCli *s3.Client, bucket string, strict ...bool) error { + if err := cfg.ValidateMigration(); err != nil { return err } - defer st.Close() if err := cluster.HeadBucket(ctx, oldCli, bucket); err != nil { return err } - targetErr := cluster.HeadBucket(ctx, newCli, bucket) - if targetErr != nil && !s3client.IsNotFound(targetErr) { - return targetErr + if _, err := os.Stat(cfg.DBPathFor(bucket)); err != nil { + return fmt.Errorf("migration requires an existing completed scan; run scan or run first: %w", err) } - // Bind after the endpoints respond, but before creating anything on the target. - if err := st.BindEndpoints(cfg.Old.Endpoint, cfg.New.Endpoint); err != nil { + st, err := store.Open(cfg.DBPathFor(bucket), bucket) + if err != nil { return err } - if targetErr != nil { - if err := cluster.CreateBucket(ctx, newCli, bucket); err != nil { - return err - } + defer st.Close() + if err := st.BindMigration(cfg.Old.Endpoint, cfg.New.Endpoint); err != nil { + return err + } + if err := st.RequireCompleteScan(); err != nil { + return err + } + if err := cluster.EnsureBucket(ctx, newCli, bucket); err != nil { + return err } m, err := migrator.NewForBucket(cfg, bucket, oldCli, newCli, st) if err != nil { @@ -392,59 +452,61 @@ func migrateOne(ctx context.Context, cfg *config.Config, oldCli, newCli *s3.Clie defer m.Close() log.Printf("migrate: bucket=%s workers=%d rate_limit=%s threshold=%dMiB partSize=%dMiB partConcurrency=%d", bucket, cfg.Workers, cfg.RateLimit, cfg.MultipartThreshold>>20, cfg.MultipartPartSize>>20, cfg.MultipartConcurrency) - return m.Run(ctx) -} - -func printStatus(path, requested string) error { - st, err := store.OpenExisting(path) - if err != nil { - return err - } - defer st.Close() - bucket, err := st.BoundBucket() - if err != nil { + if err := m.Run(ctx); err != nil { return err } - if requested != "" && requested != bucket { - return fmt.Errorf("db_path is bound to bucket %q but config requests %q", bucket, requested) - } - c, err := st.Counts() - if err != nil { - return err + if len(strict) > 0 && strict[0] { + counts, err := st.Counts() + if err != nil { + return fmt.Errorf("read migration status: %w", err) + } + if counts.Pending != 0 || counts.Failed != 0 || counts.Conflict != 0 || counts.Skipped != 0 || counts.Done != counts.Total { + return fmt.Errorf("strict migration incomplete: pending=%d failed=%d conflict=%d skipped=%d done=%d total=%d", counts.Pending, counts.Failed, counts.Conflict, counts.Skipped, counts.Done, counts.Total) + } } - fmt.Printf("%-30s %9d %9d %9d %9d %9d %9d\n", - truncate(bucket, 30), c.Total, c.Pending, c.Done, c.Conflict, c.Skipped, c.Failed) return nil } -func statusTargets(cfg *config.Config) ([]string, error) { - base := filepath.Clean(cfg.DBPath) - var paths []string - if _, err := os.Stat(base); err == nil { - paths = append(paths, base) - } else if !os.IsNotExist(err) { - return nil, err - } +type dbTarget struct { + bucket string + path string +} + +func statusTargets(cfg *config.Config) ([]dbTarget, error) { if !cfg.AllBuckets() { - return paths, nil - } - dir := filepath.Dir(base) - entries, err := os.ReadDir(dir) - if os.IsNotExist(err) { - return paths, nil + return []dbTarget{{bucket: cfg.Bucket, path: cfg.DBPath}}, nil } + matches, err := filepath.Glob(cfg.DBPathFor("*")) if err != nil { return nil, err } - for _, entry := range entries { - name := entry.Name() - if !entry.IsDir() && strings.HasPrefix(name, "migration-") && strings.HasSuffix(name, ".db") { - if path := filepath.Join(dir, name); path != base { - paths = append(paths, path) - } + if _, err := os.Stat(cfg.DBPath); err == nil { + matches = append(matches, cfg.DBPath) + } else if !os.IsNotExist(err) { + return nil, err + } + var out []dbTarget + seen := make(map[string]bool) + for _, path := range matches { + if seen[path] { + continue + } + seen[path] = true + st, err := store.OpenExisting(path) + if err != nil { + return nil, 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 + } + if name == "" { + return nil, fmt.Errorf("state %s has no bound bucket", path) } + out = append(out, dbTarget{bucket: name, path: path}) } - return paths, nil + return out, nil } func truncate(s string, max int) string { diff --git a/cmd/safe_error_test.go b/cmd/safe_error_test.go new file mode 100644 index 0000000..f13d9b5 --- /dev/null +++ b/cmd/safe_error_test.go @@ -0,0 +1,20 @@ +package cmd + +import ( + "bytes" + "testing" +) + +func TestCobraLeavesErrorOutputToSafeBoundary(t *testing.T) { + root := NewRoot() + var output bytes.Buffer + root.SetErr(&output) + root.SetOut(&output) + root.SetArgs([]string{"--definitely-invalid\nforged"}) + if err := root.Execute(); err == nil { + t.Fatal("expected flag error") + } + if output.Len() != 0 { + t.Fatalf("Cobra printed unescaped error: %q", output.String()) + } +} diff --git a/cmd/smoke_test.go b/cmd/smoke_test.go index 29c171c..358393e 100644 --- a/cmd/smoke_test.go +++ b/cmd/smoke_test.go @@ -77,16 +77,13 @@ rate_limit: 0 t.Fatalf("list exit %d\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) } - // Reading status before the first scan must not create an inventory. + // Read-only status must not manufacture a successful empty inventory. stdout, stderr, code = runBin(t, bin, "status", "-c", cfgPath) - if code != 0 { - t.Fatalf("status before scan exit %d\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) - } - if !strings.Contains(stdout, "no state DBs") { - t.Fatalf("status before scan: %s", stdout) + if code == 0 { + t.Fatalf("status before scan unexpectedly succeeded\nstdout:\n%s\nstderr:\n%s", stdout, stderr) } if _, err := os.Stat(filepath.Join(dir, "migration.db")); !os.IsNotExist(err) { - t.Fatalf("status created a database, stat err=%v", err) + t.Fatalf("status created an inventory before scan: %v", err) } if _, stderr, code = runBin(t, bin, "scan", "-c", cfgPath); code != 0 { diff --git a/cmd/strict_test.go b/cmd/strict_test.go new file mode 100644 index 0000000..4764ce3 --- /dev/null +++ b/cmd/strict_test.go @@ -0,0 +1,43 @@ +package cmd + +import ( + "path/filepath" + "strings" + "testing" + "time" + + "github.com/rustfs/migration/internal/fakes3" +) + +func TestStrictMigrationRejectsExistingConflictOnResume(t *testing.T) { + source := fakes3.NewWithObjects(t, "photos", map[string][]byte{"key": []byte("source")}, time.Now()) + defer source.Close() + target := fakes3.NewWithObjects(t, "photos", map[string][]byte{"key": []byte("target")}, time.Now()) + defer target.Close() + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, path, source.URL, target.URL, filepath.Join(dir, "state.db"), filepath.Join(dir, "conflict.log"), dir, "bucket: photos\nworkers: 1\n") + for _, command := range []string{"run", "migrate"} { + _, err := execRoot(t, command, "-c", path, "--strict") + if err == nil || !strings.Contains(err.Error(), "failed buckets") { + t.Fatalf("%s --strict should fail for conflict, got %v", command, err) + } + } + got, _ := target.Object("photos", "key") + if string(got) != "target" { + t.Fatalf("strict mode overwrote target: %q", got) + } +} + +func TestStrictDiffRejectsTargetOnlyObjects(t *testing.T) { + source := fakes3.NewWithObjects(t, "photos", map[string][]byte{"same": []byte("body")}, time.Now()) + defer source.Close() + target := fakes3.NewWithObjects(t, "photos", map[string][]byte{"same": []byte("body"), "extra": []byte("extra")}, time.Now()) + defer target.Close() + dir := t.TempDir() + path := filepath.Join(dir, "config.yaml") + writeClusterConfig(t, path, source.URL, target.URL, filepath.Join(dir, "state.db"), filepath.Join(dir, "conflict.log"), dir, "bucket: photos\nworkers: 1\n") + if _, err := execRoot(t, "diff", "-c", path, "--strict"); err == nil { + t.Fatal("strict diff accepted a target-only object") + } +} diff --git a/config.example.yaml b/config.example.yaml index 97ab327..d409517 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -5,10 +5,10 @@ # 目标端必须支持普通上传和完成分片上传时的条件写入,才能保留并发写入的同名对象。 # # Env / 环境变量: -# OLD_ENDPOINT OLD_AK OLD_SK OLD_REGION -# NEW_ENDPOINT NEW_AK NEW_SK NEW_REGION REGION +# OLD_ENDPOINT OLD_AK OLD_SK OLD_REGION OLD_SESSION_TOKEN +# NEW_ENDPOINT NEW_AK NEW_SK NEW_REGION NEW_SESSION_TOKEN REGION # BUCKET DB_PATH CONFLICT_LOG SPOOL_DIR -# WORKERS MULTIPART_CONCURRENCY RATE_LIMIT +# WORKERS MULTIPART_CONCURRENCY RATE_LIMIT SOURCE_FROZEN old: endpoint: "http://10.0.0.1:9000" # source / 来源(只读) @@ -28,12 +28,14 @@ bucket: "" db_path: "./migration.db" conflict_log: "./conflict.log" -# Temp dir for small-object spooling. Default = directory of db_path. -# 小对象落盘目录。默认是 db_path 所在目录。若 /tmp 是内存盘请改到真实磁盘。 +# Temp dir for object and multipart-part spooling. Default = directory of db_path. +# 对象和分片落盘目录。默认是 db_path 所在目录。若 /tmp 是内存盘请改到真实磁盘。 # workers 越大,同时存在的临时文件越多,请留出磁盘空间。 +# Maximum aggregate bytes reserved for temporary copy files (default: 1 GiB). +spool_max_bytes: 1073741824 spool_dir: "" -# 对象并发:run / migrate 同时复制多少个对象,diff 同时 HEAD 多少个对象。 +# 对象并发:run / migrate 同时复制多少个对象,diff 同时读取并校验多少个对象。 # scan 始终单线程(List 分页必须串行),不受此项影响。 # 省略或写 0 = 默认 16。负数会报错。须 >= 1。 # 命令行覆盖:--workers 32 。环境变量:WORKERS(覆盖本文件,但命令行优先)。 @@ -71,6 +73,11 @@ multipart_concurrency: 4 # 20Mi / 20MiB = 20 × 1024 × 1024 = 20971520 字节/秒 # 裸数字表示字节/秒,例如 1048576。大小写不敏感,可以加 /s。 # K/KB=1000,Ki/KiB=1024;G/GB=1000³,Gi/GiB=1024³。 -# 只限制 run / migrate 复制对象正文。scan / diff / list 不读正文,不受影响。 +# 只限制 run / migrate 复制对象正文。scan / list 不读正文;diff 完整读取两端正文,但不受此速率参数限制。 # 生产时段示例:rate_limit: 20M 。确认不影响业务后再调到 30M 或 50M。 rate_limit: 0 + +# 在应用/存储层冻结源写入及删除后才设 true;本参数不自动冻结 S3。 +# 迁移和最终验收期间必须保持冻结;涉及清单对象的业务删除(包括目标端)也必须暂停或有墓碑协调。 +# 也可使用 --source-frozen。 +source_frozen: false diff --git a/docs/AUDIT-2026-10-29.md b/docs/AUDIT-2026-10-29.md new file mode 100644 index 0000000..3c54dad --- /dev/null +++ b/docs/AUDIT-2026-10-29.md @@ -0,0 +1,201 @@ +# S3 迁移可靠性审计报告 + +此文保留基线提交的历史审计结果。随后代码修复及最新测试结果见 [修复验证记录](FIXES-2026-10-29.md),不要把本页的失败数量当作修复后状态。 + +审计日期:2026-10-29(Asia/Shanghai)。仓库:rustfs/migration,基线提交 `6224d05ddf7aa1663c662c91543a3572603d3efc`。 + +**结论:当前版本不能作为在线迁移完成、可下线源集群的可靠性保证。** 已复现并发覆盖目标新数据、分片混合源版本、删除后复活、断点误复用漏迁,以及失败却返回成功等问题。基础传输路径有一定测试覆盖,但 README 的“永不覆盖”和 DESIGN 的线上双删假设没有实现所需的原子性与协调机制。 + +本次交付是代码审计、可复现测试和修复建议;没有修改生产实现,也没有将发现的问题修复后标为通过。所有新增请求只访问本机测试服务,未访问生产桶。未提交、推送或创建 PR。 + +## 审计范围与验证结果 + +检查了全部生产 Go 模块、CLI、现有测试、配置示例、README 和设计/使用文档,涵盖扫描分页、SQLite 状态、并发、重试、取消、分片、完整性核验、权限错误、元数据和资源边界。 + +| 验证 | 实际结果 | +| --- | --- | +| 原有测试,`go test -count=1 -json -coverpkg=./... ... ./...` | 64 个顶层测试:63 通过、1 失败;包括子例的叶子用例为 138 通过、1 失败 | +| 原有测试,`go test -race -coverprofile=... ./...` | 同一并发测试失败;未出现 DATA RACE 报告 | +| 原失败项单独 `-race -count=10` | 10/10 失败;原因是测试时序假设,见下文 | +| 新增审计测试,`go test -race -tags audit -run '^TestAudit' ... ./...` | 24 个顶层测试:20 失败、4 通过;叶子用例 29 失败、5 通过;无 DATA RACE 报告 | +| 跨包语句覆盖率 | 80.1%;扣除 `internal/fakes3` 测试服务实现后为 76.2%。该结果来自有 1 项失败的测试运行,不能称全套验收通过 | +| `go vet ./...` 和包含 `audit real_s3` 标签的 vet | 通过 | +| `go mod verify` | 通过 | +| `CGO_ENABLED=0 go build` | 通过,本机 Go 1.24.1 / darwin arm64 | +| 两个隔离 RustFS 实例实测 | 4 个小对象 SHA-256 一致;2 个分片对象失败;详见兼容性结果 | +| govulncheck | 有告警,需区分依赖版本、编译工具链和实际可达性,见依赖部分 | + +审计测试断言的是生产可靠性所需的安全行为,部分严格于当前文档承诺,因此失败数不是独立漏洞数量。测试放在 `//go:build audit` 下,保留可执行的未修复证据,避免混淆原有回归结果。`real_s3` 标签为独立服务兼容测试。 + +原有并发测试 `cmd/cli_regression_test.go:150` 用 40ms sleep 推断两个 UploadPart 必须重叠。两个分片分别为 5MiB 和 32 字节,下载和签名耗时不同,启用 race 时大分片可能晚于窗口到达。新增 `TestAuditMultipartConcurrencyWithBarrier` 使用同步屏障等待两个请求,在 race 下通过并验证最终字节一致。**不能把原测试失败解读成生产分片并发失效。** + +## 必须优先处理的风险 + +以下均为 P1,即生产迁移放行前应解决的问题;排序优先考虑业务数据破坏和错误验收。 + +### A01 并发写入可覆盖目标业务数据 + +位置:`internal/migrator/migrator.go:198`、`:307`、`:480`。 + +目标 HEAD 返回 404 后,业务可能写入同名 key;随后的 PutObject 或 CompleteMultipartUpload 是无条件写,覆盖刚写入的业务数据。两条路径均已复现,覆盖后状态仍为 done。增加一次 HEAD 无法消除这个时间窗口。 + +证据:`TestAuditConcurrentTargetWriteMustNotBeOverwritten`,单 PUT 和分片完成两个子例失败。 + +修复:在真正提交目标对象时使用服务端原子 `If-None-Match: *`,正确处理 412 和 409,验证 RustFS/MinIO/S3 对这两个 API 的支持;目标不支持时,应拒绝提供“在线永不覆盖”保证。当前 SDK `service/s3 v1.58.2` 的两个输入结构没有该字段,需要升级 SDK 或实现经过验证的签名中间件。[AWS 条件写说明](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html) + +### A02 大对象可能由不同源版本拼接而成 + +位置:`internal/migrator/migrator.go:437`、`:497`。 + +分片 Range GET 没有固定 VersionId 或 If-Match。测试在第一片读完后把源对象由全 A 更新为全 B,得到 10MiB 的 A/B 拼接对象;目标总长度正确,状态为 done,但内容不是任何一个完整源版本。 + +证据:`TestAuditMultipartSourceMutationMustNotCommitMixedVersions`。 + +修复:固定每个对象的源版本,或对 HEAD/GET/所有 Range 使用同一 ETag 条件;遇 412 失效整次传输,不能继续拼接。单 PUT 也应检测扫描到读取之间的源身份变化,并更新/失效清单记录。分片完成后还须做内容摘要验证。 + +### A03 应用双端删除后对象会复活 + +位置:`internal/migrator/migrator.go:275`、`:307`;关联 `docs/DESIGN.md` 的线上双读双删假设。 + +迁移先读完旧对象,应用随后删除源和目标,迁移仍把已读数据写回目标。测试确认源对象已消失、目标被重新创建并标为 done。 + +证据:`TestAuditConcurrentDeleteMustNotResurrect`。 + +修复:引入删除墓碑、可靠删除事件回放或应用写入协调,或在迁移窗口冻结删除。**仅增加条件写不能解决本项**:删除后目标不存在,`If-None-Match: *` 仍会成功。 + +### A04 大小相同被误当成内容已验证 + +位置:`internal/migrator/migrator.go:555`、`:497`;`internal/differ/differ.go:111`。 + +已有目标只要大小相同,而 ETag 为 multipart 或为空,就会被判断为已迁移;diff 同样计入 OK。新传输的分片对象也只验总长度。故“已有同尺寸但错误的对象”“源混版”“传输中同尺寸损坏”均可能逃过验收。 + +证据:`TestAuditUnverifiableTargetMustNotBeConsideredMigrated` 的 4 个子例,以及 `TestAuditDiffDoesNotCertifySameSizeCorruption`。后者构造合法 5MiB+8 字节对象及真实两分片 ETag,目标改坏一字节后仍得到 `OK=1`、无 gaps。 + +这是文档已描述的 size-only 降级策略,但不足以满足可靠迁移验收。修复应引入完整对象摘要或读回校验,无法验证的对象单列 unverified,不能标 verified/done。跨服务使用 checksum 时必须区分算法、完整对象与复合分片摘要。无连字符的 ETag 也不必然是可跨端比较的 MD5,SSE-KMS/SSE-C 是典型例外。[AWS ETag 语义](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Object.html) + +### A05 更换目标复用断点库会静默漏迁 + +位置:`internal/store/store.go:58`、`:146`、`:163`;`internal/config/config.go:359`。 + +DB 只绑定 bucket 名,没有源/目标身份。向目标 A 完成后,把配置改成目标 B 并复用 DB,重新 scan/run 仍忽略 done 行,返回成功、processed=0,而 B 缺少数据。 + +证据:`TestAuditResumeRejectsDifferentDestination`。 + +全桶模式还忽略 `db_path` 的文件名,使用同目录的 `migration-.db`;仅将 `/state/job-A.db` 换成 `/state/job-B.db` 不能隔离任务。 + +修复:持久化迁移任务身份、源/目标规范化地址与账户/集群身份、bucket、清单 generation;恢复前验证一致,不一致则拒绝。暂时必须每个迁移任务使用独立状态目录。 + +### A06 复制失败仍返回成功 + +位置:`internal/migrator/migrator.go:259`、`:164`;`cmd/root.go:374`。 + +markFailed 写 DB 成功后返回 nil,Run 未汇总失败对象。真实 Cobra run 测试中,源 GET403、failed=1、done=0、目标缺对象,命令仍返回 nil,进程会退出 0。隔离 RustFS 分片失败也出现相同行为。 + +证据:`TestAuditRunReportsObjectFailure`。 + +修复:可以继续处理其他对象,但最终返回包含 failed/pending/unverified 的结构化未完成结果和非零退出码。conflict/skipped 应有明确验收策略,不能仅凭命令 exit 0 下线源集群。 + +### A07 目标端 404 被误判为源对象不存在 + +位置:`internal/migrator/migrator.go:229`。 + +copy 的全部错误经同一 IsNotFound 分支处理,目标 PutObject、CreateMultipartUpload、CompleteMultipartUpload 或验收 HEAD 的 404 都被写成 `skipped / source 404`。普通 migrate 只处理 pending/failed,因此不会重试;重新扫描可能恢复,但错误的 skipped 会误导操作员。 + +证据:`TestAuditTarget404MustRemainRetryable` 的 4 个阶段子例。 + +修复:错误必须携带源/目标及操作类型;只有确认来自源 GET/HEAD 的对象缺失才能 skipped。桶缺失与对象缺失也应分别处理。 + +### A08 diff 遇权限错误可能永久阻塞 + +位置:`internal/differ/differ.go:119`、`:160`。 + +worker 遇 HEAD403 等致命错误后直接退出;同页生产者仅等待 jobs 或外部 ctx。工作队列满且 worker 已退出时,生产者不会再检查 fatal。测试用 10 个对象、workers=1 即可复现,必须外部取消才释放。默认并发在足够多错误对象时同样可能触发。 + +证据:`TestAuditDiffReturnsOnHeadFailure`。 + +修复:派生可取消 context;首个致命错误同步取消生产者和 worker,等待全部退出后返回根因。 + +### A09 网络错误文本中的 key 可被误认作 404 + +位置:`internal/s3client/errors.go:90` 到函数末尾。 + +未得到结构化 APIError 时,用错误字符串包含 NotFound/NoSuchKey/NoSuchBucket 判断不存在。网络断连的 URL 若含这些 key 片段,就被错误分类。目标 HEAD 由此绕过“确认不存在”的检查,或源 GET 被永久 skipped。 + +证据:`TestAuditTransportFailureIsNotObjectNotFound` 的 3 个 url.Error 子例。 + +修复:仅依据结构化 S3 错误和实际 HTTP 状态;网络/协议错误不得通过任意字符串猜测对象是否存在。 + +## 其他已验证不足 + +| 等级 | 不足与影响 | 位置与测试 | +| --- | --- | --- | +| P2 | 首次直接 migrate 自动创建空 DB,源有对象却零处理成功;缺少完整扫描标记 | `cmd/root.go:362`;`TestAuditMigrateRequiresScannedInventory` | +| P2 | 复制取消后返回 nil,单桶 Ctrl-C 可退出 0。文档有说明,但不适合作为自动化成功信号 | `migrator.go:168`;`TestAuditMigrateReturnsCancellation` | +| P2 | status 遇损坏 DB 只打印错误、继续并退出 0 | `cmd/root.go:257`、`:264`;`TestAuditStatusReportsCorruptState` | +| P2 | 空源桶、目标桶不存在时 diff 仍无 gaps,不能验收桶存在性 | `differ.go:66`;`TestAuditDiffDetectsMissingEmptyBucket` | +| P2 | YAML `buckte: production-photos` 被静默忽略,bucket 变空,扩大为全桶迁移 | `config.go:70`;`TestAuditRejectMisspelledBucketSetting`;建议 KnownFields 严格解析 | +| P2 | 扫描未请求 URL 编码,合法 S3 key 中的 XML 不可表示字符令整页失败;diff 也用相同 List 模式 | `scanner.go:31`;`TestAuditScanXMLUnsafeObjectKey`;增加 encoding-type=url 并正确解码。[AWS ListObjectsV2](https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html) | +| P2 | BucketAlreadyExists 被视为创建成功,不能证明桶归属与访问权限 | `cluster.go:53`、`s3client/errors.go:103`;`TestAuditEnsureBucketRejectsForeignOwner` | +| P2 | 非 us-east-1 的新桶创建缺少 LocationConstraint,配置区域不自动进入创建 XML | `cluster.go:53`;`TestAuditEnsureBucketUsesConfiguredRegion`。[AWS CreateBucket](https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) | +| P3 | workers 极端正整数先乘 2 溢出为负数,随后 channel 创建 panic | `config.go:342`;`TestAuditJobBufferCannotOverflow`;先比较上限再乘并限制并发 | +| 范围限制 | done/conflict 是永久终态,源同 key 更新后重扫不刷新,目标删除后也不会自动补回;不能用作持续同步 | `store.go:124` 到 `:146`;`TestAuditChangedSourceInvalidatesDone`;该终态行为已文档化 | + +## 静态审查发现的资源和恢复风险 + +这些项目有代码依据,但未全部进行压力、断电或硬杀复现,不能与上面的确定性缺陷测试混称。 + +- `migrator.go:446` 对 Range 响应直接 io.ReadAll,没有限读,也不验证 Content-Range/预期分片长度。服务端或代理忽略 Range 时可能将整个大对象读入内存;最终大小核验发生在提交之后。应检查范围、限制读取到 partLength+1,拒绝异常响应。 +- 默认原始分片缓冲约为 `16 workers × 4 parts × 16MiB = 1GiB`,不含 ReadAll 扩容、SDK 与 HTTP 开销。自动放大分片大小后资源继续增长;没有全局字节预算、磁盘空间预检、part size 上限。并发数量有限不等于内存占用足够安全。 +- `s3client/client.go:42` 未设置 HTTP 总超时,默认 Transport 无响应头超时,命令 context 主要依赖信号取消。对连接已建立但永久不返回的数据/头部,需要可配置请求超时和读停滞检测;不可只设一个会误杀正常大对象的短总时限。 +- 分片 uploadId/已完成 parts 未持久化;重启会重新创建上传。进程被 kill -9 时无法执行 abort,残留分片须依赖服务端明确配置的清理生命周期。当前“断点恢复”是对象级重试,不是分片级续传。 +- SQLite WAL 使用 synchronous=NORMAL;正常关闭重开已测,断电后的最后事务持久性未验证。conflict.log 与 DB 不在同一事务中,日志无 fsync,key 未转义 TSV 换行/制表符。建议用 DB 作为权威事件记录,导出 JSONL 并保留校验信息。 +- 未设置跨进程任务锁;文档明确不支持多进程共享 DB。状态没有 claim/lease,应主动拒绝第二实例以防误操作。 +- HTTP 明文 endpoint 被允许;示例采用 HTTP。跨不可信网络部署必须配置 HTTPS。静态凭证 provider 的 session token 固定为空,不能据此宣称完整支持 STS 临时凭证。该项是部署/能力限制。 + +## S3 语义与兼容边界 + +当前迁移保存对象内容、常见内容头和用户 metadata;未迁移版本历史、删除标记、Object Lock、桶策略、生命周期等。README 已明确排除其中多项,不能把这些都算作未声明缺陷。 + +对象 tags、ACL、存储等级、SSE 配置、retention/legal hold 不在当前复制参数中;依赖它们的访问控制、合规保留或存储策略不能仅通过内容拷贝保持。已有目标“大小和 ETag 匹配”时也不会核对 metadata。上线前需对实际使用的 S3 功能做清单,明确迁移、拒绝或另行配置,不应承诺完整复制全部 S3 语义。 + +**隔离服务实测的具体范围:** 本机安装的是 RustFS `1.0.0-alpha.61`(commit `7622b37f7be3e7e83a2a3fbfc5547e18930cce55`,2025-10-07 构建),不是最新服务端。脚本启动两个临时目录和回环端口的独立实例,执行扫描、迁移、重跑、目标读回 SHA-256 与 diff,完成后停止进程并清除临时数据。 + +- `empty`、`hello.txt`、`中文/空 格+%?#.txt`、`folder/` 四个对象内容 SHA-256 一致,迁移保留了源响应中可见的 Content-Type、audit metadata 和 Cache-Control 值。 +- 源服务的基线 GET 已把 Cache-Control 暴露为用户 metadata 而非标准响应字段;这不是本次证实的迁移工具新增丢失。 +- 5MiB 边界对象和 11,200,000 字节对象都在 CompleteMultipartUpload 返回 InvalidPart:服务端期望无引号 ETag,而收到带引号 ETag。两次运行均失败,最终 `Done=4, Failed=2`,但 Migrator.Run 仍 nil;diff 正确报 Missing=2。 +- 这是指定旧版服务端与当前客户端的兼容性失败,不能直接归因于最新 RustFS,也不应据此全局去掉 ETag 引号作为通用 S3 修复。应在拟部署的服务端版本上复测并修复对应兼容层。 + +现有 fake S3 不充分校验分片最小尺寸、Complete manifest、条件写及 abort 清理;Range 分支在发出 206 后才设置部分响应头,key 解析还会裁剪尾斜杠/重复解码。因此 mock 测试通过不能替代真实协议兼容矩阵。 + +## 依赖与工具链 + +`go.mod` 的 S3 SDK 为 v1.58.2、eventstream 为 v1.6.3。govulncheck 源码扫描报告 GO-2026-5764;官方修复版本包含 eventstream v1.7.8、S3 v1.97.3。该问题是 EventStream 解码拒绝服务,当前代码未直接调用 SelectObjectContent,工具调用图告警不等于本次已证明迁移流程可被该漏洞攻击。仍建议成组升级兼容的 AWS SDK 依赖并重跑协议测试。[AWS 安全公告](https://github.com/aws/aws-sdk-go-v2/security/advisories/GHSA-xmrv-pmrh-hhx2) + +扫描工具 v1.9.0 自动使用 Go 1.26.10,源码扫描因此检测的是该工具链标准库,不能替代本机 Go 1.24.1 构建产物检查。对实际生成二进制另做了 `-mode binary` 扫描,工具报告 45 项符号级告警及其他包/模块告警,包括旧 Go 标准库。二进制扫描是保守匹配,包含与客户端迁移路径无关的服务端功能,**不是已确认 45 个可利用漏洞**。应使用受支持且已修补的 Go 工具链构建,升级依赖后再做可达性分析。Windows x/sys 模块告警也不能直接算成本次 darwin 平台可利用问题。 + +## 修复顺序与生产验收条件 + +1. 先解决 A01–A04 的数据安全:目标条件写、固定源版本、删除协调、完整内容验证;同步收紧文档承诺。 +2. 解决 A05–A09 的状态与控制流:任务绑定、完整扫描 generation、明确错误来源、非零失败/取消退出码、diff 全链路取消。 +3. 补严格配置、桶存在/区域/归属校验、合法 key 编码、资源预算、超时、上传残留清理与任务锁。 +4. 固定拟部署服务端和 SDK/Go 版本,在 RustFS、MinIO、AWS S3 实际使用组合上运行相同验收矩阵。 + +放行条件应包括:所有适用审计用例转绿;稳定同步屏障替换原有时序测试;清单完整;pending/failed/unverified 为零;conflict/skipped 逐项有处置结论;所有迁移对象具备可比内容摘要或独立读回验证;业务并发写/删场景符合约定;重启与硬杀后可恢复,残留分片可清理;验收结束到切换期间有冻结窗口或增量事件收敛机制。**仅对象数量、总字节数、ETag 形状或当前 diff=0 均不足以证明可以下线源集群。** + +还需执行的生产级验证:多 GB/最大预期对象、百万级以上清单性能、磁盘满/损坏、kill -9/主机断电、网络半开/丢包、服务限流和重试耗尽、KMS/STS、版本桶、Object Lock、真实权限策略。此次未执行这些场景,不作相应保证。 + +## 复现与交付文件 + +在仓库根目录执行: + +```sh +go test -count=1 ./... +go test -race -count=1 ./... +go test -race -tags audit -run '^TestAudit' -count=1 -timeout 90s ./... +go vet -tags 'audit real_s3' ./... +python3 scripts/audit-local-rustfs.py +``` + +当前审计测试预期非零退出,因为缺陷尚未修复;正常回归原有的并发时序测试也可能失败。真实服务脚本需本机安装 rustfs,只使用脚本启动的隔离实例。新增文件位于 `cmd/audit_test.go`、`internal/{cluster,config,differ,scanner,store}/audit_test.go`、`internal/migrator/audit_transfer_test.go`、`internal/s3client/audit_errors_test.go`、`internal/migrator/audit_real_s3_test.go` 与 `scripts/audit-local-rustfs.py`。 + +原始证据保存在 `audit-results/`:`summary.json`、`baseline-tests.jsonl`、`baseline-race.log`、`concurrency-repeat.log`、`audit-final.jsonl`、`full-coverage.out`、`coverage-summary.txt`、`real-rustfs-final.log`、`govulncheck.log`、`govulncheck-binary.log`、`vet.log`、`vet-with-audit.log`、`mod-verify.log`。具体安全断言和故障注入代码可用于后续修复回归。 diff --git a/docs/DESIGN.md b/docs/DESIGN.md index a67f074..dd1c722 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,89 +1,58 @@ -# How migration copies objects between S3 clusters +# Migration design -`migration` backfills current objects from one S3-compatible cluster to another while applications can continue writing to the destination. The source can be a single RustFS or MinIO instance and the destination can sit behind a load balancer. Transfers go through the migration host because the two clusters have separate object stores. The tool issues no `CopyObject` or `DeleteObject` requests. +## Safety model -The unit of work is one current object in one bucket. The tool preserves its common content headers and user metadata. Historical versions, delete markers, bucket policies, lifecycle rules and Object Lock configuration require separate handling. [Operator guide](../README.md) +The source is externally frozen for writes and deletes through scan, migration and verification. SourceFrozen is an explicit operator assertion and does not enforce an S3 lock. Business deletes of inventory keys on the target must also be paused or coordinated through tombstones. Cross-cluster concurrent deletes cannot be made atomic by a client; they are unsupported without application-level coordination. -## From inventory to copy +The destination must correctly implement atomic If-None-Match: * for PutObject and CompleteMultipartUpload. No DeleteObject or CopyObject operations are used. Existing target bytes are preserved on conflict. Compatibility tests against the deployed server version are a prerequisite. -```text - scan (ListObjectsV2) -source bucket ───────────────────────────────────▶ local SQLite inventory - │ │ - │ GET or ranged GET pending / failed rows - ▼ ▼ -migration workers ── conditional PUT or multipart ──▶ destination bucket - │ │ - └────────────── update SQLite and conflict log ◀─────┘ -``` - -| Package | Responsibility | -| --- | --- | -| `cmd` | CLI, bucket selection, signals and exit status | -| `internal/config` | YAML, environment and CLI settings, validation and per-bucket paths | -| `internal/s3client` | AWS SDK for Go v2 clients, path-style requests and S3 error classification | -| `internal/cluster` | Bucket discovery and creation, validated and decoded object listings | -| `internal/scanner`, `internal/store` | Build the inventory and persist progress in SQLite | -| `internal/migrator` | Compare keys, transfer bodies, verify writes and log conflicts | -| `internal/ratelimit` | Limit the combined rate of source reads | -| `internal/differ` | Audit the live source and destination using lists and HEAD requests | -| `internal/fakes3` | In-process S3 HTTP server used by regression tests | - -`run` scans and then copies one bucket at a time. `scan` and `migrate` expose the two phases independently. A scan checks that the source bucket exists, requests URL-encoded keys with `ListObjectsV2` and validates the returned bucket, keys, sizes and continuation tokens. Pages are read sequentially. The scanner writes batches of up to 500 rows in transactions and marks the scan complete after the last batch is committed. During the copy phase the destination bucket is created if missing. Existing bucket configuration is preserved. - -## Local state - -SQLite uses the pure Go `modernc.org/sqlite` driver in WAL mode. Rows store the key, size, last-modified time, ETag, status, attempt count, last error and update time. State writes share one database connection while S3 requests proceed in parallel. Use one migration process per state file. +## Inventory and persistence -Each database records the bucket and cluster endpoints. A scan binds the source endpoint and copying binds the destination. Older databases without these fields adopt the configured addresses on first use. An operator must check which clusters such a database belongs to before using it again. A missing inventory or a scan marked incomplete prevents `migrate` from starting. Databases from versions without a scan-completion marker can still be resumed. If the old scan may have stopped early, rescan first. +SQLite holds bucket, normalized source/target endpoint identity, scan generation, completion generation and per-key size/ETag/last-modified/status. The state format distinguishes new databases from legacy unbound checkpoints. Unsafe legacy adoption or endpoint reuse is rejected. -| State | Meaning | Next scan, if the key is listed | -| --- | --- | --- | -| `pending` | Waiting for a copy worker | Refresh the inventory entry | -| `failed` | A transfer, verification or remote request failed | Refresh and return to `pending` | -| `skipped` | The source object disappeared before it could be copied | Refresh and return to `pending` | -| `done` | The new write was verified, or the existing size and ETag matched | Keep the terminal state | -| `conflict` | The destination already contains an object that cannot be confirmed as a match | Keep the terminal state | +Scanning invalidates completeness before network work, lists using encoding-type=url, decodes keys exactly once, validates pagination and persists batches transactionally. Completion is recorded only after the final successful flush. A partial scan cannot authorize copying. Changed source identity resets terminal rows for revalidation; targets are never overwritten because of a rescan. -New source keys enter the inventory as `pending`. Rescanning means listing the source again because S3 cannot bound a listing by modification time. Reconciliation of a previously terminal key, such as an object removed from the destination later, requires a new inventory in a separate state directory. +A separate SQLite pager lock excludes writers across processes and is released by the OS on process death. Status opens the inventory read-only. The inventory uses WAL and synchronous=FULL with one writer connection. Keep state, sidecar and lock files together during operation. -## Decisions for each key +## Transfer -1. Issue `HeadObject` on the destination. If the key exists, require an equal size and identical nonempty ETags, including when both ETags are multipart. On a match, mark the row `done`. Otherwise append the conflict to the log and mark the row `conflict`. -2. If the destination reports the key missing, fetch the source. Use its inventoried ETag in `If-Match` when available. A confirmed source-object 404 yields `skipped`. A timeout, cancellation, changed source or failed destination request can be retried. -3. Create a missing key using `If-None-Match: *` on `PutObject` or `CompleteMultipartUpload`. The destination must implement this condition. A HEAD request alone cannot protect against a concurrent writer. If the conditional write loses a race, check the winning object again and classify it under the same match rule. There is no unconditional fallback. -4. Verify the committed size with `HeadObject`, conditioned on the returned write ETag when present. On the single-part path, compare the source and resulting ETags when both are present and comparable. Mark the row `done` after successful verification. +1. HEAD target; only a structured missing response permits the create path. +2. HEAD source and compare its identity against the inventory. HEAD404 is not enough to declare a source key deleted; a GET must confirm NoSuchKey. +3. If target exists, read both equal-size objects with If-Match, compare full SHA-256 and preserved metadata, then mark done or conflict. ETags are concurrency tokens, not cross-cluster content hashes. +4. Otherwise read source using the pinned ETag/available VersionId. Small objects spool to disk while hashing. Multipart ranges validate Content-Range, Content-Length and ETag, spool to disk and upload through bounded concurrency. +5. Before commit, recheck source identity. Multipart also reads the source sequentially for a complete digest. These checks detect completed mutations but do not replace the external freeze requirement. +6. Commit with If-None-Match: *. A competing target writer produces a conflict; other write errors remain retryable failures. +7. HEAD and read back target with If-Match; compare full SHA-256 before done. -A source and a destination may have identical bytes but different multipart ETags when the part boundaries differ. After a crash between upload completion and the local status update, this can leave a conflict requiring manual review. Comparing the destination's size alone does not authorize marking an existing key `done`. +Source and destination errors retain provenance. Only a confirmed source NoSuchKey becomes skipped; destination404, bucket disappearance, network failures, canceled reads and digest failures are failed. Local persistence failures cancel the worker pool. Ordinary object failures do not stop unrelated objects, but the final command returns a failure summary. Cancellation returns an error. -The conflict log uses three tab-separated fields per record. The first is the object key, followed by the source and destination modification times in RFC3339 UTC. Keys containing control characters or beginning with a quotation mark are written as Go-quoted strings. A mutex serializes appends within the process. If an append succeeds but the database update fails, a retry can produce a second record for that key. +Object-level retries resume pending/failed rows. Multipart upload IDs are not checkpointed; normal failures abort the session with an independent bounded context. Crash leftovers require server lifecycle cleanup. A committed object whose local done update was interrupted is verified on retry. -## Transfer paths and resource use +## Verification -**Single-part uploads.** The worker fetches the source object and streams it to a temporary file in `spool_dir`. It checks the byte count against the inventoried size before rewinding the file for a signed, seekable PUT request. Both paths copy `Content-Type`, `Cache-Control`, `Content-Disposition`, `Content-Encoding`, `Content-Language`, `Expires` and `x-amz-meta-*` user metadata. +Diff checks both buckets, inventories source keys and validates every equal-size object by complete SHA-256 reads of both endpoints, plus preserved metadata. Missing identity or unreadable data returns an error. Target-only keys are optional informational output. -**Multipart uploads.** At or above `multipart_threshold` the worker uses multipart upload. Objects larger than 5 GiB always take this path. A source HEAD establishes the ETag and size. Each ranged GET uses the same ETag in `If-Match`. Before uploading a part, the worker checks the returned ETag, content range and body length. Part numbers determine the order passed to `CompleteMultipartUpload`. On error or cancellation the worker attempts to abort the unfinished upload with a fresh timeout. A process killed before cleanup can leave an incomplete upload on the server. +Workers and producer share cancellation; a fatal HEAD/GET error stops all producers, avoiding blocked sends after workers exit. Each diff run owns a uniquely created temporary database, so concurrent calls cannot delete each other's inventory. Report write errors propagate. -**Concurrency.** Up to `workers` objects are active, with at most `multipart_concurrency` parts per object. Pending rows are fetched in key order and queued in batches, with a channel of at most 2,048 descriptors. Small transfers need temporary disk space. Multipart workers buffer a part in memory, so the byte footprint grows with part size and the number of active parts. The configured part size ranges from 5 MiB to 5 GiB. It increases automatically to fit within 10,000 parts, or the transfer fails if that would exceed 5 GiB per part. +## Resources and transport -**Bandwidth.** All source-body reads share the byte limiter, including each ranged read. List, HEAD and upload traffic are outside the limit. The worker and part limits control simultaneous requests separately. The per-host idle connection pool scales with their product, capped at 1,024, to allow connection reuse. +Object workers, part concurrency and job queues are bounded. Multipart bodies spool to disk instead of io.ReadAll; range reads are limited to expected bytes plus one. Temporary disk remains a capacity requirement. A shared limiter covers all source body reads in migration, including the extra digest pass. Destination reads/writes and diff are not throttled by this setting. -## Failures and signals +HTTP/1 connection pools follow worker fan-out. Response headers have a 30-second timeout; each blocked body Read and connection Write has a 90-second deadline. The body watchdog is inactive between reads, so low configured bandwidth does not cause false idle timeouts. Optional SDK checksum extensions are disabled unless required; application SHA-256 validation remains mandatory. -Per-object errors are recorded in `last_error`. Workers can continue processing other keys, and the command returns an error when an object failed. A persistence error cancels the worker pool and is returned to the caller. Conflicts and confirmed source deletions have their own states and counts. The first interrupt cancels work and returns a nonzero exit status. A second signal forces an immediate exit with code 130. Restart `migrate` to retry unfinished rows after a completed scan. +## Scope and testing -## Independent audit +The tool migrates current object content, common HTTP content headers and user metadata. Version history, delete markers, tags, ACLs, storage classes, source SSE configuration, Object Lock and bucket configuration require separate migration planning. -`diff` lists the live source and sends parallel HEAD requests to the destination. It reports missing keys, size mismatches and mismatched comparable ETags. Multipart ETags from different layouts and absent ETags can leave only size to compare. These keys contribute to both `ok` and `size_only`. If the source has no objects, an explicit HEAD checks that the destination bucket exists. A missing destination bucket fails the audit. The audit does not read bodies or change migration state. With `--extra`, a temporary SQLite index of source keys supports a second listing of the destination. Keys found only there do not affect the exit status. +Regression tests cover conditional-write races, source mutation/mixed parts, completed deletion before commit, same-size corruption, error provenance, partial scans, cross-endpoint checkpoint reuse, process-lock crash recovery, diff cancellation, encoding and explicit freeze prerequisites. Fake S3 models conditional requests and range headers but is not a full S3 certification suite. The optional `real_s3` harness tests an explicitly selected executable, rather than whichever RustFS version happens to be installed on PATH: -## Verification +```sh +python3 scripts/audit-local-rustfs.py \ + --rustfs-binary /absolute/path/rustfs --expect-version 1.0.4 +``` -`go test -race ./...` exercises Go packages and integration tests against the in-process S3 server, including induced errors and concurrent mutations. The end-to-end test runs the built CLI against independent MinIO and RustFS servers and checks the destination via the S3 API. To run it locally, start Docker, install Go and run the following from the repository root. [Test workflow](../.github/workflows/tests.yml) · [E2E scenarios](../tests/e2e.py) +The executable path must be absolute. The launcher checks that file's `--version` output against the exact expected version before starting either node; a mismatch aborts setup. It records the resolved path, version output and executable SHA-256, then starts both isolated loopback nodes from that same file. The default evidence directory is `audit-results/rustfs-1.0.4/`, including `rustfs-binary.json` and node logs; `--output-dir` can override it. Processes and temporary server data are cleaned up at the end. -```bash -python3 -m venv .venv -.venv/bin/python -m pip install boto3==1.42.97 -.venv/bin/python tests/e2e.py -``` +The suite exercises full-body verification and recovery after a real UploadPart has been accepted but its response is interrupted. The recovery test checks cancellation, remote abort cleanup, a retryable checkpoint, reopening SQLite without rescanning, and final SHA-256 plus diff results through the unchanged endpoint. Describing these scenarios does not claim a successful `1.0.4` run; that requires actual execution against the recorded binary. Previous `1.0.0-alpha.61` results describe only that historical release. -The packaging workflow builds Linux amd64, Linux arm64 and Windows amd64 archives on matching runners, verifies their SHA-256 digests and starts each packaged executable with `--version`. [Package workflow](../.github/workflows/packages.yml) +See [fix validation](FIXES-2026-10-29.md) for actual test results and remaining service compatibility constraints. The earlier audit remains a historical record of its pinned commit. diff --git a/docs/FIXES-2026-10-29.md b/docs/FIXES-2026-10-29.md new file mode 100644 index 0000000..faf74d8 --- /dev/null +++ b/docs/FIXES-2026-10-29.md @@ -0,0 +1,117 @@ +# S3 迁移审计修复与验证 + +2026-10-29,针对基线 `6224d05ddf7aa1663c662c91543a3572603d3efc` 的审计问题完成代码修复。本记录描述本地工作区中的变更;尚未提交或推送。 + +## 修复结果 + +| 审计问题 | 修复行为 | +| --- | --- | +| 并发目标写入被覆盖 | PutObject、CompleteMultipartUpload 使用原子 If-None-Match;竞争写入保留目标并进入冲突处理 | +| 成功响应丢失后重试误报冲突 | 目标条件提交收到412后,复核源身份、元数据和完整SHA-256;正确已提交对象恢复为done,业务替换仍保留冲突,409仍为可重试失败 | +| 分片拼接不同源版本 | 清单与源 HEAD 核对,GET 使用 If-Match/可用 VersionId,提交前复核源身份 | +| 同大小错误内容误报完成 | 新复制目标、已有目标与 diff 均执行完整 SHA-256 校验;无法验证返回错误 | +| 内容一致但元数据不同 | 比较常见内容头、Expires、用户 metadata;迁移报告冲突,diff 报 metadata mismatch | +| 删除后对象复活 | 显式要求外部冻结源数据集变更及相关业务删除;提交前检测已完成源删除。没有把客户端检查宣称为跨集群原子删除机制 | +| 换端点复用状态库漏迁 | 持久化源/目标端点和桶身份;scanner 也绑定实际客户端源端点;不匹配直接拒绝 | +| 未扫描或中断扫描误当完整 | 持久化扫描 generation,仅完整成功的扫描允许 migrate | +| 源同 key 更新后保留旧 done | 源身份变化后重新进入 pending,再验证目标,仍不赋予覆盖权限 | +| 多进程误用状态库 | SQLite 独立任务锁排除第二 writer,允许只读 status;子进程被 kill 后锁可释放 | +| 复制失败/取消仍成功 | 聚合对象失败并返回错误;取消和本地持久化故障返回非零,后者取消工作池 | +| 目标404或网络错误被写成源缺失 | 保留源/目标错误来源,仅真实源 NoSuchKey 可 skipped;不再从 URL/错误文本猜测404 | +| diff 权限错误后卡住 | 首个致命错误取消生产者和 worker,退出并返回根因 | +| 空目标桶缺失未发现 | diff 检查两端桶;权限/不存在均失败 | +| 非美东区域建桶错误/他人桶误接受 | 传 LocationConstraint;只容忍已归属自身且再次 HEAD 成功的创建竞态 | +| 特殊 key 和损坏分页 | 请求 URL 编码、解码一次;验证 key/size/IsTruncated/token;不认证缺结束标志的扫描 | +| 配置拼写和整数溢出 | YAML 严格字段与单文档解析;先限长再乘;并发/分片资源上限;端点和桶名防误用检查 | +| 全桶状态文件名冲突 | 派生路径保留配置 basename,status 使用相同规则发现文件 | +| 无界分片缓冲 | 精确范围和长度校验、限读;分片落磁盘,避免完整分片驻留内存 | +| 网络永久停滞 | 响应头30秒;每次阻塞正文读取/连接写入90秒;使用 HTTP/1 保证上传连接超时可控 | +| 冲突日志与状态持久化顺序 | key 转义,日志 Sync 后才提交 conflict;新日志权限0600 | +| 旧依赖与构建工具链告警 | S3 SDK v1.97.3、eventstream v1.7.8、x/sys v0.44.0;Go 1.26.10 工具链 | +| 原有并发测试时序不稳定 | 同步屏障替代固定40ms sleep,验证两个分片实际并行及最终内容 | + +审计用例已进入默认回归测试,不再需要 `-tags audit`。额外测试包括真实子进程崩溃释放锁、源响应身份变化、相同 ETag 不同内容、同长度目标损坏、异常 Range、元数据冲突、网络读写停滞、低速读取间隔、损坏报告输出和清单分页缺失标志。 + +## 已完成的本地回归记录 + +环境:darwin/arm64,Go 1.26.10。运行在本机临时 HTTP 服务和临时 SQLite 目录上;未访问生产桶。 + +以下为最终修复代码的默认回归结果;RustFS `1.0.4` 的真实服务结果单独记录在下一节。 + +| 检查 | 结果 | +| --- | --- | +| `go test -race -count=1 -json -coverpkg=./... -coverprofile=... ./...` | 129 个顶层测试、235 个叶子用例全部通过;零失败、零跳过、无 DATA RACE | +| 跨包语句覆盖率 | 82.3%;排除 fake S3 测试服务代码后,生产代码80.9% | +| `go vet -tags real_s3 ./...` | 通过 | +| `go mod verify` | 通过 | +| `CGO_ENABLED=0 go build` | 通过 | +| govulncheck v1.9.0 源码扫描 | No vulnerabilities found | +| govulncheck v1.9.0 对实际修复后二进制扫描 | No vulnerabilities found | +| `git diff --check` | 通过 | +| Python启动器单元测试 | 7项通过,覆盖精确版本、绝对路径、拒绝PATH回退、制品摘要和节点环境隔离 | + +本地原始证据:`audit-results/fix-final-tests.jsonl`、`fix-summary.json`、`fix-final-coverage.out`、`fix-final-vet.log`、`fix-final-mod-verify.log`、`fix-govulncheck.log`、`fix-final-binary-vuln.log`。该目录被 gitignore 排除,避免把本机日志和二进制加入代码提交。 + +## RustFS 1.0.4 真实服务验证结果 + +```sh +python3 scripts/audit-local-rustfs.py \ + --rustfs-binary /absolute/path/rustfs --expect-version 1.0.4 +``` + +将占位路径替换为待测二进制的绝对路径。启动器对指定文件执行 `--version` 并精确匹配 `1.0.4`;不匹配会在启动实例前失败,不会从 PATH 换用其他已安装版本。随后记录文件路径、完整版本输出和 SHA-256,并用同一文件启动两个隔离回环实例。默认在 `audit-results/rustfs-1.0.4/` 保存 `rustfs-binary.json` 和节点日志;可通过 `--output-dir` 指定独立目录。结束后清理临时实例和数据。 + +最终真实服务验证已于 **2026-10-29 11:10:59(Asia/Shanghai)完成并通过**,包括最后补充的成功响应丢失修复和故障注入测试。实际使用官方 `rustfs-macos-aarch64-v1.0.4.zip` 解压得到的 macOS ARM64 release 二进制,在本机启动两个隔离实例;没有连接生产桶。启动前精确核对 `rustfs 1.0.4`,官方压缩包 SHA-256 与 GitHub release digest、SHA256SUMS 均匹配。 + +| 受测制品 | 记录 | +| --- | --- | +| 官方 release | [RustFS 1.0.4](https://github.com/rustfs/rustfs/releases/tag/1.0.4) | +| 包名 | `rustfs-macos-aarch64-v1.0.4.zip` | +| 压缩包 SHA-256 | `49057482769d7904ef95dc40457d71122f48cbb8e9e0725a0817a3ec6daf8270` | +| 实际执行文件 SHA-256 | `099ee45edb1ea94bd5ccdc0eb33bafe9717e4d2b6858dfded9a21e77e7697660` | +| 二进制报告的 Git commit | `46337942d55f3a8e6a97b147ca98d9ea8115555d` | +| 执行命令 | `go test -race -tags real_s3 -run '^TestRealS3' -count=1 -timeout=5m -v ./internal/migrator` | +| 测试结果 | 6 个顶层测试、8 个叶子用例全部通过;零失败、零跳过、无 DATA RACE;退出码 0,Go package 耗时 17.538 秒 | + +叶子用例数分别计入普通/Range GET 和单次/分片提交响应丢失的子测试,不重复计入父测试。已完成的场景如下: + +| 场景 | 实际结果 | +| --- | --- | +| 扫描、单对象与分片迁移 | 6 个对象全部 done,共 16,442,909 字节;包括空对象、普通文本、中文/空格/特殊字符 key、`folder/`、5 MiB 边界对象和 11,200,000 字节分片对象。failed/conflict/skipped 均为 0 | +| 重扫后再次运行 | `processed=0 copied=0`;未重复上传已完成对象 | +| 完整性与元数据 | 6 个对象的目标读回 SHA-256 与原始内容一致,保留元数据匹配,最终 diff 为 6 个 OK、无 gaps、无额外对象 | +| PutObject 条件禁止覆盖 | 对已存在目标使用 `If-None-Match: *`,服务端返回 HTTP 412;原有目标正文及 SHA-256 保持不变 | +| CompleteMultipartUpload 条件禁止覆盖 | 条件分片提交返回 HTTP 412;原有目标正文及 SHA-256 保持不变 | +| 固定源读取身份 | 普通 GET 与 Range GET 使用过期 If-Match 时均返回 HTTP 412 | +| 真实分片中断与恢复 | RustFS 已接收 UploadPart 后取消客户端;Run 返回取消错误,Abort 成功 1 次,目标对象未提交、无残留 multipart upload,SQLite 保持 `failed=1`。关闭并重开同一 SQLite,不重扫、不改变代理端点,恢复后 `done=1 failed=0`;10,485,997 字节对象通过两端独立 SHA-256、元数据及 diff 验证,`diff_ok=1` | +| 成功提交响应丢失 | 对1 KiB单次上传、两个合法5 MiB分片的完成请求,各丢弃一次服务端真实成功响应并替换为500。两例均触发2次提交请求、只有1次实际提交,首轮均正确恢复为done,无conflict/failed;重开同一SQLite再次运行未重写对象。原有业务对象无写请求,正文与元数据均保留,两个场景最终diff均为2个OK | + +本机证据:[最终真实服务测试日志](../audit-results/rustfs-1.0.4-final/test.log)、[最终受测二进制与运行清单](../audit-results/rustfs-1.0.4-final/rustfs-binary.json)、[官方制品校验记录](../audit-results/runtimes/rustfs-1.0.4/verification.json)。首轮日志另保留在 `audit-results/rustfs-1.0.4/`。证据位于被 gitignore 排除的本地目录,应随验收记录另行保存。 + +取消场景中的ERROR是预期注入故障;响应丢失场景中清理已完成upload的NoSuchUpload警告也符合该场景,最终对象、检查点和独立完整性校验均成功。 + +旧 `1.0.0-alpha.61` 中记录的分片 `InvalidPart` 和 `folder/` 的 VersionId 读取问题,**在本轮 `1.0.4` 的相同迁移场景中未再复现**。这一结果验证了上表场景,不代表已完成生产规模、主机断电或所有 S3 功能的认证。 + +## 历史真实服务记录:RustFS 1.0.0-alpha.61 + +此前对本机已有 RustFS `1.0.0-alpha.61` 启动两个独立临时实例,执行扫描、迁移、重试、SHA-256读回和diff。以下是该旧版本的历史结果,不是 `1.0.4` 的测试结果,也不能据此推断 `1.0.4` 通过或失败。 + +- empty、hello.txt、含中文/空格/特殊字符 key 的3个对象成功,目标读回 SHA-256 一致。 +- 两个分片对象仍因该版本 CompleteMultipartUpload 的带引号 ETag 兼容问题返回 InvalidPart。 +- folder/ 的源端带 VersionId GET 返回 InvalidArgument;这是新版迁移严格固定源身份后暴露的旧服务版本读取兼容限制。 +- 这些失败现在保留为 failed,并使 Migrator.Run 明确返回错误;重跑仍失败,不会被记成 done 或 skipped。最终 diff 报3个缺失。 + +历史原始证据:[alpha.61 运行日志](../audit-results/fix-real-rustfs.log)。**当时不能批准该旧服务版本的完整生产迁移。** 此限制针对上述旧版本与历史运行;`1.0.4` 的实际结果以上一节为准。其他拟部署的 RustFS/MinIO/AWS S3 版本仍需分别验证,尤其是条件写、分片完成、版本读取和元数据。未通过时应升级或修复服务端,不应通过删除条件、关闭校验或只比较大小绕过。 + +## 升级与运行要求 + +1. Go构建环境升级到1.26+,默认工具链1.26.10;阅读更新后的README和配置示例。 +2. 对有处理记录的旧无身份状态库,使用新的状态目录完整重扫。程序重新验证现有目标内容,不要求删除目标数据。 +3. 从扫描开始冻结源写入、删除及生命周期变更,并暂停迁移 key 在目标端的业务删除,或使用外部可靠墓碑协调。随后显式使用 `--source-frozen` 或设置 `source_frozen: true`;该参数不会自动冻结任何服务。 +4. 目标端必须正确实现原子条件写;仅发出HTTP条件头不能补救一个忽略条件的服务端。源码回归通过不等于所有 S3 实现都已验证。 +5. `diff` 现在完整读取双端正文,并检查保留元数据,需要 GetObject 权限和读带宽;当前不受 run/migrate 的 rate-limit 限制。分片迁移通常读源两遍、读目标一遍,临时盘需留足容量。 +6. `run` 的零退出表示没有传输失败,不代表所有源数据已迁入;conflict/skipped 仍需处置,最终必须审阅状态并运行diff。最终验收期间相关数据应保持稳定;独立对象读回不是跨集群原子快照。 + +同URL后端被重建、DNS切换到另一集群、或凭证切换租户不一定能由端点字符串区分,应使用新状态目录。恢复仍为对象级重试;硬杀残留分片依赖服务端清理生命周期。版本历史、删除标记、tags、ACL、Object Lock、桶策略等仍不在工具迁移范围。 + +本次没有执行生产规模压力、主机断电、真实KMS/STS权限矩阵或所有服务版本认证;这些部署验收不能由本机单元测试替代。 diff --git a/docs/RETEST-2026-10-29.md b/docs/RETEST-2026-10-29.md new file mode 100644 index 0000000..e2f2c0a --- /dev/null +++ b/docs/RETEST-2026-10-29.md @@ -0,0 +1,70 @@ +# 全量冒烟与回归复测记录 + +2026-10-29,针对当前修复工作区重新执行测试,未使用上轮测试结果代替本轮执行。全量回归、真实服务测试和最终CLI冒烟均通过;未发现新的产品缺陷。首轮辅助脚本的SQLite读取异常另行记录在下方。 + +## 受测版本与范围 + +- 仓库基线:`6224d05ddf7aa1663c662c91543a3572603d3efc`,加当前尚未提交的修复。 +- 环境:macOS ARM64,Go 1.26.10。 +- 后端:官方RustFS **1.0.4**,提交 `46337942d55f3a8e6a97b147ca98d9ea8115555d`;重新执行版本检查与SHA-256比对。 +- RustFS执行文件SHA-256:`099ee45edb1ea94bd5ccdc0eb33bafe9717e4d2b6858dfded9a21e77e7697660`。 +- 本轮CLI和漏洞扫描使用的迁移二进制摘要相同:`2ac0793a714497abd4de3576b3fc9c44586b67acf8edf6ddbc3b80f0bfbf0dc8`。 +- 测试使用新建的回环服务、临时桶与数据目录;本轮未修改生产源码和现有测试代码,未访问生产桶。测试前记录62个仓库文件摘要,并在结束时核对。 + +## 本轮结果 + +| 检查 | 结果 | +| --- | --- | +| 全量Go回归 | 11个包通过;129个顶层测试、235个叶子用例通过;零失败、零跳过、无DATA RACE | +| 执行顺序与缓存 | `-race -shuffle=1793243573 -count=1 -timeout=10m`,固定随机种子便于复现,不复用测试结果缓存 | +| 语句覆盖率 | 全部82.3%;排除fake S3测试服务代码后生产代码80.9% | +| RustFS 1.0.4真实服务 | `-race -count=1`,6个顶层测试、8个叶子用例通过;零失败、零跳过、无DATA RACE | +| 编译后二进制CLI冒烟 | 5类场景、17条功能命令全部符合预期;13次退出0,4次预期退出1 | +| 启动器Python测试 | 7项通过 | +| 静态与构建 | `go vet -tags real_s3 ./...`、`go mod verify`、`CGO_ENABLED=0 go build`通过 | +| 漏洞扫描 | govulncheck v1.9.0对源码及本轮二进制均返回 `No vulnerabilities found` | +| 格式检查 | 48个Go文件gofmt只读检查通过,`git diff --check`通过 | +| 清理 | 真实服务测试和CLI冒烟各自启动的两个RustFS实例均已停止,临时服务数据已清理 | + +叶子用例不重复计入父测试。故障注入中出现的取消错误、已完成upload的NoSuchUpload清理警告,以及下表中的非零退出均是预期断言,未计为通过的普通业务操作。 + +## 真实CLI冒烟 + +| 场景 | 验收结果 | +| --- | --- | +| 单桶完整链路 | 实际执行scan、status、migrate、diff和重复run;4对象包含空对象、普通文本、中文/转义key和5 MiB+123字节分片对象。独立读回SHA-256及元数据一致,状态由pending变done,重复运行保持完成 | +| 全桶模式 | list、run、status、diff通过;3个桶共5对象,其中包含空桶;目标自动建桶、每桶独立状态文件及读回内容正确 | +| 同长度不同内容冲突 | 源`OLD-DATA`、目标`NEW-DATA`;run退出0并记录conflict=1,目标原始SHA-256保持;diff退出1 | +| 缺失目标桶 | 空源桶的目标桶不存在时diff退出1;只读比较未创建目标桶 | +| 冻结声明缺失 | 未设置source_frozen时,run和migrate各退出1;目标桶保持不存在 | + +冲突场景再次确认:**run退出0不是迁移完整性验收结论**,还需要处理conflict/skipped并完成diff。 + +真实服务自动化还验证了:6类对象完整迁移及重复扫描;PutObject和CompleteMultipartUpload条件请求返回412且业务对象未被覆盖;过期If-Match的普通/Range GET返回412;分片已接收后的取消、Abort清理和SQLite重开恢复;单次/分片提交成功响应丢失后的SDK重试、完整性核验和检查点恢复。 + +## 辅助脚本异常与限制 + +首轮CLI冒烟在辅助Python脚本使用SQLite `mode=ro`查询时出现 `unable to open database file`;真实CLI状态命令与独立对象校验均成功。该错误的底层原因尚未确定。仅将辅助脚本改为在CLI子进程退出后使用immutable只读模式并明确关闭连接,再从全新的隔离实例重跑,最终5类场景全部通过。事后确认最终数据库无WAL,初轮数据库WAL为0字节,但未记录每次辅助读取时的WAL状态;因此验收还单独核对了真实CLI输出的pending=4、done=4、conflict=1及S3内容和diff,不以辅助SQL查询作为唯一依据。首轮失败与处理细节完整保留在[辅助SQLite异常说明](../audit-results/retest-20261029-111253/cli-smoke/auxiliary-sqlite-note.json),生产程序未因此修改。 + +本轮覆盖当前仓库全部默认测试及全部real_s3测试,并执行上述真实CLI场景。它不替代Linux部署环境验证、生产规模长时间压力、主机断电、多节点故障或KMS/STS权限矩阵测试。历史版本、删除标记、tags、ACL和Object Lock等仍不在当前迁移工具范围。生产迁移仍需外部冻结相关变更并以最终diff验收。 + +## 证据与复现 + +本轮证据独立保存在 `audit-results/retest-20261029-111253/`,不覆盖之前日志。该目录由gitignore排除,需要作为验收附件单独保存。 + +- [源码快照](../audit-results/retest-20261029-111253/source-manifest.json)与[快照核对](../audit-results/retest-20261029-111253/source-stability.json) +- [全量回归结果](../audit-results/retest-20261029-111253/regression-summary.json)与[逐项测试事件](../audit-results/retest-20261029-111253/regression.jsonl) +- [真实服务结果](../audit-results/retest-20261029-111253/real-s3-summary.json)与[原始日志](../audit-results/retest-20261029-111253/real-s3.log) +- [CLI逐命令结果](../audit-results/retest-20261029-111253/cli-smoke/results.json)、[本机复现脚本](../audit-results/retest-20261029-111253/cli-smoke/blackbox_smoke.py)及[首轮辅助脚本异常](../audit-results/retest-20261029-111253/cli-smoke/harness-initial.log) +- [构建、静态、漏洞扫描与Python测试](../audit-results/retest-20261029-111253/checks/summary.json) + +```sh +go test -race -shuffle=1793243573 -count=1 -timeout=10m \ + -json -coverpkg=./... -coverprofile=coverage.out ./... + +python3 scripts/audit-local-rustfs.py \ + --rustfs-binary /absolute/path/to/rustfs-1.0.4 \ + --expect-version 1.0.4 --output-dir /path/to/new-results +``` + +修复内容和运行约束见[审计修复报告](FIXES-2026-10-29.md)。 diff --git a/docs/USAGE.md b/docs/USAGE.md index 97bb5a2..6de73d7 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -1,54 +1,53 @@ -# Running a migration +# Migration usage -Use `run` for the first transfer and `diff` for an independent check of the destination. The full operator guide covers installation, permissions, configuration, concurrency and troubleshooting. [English guide](../README.md) · [中文使用手册](使用手册.md) +Use a frozen source: stop source writes and deletes, including lifecycle deletion, until final verification and cutover complete. `--source-frozen` acknowledges this external action; it does not lock S3. Uncoordinated dual-cluster deletes are unsupported. Business deletes of inventory keys on the target must also be paused or coordinated through tombstones; freezing only source DELETE requests is insufficient. -Copy `config.example.yaml` to `config.yaml`. Set `old` to the source and `new` to the destination. The destination must honor `If-None-Match: *` on both `PutObject` and `CompleteMultipartUpload`. This protects an object created by another writer between the initial check and the upload. +The target must support atomic `If-None-Match: *` on PutObject and CompleteMultipartUpload. Verify your actual server version before production use. The tool never calls DeleteObject or CopyObject. -```bash -./bin/migration list -c config.yaml -./bin/migration run -c config.yaml --bucket photos --rate-limit 20M -./bin/migration status -c config.yaml --bucket photos -./bin/migration diff -c config.yaml --bucket photos +```sh +go build -o bin/migration . +cp config.example.yaml config.yaml +# Set endpoints, credentials and an independent state directory. +# Freeze source mutations externally, then: +./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 ``` -Omit `--bucket photos` and leave `bucket` empty in the configuration to process every source bucket. An explicit `--bucket ""` also selects all buckets. Keep the bucket selection and the state directory the same when resuming. For a single bucket the tool uses `db_path`. All-bucket mode uses `migration-.db` files alongside `db_path`. +Build with Go 1.26+; go.mod selects the patched go1.26.10 toolchain. Configuration precedence is CLI, environment, YAML, defaults. Unknown YAML fields fail. Source and target support session_token / OLD_SESSION_TOKEN / NEW_SESSION_TOKEN for temporary credentials. -The source account must be able to list and read the selected bucket. The destination account needs permission to check keys and write objects, including multipart uploads and aborts. On Amazon S3, `s3:ListBucket` lets a HEAD request distinguish a missing key (404) from a permission error (403). The tool treats a permission error as a failure. [S3 HEAD permissions](https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadObject.html) +`scan` inventories objects and records a completed scan generation. `migrate --source-frozen` retries pending/failed objects only after a complete scan. `run` does both. `list` and `status` do not transfer object bodies. -## Pick a command +Every copied object is read back from the destination and checked with SHA-256. An existing same-size object is only done after full source/target digest comparison; different bytes or metadata remain conflicts. ETags are opaque conditional-read tokens, not assumed MD5 checksums. Missing identity or unreadable content fails verification. -| Command | When to use it | -| --- | --- | -| `list` | Check which buckets the source account can list. | -| `scan` | Save a full inventory in SQLite before you start copying. The source is read sequentially, one listing page at a time. | -| `migrate` | Copy the `pending` and `failed` rows from an existing inventory. If a scan failed or was interrupted, complete another scan first. | -| `run` | Scan and copy in one command. Run it again to pick up keys added since the previous scan. | -| `status` | Read object counts from the local state files. This does not contact S3. | -| `diff` | Check which source keys are missing or have different sizes or comparable ETags at the destination. | -| `diff --extra` | Also list keys found only at the destination. These do not make the command fail. | +`diff` verifies bucket existence, object sizes and full-body SHA-256, and compares preserved metadata. It requires read permissions on both sides and consumes read bandwidth. `--extra` additionally reports target-only keys without treating them as a migration failure. The rate limit applies to source body reads in run/migrate, including the extra full-source digest pass used by multipart copies; it does not limit diff or destination reads/writes. -## Resume a transfer +For an automated gate, `run --strict` and `migrate --strict` return an error if the state contains any pending, failed, conflict or skipped objects, including outcomes from earlier runs. `diff --strict` also checks target-only objects and fails when any exist. Strict mode does not replace a freeze window or final content verification. -After an interruption during copying, run `migrate` again. It checks existing keys before writing. A matching size and identical nonempty ETags mark an existing object `done`. Any other existing object is recorded as `conflict` and preserved. Even identical multipart content can have different ETags when the part sizes differ, so review conflicts left by an interrupted upload. If the source has changed since the inventory was built, use `run` to refresh the inventory before retrying. +`diff --issues-jsonl /path/to/new-file.jsonl` streams all issues as JSON lines containing bucket, key, kind and detail. It refuses to overwrite an existing file. Include `--extra` or `--strict` to record target-only keys. An error or interruption can leave a partial file, so check the command result before treating it as complete. -Inspect `last_error` on `failed` rows. A confirmed missing source key is `skipped` and can be picked up if it reappears on a later scan. Both `done` and `conflict` are terminal. If an object was subsequently removed from the destination, start a new inventory in a separate state directory to reconsider it. A database belongs to one bucket and one pair of endpoints. Confirm the cluster addresses before opening a database created by an older version. +Errors, partial scans and cancellation return nonzero. Review conflicts and skipped source keys even when a copy command exits successfully; only an independently reviewed final verification is a cutover gate. -`diff` reads current listings and object headers independently of the inventory. Its `size_only` counter is included in `ok` and identifies objects for which only the size could be checked. For an empty source bucket, `diff` checks that the destination bucket exists. A missing destination bucket also yields exit code 1. A byte-for-byte audit requires reading object bodies separately. +State binds source/target endpoints and bucket. Do not repoint a state DB to another cluster. Legacy unbound state with processed rows is rejected: choose a new state directory, rescan and let the tool verify existing target objects. All-bucket mode preserves your basename: job-a.db becomes job-a-photos.db. A process lock prevents concurrent writers while status is read-only. Keep DB, WAL and lock files intact while running. -## Set concurrency and bandwidth +Parts spool to disk with strict range and length checks. `spool_max_bytes` defaults to 1 GiB and bounds concurrent reservations in one migration, including one extra byte per file for length checks. A single object or part larger than the budget fails; increase the budget or reduce the part size/threshold. This is not a disk quota: files left by crashes, other processes, and other directory contents are excluded. After confirming no jobs are active, manually clean stale files from a dedicated spool directory; monitor free space. Resume retries whole objects; interrupted uploads after SIGKILL require the target's incomplete-multipart lifecycle cleanup. Source changes invalidate inventory rows and may produce conflicts; this is not continuous synchronization. -| Setting | Default | Effect | -| --- | --- | --- | -| `--workers` / `WORKERS` | 16 | Concurrent copies, or concurrent HEAD requests for `diff` | -| `--multipart-concurrency` / `MULTIPART_CONCURRENCY` | 4 | Concurrent parts per large object | -| `--rate-limit` / `RATE_LIMIT` | Unlimited | Combined bandwidth for reading source object bodies | +Only current object data, common content headers and user metadata are migrated. Versions, delete markers, bucket policies, tags, ACLs, storage class, Object Lock, retention/legal hold and source encryption settings are outside scope. -The CLI takes precedence over the environment, which takes precedence over YAML. In YAML, setting either concurrency value to zero selects its default. On the command line and in the environment, concurrency must be at least one. A zero rate limit always means unlimited. `20M` means 20,000,000 bytes/s and `20MiB` means 20,971,520 bytes/s. Uploads consume bandwidth in addition to source reads. [Configuration and tuning](../README.md#concurrency) +## Testing an explicit RustFS release -## Exit status +```sh +go test ./... +go test -race ./... +go vet ./... +python3 scripts/audit-local-rustfs.py \ + --rustfs-binary /absolute/path/rustfs --expect-version 1.0.4 +``` + +Replace `/absolute/path/rustfs` with the absolute path to the release executable. Before starting either node, the launcher runs that exact file with `--version` and requires an exact match with `1.0.4`. It never falls back to a RustFS executable found on PATH. Both isolated loopback nodes use the verified file, and their processes and temporary data are cleaned up afterward. + +The launcher records the executable path, version output and binary SHA-256 in `audit-results/rustfs-1.0.4/rustfs-binary.json`, with node logs beside it; `--output-dir` selects another evidence directory. The separate `real_s3` suite includes full-content verification and interrupted multipart migration followed by recovery from reopened SQLite. These are test scenarios, not a claim that this release has passed. Actual results must be recorded after running the suite against the identified binary. + +Earlier results for `1.0.0-alpha.61` remain historical evidence for that release only. They do not establish either success or failure for `1.0.4`. -| Code | Meaning | -| --- | --- | -| 0 | The command completed. Check `conflict` and `skipped` counts for objects that may need attention. | -| 1 | The operation failed or was interrupted, at least one copy failed, or `diff` found missing or mismatched keys. | -| 130 | A second interrupt forced an immediate exit. | +See [README](../README.md) for configuration, tuning and limits, [design](DESIGN.md) for implementation, and [fix validation](FIXES-2026-10-29.md) for the tested version and remaining compatibility constraints. diff --git "a/docs/\344\275\277\347\224\250\346\211\213\345\206\214.md" "b/docs/\344\275\277\347\224\250\346\211\213\345\206\214.md" index 93f184c..0696793 100644 --- "a/docs/\344\275\277\347\224\250\346\211\213\345\206\214.md" +++ "b/docs/\344\275\277\347\224\250\346\211\213\345\206\214.md" @@ -1,412 +1,74 @@ -# migration 中文使用手册 +# S3 对象迁移使用手册 -[中文快速入门](../README_ZH.md)介绍安装和日常用法。本手册说明如何为生产环境建立清单、控制迁移负载,以及在中断或失败后核对结果。 +## 迁移前提 -工具会补齐缺失的对象,将同名冲突记入 `conflict.log`,并用本地 SQLite 数据库保存进度。迁移不会删除对象。目标端的 `PutObject` 和 `CompleteMultipartUpload` 都必须支持 `If-None-Match: *` 条件写入。这样,即使业务在迁移检查之后才写入同名对象,也能保留该对象。 +源集群在扫描、迁移和最终验收期间必须冻结写入与删除,包括应用双删和生命周期删除。 迁移清单对象在目标端的业务删除也必须暂停或通过删除墓碑协调;仅禁止旧集群删除不能阻止历史对象被重新写入目标。`source_frozen: true`、`SOURCE_FROZEN=true` 或 `--source-frozen` 只是声明已经完成外部冻结,不会替你修改桶权限或停止应用。 ---- +目标集群必须原子实现 PutObject、CompleteMultipartUpload 的 `If-None-Match: *`。程序对已有目标执行内容校验或报告冲突,不主动覆盖,不调用 DeleteObject。迁移必须以实际服务版本验证条件写支持;客户端无法修复服务端忽略条件请求的问题。 -## 1. 首次迁移与核对 +## 操作步骤 -```bash -cp config.example.yaml config.yaml # 填写来源 / 目标地址和密钥 -./bin/migration run -c config.yaml # 扫描 + 复制 -./bin/migration diff -c config.yaml # 核对来源是否都到了目标 +```sh +# Go 1.26+,go.mod 选择 go1.26.10 +go build -o bin/migration . +cp config.example.yaml config.yaml +# 编辑配置,为任务创建独立状态目录,并在外部冻结源写入/删除 +./bin/migration list -c config.yaml +./bin/migration run -c config.yaml --source-frozen --bucket photos --rate-limit 20M +./bin/migration status -c config.yaml +./bin/migration diff -c config.yaml ``` -如果集群还有余量,可以提高并发数。下面的示例允许同时处理 32 个对象,所有任务每秒合计最多从源端读取 20 MB。 +配置完整说明见 [README](../README.md)。bucket 为空迁移全部源桶;未知字段会报错,避免拼错 bucket 后静默扩大范围。CLI > 环境变量 > YAML > 默认值。跨不可信网络使用 HTTPS;配置文件权限建议 0600。 -```bash -./bin/migration run -c config.yaml --workers 32 --multipart-concurrency 4 --rate-limit 20M -``` - -`config.yaml` 里 `bucket:` 留空,就会迁移来源上的**每一个桶**。只迁一个桶时写成 `bucket: photos`,或命令行加 `--bucket photos`。 - -查看全部帮助(中英双语): - -```bash -./bin/migration --help -./bin/migration run --help -./bin/migration diff --help -``` - ---- - -## 2. 安装与编译 - -需要 Go 1.22+。纯 Go SQLite,**不需要 CGO**。 - -```bash -git clone https://github.com/rustfs/migration.git -cd migration -CGO_ENABLED=0 go build -o bin/migration . -# 或 -make build -``` - -以上命令会生成可执行文件 `bin/migration`。 - -打开 [Build packages](https://github.com/rustfs/migration/actions/workflows/packages.yml),在成功运行的 **Artifacts** 中选择对应平台。解压下载文件,用随附的 SHA-256 校验值核对软件包,再解开软件包。Linux amd64 和 arm64 使用 `.tar.gz`,Windows amd64 使用 `.zip`,可执行文件为 `migration.exe`。 - ---- - -## 3. 配置 - -```yaml -old: # 来源(只读) - endpoint: "http://10.0.0.1:9000" - access_key: "OLD_AK" - secret_key: "OLD_SK" - region: "us-east-1" - -new: # 目标(读 + 写,需要能 CreateBucket) - endpoint: "http://haproxy.new.local:9000" - access_key: "NEW_AK" - secret_key: "NEW_SK" - region: "us-east-1" - -bucket: "" # 空 = 全部桶 -db_path: "./migration.db" -conflict_log: "./conflict.log" -spool_dir: "" # 小对象临时目录,默认跟 db 同目录 - -workers: 16 # 对象并发。0 或省略 = 16 -multipart_threshold: 52428800 # ≥ 50MiB 走分片上传。0 或省略 = 50MiB -multipart_part_size: 16777216 # 16 MiB。0 或省略 = 16MiB。非末片必须 ≥ 5 MiB(5242880);更小会在加载配置时失败 -multipart_concurrency: 4 # 单个大对象的分片并发。0 或省略 = 4 -rate_limit: 0 # 源读取合计上限。0 或省略 = 不限速 -``` - -用 `rate_limit` 限制源端总读取带宽,用 `workers` 和 `multipart_concurrency` 控制请求并发数。具体用法见[并发与带宽](#9-并发与带宽)。 - -分别填写两端的 HTTP 或 HTTPS 地址,并在凭据字段中填写访问密钥。端点 URL 不可包含凭据、查询参数或片段。如果需要在目标端创建桶,目标账户还需具备 `s3:CreateBucket` 权限。地址均采用路径式寻址。 - -### 3.1 配置优先级 - -优先级从高到低: - -1. 命令行 `--workers`、`--multipart-concurrency`、`--rate-limit`、`--bucket` -2. 环境变量 -3. YAML -4. 内置默认值(`workers=16`,`multipart_concurrency=4`,分片阈值 50MiB,分片大小 16MiB,`rate_limit` 不限速) - -环境变量: - -`OLD_ENDPOINT` `OLD_AK` `OLD_SK` `OLD_REGION` -`NEW_ENDPOINT` `NEW_AK` `NEW_SK` `NEW_REGION` `REGION` -`BUCKET` `DB_PATH` `CONFLICT_LOG` `SPOOL_DIR` -`WORKERS` `MULTIPART_CONCURRENCY` `RATE_LIMIT` - -并发数字的写法: - -| 写法 | 结果 | -| --- | --- | -| YAML 省略,或写成 `0` | 用默认值 | -| YAML 写成负数,或分片阈值 / 分片大小为负数 | 启动即报错 | -| 环境变量 `WORKERS` / `MULTIPART_CONCURRENCY` 未设置 | 沿用 YAML | -| 环境变量设为 `0`、负数或非整数 | 报错,不会悄悄退回默认值 | -| 命令行没写这两个 flag | 沿用环境变量或 YAML | -| 命令行写了 `--workers 0` 或负数 | 报错 | - -例子:YAML 里 `workers: 8`,环境变量 `WORKERS=32`,命令行 `--workers 4`,实际使用 **4**。 - -`rate_limit` 的 `0` 在每一层都表示不限速,包括命令行 `--rate-limit 0` 和 `RATE_LIMIT=0`。这和 `workers` 不同:`workers` 在 YAML 里写 `0` 才表示默认 16,写在命令行或环境变量里会报错。 - -带宽的写法(大小写不敏感): - -| 写法 | 含义 | 字节/秒 | -| --- | --- | --- | -| `20M`、`20MB` | 十进制兆字节,20×1000×1000 | 20000000 | -| `30M` | 十进制,30×1000×1000 | 30000000 | -| `50M`、`50MB` | 十进制,50×1000×1000 | 50000000 | -| `20Mi`、`20MiB` | 二进制兆字节,20×1024×1024 | 20971520 | -| `2K`、`2KB` | 十进制,2×1000 | 2000 | -| `2Ki`、`2KiB` | 二进制,2×1024 | 2048 | -| `1G`、`1GB` | 十进制,1000³ | 1000000000 | -| `1Gi`、`1GiB` | 二进制,1024³ | 1073741824 | -| 裸数字,如 `1048576` | 字节/秒 | 1048576 | -| `0`、`0M`,或整项省略 | 不限速 | — | - -`M` 不是 `Mi`。口语里的「20 兆」如果按 1024 算,要写成 `20Mi` 或 `20MiB`,不要写成 `20M`。`20M` 比 `20MiB` 少大约 5%(20000000 对 20971520)。 - ---- - -## 4. 命令说明 - -| 命令 | 作用 | 是否写目标 | 用到的并发 | -| --- | --- | --- | --- | -| `migration list -c config.yaml` | 列出源集群全部桶 | 否 | 无 | -| `migration run -c config.yaml` | **推荐**:先扫描再复制 | 是(但不覆盖) | 复制阶段用 `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 status -c config.yaml` | 看本地进度,不访问 S3 | 否 | 无 | -| `migration diff -c config.yaml` | 按源清单对目标做 HEAD,查缺失和不一致 | 否 | `workers`(并行 HEAD)。不限速 | -| `migration diff --extra -c config.yaml` | 同上,并列出**仅目标上有**的 key | 否 | `workers` | - -通用参数: - -- `-c, --config` 配置文件,默认 `config.yaml` -- `--bucket NAME` 覆盖 YAML 里的桶名 -- `--workers N` 对象并发。`run` / `migrate` 同时复制 N 个对象;`diff` 同时 HEAD N 个对象。必须 `>= 1` -- `--multipart-concurrency N` 单个大对象内部同时上传的分片数。必须 `>= 1`。`diff` / `scan` / `list` 不使用它 -- `--rate-limit SIZE` 所有复制 worker 从源读取的合计上限,例如 `--rate-limit 20M`。`0` 表示不限速。`scan` / `diff` / `list` 不使用它 -- `--help` 中英双语帮助 -- `--version` 版本号 - ---- - -## 5. 推荐操作流程 - -### 5.1 全量迁移(最常用) - -```bash -./bin/migration list -c config.yaml # 确认能连上来源 -./bin/migration run -c config.yaml --workers 16 --rate-limit 20M # 扫描并复制,源读取合计不超过 20MB/s -./bin/migration status -c config.yaml # 看进度 -./bin/migration diff -c config.yaml --workers 32 # 确认源上的对象都在目标上 -``` - -`run` 对每个桶会: - -1. 检查源桶存在(`HeadBucket`) -2. 单线程执行 `ListObjectsV2`,将完整清单写入 SQLite。 -3. 检查目标桶,缺失时创建。 -4. 最多同时复制 `workers` 个对象。如果业务恰好在目标检查后创建同名对象,条件写入会保护该对象。工具会重新核对目标,将结果记为 `done` 或 `conflict`。 -5. 对象大小达到 `multipart_threshold` 时采用分片上传。每个对象最多并行传输 `multipart_concurrency` 个分片,所有源端读取共享同一带宽上限。 -6. 核对已写入对象的大小,并用写入操作返回的 ETag 核实目标对象。单次 PUT 还会核对可比较的源、目标 ETag。 - -### 5.2 只迁一个桶 - -```bash -./bin/migration run -c config.yaml --bucket photos --workers 8 --multipart-concurrency 8 --rate-limit 30M -``` - -### 5.3 增量补拷(源上后来新写入的对象) - -S3 的 List 接口**不能**按修改时间在服务端过滤。正确做法是再扫一遍全量清单: - -```bash -./bin/migration scan -c config.yaml # 新 key 变成 pending;曾经 skipped 后又出现的也会重试 -./bin/migration migrate -c config.yaml --workers 16 -./bin/migration diff -c config.yaml -``` +## 恢复和升级 -或直接再跑一次 `run`(已 `done` / `conflict` 的行不会被覆盖重传)。 +`scan` 完整扫描到 SQLite;失败扫描会使上一代完成凭证失效。`migrate --source-frozen` 必须使用已经扫描完成的清单,不会新建空库后宣告成功。`run --source-frozen` 先扫描再迁移。 -### 5.4 中断后续跑 +每个状态库绑定源/目标端点与桶。不同任务使用不同目录或文件名,全桶模式也保留自定义文件名,如 job-a.db 派生 job-a-photos.db。旧版无端点身份且已有处理记录的 DB 不能自动接管;使用新目录重新扫描,程序会读回已有目标核对内容,不需要删除目标数据。 -第一次 `Ctrl-C` 或 `SIGTERM`:取消 worker 池。还没开始的对象保持 `pending`;正在上传的分片会 `AbortMultipartUpload`(放弃这次未完成的上传会话,不删除已提交对象)。SQLite 里已经写完的状态会保留。再按一次强制退出,退出码 `130`。 +同一 DB 只允许一个写入进程。status 只读,可与迁移并行;缺库/坏库会报错。运行期间不要手工删除 DB、WAL、SHM 或 .lock 文件,也不要复制一个仍在变化的 DB 当成可靠备份。 -目标端已有同名对象时,只有大小相同,且两端 ETag 均非空、完全相同,才会记为 `done`。其余情况均记为 `conflict`,保留目标对象。分片边界不同,即便内容相同也可能产生不同的 ETag。若在上传成功后、状态落盘前中断,恢复时请人工核实这类冲突。 +源同 key 发生变化后重扫会重新验证,不会保持旧 done。目标有不同内容时记录 conflict,不会更新覆盖。这不是双向同步或持续同步工具。 -若源对象的 ETag 在扫描和复制之间发生变化,本次复制会失败。请先用 `scan` 刷新清单,再用 `migrate` 重试,也可直接重新执行 `run`。 +## 校验与退出状态 -取消(`context.Canceled`)、截止时间或 `request canceled` 记为 `failed`,下次直接 `migrate` 就会重试。错误文本里即使出现 `NotFound` 或 `StatusCode: 404`(分片 Abort 经常带 NoSuchUpload),也不记 `skipped`。`skipped` 只表示源请求完整结束,并确认对象已经不在。 +迁移通过 If-Match/VersionId 固定源读取,验证清单身份、分片范围和长度。目标提交后完整读回做 SHA-256 校验;已有同大小对象也读取两端比较。不能比较或缺少稳定 ETag 时失败,不会退化到只验大小。 -```bash -./bin/migration migrate -c config.yaml # 只重试 pending / failed -``` - -### 5.5 先盘点、再决定是否拷 - -```bash -./bin/migration scan -c config.yaml -./bin/migration status -c config.yaml # 查看各状态的对象数 -# 确认后再 -./bin/migration migrate -c config.yaml --workers 16 -``` - -`status` 以只读方式查看本地清单。全桶模式下,它会查找 `db_path` 旁边的 `migration-*.db`,以及已经绑定到桶的 `db_path` 文件本身。 - -执行 `migrate` 前须先用 `scan` 或 `run` 建立清单。状态库会绑定桶名和两端地址。使用旧版本的状态库前,请先核实它对应的集群。升级后的首次扫描会记录源地址,首次迁移会记录目标地址。 扫描失败或中断后,请先重新执行 `scan` 或 `run`,再使用 `migrate`。旧版本的状态库没有扫描完成标记。如果无法确认清单完整,请重新扫描。 - ---- - -## 6. 对象状态与冲突日志 - -| 状态 | 含义 | 再扫会刷新吗 | -| --- | --- | --- | -| `pending` | 待拷 | 会更新 size/etag | -| `failed` | 上次失败,`migrate` 会重试 | 会回到 pending | -| `skipped` | 源请求完整返回 404(对象已删)。取消或超时不是 skipped | **会**回到 pending(对象后来又出现时) | -| `done` | 已拷到目标并校验,或目标上已有与清单一致的对象 | 不会动 | -| `conflict` | 目标已有同名对象,且与清单不一致(大小不同,或缺少相同的非空 ETag),未覆盖 | 不会动 | - -冲突行写入 `conflict.log`(TSV): - -``` - -``` - -键名若包含控制字符或以双引号开头,日志会按 Go 字符串字面量的规则加引号并转义。 - -单桶模式使用你配置的 `db_path` / `conflict_log`。全桶模式自动变成: - -- `migration-<桶名>.db` -- `conflict-<桶名>.log` - -SQLite 以 WAL 打开。进程内只用一条数据库连接,避免把 `workers` 开大以后出现 `database is locked`。对象的字节流不经过这条连接,复制本身仍然并行。 - ---- - -## 7. diff 怎么读 - -```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 -``` - -- **missing**:源端存在,目标端缺失。处理方式取决于该对象的本地状态,见[常见问题](#11-常见问题) -- **size / etag**:两边同名但内容对不上(目标可能被别的写入改过;本工具不会覆盖) -- **extra_on_target**(需 `--extra`):只在目标上,通常是业务已经写到新集群,**不算失败** - -`diff` 通过大小和可比较的 ETag 核对对象,不下载正文。`ok` 中仅校验了大小的对象另计入 `size_only`。添加 `--extra` 会建立临时索引,列出仅存在于目标端的对象。源桶为空时,`diff` 仍会检查目标桶是否存在。目标桶缺失会返回退出码 1。缺失、大小不符或可比较的 ETag 不一致时,退出码为 `1`。 - -`--workers` 在 diff 里只控制并行 HEAD。diff 不读取 `multipart_concurrency`,也不会上传或删除。 - ---- - -## 8. 安全保证 +`diff` 验证两端桶、源清单中的 key、大小、完整 SHA-256 和保留的元数据。`diff --extra` 另外显示目标独有 key;目标允许有新业务对象,因此 extra 不独自令验收失败。 -| 保证 | 做法 | -| --- | --- | -| 永不覆盖目标对象 | 写前用 `HeadObject` 检查目标,并在 `PutObject` 和 `CompleteMultipartUpload` 时设置 `If-None-Match: *` | -| 永不删除 | 代码里没有 `DeleteObject`(分片失败只 `AbortMultipartUpload`) | -| 不走错桶 | `HeadBucket` + 每页 Name 校验 + SQLite 绑定桶名 | -| 源中途被删 | 只有完整返回的源 404 记 `skipped`;取消或超时记 `failed` | -| 崩溃可续 | 每对象状态在 SQLite WAL | -| 取消可续 | 第一次信号取消 worker;未完成的对象下次 `migrate` 继续 | -| 内存有上限 | 小对象落盘;大对象按分片读。等待队列最多约 2048 个对象描述,不会把全桶清单堆进内存 | -| 拷后校验 | 比 size;单 part 再比 ETag | +传输失败、取消、状态库错误、扫描不完整、diff 内容差异或验证错误都会非零退出。conflict 和明确源 NoSuchKey 的 skipped 需要人工核对。不能仅因 run 返回 0 就下线旧集群;还须确认冲突/跳过处置、最终 diff、冻结窗口和流量切换方案。 -不迁移:版本历史、删除标记、Object Lock、桶策略、生命周期规则。 +自动化场景可使用 `run --strict` 或 `migrate --strict`,状态库中存在待处理、失败、冲突或跳过对象时返回非零,包含之前运行留下的状态;`diff --strict` 也会检查并拒绝目标独有对象。严格模式不能代替冻结和最终内容验收。 ---- +`diff --issues-jsonl /path/to/new-file.jsonl` 可流式导出完整差异,每行包含 bucket、key、kind 和 detail,已有文件不会被覆盖。目标独有 key 需同时指定 `--extra` 或 `--strict` 才会记录。任务出错或中断可能留下不完整文件,应结合命令结果判断。 -## 9. 并发与带宽 +`spool_max_bytes` 默认 1 GiB,限制一次迁移中并发临时文件的预留总量。单个对象或分片超过预算会失败,可增大预算或降低分片大小、阈值。该限制不覆盖其他进程、异常退出留下的文件或磁盘上的其他数据;应使用专用临时目录、监控可用空间,并在确认任务已停止后清理遗留文件。 -### 9.1 并发 +## 资源与清理 -字节速率用 `rate_limit` / `--rate-limit`,见 [§9.3](#93-带宽限速)。并发决定在途请求数: +workers 控制对象并发,默认16;multipart_concurrency 控制单对象分片并发,默认4。分片落临时磁盘,单片5MiB到5GiB;磁盘峰值可能达到 workers×分片并发×分片大小,另有数据库和小对象开销。将 spool_dir 指向容量充足的磁盘。 -| 字段 | 含义 | 默认 | -| --- | --- | --- | -| `workers` | 同时在拷贝的对象数。`diff` 对目标做 HEAD 时也用这个并发。命令行 `--workers`,环境变量 `WORKERS` | 16 | -| `multipart_concurrency` | 单个大对象里并行上传的分片数(只在 `run` / `migrate` 的分片路径上)。命令行 `--multipart-concurrency`,环境变量 `MULTIPART_CONCURRENCY` | 4 | +rate_limit 限制 run/migrate 的所有源正文读取,包括分片完成前额外的完整源摘要读取。20M=20,000,000 B/s,20MiB=20×1024×1024 B/s,0=不限速。目标上传/校验读回和 diff 不受该限额限制。diff 会完整读取两端数据,需要安排业务负载窗口。 -`workers` 和 `multipart_concurrency` 是两层: +单对象正常迁移读取源1遍和目标1遍;分片正常迁移读取源约2遍和目标1遍。可靠校验增加读流量,不能套用旧版仅 HEAD 对比的成本估计。 -```text -workers = 4 个对象同时复制 - 对象 A(小文件) ── 1 个 GET + PUT - 对象 B(小文件) ── 1 个 GET + PUT - 对象 C(大文件) ── multipart_concurrency 个分片同时 GET + UploadPart - 对象 D(大文件) ── 同上 -``` - -峰值大约是 `workers × multipart_concurrency`。小对象每个只占一路;达到 `multipart_threshold` 的大对象会按分片把并发乘上去。默认 `16 × 4` 很容易打满网卡、源或目标集群,以及前面 HAProxy 的 `maxconn`。 - -希望少影响生产时,用 `--rate-limit 20M`(或 `30M`、`50M`)直接封顶源读取。在途请求仍然太多时,再把 `workers` 调小;大对象占满链路时,再把 `multipart_concurrency` 调小。改完看 `migration status` 的本地进度,并在机器上看网卡和集群负载(`status` 本身不访问 S3)。 - -```yaml -# 降负载的起点。先跑一小段,再按 status 和网卡调整。 -workers: 2 -multipart_concurrency: 2 -``` - -| 场景 | 建议 | -| --- | --- | -| 海量小文件,链路有余量 | `workers` 16~64,`multipart_concurrency` 保持 4 | -| 大小文件混合 | `workers` 8~32,`multipart_concurrency` 4~8 | -| 主要是超大对象 | `workers` 2~8,`multipart_concurrency` 4~16 | -| 排查单个对象为什么失败 | `--workers 1`,变成串行,日志更好对 | -| 代理返回 503、大量超时、源盘 100% | 先减 `workers`。如果慢的是大文件,再减 `multipart_concurrency` | -| 扫描阶段想加速 | 做不到。`scan` 固定单线程,加大 `--workers` 不会让 List 变快 | -| 迁移时要给生产留带宽 | `--rate-limit 20M` 起步,观察源集群后再调到 `30M` 或 `50M`。业务低峰可以设 `0` 取消限额 | - -链路有余量、想更快时反过来:小文件多就加大 `workers`;单个大文件就加大 `multipart_concurrency`,或减小 `multipart_part_size`(单位字节,默认 16 MiB,不能小于 5 MiB)。 - -`multipart_part_size` 的取值范围为 5 MiB 至 5 GiB,默认 16 MiB。超过 5 GiB 的对象始终使用分片上传。每个对象最多拆为 10,000 片,必要时工具会自动增大分片。如果仍需单片超过 5 GiB,迁移会报错。 - -### 9.2 运行注意事项 - -- `/tmp` 若是内存盘,把 `spool_dir` 指到真实磁盘。每个正在复制的小对象占一个临时文件,最大约 `multipart_threshold`,个数随 `workers` 上升 -- SQLite 单文件不要多进程同时写同一个 `db_path` -- 不要按「启动时间窗口」自己做增量,List API 做不到;请全量再扫 - -SQLite 存的是元数据(key/size/etag/状态),几千万行通常没问题。对象过亿时本工具用 keyset 分页拉 pending,内存仍然受控。多台机器同时迁同一批对象需要以后换独立数据库,当前版本是单机。 - -### 9.3 带宽限速 - -`rate_limit` 是**所有正在复制的 worker 共用**的每秒字节上限,包括同一个大对象里并行的分片。实现是一个令牌桶:从源读到的对象字节都从这同一个额度里扣。多个 S3 桶按顺序迁移,同一时刻只有一个桶在复制,所以这个数字就是整个进程从源拉对象数据的上限。 +普通失败会取消同对象其他分片并尝试 AbortMultipartUpload。SIGKILL 或主机断电无法执行 abort,应配置服务端未完成分片清理生命周期。恢复是对象级重试,不保证复用已经上传的分片。 -它统计的是源对象正文,不统计 List、HEAD 和冲突检查。因此: +## 能力范围与测试 -- `run` 的扫描阶段不限速,复制阶段限速 -- `migrate` 限速 -- `scan`、`diff`、`list`、`status` 不限速 +保留当前对象内容、常见内容响应头、用户 metadata。不复制版本历史、删除标记、对象 tags、ACL、存储等级、源 SSE 配置、Object Lock/保留期、桶策略和生命周期。依赖这些语义的业务需要额外方案。 -`20M` 表示每秒最多读 20000000 字节(十进制 MB)。`20MiB` 表示每秒 20971520 字节。生产上想少影响在线业务时,从 `20M` 开始,确认源延迟正常后再放到 `30M` 或 `50M`。设为 `0` 或从配置里删掉这一项,就是不限速。 - -上传不重复扣这个额度。小对象会先按限额从源读完,再写入目标,所以源侧的读取速度不超过配置值;目标侧在读完之后可能短时更快。迁移进程和业务如果走同一块网卡,写入仍会再占带宽,请把额度留出余量。 - -限速不改变安全模型。目标上已有且与清单一致的对象记 `done`,不再上传;不一致才记冲突,不覆盖。没有任何删除。第一次 Ctrl-C 会取消正在等待额度的读取,未完成的对象留在 SQLite,再次执行 `migrate` 即可继续。 - -YAML、环境变量和命令行示例(优先级:命令行 > 环境变量 > YAML): - -```yaml -rate_limit: 20M +```sh +go test ./... +go test -race ./... +go vet ./... +python3 scripts/audit-local-rustfs.py \ + --rustfs-binary /absolute/path/rustfs --expect-version 1.0.4 ``` -```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 # 明确取消限额 -``` - ---- - -## 10. 退出码 - -| 码 | 含义 | -| --- | --- | -| 0 | 命令执行完成。冲突以及源端已删除的对象分别计数。 | -| 1 | 配置有误、操作被中断或失败、有对象复制失败,或 `diff` 发现对象缺失或不一致。 | -| 130 | 第二次 SIGINT / SIGTERM,强制退出 | - ---- - -## 11. 常见问题 - -| 现象 | 处理 | -| --- | --- | -| 想把速度限在大约 20 MB/s | `--rate-limit 20M`(十进制,20000000 字节/秒)。1024 进制写 `20MiB`。见[带宽限速](#93-带宽限速) | -| `old.endpoint is required` | 检查 YAML 或 `OLD_ENDPOINT` | -| `multipart_part_size must be >= 5242880` | 分片小于 5 MiB。改成 ≥ 5242880(默认 16 MiB)。工具不会自动抬高 | -| `workers must be >= 1` | 命令行、`WORKERS` 或 YAML 的 `workers` 不合法。YAML 的 `0` 才表示默认 16 | -| `multipart_concurrency must be >= 1` | 同上,针对分片并发 | -| `env WORKERS="…" is not an integer` | 环境变量里有空格或单位,改成纯数字。带宽要用 `RATE_LIMIT=20M`,不要把单位写进 `WORKERS` | -| `unknown size suffix` 或 `rate limit` | `rate_limit` / `RATE_LIMIT` / `--rate-limit` 的单位无法识别。十进制写 `20M`,1024 进制写 `20MiB` | -| 限速后源仍然很忙 | `20M` 只限制从源读出的对象字节。上传另算。共用网卡时把数字再调低,例如 `20M` 改成 `10M` | -| 扫描、diff 没有变慢 | 正常。限额只在复制对象正文时生效 | -| `head bucket "…" on source` | 桶不存在、地址错、或密钥没有读权限 | -| `create bucket … on target` | 目标密钥缺少 `s3:CreateBucket` | -| 扫描很慢 | 正常,`scan` 是单线程。并发从 `migrate` / `run` 的复制阶段才开始 | -| 加大 workers 后 503 变多 | 减小 `workers`。大对象再减小 `multipart_concurrency`,让峰值 `workers × multipart_concurrency` 低于代理 `maxconn` | -| 多个对象出现 `etag mismatch` | 单独核对相关对象的内容。分片方式和服务端加密都可能影响 ETag。 | -| `db_path is bound to bucket "X"` | 一个 db 只绑定一个桶,换路径 | -| `database is locked` | 不要对同一 db 起两个进程 | -| 磁盘被写满 | 检查 `spool_dir`。workers 大时临时文件更多 | -| Ctrl-C 退不出 | 等当前请求结束,或再按一次 | -| `diff` 仍报告 `missing` | 若状态为 `failed`,先查看 `last_error`,排除原因后重试。若已记为 `done` 或 `conflict`,请另设状态目录,重新建立清单。全桶模式下,仅更换数据库文件名不足以启用新清单。 | - ---- - -## 12. 和生产架构的关系 +将 `/absolute/path/rustfs` 替换为待测 RustFS 二进制的绝对路径。最后一条命令先运行这个文件的 `--version`,要求版本与 `1.0.4` 精确一致;不一致时不启动任何实例,也不会退回 PATH 中已有的其他版本。验证后使用同一二进制创建两个独立回环实例及临时数据,结束后清理。 -典型场景:旧集群只读历史数据,新集群承接全部写入;应用双读。本工具把旧集群上「目标还没有的 key」补过去,**不会**把新集群上更新的对象打回旧内容。 +启动器将实际二进制路径、版本输出和 SHA-256 保存到 `audit-results/rustfs-1.0.4/rustfs-binary.json`,同目录保存节点日志;可用 `--output-dir` 改变证据目录。独立的 `real_s3` 测试包含完整内容验收,以及真实分片上传取消、Abort 清理、重开 SQLite 后恢复等场景。测试覆盖范围不等于测试已经通过,`1.0.4` 的结论必须以实际执行结果为准。 -下线旧集群前,请检查 `diff` 的缺失项、`size_only` 数量,以及 `conflict.log` 中需要人工核实的对象。 +本机旧 RustFS `1.0.0-alpha.61` 的分片兼容失败仅作为该版本的历史证据保留,不能解释为 `1.0.4` 的通过或失败。请对拟上线版本验证,不通过时不能关闭完整性校验绕过。具体结果见 [修复验证记录](FIXES-2026-10-29.md)。 diff --git a/go.mod b/go.mod index b2eacf0..f4400a6 100644 --- a/go.mod +++ b/go.mod @@ -1,29 +1,31 @@ module github.com/rustfs/migration -go 1.22 +go 1.26.0 + +toolchain go1.26.10 require ( - github.com/aws/aws-sdk-go-v2 v1.30.3 + github.com/aws/aws-sdk-go-v2 v1.41.5 github.com/aws/aws-sdk-go-v2/config v1.27.27 github.com/aws/aws-sdk-go-v2/credentials v1.17.27 - github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2 - github.com/aws/smithy-go v1.20.3 + github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3 + github.com/aws/smithy-go v1.24.2 github.com/spf13/cobra v1.8.1 gopkg.in/yaml.v3 v3.0.1 modernc.org/sqlite v1.31.1 ) require ( - github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 // indirect - github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 // indirect github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 // indirect @@ -35,7 +37,7 @@ require ( github.com/ncruces/go-strftime v0.1.9 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/spf13/pflag v1.0.5 // indirect - golang.org/x/sys v0.22.0 // indirect + golang.org/x/sys v0.44.0 // indirect modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect modernc.org/libc v1.55.3 // indirect modernc.org/mathutil v1.6.0 // indirect diff --git a/go.sum b/go.sum index 23a5aae..9a01ce1 100644 --- a/go.sum +++ b/go.sum @@ -1,39 +1,39 @@ -github.com/aws/aws-sdk-go-v2 v1.30.3 h1:jUeBtG0Ih+ZIFH0F4UkmL9w3cSpaMv9tYYDbzILP8dY= -github.com/aws/aws-sdk-go-v2 v1.30.3/go.mod h1:nIQjQVp5sfpQcTc9mPSr1B0PaWK5ByX9MOoDadSN4lc= -github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 h1:tW1/Rkad38LA15X4UQtjXZXNKsCgkshC3EbmcUmghTg= -github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3/go.mod h1:UbnqO+zjqk3uIt9yCACHJ9IVNhyhOCnYk8yA19SAWrM= +github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY= +github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI= github.com/aws/aws-sdk-go-v2/config v1.27.27 h1:HdqgGt1OAP0HkEDDShEl0oSYa9ZZBSOmKpdpsDMdO90= github.com/aws/aws-sdk-go-v2/config v1.27.27/go.mod h1:MVYamCg76dFNINkZFu4n4RjDixhVr51HLj4ErWzrVwg= github.com/aws/aws-sdk-go-v2/credentials v1.17.27 h1:2raNba6gr2IfA0eqqiP2XiQ0UVOpGPgDSi0I9iAP+UI= github.com/aws/aws-sdk-go-v2/credentials v1.17.27/go.mod h1:gniiwbGahQByxan6YjQUMcW4Aov6bLC3m+evgcoN4r4= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11 h1:KreluoV8FZDEtI6Co2xuNk/UqI9iwMrOx/87PBNIKqw= github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11/go.mod h1:SeSUYBLsMYFoRvHE0Tjvn7kbxaUhl75CJi1sbfhMxkU= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 h1:SoNJ4RlFEQEbtDcCEt+QG56MY4fm4W8rYirAmq+/DdU= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15/go.mod h1:U9ke74k1n2bf+RIgoX1SXFed1HLs51OgUSs+Ph0KJP8= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 h1:C6WHdGnTDIYETAm5iErQUiVNsclNx9qbJVPIt03B6bI= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15/go.mod h1:ZQLZqhcu+JhSrA9/NXRm8SkDvsycE+JkV3WGY41e+IM= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 h1:Rgg6wvjjtX8bNHcvi9OnXWwcE0a2vGpbwmtICOsvcf4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21/go.mod h1:A/kJFst/nm//cyqonihbdpQZwiUhhzpqTsdbhDdRF9c= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 h1:PEgGVtPoB6NTpPrBgqSE5hE/o47Ij9qk/SEZFbUOe9A= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21/go.mod h1:p+hz+PRAYlY3zcpJhPwXlLC4C+kqn70WIHwnzAfs6ps= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 h1:hT8rVHwugYE2lEfdFE0QWVo81lF7jMrYJVDWI+f+VxU= github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0/go.mod h1:8tu/lYfQfFe6IGnaOdrpVgEL2IrrDOf6/m9RQum4NkY= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15 h1:Z5r7SycxmSllHYmaAZPpmN8GviDrSGhMS6bldqtXZPw= -github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15/go.mod h1:CetW7bDE00QoGEmPUoZuRog07SGVAUVW6LFpNP0YfIg= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 h1:dT3MqvGhSoaIhRseqw2I0yH81l7wiR2vjs57O51EAm8= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3/go.mod h1:GlAeCkHwugxdHaueRr4nhPuY+WW+gR8UjlcqzPr1SPI= -github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17 h1:YPYe6ZmvUfDDDELqEKtAd6bo8zxhkm+XEFEzQisqUIE= -github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17/go.mod h1:oBtcnYua/CgzCWYN7NZ5j7PotFDaFSUjCYVTtfyn7vw= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 h1:HGErhhrxZlQ044RiM+WdoZxp0p+EGM62y3L6pwA4olE= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17/go.mod h1:RkZEx4l0EHYDJpWppMJ3nD9wZJAa8/0lq9aVC+r2UII= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15 h1:246A4lSTXWJw/rmlQI+TT2OcqeDMKBdyjEQrafMaQdA= -github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15/go.mod h1:haVfg3761/WF7YPuJOER2MP0k4UAXyHaLclKXB6usDg= -github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2 h1:sZXIzO38GZOU+O0C+INqbH7C2yALwfMWpd64tONS/NE= -github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2/go.mod h1:Lcxzg5rojyVPU/0eFwLtcyTaek/6Mtic5B1gJo7e/zE= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22 h1:rWyie/PxDRIdhNf4DzRk0lvjVOqFJuNnO8WwaIRVxzQ= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22/go.mod h1:zd/JsJ4P7oGfUhXn1VyLqaRZwPmZwg44Jf2dS84Dm3Y= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 h1:5EniKhLZe4xzL7a+fU3C2tfUN4nWIqlLesfrjkuPFTY= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7/go.mod h1:x0nZssQ3qZSnIcePWLvcoFisRXJzcTVvYpAAdYX8+GI= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 h1:JRaIgADQS/U6uXDqlPiefP32yXTda7Kqfx+LgspooZM= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13/go.mod h1:CEuVn5WqOMilYl+tbccq8+N2ieCy0gVn3OtRb0vBNNM= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 h1:c31//R3xgIJMSC8S6hEVq+38DcvUlgFY0FM6mSI5oto= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21/go.mod h1:r6+pf23ouCB718FUxaqzZdbpYFyDtehyZcmP5KL9FkA= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 h1:ZlvrNcHSFFWURB8avufQq9gFsheUgjVD9536obIknfM= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21/go.mod h1:cv3TNhVrssKR0O/xxLJVRfd2oazSnZnkUeTf6ctUwfQ= +github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3 h1:HwxWTbTrIHm5qY+CAEur0s/figc3qwvLWsNkF4RPToo= +github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM= github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 h1:BXx0ZIxvrJdSgSvKTZ+yRBeSqqgPM89VPlulEcl37tM= github.com/aws/aws-sdk-go-v2/service/sso v1.22.4/go.mod h1:ooyCOXjvJEsUw7x+ZDHeISPMhtwI3ZCB7ggFMcFfWLU= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 h1:yiwVzJW2ZxZTurVbYWA7QOrAaCYQR72t0wrSBfoesUE= github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4/go.mod h1:0oxfLkpz3rQ/CHlx5hB7H69YUpFiI1tql6Q6Ne+1bCw= github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 h1:ZsDKRLXGWHk8WdtyYMoGNO7bTudrvuKpDKgMVRlepGE= github.com/aws/aws-sdk-go-v2/service/sts v1.30.3/go.mod h1:zwySh8fpFyXp9yOr/KVzxOl8SRqgf/IDw5aUt9UKFcQ= -github.com/aws/smithy-go v1.20.3 h1:ryHwveWzPV5BIof6fyDvor6V3iUL7nTfiTKXHiW05nE= -github.com/aws/smithy-go v1.20.3/go.mod h1:krry+ya/rV9RDcV/Q16kpu6ypI4K2czasz0NC3qS14E= +github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng= +github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= @@ -61,8 +61,8 @@ github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= -golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ= +golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw= golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= diff --git a/internal/cluster/audit_test.go b/internal/cluster/audit_test.go new file mode 100644 index 0000000..5afa07e --- /dev/null +++ b/internal/cluster/audit_test.go @@ -0,0 +1,143 @@ +package cluster + +import ( + "context" + "encoding/xml" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/rustfs/migration/internal/config" + "github.com/rustfs/migration/internal/s3client" +) + +func TestListBucketsFollowsContinuation(t *testing.T) { + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + w.Header().Set("Content-Type", "application/xml") + if r.URL.Query().Get("continuation-token") == "page-two" { + _, _ = io.WriteString(w, `second`) + return + } + _, _ = io.WriteString(w, `firstpage-two`) + })) + defer srv.Close() + buckets, err := ListBuckets(context.Background(), auditClient(t, srv.URL, "us-east-1")) + if err != nil || len(buckets) != 2 || buckets[0].Name != "first" || buckets[1].Name != "second" || requests.Load() != 2 { + t.Fatalf("bucket pagination: buckets=%+v requests=%d err=%v", buckets, requests.Load(), err) + } +} + +func auditClient(t *testing.T, endpoint, region string) *s3.Client { + t.Helper() + cli, err := s3client.New(context.Background(), config.Endpoint{ + Endpoint: endpoint, Region: region, AccessKey: "test", SecretKey: "test", + }) + if err != nil { + t.Fatal(err) + } + return cli +} + +func TestEnsureBucketRechecksAlreadyOwned(t *testing.T) { + for _, accessible := range []bool{true, false} { + t.Run(fmt.Sprint(accessible), func(t *testing.T) { + var heads atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + if heads.Add(1) == 1 { + w.WriteHeader(http.StatusNotFound) + } else if accessible { + w.WriteHeader(http.StatusOK) + } else { + w.WriteHeader(http.StatusForbidden) + } + return + } + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(http.StatusConflict) + _, _ = io.WriteString(w, `BucketAlreadyOwnedByYou`) + })) + defer srv.Close() + err := EnsureBucket(context.Background(), auditClient(t, srv.URL, "us-east-1"), "bucket") + if (err == nil) != accessible || heads.Load() != 2 { + t.Fatalf("access=%v heads=%d err=%v", accessible, heads.Load(), err) + } + }) + } +} + +// BucketAlreadyExists means the name belongs to somebody else, unlike +// BucketAlreadyOwnedByYou. A failed create cannot prove a usable target. +func TestAuditEnsureBucketRejectsForeignOwner(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodHead: + w.WriteHeader(http.StatusNotFound) + case http.MethodPut: + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(http.StatusConflict) + _, _ = io.WriteString(w, `BucketAlreadyExistsname owned by another account`) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + })) + defer srv.Close() + if err := EnsureBucket(context.Background(), auditClient(t, srv.URL, "us-east-1"), "bucket"); err == nil { + t.Fatal("EnsureBucket accepted BucketAlreadyExists; target ownership/access was never established") + } +} + +// A regional client only changes endpoint/signing; CreateBucket still needs +// LocationConstraint in its XML body outside us-east-1. +func TestAuditEnsureBucketUsesConfiguredRegion(t *testing.T) { + const region = "eu-west-1" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + w.WriteHeader(http.StatusNotFound) + return + } + var input struct { + LocationConstraint string `xml:"LocationConstraint"` + } + if err := xml.NewDecoder(r.Body).Decode(&input); err != nil || input.LocationConstraint != region { + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `IllegalLocationConstraintExceptionmissing regional LocationConstraint`) + return + } + w.WriteHeader(http.StatusOK) + })) + defer srv.Close() + if err := EnsureBucket(context.Background(), auditClient(t, srv.URL, region), "bucket"); err != nil { + t.Fatalf("creating a bucket in configured region %s failed: %v", region, err) + } +} + +func TestListBucketsRejectsAlternatingContinuationTokens(t *testing.T) { + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := requests.Add(1) + w.Header().Set("Content-Type", "application/xml") + if n > 3 { + w.WriteHeader(http.StatusBadRequest) + return + } + next := "a" + if r.URL.Query().Get("continuation-token") == "a" { + next = "b" + } + fmt.Fprintf(w, `%s`, next) + })) + defer srv.Close() + _, err := ListBuckets(context.Background(), auditClient(t, srv.URL, "us-east-1")) + if err == nil || !strings.Contains(err.Error(), "repeated") || requests.Load() != 3 { + t.Fatalf("requests=%d err=%v", requests.Load(), err) + } +} diff --git a/internal/cluster/cluster.go b/internal/cluster/cluster.go index 384ca17..ae81e2f 100644 --- a/internal/cluster/cluster.go +++ b/internal/cluster/cluster.go @@ -2,13 +2,16 @@ package cluster import ( "context" + "errors" "fmt" "time" awsv2 "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" - "github.com/aws/aws-sdk-go-v2/service/s3/types" + s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" + "github.com/aws/smithy-go" + "github.com/rustfs/migration/internal/config" "github.com/rustfs/migration/internal/s3client" ) @@ -18,22 +21,44 @@ type Bucket struct { } func ListBuckets(ctx context.Context, cli *s3.Client) ([]Bucket, error) { - page, err := cli.ListBuckets(ctx, &s3.ListBucketsInput{}) - if err != nil { - return nil, fmt.Errorf("list buckets: %w", err) - } - out := make([]Bucket, 0, len(page.Buckets)) - for _, b := range page.Buckets { - item := Bucket{Name: awsv2.ToString(b.Name)} - if b.CreationDate != nil { - item.Created = *b.CreationDate + p := s3.NewListBucketsPaginator(cli, &s3.ListBucketsInput{MaxBuckets: awsv2.Int32(1000)}) + var out []Bucket + seenTokens := make(map[string]struct{}) + for p.HasMorePages() { + page, err := p.NextPage(ctx) + if err != nil { + return nil, fmt.Errorf("list buckets: %w", err) + } + if next := awsv2.ToString(page.ContinuationToken); next != "" { + if _, exists := seenTokens[next]; exists { + return nil, fmt.Errorf("list buckets repeated its continuation token") + } + seenTokens[next] = struct{}{} + } + for _, b := range page.Buckets { + item := Bucket{Name: awsv2.ToString(b.Name)} + if item.Name == "" { + return nil, fmt.Errorf("list buckets returned an empty name") + } + if err := config.ValidateBucketName(item.Name); err != nil { + return nil, fmt.Errorf("invalid listed bucket: %w", err) + } + if b.CreationDate != nil { + item.Created = *b.CreationDate + } + out = append(out, item) } - out = append(out, item) } return out, nil } func HeadBucket(ctx context.Context, cli *s3.Client, name string) error { + if name == "" { + return fmt.Errorf("bucket name is required") + } + if err := config.ValidateBucketName(name); err != nil { + return err + } _, err := cli.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: awsv2.String(name)}) if err != nil { return fmt.Errorf("head bucket %q: %w", name, err) @@ -44,6 +69,12 @@ func HeadBucket(ctx context.Context, cli *s3.Client, name string) error { // EnsureBucket creates the bucket on the target if it does not exist yet. // An already-existing bucket is left untouched. func EnsureBucket(ctx context.Context, cli *s3.Client, name string) error { + if name == "" { + return fmt.Errorf("bucket name is required") + } + if err := config.ValidateBucketName(name); err != nil { + return err + } _, err := cli.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: awsv2.String(name)}) if err == nil { return nil @@ -54,17 +85,28 @@ func EnsureBucket(ctx context.Context, cli *s3.Client, name string) error { return CreateBucket(ctx, cli, name) } -// CreateBucket tolerates a concurrent creation by the same owner. +// CreateBucket creates a bucket without a preliminary HEAD. func CreateBucket(ctx context.Context, cli *s3.Client, name string) error { + if err := config.ValidateBucketName(name); err != nil { + return err + } input := &s3.CreateBucketInput{Bucket: awsv2.String(name)} if region := cli.Options().Region; region != "" && region != "us-east-1" { - input.CreateBucketConfiguration = &types.CreateBucketConfiguration{ - LocationConstraint: types.BucketLocationConstraint(region), + input.CreateBucketConfiguration = &s3types.CreateBucketConfiguration{ + LocationConstraint: s3types.BucketLocationConstraint(region), } } _, err := cli.CreateBucket(ctx, input) - if err != nil && !s3client.IsAlreadyOwned(err) { - return fmt.Errorf("create bucket %q on target (need s3:CreateBucket): %w", name, err) + if err != nil { + var apiErr smithy.APIError + if !errors.As(err, &apiErr) || apiErr.ErrorCode() != "BucketAlreadyOwnedByYou" { + return fmt.Errorf("create bucket %q on target (need s3:CreateBucket): %w", name, err) + } + // A concurrent creator in our account can legitimately win. Recheck + // access instead of treating a globally occupied name as success. + if err := HeadBucket(ctx, cli, name); err != nil { + return err + } } return nil } diff --git a/internal/cluster/objects.go b/internal/cluster/objects.go index 9876269..cec1e9a 100644 --- a/internal/cluster/objects.go +++ b/internal/cluster/objects.go @@ -14,6 +14,7 @@ import ( // encoding so even keys containing characters forbidden in XML can be listed. func WalkObjects(ctx context.Context, cli *s3.Client, bucket string, visit func([]types.Object) error) error { input := &s3.ListObjectsV2Input{Bucket: aws.String(bucket), EncodingType: types.EncodingTypeUrl} + seenTokens := make(map[string]struct{}) for { page, err := cli.ListObjectsV2(ctx, input) if err != nil { @@ -22,6 +23,9 @@ func WalkObjects(ctx context.Context, cli *s3.Client, bucket string, visit func( if name := aws.ToString(page.Name); name != "" && name != bucket { return fmt.Errorf("list page bucket mismatch: requested %q, server returned %q", bucket, name) } + if page.IsTruncated == nil { + return fmt.Errorf("incomplete listing for bucket %q: missing IsTruncated", bucket) + } for i := range page.Contents { obj := &page.Contents[i] if aws.ToString(obj.Key) == "" || obj.Size == nil || *obj.Size < 0 { @@ -44,9 +48,10 @@ func WalkObjects(ctx context.Context, cli *s3.Client, bucket string, visit func( return nil } next := aws.ToString(page.NextContinuationToken) - if next == "" || next == aws.ToString(input.ContinuationToken) { + 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/cluster/objects_test.go b/internal/cluster/objects_test.go index 5775eeb..1cf9238 100644 --- a/internal/cluster/objects_test.go +++ b/internal/cluster/objects_test.go @@ -37,7 +37,7 @@ func TestWalkObjectsDecodesKeysOnceAndPreservesOpaqueTokens(t *testing.T) { page = "urltrue" + token + "dir%2F%25%32%46%2B+a%20b%09%010" case token: // Older compatible implementations can omit EncodingType and return plain keys. - page = "literal%2F1" + page = "falseliteral%2F1" default: t.Errorf("unexpected token %q", query.Get("continuation-token")) } @@ -74,3 +74,24 @@ func TestWalkObjectsRejectsBrokenPagination(t *testing.T) { } } } + +func TestWalkObjectsRejectsAlternatingTokens(t *testing.T) { + requests := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + if requests > 3 { + w.WriteHeader(http.StatusBadRequest) + return + } + next := "a" + if r.URL.Query().Get("continuation-token") == "a" { + next = "b" + } + fmt.Fprintf(w, `true%s`, next) + })) + defer server.Close() + err := WalkObjects(context.Background(), clientFor(t, server.URL), "photos", func([]types.Object) error { return nil }) + if err == nil || !strings.Contains(err.Error(), "continuation token") || requests != 3 { + t.Fatalf("requests=%d err=%v", requests, err) + } +} diff --git a/internal/config/audit_test.go b/internal/config/audit_test.go new file mode 100644 index 0000000..a16ebf9 --- /dev/null +++ b/internal/config/audit_test.go @@ -0,0 +1,28 @@ +package config + +import ( + "os" + "path/filepath" + "testing" +) + +// Unknown configuration keys must not silently expand a requested single-bucket +// run to every bucket. This is an operator typo, not a request for all buckets. +func TestAuditRejectMisspelledBucketSetting(t *testing.T) { + t.Setenv("BUCKET", "") + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte("buckte: production-photos\n"), 0600); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if err == nil { + t.Fatalf("unknown bucket field accepted; all-buckets mode=%t", cfg.AllBuckets()) + } +} + +func TestAuditJobBufferCannotOverflow(t *testing.T) { + maxInt := int(^uint(0) >> 1) + if n := JobBuffer(maxInt); n < 1 || n > 2048 { + t.Fatalf("workers=%d produced invalid channel capacity=%d", maxInt, n) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 32986b4..052caa8 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1,7 +1,9 @@ package config import ( + "bytes" "fmt" + "io" "net/url" "os" "path/filepath" @@ -19,13 +21,16 @@ const ( // DefaultMultipartConcurrency is the per-object part parallelism when // multipart_concurrency is omitted or 0. DefaultMultipartConcurrency = 4 + // DefaultSpoolMaxBytes bounds temporary copy data for one migration. + DefaultSpoolMaxBytes int64 = 1 << 30 ) type Endpoint struct { - Endpoint string `yaml:"endpoint"` - AccessKey string `yaml:"access_key"` - SecretKey string `yaml:"secret_key"` - Region string `yaml:"region"` + Endpoint string `yaml:"endpoint"` + AccessKey string `yaml:"access_key"` + SecretKey string `yaml:"secret_key"` + Region string `yaml:"region"` + SessionToken string `yaml:"session_token"` } type Config struct { @@ -33,10 +38,14 @@ type Config struct { New Endpoint `yaml:"new"` // Bucket is optional. Empty means "every bucket on the source". - Bucket string `yaml:"bucket"` - DBPath string `yaml:"db_path"` - ConflictLog string `yaml:"conflict_log"` - SpoolDir string `yaml:"spool_dir"` + Bucket string `yaml:"bucket"` + DBPath string `yaml:"db_path"` + ConflictLog string `yaml:"conflict_log"` + SpoolDir string `yaml:"spool_dir"` + SpoolMaxBytes int64 `yaml:"spool_max_bytes"` + // SourceFrozen is an operator assertion, not a remote locking mechanism. + // Source writes and deletes must remain frozen through final verification. + SourceFrozen bool `yaml:"source_frozen"` Workers int `yaml:"workers"` MultipartThreshold int64 `yaml:"multipart_threshold"` @@ -59,8 +68,8 @@ type Config struct { // per-object adjustment that keeps an upload under 10 000 parts only grows // an already-valid part size, so it is not a reason to silently raise a // value the operator chose. -const MinMultipartPartSize int64 = 5 << 20 -const MaxMultipartPartSize int64 = 5 << 30 +const MinMultipartPartSize int64 = 5 * 1024 * 1024 +const MaxMultipartPartSize int64 = 5 * 1024 * 1024 * 1024 // Load parses YAML, applies env overrides and defaults. It does not require // every field: each command validates what it needs. @@ -70,9 +79,15 @@ func Load(path string) (*Config, error) { return nil, fmt.Errorf("read config %s: copy config.example.yaml first: %w", path, err) } c := &Config{} - if err := yaml.Unmarshal(b, c); err != nil { + dec := yaml.NewDecoder(bytes.NewReader(b)) + dec.KnownFields(true) + if err := dec.Decode(c); err != nil { return nil, fmt.Errorf("parse config: %w", err) } + var extra any + if err := dec.Decode(&extra); err != io.EOF { + return nil, fmt.Errorf("config must contain exactly one YAML document") + } if err := c.applyEnv(); err != nil { return nil, err } @@ -98,10 +113,19 @@ func (c *Config) applyEnv() error { c.Old.AccessKey = envOr(c.Old.AccessKey, "OLD_AK") c.Old.SecretKey = envOr(c.Old.SecretKey, "OLD_SK") c.Old.Region = envOr(c.Old.Region, "OLD_REGION") + c.Old.SessionToken = envOr(c.Old.SessionToken, "OLD_SESSION_TOKEN") c.New.Endpoint = envOr(c.New.Endpoint, "NEW_ENDPOINT") c.New.AccessKey = envOr(c.New.AccessKey, "NEW_AK") c.New.SecretKey = envOr(c.New.SecretKey, "NEW_SK") c.New.Region = envOr(c.New.Region, "NEW_REGION") + c.New.SessionToken = envOr(c.New.SessionToken, "NEW_SESSION_TOKEN") + if raw, set := os.LookupEnv("SOURCE_FROZEN"); set { + v, err := strconv.ParseBool(strings.TrimSpace(raw)) + if err != nil { + return fmt.Errorf("SOURCE_FROZEN must be true or false") + } + c.SourceFrozen = v + } sharedRegion := os.Getenv("REGION") if sharedRegion != "" { if c.Old.Region == "" { @@ -191,6 +215,9 @@ func (c *Config) applyDefaults() { c.MultipartConcurrency = DefaultMultipartConcurrency } // RateLimit 0 (omitted) stays 0: unlimited. Do not invent a default cap. + if c.SpoolMaxBytes == 0 { + c.SpoolMaxBytes = DefaultSpoolMaxBytes + } if c.SpoolDir == "" { c.SpoolDir = filepath.Dir(c.DBPath) } @@ -219,7 +246,7 @@ func (c *Config) validateMultipartPartSize() error { return fmt.Errorf("multipart_part_size must be >= %d (5 MiB): non-final S3 parts smaller than that are rejected with EntityTooSmall (got %d)", MinMultipartPartSize, c.MultipartPartSize) } if c.MultipartPartSize > MaxMultipartPartSize { - return fmt.Errorf("multipart_part_size must be <= %d (5 GiB), got %d", MaxMultipartPartSize, c.MultipartPartSize) + return fmt.Errorf("multipart_part_size must be <= 5 GiB") } return nil } @@ -231,11 +258,9 @@ func (c *Config) ValidateNames() error { return ValidateBucketName(c.Bucket) } -// ValidateBucketName also protects per-bucket filenames derived from a remote listing. -func ValidateBucketName(bucket string) error { - if bucket == "" || bucket == "." || bucket == ".." || strings.ContainsAny(bucket, `/\:<>|"?*`) || - strings.IndexFunc(bucket, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) >= 0 { - return fmt.Errorf("invalid bucket name %q", bucket) +func ValidateBucketName(name string) error { + if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\:<>|"?*`) || strings.ContainsFunc(name, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) }) { + return fmt.Errorf("bucket %q must not contain whitespace, control characters or path separators", name) } return nil } @@ -245,16 +270,6 @@ func (c *Config) AllBuckets() bool { return c.Bucket == "" } -func validateEndpoint(label, endpoint string) error { - u, err := url.Parse(endpoint) - if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || - u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" { - // Avoid echoing URLs that may include embedded credentials or signatures. - return fmt.Errorf("%s.endpoint must be an HTTP(S) URL with a host and no credentials, query or fragment", label) - } - return nil -} - // ValidateSource is required by list / scan. func (c *Config) ValidateSource() error { if c.Old.Endpoint == "" { @@ -263,7 +278,7 @@ func (c *Config) ValidateSource() error { if c.Old.AccessKey == "" || c.Old.SecretKey == "" { return fmt.Errorf("old.access_key and old.secret_key are required") } - return validateEndpoint("old", c.Old.Endpoint) + return validateEndpoint(c.Old.Endpoint) } // ValidatePair is required by run / migrate / diff. @@ -277,18 +292,52 @@ func (c *Config) ValidatePair() error { if c.New.AccessKey == "" || c.New.SecretKey == "" { return fmt.Errorf("new.access_key and new.secret_key are required") } - return validateEndpoint("new", c.New.Endpoint) + if err := validateEndpoint(c.New.Endpoint); err != nil { + return err + } + if strings.EqualFold(c.Old.Endpoint, c.New.Endpoint) { + return fmt.Errorf("source and target endpoints must be different") + } + return nil +} + +func validateEndpoint(endpoint string) error { + u, err := url.Parse(endpoint) + if err != nil || u.Hostname() == "" || (u.Scheme != "http" && u.Scheme != "https") { + return fmt.Errorf("endpoint must be an absolute http or https URL") + } + if u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" { + return fmt.Errorf("endpoint must not contain credentials, a query or a fragment") + } + return nil +} + +// ValidateMigration validates the conditions for commands that write objects. +func (c *Config) ValidateMigration() error { + if err := c.ValidatePair(); err != nil { + return err + } + if !c.SourceFrozen { + return fmt.Errorf("migration requires frozen source writes and deletes; freeze the source, then set source_frozen: true or --source-frozen (this flag does not freeze S3)") + } + return nil } // ValidateConcurrency checks the knobs that size the worker pool and the // per-object part semaphore. Call it after defaults and again after CLI overrides. func (c *Config) ValidateConcurrency() error { + if c.SpoolMaxBytes < 0 { + return fmt.Errorf("spool_max_bytes must be positive") + } if c.Workers < 1 { return fmt.Errorf("workers must be >= 1, got %d", c.Workers) } if c.MultipartConcurrency < 1 { return fmt.Errorf("multipart_concurrency must be >= 1, got %d", c.MultipartConcurrency) } + if c.Workers > 1024 || c.MultipartConcurrency > 64 || c.Workers > 4096/c.MultipartConcurrency { + return fmt.Errorf("concurrency exceeds resource limits: workers <= 1024, multipart_concurrency <= 64, product <= 4096") + } if c.MultipartThreshold < 1 { return fmt.Errorf("multipart_threshold must be >= 1, got %d", c.MultipartThreshold) } @@ -376,12 +425,12 @@ func (c *Config) ApplyBucketFlag(flag string) { } // DBPathFor returns the state DB for one bucket. Single-bucket mode uses -// db_path verbatim; all-buckets mode derives migration-.db next to it. +// db_path verbatim; all-buckets mode preserves the configured job basename. func (c *Config) DBPathFor(bucket string) string { if !c.AllBuckets() { return c.DBPath } - return sibling(c.DBPath, "migration-"+bucket+".db") + return bucketPath(c.DBPath, bucket, ".db") } // ConflictLogFor follows the same rule as DBPathFor. @@ -389,7 +438,16 @@ func (c *Config) ConflictLogFor(bucket string) string { if !c.AllBuckets() { return c.ConflictLog } - return sibling(c.ConflictLog, "conflict-"+bucket+".log") + return bucketPath(c.ConflictLog, bucket, ".log") +} + +func bucketPath(base, bucket, fallbackExt string) string { + ext := filepath.Ext(base) + stem := strings.TrimSuffix(filepath.Base(base), ext) + if ext == "" { + ext = fallbackExt + } + return sibling(base, stem+"-"+bucket+ext) } func sibling(base, name string) string { diff --git a/internal/config/safety_test.go b/internal/config/safety_test.go new file mode 100644 index 0000000..4946ed1 --- /dev/null +++ b/internal/config/safety_test.go @@ -0,0 +1,55 @@ +package config + +import ( + "os" + "path/filepath" + "testing" +) + +func TestMigrationRequiresExplicitFrozenSource(t *testing.T) { + c := &Config{Old: Endpoint{Endpoint: "https://source.example", AccessKey: "a", SecretKey: "b"}, New: Endpoint{Endpoint: "https://target.example", AccessKey: "a", SecretKey: "b"}} + if err := c.ValidateMigration(); err == nil { + t.Fatal("unfrozen migration accepted") + } + c.SourceFrozen = true + if err := c.ValidateMigration(); err != nil { + t.Fatal(err) + } + c.New.Endpoint = c.Old.Endpoint + if err := c.ValidateMigration(); err == nil { + t.Fatal("same cluster accepted") + } +} + +func TestConfigRejectsAdditionalDocument(t *testing.T) { + p := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(p, []byte("bucket: first\n---\nbucket: second\n"), 0600); err != nil { + t.Fatal(err) + } + if _, err := Load(p); err == nil { + t.Fatal("additional YAML document accepted") + } +} + +func TestJobPathsPreserveDistinctBasenames(t *testing.T) { + a, b := Config{DBPath: "/state/job-a.db"}, Config{DBPath: "/state/job-b.db"} + if a.DBPathFor("photos") == b.DBPathFor("photos") { + t.Fatal("distinct jobs share state") + } + if a.DBPathFor("photos") != "/state/job-a-photos.db" { + t.Fatal(a.DBPathFor("photos")) + } +} + +func TestUnsafeBucketAndEndpointRejected(t *testing.T) { + for _, name := range []string{"..", "a\\b", "a\nb", "a/b", "a\x00b"} { + if err := ValidateBucketName(name); err == nil { + t.Fatalf("accepted bucket %q", name) + } + } + for _, endpoint := range []string{"file:///tmp/data", "https://user:password@host", "https://host?secret=key", "host:9000"} { + if err := validateEndpoint(endpoint); err == nil { + t.Fatalf("accepted unsafe endpoint") + } + } +} diff --git a/internal/differ/audit_test.go b/internal/differ/audit_test.go new file mode 100644 index 0000000..7cb1c51 --- /dev/null +++ b/internal/differ/audit_test.go @@ -0,0 +1,408 @@ +package differ + +import ( + "bytes" + "context" + "crypto/md5" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/service/s3/types" + "github.com/rustfs/migration/internal/fakes3" +) + +// A terminal HEAD failure must stop the producer as well as the worker. +// Otherwise a real CLI invocation, whose context has no deadline, hangs forever. +func TestAuditDiffReturnsOnHeadFailure(t *testing.T) { + objects := map[string][]byte{} + for i := 0; i < 10; i++ { + objects[fmt.Sprintf("key-%02d", i)] = []byte("body") + } + source := fakes3.NewWithObjects(t, "bucket", objects, time.Now()) + defer source.Close() + headStarted := make(chan struct{}, 1) + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/bucket" || r.URL.Path == "/bucket/" { + w.WriteHeader(http.StatusOK) + return + } + select { + case headStarted <- struct{}{}: + default: + } + w.WriteHeader(http.StatusForbidden) + })) + defer target.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + oldCli := testClient(t, ctx, source.URL) + newCli := testClient(t, ctx, target.URL) + done := make(chan error, 1) + go func() { + _, err := Run(ctx, oldCli, newCli, "bucket", Options{Workers: 1}) + done <- err + }() + select { + case <-headStarted: + case <-time.After(5 * time.Second): + t.Fatal("fixture did not reach target HEAD") + } + select { + case err := <-done: + if err == nil { + t.Fatal("HEAD 403 must be returned as an error") + } + case <-time.After(time.Second): + cancel() // Release the blocked producer; do not leak the audit goroutine. + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("diff failed to stop even after cancellation") + } + t.Fatal("diff remained blocked after terminal HEAD 403; only external cancellation released it") + } +} + +// A multipart ETag is not comparable to a simple MD5. It also is not evidence +// that two equal-length objects match. The verifier must report unverified or +// compare full-object checksums instead of counting this object as OK. +func TestAuditDiffDoesNotCertifySameSizeCorruption(t *testing.T) { + const partSize = 5 * 1024 * 1024 + sourceBody := bytes.Repeat([]byte("a"), partSize+8) + corruptBody := append([]byte(nil), sourceBody...) + corruptBody[0] = 'b' + first, last := md5.Sum(corruptBody[:partSize]), md5.Sum(corruptBody[partSize:]) + combined := append(first[:], last[:]...) + corruptETag := fmt.Sprintf(`"%x-2"`, md5.Sum(combined)) + source := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"key": sourceBody}, time.Now()) + defer source.Close() + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", fmt.Sprint(len(corruptBody))) + w.Header().Set("ETag", corruptETag) + w.Header().Set("Content-Type", "application/test") + w.Header().Set("X-Amz-Meta-Origin", "old") + if r.Method != http.MethodHead { + _, _ = w.Write(corruptBody) + } + })) + defer target.Close() + ctx := context.Background() + res, err := Run(ctx, testClient(t, ctx, source.URL), testClient(t, ctx, target.URL), "bucket", Options{Workers: 1}) + if err != nil { + t.Fatal(err) + } + if res.OK != 0 || res.ContentMismatch != 1 || !res.HasGaps() { + t.Fatalf("expected SHA256 content mismatch: %+v", res) + } +} + +// Bucket existence is part of successful migration even if there are no keys. +func TestAuditDiffDetectsMissingEmptyBucket(t *testing.T) { + source := fakes3.New(t) + defer source.Close() + source.Put("empty-bucket", "seed", []byte("seed"), time.Now(), fakes3.Metadata{}) + source.DeleteKey("empty-bucket", "seed") + target := fakes3.New(t) + defer target.Close() + ctx := context.Background() + res, err := Run(ctx, testClient(t, ctx, source.URL), testClient(t, ctx, target.URL), "empty-bucket", Options{Workers: 1}) + if err == nil && !res.HasGaps() { + t.Fatalf("missing target bucket accepted as clean: %+v", res) + } +} + +func TestDiffAcceptsSameContentWithDifferentOpaqueETags(t *testing.T) { + body := []byte("identical bytes despite different encryption or part layout") + source := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"key": body}, time.Now()) + defer source.Close() + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead && r.URL.Path == "/bucket" { + return + } + w.Header().Set("Content-Length", fmt.Sprint(len(body))) + w.Header().Set("ETag", `"opaque-encrypted-token"`) + w.Header().Set("Content-Type", "application/test") + w.Header().Set("X-Amz-Meta-Origin", "old") + if r.Method == http.MethodGet { + if r.Header.Get("If-Match") != `"opaque-encrypted-token"` { + http.Error(w, "missing representation condition", http.StatusPreconditionFailed) + return + } + _, _ = w.Write(body) + } + })) + defer target.Close() + ctx := context.Background() + res, err := Run(ctx, testClient(t, ctx, source.URL), testClient(t, ctx, target.URL), "bucket", Options{Workers: 1}) + if err != nil || res.OK != 1 || res.HasGaps() { + t.Fatalf("opaque ETags must not cause a false conflict: result=%+v err=%v", res, err) + } +} + +type failingWriter struct{ err error } + +func (w failingWriter) Write(p []byte) (int, error) { return 0, w.err } + +func TestDiffPropagatesReportWriteFailure(t *testing.T) { + source := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"key": []byte("body")}, time.Now()) + defer source.Close() + target := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"key": []byte("body")}, time.Now()) + defer target.Close() + ctx := context.Background() + want := errors.New("report storage full") + _, err := Run(ctx, testClient(t, ctx, source.URL), testClient(t, ctx, target.URL), "bucket", Options{Workers: 1, Writer: failingWriter{want}}) + if !errors.Is(err, want) { + t.Fatalf("report error lost: %v", err) + } +} + +func TestConcurrentDiffUsesSeparateInventoryFiles(t *testing.T) { + objects := map[string][]byte{"key": []byte("body")} + source := fakes3.NewWithObjects(t, "bucket", objects, time.Now()) + t.Cleanup(source.Close) + target := fakes3.NewWithObjects(t, "bucket", objects, time.Now()) + t.Cleanup(target.Close) + for i := 0; i < 3; i++ { + t.Run(fmt.Sprint(i), func(t *testing.T) { + t.Parallel() + ctx := context.Background() + res, err := Run(ctx, testClient(t, ctx, source.URL), testClient(t, ctx, target.URL), "bucket", Options{Workers: 1, ReportExtra: true}) + if err != nil || res.OK != 1 || res.HasGaps() { + t.Fatalf("concurrent diff result=%+v err=%v", res, err) + } + }) + } +} + +func TestDiffDecodesURLKeysWithoutTurningPlusIntoSpace(t *testing.T) { + key := "dir/plus+ percent% 中文\x01" + body := []byte("body") + makeEndpoint := func(extra bool) *httptest.Server { + objects := map[string][]byte{key: body} + if extra { + objects["extra+%\x02"] = body + } + backend := fakes3.NewWithObjects(t, "bucket", objects, time.Now()) + t.Cleanup(backend.Close) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && r.URL.Query().Get("list-type") == "2" { + if r.URL.Query().Get("encoding-type") != "url" { + http.Error(w, "listing must request URL encoding", http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "application/xml") + fmt.Fprint(w, `bucketurlfalse`) + for k := range objects { + fmt.Fprintf(w, `%s%d"%x"`, url.QueryEscape(k), len(body), md5.Sum(body)) + } + fmt.Fprint(w, ``) + return + } + backend.Config.Handler.ServeHTTP(w, r) + })) + t.Cleanup(server.Close) + return server + } + source, target := makeEndpoint(false), makeEndpoint(true) + ctx := context.Background() + res, err := Run(ctx, testClient(t, ctx, source.URL), testClient(t, ctx, target.URL), "bucket", Options{Workers: 1, ReportExtra: true}) + if err != nil || res.OK != 1 || res.Extra != 1 || res.HasGaps() { + t.Fatalf("encoded keys result=%+v err=%v", res, err) + } + if len(res.Issues) != 1 || res.Issues[0].Key != "extra+%\x02" { + t.Fatalf("extra key was not decoded faithfully: %+v", res.Issues) + } +} + +func TestDiffRejectsIncompletePagination(t *testing.T) { + for _, token := range []string{"", "repeated"} { + t.Run("token="+token, func(t *testing.T) { + source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + return + } + w.Header().Set("Content-Type", "application/xml") + fmt.Fprintf(w, `buckettrue%s`, token) + })) + defer source.Close() + target := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"seed": []byte("body")}, time.Now()) + defer target.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, err := Run(ctx, testClient(t, ctx, source.URL), testClient(t, ctx, target.URL), "bucket", Options{Workers: 1}) + if err == nil || !strings.Contains(err.Error(), "continuation token") { + t.Fatalf("invalid pagination was not rejected: %v", err) + } + }) + } +} + +func TestDiffRejectsMissingCompletionFlag(t *testing.T) { + for _, extra := range []bool{false, true} { + t.Run(fmt.Sprintf("target-extra=%t", extra), func(t *testing.T) { + broken := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + return + } + w.Header().Set("Content-Type", "application/xml") + fmt.Fprint(w, `bucket`) + })) + defer broken.Close() + good := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"seed": []byte("body")}, time.Now()) + defer good.Close() + good.DeleteKey("bucket", "seed") + source, target := broken.URL, good.URL + if extra { + source, target = good.URL, broken.URL + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, err := Run(ctx, testClient(t, ctx, source), testClient(t, ctx, target), "bucket", Options{Workers: 1, ReportExtra: extra}) + if err == nil || !strings.Contains(err.Error(), "IsTruncated") { + t.Fatalf("missing completion flag accepted: %v", err) + } + }) + } +} + +func TestDiffReportsPreservedMetadataMismatch(t *testing.T) { + body := []byte("same body") + source := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"key": body}, time.Now()) + defer source.Close() + target := fakes3.New(t) + defer target.Close() + target.Put("bucket", "key", body, time.Now(), fakes3.Metadata{ContentType: "application/test", Metadata: map[string]string{"origin": "different"}}) + ctx := context.Background() + res, err := Run(ctx, testClient(t, ctx, source.URL), testClient(t, ctx, target.URL), "bucket", Options{Workers: 1}) + if err != nil || res.MetadataMismatch != 1 || !res.HasGaps() || res.OK != 0 { + t.Fatalf("metadata mismatch missed: result=%+v err=%v", res, err) + } +} + +func TestDiffRejectsSourceChangedSinceListing(t *testing.T) { + body := []byte("body") + source := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"key": body}, time.Now()) + defer source.Close() + sourceProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead && r.URL.Path == "/bucket/key" { + if r.Header.Get("If-Match") != fmt.Sprintf(`"%x"`, md5.Sum(body)) { + http.Error(w, "HEAD must bind the listing ETag", http.StatusBadRequest) + return + } + w.Header().Set("Content-Length", fmt.Sprint(len(body))) + w.Header().Set("ETag", `"changed-since-list"`) + return + } + source.Config.Handler.ServeHTTP(w, r) + })) + defer sourceProxy.Close() + target := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"key": body}, time.Now()) + defer target.Close() + ctx := context.Background() + _, err := Run(ctx, testClient(t, ctx, sourceProxy.URL), testClient(t, ctx, target.URL), "bucket", Options{Workers: 1}) + if err == nil || !strings.Contains(err.Error(), "changed after listing") { + t.Fatalf("changed source must fail verification: %v", err) + } +} + +func TestDiffRejectsAlternatingContinuationTokens(t *testing.T) { + for _, targetExtra := range []bool{false, true} { + t.Run(fmt.Sprintf("target-extra=%t", targetExtra), func(t *testing.T) { + var requests atomic.Int32 + broken := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + return + } + n := requests.Add(1) + w.Header().Set("Content-Type", "application/xml") + if n > 3 { + w.WriteHeader(http.StatusBadRequest) + return + } + next := "a" + if r.URL.Query().Get("continuation-token") == "a" { + next = "b" + } + fmt.Fprintf(w, `buckettrue%s`, next) + })) + defer broken.Close() + good := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"seed": []byte("body")}, time.Now()) + defer good.Close() + good.DeleteKey("bucket", "seed") + source, target := broken.URL, good.URL + if targetExtra { + source, target = good.URL, broken.URL + } + ctx := context.Background() + _, err := Run(ctx, testClient(t, ctx, source), testClient(t, ctx, target), "bucket", Options{Workers: 1, ReportExtra: targetExtra}) + if err == nil || !strings.Contains(err.Error(), "continuation token") || requests.Load() != 3 { + t.Fatalf("requests=%d err=%v", requests.Load(), err) + } + }) + } +} + +func TestDiffStreamsAllIssuesAndPropagatesWriterErrors(t *testing.T) { + objects := map[string][]byte{} + for i := 0; i < 75; i++ { + objects[fmt.Sprintf("key-%03d", i)] = []byte("data") + } + objects["special\n雪"] = []byte("data") + src := fakes3.NewWithObjects(t, "bucket", objects, time.Now()) + defer src.Close() + dst := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"extra": []byte("target")}, time.Now()) + defer dst.Close() + ctx := context.Background() + oldCli, newCli := testClient(t, ctx, src.URL), testClient(t, ctx, dst.URL) + var jsonl, summary bytes.Buffer + result, err := Run(ctx, oldCli, newCli, "bucket", Options{Workers: 8, ReportExtra: true, Writer: &summary, IssuesJSONL: &jsonl}) + if err != nil { + t.Fatal(err) + } + if result.Missing != 76 || result.Extra != 1 || len(result.Issues) != 50 { + t.Fatalf("result: %+v", result) + } + decoder := json.NewDecoder(&jsonl) + entries := map[string]string{} + for decoder.More() { + var entry struct{ Bucket, Key, Kind, Detail string } + if err := decoder.Decode(&entry); err != nil { + t.Fatal(err) + } + if entry.Bucket != "bucket" || entry.Detail == "" { + t.Fatalf("entry: %+v", entry) + } + if _, ok := entries[entry.Key]; ok { + t.Fatalf("duplicate key %q", entry.Key) + } + entries[entry.Key] = entry.Kind + } + if len(entries) != 77 || entries["special\n雪"] != "missing" || entries["extra"] != "extra" || !strings.Contains(summary.String(), "27 more issues") { + t.Fatalf("entries=%d summary=%s", len(entries), summary.String()) + } + _, err = Run(ctx, oldCli, newCli, "bucket", Options{Workers: 8, IssuesJSONL: errorWriter{}}) + if err == nil || !strings.Contains(err.Error(), "write diff JSONL") { + t.Fatalf("writer error lost: %v", err) + } +} + +type errorWriter struct{} + +func (errorWriter) Write([]byte) (int, error) { return 0, errors.New("injected disk failure") } + +func TestDecodeKeyHandlesBothSpaceEncodings(t *testing.T) { + for _, encoded := range []string{"space+and%2Bplus%25", "space%20and%2Bplus%25"} { + got, err := decodeKey(encoded, types.EncodingTypeUrl) + if err != nil || got != "space and+plus%" { + t.Fatalf("%q decoded to %q: %v", encoded, got, err) + } + } +} diff --git a/internal/differ/differ.go b/internal/differ/differ.go index aa9bdd2..688dc37 100644 --- a/internal/differ/differ.go +++ b/internal/differ/differ.go @@ -1,14 +1,16 @@ package differ import ( + "bytes" "context" "database/sql" + "encoding/json" "fmt" "io" - "strconv" + "net/url" + "os" "strings" "sync" - "unicode" awsv2 "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" @@ -24,29 +26,32 @@ const maxPrinted = 50 type Issue struct { Key string - Kind string // missing | size | etag | extra + Kind string // missing | size | content | metadata | extra Detail string } type Result struct { - Bucket string - OK int64 - SizeOnly int64 // subset of OK for which ETags could not confirm a match - Missing int64 - SizeMismatch int64 - ETagMismatch int64 - Extra int64 - Issues []Issue + Bucket string + OK int64 + Missing int64 + SizeMismatch int64 + ETagMismatch int64 // Retained for compatibility; ETags alone do not prove different content. + ContentMismatch int64 + MetadataMismatch int64 + Extra int64 + Issues []Issue } func (r Result) HasGaps() bool { - return r.Missing > 0 || r.SizeMismatch > 0 || r.ETagMismatch > 0 + return r.Missing > 0 || r.SizeMismatch > 0 || r.ETagMismatch > 0 || r.ContentMismatch > 0 || r.MetadataMismatch > 0 } type Options struct { Workers int ReportExtra bool Writer io.Writer + // IssuesJSONL receives every issue, one JSON object per line. The caller owns it. + IssuesJSONL io.Writer } type listed struct { @@ -55,50 +60,67 @@ type listed struct { etag string } -// Run lists the source bucket and HEADs each key on the target. -// Extra-on-target keys are reported when ReportExtra is true. +// Run compares all current source objects with the target. Equal sizes are +// verified by reading both bodies with If-Match and comparing SHA-256; ETags +// from different encryption schemes or multipart layouts are not comparable. +// Source and target must remain quiescent for the duration of final acceptance: +// individual conditional reads cannot provide an atomic cross-cluster snapshot. func Run(ctx context.Context, oldCli, newCli *s3.Client, bucket string, opt Options) (Result, error) { if opt.Workers <= 0 { - opt.Workers = 16 + opt.Workers = config.DefaultWorkers } if opt.Writer == nil { opt.Writer = io.Discard } + res := Result{Bucket: bucket} if err := cluster.HeadBucket(ctx, oldCli, bucket); err != nil { - return Result{}, err + return res, err + } + if _, err := newCli.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: awsv2.String(bucket)}); err != nil { + return res, fmt.Errorf("head target bucket %q: %w", bucket, err) } - ctx, cancel := context.WithCancelCause(ctx) - defer cancel(nil) - - // Only --extra needs a source index. SQLite gives each empty filename - // its own disk-backed temporary database and removes it on close. - var index *sql.Tx - var insert *sql.Stmt - if opt.ReportExtra { - db, err := sql.Open("sqlite", "") - if err != nil { - return Result{}, err - } - defer db.Close() - index, err = db.BeginTx(ctx, nil) - if err != nil { - return Result{}, err - } - defer index.Rollback() - if _, err := index.Exec(`CREATE TABLE src (key TEXT PRIMARY KEY) WITHOUT ROWID`); err != nil { - return Result{}, err - } - insert, err = index.Prepare(`INSERT OR IGNORE INTO src(key) VALUES(?)`) - if err != nil { - return Result{}, err - } - defer insert.Close() + 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.Close(); err != nil { + return res, err + } + db, err := sql.Open("sqlite", tmp+"?_pragma=journal_mode(WAL)&_pragma=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 } + insert, err := db.PrepareContext(ctx, `INSERT OR IGNORE INTO src(key, size, etag) VALUES(?,?,?)`) + if err != nil { + return res, err + } + defer insert.Close() - res := Result{Bucket: bucket} + ctx, cancel := context.WithCancel(ctx) + defer cancel() jobs := make(chan listed, config.JobBuffer(opt.Workers)) var mu sync.Mutex + var firstErr error + fail := func(err error) { + mu.Lock() + if firstErr == nil { + firstErr = err + } + mu.Unlock() + cancel() + } var wg sync.WaitGroup for i := 0; i < opt.Workers; i++ { wg.Add(1) @@ -108,98 +130,179 @@ func Run(ctx context.Context, oldCli, newCli *s3.Client, bucket string, opt Opti if ctx.Err() != nil { return } - head, err := newCli.HeadObject(ctx, &s3.HeadObjectInput{ - Bucket: awsv2.String(bucket), - Key: awsv2.String(item.key), - }) - switch { - case err == nil: - if head.ContentLength == nil { - cancel(fmt.Errorf("head target %q: missing Content-Length", item.key)) + head, err := newCli.HeadObject(ctx, &s3.HeadObjectInput{Bucket: awsv2.String(bucket), Key: awsv2.String(item.key)}) + if err != nil { + if s3client.IsNotFound(err) { + if err := record(&mu, &res, opt.IssuesJSONL, Issue{Key: item.key, Kind: "missing", Detail: "not on target"}); err != nil { + fail(err) + return + } + continue + } + fail(fmt.Errorf("head target %q: %w", item.key, err)) + return + } + if head.ContentLength == nil || *head.ContentLength != item.size { + if err := record(&mu, &res, opt.IssuesJSONL, Issue{Key: item.key, Kind: "size", Detail: fmt.Sprintf("src=%d dst=%d", item.size, deref(head.ContentLength))}); err != nil { + fail(err) return } - got := *head.ContentLength - dstETag := normalizeETag(awsv2.ToString(head.ETag)) - srcETag := normalizeETag(item.etag) - switch { - case got != item.size: - record(&mu, &res, Issue{Key: item.key, Kind: "size", Detail: fmt.Sprintf("src=%d dst=%d", item.size, got)}) - case srcETag != "" && dstETag != "" && !isMultipart(srcETag) && !isMultipart(dstETag) && srcETag != dstETag: - record(&mu, &res, Issue{Key: item.key, Kind: "etag", Detail: fmt.Sprintf("src=%s dst=%s", srcETag, dstETag)}) - default: - mu.Lock() - res.OK++ - if srcETag == "" || dstETag == "" || srcETag != dstETag { - res.SizeOnly++ - } - mu.Unlock() + continue + } + sourceHead, err := oldCli.HeadObject(ctx, &s3.HeadObjectInput{ + Bucket: awsv2.String(bucket), Key: awsv2.String(item.key), IfMatch: awsv2.String(item.etag), + }) + if err != nil { + fail(fmt.Errorf("head source %q: %w", item.key, err)) + return + } + if sourceHead.ContentLength == nil || *sourceHead.ContentLength != item.size || + strings.Trim(awsv2.ToString(sourceHead.ETag), `"`) != strings.Trim(item.etag, `"`) { + fail(fmt.Errorf("source %q changed after listing", item.key)) + return + } + if !s3client.MetadataEqual(sourceHead, head) { + if err := record(&mu, &res, opt.IssuesJSONL, Issue{Key: item.key, Kind: "metadata", Detail: "preserved headers or user metadata differ"}); err != nil { + fail(err) + return } - case s3client.IsNotFound(err): - record(&mu, &res, Issue{Key: item.key, Kind: "missing", Detail: "not on target"}) - default: - cancel(fmt.Errorf("head target %q: %w", item.key, err)) + continue + } + srcDigest, err := s3client.Digest(ctx, oldCli, bucket, item.key, item.size, item.etag) + if err != nil { + fail(fmt.Errorf("verify source %q: %w", item.key, err)) + return + } + dstDigest, err := s3client.Digest(ctx, newCli, bucket, item.key, item.size, awsv2.ToString(head.ETag)) + if err != nil { + fail(fmt.Errorf("verify target %q: %w", item.key, err)) return } + if srcDigest != dstDigest { + if err := record(&mu, &res, opt.IssuesJSONL, Issue{Key: item.key, Kind: "content", Detail: fmt.Sprintf("sha256 src=%x dst=%x", srcDigest, dstDigest)}); err != nil { + fail(err) + return + } + continue + } + mu.Lock() + res.OK++ + mu.Unlock() } }() } - err := cluster.WalkObjects(ctx, oldCli, bucket, func(objects []types.Object) error { - for _, obj := range objects { - item := listed{key: *obj.Key, size: *obj.Size, etag: awsv2.ToString(obj.ETag)} - if insert != nil { - if _, err := insert.ExecContext(ctx, item.key); err != nil { - return err - } + 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 + } + 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 } select { case <-ctx.Done(): - return context.Cause(ctx) + break feed case jobs <- item: } } - return nil - }) - if err != nil { - cancel(fmt.Errorf("list source: %w", err)) } close(jobs) wg.Wait() - if err := context.Cause(ctx); err != nil { + if firstErr != nil { + return res, firstErr + } + if err := ctx.Err(); err != nil { return res, err } - // No object HEAD ran for an empty source. Check that the bucket itself - // was migrated, including in --extra mode. - if res.OK == 0 && !res.HasGaps() { - if err := cluster.HeadBucket(ctx, newCli, bucket); err != nil { - return res, fmt.Errorf("check empty bucket on target: %w", err) - } - } if opt.ReportExtra { - err := cluster.WalkObjects(ctx, newCli, bucket, func(objects []types.Object) error { - for _, obj := range objects { - var exists bool - if err := index.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM src WHERE key = ?)`, *obj.Key).Scan(&exists); err != nil { - return err + 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 !exists { - record(&mu, &res, Issue{Key: *obj.Key, Kind: "extra", Detail: "only on target"}) + if key == "" { + return res, fmt.Errorf("target listing contains empty key") + } + var n int + if err := db.QueryRowContext(ctx, `SELECT COUNT(*) FROM src WHERE key = ?`, key).Scan(&n); err != nil { + return res, 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 nil - }) - // A missing target bucket has no extra keys. - if err != nil && !s3client.IsNotFound(err) { - return res, fmt.Errorf("list target: %w", err) } } + return res, printResult(opt.Writer, res) +} - printResult(opt.Writer, res) - return res, nil +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 record(mu *sync.Mutex, res *Result, issue Issue) { +func decodeKey(key string, encoding types.EncodingType) (string, error) { + if encoding != types.EncodingTypeUrl { + return key, nil + } + decoded, err := url.QueryUnescape(key) + if err != nil { + return "", fmt.Errorf("invalid URL-encoded object key %q: %w", key, err) + } + return decoded, nil +} + +func record(mu *sync.Mutex, res *Result, output io.Writer, issue Issue) error { mu.Lock() defer mu.Unlock() switch issue.Kind { @@ -207,34 +310,54 @@ func record(mu *sync.Mutex, res *Result, issue Issue) { res.Missing++ case "size": res.SizeMismatch++ - case "etag": - res.ETagMismatch++ + case "content": + res.ContentMismatch++ + case "metadata": + res.MetadataMismatch++ case "extra": res.Extra++ } if len(res.Issues) < maxPrinted { res.Issues = append(res.Issues, issue) } + if output != nil { + entry := struct { + Bucket string `json:"bucket"` + Key string `json:"key"` + Kind string `json:"kind"` + Detail string `json:"detail"` + }{res.Bucket, issue.Key, issue.Kind, issue.Detail} + if err := json.NewEncoder(output).Encode(entry); err != nil { + return fmt.Errorf("write diff JSONL: %w", err) + } + } + return nil } -func printResult(w io.Writer, res Result) { - fmt.Fprintf(w, "=== diff %s ===\n", res.Bucket) - fmt.Fprintf(w, "ok=%d missing=%d size_mismatch=%d etag_mismatch=%d extra_on_target=%d size_only=%d\n", - res.OK, res.Missing, res.SizeMismatch, res.ETagMismatch, res.Extra, res.SizeOnly) - fmt.Fprintf(w, "一致=%d 缺失=%d 大小不一致=%d ETag不一致=%d 仅目标有=%d 仅比大小=%d\n", - res.OK, res.Missing, res.SizeMismatch, res.ETagMismatch, res.Extra, res.SizeOnly) +func printResult(w io.Writer, res Result) error { + var report bytes.Buffer + fmt.Fprintf(&report, "=== diff %s ===\n", res.Bucket) + fmt.Fprintf(&report, "ok=%d missing=%d size_mismatch=%d etag_mismatch=%d content_mismatch=%d metadata_mismatch=%d extra_on_target=%d\n", + res.OK, res.Missing, res.SizeMismatch, res.ETagMismatch, res.ContentMismatch, res.MetadataMismatch, res.Extra) + fmt.Fprintf(&report, "一致=%d 缺失=%d 大小不一致=%d 内容SHA256不一致=%d 元数据不一致=%d 仅目标有=%d\n", + res.OK, res.Missing, res.SizeMismatch, res.ContentMismatch, res.MetadataMismatch, res.Extra) for _, issue := range res.Issues { - key := issue.Key - if strings.IndexFunc(key, unicode.IsControl) >= 0 { - key = strconv.Quote(key) - } - fmt.Fprintf(w, " %-8s %s %s\n", issue.Kind, key, issue.Detail) + fmt.Fprintf(&report, " %-8s %q %s\n", issue.Kind, issue.Key, issue.Detail) } - hidden := res.Missing + res.SizeMismatch + res.ETagMismatch + res.Extra - int64(len(res.Issues)) + hidden := res.Missing + res.SizeMismatch + res.ETagMismatch + res.ContentMismatch + res.MetadataMismatch + res.Extra - int64(len(res.Issues)) if hidden > 0 { - fmt.Fprintf(w, " ... and %d more issues / 还有 %d 条未打印\n", hidden, hidden) + fmt.Fprintf(&report, " ... and %d more issues / 还有 %d 条未打印\n", hidden, hidden) } + _, err := report.WriteTo(w) + if err != nil { + return fmt.Errorf("write diff report: %w", err) + } + return nil } -func normalizeETag(s string) string { return strings.Trim(s, `"`) } -func isMultipart(s string) bool { return strings.Contains(s, "-") } +func deref(p *int64) int64 { + if p == nil { + return 0 + } + return *p +} diff --git a/internal/differ/differ_test.go b/internal/differ/differ_test.go index d2ae3ca..1254731 100644 --- a/internal/differ/differ_test.go +++ b/internal/differ/differ_test.go @@ -181,7 +181,7 @@ func TestDiffReturnsTargetErrorWithFullQueue(t *testing.T) { } } -func TestDiffSeparatesSizeOnlyFromETagMatches(t *testing.T) { +func TestDiffRejectsUnverifiableSameSizeObjects(t *testing.T) { old := fakes3.NewWithObjects(t, "photos", map[string][]byte{ "ok": []byte("x"), "multipart": []byte("x"), "missing-tag": []byte("x"), }, time.Now()) @@ -199,8 +199,8 @@ func TestDiffSeparatesSizeOnlyFromETagMatches(t *testing.T) { defer target.Close() ctx := context.Background() res, err := Run(ctx, testClient(t, ctx, old.URL), testClient(t, ctx, target.URL), "photos", Options{Workers: 2}) - if err != nil || res.OK != 3 || res.SizeOnly != 2 || res.HasGaps() { - t.Fatalf("result=%+v err=%v", res, err) + if err == nil && (!res.HasGaps() || res.OK != 0) { + t.Fatalf("unreadable target must not be certified: result=%+v", res) } } diff --git a/internal/fakes3/fakes3.go b/internal/fakes3/fakes3.go index 318b4a8..117a405 100644 --- a/internal/fakes3/fakes3.go +++ b/internal/fakes3/fakes3.go @@ -4,6 +4,7 @@ package fakes3 import ( "crypto/md5" + "encoding/xml" "fmt" "io" "net/http" @@ -97,6 +98,9 @@ func (s *Server) Put(bucket, key string, body []byte, lm time.Time, meta Metadat if meta.Metadata == nil { meta.Metadata = map[string]string{} } + if meta.ContentType == "" { + meta.ContentType = "application/octet-stream" + } s.buckets[bucket][key] = &object{ body: append([]byte(nil), body...), etag: md5hex(body), @@ -288,7 +292,7 @@ func (s *Server) handle(w http.ResponseWriter, r *http.Request) { case r.Method == http.MethodGet && bucket == "" && key == "": s.listBuckets(w) case r.Method == http.MethodGet && q.Get("list-type") == "2": - s.listObjects(w, bucket) + s.listObjects(w, r, bucket) case r.Method == http.MethodHead && key == "": s.headBucket(w, bucket) case r.Method == http.MethodPut && key == "" && q.Get("partNumber") == "": @@ -306,7 +310,7 @@ func (s *Server) handle(w http.ResponseWriter, r *http.Request) { case r.Method == http.MethodPost && q.Get("uploadId") != "": s.completeMultipart(w, r, bucket, key, q.Get("uploadId")) case r.Method == http.MethodDelete && q.Get("uploadId") != "": - s.abortMultipart(w) + s.abortMultipart(w, q.Get("uploadId")) default: http.Error(w, "unsupported", http.StatusBadRequest) } @@ -356,7 +360,7 @@ func (s *Server) createBucket(w http.ResponseWriter, bucket string) { w.WriteHeader(http.StatusOK) } -func (s *Server) listObjects(w http.ResponseWriter, bucket string) { +func (s *Server) listObjects(w http.ResponseWriter, r *http.Request, bucket string) { s.mu.Lock() defer s.mu.Unlock() bkt, ok := s.buckets[bucket] @@ -374,9 +378,16 @@ func (s *Server) listObjects(w http.ResponseWriter, bucket string) { b.WriteString(``) b.WriteString(``) b.WriteString(`` + xmlEscape(bucket) + `` + strconv.Itoa(len(keys)) + `1000false`) + if r.URL.Query().Get("encoding-type") == "url" { + b.WriteString(`url`) + } for _, key := range keys { obj := bkt[key] - b.WriteString(`` + xmlEscape(key) + ``) + encodedKey := key + if r.URL.Query().Get("encoding-type") == "url" { + encodedKey = url.PathEscape(key) + } + b.WriteString(`` + xmlEscape(encodedKey) + ``) b.WriteString(`` + obj.lm.UTC().Format(time.RFC3339) + ``) b.WriteString(`"` + obj.etag + `"`) b.WriteString(`` + strconv.Itoa(len(obj.body)) + `STANDARD`) @@ -401,8 +412,7 @@ func (s *Server) headObject(w http.ResponseWriter, r *http.Request, bucket, key writeNoSuchKey(w) return } - if match := r.Header.Get("If-Match"); match != "" && match != `"`+obj.etag+`"` { - w.WriteHeader(http.StatusPreconditionFailed) + if !matchCondition(w, r, obj.etag) { return } w.Header().Set("Content-Length", strconv.Itoa(len(obj.body))) @@ -412,11 +422,16 @@ func (s *Server) headObject(w http.ResponseWriter, r *http.Request, bucket, key w.WriteHeader(http.StatusOK) } -func (s *Server) abortMultipart(w http.ResponseWriter) { +func (s *Server) abortMultipart(w http.ResponseWriter, uploadID string) { s.mu.Lock() fail := s.failAborts > 0 if fail { s.failAborts-- + } else { + delete(s.multipart, uploadID) + delete(s.uploadMeta, uploadID) + delete(s.uploadBucket, uploadID) + delete(s.uploadKey, uploadID) } s.mu.Unlock() if fail { @@ -444,26 +459,27 @@ func (s *Server) getObject(w http.ResponseWriter, r *http.Request, bucket, key s writeNoSuchKey(w) return } - if match := r.Header.Get("If-Match"); match != "" && match != `"`+obj.etag+`"` { - w.WriteHeader(http.StatusPreconditionFailed) + value := obj.body + if !matchCondition(w, r, obj.etag) { return } - chunk := obj.body - status := http.StatusOK - if hdr := r.Header.Get("Range"); hdr != "" { - var start, end int - if _, err := fmt.Sscanf(hdr, "bytes=%d-%d", &start, &end); err != nil || start < 0 || end >= len(chunk) || start > end { + start, end := int64(0), int64(len(value)-1) + partial := r.Header.Get("Range") != "" + if partial { + if _, err := fmt.Sscanf(r.Header.Get("Range"), "bytes=%d-%d", &start, &end); err != nil || start < 0 || end >= int64(len(value)) || start > end { http.Error(w, "bad range", http.StatusRequestedRangeNotSatisfiable) return } - w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(chunk))) - chunk = chunk[start : end+1] - status = http.StatusPartialContent + w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, len(value))) } + chunk := value[start : end+1] w.Header().Set("Content-Length", strconv.Itoa(len(chunk))) w.Header().Set("ETag", `"`+obj.etag+`"`) + w.Header().Set("Last-Modified", obj.lm.UTC().Format(http.TimeFormat)) writeMetadataHeaders(w, obj.meta) - w.WriteHeader(status) + if partial { + w.WriteHeader(http.StatusPartialContent) + } _, _ = w.Write(chunk) } @@ -493,7 +509,7 @@ func (s *Server) putObject(w http.ResponseWriter, r *http.Request, bucket, key s s.ensureBucketLocked(bucket) if _, exists := s.buckets[bucket][key]; exists && r.Header.Get("If-None-Match") == "*" { s.mu.Unlock() - w.WriteHeader(http.StatusPreconditionFailed) + writePreconditionFailed(w) return } s.buckets[bucket][key] = &object{ @@ -572,8 +588,35 @@ func (s *Server) uploadPart(w http.ResponseWriter, r *http.Request, key string, } func (s *Server) completeMultipart(w http.ResponseWriter, r *http.Request, bucket, key, uploadID string) { + var manifest struct { + Parts []struct { + PartNumber int `xml:"PartNumber"` + ETag string `xml:"ETag"` + } `xml:"Part"` + } + if err := xml.NewDecoder(r.Body).Decode(&manifest); err != nil { + http.Error(w, "bad manifest", 400) + return + } s.mu.Lock() - parts := s.multipart[uploadID] + parts, exists := s.multipart[uploadID] + if !exists { + s.mu.Unlock() + writeNotFound(w, "NoSuchUpload", "missing upload") + return + } + if len(manifest.Parts) != len(parts) { + s.mu.Unlock() + http.Error(w, "missing parts", 400) + return + } + for i, p := range manifest.Parts { + if p.PartNumber != i+1 || strings.Trim(p.ETag, `"`) != md5hex(parts[p.PartNumber]) { + s.mu.Unlock() + http.Error(w, "invalid part", 400) + return + } + } nums := make([]int, 0, len(parts)) for num := range parts { nums = append(nums, num) @@ -586,7 +629,7 @@ func (s *Server) completeMultipart(w http.ResponseWriter, r *http.Request, bucke s.ensureBucketLocked(bucket) if _, exists := s.buckets[bucket][key]; exists && r.Header.Get("If-None-Match") == "*" { s.mu.Unlock() - w.WriteHeader(http.StatusPreconditionFailed) + writePreconditionFailed(w) return } etag := fmt.Sprintf("%s-%d", md5hex(body), len(nums)) @@ -607,9 +650,15 @@ func (s *Server) completeMultipart(w http.ResponseWriter, r *http.Request, bucke } func parsePath(rawPath string) (bucket, key string) { - // net/http has already decoded URL.Path. Slashes in the key are data. - bucket, key, _ = strings.Cut(strings.TrimPrefix(rawPath, "/"), "/") - return bucket, key + clean := strings.TrimPrefix(rawPath, "/") + if clean == "" { + return "", "" + } + bucket, rest, found := strings.Cut(clean, "/") + if !found { + return bucket, "" + } + return bucket, rest } func writeNoSuchKey(w http.ResponseWriter) { @@ -645,6 +694,9 @@ func readMetadataHeaders(r *http.Request) Metadata { ContentEncoding: r.Header.Get("Content-Encoding"), Metadata: map[string]string{}, } + if meta.ContentType == "" { + meta.ContentType = "application/octet-stream" + } for key, values := range r.Header { if !strings.HasPrefix(strings.ToLower(key), "x-amz-meta-") || len(values) == 0 { continue @@ -667,3 +719,16 @@ func xmlEscape(s string) string { replacer := strings.NewReplacer("&", "&", "<", "<", ">", ">", "\"", """, "'", "'") return replacer.Replace(s) } + +func matchCondition(w http.ResponseWriter, r *http.Request, objectETag string) bool { + if etag := r.Header.Get("If-Match"); etag != "" && strings.Trim(etag, `"`) != objectETag { + writePreconditionFailed(w) + return false + } + return true +} +func writePreconditionFailed(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(http.StatusPreconditionFailed) + _, _ = io.WriteString(w, `PreconditionFailed`) +} diff --git a/internal/migrator/audit_real_s3_test.go b/internal/migrator/audit_real_s3_test.go new file mode 100644 index 0000000..0d6acd8 --- /dev/null +++ b/internal/migrator/audit_real_s3_test.go @@ -0,0 +1,124 @@ +//go:build real_s3 + +package migrator + +import ( + "bytes" + "context" + "crypto/sha256" + "fmt" + "io" + "net/url" + "os" + "path/filepath" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/rustfs/migration/internal/cluster" + "github.com/rustfs/migration/internal/config" + "github.com/rustfs/migration/internal/differ" + "github.com/rustfs/migration/internal/s3client" + "github.com/rustfs/migration/internal/scanner" + "github.com/rustfs/migration/internal/store" +) + +// Only isolated loopback servers started by scripts/audit-local-rustfs.py are +// accepted. The script owns and destroys their data directories after the test. +func TestRealS3MigrationSHA256AndResume(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) + defer cancel() + client := func(name string) *s3.Client { + endpoint := os.Getenv(name) + if endpoint == "" { + t.Skip("run via scripts/audit-local-rustfs.py") + } + u, err := url.Parse(endpoint) + if err != nil || u.Hostname() != "127.0.0.1" { + t.Fatal("requires isolated loopback endpoint") + } + c, err := s3client.New(ctx, config.Endpoint{Endpoint: endpoint, Region: "us-east-1", AccessKey: "audit-local", SecretKey: "audit-local-secret"}) + if err != nil { + t.Fatal(err) + } + return c + } + src, dst := client("AUDIT_SOURCE"), client("AUDIT_TARGET") + bucket := fmt.Sprintf("migration-audit-%d", time.Now().UnixNano()) + for _, c := range []*s3.Client{src, dst} { + if err := cluster.EnsureBucket(ctx, c, bucket); err != nil { + t.Fatal(err) + } + } + objects := map[string][]byte{ + "empty": {}, "hello.txt": []byte("migration"), + "中文/空 格+%?#.txt": []byte("unicode and escaping"), + "folder/": {}, "boundary.bin": bytes.Repeat([]byte{0x91}, 5*1024*1024), + "multipart.bin": bytes.Repeat([]byte("abcdefg"), 1600000), + } + sourceAttrs := make(map[string]objectAttrs) + for key, data := range objects { + _, err := src.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String(key), Body: bytes.NewReader(data), ContentType: aws.String("application/x-audit"), CacheControl: aws.String("max-age=60"), Metadata: map[string]string{"audit": "preserve"}}) + if err != nil { + t.Fatal(err) + } + baseline, err := src.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}) + if err != nil { + t.Fatal(err) + } + _, readErr := io.Copy(io.Discard, baseline.Body) + baseline.Body.Close() + if readErr != nil { + t.Fatal(readErr) + } + sourceAttrs[key] = objectAttrs{ContentType: baseline.ContentType, CacheControl: baseline.CacheControl, Metadata: baseline.Metadata} + t.Logf("source baseline key=%q content-type=%q cache-control=%q metadata=%v", key, aws.ToString(baseline.ContentType), aws.ToString(baseline.CacheControl), baseline.Metadata) + } + dir := t.TempDir() + cfg := &config.Config{SourceFrozen: true, Bucket: bucket, DBPath: filepath.Join(dir, "state.db"), ConflictLog: filepath.Join(dir, "conflict.log"), SpoolDir: dir, Workers: 3, MultipartConcurrency: 2, MultipartThreshold: 5 * 1024 * 1024, MultipartPartSize: 5 * 1024 * 1024} + st, err := store.Open(cfg.DBPath, bucket) + if err != nil { + t.Fatal(err) + } + defer st.Close() + for run := 0; run < 2; run++ { + if _, err := scanner.Run(ctx, src, bucket, st); err != nil { + t.Fatal(err) + } + m, err := New(cfg, src, dst, st) + if err != nil { + t.Fatal(err) + } + err = m.Run(ctx) + m.Close() + if err != nil { + t.Errorf("migration run %d: %v", run, err) + } + counts, err := st.Counts() + if err != nil || counts.Done != int64(len(objects)) || counts.Failed != 0 { + t.Errorf("run %d counts=%+v err=%v", run, counts, err) + } + } + for key, want := range objects { + out, err := dst.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}) + if err != nil { + t.Errorf("read target key=%q: %v", key, err) + continue + } + got, err := io.ReadAll(out.Body) + out.Body.Close() + if err != nil || sha256.Sum256(got) != sha256.Sum256(want) { + t.Fatalf("SHA256 mismatch key=%q err=%v", key, err) + } + wantAttrs := sourceAttrs[key] + if aws.ToString(out.ContentType) != aws.ToString(wantAttrs.ContentType) || aws.ToString(out.CacheControl) != aws.ToString(wantAttrs.CacheControl) || out.Metadata["audit"] != wantAttrs.Metadata["audit"] { + t.Errorf("metadata mismatch key=%q source=%+v target content-type=%q cache-control=%q metadata=%v", key, wantAttrs, aws.ToString(out.ContentType), aws.ToString(out.CacheControl), out.Metadata) + } + t.Logf("verified key=%q bytes=%d sha256=%x", key, len(got), sha256.Sum256(got)) + } + r, err := differ.Run(ctx, src, dst, bucket, differ.Options{Workers: 3, ReportExtra: true, Writer: io.Discard}) + if err != nil || r.HasGaps() || r.OK != int64(len(objects)) || r.Extra != 0 { + t.Fatalf("diff=%+v err=%v", r, err) + } +} diff --git a/internal/migrator/audit_transfer_test.go b/internal/migrator/audit_transfer_test.go new file mode 100644 index 0000000..a5663bf --- /dev/null +++ b/internal/migrator/audit_transfer_test.go @@ -0,0 +1,557 @@ +package migrator + +// Regression tests for the 2026-10-29 audit safety findings. +// All servers are loopback-only; all non-final audit parts are at least 5 MiB. + +import ( + "bytes" + "context" + "crypto/md5" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws/retry" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/rustfs/migration/internal/fakes3" + "github.com/rustfs/migration/internal/scanner" + "github.com/rustfs/migration/internal/store" +) + +const auditPartSize = 5 << 20 // legal S3 non-final multipart part size + +var auditModified = time.Date(2026, 10, 29, 0, 0, 0, 0, time.UTC) + +func auditServer(t *testing.T, objects map[string][]byte) *fakes3.Server { + t.Helper() + s := fakes3.NewWithObjects(t, "bucket", objects, auditModified) + t.Cleanup(s.Close) + return s +} + +func auditWrap(t *testing.T, s *fakes3.Server, hook func(http.ResponseWriter, *http.Request, http.Handler)) string { + t.Helper() + wrapped := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hook(w, r, s.Config.Handler) + })) + t.Cleanup(wrapped.Close) + return wrapped.URL +} + +func auditMigration(t *testing.T, sourceURL, targetURL string) (*Migrator, *store.Store) { + t.Helper() + dir := t.TempDir() + dbPath := filepath.Join(dir, "migration.db") + st, err := store.Open(dbPath, "bucket") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = st.Close() }) + source := newTestClient(t, context.Background(), sourceURL) + target := newTestClient(t, context.Background(), targetURL) + if _, err := scanner.Run(context.Background(), source, "bucket", st); err != nil { + t.Fatal(err) + } + cfg := testCfg(dbPath, filepath.Join(dir, "conflict.log"), dir) + cfg.Workers = 1 + cfg.MultipartThreshold = auditPartSize + cfg.MultipartPartSize = auditPartSize + cfg.MultipartConcurrency = 1 + m, err := New(cfg, source, target, st) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = m.Close() }) + return m, st +} + +func auditRun(t *testing.T, m *Migrator) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + // Per-object errors may legitimately be returned by a future fix. + _ = m.Run(ctx) + if ctx.Err() != nil { + t.Fatalf("migration exceeded test deadline: %v", ctx.Err()) + } +} + +func auditError(w http.ResponseWriter, status int, code string) { + w.Header().Set("Content-Type", "application/xml") + w.WriteHeader(status) + _, _ = fmt.Fprintf(w, "%sinjected audit response", code) +} + +func TestAuditConcurrentTargetWriteMustNotBeOverwritten(t *testing.T) { + for _, multipart := range []bool{false, true} { + t.Run(fmt.Sprintf("multipart=%t", multipart), func(t *testing.T) { + body := []byte("source snapshot") + if multipart { + body = bytes.Repeat([]byte("S"), auditPartSize+1) + } + source := auditServer(t, map[string][]byte{"key": body}) + target := auditServer(t, nil) + businessWrite := []byte("business data committed after migration HEAD") + var once sync.Once + url := auditWrap(t, target, func(w http.ResponseWriter, r *http.Request, next http.Handler) { + q := r.URL.Query() + isCommit := r.Method == http.MethodPut && q.Get("uploadId") == "" || + r.Method == http.MethodPost && q.Get("uploadId") != "" + if isCommit { + once.Do(func() { + target.Put("bucket", "key", businessWrite, auditModified, fakes3.Metadata{}) + }) + // Model S3's server-side conditional write support. The original + // fixture ignores this header, so it cannot test atomic creation. + if r.Header.Get("If-None-Match") == "*" { + auditError(w, http.StatusPreconditionFailed, "PreconditionFailed") + return + } + } + next.ServeHTTP(w, r) + }) + m, st := auditMigration(t, source.URL, url) + auditRun(t, m) + got, exists := target.Object("bucket", "key") + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if !exists || !bytes.Equal(got, businessWrite) { + t.Fatalf("concurrent target write overwritten: stored_bytes=%d source_bytes=%d counts=%+v", len(got), len(body), counts) + } + }) + } +} + +func TestAuditMultipartSourceMutationMustNotCommitMixedVersions(t *testing.T) { + before := bytes.Repeat([]byte("A"), 2*auditPartSize) + after := bytes.Repeat([]byte("B"), 2*auditPartSize) + source := auditServer(t, map[string][]byte{"key": before}) + target := auditServer(t, nil) + var mutate sync.Once + url := auditWrap(t, source, func(w http.ResponseWriter, r *http.Request, next http.Handler) { + if r.Method == http.MethodGet && r.Header.Get("Range") != "" { + body, _ := source.Object("bucket", "key") + etag := fmt.Sprintf("\"%x\"", md5.Sum(body)) + if match := r.Header.Get("If-Match"); match != "" && match != etag { + auditError(w, http.StatusPreconditionFailed, "PreconditionFailed") + return + } + // Set ETag before the fixture writes status 206, matching real S3. + w.Header().Set("ETag", etag) + next.ServeHTTP(w, r) + mutate.Do(func() { + source.Put("bucket", "key", after, auditModified.Add(time.Second), fakes3.Metadata{}) + }) + return + } + next.ServeHTTP(w, r) + }) + m, st := auditMigration(t, url, target.URL) + auditRun(t, m) + got, exists := target.Object("bucket", "key") + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if exists && !bytes.Equal(got, before) && !bytes.Equal(got, after) { + t.Fatalf("committed object combines two source versions: bytes=%d prefix=%q suffix=%q counts=%+v", len(got), got[:8], got[len(got)-8:], counts) + } +} + +func TestAuditConcurrentDeleteMustNotResurrect(t *testing.T) { + body := []byte("live application deletes this historical object") + source := auditServer(t, map[string][]byte{"key": body}) + target := auditServer(t, nil) + deleted := make(chan struct{}) + var once sync.Once + sourceURL := auditWrap(t, source, func(w http.ResponseWriter, r *http.Request, next http.Handler) { + next.ServeHTTP(w, r) + if r.Method == http.MethodGet && r.URL.Path == "/bucket/key" { + // The body has been captured by the migration GET. Model the + // application's dual-delete from DESIGN.md, before target commit. + once.Do(func() { + source.DeleteKey("bucket", "key") + target.DeleteKey("bucket", "key") + close(deleted) + }) + } + }) + targetURL := auditWrap(t, target, func(w http.ResponseWriter, r *http.Request, next http.Handler) { + if r.Method == http.MethodPut { + select { + case <-deleted: + case <-r.Context().Done(): + return + } + } + next.ServeHTTP(w, r) + }) + m, st := auditMigration(t, sourceURL, targetURL) + auditRun(t, m) + select { + case <-deleted: + default: + t.Fatal("test did not reach the concurrent application delete") + } + if _, exists := source.Object("bucket", "key"); exists { + t.Fatal("application delete did not remove source") + } + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if got, exists := target.Object("bucket", "key"); exists { + t.Fatalf("application-deleted object resurrected on target: body=%q counts=%+v", got, counts) + } +} + +func TestAuditUnverifiableTargetMustNotBeConsideredMigrated(t *testing.T) { + for _, etag := range []string{"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-2", "opaque-encrypted", ""} { + t.Run("etag="+etag, func(t *testing.T) { + source := auditServer(t, map[string][]byte{"key": []byte("AAAA")}) + target := auditServer(t, map[string][]byte{"key": []byte("BBBB")}) + m, st := auditMigration(t, source.URL, auditETagEndpoint(t, target, etag)) + auditRun(t, m) + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if counts.Done != 0 || counts.Conflict+counts.Failed != 1 { + t.Fatalf("same-sized unverified content accepted: %+v", counts) + } + got, _ := target.Object("bucket", "key") + if !bytes.Equal(got, []byte("BBBB")) { + t.Fatal("existing target was modified") + } + }) + } +} + +func TestAuditTarget404MustRemainRetryable(t *testing.T) { + for _, phase := range []string{"put", "create-multipart", "complete-multipart", "verify-head"} { + t.Run(phase, func(t *testing.T) { + body := []byte("source still exists") + if strings.Contains(phase, "multipart") { + body = bytes.Repeat([]byte("M"), auditPartSize+1) + } + source := auditServer(t, map[string][]byte{"key": body}) + target := auditServer(t, nil) + url := auditWrap(t, target, func(w http.ResponseWriter, r *http.Request, next http.Handler) { + q := r.URL.Query() + _, exists := target.Object("bucket", "key") + fail := phase == "put" && r.Method == http.MethodPut && q.Get("uploadId") == "" || + phase == "create-multipart" && r.Method == http.MethodPost && q.Has("uploads") || + phase == "complete-multipart" && r.Method == http.MethodPost && q.Get("uploadId") != "" || + phase == "verify-head" && r.Method == http.MethodHead && exists + if fail { + auditError(w, http.StatusNotFound, "NoSuchBucket") + return + } + next.ServeHTTP(w, r) + }) + m, st := auditMigration(t, source.URL, url) + auditRun(t, m) + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if counts.Skipped != 0 || counts.Failed != 1 { + t.Fatalf("destination %s 404 misclassified as missing source: %+v", phase, counts) + } + }) + } +} + +func TestAuditControlStableSourceCopiesSingleAndMultipart(t *testing.T) { + for _, size := range []int{15, auditPartSize + 1} { + t.Run(fmt.Sprintf("size=%d", size), func(t *testing.T) { + body := bytes.Repeat([]byte("C"), size) + source := auditServer(t, map[string][]byte{"key": body}) + target := auditServer(t, nil) + m, st := auditMigration(t, source.URL, target.URL) + auditRun(t, m) + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + got, exists := target.Object("bucket", "key") + if !exists || !bytes.Equal(got, body) || counts.Done != 1 { + t.Fatalf("control copy failed: exists=%t bytes=%d counts=%+v", exists, len(got), counts) + } + }) + } +} + +func TestMigrationRequiresFrozenSource(t *testing.T) { + source := auditServer(t, map[string][]byte{"key": []byte("source")}) + target := auditServer(t, nil) + m, st := auditMigration(t, source.URL, target.URL) + m.Cfg.SourceFrozen = false + if err := m.Run(context.Background()); err == nil || !strings.Contains(err.Error(), "source_frozen") { + t.Fatalf("unfrozen migration must fail before copying: %v", err) + } + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if counts.Pending != 1 || target.PutObjectCalls("key") != 0 { + t.Fatalf("unfrozen migration performed work: %+v", counts) + } +} + +func TestSameETagDoesNotProveContentEquality(t *testing.T) { + sourceBytes := []byte("AAAA") + source := auditServer(t, map[string][]byte{"key": sourceBytes}) + target := auditServer(t, map[string][]byte{"key": []byte("BBBB")}) + etag := fmt.Sprintf("\"%x\"", md5.Sum(sourceBytes)) + url := auditWrap(t, target, func(w http.ResponseWriter, r *http.Request, next http.Handler) { + // Model opaque ETags that happen to be equal across two endpoints. + if r.Method == http.MethodHead || r.Method == http.MethodGet { + r.Header.Del("If-Match") + recorder := httptest.NewRecorder() + next.ServeHTTP(recorder, r) + for key, values := range recorder.Header() { + w.Header()[key] = values + } + w.Header().Set("ETag", etag) + w.WriteHeader(recorder.Code) + _, _ = w.Write(recorder.Body.Bytes()) + return + } + next.ServeHTTP(w, r) + }) + m, st := auditMigration(t, source.URL, url) + auditRun(t, m) + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if counts.Done != 0 || counts.Conflict != 1 { + t.Fatalf("equal ETags hid different content: %+v", counts) + } + got, _ := target.Object("bucket", "key") + if !bytes.Equal(got, []byte("BBBB")) { + t.Fatal("existing target was modified") + } +} + +func TestMultipartRejectsInvalidRangeBeforeCommit(t *testing.T) { + source := auditServer(t, map[string][]byte{"key": bytes.Repeat([]byte("R"), auditPartSize+1)}) + target := auditServer(t, nil) + url := auditWrap(t, source, func(w http.ResponseWriter, r *http.Request, next http.Handler) { + if r.Method == http.MethodGet && r.Header.Get("Range") != "" { + // A proxy incorrectly strips Range, so S3 returns the full body. + r.Header.Del("Range") + } + next.ServeHTTP(w, r) + }) + m, st := auditMigration(t, url, target.URL) + if err := m.Run(context.Background()); err == nil { + t.Fatal("invalid range response must fail") + } + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if counts.Failed != 1 || target.CompleteMultipartCalls("key") != 0 { + t.Fatalf("invalid range was committed: %+v", counts) + } +} + +func TestSourceChangedSinceScanFailsBeforeWrite(t *testing.T) { + source := auditServer(t, map[string][]byte{"key": []byte("old-data")}) + target := auditServer(t, nil) + m, st := auditMigration(t, source.URL, target.URL) + source.Put("bucket", "key", []byte("new-data"), auditModified.Add(time.Second), fakes3.Metadata{}) + if err := m.Run(context.Background()); err == nil { + t.Fatal("changed source must fail") + } + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if counts.Failed != 1 || target.PutObjectCalls("key") != 0 { + t.Fatalf("changed source was copied: %+v", counts) + } +} + +func TestCommittedTargetCorruptionIsNotMarkedDone(t *testing.T) { + source := auditServer(t, map[string][]byte{"key": []byte("AAAA")}) + target := auditServer(t, nil) + url := auditWrap(t, target, func(w http.ResponseWriter, r *http.Request, next http.Handler) { + next.ServeHTTP(w, r) + if r.Method == http.MethodPut { + target.Put("bucket", "key", []byte("BBBB"), auditModified, fakes3.Metadata{ContentType: "application/test", Metadata: map[string]string{"origin": "old"}}) + } + }) + m, st := auditMigration(t, source.URL, url) + if err := m.Run(context.Background()); err == nil { + t.Fatal("read-back corruption must fail") + } + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if counts.Done != 0 || counts.Failed != 1 { + t.Fatalf("corrupt target accepted: %+v", counts) + } +} + +func TestEqualContentDifferentMetadataConflicts(t *testing.T) { + body := []byte("same content") + source := auditServer(t, map[string][]byte{"key": body}) + target := auditServer(t, nil) + target.Put("bucket", "key", body, auditModified, fakes3.Metadata{ContentType: "text/plain", Metadata: map[string]string{"origin": "business"}}) + m, st := auditMigration(t, source.URL, target.URL) + auditRun(t, m) + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if counts.Done != 0 || counts.Conflict != 1 { + t.Fatalf("metadata mismatch was accepted as done: %+v", counts) + } + meta, _ := target.ObjectMetadata("bucket", "key") + if meta.ContentType != "text/plain" || meta.Metadata["origin"] != "business" { + t.Fatal("existing target metadata changed") + } +} + +func TestConflictPersistenceFailureStopsWorkerPool(t *testing.T) { + source := auditServer(t, map[string][]byte{"a": []byte("source"), "b": []byte("source")}) + target := auditServer(t, map[string][]byte{"a": []byte("target"), "b": []byte("target")}) + m, st := auditMigration(t, source.URL, target.URL) + if err := m.conflict.f.Close(); err != nil { + t.Fatal(err) + } + err := m.Run(context.Background()) + var fatal *persistenceError + if !errors.As(err, &fatal) { + t.Fatalf("want fatal persistence error, got %v", err) + } + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if counts.Pending != 2 || counts.Failed != 0 || m.processed.Load() != 1 { + t.Fatalf("fatal persistence error was downgraded or pool continued: %+v processed=%d", counts, m.processed.Load()) + } +} + +func TestLostCommitResponseReconcilesRetryPrecondition(t *testing.T) { + for _, tc := range []struct { + name string + multipart, businessOverwrite, sourceChanged, retryConflict bool + }{ + {name: "single-own-commit"}, + {name: "multipart-own-commit", multipart: true}, + {name: "single-business-replacement", businessOverwrite: true}, + {name: "multipart-business-replacement", multipart: true, businessOverwrite: true}, + {name: "source-changed-after-commit", sourceChanged: true}, + {name: "retry-409-remains-failed", retryConflict: true}, + } { + t.Run(tc.name, func(t *testing.T) { + body := []byte("historical object") + if tc.multipart { + body = bytes.Repeat([]byte("S"), auditPartSize+1) + } + source := auditServer(t, map[string][]byte{"key": body}) + target := auditServer(t, nil) + business := bytes.Repeat([]byte("B"), len(body)) + var commits atomic.Int32 + url := auditWrap(t, target, func(w http.ResponseWriter, r *http.Request, next http.Handler) { + q := r.URL.Query() + commit := r.Method == http.MethodPut && q.Get("uploadId") == "" || + r.Method == http.MethodPost && q.Get("uploadId") != "" + if !commit { + next.ServeHTTP(w, r) + return + } + if r.Header.Get("If-None-Match") != "*" { + t.Error("commit lost its atomic create condition") + } + if commits.Add(1) > 1 { + if tc.retryConflict { + auditError(w, http.StatusConflict, "ConditionalRequestConflict") + return + } + // Some servers check the existing key before the completed + // upload ID. Model that legitimate 412 retry response for MPU. + auditError(w, http.StatusPreconditionFailed, "PreconditionFailed") + return + } + recorded := httptest.NewRecorder() + next.ServeHTTP(recorded, r) // Commit bytes, but discard the response. + if recorded.Code != http.StatusOK { + t.Errorf("injected commit did not succeed: %d %s", recorded.Code, recorded.Body.String()) + } + attrs := fakes3.Metadata{ContentType: "application/test", Metadata: map[string]string{"origin": "old"}} + if tc.businessOverwrite { + target.Put("bucket", "key", business, auditModified, attrs) + } + if tc.sourceChanged { + source.Put("bucket", "key", business, auditModified.Add(time.Second), attrs) + } + connection, _, err := w.(http.Hijacker).Hijack() + if err != nil { + t.Errorf("drop committed response: %v", err) + return + } + _ = connection.Close() // SDK retries the real request after EOF. + }) + m, st := auditMigration(t, source.URL, url) + // Keep fault-injection deterministic and independent of ambient + // AWS retry settings; the seekable spool supports a full retry. + m.NewCli = s3.New(m.NewCli.Options(), func(options *s3.Options) { + options.Retryer = retry.NewStandard(func(opts *retry.StandardOptions) { opts.MaxAttempts = 2; opts.MaxBackoff = time.Millisecond }) + }) + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + err := m.Run(ctx) + if ctx.Err() != nil { + t.Fatalf("lost-response test timed out: %v", ctx.Err()) + } + if (err != nil) != (tc.sourceChanged || tc.retryConflict) { + t.Fatalf("run error=%v sourceChanged=%t retryConflict=%t", err, tc.sourceChanged, tc.retryConflict) + } + if commits.Load() != 2 { + t.Fatalf("did not exercise lost-response retry: commits=%d", commits.Load()) + } + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + switch { + case tc.sourceChanged || tc.retryConflict: + if counts.Failed != 1 || counts.Done != 0 || counts.Conflict != 0 { + t.Fatalf("changed source accepted during reconciliation: %+v", counts) + } + case tc.businessOverwrite: + if counts.Conflict != 1 || counts.Done != 0 { + t.Fatalf("business replacement was mistaken for own commit: %+v", counts) + } + default: + if counts.Done != 1 || counts.Conflict != 0 || counts.Failed != 0 { + t.Fatalf("own successful commit was not recovered: %+v", counts) + } + } + want := body + if tc.businessOverwrite { + want = business + } + got, exists := target.Object("bucket", "key") + if !exists || !bytes.Equal(got, want) { + t.Fatal("reconciliation changed committed target bytes") + } + }) + } +} diff --git a/internal/migrator/copy_safety_test.go b/internal/migrator/copy_safety_test.go index 43f799e..7fc30eb 100644 --- a/internal/migrator/copy_safety_test.go +++ b/internal/migrator/copy_safety_test.go @@ -62,7 +62,7 @@ func TestCreateOnlyWritePreservesConcurrentTarget(t *testing.T) { endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() if (r.Method == http.MethodPut && !q.Has("partNumber")) || (r.Method == http.MethodPost && q.Has("uploadId")) { - dst.Put("bucket", "key", []byte(tc.winner), time.Now(), fakes3.Metadata{}) + dst.Put("bucket", "key", []byte(tc.winner), time.Now(), fakes3.Metadata{ContentType: "application/test", Metadata: map[string]string{"origin": "old"}}) } if r.Method == http.MethodDelete && q.Has("uploadId") { aborts.Add(1) diff --git a/internal/migrator/migrator.go b/internal/migrator/migrator.go index e31feb1..22e72f1 100644 --- a/internal/migrator/migrator.go +++ b/internal/migrator/migrator.go @@ -1,13 +1,14 @@ package migrator import ( - "bytes" "context" + "crypto/sha256" "errors" "fmt" "io" "log" - "net/http" + "maps" + "math" "os" "path/filepath" "strconv" @@ -21,11 +22,11 @@ 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" "github.com/rustfs/migration/internal/s3client" + "github.com/rustfs/migration/internal/safeoutput" "github.com/rustfs/migration/internal/store" ) @@ -49,7 +50,18 @@ type Migrator struct { // lim is shared by every worker and every multipart part of this migrator. // Nil means unlimited. Buckets are copied one at a time, so this is the // process-wide source-read cap while a copy is running. - lim *ratelimit.Limiter + lim *ratelimit.Limiter + spoolBudget *spoolBudget +} + +type objectAttrs struct { + CacheControl *string + ContentDisposition *string + ContentEncoding *string + ContentLanguage *string + ContentType *string + Expires *time.Time + Metadata map[string]string } func New(cfg *config.Config, oldCli, newCli *s3.Client, st *store.Store) (*Migrator, error) { @@ -60,6 +72,16 @@ func NewForBucket(cfg *config.Config, bucket string, oldCli, newCli *s3.Client, if bucket == "" { return nil, fmt.Errorf("migrator: bucket must not be empty") } + boundBucket, err := st.BoundBucket() + if err != nil { + return nil, err + } + if boundBucket != bucket { + return nil, fmt.Errorf("state bucket %q does not match migration bucket %q", boundBucket, bucket) + } + if err := st.BindMigration(awsv2.ToString(oldCli.Options().BaseEndpoint), awsv2.ToString(newCli.Options().BaseEndpoint)); err != nil { + return nil, err + } if err := os.MkdirAll(cfg.SpoolDir, 0o755); err != nil { return nil, fmt.Errorf("create spool_dir %s: %w", cfg.SpoolDir, err) } @@ -68,13 +90,14 @@ func NewForBucket(cfg *config.Config, bucket string, oldCli, newCli *s3.Client, return nil, err } return &Migrator{ - Cfg: cfg, - Bucket: bucket, - OldCli: oldCli, - NewCli: newCli, - Store: st, - conflict: cw, - lim: ratelimit.New(int64(cfg.RateLimit)), + Cfg: cfg, + Bucket: bucket, + OldCli: oldCli, + NewCli: newCli, + Store: st, + conflict: cw, + lim: ratelimit.New(int64(cfg.RateLimit)), + spoolBudget: newSpoolBudget(cfg.SpoolMaxBytes), }, nil } @@ -84,11 +107,35 @@ func (m *Migrator) Run(ctx context.Context) error { if err := m.Cfg.ValidateConcurrency(); err != nil { return err } + if !m.Cfg.SourceFrozen { + return fmt.Errorf("source_frozen must be true: freeze source writes and deletes before migration") + } + if err := m.Store.RequireCompleteScan(); err != nil { + return err + } failedBefore := m.failed.Load() - ctx, cancel := context.WithCancelCause(ctx) - defer cancel(nil) + ctx, cancel := context.WithCancel(ctx) + defer cancel() jobs := make(chan store.Object, config.JobBuffer(m.Cfg.Workers)) + var fatalMu sync.Mutex + var firstFatal error + recordFatal := func(err error) { + if err == nil { + return + } + fatalMu.Lock() + first := firstFatal == nil + if first { + firstFatal = err + } + fatalMu.Unlock() + if first { + log.Printf("FATAL %s; cancelling remaining work", safeoutput.Escape(err.Error())) + cancel() + } + } + var wg sync.WaitGroup for i := 0; i < m.Cfg.Workers; i++ { wg.Add(1) @@ -98,10 +145,7 @@ func (m *Migrator) Run(ctx context.Context) error { if ctx.Err() != nil { return } - if err := m.handle(ctx, obj); err != nil { - cancel(err) // State could not be persisted. - return - } + recordFatal(m.handle(ctx, obj)) } }() } @@ -144,14 +188,17 @@ func (m *Migrator) Run(ctx context.Context) error { close(stopProgress) m.logFinal() - if err := context.Cause(ctx); err != nil { - return err + if firstFatal != nil { + return firstFatal } if feedErr != nil { return feedErr } - if n := m.failed.Load() - failedBefore; n != 0 { - return fmt.Errorf("%d object(s) failed in bucket %q; see the object errors above", n, m.Bucket) + if ctx.Err() != nil { + return ctx.Err() + } + if failed := m.failed.Load() - failedBefore; failed > 0 { + return fmt.Errorf("migration failed for %d objects; inspect status and retry", failed) } return nil } @@ -177,355 +224,426 @@ func (m *Migrator) logFinal() { m.processed.Load(), m.copied.Load(), m.conflicts.Load(), m.skipped.Load(), m.failed.Load(), m.bytes.Load()) } +// sourceReadError preserves which side failed. Destination 404s must never +// be interpreted as a deleted source object. +type sourceReadError struct{ err error } + +func (e *sourceReadError) Error() string { return "source: " + e.err.Error() } +func (e *sourceReadError) Unwrap() error { return e.err } + +// Failure to durably record local outcomes is fatal to the whole worker pool. +type persistenceError struct{ err error } + +func (e *persistenceError) Error() string { return e.err.Error() } +func (e *persistenceError) Unwrap() error { return e.err } + +type sourceSnapshot struct { + attrs objectAttrs + etag string + versionID *string + size int64 +} + +func isMissingSource(err error) bool { + var source *sourceReadError + if !errors.As(err, &source) || s3client.IsCanceled(err) { + return false + } + var api smithy.APIError + return errors.As(source.err, &api) && api.ErrorCode() == "NoSuchKey" +} + func (m *Migrator) handle(ctx context.Context, obj store.Object) error { m.processed.Add(1) - - input := &s3.HeadObjectInput{Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key)} - head, err := m.NewCli.HeadObject(ctx, input) + err := m.migrateObject(ctx, obj) if err == nil { - return m.recordExisting(obj, head) + return nil + } + var persist *persistenceError + if errors.As(err, &persist) { + return err + } + if ctx.Err() == nil && isMissingSource(err) { + m.skipped.Add(1) + if e := m.Store.MarkStatus(obj.Key, store.StatusSkipped, "source NoSuchKey"); e != nil { + return fmt.Errorf("mark skipped key=%q: %w", obj.Key, e) + } + return nil + } + return m.markFailed(obj.Key, err) +} + +func (m *Migrator) migrateObject(ctx context.Context, obj store.Object) error { + head, err := m.NewCli.HeadObject(ctx, &s3.HeadObjectInput{Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key)}) + if err != nil && (ctx.Err() != nil || !s3client.IsNotFound(err)) { + return fmt.Errorf("head target: %w", err) + } + snapshot, err := m.sourceSnapshot(ctx, obj) + if err != nil { + return err + } + if head != nil { + return m.reconcileExistingTarget(ctx, obj, snapshot, head) } - if ctx.Err() != nil || !s3client.IsNotFound(err) { - return m.markFailed(obj.Key, fmt.Errorf("head new: %w", err)) + if obj.Size > 0 && (obj.Size >= m.Cfg.MultipartThreshold || obj.Size > config.MaxMultipartPartSize) { + err = m.copyMultipart(ctx, obj, snapshot) + } else { + err = m.copySingle(ctx, obj, snapshot) + } + 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 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)}) + if herr == nil { + 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) + } + } + } + return err } + return m.markDone(obj) +} - err = m.copy(ctx, obj) - switch { - case err == nil: - return m.markDone(obj) - case errors.Is(err, errTargetRace): - // A writer won the race after HEAD. Classify its object exactly as - // we would on resume. If it vanished again, retry on the next run. - head, err := m.NewCli.HeadObject(ctx, input) +// reconcileExistingTarget distinguishes an independent business write from +// our own committed upload whose successful response was lost in transit. +func (m *Migrator) reconcileExistingTarget(ctx context.Context, obj store.Object, snapshot sourceSnapshot, head *s3.HeadObjectOutput) error { + // ETags only pin a representation; all equality decisions use SHA256. + if head != nil && head.ContentLength != nil && *head.ContentLength == obj.Size && attributesEqual(snapshot.attrs, head) { + sourceDigest, err := m.sourceDigest(ctx, obj.Key, snapshot) if err != nil { - return m.markFailed(obj.Key, fmt.Errorf("head new after conditional write: %w", err)) + return err } - return m.recordExisting(obj, head) - case ctx.Err() == nil && errors.Is(err, errSourceMissing): - log.Printf("WARN source missing, skipping key=%s", obj.Key) - m.skipped.Add(1) - if err := m.Store.MarkStatus(obj.Key, store.StatusSkipped, "source 404"); err != nil { - return fmt.Errorf("mark skipped key=%s: %w", obj.Key, err) + targetDigest, err := s3client.Digest(ctx, m.NewCli, m.Bucket, obj.Key, obj.Size, awsv2.ToString(head.ETag)) + if err != nil { + return fmt.Errorf("verify existing target: %w", err) + } + if sourceDigest == targetDigest { + if err := m.checkSourceBeforeCommit(ctx, obj, snapshot); err != nil { + return err + } + return m.markDone(obj) } - return nil - default: - return m.markFailed(obj.Key, err) } + return m.markConflict(obj, head) } -func (m *Migrator) recordExisting(obj store.Object, head *s3.HeadObjectOutput) error { - if targetAlreadyMigrated(obj, head) { - return m.markDone(obj) +func (m *Migrator) markConflict(obj store.Object, head *s3.HeadObjectOutput) error { + var modified time.Time + if head != nil && head.LastModified != nil { + modified = *head.LastModified } - if err := m.conflict.Write(obj.Key, obj.LastModified, awsv2.ToTime(head.LastModified)); err != nil { - return fmt.Errorf("persist conflict log key=%s: %w", obj.Key, err) + if err := m.conflict.Write(obj.Key, obj.LastModified, modified); err != nil { + return &persistenceError{fmt.Errorf("persist conflict key=%q: %w", obj.Key, err)} } - m.conflicts.Add(1) if err := m.Store.MarkStatus(obj.Key, store.StatusConflict, "exists on new"); err != nil { - return fmt.Errorf("mark conflict key=%s: %w", obj.Key, err) + return &persistenceError{fmt.Errorf("mark conflict key=%q: %w", obj.Key, err)} } + m.conflicts.Add(1) return nil } func (m *Migrator) markDone(obj store.Object) error { + if err := m.Store.MarkStatus(obj.Key, store.StatusDone, ""); err != nil { + return &persistenceError{fmt.Errorf("mark done key=%q: %w", obj.Key, err)} + } m.copied.Add(1) if obj.Size > 0 { m.bytes.Add(obj.Size) } - if err := m.Store.MarkStatus(obj.Key, store.StatusDone, ""); err != nil { - return fmt.Errorf("mark done key=%s: %w", obj.Key, err) - } return nil } func (m *Migrator) markFailed(key string, err error) error { m.failed.Add(1) - log.Printf("ERROR key=%s: %v", key, err) + log.Printf("ERROR key=%q: %q", key, err.Error()) if markErr := m.Store.MarkStatus(key, store.StatusFailed, err.Error()); markErr != nil { - return fmt.Errorf("mark failed key=%s: %w (original error: %v)", key, markErr, err) + return fmt.Errorf("mark failed key=%q: %w (original error: %q)", key, markErr, err.Error()) } return nil } -var ( - errSourceMissing = errors.New("source object missing") - errTargetRace = errors.New("conditional target write lost a race") -) - -// Only a HEAD or GET of the source can make an inventory row skipped. -func sourceReadError(op string, err error) error { - if s3client.IsNotFound(err) { - return fmt.Errorf("%s: %w: %w", op, errSourceMissing, err) +func (m *Migrator) sourceSnapshot(ctx context.Context, obj store.Object) (sourceSnapshot, error) { + out, err := m.OldCli.HeadObject(ctx, &s3.HeadObjectInput{Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key)}) + if err != nil { + if s3client.IsNotFound(err) && ctx.Err() == nil { + // HEAD 404 cannot distinguish NoSuchBucket from NoSuchKey. GET + // supplies the typed object error before we permanently skip it. + get, getErr := m.OldCli.GetObject(ctx, &s3.GetObjectInput{Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key)}) + if getErr != nil { + return sourceSnapshot{}, &sourceReadError{getErr} + } + get.Body.Close() + } + return sourceSnapshot{}, &sourceReadError{err} } - return fmt.Errorf("%s: %w", op, err) -} - -// This SDK predates IfNoneMatch on the two S3 commit operations. -func createOnly(o *s3.Options) { - o.APIOptions = append(o.APIOptions, smithyhttp.SetHeaderValue("If-None-Match", "*")) + etag := awsv2.ToString(out.ETag) + if obj.Size < 0 || obj.Size == math.MaxInt64 || out.ContentLength == nil || *out.ContentLength != obj.Size || + normalizeETag(etag) == "" || normalizeETag(obj.ETag) == "" || normalizeETag(etag) != normalizeETag(obj.ETag) { + return sourceSnapshot{}, fmt.Errorf("source changed since scan or lacks a stable identity: key=%q", obj.Key) + } + if !obj.LastModified.IsZero() && out.LastModified != nil && !obj.LastModified.Truncate(time.Second).Equal(out.LastModified.Truncate(time.Second)) { + return sourceSnapshot{}, fmt.Errorf("source last-modified changed since scan: key=%q", obj.Key) + } + 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), + }}, nil } -func targetWriteError(op string, err error) error { - var response *smithyhttp.ResponseError - var api smithy.APIError - if (errors.As(err, &response) && response.HTTPStatusCode() == http.StatusPreconditionFailed) || - (errors.As(err, &api) && api.ErrorCode() == "ConditionalRequestConflict") { - return fmt.Errorf("%s: %w: %w", op, errTargetRace, err) +func (m *Migrator) sourceDigest(ctx context.Context, key string, snap sourceSnapshot) ([32]byte, error) { + digest, err := s3client.DigestWithReader(ctx, m.OldCli, m.Bucket, key, snap.size, snap.etag, func(r io.Reader) io.Reader { return m.throttle(ctx, r) }) + if err != nil { + return digest, &sourceReadError{err} } - return fmt.Errorf("%s: %w", op, err) + return digest, nil } -func quotedETag(tag string) *string { - if tag = normalizeETag(tag); tag != "" { - return awsv2.String(`"` + tag + `"`) +// checkSourceBeforeCommit detects completed deletes/updates, but cannot make +// a cross-cluster transaction. SourceFrozen is the required operational fence. +func (m *Migrator) checkSourceBeforeCommit(ctx context.Context, obj store.Object, snap sourceSnapshot) error { + latest, err := m.sourceSnapshot(ctx, obj) + if err != nil { + return err + } + if latest.etag != snap.etag || awsv2.ToString(latest.versionID) != awsv2.ToString(snap.versionID) { + return fmt.Errorf("source representation changed before target commit") } return nil } -func (m *Migrator) copy(ctx context.Context, obj store.Object) error { - if obj.Size >= m.Cfg.MultipartThreshold || obj.Size > config.MaxMultipartPartSize { - return m.copyMultipart(ctx, obj) +func (m *Migrator) spool(ctx context.Context, reader io.Reader, expected int64) (*os.File, [32]byte, error) { + var digest [32]byte + tmp, err := os.CreateTemp(m.Cfg.SpoolDir, "migration-*") + if err != nil { + return nil, digest, err + } + h := sha256.New() + n, err := io.Copy(io.MultiWriter(tmp, h), io.LimitReader(m.throttle(ctx, reader), expected+1)) + if err == nil && n != expected { + err = fmt.Errorf("source body length mismatch: got=%d want=%d", n, expected) + } + if err == nil { + _, err = tmp.Seek(0, io.SeekStart) + } + if err != nil { + tmp.Close() + os.Remove(tmp.Name()) + return nil, digest, err } - return m.copySingle(ctx, obj) + copy(digest[:], h.Sum(nil)) + return tmp, digest, nil } -func (m *Migrator) copySingle(ctx context.Context, obj store.Object) error { - out, err := m.OldCli.GetObject(ctx, &s3.GetObjectInput{ - Bucket: awsv2.String(m.Bucket), - Key: awsv2.String(obj.Key), - IfMatch: quotedETag(obj.ETag), - }) +func (m *Migrator) copySingle(ctx context.Context, obj store.Object, snap sourceSnapshot) error { + release, err := m.spoolBudget.acquire(ctx, obj.Size+1) + if err != nil { + return err + } + defer release() + out, err := m.OldCli.GetObject(ctx, &s3.GetObjectInput{Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key), IfMatch: awsv2.String(snap.etag), VersionId: snap.versionID}) if err != nil { - return sourceReadError("get old", err) + return &sourceReadError{err} } defer out.Body.Close() - - if obj.ETag != "" && normalizeETag(awsv2.ToString(out.ETag)) != normalizeETag(obj.ETag) { - return fmt.Errorf("source ETag changed since scan; rescan bucket %q", m.Bucket) + if out.ContentLength == nil || *out.ContentLength != obj.Size || normalizeETag(awsv2.ToString(out.ETag)) != normalizeETag(snap.etag) { + return fmt.Errorf("source response does not match snapshot") } - tmp, err := os.CreateTemp(m.Cfg.SpoolDir, "migration-*") + tmp, digest, err := m.spool(ctx, out.Body, obj.Size) if err != nil { - return fmt.Errorf("create temp file: %w", err) + return &sourceReadError{err} } defer os.Remove(tmp.Name()) defer tmp.Close() - - written, err := io.Copy(tmp, m.throttle(ctx, io.LimitReader(out.Body, obj.Size+1))) - if err != nil { - return fmt.Errorf("spool old body: %w", err) - } - if written != obj.Size { - return fmt.Errorf("source size changed since scan: got=%d want=%d", written, obj.Size) - } - if _, err := tmp.Seek(0, io.SeekStart); err != nil { - return fmt.Errorf("rewind temp file: %w", err) - } - - putOut, err := m.NewCli.PutObject(ctx, &s3.PutObjectInput{ - Bucket: awsv2.String(m.Bucket), - Key: awsv2.String(obj.Key), - Body: tmp, - ContentLength: awsv2.Int64(written), - CacheControl: out.CacheControl, - ContentDisposition: out.ContentDisposition, - ContentEncoding: out.ContentEncoding, - ContentLanguage: out.ContentLanguage, - ContentType: out.ContentType, - Expires: out.Expires, - Metadata: out.Metadata, - }, createOnly) + if err = m.checkSourceBeforeCommit(ctx, obj, snap); err != nil { + return err + } + attrs := snap.attrs + _, 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, + }) if err != nil { - return targetWriteError("put new", err) + return fmt.Errorf("put target: %w", err) } + return m.verifyTarget(ctx, obj, digest, snap.attrs) +} - srcETag := normalizeETag(awsv2.ToString(out.ETag)) - dstETag := normalizeETag(awsv2.ToString(putOut.ETag)) - if srcETag != "" && dstETag != "" && !isMultipartETag(srcETag) && !isMultipartETag(dstETag) && srcETag != dstETag { - return fmt.Errorf("etag mismatch: src=%s dst=%s", srcETag, dstETag) +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 } - return m.verifyTarget(ctx, obj, putOut.ETag) + if attrs.Expires != nil && !attrs.Expires.Equal(*head.Expires) { + return false + } + return maps.Equal(attrs.Metadata, head.Metadata) } -func (m *Migrator) copyMultipart(ctx context.Context, obj store.Object) error { - attrs, err := m.OldCli.HeadObject(ctx, &s3.HeadObjectInput{ - Bucket: awsv2.String(m.Bucket), - Key: awsv2.String(obj.Key), - IfMatch: quotedETag(obj.ETag), - }) +func (m *Migrator) verifyTarget(ctx context.Context, obj store.Object, sourceDigest [32]byte, attrs objectAttrs) error { + head, err := m.NewCli.HeadObject(ctx, &s3.HeadObjectInput{Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key)}) if err != nil { - return sourceReadError("head old", err) + return fmt.Errorf("verify head target: %w", err) } - if attrs.ContentLength == nil || *attrs.ContentLength != obj.Size || - (obj.ETag != "" && normalizeETag(awsv2.ToString(attrs.ETag)) != normalizeETag(obj.ETag)) { - return fmt.Errorf("source changed since scan; rescan bucket %q", m.Bucket) + if head.ContentLength == nil || *head.ContentLength != obj.Size { + return fmt.Errorf("target size mismatch: want=%d", obj.Size) } - match := quotedETag(awsv2.ToString(attrs.ETag)) - if match == nil { - return errors.New("source HEAD returned no ETag to pin multipart reads") + if !attributesEqual(attrs, head) { + return fmt.Errorf("target metadata mismatch after commit") } - - partConc := m.Cfg.MultipartConcurrency - if partConc < 1 { - return fmt.Errorf("multipart_concurrency must be >= 1, got %d", partConc) + digest, err := s3client.Digest(ctx, m.NewCli, m.Bucket, obj.Key, obj.Size, awsv2.ToString(head.ETag)) + if err != nil { + return fmt.Errorf("verify target digest: %w", err) + } + if digest != sourceDigest { + return fmt.Errorf("SHA256 mismatch after target commit") } + return nil +} +func (m *Migrator) copyMultipart(ctx context.Context, obj store.Object, snap sourceSnapshot) error { partSize := m.Cfg.MultipartPartSize - if obj.Size <= 0 || partSize <= 0 { - return fmt.Errorf("invalid multipart object or part size: object=%d part=%d", obj.Size, partSize) + if partSize <= 0 || m.Cfg.MultipartConcurrency < 1 { + return fmt.Errorf("invalid multipart configuration") } - const maxParts = 10000 - partSize = max(partSize, 1+(obj.Size-1)/maxParts) - if partSize > config.MaxMultipartPartSize { - return fmt.Errorf("required part size %d exceeds S3 limit %d", partSize, config.MaxMultipartPartSize) + numParts := (obj.Size-1)/partSize + 1 + if numParts > 10000 { + partSize = (obj.Size-1)/10000 + 1 + numParts = (obj.Size-1)/partSize + 1 } - numParts := int(1 + (obj.Size-1)/partSize) - + if partSize > 5<<30 { + return fmt.Errorf("multipart part size exceeds S3 maximum of 5 GiB") + } + 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, + 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, }) if err != nil { - return fmt.Errorf("create multipart: %w", err) + return fmt.Errorf("create multipart target: %w", err) } uploadID := awsv2.ToString(create.UploadId) - - abort := func(reason error) error { - abortCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + if uploadID == "" { + return fmt.Errorf("target returned empty multipart upload ID") + } + committed := false + defer func() { + if committed { + return + } + cleanup, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - _, aerr := m.NewCli.AbortMultipartUpload(abortCtx, &s3.AbortMultipartUploadInput{ - Bucket: awsv2.String(m.Bucket), - Key: awsv2.String(obj.Key), - UploadId: awsv2.String(uploadID), - }) - var gone *s3types.NoSuchUpload - if aerr != nil && !errors.As(aerr, &gone) { - return fmt.Errorf("abort multipart after %v: %w", reason, aerr) + if _, err := m.NewCli.AbortMultipartUpload(cleanup, &s3.AbortMultipartUploadInput{Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key), UploadId: awsv2.String(uploadID)}); err != nil { + log.Printf("WARN abort multipart key=%q upload=%q: %q", obj.Key, uploadID, err.Error()) } - return reason - } - - parts := make([]s3types.CompletedPart, numParts) - sem := make(chan struct{}, partConc) + }() + partCtx, cancel := context.WithCancel(ctx) + defer cancel() + parts := make([]s3types.CompletedPart, int(numParts)) + sem := make(chan struct{}, m.Cfg.MultipartConcurrency) var wg sync.WaitGroup - partCtx, cancelParts := context.WithCancelCause(ctx) - defer cancelParts(nil) - -partLoop: - for i := 0; i < numParts; i++ { - if partCtx.Err() != nil { - break + var firstErr error + var errOnce sync.Once + record := func(err error) { + if err != nil { + errOnce.Do(func() { firstErr = err; cancel() }) } + } +partLoop: + for i := int64(0); i < numParts; i++ { select { case <-partCtx.Done(): - // Do not block on a full semaphore after Ctrl-C, and do not - // start parts that have not been scheduled yet. break partLoop case sem <- struct{}{}: } wg.Add(1) - go func(idx int) { + go func(idx int64) { defer wg.Done() defer func() { <-sem }() - if partCtx.Err() != nil { - return + start := idx * partSize + length := partSize + if length > obj.Size-start { + length = obj.Size - start } - - start := int64(idx) * partSize - end := start + partSize - 1 - if end >= obj.Size { - end = obj.Size - 1 - } - rangeHdr := fmt.Sprintf("bytes=%d-%d", start, end) - - getOut, gerr := m.OldCli.GetObject(partCtx, &s3.GetObjectInput{ - Bucket: awsv2.String(m.Bucket), - Key: awsv2.String(obj.Key), - Range: awsv2.String(rangeHdr), - IfMatch: match, - }) - if gerr != nil { - cancelParts(sourceReadError(fmt.Sprintf("get part %d", idx+1), gerr)) + end := start + length - 1 + release, err := m.spoolBudget.acquire(partCtx, length+1) + if err != nil { + record(err) return } - defer getOut.Body.Close() - wantRange := fmt.Sprintf("bytes %d-%d/%d", start, end, obj.Size) - if awsv2.ToString(getOut.ContentRange) != wantRange || - normalizeETag(awsv2.ToString(getOut.ETag)) != normalizeETag(*match) { - cancelParts(fmt.Errorf("unexpected source range or ETag for part %d (expected %s)", idx+1, wantRange)) + defer release() + get, err := m.OldCli.GetObject(partCtx, &s3.GetObjectInput{Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key), Range: awsv2.String(fmt.Sprintf("bytes=%d-%d", start, end)), IfMatch: awsv2.String(snap.etag), VersionId: snap.versionID}) + if err != nil { + record(&sourceReadError{err}) return } - size := end - start + 1 - body, rerr := io.ReadAll(m.throttle(partCtx, io.LimitReader(getOut.Body, size+1))) - if rerr != nil { - cancelParts(fmt.Errorf("read part %d: %w", idx+1, rerr)) + defer get.Body.Close() + expectedRange := fmt.Sprintf("bytes %d-%d/%d", start, end, obj.Size) + if awsv2.ToString(get.ContentRange) != expectedRange || get.ContentLength == nil || *get.ContentLength != length || normalizeETag(awsv2.ToString(get.ETag)) != normalizeETag(snap.etag) { + record(fmt.Errorf("invalid source range response: got=%q expected=%q", awsv2.ToString(get.ContentRange), expectedRange)) return } - - if int64(len(body)) != size { - cancelParts(fmt.Errorf("part %d length: got=%d want=%d", idx+1, len(body), size)) + tmp, _, err := m.spool(partCtx, get.Body, length) + if err != nil { + record(&sourceReadError{err}) return } - - up, uerr := m.NewCli.UploadPart(partCtx, &s3.UploadPartInput{ - Bucket: awsv2.String(m.Bucket), - Key: awsv2.String(obj.Key), - UploadId: awsv2.String(uploadID), - PartNumber: awsv2.Int32(int32(idx + 1)), - Body: bytes.NewReader(body), - ContentLength: awsv2.Int64(int64(len(body))), - }) - if uerr != nil { - cancelParts(fmt.Errorf("upload part %d: %w", idx+1, uerr)) + defer os.Remove(tmp.Name()) + defer tmp.Close() + up, err := m.NewCli.UploadPart(partCtx, &s3.UploadPartInput{Bucket: awsv2.String(m.Bucket), Key: awsv2.String(obj.Key), UploadId: awsv2.String(uploadID), PartNumber: awsv2.Int32(int32(idx + 1)), Body: tmp, ContentLength: awsv2.Int64(length)}) + if err != nil { + record(fmt.Errorf("upload target part %d: %w", idx+1, err)) return } - parts[idx] = s3types.CompletedPart{ - ETag: up.ETag, - PartNumber: awsv2.Int32(int32(idx + 1)), + if awsv2.ToString(up.ETag) == "" { + record(fmt.Errorf("target part %d has no ETag", idx+1)) + return } + parts[idx] = s3types.CompletedPart{ETag: up.ETag, PartNumber: awsv2.Int32(int32(idx + 1))} }(i) } wg.Wait() - - if err := context.Cause(partCtx); err != nil { - return abort(err) + if firstErr != nil { + return firstErr } - - committed, 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}, - }, createOnly) - if err != nil { - return abort(targetWriteError("complete multipart", err)) + if ctx.Err() != nil { + return ctx.Err() } - - return m.verifyTarget(ctx, obj, committed.ETag) -} - -func (m *Migrator) verifyTarget(ctx context.Context, obj store.Object, committedETag *string) error { - head, err := m.NewCli.HeadObject(ctx, &s3.HeadObjectInput{ - Bucket: awsv2.String(m.Bucket), - Key: awsv2.String(obj.Key), - IfMatch: quotedETag(awsv2.ToString(committedETag)), - }) + // Re-read the pinned source sequentially. This keeps memory bounded even + // for very large objects and independently checks the assembled target. + digest, err := m.sourceDigest(ctx, obj.Key, snap) if err != nil { - return fmt.Errorf("verify head new: %w", err) + return err } - if head.ContentLength == nil || *head.ContentLength != obj.Size { - return fmt.Errorf("target size after upload: got=%d want=%d", awsv2.ToInt64(head.ContentLength), obj.Size) + if err = m.checkSourceBeforeCommit(ctx, obj, snap); err != nil { + return err } - if committedETag != nil && normalizeETag(*committedETag) != normalizeETag(awsv2.ToString(head.ETag)) { - return errors.New("target ETag changed after upload") + _, 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) } - return nil + committed = true + return m.verifyTarget(ctx, obj, digest, snap.attrs) } // throttle charges source body bytes to the shared limiter. Metadata HEAD @@ -534,21 +652,19 @@ func (m *Migrator) throttle(ctx context.Context, r io.Reader) io.Reader { return ratelimit.Wrap(ctx, r, m.lim) } -func normalizeETag(s string) string { return strings.Trim(s, `"`) } - -// isMultipartETag reports S3 multipart ETags, which look like "-". -func isMultipartETag(s string) bool { return strings.Contains(s, "-") } - -// Different multipart layouts may represent the same bytes, but size alone -// is insufficient evidence that an existing target belongs to this migration. -func targetAlreadyMigrated(obj store.Object, head *s3.HeadObjectOutput) bool { - if head == nil || head.ContentLength == nil || *head.ContentLength != obj.Size { - return false +func copyMetadata(src map[string]string) map[string]string { + if len(src) == 0 { + return nil } - srcETag := normalizeETag(obj.ETag) - return srcETag != "" && srcETag == normalizeETag(awsv2.ToString(head.ETag)) + dst := make(map[string]string, len(src)) + for key, value := range src { + dst[key] = value + } + return dst } +func normalizeETag(s string) string { return strings.Trim(s, `"`) } + type conflictWriter struct { mu sync.Mutex f *os.File @@ -560,7 +676,7 @@ func newConflictWriter(path string) (*conflictWriter, error) { return nil, fmt.Errorf("create conflict log dir %s: %w", dir, err) } } - f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) + f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) if err != nil { return nil, fmt.Errorf("open conflict log: %w", err) } @@ -568,7 +684,9 @@ func newConflictWriter(path string) (*conflictWriter, error) { } func (c *conflictWriter) Write(key string, oldLM, newLM time.Time) error { - if strings.HasPrefix(key, `"`) || strings.IndexFunc(key, unicode.IsControl) >= 0 { + // Quote keys containing control characters, escapes, or an initial quote so + // the first TSV column remains both safe and unambiguously reversible. + if strings.HasPrefix(key, `"`) || strings.Contains(key, `\`) || strings.IndexFunc(key, unicode.IsControl) >= 0 { key = strconv.Quote(key) } line := fmt.Sprintf("%s\t%s\t%s\n", @@ -579,7 +697,11 @@ func (c *conflictWriter) Write(key string, oldLM, newLM time.Time) error { c.mu.Lock() defer c.mu.Unlock() _, err := c.f.WriteString(line) - return err + if err != nil { + return err + } + // Persist the audit record before the durable conflict status is committed. + return c.f.Sync() } func (c *conflictWriter) Close() error { return c.f.Close() } diff --git a/internal/migrator/migrator_integration_test.go b/internal/migrator/migrator_integration_test.go index f06054f..8bb1eb8 100644 --- a/internal/migrator/migrator_integration_test.go +++ b/internal/migrator/migrator_integration_test.go @@ -136,7 +136,7 @@ func TestResumeAfterTransientFailure(t *testing.T) { t.Fatalf("new migrator: %v", err) } if err := m1.Run(ctx); err == nil { - t.Fatal("run1 reported success despite a failed upload") + t.Fatal("migrate run1 must report the failed object") } _ = m1.Close() @@ -367,6 +367,9 @@ func TestResumeAfterPutBeforeMarkDone(t *testing.T) { ContentType: "application/test", Metadata: map[string]string{"origin": "old"}, }) + if err := st.BindMigration(oldS3.URL, newS3.URL); err != nil { + t.Fatal(err) + } if err := st.MarkStatus("resume/a.dat", store.StatusFailed, "context canceled"); err != nil { t.Fatal(err) } @@ -463,7 +466,7 @@ func TestCanceledMultipartGetIsFailedNotSkipped(t *testing.T) { select { case err := <-errCh: if !errors.Is(err, context.Canceled) { - t.Fatalf("migrate: %v", err) + t.Fatalf("migrate cancellation: %v", err) } case <-time.After(15 * time.Second): t.Fatal("migrate did not return after cancel") @@ -814,6 +817,7 @@ func TestRunRejectsNonPositiveMultipart(t *testing.T) { func testCfg(db, conflict, spool string) *appconfig.Config { return &appconfig.Config{ Bucket: "bucket", + SourceFrozen: true, DBPath: db, ConflictLog: conflict, SpoolDir: spool, diff --git a/internal/migrator/migrator_match_test.go b/internal/migrator/migrator_match_test.go index 17b202e..19a68ae 100644 --- a/internal/migrator/migrator_match_test.go +++ b/internal/migrator/migrator_match_test.go @@ -1,107 +1,80 @@ package migrator import ( + "bytes" + "context" + "github.com/rustfs/migration/internal/fakes3" + "net/http" + "net/http/httptest" "testing" - - awsv2 "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/s3" - - "github.com/rustfs/migration/internal/store" ) -func TestTargetAlreadyMigrated(t *testing.T) { - const etag = "aadd3e6a955c4a99024ca0bf126144a9" - cases := []struct { - name string - obj store.Object - head *s3.HeadObjectOutput - want bool +// ETags are concurrency tokens. A different multipart/encryption ETag is not +// itself a content conflict, and an equal ETag is never proof of equality. +func TestExistingTargetRequiresVerifiedBytes(t *testing.T) { + for _, tc := range []struct { + name string + source, target []byte + etag string + done, conflict, failed int64 }{ - { - name: "identical quoted etag", - obj: store.Object{Size: 1024, ETag: `"` + etag + `"`}, - head: headOf(1024, `"`+etag+`"`), - want: true, - }, - { - name: "quotes only on inventory", - obj: store.Object{Size: 1024, ETag: `"` + etag + `"`}, - head: headOf(1024, etag), - want: true, - }, - { - name: "same size different etag", - obj: store.Object{Size: 1024, ETag: etag}, - head: headOf(1024, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), - want: false, - }, - { - name: "different size same etag", - obj: store.Object{Size: 1024, ETag: etag}, - head: headOf(1025, etag), - want: false, - }, - { - name: "multipart dest etag is not comparable", - obj: store.Object{Size: 1024, ETag: etag}, - head: headOf(1024, etag+"-3"), - want: false, - }, - { - name: "both multipart etags differ", - obj: store.Object{Size: 4096, ETag: etag + "-2"}, - head: headOf(4096, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-4"), - want: false, - }, - { - name: "missing etags cannot establish equality", - obj: store.Object{Size: 8}, - head: headOf(8, ""), - want: false, - }, - { - name: "one missing etag cannot establish equality", - obj: store.Object{Size: 8, ETag: etag}, - head: headOf(8, ""), - want: false, - }, - { - name: "identical multipart layouts", - obj: store.Object{Size: 4096, ETag: etag + "-2"}, - head: headOf(4096, etag+"-2"), - want: true, - }, - { - name: "zero byte identical", - obj: store.Object{Size: 0, ETag: "d41d8cd98f00b204e9800998ecf8427e"}, - head: headOf(0, `"d41d8cd98f00b204e9800998ecf8427e"`), - want: true, - }, - { - name: "nil head", - obj: store.Object{Size: 1, ETag: "a"}, - head: nil, - want: false, - }, - { - name: "missing content length", - obj: store.Object{Size: 4, ETag: "abcd"}, - head: &s3.HeadObjectOutput{ETag: awsv2.String("abcd")}, - want: false, - }, - } - for _, tc := range cases { + {"same-content-opaque-etag", []byte("same"), []byte("same"), "opaque-encrypted-value", 1, 0, 0}, + {"same-content-multipart-etag", []byte("same"), []byte("same"), "digest-2", 1, 0, 0}, + {"same-content-quoted-etag", []byte("same"), []byte("same"), `"quoted-value"`, 1, 0, 0}, + {"different-content-same-size", []byte("AAAA"), []byte("BBBB"), "opaque", 0, 1, 0}, + {"different-size", []byte("longer"), []byte("short"), "opaque", 0, 1, 0}, + {"missing-target-etag", []byte("same"), []byte("same"), "", 0, 0, 1}, + {"zero-byte", []byte{}, []byte{}, "empty-object-etag", 1, 0, 0}, + } { t.Run(tc.name, func(t *testing.T) { - if got := targetAlreadyMigrated(tc.obj, tc.head); got != tc.want { - t.Fatalf("targetAlreadyMigrated() = %v, want %v", got, tc.want) + source := auditServer(t, map[string][]byte{"key": tc.source}) + target := auditServer(t, map[string][]byte{"key": tc.target}) + url := auditETagEndpoint(t, target, tc.etag) + m, st := auditMigration(t, source.URL, url) + err := m.Run(context.Background()) + if (err != nil) != (tc.failed != 0) { + t.Fatalf("unexpected run error: %v", err) + } + counts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if counts.Done != tc.done || counts.Conflict != tc.conflict || counts.Failed != tc.failed { + t.Fatalf("counts=%+v", counts) + } + got, _ := target.Object("bucket", "key") + if !bytes.Equal(got, tc.target) || target.PutObjectCalls("key") != 0 { + t.Fatal("existing target was modified") } }) } } -func headOf(size int64, etag string) *s3.HeadObjectOutput { - return &s3.HeadObjectOutput{ - ContentLength: awsv2.Int64(size), - ETag: awsv2.String(etag), - } +// Override the fixture's MD5-shaped ETags to model an endpoint with opaque +// representation tags, while still enforcing the requested If-Match token. +func auditETagEndpoint(t *testing.T, target *fakes3.Server, etag string) string { + t.Helper() + return auditWrap(t, target, func(w http.ResponseWriter, r *http.Request, next http.Handler) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + next.ServeHTTP(w, r) + return + } + if match := r.Header.Get("If-Match"); match != "" && match != etag { + auditError(w, http.StatusPreconditionFailed, "PreconditionFailed") + return + } + r.Header.Del("If-Match") + recorded := httptest.NewRecorder() + next.ServeHTTP(recorded, r) + for key, values := range recorded.Header() { + w.Header()[key] = values + } + if etag == "" { + w.Header().Del("ETag") + } else { + w.Header().Set("ETag", etag) + } + w.WriteHeader(recorded.Code) + _, _ = w.Write(recorded.Body.Bytes()) + }) } diff --git a/internal/migrator/real_s3_conditions_test.go b/internal/migrator/real_s3_conditions_test.go new file mode 100644 index 0000000..a96a27c --- /dev/null +++ b/internal/migrator/real_s3_conditions_test.go @@ -0,0 +1,219 @@ +//go:build real_s3 + +package migrator + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "fmt" + "io" + "net/url" + "os" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "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" + "github.com/rustfs/migration/internal/cluster" + "github.com/rustfs/migration/internal/config" + "github.com/rustfs/migration/internal/s3client" +) + +// These tests write only to disposable loopback services supplied by the local +// audit launcher. Their buckets disappear when the launcher removes its data. +func realConditionClient(t *testing.T, ctx context.Context, env string) *s3.Client { + t.Helper() + endpoint := os.Getenv(env) + if endpoint == "" { + t.Skip("run via scripts/audit-local-rustfs.py") + } + u, err := url.Parse(endpoint) + if err != nil || u.Hostname() != "127.0.0.1" || u.Port() == "" || + (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" { + t.Fatalf("%s must identify an isolated loopback service", env) + } + client, err := s3client.New(ctx, config.Endpoint{ + Endpoint: endpoint, Region: "us-east-1", AccessKey: "audit-local", SecretKey: "audit-local-secret", + }) + if err != nil { + t.Fatal(err) + } + return client +} + +func realConditionBucket(t *testing.T, ctx context.Context, client *s3.Client) string { + t.Helper() + bucket := fmt.Sprintf("migration-condition-%d", time.Now().UnixNano()) + if err := cluster.EnsureBucket(ctx, client, bucket); err != nil { + t.Fatal(err) + } + return bucket +} + +func realConditionPut(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, body []byte) string { + t.Helper() + out, err := client.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(key), Body: bytes.NewReader(body), + ContentLength: aws.Int64(int64(len(body))), ContentType: aws.String("application/octet-stream"), + }) + if err != nil { + t.Fatal(err) + } + if aws.ToString(out.ETag) == "" { + t.Fatal("PutObject returned no ETag") + } + return *out.ETag +} + +func realConditionAssertObject(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, want []byte) { + t.Helper() + out, err := client.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}) + if err != nil { + t.Fatal(err) + } + defer out.Body.Close() + got, err := io.ReadAll(io.LimitReader(out.Body, int64(len(want))+1)) + if err != nil { + t.Fatal(err) + } + if out.ContentLength == nil || *out.ContentLength != int64(len(want)) || !bytes.Equal(got, want) { + t.Fatalf("committed business data changed: returned_length=%v read=%d want=%d got_sha256=%x want_sha256=%x", + out.ContentLength, len(got), len(want), sha256.Sum256(got), sha256.Sum256(want)) + } + t.Logf("preserved key=%q bytes=%d sha256=%x", key, len(got), sha256.Sum256(got)) +} + +func realConditionHTTPStatus(err error) int { + var status interface{ HTTPStatusCode() int } + if errors.As(err, &status) { + return status.HTTPStatusCode() + } + return 0 +} + +func TestRealS3PutRequiresAbsentTarget(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + client := realConditionClient(t, ctx, "AUDIT_TARGET") + bucket := realConditionBucket(t, ctx, client) + const key = "conditional-put" + business := []byte("business data must survive conditional migration writes") + realConditionPut(t, ctx, client, bucket, key, business) + migration := []byte("historical source bytes") + _, err := client.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(key), Body: bytes.NewReader(migration), + ContentLength: aws.Int64(int64(len(migration))), IfNoneMatch: aws.String("*"), + }) + if status := realConditionHTTPStatus(err); status != 412 { + t.Errorf("PutObject If-None-Match:* must reject an existing key with 412; got status=%d error=%v", status, err) + } else { + t.Log("server rejected conditional PutObject with HTTP 412") + } + realConditionAssertObject(t, ctx, client, bucket, key, business) +} + +func TestRealS3MultipartCompletionRequiresAbsentTarget(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) + defer cancel() + client := realConditionClient(t, ctx, "AUDIT_TARGET") + bucket := realConditionBucket(t, ctx, client) + const key = "conditional-multipart" + upload, err := client.CreateMultipartUpload(ctx, &s3.CreateMultipartUploadInput{ + Bucket: aws.String(bucket), Key: aws.String(key), ContentType: aws.String("application/octet-stream"), + }) + if err != nil { + t.Fatal(err) + } + if aws.ToString(upload.UploadId) == "" { + t.Fatal("CreateMultipartUpload returned no upload ID") + } + t.Cleanup(func() { + cleanup, stop := context.WithTimeout(context.Background(), 15*time.Second) + defer stop() + _, err := client.AbortMultipartUpload(cleanup, &s3.AbortMultipartUploadInput{ + Bucket: aws.String(bucket), Key: aws.String(key), UploadId: upload.UploadId, + }) + var api smithy.APIError + if err != nil && !(errors.As(err, &api) && api.ErrorCode() == "NoSuchUpload") { + t.Errorf("clean up multipart upload: %v", err) + } + }) + parts := make([]s3types.CompletedPart, 0, 2) + for number := int32(1); number <= 2; number++ { + // Both parts meet S3's 5 MiB minimum; no tiny fake-server parts. + body := bytes.Repeat([]byte{byte('A' + number - 1)}, 5*1024*1024) + part, err := client.UploadPart(ctx, &s3.UploadPartInput{ + Bucket: aws.String(bucket), Key: aws.String(key), UploadId: upload.UploadId, + PartNumber: aws.Int32(number), Body: bytes.NewReader(body), ContentLength: aws.Int64(int64(len(body))), + }) + if err != nil { + t.Fatal(err) + } + if aws.ToString(part.ETag) == "" { + t.Fatal("UploadPart returned no ETag") + } + parts = append(parts, s3types.CompletedPart{PartNumber: aws.Int32(number), ETag: part.ETag}) + } + // This write occurs after upload creation and all part uploads, immediately + // before completion. A preliminary HEAD cannot protect this commit window. + business := []byte("business object created while multipart migration was running") + realConditionPut(t, ctx, client, bucket, key, business) + _, err = client.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{ + Bucket: aws.String(bucket), Key: aws.String(key), UploadId: upload.UploadId, + MultipartUpload: &s3types.CompletedMultipartUpload{Parts: parts}, IfNoneMatch: aws.String("*"), + }) + if status := realConditionHTTPStatus(err); status != 412 && status != 409 { + t.Errorf("conditional completion must reject concurrent target creation with 412/409; got status=%d error=%v", status, err) + } else { + t.Logf("server rejected conditional CompleteMultipartUpload with HTTP %d", status) + } + realConditionAssertObject(t, ctx, client, bucket, key, business) +} + +func TestRealS3GetRejectsStaleIfMatch(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + client := realConditionClient(t, ctx, "AUDIT_SOURCE") + bucket := realConditionBucket(t, ctx, client) + const key = "conditional-source" + before, after := bytes.Repeat([]byte("A"), 32), bytes.Repeat([]byte("B"), 32) + oldETag := realConditionPut(t, ctx, client, bucket, key, before) + newETag := realConditionPut(t, ctx, client, bucket, key, after) + if oldETag == newETag { + t.Fatal("source replacement failed to change the concurrency token") + } + for _, ranged := range []bool{false, true} { + t.Run(fmt.Sprintf("range=%t", ranged), func(t *testing.T) { + input := &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key), IfMatch: aws.String(oldETag)} + if ranged { + input.Range = aws.String("bytes=0-3") + } + out, err := client.GetObject(ctx, input) + if out != nil && out.Body != nil { + out.Body.Close() + } + if status := realConditionHTTPStatus(err); status != 412 { + t.Errorf("stale If-Match must reject source replacement with 412; got status=%d error=%v", status, err) + } else { + t.Log("server rejected stale source If-Match with HTTP 412") + } + }) + } + // Positive control: the same Range is readable with the current ETag. + out, err := client.GetObject(ctx, &s3.GetObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(key), IfMatch: aws.String(newETag), Range: aws.String("bytes=0-3"), + }) + if err != nil { + t.Fatal(err) + } + defer out.Body.Close() + got, err := io.ReadAll(io.LimitReader(out.Body, 5)) + if err != nil || !bytes.Equal(got, after[:4]) || aws.ToString(out.ContentRange) != "bytes 0-3/32" || aws.ToInt64(out.ContentLength) != 4 { + t.Fatalf("current ETag range control failed: bytes=%q content-range=%q length=%d error=%v", got, aws.ToString(out.ContentRange), aws.ToInt64(out.ContentLength), err) + } + realConditionAssertObject(t, ctx, client, bucket, key, after) +} diff --git a/internal/migrator/real_s3_recovery_test.go b/internal/migrator/real_s3_recovery_test.go new file mode 100644 index 0000000..60c00e4 --- /dev/null +++ b/internal/migrator/real_s3_recovery_test.go @@ -0,0 +1,257 @@ +//go:build real_s3 + +package migrator + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/rustfs/migration/internal/cluster" + "github.com/rustfs/migration/internal/config" + "github.com/rustfs/migration/internal/differ" + "github.com/rustfs/migration/internal/s3client" + "github.com/rustfs/migration/internal/scanner" + "github.com/rustfs/migration/internal/store" +) + +// The proxy forwards real UploadPart bodies and waits only after RustFS has +// accepted a part. Cancellation therefore exercises a real, incomplete remote +// multipart upload, rather than failing before any data reached the server. +// The same proxy endpoint remains bound to the checkpoint during both runs. +func TestRealS3MultipartCancellationAndCheckpointRecovery(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + endpoint := func(name string) string { + raw := os.Getenv(name) + if raw == "" { + t.Skip("run via scripts/audit-local-rustfs.py with isolated local RustFS nodes") + } + u, err := url.Parse(raw) + if err != nil || u.Scheme != "http" || u.Hostname() != "127.0.0.1" || u.Port() == "" || u.User != nil || u.RawQuery != "" || (u.Path != "" && u.Path != "/") { + t.Fatalf("%s must identify an isolated HTTP loopback server", name) + } + return raw + } + newClient := func(raw string) *s3.Client { + cli, err := s3client.New(ctx, config.Endpoint{Endpoint: raw, Region: "us-east-1", AccessKey: "audit-local", SecretKey: "audit-local-secret"}) + if err != nil { + t.Fatal(err) + } + return cli + } + sourceURL, targetURL := endpoint("AUDIT_SOURCE"), endpoint("AUDIT_TARGET") + if sourceURL == targetURL { + t.Fatal("recovery test requires separate source and target nodes") + } + src, directTarget := newClient(sourceURL), newClient(targetURL) + upstream, err := url.Parse(targetURL) + if err != nil { + t.Fatal(err) + } + proxy := httputil.NewSingleHostReverseProxy(upstream) + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + proxy.Transport = transport + defer transport.CloseIdleConnections() + var injectFailure atomic.Bool + injectFailure.Store(true) + partAccepted := make(chan string, 1) + var signalPart sync.Once + var successfulAborts atomic.Int32 + proxy.ModifyResponse = func(response *http.Response) error { + request := response.Request + query := request.URL.Query() + if response.StatusCode >= 200 && response.StatusCode < 300 { + if request.Method == http.MethodDelete && query.Get("uploadId") != "" { + successfulAborts.Add(1) + } + if request.Method == http.MethodPut && query.Get("partNumber") != "" && query.Get("uploadId") != "" && injectFailure.Load() { + signalPart.Do(func() { partAccepted <- query.Get("uploadId") }) + <-request.Context().Done() + return request.Context().Err() + } + } + return nil + } + proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { + // Expected cancellation should not generate misleading proxy diagnostics. + if r.Context().Err() == nil { + http.Error(w, "local recovery proxy: "+err.Error(), http.StatusBadGateway) + } + } + server := httptest.NewServer(proxy) + defer server.Close() + dst := newClient(server.URL) + bucket := fmt.Sprintf("migration-recovery-%d", time.Now().UnixNano()) + for _, cli := range []*s3.Client{src, directTarget} { + if err := cluster.EnsureBucket(ctx, cli, bucket); err != nil { + t.Fatal(err) + } + } + const partSize = 5 * 1024 * 1024 + const key = "recovery/multipart.bin" + payload := bytes.Repeat([]byte{0x7c}, 2*partSize+237) + // Different part boundaries carry different bytes, so order and truncation + // mistakes cannot accidentally retain the expected final digest. + for offset := 0; offset < len(payload); offset += 4093 { + payload[offset] = byte(offset / 4093) + } + wantDigest := sha256.Sum256(payload) + if _, err := src.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(key), Body: bytes.NewReader(payload), + ContentLength: aws.Int64(int64(len(payload))), ContentType: aws.String("application/x-recovery-test"), + CacheControl: aws.String("max-age=60"), Metadata: map[string]string{"recovery": "checkpoint"}, + }); err != nil { + t.Fatal(err) + } + dir := t.TempDir() + cfg := &config.Config{ + SourceFrozen: true, Bucket: bucket, DBPath: filepath.Join(dir, "checkpoint.db"), + ConflictLog: filepath.Join(dir, "conflict.log"), SpoolDir: dir, + Workers: 1, MultipartThreshold: partSize, MultipartPartSize: partSize, MultipartConcurrency: 2, + } + st, err := store.Open(cfg.DBPath, bucket) + if err != nil { + t.Fatal(err) + } + defer func() { + if st != nil { + _ = st.Close() + } + }() + if _, err := scanner.Run(ctx, src, bucket, st); err != nil { + t.Fatal(err) + } + active, err := New(cfg, src, dst, st) + if err != nil { + t.Fatal(err) + } + defer func() { + if active != nil { + _ = active.Close() + } + }() + first := active + runCtx, stopRun := context.WithCancel(ctx) + finished := make(chan struct{}) + runResult := make(chan error, 1) + go func() { + defer close(finished) + runResult <- first.Run(runCtx) + }() + defer func() { + stopRun() + select { + case <-finished: + case <-time.After(40 * time.Second): + t.Error("canceled migration did not finish during test cleanup") + } + }() + var interruptedUploadID string + select { + case interruptedUploadID = <-partAccepted: + case err := <-runResult: + t.Fatalf("migration ended before RustFS accepted a multipart part: %v", err) + case <-time.After(time.Minute): + t.Fatal("RustFS did not accept an UploadPart within one minute") + } + // Removing the fault does not change the endpoint bound in SQLite. The + // already held response still waits for cancellation, while abort/retry + // requests are forwarded normally. + injectFailure.Store(false) + stopRun() + select { + case err := <-runResult: + if err == nil || !errors.Is(err, context.Canceled) { + t.Fatalf("interrupted migration must return cancellation, got %v", err) + } + case <-time.After(40 * time.Second): + t.Fatal("migration did not stop and abort after cancellation") + } + counts, err := st.Counts() + if err != nil || counts.Total != 1 || counts.Failed != 1 || counts.Done != 0 || counts.Skipped != 0 || counts.Conflict != 0 { + t.Fatalf("cancellation lost retryable checkpoint: counts=%+v err=%v", counts, err) + } + if successfulAborts.Load() == 0 { + t.Fatal("cancellation did not receive a successful real AbortMultipartUpload response") + } + if _, err := directTarget.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}); !s3client.IsNotFound(err) { + t.Fatalf("cancellation unexpectedly committed a target object: %v", err) + } + assertNoMultipartUploads := func(stage string) { + t.Helper() + listing, err := directTarget.ListMultipartUploads(ctx, &s3.ListMultipartUploadsInput{Bucket: aws.String(bucket)}) + if err != nil { + t.Fatalf("%s: cannot verify multipart cleanup: %v", stage, err) + } + if aws.ToBool(listing.IsTruncated) || len(listing.Uploads) != 0 { + t.Fatalf("%s: incomplete uploads remain after abort/complete: %+v", stage, listing.Uploads) + } + } + assertNoMultipartUploads("canceled run") + t.Logf("canceled after RustFS accepted a part; upload=%q aborts=%d checkpoint failed=%d", interruptedUploadID, successfulAborts.Load(), counts.Failed) + if err := active.Close(); err != nil { + t.Fatal(err) + } + active = nil + if err := st.Close(); err != nil { + t.Fatal(err) + } + st = nil + + // Reopen the same durable inventory and resume directly: no rescan, no + // manual state changes, and no replacement of the target proxy endpoint. + st, err = store.Open(cfg.DBPath, bucket) + if err != nil { + t.Fatal(err) + } + pending, err := st.BatchPendingAfter("", 10) + if err != nil || len(pending) != 1 || pending[0].Key != key || pending[0].Status != store.StatusFailed { + t.Fatalf("reopened checkpoint is not retryable: objects=%+v err=%v", pending, err) + } + active, err = New(cfg, src, dst, st) + if err != nil { + t.Fatal(err) + } + if err := active.Run(ctx); err != nil { + t.Fatalf("resume after reopening checkpoint: %v", err) + } + counts, err = st.Counts() + if err != nil || counts.Total != 1 || counts.Done != 1 || counts.Pending != 0 || counts.Failed != 0 || counts.Conflict != 0 || counts.Skipped != 0 { + t.Fatalf("recovered checkpoint not complete: counts=%+v err=%v", counts, err) + } + for name, cli := range map[string]*s3.Client{"source": src, "target": directTarget} { + object, err := cli.GetObject(ctx, &s3.GetObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}) + if err != nil { + t.Fatal(err) + } + hash := sha256.New() + n, readErr := io.Copy(hash, object.Body) + closeErr := object.Body.Close() + if readErr != nil || closeErr != nil || n != int64(len(payload)) || !bytes.Equal(hash.Sum(nil), wantDigest[:]) { + t.Fatalf("%s SHA256/length mismatch after recovery: bytes=%d read=%v close=%v", name, n, readErr, closeErr) + } + } + result, err := differ.Run(ctx, src, dst, bucket, differ.Options{Workers: 2, ReportExtra: true, Writer: io.Discard}) + if err != nil || result.HasGaps() || result.OK != 1 || result.Extra != 0 { + t.Fatalf("recovery verification failed: result=%+v err=%v", result, err) + } + assertNoMultipartUploads("recovered run") + t.Logf("resumed from reopened SQLite via unchanged endpoint; bytes=%d sha256=%x diff_ok=%d", len(payload), wantDigest, result.OK) +} diff --git a/internal/migrator/real_s3_response_loss_test.go b/internal/migrator/real_s3_response_loss_test.go new file mode 100644 index 0000000..c2aef6e --- /dev/null +++ b/internal/migrator/real_s3_response_loss_test.go @@ -0,0 +1,226 @@ +//go:build real_s3 + +package migrator + +import ( + "bytes" + "context" + "crypto/sha256" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/http/httputil" + "net/url" + "path/filepath" + "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/cluster" + "github.com/rustfs/migration/internal/config" + "github.com/rustfs/migration/internal/differ" + "github.com/rustfs/migration/internal/s3client" + "github.com/rustfs/migration/internal/scanner" + "github.com/rustfs/migration/internal/store" +) + +// A genuine successful RustFS commit is hidden from the caller exactly once. +// The SDK retries the conditional write, which can now return 412/409 or +// NoSuchUpload. That response must not turn our own committed object into a +// permanent conflict. Both runs use the same proxy endpoint and SQLite file. +func TestRealS3CommittedResponseLossRecoversFromCheckpoint(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + source := realConditionClient(t, ctx, "AUDIT_SOURCE") + directTarget := realConditionClient(t, ctx, "AUDIT_TARGET") + if aws.ToString(source.Options().BaseEndpoint) == aws.ToString(directTarget.Options().BaseEndpoint) { + t.Fatal("response-loss test requires separate source and target nodes") + } + for _, multipart := range []bool{false, true} { + t.Run(fmt.Sprintf("multipart=%t", multipart), func(t *testing.T) { + const partSize = 5 * 1024 * 1024 + const key = "lost-response.bin" + const businessKey = "business-preserved.txt" + bucket := fmt.Sprintf("migration-response-loss-%d", time.Now().UnixNano()) + for _, client := range []*s3.Client{source, directTarget} { + if err := cluster.EnsureBucket(ctx, client, bucket); err != nil { + t.Fatal(err) + } + } + size := 1024 + if multipart { + size = 2 * partSize // Two legal 5 MiB parts. + } + payload := bytes.Repeat([]byte{0x6d}, size) + for i := 0; i < len(payload); i += 4093 { + payload[i] = byte(i / 4093) + } + if _, err := source.PutObject(ctx, &s3.PutObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(key), Body: bytes.NewReader(payload), + ContentLength: aws.Int64(int64(len(payload))), ContentType: aws.String("application/x-response-loss"), + CacheControl: aws.String("max-age=60"), Metadata: map[string]string{"recovery": "response-loss"}, + }); err != nil { + t.Fatal(err) + } + business := []byte("existing business object must not be rewritten by retries") + for _, client := range []*s3.Client{source, directTarget} { + realConditionPut(t, ctx, client, bucket, businessKey, business) + } + sourceHead, err := source.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}) + if err != nil { + t.Fatal(err) + } + + upstream, err := url.Parse(aws.ToString(directTarget.Options().BaseEndpoint)) + if err != nil { + t.Fatal(err) + } + proxy := httputil.NewSingleHostReverseProxy(upstream) + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + proxy.Transport = transport + defer transport.CloseIdleConnections() + isCommit := func(request *http.Request) bool { + if request.URL.Path != "/"+bucket+"/"+key { + return false + } + query := request.URL.Query() + if multipart { + return request.Method == http.MethodPost && query.Get("uploadId") != "" + } + return request.Method == http.MethodPut && query.Get("uploadId") == "" + } + var attempts, committed, injected, businessWrites atomic.Int32 + proxy.ModifyResponse = func(response *http.Response) error { + if !isCommit(response.Request) || response.StatusCode < 200 || response.StatusCode >= 300 { + return nil + } + committed.Add(1) + if !injected.CompareAndSwap(0, 1) { + return nil + } + // Read the real upstream acknowledgement completely before + // replacing it. No failure is injected before RustFS commits. + _, readErr := io.Copy(io.Discard, response.Body) + closeErr := response.Body.Close() + if readErr != nil || closeErr != nil { + return fmt.Errorf("read actual committed response: read=%v close=%v", readErr, closeErr) + } + body := `InternalErrorlocal audit discarded a successful commit response` + response.StatusCode = http.StatusInternalServerError + response.Status = "500 Internal Server Error" + response.Header = make(http.Header) + response.Header.Set("Content-Type", "application/xml") + response.Header.Set("Content-Length", fmt.Sprint(len(body))) + response.ContentLength = int64(len(body)) + response.TransferEncoding, response.Trailer = nil, nil + response.Body = io.NopCloser(strings.NewReader(body)) + return nil + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if isCommit(r) { + attempts.Add(1) + } + if r.URL.Path == "/"+bucket+"/"+businessKey && (r.Method == http.MethodPut || r.Method == http.MethodPost || r.Method == http.MethodDelete) { + businessWrites.Add(1) + } + proxy.ServeHTTP(w, r) + })) + defer server.Close() + target, err := s3client.New(ctx, config.Endpoint{ + Endpoint: server.URL, Region: "us-east-1", AccessKey: "audit-local", SecretKey: "audit-local-secret", + }) + if err != nil { + t.Fatal(err) + } + // Exercise an SDK retry independently of inherited AWS_MAX_ATTEMPTS. + target = s3.New(target.Options(), func(options *s3.Options) { + options.Retryer = retry.NewStandard(func(options *retry.StandardOptions) { + options.MaxAttempts = 3 + options.MaxBackoff = 100 * time.Millisecond + }) + }) + dir := t.TempDir() + cfg := &config.Config{ + SourceFrozen: true, Bucket: bucket, DBPath: filepath.Join(dir, "checkpoint.db"), + ConflictLog: filepath.Join(dir, "conflict.log"), SpoolDir: dir, + Workers: 1, MultipartThreshold: partSize, MultipartPartSize: partSize, MultipartConcurrency: 2, + } + st, err := store.Open(cfg.DBPath, bucket) + if err != nil { + t.Fatal(err) + } + defer func() { + if st != nil { + _ = st.Close() + } + }() + if _, err := scanner.Run(ctx, source, bucket, st); err != nil { + t.Fatal(err) + } + migration, err := New(cfg, source, target, st) + if err != nil { + t.Fatal(err) + } + firstErr := migration.Run(ctx) + if err := migration.Close(); err != nil { + t.Fatal(err) + } + firstCounts, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if injected.Load() != 1 || committed.Load() != 1 || attempts.Load() < 2 { + t.Fatalf("did not lose exactly one successful commit and retry: injected=%d committed=%d attempts=%d run=%v", injected.Load(), committed.Load(), attempts.Load(), firstErr) + } + if firstCounts.Conflict != 0 || firstCounts.Skipped != 0 { + t.Fatalf("lost success became a terminal conflict/skip: counts=%+v run=%v", firstCounts, firstErr) + } + // This proves the injected response followed a real object commit. + realConditionAssertObject(t, ctx, directTarget, bucket, key, payload) + t.Logf("real commit response replaced once; attempts=%d first_run=%v counts=%+v", attempts.Load(), firstErr, firstCounts) + if err := st.Close(); err != nil { + t.Fatal(err) + } + st = nil + + // No rescan or manual status edit: resume the same checkpoint and URL. + st, err = store.Open(cfg.DBPath, bucket) + if err != nil { + t.Fatal(err) + } + migration, err = New(cfg, source, target, st) + if err != nil { + t.Fatal(err) + } + err = migration.Run(ctx) + closeErr := migration.Close() + if err != nil || closeErr != nil { + t.Fatalf("reopen recovery failed: run=%v close=%v", err, closeErr) + } + counts, err := st.Counts() + if err != nil || counts.Total != 2 || counts.Done != 2 || counts.Pending != 0 || counts.Failed != 0 || counts.Conflict != 0 || counts.Skipped != 0 { + t.Fatalf("checkpoint not fully recovered: counts=%+v err=%v", counts, err) + } + if committed.Load() != 1 || businessWrites.Load() != 0 { + t.Fatalf("recovery rewrote an existing object: successful_commits=%d business_writes=%d", committed.Load(), businessWrites.Load()) + } + realConditionAssertObject(t, ctx, directTarget, bucket, key, payload) + realConditionAssertObject(t, ctx, directTarget, bucket, businessKey, business) + targetHead, err := directTarget.HeadObject(ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}) + if err != nil || !s3client.MetadataEqual(sourceHead, targetHead) { + t.Fatalf("metadata changed across response-loss recovery: err=%v", err) + } + result, err := differ.Run(ctx, source, target, bucket, differ.Options{Workers: 2, ReportExtra: true, Writer: io.Discard}) + if err != nil || result.HasGaps() || result.OK != 2 || result.Extra != 0 { + t.Fatalf("recovered diff failed: result=%+v err=%v", result, err) + } + t.Logf("reopened SQLite recovered without rewriting; multipart=%t bytes=%d sha256=%x diff_ok=%d", multipart, len(payload), sha256.Sum256(payload), result.OK) + }) + } +} diff --git a/internal/migrator/security_logging_test.go b/internal/migrator/security_logging_test.go new file mode 100644 index 0000000..310235f --- /dev/null +++ b/internal/migrator/security_logging_test.go @@ -0,0 +1,51 @@ +package migrator + +import ( + "bytes" + "errors" + "log" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/rustfs/migration/internal/store" +) + +func TestUntrustedKeyAndErrorCannotInjectLogs(t *testing.T) { + path := filepath.Join(t.TempDir(), "conflicts") + w, err := newConflictWriter(path) + if err != nil { + t.Fatal(err) + } + key := "object\nforged\x1b[31m\tend" + if err := w.Write(key, time.Time{}, time.Time{}); err != nil { + t.Fatal(err) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if strings.Count(string(data), "\n") != 1 || bytes.Contains(data, []byte{0x1b}) { + t.Fatalf("unsafe conflict log: %q", data) + } + + st, err := store.Open(filepath.Join(t.TempDir(), "state.db"), "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + var out bytes.Buffer + prev := log.Writer() + log.SetOutput(&out) + defer log.SetOutput(prev) + m := &Migrator{Store: st} + _ = m.markFailed(key, errors.New("server error\nforged\x1b[31m")) + if strings.Count(out.String(), "\n") != 1 || bytes.Contains(out.Bytes(), []byte{0x1b}) { + t.Fatalf("unsafe error log: %q", out.String()) + } +} diff --git a/internal/migrator/spool_budget.go b/internal/migrator/spool_budget.go new file mode 100644 index 0000000..6311e07 --- /dev/null +++ b/internal/migrator/spool_budget.go @@ -0,0 +1,55 @@ +package migrator + +import ( + "context" + "fmt" + "sync" + + "github.com/rustfs/migration/internal/config" +) + +// spoolBudget reserves the entire temporary file before downloading, so no +// collection of partial files can deadlock waiting for space to finish. +type spoolBudget struct { + mu sync.Mutex + limit, used int64 + changed chan struct{} +} + +func newSpoolBudget(limit int64) *spoolBudget { + if limit == 0 { + limit = config.DefaultSpoolMaxBytes + } + return &spoolBudget{limit: limit, changed: make(chan struct{})} +} + +func (b *spoolBudget) acquire(ctx context.Context, size int64) (func(), error) { + if size < 0 || size > b.limit { + return nil, fmt.Errorf("spool reservation %d exceeds spool_max_bytes %d; increase budget or reduce part size", size, b.limit) + } + for { + b.mu.Lock() + if err := ctx.Err(); err != nil { + b.mu.Unlock() + return nil, err + } + if size <= b.limit-b.used { + b.used += size + b.mu.Unlock() + return func() { + b.mu.Lock() + b.used -= size + close(b.changed) + b.changed = make(chan struct{}) + b.mu.Unlock() + }, nil + } + changed := b.changed + b.mu.Unlock() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-changed: + } + } +} diff --git a/internal/migrator/spool_budget_test.go b/internal/migrator/spool_budget_test.go new file mode 100644 index 0000000..87c0141 --- /dev/null +++ b/internal/migrator/spool_budget_test.go @@ -0,0 +1,67 @@ +package migrator + +import ( + "context" + "errors" + "testing" + "time" +) + +func TestSpoolBudgetWaitReleaseAndCancellation(t *testing.T) { + b := newSpoolBudget(10) + release, err := b.acquire(context.Background(), 8) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + waiting := make(chan error, 1) + go func() { _, err := b.acquire(ctx, 3); waiting <- err }() + select { + case err := <-waiting: + t.Fatalf("reservation did not wait: %v", err) + case <-time.After(20 * time.Millisecond): + } + cancel() + if err := <-waiting; !errors.Is(err, context.Canceled) { + t.Fatalf("wait cancellation: %v", err) + } + ready := make(chan func(), 1) + go func() { + done, err := b.acquire(context.Background(), 10) + if err == nil { + ready <- done + } + }() + select { + case <-ready: + t.Fatal("reservation exceeded limit") + case <-time.After(20 * time.Millisecond): + } + release() + select { + case done := <-ready: + done() + case <-time.After(time.Second): + t.Fatal("release did not wake waiter") + } + if _, err := b.acquire(context.Background(), 11); err == nil { + t.Fatal("oversized reservation succeeded") + } +} + +func TestSpoolBudgetRejectsOversizedObjectBeforeCopy(t *testing.T) { + source := auditServer(t, map[string][]byte{"key": []byte("1234567890")}) + target := auditServer(t, nil) + m, st := auditMigration(t, source.URL, target.URL) + m.spoolBudget = newSpoolBudget(10) // data needs 10 bytes plus 1 byte for length checking + if err := m.Run(context.Background()); err == nil { + t.Fatal("expected budget failure") + } + counts, err := st.Counts() + if err != nil || counts.Failed != 1 { + t.Fatalf("expected retryable failure: counts=%+v err=%v", counts, err) + } + if _, ok := target.Object("bucket", "key"); ok { + t.Fatal("oversized object was copied") + } +} diff --git a/internal/s3client/audit_errors_test.go b/internal/s3client/audit_errors_test.go new file mode 100644 index 0000000..590232c --- /dev/null +++ b/internal/s3client/audit_errors_test.go @@ -0,0 +1,21 @@ +package s3client + +import ( + "errors" + "net/url" + "testing" +) + +// A transport failure is not an S3 response, even when the object key happens +// to contain an S3 error name. Treating it as 404 bypasses the target guard or +// makes a source object permanently skipped. +func TestAuditTransportFailureIsNotObjectNotFound(t *testing.T) { + for _, key := range []string{"NotFound-report", "NoSuchKey-report", "NoSuchBucket-report"} { + t.Run(key, func(t *testing.T) { + err := &url.Error{Op: "Head", URL: "https://s3.example/bucket/" + key, Err: errors.New("connection reset by peer")} + if IsNotFound(err) { + t.Fatalf("transport failure misclassified as completed 404: %v", err) + } + }) + } +} diff --git a/internal/s3client/client.go b/internal/s3client/client.go index 9f6cc8b..c1b2c59 100644 --- a/internal/s3client/client.go +++ b/internal/s3client/client.go @@ -3,8 +3,10 @@ package s3client import ( "context" "fmt" + "net" "net/http" "os" + "time" awsv2 "github.com/aws/aws-sdk-go-v2/aws" awsconfig "github.com/aws/aws-sdk-go-v2/config" @@ -37,9 +39,9 @@ func NewWithPool(ctx context.Context, ep config.Endpoint, idlePerHost int) (*s3. cfg, err := awsconfig.LoadDefaultConfig(ctx, awsconfig.WithRegion(ep.Region), awsconfig.WithCredentialsProvider( - credentials.NewStaticCredentialsProvider(ep.AccessKey, ep.SecretKey, ""), + credentials.NewStaticCredentialsProvider(ep.AccessKey, ep.SecretKey, ep.SessionToken), ), - awsconfig.WithHTTPClient(&http.Client{Transport: pooledTransport(idlePerHost)}), + awsconfig.WithHTTPClient(&http.Client{Transport: idleTimeoutTransport{base: pooledTransport(idlePerHost), timeout: 90 * time.Second}}), ) if err != nil { return nil, fmt.Errorf("aws config: %w", err) @@ -48,6 +50,10 @@ func NewWithPool(ctx context.Context, ep config.Endpoint, idlePerHost int) (*s3. client := s3.NewFromConfig(cfg, func(o *s3.Options) { o.BaseEndpoint = awsv2.String(ep.Endpoint) o.UsePathStyle = true + // Avoid assuming optional checksum extensions on S3-compatible servers. + // Migration and diff verify full SHA-256 content independently. + o.RequestChecksumCalculation = awsv2.RequestChecksumCalculationWhenRequired + o.ResponseChecksumValidation = awsv2.ResponseChecksumValidationWhenRequired }) return client, nil } @@ -69,6 +75,23 @@ func pooledTransport(idlePerHost int) *http.Transport { tr = &http.Transport{} } tr.MaxIdleConnsPerHost = idlePerHost + tr.ResponseHeaderTimeout = 30 * time.Second + // HTTP/1 gives each upload its own connection write deadline. HTTP/2 + // stream flow-control waits cannot be bounded by a socket WriteDeadline. + tr.ForceAttemptHTTP2 = false + tr.Protocols = new(http.Protocols) + tr.Protocols.SetHTTP1(true) + dial := tr.DialContext + if dial == nil { + dial = (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext + } + tr.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) { + conn, err := dial(ctx, network, address) + if err != nil { + return nil, err + } + return &writeTimeoutConn{Conn: conn, timeout: 90 * time.Second}, nil + } if tr.MaxIdleConns < idlePerHost*2 { tr.MaxIdleConns = idlePerHost * 2 } diff --git a/internal/s3client/errors.go b/internal/s3client/errors.go index 906c51f..599376c 100644 --- a/internal/s3client/errors.go +++ b/internal/s3client/errors.go @@ -4,7 +4,6 @@ import ( "context" "errors" "net" - "net/http" "strings" "syscall" @@ -53,35 +52,42 @@ func IsCanceled(err error) bool { // 404s (NoSuchBucket) across the typed and untyped shapes aws-sdk-go-v2 // returns against self-hosted S3 implementations. // -// NoSuchUpload refers to an upload ID. A URL or key in a transport error -// can contain any text, including "NoSuchKey", without being a 404. +// Only structured API codes or an actual HTTP response are evidence of a 404. +// Object keys and proxy messages in error text must never authorize a write. func IsNotFound(err error) bool { if err == nil || IsCanceled(err) { return false } + var nsk *s3types.NoSuchKey + if errors.As(err, &nsk) { + return true + } + var nf *s3types.NotFound + if errors.As(err, &nf) { + return true + } + var nsb *s3types.NoSuchBucket + if errors.As(err, &nsb) { + return true + } var ae smithy.APIError if errors.As(err, &ae) { switch ae.ErrorCode() { case "NoSuchKey", "NotFound", "NoSuchBucket", "404": return true case "": - // Some HEAD responses have an HTTP status and no S3 error code. + // A HEAD response may have no body or API code. default: + // Completed response for some other code, such as NoSuchUpload. return false } } var response interface{ HTTPStatusCode() int } - if errors.As(err, &response) { - return response.HTTPStatusCode() == http.StatusNotFound - } - // Also recognize the old, unwrapped SDK response format. - msg := err.Error() - return strings.HasPrefix(msg, "https response error StatusCode: 404,") && - !strings.Contains(msg, "NoSuchUpload") + return errors.As(err, &response) && response.HTTPStatusCode() == 404 } -// IsAlreadyOwned recognizes a concurrent creation by the same owner. -func IsAlreadyOwned(err error) bool { +// IsAlreadyExists matches CreateBucket when the bucket is already there. +func IsAlreadyExists(err error) bool { if err == nil { return false } @@ -98,3 +104,6 @@ func IsAlreadyOwned(err error) bool { } return false } + +// IsAlreadyOwned is the explicit ownership-specific name. +func IsAlreadyOwned(err error) bool { return IsAlreadyExists(err) } diff --git a/internal/s3client/errors_test.go b/internal/s3client/errors_test.go index f945232..32cfd71 100644 --- a/internal/s3client/errors_test.go +++ b/internal/s3client/errors_test.go @@ -75,8 +75,8 @@ func TestCanceledRequestIsNotSource404(t *testing.T) { if !IsNotFound(&s3types.NotFound{}) { t.Fatal("typed NotFound") } - if !IsNotFound(errors.New("https response error StatusCode: 404, RequestID: z, NotFound")) { - t.Fatal("completed untyped 404") + if IsNotFound(errors.New("https response error StatusCode: 404, RequestID: z, NotFound")) { + t.Fatal("text without a structured HTTP response is not evidence of 404") } upload404 := fmt.Errorf("upload part 1: https response error StatusCode: 404, RequestID: r, HostID: h, %w", &s3types.NoSuchUpload{}) if IsNotFound(upload404) { @@ -84,14 +84,20 @@ func TestCanceledRequestIsNotSource404(t *testing.T) { } } -func TestIsAlreadyOwned(t *testing.T) { - if IsAlreadyOwned(&s3types.BucketAlreadyExists{}) { - t.Fatal("a bucket owned by someone else must not be accepted") +func TestIsAlreadyExists(t *testing.T) { + if IsAlreadyExists(&s3types.BucketAlreadyExists{}) { + t.Fatal("foreign bucket ownership must not be accepted") } - if !IsAlreadyOwned(&s3types.BucketAlreadyOwnedByYou{}) { + if !IsAlreadyExists(&s3types.BucketAlreadyOwnedByYou{}) { t.Fatal("owned") } - if IsAlreadyOwned(errors.New("nope")) { + if IsAlreadyExists(errors.New("nope")) { t.Fatal("plain") } } + +func TestIsAlreadyOwned(t *testing.T) { + if IsAlreadyOwned(&s3types.BucketAlreadyExists{}) || !IsAlreadyOwned(&s3types.BucketAlreadyOwnedByYou{}) { + t.Fatal("incorrect bucket ownership classification") + } +} diff --git a/internal/s3client/integrity.go b/internal/s3client/integrity.go new file mode 100644 index 0000000..ae96726 --- /dev/null +++ b/internal/s3client/integrity.go @@ -0,0 +1,54 @@ +package s3client + +import ( + "context" + "crypto/sha256" + "fmt" + "io" + "math" + "strings" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" +) + +// Digest reads a specific object representation and verifies its exact length. +// ETags are opaque concurrency tokens, never treated as content digests. +func Digest(ctx context.Context, cli *s3.Client, bucket, key string, size int64, etag string) ([32]byte, error) { + return DigestWithReader(ctx, cli, bucket, key, size, etag, nil) +} + +// DigestWithReader permits a caller to apply its aggregate read-rate limiter. +func DigestWithReader(ctx context.Context, cli *s3.Client, bucket, key string, size int64, etag string, wrap func(io.Reader) io.Reader) ([32]byte, error) { + var digest [32]byte + if size < 0 || size == math.MaxInt64 || strings.Trim(etag, `"`) == "" { + return digest, fmt.Errorf("cannot verify object without valid size and ETag") + } + out, err := cli.GetObject(ctx, &s3.GetObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(key), IfMatch: aws.String(etag), + }) + if err != nil { + return digest, err + } + defer out.Body.Close() + if out.ContentLength == nil || *out.ContentLength != size { + return digest, fmt.Errorf("digest content length mismatch: got=%v want=%d", out.ContentLength, size) + } + if strings.Trim(aws.ToString(out.ETag), `"`) != strings.Trim(etag, `"`) { + return digest, fmt.Errorf("object ETag changed during digest") + } + var reader io.Reader = out.Body + if wrap != nil { + reader = wrap(reader) + } + h := sha256.New() + n, err := io.Copy(h, io.LimitReader(reader, size+1)) + if err != nil { + return digest, fmt.Errorf("read digest body: %w", err) + } + if n != size { + return digest, fmt.Errorf("digest body length mismatch: got=%d want=%d", n, size) + } + copy(digest[:], h.Sum(nil)) + return digest, nil +} diff --git a/internal/s3client/integrity_test.go b/internal/s3client/integrity_test.go new file mode 100644 index 0000000..43d3881 --- /dev/null +++ b/internal/s3client/integrity_test.go @@ -0,0 +1,61 @@ +package s3client + +import ( + "context" + "crypto/sha256" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/rustfs/migration/internal/config" +) + +func TestDigestPinsRepresentationAndChecksExactBytes(t *testing.T) { + for _, tc := range []struct { + name, body, responseETag string + wantSize, declaredSize int64 + wantError bool + }{ + {"valid", "abc", `"opaque"`, 3, 3, false}, + {"empty", "", `"opaque"`, 0, 0, false}, + {"truncated", "abc", `"opaque"`, 10, 10, true}, + {"oversized", "abcd", `"opaque"`, 3, 4, true}, + {"changed-etag", "abc", `"changed"`, 3, 3, true}, + {"missing-etag", "abc", "", 3, 3, true}, + } { + t.Run(tc.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("If-Match") != `"opaque"` { + t.Errorf("unconditional digest read: %v", r.Header) + } + w.Header().Set("Content-Length", fmt.Sprint(tc.declaredSize)) + if tc.responseETag != "" { + w.Header().Set("ETag", tc.responseETag) + } + _, _ = w.Write([]byte(tc.body)) + })) + defer server.Close() + client, err := New(context.Background(), config.Endpoint{Endpoint: server.URL, Region: "us-east-1", AccessKey: "test", SecretKey: "test"}) + if err != nil { + t.Fatal(err) + } + got, err := Digest(context.Background(), client, "bucket", "key", tc.wantSize, `"opaque"`) + if (err != nil) != tc.wantError { + t.Fatalf("digest error=%v wantError=%t", err, tc.wantError) + } + if !tc.wantError && got != sha256.Sum256([]byte(tc.body)) { + t.Fatal("incorrect SHA256") + } + }) + } +} + +func TestDigestRejectsUnpinnedReadsBeforeNetwork(t *testing.T) { + // Nil client deliberately proves missing identity is rejected before I/O. + _, err := Digest(context.Background(), nil, "bucket", "key", 3, "") + if err == nil || !strings.Contains(err.Error(), "ETag") { + t.Fatalf("missing identity: %v", err) + } +} diff --git a/internal/s3client/metadata.go b/internal/s3client/metadata.go new file mode 100644 index 0000000..8547909 --- /dev/null +++ b/internal/s3client/metadata.go @@ -0,0 +1,34 @@ +package s3client + +import ( + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" +) + +// 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. +func MetadataEqual(a, b *s3.HeadObjectOutput) bool { + if a == nil || b == nil { + return false + } + if aws.ToString(a.CacheControl) != aws.ToString(b.CacheControl) || + aws.ToString(a.ContentType) != aws.ToString(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)) { + return false + } + if len(a.Metadata) != len(b.Metadata) { + return false + } + for key, value := range a.Metadata { + if other, ok := b.Metadata[key]; !ok || other != value { + return false + } + } + return true +} diff --git a/internal/s3client/metadata_test.go b/internal/s3client/metadata_test.go new file mode 100644 index 0000000..eaf4c3e --- /dev/null +++ b/internal/s3client/metadata_test.go @@ -0,0 +1,49 @@ +package s3client + +import ( + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/s3" +) + +func TestMetadataEqualPreservedFields(t *testing.T) { + expires := time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC) + source := &s3.HeadObjectOutput{ + CacheControl: aws.String("max-age=30"), ContentType: aws.String("application/json"), + ContentEncoding: aws.String("gzip"), ContentDisposition: aws.String("inline"), + ContentLanguage: aws.String("en"), Expires: &expires, + Metadata: map[string]string{"origin": "source"}, ETag: aws.String("source-token"), + } + mutations := map[string]func(*s3.HeadObjectOutput){ + "cache-control": func(h *s3.HeadObjectOutput) { h.CacheControl = aws.String("no-store") }, + "content-type": func(h *s3.HeadObjectOutput) { h.ContentType = aws.String("text/html") }, + "encoding": func(h *s3.HeadObjectOutput) { h.ContentEncoding = nil }, + "disposition": func(h *s3.HeadObjectOutput) { h.ContentDisposition = aws.String("attachment") }, + "language": func(h *s3.HeadObjectOutput) { h.ContentLanguage = aws.String("zh") }, + "expires-missing": func(h *s3.HeadObjectOutput) { h.Expires = nil }, + "expires-changed": func(h *s3.HeadObjectOutput) { h.Expires = aws.Time(expires.Add(time.Second)) }, + "metadata-value": func(h *s3.HeadObjectOutput) { h.Metadata = map[string]string{"origin": "different"} }, + "metadata-key": func(h *s3.HeadObjectOutput) { h.Metadata = map[string]string{"other": "source"} }, + "metadata-missing": func(h *s3.HeadObjectOutput) { h.Metadata = nil }, + } + for name, mutate := range mutations { + t.Run(name, func(t *testing.T) { + target := *source + mutate(&target) + if MetadataEqual(source, &target) || MetadataEqual(&target, source) { + t.Fatal("different preserved metadata accepted") + } + }) + } + target := *source + target.ETag = aws.String("different-target-token") + target.LastModified = aws.Time(expires.Add(time.Hour)) + if !MetadataEqual(source, &target) { + t.Fatal("ETag and LastModified are not preserved metadata") + } + if MetadataEqual(nil, source) || MetadataEqual(source, nil) { + t.Fatal("missing HEAD response cannot match metadata") + } +} diff --git a/internal/s3client/timeout.go b/internal/s3client/timeout.go new file mode 100644 index 0000000..d7903c0 --- /dev/null +++ b/internal/s3client/timeout.go @@ -0,0 +1,60 @@ +package s3client + +import ( + "context" + "io" + "net" + "net/http" + "time" +) + +type writeTimeoutConn struct { + net.Conn + timeout time.Duration +} + +func (c *writeTimeoutConn) Write(p []byte) (int, error) { + if err := c.Conn.SetWriteDeadline(time.Now().Add(c.timeout)); err != nil { + return 0, err + } + n, err := c.Conn.Write(p) + _ = c.Conn.SetWriteDeadline(time.Time{}) + return n, err +} + +// Bound individual blocked network reads, not time spent pacing a source body. +// A slow configured bandwidth cap must not trip the idle watchdog between reads. +type idleTimeoutTransport struct { + base http.RoundTripper + timeout time.Duration +} + +func (t idleTimeoutTransport) RoundTrip(req *http.Request) (*http.Response, error) { + ctx, cancel := context.WithCancelCause(req.Context()) + resp, err := t.base.RoundTrip(req.Clone(ctx)) + if err != nil { + cancel(err) + return nil, err + } + resp.Body = &idleTimeoutBody{ReadCloser: resp.Body, ctx: ctx, cancel: cancel, timeout: t.timeout} + return resp, nil +} + +type idleTimeoutBody struct { + io.ReadCloser + ctx context.Context + cancel context.CancelCauseFunc + timeout time.Duration +} + +func (b *idleTimeoutBody) Read(p []byte) (int, error) { + timer := time.AfterFunc(b.timeout, func() { b.cancel(context.DeadlineExceeded) }) + n, err := b.ReadCloser.Read(p) + timer.Stop() + if err != nil && context.Cause(b.ctx) != nil { + return n, context.Cause(b.ctx) + } + return n, err +} + +func (b *idleTimeoutBody) Close() error { b.cancel(nil); return b.ReadCloser.Close() } diff --git a/internal/s3client/timeout_test.go b/internal/s3client/timeout_test.go new file mode 100644 index 0000000..08b57cf --- /dev/null +++ b/internal/s3client/timeout_test.go @@ -0,0 +1,66 @@ +package s3client + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestStalledUploadWriteTimesOut(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + conn := &writeTimeoutConn{Conn: client, timeout: 30 * time.Millisecond} + _, err := conn.Write([]byte("the peer never reads")) + var timeout net.Error + if !errors.As(err, &timeout) || !timeout.Timeout() { + t.Fatalf("stalled upload: %v", err) + } +} + +func TestStalledBodyReadTimesOut(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "100") + w.WriteHeader(200) + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + defer s.Close() + c := &http.Client{Transport: idleTimeoutTransport{base: http.DefaultTransport, timeout: 30 * time.Millisecond}} + resp, err := c.Get(s.URL) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + _, err = io.ReadAll(resp.Body) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("stalled read: %v", err) + } +} + +func TestBandwidthPacingBetweenReadsDoesNotTimeOut(t *testing.T) { + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, "ab") })) + defer s.Close() + c := &http.Client{Transport: idleTimeoutTransport{base: http.DefaultTransport, timeout: 30 * time.Millisecond}} + resp, err := c.Get(s.URL) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + buf := make([]byte, 1) + if _, err = io.ReadFull(resp.Body, buf); err != nil { + t.Fatal(err) + } + time.Sleep(60 * time.Millisecond) + if _, err = io.ReadFull(resp.Body, buf); err != nil { + t.Fatal(err) + } + if buf[0] != 'b' { + t.Fatal("wrong body") + } +} diff --git a/internal/safeoutput/safeoutput.go b/internal/safeoutput/safeoutput.go new file mode 100644 index 0000000..2ca508f --- /dev/null +++ b/internal/safeoutput/safeoutput.go @@ -0,0 +1,23 @@ +// Package safeoutput escapes control characters in untrusted terminal output. +package safeoutput + +import ( + "strconv" + "strings" + "unicode" +) + +// Escape makes text safe to print on one terminal line without changing the +// underlying error value or its wrapping chain. +func Escape(s string) string { + var out strings.Builder + for _, r := range s { + if unicode.IsPrint(r) { + out.WriteRune(r) + } else { + q := strconv.QuoteRune(r) + out.WriteString(q[1 : len(q)-1]) + } + } + return out.String() +} diff --git a/internal/safeoutput/safeoutput_test.go b/internal/safeoutput/safeoutput_test.go new file mode 100644 index 0000000..2f79797 --- /dev/null +++ b/internal/safeoutput/safeoutput_test.go @@ -0,0 +1,11 @@ +package safeoutput + +import "testing" + +func TestEscape(t *testing.T) { + got := Escape("服务 \"x\"\nforged\x1b[31m\r\t\u202e") + want := "服务 \"x\"\\nforged\\x1b[31m\\r\\t\\u202e" + if got != want { + t.Fatalf("got %q, want %q", got, want) + } +} diff --git a/internal/scanner/audit_test.go b/internal/scanner/audit_test.go new file mode 100644 index 0000000..2fbeb68 --- /dev/null +++ b/internal/scanner/audit_test.go @@ -0,0 +1,315 @@ +package scanner_test + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/rustfs/migration/internal/cluster" + "github.com/rustfs/migration/internal/config" + "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 auditClient(t *testing.T, endpoint string) *s3.Client { + t.Helper() + cli, err := s3client.New(context.Background(), config.Endpoint{ + Endpoint: endpoint, Region: "us-east-1", AccessKey: "test", SecretKey: "test", + }) + if err != nil { + t.Fatal(err) + } + return cli +} + +func TestAuditResumeRejectsDifferentDestination(t *testing.T) { + ctx := context.Background() + source := fakes3.NewWithObjects(t, "bucket", map[string][]byte{"key": []byte("data")}, time.Unix(1, 0)) + defer source.Close() + first := fakes3.New(t) + defer first.Close() + second := fakes3.New(t) + defer second.Close() + oldCli := auditClient(t, source.URL) + dir := t.TempDir() + cfg := &config.Config{ + Bucket: "bucket", DBPath: filepath.Join(dir, "state.db"), ConflictLog: filepath.Join(dir, "conflicts.log"), + SourceFrozen: true, SpoolDir: dir, Workers: 1, MultipartThreshold: 1024, MultipartPartSize: 5 * 1024 * 1024, MultipartConcurrency: 1, + Old: config.Endpoint{Endpoint: source.URL}, New: config.Endpoint{Endpoint: first.URL}, + } + run := func(target *fakes3.Server) error { + st, err := store.Open(cfg.DBPath, cfg.Bucket) + if err != nil { + return err + } + defer st.Close() + if _, err := scanner.Run(ctx, oldCli, cfg.Bucket, st); err != nil { + return err + } + newCli := auditClient(t, target.URL) + if err := cluster.EnsureBucket(ctx, newCli, cfg.Bucket); err != nil { + return err + } + m, err := migrator.New(cfg, oldCli, newCli, st) + if err != nil { + return err + } + defer m.Close() + return m.Run(ctx) + } + if err := run(first); err != nil { + t.Fatal(err) + } + if body, ok := first.Object(cfg.Bucket, "key"); !ok || string(body) != "data" { + t.Fatal("initial migration did not establish the completed checkpoint") + } + cfg.New.Endpoint = second.URL + err := run(second) + if _, ok := second.Object(cfg.Bucket, "key"); !ok && err == nil { + t.Fatal("reusing checkpoint with another target returned success but copied no object; DB is only bound to bucket name") + } +} + +// S3 permits object keys that cannot be represented in XML 1.0. Requesting +// encoding-type=url and decoding the returned key permits a complete inventory. +func TestAuditScanXMLUnsafeObjectKey(t *testing.T) { + const key = "before +\x01%after" + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + w.WriteHeader(http.StatusOK) + return + } + w.Header().Set("Content-Type", "application/xml") + encodedKey, encoding := key, "" + if r.URL.Query().Get("encoding-type") == "url" { + encodedKey, encoding = "before+%20%2B%01%25after", "url" + } + _, _ = fmt.Fprintf(w, `bucketfalse%s%s1abc2026-01-01T00:00:00Z`, encoding, encodedKey) + })) + defer srv.Close() + st, err := store.Open(filepath.Join(t.TempDir(), "state.db"), "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + if _, err := scanner.Run(context.Background(), auditClient(t, srv.URL), "bucket", st); err != nil { + t.Fatalf("legal object key cannot be inventoried: %v", err) + } + batch, err := st.BatchPendingAfter("", 10) + if err != nil || len(batch) != 1 || batch[0].Key != key { + t.Fatalf("key not preserved: rows=%+v err=%v", batch, err) + } +} + +func TestAuditScanContinuationAcrossBatchBoundary(t *testing.T) { + var calls atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + w.WriteHeader(http.StatusOK) + return + } + calls.Add(1) + w.Header().Set("Content-Type", "application/xml") + _, _ = io.WriteString(w, `bucket`) + start, end := 0, 1000 + if r.URL.Query().Get("continuation-token") == "next-page" { + start, end = 1000, 1501 + _, _ = io.WriteString(w, `false`) + } else { + _, _ = io.WriteString(w, `truenext-page`) + } + for i := start; i < end; i++ { + _, _ = fmt.Fprintf(w, `key-%04d1tag2026-01-01T00:00:00Z`, i) + } + _, _ = io.WriteString(w, ``) + })) + defer srv.Close() + st, err := store.Open(filepath.Join(t.TempDir(), "state.db"), "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + n, err := scanner.Run(context.Background(), auditClient(t, srv.URL), "bucket", st) + if err != nil { + t.Fatal(err) + } + c, err := st.Counts() + if err != nil || n != 1501 || c.Pending != 1501 || calls.Load() != 2 { + t.Fatalf("pagination lost or duplicated work: total=%d counts=%+v pages=%d err=%v", n, c, calls.Load(), err) + } +} + +func TestFailedRescanRequiresCompleteRetry(t *testing.T) { + var denySecond atomic.Bool + denySecond.Store(true) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + w.WriteHeader(http.StatusOK) + return + } + w.Header().Set("Content-Type", "application/xml") + if r.URL.Query().Get("continuation-token") == "second" { + if denySecond.Load() { + w.WriteHeader(http.StatusForbidden) + _, _ = io.WriteString(w, `AccessDenied`) + return + } + _, _ = io.WriteString(w, `bucketfalsez-last1`) + return + } + _, _ = io.WriteString(w, `buckettruesecond`) + for i := 0; i < 500; i++ { + _, _ = fmt.Fprintf(w, `key-%04d1`, i) + } + _, _ = io.WriteString(w, ``) + })) + defer srv.Close() + st, err := store.Open(filepath.Join(t.TempDir(), "state.db"), "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + if err := st.BeginScan(); err != nil { + t.Fatal(err) + } + if err := st.CompleteScan(); err != nil { + t.Fatal(err) + } + cli := auditClient(t, srv.URL) + if _, err := scanner.Run(context.Background(), cli, "bucket", st); err == nil { + t.Fatal("partial listing failure was hidden") + } + if err := st.RequireCompleteScan(); err == nil { + t.Fatal("failed rescan authorized migration of partial inventory") + } + c, err := st.Counts() + if err != nil || c.Pending != 500 { + t.Fatalf("first committed batch should remain resumable: %+v, %v", c, err) + } + denySecond.Store(false) + if n, err := scanner.Run(context.Background(), cli, "bucket", st); err != nil || n != 501 { + t.Fatalf("retry scan: n=%d err=%v", n, err) + } + if err := st.RequireCompleteScan(); err != nil { + t.Fatalf("successful retry not certified: %v", err) + } +} + +func TestScanRejectsInvalidContinuation(t *testing.T) { + for _, token := range []string{"", "repeated", "missing-truncation-flag"} { + t.Run("token="+token, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + w.WriteHeader(http.StatusOK) + return + } + w.Header().Set("Content-Type", "application/xml") + if token == "missing-truncation-flag" { + _, _ = io.WriteString(w, `bucket`) + return + } + _, _ = fmt.Fprintf(w, `buckettrue%s`, token) + })) + defer srv.Close() + st, err := store.Open(filepath.Join(t.TempDir(), "state.db"), "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := scanner.Run(ctx, auditClient(t, srv.URL), "bucket", st); err == nil { + t.Fatal("broken pagination marked complete") + } + if ctx.Err() != nil { + t.Fatal("scanner relied on deadline to escape broken pagination") + } + if err := st.RequireCompleteScan(); err == nil { + t.Fatal("broken pagination left completed generation") + } + }) + } +} + +func TestScanRejectsDifferentSourceBeforeInvalidatingInventory(t *testing.T) { + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + w.WriteHeader(http.StatusInternalServerError) + })) + defer srv.Close() + st, err := store.Open(filepath.Join(t.TempDir(), "state.db"), "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + if err := st.BindMigration("https://original-source.example", "https://target.example"); err != nil { + t.Fatal(err) + } + if err := st.BeginScan(); err != nil { + t.Fatal(err) + } + if err := st.BatchUpsertScanned([]store.Object{{Key: "original", Size: 4, ETag: "original-etag"}}); err != nil { + t.Fatal(err) + } + if err := st.CompleteScan(); err != nil { + t.Fatal(err) + } + if _, err := scanner.Run(context.Background(), auditClient(t, srv.URL), "bucket", st); err == nil { + t.Fatal("scan accepted a different source endpoint") + } + if requests.Load() != 0 { + t.Fatalf("mismatched source received %d requests", requests.Load()) + } + if err := st.RequireCompleteScan(); err != nil { + t.Fatalf("rejected source invalidated original complete scan: %v", err) + } + rows, err := st.BatchPendingAfter("", 10) + if err != nil || len(rows) != 1 || rows[0].Key != "original" || rows[0].ETag != "original-etag" { + t.Fatalf("rejected source changed inventory: %+v, %v", rows, err) + } +} + +func TestScanRejectsAlternatingContinuationTokens(t *testing.T) { + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodHead { + return + } + n := requests.Add(1) + w.Header().Set("Content-Type", "application/xml") + if n > 3 { + w.WriteHeader(http.StatusBadRequest) + return + } + next := "a" + if r.URL.Query().Get("continuation-token") == "a" { + next = "b" + } + fmt.Fprintf(w, `buckettrue%s`, next) + })) + defer srv.Close() + st, err := store.Open(filepath.Join(t.TempDir(), "state.db"), "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + _, err = scanner.Run(context.Background(), auditClient(t, srv.URL), "bucket", st) + if err == nil || !strings.Contains(err.Error(), "continuation token") || requests.Load() != 3 { + t.Fatalf("requests=%d err=%v", requests.Load(), err) + } + if err := st.RequireCompleteScan(); err == nil { + t.Fatal("cyclic scan was marked complete") + } +} diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go index e3a7f20..18ce4bc 100644 --- a/internal/scanner/scanner.go +++ b/internal/scanner/scanner.go @@ -4,11 +4,12 @@ import ( "context" "fmt" "log" + "net/url" "time" awsv2 "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/s3" - "github.com/aws/aws-sdk-go-v2/service/s3/types" + s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" "github.com/rustfs/migration/internal/cluster" "github.com/rustfs/migration/internal/store" @@ -18,17 +19,35 @@ const batchSize = 500 // Run lists every object in bucket on the source cluster and persists // metadata into the store. Full ListObjectsV2 (S3 has no LastModified -// server filter); re-runs only refresh pending/failed/skipped rows. +// server filter); changes invalidate previous completion for that key. // // Listing stays single-threaded on purpose: each page needs the previous // continuation token, and the rows land in one SQLite file. Object // concurrency (workers) applies to copy and diff, not to scan. // rate_limit applies to copy body reads only. func Run(ctx context.Context, cli *s3.Client, bucket string, st *store.Store) (int64, error) { - if err := st.SetScanComplete(false); err != nil { + bound, err := st.BoundBucket() + if err != nil { + return 0, err + } + if bound != bucket { + return 0, fmt.Errorf("scan bucket %q does not match state bucket %q", bucket, bound) + } + if err := st.BindMigration(awsv2.ToString(cli.Options().BaseEndpoint), ""); err != nil { + return 0, err + } + if err := st.BeginScan(); err != nil { + return 0, fmt.Errorf("begin scan: %w", err) + } + if err := cluster.HeadBucket(ctx, cli, bucket); err != nil { 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) @@ -45,11 +64,44 @@ func Run(ctx context.Context, cli *s3.Client, bucket string, st *store.Store) (i return nil } - err := cluster.WalkObjects(ctx, cli, bucket, func(objects []types.Object) error { - for _, obj := range objects { + 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) + } o := store.Object{ - Key: awsv2.ToString(obj.Key), - Size: *obj.Size, + Key: key, + Size: deref(obj.Size), ETag: awsv2.ToString(obj.ETag), } if obj.LastModified != nil { @@ -58,22 +110,28 @@ 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 err + return total, err } log.Printf("scan %s: %d objects (elapsed %s)", bucket, total, time.Since(start).Truncate(time.Second)) } } - return nil - }) - if err != nil { - return total, fmt.Errorf("scan %s: %w", bucket, err) } if err := flush(); err != nil { return total, err } - if err := st.SetScanComplete(true); err != nil { + if err := ctx.Err(); err != nil { return total, err } + if err := st.CompleteScan(); err != nil { + return total, fmt.Errorf("complete scan: %w", err) + } log.Printf("scan %s complete: %d objects in %s", bucket, total, time.Since(start).Truncate(time.Second)) return total, nil } + +func deref(p *int64) int64 { + if p == nil { + return 0 + } + return *p +} diff --git a/internal/store/audit_test.go b/internal/store/audit_test.go new file mode 100644 index 0000000..32b8aa5 --- /dev/null +++ b/internal/store/audit_test.go @@ -0,0 +1,245 @@ +package store + +import ( + "bufio" + "fmt" + "os" + "os/exec" + "path/filepath" + "testing" + "time" +) + +func TestMigrationBindingRejectsChangedClusters(t *testing.T) { + st, err := Open(filepath.Join(t.TempDir(), "state.db"), "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + if err := st.BindMigration("https://SOURCE.example/", ""); err != nil { + t.Fatal(err) + } + if err := st.BeginScan(); err != nil { + t.Fatal(err) + } + if err := st.BatchUpsertScanned([]Object{{Key: "key", Size: 4}}); err != nil { + t.Fatal(err) + } + if err := st.CompleteScan(); err != nil { + t.Fatal(err) + } + if err := st.BindMigration("https://source.example", "https://target.example/"); err != nil { + t.Fatal(err) + } + if err := st.MarkStatus("key", StatusDone, ""); err != nil { + t.Fatal(err) + } + if err := st.BindMigration("https://source.example", "https://target.example"); err != nil { + t.Fatalf("safe resume rejected: %v", err) + } + if err := st.BindMigration("https://other-source.example", "https://target.example"); err == nil { + t.Fatal("different source accepted") + } + if err := st.BindMigration("https://source.example", "https://other-target.example"); err == nil { + t.Fatal("different target accepted") + } +} + +func TestLegacyUnboundInventoryIsRejected(t *testing.T) { + st, err := Open(filepath.Join(t.TempDir(), "state.db"), "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + if err := st.BatchUpsertScanned([]Object{{Key: "key", Size: 4}}); err != nil { + t.Fatal(err) + } + if _, err := st.db.Exec(`DELETE FROM meta WHERE key='state_format'`); err != nil { + t.Fatal(err) + } + if err := st.BindMigration("https://source.example", "https://target.example"); err == nil { + t.Fatal("legacy unbound rows adopted without knowing their source") + } +} + +func TestInterruptedRescanInvalidatesPreviousInventory(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.db") + st, err := Open(path, "bucket") + if err != nil { + t.Fatal(err) + } + if err := st.RequireCompleteScan(); err == nil { + t.Fatal("new DB treated as scanned") + } + if err := st.CompleteScan(); err == nil { + t.Fatal("completion before scan accepted") + } + if err := st.BeginScan(); err != nil { + t.Fatal(err) + } + if err := st.CompleteScan(); err != nil { + t.Fatal(err) + } + if err := st.RequireCompleteScan(); err != nil { + t.Fatalf("empty completed bucket rejected: %v", err) + } + if err := st.BeginScan(); err != nil { + t.Fatal(err) + } + if err := st.BatchUpsertScanned([]Object{{Key: "partial", Size: 1}}); err != nil { + t.Fatal(err) + } + if err := st.Close(); err != nil { + t.Fatal(err) + } + st, err = Open(path, "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + if err := st.RequireCompleteScan(); err == nil { + t.Fatal("interrupted second generation inherited prior completion") + } +} + +func TestWriterLockAllowsReadOnlyStatus(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.db") + writer, err := Open(path, "bucket") + if err != nil { + t.Fatal(err) + } + defer writer.Close() + if another, err := Open(path, "bucket"); err == nil { + another.Close() + t.Fatal("second concurrent migration writer accepted") + } + alias := filepath.Join(filepath.Dir(path), "alias.db") + if err := os.Symlink(path, alias); err == nil { + if another, err := Open(alias, "bucket"); err == nil { + another.Close() + t.Fatal("symlink alias bypassed writer lock") + } + } + reader, err := OpenExisting(path) + if err != nil { + t.Fatalf("status cannot read active migration: %v", err) + } + defer reader.Close() + if _, err := reader.Counts(); err != nil { + t.Fatal(err) + } + if err := reader.BeginScan(); err == nil { + t.Fatal("status reader unexpectedly permits mutation") + } +} + +// The helper owns the SQLite pager lock in another process. Killing it must +// release the lock without a stale PID file or a manual unlock operation. +func TestWriterLockRecoversAfterProcessCrash(t *testing.T) { + if os.Getenv("MIGRATION_TEST_LOCK_HELPER") == "1" { + st, err := Open(os.Getenv("MIGRATION_TEST_LOCK_PATH"), "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + fmt.Println("ready") + _, _ = bufio.NewReader(os.Stdin).ReadString('\n') + return + } + path := filepath.Join(t.TempDir(), "state.db") + cmd := exec.Command(os.Args[0], "-test.run=^TestWriterLockRecoversAfterProcessCrash$") + cmd.Env = append(os.Environ(), "MIGRATION_TEST_LOCK_HELPER=1", "MIGRATION_TEST_LOCK_PATH="+path) + stdin, err := cmd.StdinPipe() + if err != nil { + t.Fatal(err) + } + defer stdin.Close() + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + cmd.Stderr = os.Stderr + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + line, err := bufio.NewReader(stdout).ReadString('\n') + if err != nil || line != "ready\n" { + t.Fatalf("helper did not acquire lock: %q %v", line, err) + } + if st, err := Open(path, "bucket"); err == nil { + st.Close() + t.Fatal("cross-process writer lock was bypassed") + } + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + _ = cmd.Wait() + st, err := Open(path, "bucket") + if err != nil { + t.Fatalf("lock remained after process death: %v", err) + } + defer st.Close() +} + +// Keeping an object terminal must not conceal that the source now contains +// different bytes under the same key. This does not request an overwrite: +// invalidating verification or surfacing a conflict is sufficient. +func TestAuditChangedSourceInvalidatesDone(t *testing.T) { + st, err := Open(filepath.Join(t.TempDir(), "state.db"), "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + original := Object{Key: "key", Size: 4, ETag: "old", LastModified: time.Unix(1, 0)} + if err := st.BatchUpsertScanned([]Object{original}); err != nil { + t.Fatal(err) + } + if err := st.MarkStatus(original.Key, StatusDone, ""); err != nil { + t.Fatal(err) + } + changed := Object{Key: "key", Size: 8, ETag: "new", LastModified: time.Unix(2, 0)} + if err := st.BatchUpsertScanned([]Object{changed}); err != nil { + return // Explicitly rejecting a changed completed object is also safe. + } + c, err := st.Counts() + if err != nil { + t.Fatal(err) + } + if c.Done != 0 { + t.Fatalf("changed source is still reported done with stale inventory: %+v", c) + } +} + +func TestAuditPendingAndFailedSurviveReopen(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.db") + st, err := Open(path, "bucket") + if err != nil { + t.Fatal(err) + } + objects := []Object{ + {Key: "a", Size: 10, ETag: "first", LastModified: time.Unix(1, 0)}, + {Key: "b", Size: 20, ETag: "second", LastModified: time.Unix(2, 0)}, + } + if err := st.BatchUpsertScanned(objects); err != nil { + t.Fatal(err) + } + if err := st.MarkStatus("b", StatusFailed, "interrupted upload"); err != nil { + t.Fatal(err) + } + if err := st.Close(); err != nil { + t.Fatal(err) + } + st, err = Open(path, "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + batch, err := st.BatchPendingAfter("", 10) + if err != nil { + t.Fatal(err) + } + if len(batch) != 2 || batch[0].Key != "a" || batch[1].Key != "b" || batch[1].Status != StatusFailed || batch[1].Size != 20 || batch[1].ETag != "second" { + t.Fatalf("reopened work differs from committed work: %+v", batch) + } +} diff --git a/internal/store/security_permissions_test.go b/internal/store/security_permissions_test.go new file mode 100644 index 0000000..4bbabea --- /dev/null +++ b/internal/store/security_permissions_test.go @@ -0,0 +1,49 @@ +package store + +import ( + "os" + "path/filepath" + "runtime" + "testing" +) + +func TestNewStateFilesArePrivateAndExistingModePreserved(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows file access is governed by ACLs, not Unix mode bits") + } + path := filepath.Join(t.TempDir(), "state.db") + st, err := Open(path, "bucket") + if err != nil { + t.Fatal(err) + } + for _, name := range []string{path, path + ".lock", path + "-wal", path + "-shm"} { + info, err := os.Stat(name) + if os.IsNotExist(err) && (name == path+"-wal" || name == path+"-shm") { + continue + } + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm()&0o077 != 0 { + t.Errorf("%s has non-private mode %o", name, info.Mode().Perm()) + } + } + if err := st.Close(); err != nil { + t.Fatal(err) + } + if err := os.Chmod(path, 0o640); err != nil { + t.Fatal(err) + } + st, err = Open(path, "bucket") + if err != nil { + t.Fatal(err) + } + defer st.Close() + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o640 { + t.Fatalf("existing database permissions changed to %o", info.Mode().Perm()) + } +} diff --git a/internal/store/sqlite_uri_test.go b/internal/store/sqlite_uri_test.go new file mode 100644 index 0000000..0eefc0b --- /dev/null +++ b/internal/store/sqlite_uri_test.go @@ -0,0 +1,55 @@ +package store + +import ( + "net/url" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestSQLiteURIWindowsPathFormatting(t *testing.T) { + for _, tc := range []struct{ path, want string }{ + {"C:/Users/user/state #1.db", "file:///C:/Users/user/state%20%231.db"}, + {"//server/share/state #1.db", "file:////server/share/state%20%231.db"}, + } { + got := (&url.URL{Scheme: "file", Path: sqliteURIPath(tc.path, true)}).String() + if got != tc.want { + t.Errorf("%q: got %q, want %q", tc.path, got, tc.want) + } + } +} + +func TestSQLiteURIPathSpecialCharactersAndWriterLock(t *testing.T) { + name := "state #? % ü.db" + if runtime.GOOS == "windows" { + name = "state # % ü.db" // Windows filenames cannot contain question marks. + } + path := filepath.Join(t.TempDir(), name) + writer, err := Open(path, "bucket") + if err != nil { + t.Fatal(err) + } + if other, err := Open(path, "bucket"); err == nil { + other.Close() + writer.Close() + t.Fatal("second writer acquired lock") + } else if !strings.Contains(err.Error(), "in use by another writer") { + writer.Close() + t.Fatalf("unexpected lock error: %v", err) + } + reader, err := OpenExisting(path) + if err != nil { + writer.Close() + t.Fatalf("open read-only: %v", err) + } + reader.Close() + if err := writer.Close(); err != nil { + t.Fatal(err) + } + reopened, err := Open(path, "bucket") + if err != nil { + t.Fatalf("reopen after release: %v", err) + } + reopened.Close() +} diff --git a/internal/store/store.go b/internal/store/store.go index 1722812..c0d3fe3 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -2,14 +2,17 @@ package store import ( "database/sql" + "errors" "fmt" "net/url" "os" "path/filepath" + "runtime" "strings" + "sync" "time" - _ "modernc.org/sqlite" + "modernc.org/sqlite" ) const ( @@ -29,10 +32,17 @@ type Object struct { } type Store struct { - db *sql.DB + db *sql.DB + lock *sql.DB + closeOnce sync.Once + closeErr error } func Open(path, bucket string) (*Store, error) { + return open(path, bucket, "rwc") +} + +func open(path, bucket, mode string) (*Store, error) { if bucket == "" { return nil, fmt.Errorf("store: bucket must not be empty") } @@ -41,108 +51,125 @@ func Open(path, bucket string) (*Store, error) { return nil, fmt.Errorf("create db dir %s: %w", dir, err) } } - db, err := openDB(path, "rwc") + // File aliases must share a task lock as well as SQLite's data locks. + if canonical, err := filepath.EvalSymlinks(path); err == nil { + path = canonical + } else if dir, err := filepath.EvalSymlinks(filepath.Dir(path)); err == nil { + path = filepath.Join(dir, filepath.Base(path)) + } + // SQLite otherwise creates files according to the process umask, which can + // expose object names and errors to other local users. Preserve permissions + // on existing databases, which may intentionally be shared. + for _, name := range []string{path + ".lock", path} { + f, err := os.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err != nil && !os.IsExist(err) { + return nil, fmt.Errorf("create state file %s: %w", name, err) + } + if err == nil { + if err := f.Close(); err != nil { + return nil, fmt.Errorf("close state file %s: %w", name, err) + } + } + } + // 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)")) + if err != nil { + return nil, err + } + tuneSQLite(lock) + if _, err := lock.Exec(`BEGIN EXCLUSIVE`); err != nil { + lock.Close() + var sqliteErr *sqlite.Error + if errors.As(err, &sqliteErr) && (sqliteErr.Code()&0xff == 5 || sqliteErr.Code()&0xff == 6) { + return nil, fmt.Errorf("state DB %s is in use by another writer: %w", path, err) + } + 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)")) if err != nil { + unlock() return nil, err } + tuneSQLite(db) + var existingSchema int + if err := db.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='objects'`).Scan(&existingSchema); err != nil { + db.Close() + unlock() + return nil, fmt.Errorf("inspect schema: %w", err) + } if _, err := db.Exec(schema); err != nil { db.Close() + unlock() return nil, fmt.Errorf("init schema: %w", err) } + if existingSchema == 0 { + if _, err := db.Exec(`INSERT INTO meta(key,value) VALUES('state_format','2')`); err != nil { + db.Close() + unlock() + return nil, fmt.Errorf("initialize state format: %w", err) + } + } if err := ensureBucket(db, bucket); err != nil { db.Close() + unlock() return nil, err } - return &Store{db: db}, nil + return &Store{db: db, lock: lock}, nil } -func ensureBucket(db *sql.DB, bucket string) error { - tx, err := db.Begin() - if err != nil { - return err - } - defer tx.Rollback() - res, err := tx.Exec(`INSERT INTO meta(key,value) VALUES('bucket',?) ON CONFLICT(key) DO NOTHING`, bucket) - if err != nil { - return err - } - n, err := res.RowsAffected() - if err != nil { - return err - } - if n == 1 { - if _, err := tx.Exec(`INSERT INTO meta(key,value) VALUES('scan_complete', '0')`); err != nil { - return err - } +func sqliteURI(path, mode string, pragmas ...string) string { + abs, err := filepath.Abs(path) + if err == nil { + path = abs } - if err := tx.Commit(); err != nil { - return err + 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) } - return checkBucket(db, bucket) + u.RawQuery = q.Encode() + return u.String() } -func checkBucket(db *sql.DB, bucket string) error { +// Drive-letter paths need an absolute URI path. Without the leading slash, +// net/url formats file://C:/... with C: as the authority, not the path. +// UNC paths already start with // and must retain both leading slashes. +func sqliteURIPath(path string, windows bool) string { + if windows && len(path) >= 2 && path[1] == ':' && !strings.HasPrefix(path, "/") { + return "/" + path + } + return path +} + +func ensureBucket(db *sql.DB, bucket string) error { var existing string - if err := db.QueryRow(`SELECT value FROM meta WHERE key='bucket'`).Scan(&existing); err != nil { + err := db.QueryRow(`SELECT value FROM meta WHERE key = 'bucket'`).Scan(&existing) + switch { + case err == sql.ErrNoRows: + _, err := db.Exec(`INSERT INTO meta(key, value) VALUES('bucket', ?)`, bucket) + return err + case err != nil: return fmt.Errorf("read bucket meta: %w", err) - } - if existing != bucket { + case existing != bucket: return fmt.Errorf("db_path is bound to bucket %q but config requests %q; use a separate db_path per bucket", existing, bucket) } return nil } -// BindEndpoints prevents terminal rows from one migration being reused for -// another. A scan only knows the source. Existing pre-binding databases adopt -// their configured endpoint on first use without discarding completed work. -func (s *Store) BindEndpoints(source, target string) error { - tx, err := s.db.Begin() - if err != nil { - return err - } - defer tx.Rollback() - for _, entry := range []struct{ key, value string }{{"source_endpoint", source}, {"target_endpoint", target}} { - if entry.value == "" { - continue - } - if _, err := tx.Exec(`INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO NOTHING`, entry.key, entry.value); err != nil { - return err +func (s *Store) Close() error { + s.closeOnce.Do(func() { + s.closeErr = s.db.Close() + if s.lock != nil { + _, _ = s.lock.Exec(`ROLLBACK`) + if err := s.lock.Close(); s.closeErr == nil { + s.closeErr = err + } } - var bound string - if err := tx.QueryRow(`SELECT value FROM meta WHERE key=?`, entry.key).Scan(&bound); err != nil { - return err - } - if bound != entry.value { - return fmt.Errorf("db_path is bound to %s %q, configured %q; use a separate db_path for this migration", entry.key, bound, entry.value) - } - } - return tx.Commit() -} - -func (s *Store) Close() error { return s.db.Close() } - -func openDB(path, mode string) (*sql.DB, error) { - abs, err := filepath.Abs(path) - if err != nil { - return nil, err - } - // SQLite file URIs require a leading slash before Windows drive letters. - name := filepath.ToSlash(abs) - if !strings.HasPrefix(name, "/") { - name = "/" + name - } - query := url.Values{"mode": {mode}, "_pragma": {"busy_timeout(5000)"}} - if mode != "ro" { - query.Add("_pragma", "journal_mode(WAL)") - query.Add("_pragma", "synchronous(NORMAL)") - } - uri := url.URL{Scheme: "file", Path: name, RawQuery: query.Encode()} - db, err := sql.Open("sqlite", uri.String()) - if err != nil { - return nil, err - } - tuneSQLite(db) - return db, nil + }) + return s.closeErr } // tuneSQLite keeps a single connection. WAL still allows a writer plus @@ -155,12 +182,13 @@ func tuneSQLite(db *sql.DB) { db.SetMaxIdleConns(1) } -// OpenExisting opens a state database read-only for status. +// OpenExisting opens a state DB read-only without taking the writer lock. func OpenExisting(path string) (*Store, error) { - db, err := openDB(path, "ro") + db, err := sql.Open("sqlite", sqliteURI(path, "ro", "busy_timeout(5000)")) if err != nil { return nil, err } + tuneSQLite(db) s := &Store{db: db} if _, err := s.BoundBucket(); err != nil { db.Close() @@ -169,34 +197,110 @@ func OpenExisting(path string) (*Store, error) { return s, nil } -// OpenInventory requires a state DB created by scan, and never creates one. -func OpenInventory(path, bucket string) (*Store, error) { - db, err := openDB(path, "rw") +// 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. +func (s *Store) BindMigration(source, target string) error { + source, target = normalizeEndpoint(source), normalizeEndpoint(target) + if source == "" { + return fmt.Errorf("migration source identity is required") + } + tx, err := s.db.Begin() if err != nil { - return nil, err + return err } - if err := checkBucket(db, bucket); err != nil { - db.Close() - return nil, fmt.Errorf("open inventory %s (run scan first): %w", path, err) + defer tx.Rollback() + var boundSource, boundTarget, format string + read := func(key string, dst *string) error { + err := tx.QueryRow(`SELECT value FROM meta WHERE key=?`, key).Scan(dst) + if err == sql.ErrNoRows { + return nil + } + return err } - var incomplete bool - if err := db.QueryRow(`SELECT EXISTS(SELECT 1 FROM meta WHERE key='scan_complete' AND value != '1')`).Scan(&incomplete); err != nil { - db.Close() - return nil, err + if err := read("source_endpoint", &boundSource); err != nil { + return err } - if incomplete { - db.Close() - return nil, fmt.Errorf("inventory %s is incomplete; run scan again", path) + if err := read("target_endpoint", &boundTarget); err != nil { + return err + } + if boundSource != "" && boundSource != source { + return fmt.Errorf("state DB source mismatch: bound to %q, requested %q; use a new state directory", boundSource, source) + } + if target != "" && boundTarget != "" && boundTarget != target { + return fmt.Errorf("state DB target mismatch: bound to %q, requested %q; use a new state directory", boundTarget, target) } - return &Store{db: db}, nil + if boundSource == "" || (target != "" && boundTarget == "") { + if err := read("state_format", &format); err != nil { + return err + } + var unsafeRows int + if err := tx.QueryRow(`SELECT COUNT(*) FROM objects WHERE ? != '2' OR attempts > 0 OR status != 'pending'`, format).Scan(&unsafeRows); err != nil { + return err + } + if unsafeRows > 0 { + return fmt.Errorf("unbound legacy or previously migrated state cannot be adopted safely; use a new state directory and rescan") + } + if format != "2" { + if _, err := tx.Exec(`INSERT INTO meta(key,value) VALUES('state_format','2') ON CONFLICT(key) DO UPDATE SET value=excluded.value`); err != nil { + return err + } + } + } + if _, err := tx.Exec(`INSERT INTO meta(key,value) VALUES('source_endpoint',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`, source); err != nil { + return err + } + if target != "" { + if _, err := tx.Exec(`INSERT INTO meta(key,value) VALUES('target_endpoint',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value`, target); err != nil { + return err + } + } + return tx.Commit() } -// SetScanComplete leaves the last scan marked incomplete until all pages are durable. -func (s *Store) SetScanComplete(complete bool) error { - _, err := s.db.Exec(`INSERT OR REPLACE INTO meta(key,value) VALUES('scan_complete',?)`, complete) +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 +} + +// BeginScan invalidates the previous completeness certificate before any +// network request. An interrupted scan must never authorize migration. +func (s *Store) BeginScan() error { + _, err := s.db.Exec(`INSERT INTO meta(key,value) VALUES('scan_generation','1') ON CONFLICT(key) DO UPDATE SET value=CAST(value AS INTEGER)+1`) return err } +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`) + if err != nil { + return err + } + if n, err := result.RowsAffected(); err != nil { + return err + } else if n == 0 { + return fmt.Errorf("cannot complete a scan that was never started") + } + return nil +} + +func (s *Store) RequireCompleteScan() error { + var complete int + err := s.db.QueryRow(`SELECT COUNT(*) FROM meta current JOIN meta completed ON completed.key='scan_complete_generation' AND completed.value=current.value WHERE current.key='scan_generation' AND CAST(current.value AS INTEGER)>0`).Scan(&complete) + if err != nil { + return err + } + if complete != 1 { + return fmt.Errorf("state DB has no complete inventory; run scan or run successfully before migrate") + } + return nil +} + func (s *Store) BoundBucket() (string, error) { var name string err := s.db.QueryRow(`SELECT value FROM meta WHERE key = 'bucket'`).Scan(&name) @@ -222,9 +326,8 @@ CREATE TABLE IF NOT EXISTS meta ( ` // BatchUpsertScanned records objects discovered during scan. -// Terminal rows (done/conflict) are left untouched. -// pending/failed/skipped rows are refreshed and reset to pending, so a -// skipped object that reappears on the source is retried. +// Changed source identities invalidate previous completion and conflicts. +// Rechecking a changed key never authorizes overwriting a target object. func (s *Store) BatchUpsertScanned(objs []Object) error { if len(objs) == 0 { return nil @@ -244,6 +347,9 @@ func (s *Store) BatchUpsertScanned(objs []Object) error { 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,'') `) if err != nil { tx.Rollback() @@ -342,3 +448,30 @@ func (s *Store) CountWork() (int64, error) { 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 { + return nil, fmt.Errorf("open inventory %s: %w", path, err) + } + st, err := open(path, bucket, "rw") + if err != nil { + return nil, err + } + if err := st.RequireCompleteScan(); err != nil { + st.Close() + return nil, err + } + 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 { + return s.CompleteScan() + } + return s.BeginScan() +} diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 405acff..7c0060b 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -38,7 +38,7 @@ func TestOpenRejectsEmptyBucket(t *testing.T) { } } -func TestUpsertNeverResurrectsDone(t *testing.T) { +func TestUpsertPreservesUnchangedDone(t *testing.T) { st, err := Open(filepath.Join(t.TempDir(), "t.db"), "photos") if err != nil { t.Fatal(err) @@ -52,7 +52,6 @@ func TestUpsertNeverResurrectsDone(t *testing.T) { if err := st.MarkStatus("k", StatusDone, ""); err != nil { t.Fatal(err) } - obj.Size = 2 if err := st.BatchUpsertScanned([]Object{obj}); err != nil { t.Fatal(err) } @@ -154,7 +153,7 @@ func itoa2(i int) string { return string([]byte{'0' + byte(i/10), '0' + byte(i%10)}) } -func TestLegacyInventoryBindsEndpointsWithoutLosingProgress(t *testing.T) { +func TestLegacyInventoryRequiresRescanWithoutLosingProgress(t *testing.T) { path := filepath.Join(t.TempDir(), "state#1.db") st, err := Open(path, "photos") if err != nil { @@ -169,23 +168,18 @@ func TestLegacyInventoryBindsEndpointsWithoutLosingProgress(t *testing.T) { if err := st.MarkStatus("old", StatusDone, ""); err != nil { t.Fatal(err) } - st.Close() - st, err = OpenInventory(path, "photos") - if err != nil { + if err := st.Close(); err != nil { t.Fatal(err) } - defer st.Close() - if err := st.BindEndpoints("http://source", ""); err != nil { - t.Fatal(err) + if st, err = OpenInventory(path, "photos"); err == nil { + st.Close() + t.Fatal("legacy inventory without a scan certificate must not authorize migration") } - if err := st.BindEndpoints("http://source", "http://target"); err != nil { + st, err = OpenExisting(path) + if err != nil { t.Fatal(err) } - for _, pair := range [][2]string{{"http://other", "http://target"}, {"http://source", "http://other"}} { - if err := st.BindEndpoints(pair[0], pair[1]); err == nil { - t.Fatalf("accepted changed endpoint in %v", pair) - } - } + defer st.Close() counts, err := st.Counts() if err != nil || counts.Done != 1 { t.Fatalf("lost existing state: %+v err=%v", counts, err) diff --git a/main.go b/main.go index af3d69f..c3e77a5 100644 --- a/main.go +++ b/main.go @@ -5,11 +5,12 @@ import ( "os" "github.com/rustfs/migration/cmd" + "github.com/rustfs/migration/internal/safeoutput" ) func main() { if err := cmd.Execute(); err != nil { - fmt.Fprintln(os.Stderr, "error:", err) + fmt.Fprintln(os.Stderr, "error:", safeoutput.Escape(err.Error())) os.Exit(1) } } diff --git a/scripts/audit-local-rustfs.py b/scripts/audit-local-rustfs.py new file mode 100644 index 0000000..d3204d0 --- /dev/null +++ b/scripts/audit-local-rustfs.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +"""Run real_s3 tests against an explicitly selected, verified RustFS release.""" +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import re +import signal +import socket +import subprocess +import sys +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_VERSION = "1.0.4" +TOTAL_TIMEOUT_SECONDS = 420 +GO_TIMEOUT_SECONDS = 360 # Includes compilation; the test binary gets five minutes. + + +def clean_rustfs_env(): + """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} + env["RUSTFS_CONSOLE_ENABLE"] = "false" + return env + + +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: + raise ValueError(f"unrecognized RustFS --version output: {output!r}") + return match.group(1) + + +def inspect_binary(binary, expected_version): + path = Path(binary) + if not path.is_absolute(): + raise ValueError("--rustfs-binary / RUSTFS_BINARY must be an absolute path") + path = path.resolve(strict=True) + if not path.is_file() or not os.access(path, os.X_OK): + raise ValueError(f"RustFS binary is not an executable file: {path}") + result = subprocess.run([str(path), "--version"], env=clean_rustfs_env(), + capture_output=True, text=True, timeout=15, check=True) + output = (result.stdout + result.stderr).strip() + version = parse_version(output) + if version != expected_version: + raise ValueError(f"RustFS version mismatch: expected {expected_version!r}, got {version!r}; refusing to start nodes") + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return { + "binary_path": str(path), "sha256": digest.hexdigest(), + "expected_version": expected_version, "version": version, + "version_output": output, + "verified_at_utc": datetime.now(timezone.utc).isoformat(), + } + + +def free_port(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def stop_process(proc): + """Terminate a whole launcher-owned process group, including test children.""" + try: + if os.name == "posix": + os.killpg(proc.pid, signal.SIGTERM) + elif proc.poll() is None: + proc.terminate() + except ProcessLookupError: + pass + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + if os.name == "posix": + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + else: + proc.kill() + proc.wait(timeout=10) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--rustfs-binary", default=os.environ.get("RUSTFS_BINARY"), + help="absolute path to the release executable (or RUSTFS_BINARY); never resolved from PATH") + parser.add_argument("--expect-version", default=DEFAULT_VERSION, + help="exact release version required before starting either node (default: 1.0.4)") + parser.add_argument("--output-dir", type=Path, + help="directory for node logs and binary provenance (default: audit-results/rustfs-)") + args = parser.parse_args(argv) + if not args.rustfs_binary: + parser.error("provide --rustfs-binary or RUSTFS_BINARY; an installed PATH version is never used") + if not re.fullmatch(r"\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?", args.expect_version): + parser.error("--expect-version must be an exact semantic version") + metadata = inspect_binary(args.rustfs_binary, args.expect_version) + output = (args.output_dir or ROOT / "audit-results" / f"rustfs-{args.expect_version}").resolve() + output.mkdir(parents=True, exist_ok=True) + metadata_path = output / "rustfs-binary.json" + metadata_path.write_text(json.dumps(metadata, indent=2) + "\n") + print(f"Verified RustFS {metadata['version']}: {metadata['binary_path']}", flush=True) + print(f"SHA256 {metadata['sha256']}; evidence: {metadata_path}", flush=True) + + processes, logs, endpoints = [], [], [] + deadline = time.monotonic() + TOTAL_TIMEOUT_SECONDS + go_proc = None + try: + with tempfile.TemporaryDirectory(prefix="migration-audit-rustfs-") as base: + try: + for name in ("source", "target"): + data = Path(base) / name + data.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}", + "--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) + processes.append(proc) + start_deadline = min(deadline, time.monotonic() + 45) + while True: + if proc.poll() is not None: + raise RuntimeError(f"{name} exited {proc.returncode}; see {log.name}") + try: + with socket.create_connection(("127.0.0.1", port), timeout=.2): + break + except OSError: + if time.monotonic() >= start_deadline: + raise RuntimeError(f"{name} did not start within 45 seconds; see {log.name}") + time.sleep(.2) + endpoints.append(endpoint) + env = os.environ.copy() + env.update(AUDIT_SOURCE=endpoints[0], AUDIT_TARGET=endpoints[1]) + command = ["go", "test", "-race", "-tags", "real_s3", "-run", "^TestRealS3", + "-count=1", "-timeout=5m", "-v", "./internal/migrator"] + metadata.update(test_command=command, endpoints=endpoints) + metadata_path.write_text(json.dumps(metadata, indent=2) + "\n") + go_proc = subprocess.Popen(command, cwd=ROOT, env=env, start_new_session=True) + try: + returncode = go_proc.wait(timeout=min(GO_TIMEOUT_SECONDS, max(1, deadline - time.monotonic()))) + except subprocess.TimeoutExpired: + stop_process(go_proc) + raise RuntimeError("real S3 tests exceeded the launcher deadline") from None + metadata.update(test_exit_code=returncode, finished_at_utc=datetime.now(timezone.utc).isoformat()) + metadata_path.write_text(json.dumps(metadata, indent=2) + "\n") + return returncode + finally: + if go_proc is not None and go_proc.poll() is None: + stop_process(go_proc) + for proc in reversed(processes): + stop_process(proc) + finally: + for log in logs: + log.close() + + +if __name__ == "__main__": + def interrupted(signum, frame): + raise KeyboardInterrupt + + signal.signal(signal.SIGTERM, interrupted) + try: + raise SystemExit(main()) + except KeyboardInterrupt: + print("RustFS audit interrupted; owned processes were stopped", file=sys.stderr) + raise SystemExit(130) + except (ValueError, OSError, RuntimeError, subprocess.SubprocessError) as exc: + print(f"RustFS audit failed: {exc}", file=sys.stderr) + raise SystemExit(1) diff --git a/scripts/test_audit_local_rustfs.py b/scripts/test_audit_local_rustfs.py new file mode 100644 index 0000000..0acb8d1 --- /dev/null +++ b/scripts/test_audit_local_rustfs.py @@ -0,0 +1,73 @@ +"""Launcher validation tests; no installed RustFS or real S3 service is used.""" +import contextlib +import hashlib +import importlib.util +import io +import os +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +SPEC = importlib.util.spec_from_file_location("audit_local_rustfs", Path(__file__).with_name("audit-local-rustfs.py")) +launcher = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(launcher) + + +class ReleaseValidationTests(unittest.TestCase): + def binary(self, directory, version): + path = Path(directory) / "rustfs" + path.write_text("#!/bin/sh\nprintf '%s\\n' 'rustfs " + version + "'\n") + path.chmod(0o700) + return path + + def test_exact_release_and_digest_are_recorded(self): + with tempfile.TemporaryDirectory() as directory: + binary = self.binary(directory, "1.0.4") + result = launcher.inspect_binary(str(binary), "1.0.4") + self.assertEqual(result["version"], "1.0.4") + self.assertEqual(result["binary_path"], str(binary.resolve())) + self.assertEqual(result["sha256"], hashlib.sha256(binary.read_bytes()).hexdigest()) + + def test_wrong_release_and_prerelease_are_rejected(self): + with tempfile.TemporaryDirectory() as directory: + for version in ("1.0.3", "1.0.4-alpha.1", "1.0.40"): + with self.subTest(version=version): + binary = self.binary(directory, version) + with self.assertRaisesRegex(ValueError, "version mismatch"): + launcher.inspect_binary(str(binary), "1.0.4") + + def test_relative_binary_is_rejected(self): + with self.assertRaisesRegex(ValueError, "absolute path"): + launcher.inspect_binary("rustfs", "1.0.4") + + def test_missing_binary_does_not_fall_back_to_path(self): + with mock.patch.dict(os.environ, {"PATH": "/some/old/rustfs"}, clear=True): + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as error: + launcher.main([]) + self.assertEqual(error.exception.code, 2) + + def test_node_environment_excludes_external_credentials(self): + with mock.patch.dict(os.environ, { + "PATH": "/bin", "RUSTFS_ACCESS_KEY": "external", "AWS_SECRET_ACCESS_KEY": "external", + "RUSTFS_VOLUMES": "/external/data", "RUSTFS_CONSOLE_ENABLE": "true", + }, clear=True): + self.assertEqual(launcher.clean_rustfs_env(), {"PATH": "/bin", "RUSTFS_CONSOLE_ENABLE": "false"}) + + def test_unrecognized_version_output_is_rejected(self): + for output in ("1.0.4", "unrelated 1.0.4", "rustfs development"): + with self.subTest(output=output), self.assertRaises(ValueError): + launcher.parse_version(output) + + def test_release_long_version_output(self): + output = """rustfs 1.0.4 +build time : 2026-10-25 16:26:17 +build target : aarch64-apple-darwin +git commit : 46337942d55f3a8e6a97b147ca98d9ea8115555d +git tag : 1.0.4 +""" + self.assertEqual(launcher.parse_version(output), "1.0.4") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e.py b/tests/e2e.py index 8dbb5d4..4c69794 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -52,6 +52,7 @@ def exercise(binary, directory, old, new): dst, dst_config = new config = { "old": src_config, "new": dst_config, "workers": 2, + "source_frozen": True, "multipart_threshold": 5 * MIB, "multipart_part_size": 5 * MIB, "multipart_concurrency": 2, } @@ -87,6 +88,10 @@ def assert_status(*expected): assert empty_bucket in cli("list") cli("scan") + # The flag is only an assertion; rejecting a false assertion prevents writes. + cli("migrate", "--source-frozen=false", exit_code=1) + assert not dst.list_objects_v2(Bucket=bucket).get("Contents"), "freeze guard wrote objects" + assert empty_bucket not in {item["Name"] for item in dst.list_buckets()["Buckets"]}, "freeze guard created a bucket" cli("migrate") dst.head_bucket(Bucket=empty_bucket) for key, expected in bodies.items(): @@ -95,9 +100,10 @@ def assert_status(*expected): assert body.read() == expected, f"incorrect bytes for {key!r}" for field, value in attrs.items(): assert got[field] == value, f"{key!r}: incorrect {field}: {got[field]!r}" - assert "-2" in dst.head_object(Bucket=bucket, Key="large.bin")["ETag"] + # ETags are opaque; exact bytes and metadata above are the correctness test. + assert dst.head_object(Bucket=bucket, Key="large.bin")["ETag"] initial_diff = cli("diff") - assert "ok=3" in initial_diff and "size_only=1" in initial_diff, initial_diff + assert "ok=3" in initial_diff and "content_mismatch=0" in initial_diff, initial_diff def versions(): return sorted((v["Key"], v["VersionId"]) for v in @@ -117,11 +123,18 @@ def versions(): with dst.get_object(Bucket=bucket, Key="changed")["Body"] as body: assert body.read() == b"later", "rescan did not retry the changed object" - src.put_object(Bucket=bucket, Key="conflict", Body=b"source") - dst.put_object(Bucket=bucket, Key="conflict", Body=b"target") + # Both objects have identical explicit metadata and size, so diff must + # compare their bytes rather than reporting a server-default header mismatch. + src.put_object(Bucket=bucket, Key="conflict", Body=b"source", **attrs) + dst.put_object(Bucket=bucket, Key="conflict", Body=b"target", **attrs) + for client in (src, dst): + head = client.head_object(Bucket=bucket, Key="conflict") + for field, value in attrs.items(): + assert head[field] == value, f"conflict: incorrect {field}: {head.get(field)!r}" dst.put_object(Bucket=bucket, Key="extra", Body=b"target only") before_conflict = versions() cli("run") + cli("migrate", "--strict", exit_code=1) assert_status(5, 0, 4, 1, 0, 0) assert versions() == before_conflict, "conflict or target-only object was overwritten" for key, expected in {"conflict": b"target", "extra": b"target only"}.items(): @@ -152,8 +165,15 @@ def versions(): assert not dst.list_multipart_uploads(Bucket=bucket).get("Uploads") assert_status(6, 0, 4, 2, 0, 0) - gaps = cli("diff", "--extra", exit_code=1) - assert "etag_mismatch=1" in gaps and "size_mismatch=1" in gaps and "extra_on_target=1" in gaps, gaps + report = directory / "issues.jsonl" + gaps = cli("diff", "--strict", "--issues-jsonl", str(report), exit_code=1) + assert "content_mismatch=1" in gaps and "size_mismatch=1" in gaps and "extra_on_target=1" in gaps, gaps + issues = [json.loads(line) for line in report.read_text(encoding="utf-8").splitlines()] + assert {(issue["bucket"], issue["key"], issue["kind"]) for issue in issues} == { + (bucket, "conflict", "content"), (bucket, race_key, "size"), (bucket, "extra", "extra") + }, issues + # Explicitly breaking the source freeze above is adversarial fault injection; + # a production migration must keep the source frozen through final acceptance. def main():