mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-23 00:15:37 +00:00
Compare commits
182 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e6435510f8 | |||
| 5696c6f759 | |||
| 7c3732799e | |||
| adad36dc3b | |||
| 83afcf52f7 | |||
| bb044df449 | |||
| 3565ae1ddf | |||
| cce3b0873d | |||
| 6bb25182c9 | |||
| ceb8f49aae | |||
| 33aae31cb7 | |||
| f8924deb68 | |||
| 9e8c426e6f | |||
| 9815b67c51 | |||
| 496a34a6a7 | |||
| 7c9ebadffe | |||
| e376e7d774 | |||
| d211df88d5 | |||
| 21caf8bf34 | |||
| d3eaaa21a6 | |||
| ad457a2d1c | |||
| fa3ea5b4e5 | |||
| f3396952b6 | |||
| 8736b49d08 | |||
| eec468e488 | |||
| f2af45ee68 | |||
| 25b55febc5 | |||
| c2e50b3b10 | |||
| 6fde592da1 | |||
| 98259d7c46 | |||
| b5a35fc2c7 | |||
| 11a7572bba | |||
| 4c4dc84671 | |||
| 52986eefd5 | |||
| 7a5ffcfee7 | |||
| 334d615a67 | |||
| 0c813e1a9e | |||
| 0de0b85374 | |||
| 78f78ce5ee | |||
| 82ad3f0007 | |||
| 82f094f4d5 | |||
| e1df1d569b | |||
| 19487a6e34 | |||
| 6177fc280f | |||
| 14db51bba7 | |||
| 353de54fcc | |||
| 6a4f93bbaf | |||
| 74fab85ba0 | |||
| 44db2be5f9 | |||
| 3e41233589 | |||
| f36a771389 | |||
| 0447e68073 | |||
| 94dbca3840 | |||
| d2939fb43b | |||
| 9f7d1aa706 | |||
| 98675ddcbd | |||
| 357e78c523 | |||
| 411caa97d7 | |||
| 317e895096 | |||
| 7c55e265dd | |||
| f858a65f41 | |||
| f96c324734 | |||
| 7e5b3e4137 | |||
| c749351780 | |||
| 2381096448 | |||
| 99a1803773 | |||
| 5132be9c01 | |||
| 13399d98fa | |||
| ee3880ee84 | |||
| af48bb8539 | |||
| 850d7a2beb | |||
| 1acf30910f | |||
| 26757d5d5e | |||
| d69742b1e1 | |||
| b86624520c | |||
| 489143b9cf | |||
| e37aa27e40 | |||
| 6e417a458e | |||
| 60ed7f1c40 | |||
| 7f2bd6b99b | |||
| a798df7906 | |||
| 793632c0da | |||
| 301133c1c8 | |||
| a642ba2a89 | |||
| d893d70b2e | |||
| cf15e4d1b6 | |||
| 5a3e94bbbb | |||
| 29b389bf80 | |||
| f94e8cae07 | |||
| 64675785fe | |||
| 5b703b61f9 | |||
| 23420e357d | |||
| 9da1edd8d6 | |||
| d87c058a4d | |||
| 54cda17e58 | |||
| 49f6e815e7 | |||
| 58bbb17300 | |||
| 310b977f05 | |||
| bbe396219f | |||
| e286691371 | |||
| 9ff399afee | |||
| 23c8c35710 | |||
| 9c44c5ea6b | |||
| 31e0798637 | |||
| 868af666e9 | |||
| 93ddf83ee1 | |||
| fbe3d1c9c8 | |||
| 6bec9362b1 | |||
| e237d268ac | |||
| a52b51b764 | |||
| e62c6112ea | |||
| 88b90c1315 | |||
| ec8dc7d1ca | |||
| 5e55549873 | |||
| 55be4e3f79 | |||
| 5be4ef65e8 | |||
| 24f3e783c2 | |||
| 583df55d90 | |||
| 670ae01f7a | |||
| 3a1f0c09b3 | |||
| eed50fc5ff | |||
| e462fafb65 | |||
| 9c0bc265c3 | |||
| 74bf3ca5fa | |||
| 31c4f4a7ff | |||
| 3fb8d861f0 | |||
| 4b386794e1 | |||
| 23a2593aac | |||
| 7b1befa6f9 | |||
| 2f3359df69 | |||
| ea522c18b6 | |||
| 9f13eb22a5 | |||
| fec2d4bb4b | |||
| 42a1417ed0 | |||
| a3d6b59d03 | |||
| 924eb06968 | |||
| 5a44944095 | |||
| 8541ab829a | |||
| b71c6fabc3 | |||
| ed5927cf5d | |||
| c794df64b8 | |||
| 5e69593836 | |||
| e811755b8d | |||
| efed8a35d2 | |||
| b656745305 | |||
| ef974ad719 | |||
| 3af84de8f1 | |||
| d19a2ac726 | |||
| 0524cce44b | |||
| 0fac11d57b | |||
| 46c58d8758 | |||
| aa24d21807 | |||
| 3afea8ecf9 | |||
| f1fdb8c2c3 | |||
| e0afeba48f | |||
| 9e57f83885 | |||
| 283332f6f8 | |||
| 23fff7976b | |||
| 49274736f2 | |||
| 9bc60944be | |||
| 011d8bee6b | |||
| 66eb65da06 | |||
| 85898d94f9 | |||
| caefc17dd1 | |||
| c677030610 | |||
| 08deaeea38 | |||
| 17b01efc89 | |||
| 88d8cc86b1 | |||
| 640f872054 | |||
| ee333a2774 | |||
| 177572b0d9 | |||
| 2e286d3220 | |||
| cfa93b9b40 | |||
| 142cff57a3 | |||
| 447f18db43 | |||
| 975e232a63 | |||
| d921f3cb24 | |||
| 62117054d9 | |||
| 2f51a39c64 | |||
| 292c288896 | |||
| d8519549d1 | |||
| c3efe4be2a |
@@ -1,2 +1,2 @@
|
||||
sha256-darwin=24a8cfaa1b9125bd69d7d4a7ff752a8ab8ed350c761d90ae8472ef52393e2686
|
||||
sha256-linux=014257197fbbfbb48cab2864da9e10d96ee877d478fa29d119f8186532ea293d
|
||||
sha256-darwin=9ccb03f4139e99ec11a63810523d504df39191b86e74b28a72dd9a075682293b
|
||||
sha256-linux=5ef052b03a03afbd00ebfcbbdcb754bbde414b7e6151aae3e2ee78024ce1d0b6
|
||||
|
||||
@@ -103,8 +103,6 @@ script-tests: ## Run shell script tests
|
||||
$(RUSTFS_PYTHON_BIN) ./scripts/test_retain_validation_evidence.py
|
||||
$(RUSTFS_PYTHON_BIN) ./scripts/test_ci_timing_report.py
|
||||
$(RUSTFS_PYTHON_BIN) ./scripts/test_junit_diff.py
|
||||
$(RUSTFS_PYTHON_BIN) ./scripts/test_dual_stack.py
|
||||
$(RUSTFS_PYTHON_BIN) ./scripts/test_mint_stack_diff.py
|
||||
$(RUSTFS_PYTHON_BIN) ./scripts/check_conformance_rulings.py --self-test
|
||||
$(RUSTFS_PYTHON_BIN) ./scripts/compat_matrix_report.py --self-test
|
||||
$(RUSTFS_PYTHON_BIN) ./scripts/s3-tests/test_report_compat.py
|
||||
|
||||
@@ -143,7 +143,7 @@ setup = 'ecstore-base-stack'
|
||||
|
||||
# The multipart refusal fixture composes real-store setup, abort, quota and legal-hold futures.
|
||||
[[profile.default.scripts]]
|
||||
filter = 'package(rustfs-ecstore) | package(rustfs-s3select-api) | package(rustfs-scanner) | (package(rustfs) & test(/^(app::multipart_usecase::complete::tests::completion_absent_binding_refusal_order_baseline|app::multipart_usecase::complete::tests::concurrent_completions_share_durable_bucket_quota_reservations|app::object::delete::tests::compressed_delete_requests_update_observed_usage_without_releasing_quota_floor|app::object::internal_put::tests::internal_multipart_roundtrip_completes_and_abort_leaves_nothing|app::object::restore::tests::execute_restore_object_maps_failures_to_typed_s3_errors|storage::access::tests::(delete_object_access_captures_authorized_bucket_incarnation|copy_operations_reject_recreated_source_bucket_after_authorization|request_slot_keeps_bucket_policy_bound_to_its_store))$/))'
|
||||
filter = 'package(rustfs-ecstore) | package(rustfs-s3select-api) | package(rustfs-scanner) | (package(rustfs) & test(/^(app::multipart_usecase::complete::tests::completion_absent_binding_refusal_order_baseline|app::multipart_usecase::complete::tests::concurrent_completions_share_durable_bucket_quota_reservations|app::object::delete::tests::compressed_delete_requests_update_observed_usage_without_releasing_quota_floor|app::object::internal_put::tests::internal_multipart_roundtrip_completes_and_abort_leaves_nothing|app::object::restore::tests::execute_restore_object_maps_failures_to_typed_s3_errors|storage::access_owned::tests::generation_guards::(delete_object_access_captures_authorized_bucket_incarnation|copy_operations_reject_recreated_source_bucket_after_authorization|request_slot_keeps_bucket_policy_bound_to_its_store))$/))'
|
||||
setup = 'ecstore-base-stack'
|
||||
|
||||
# These handler/store fixtures and the relocated-pool GET compose deep storage
|
||||
@@ -466,7 +466,7 @@ filter = '(package(rustfs) & test(/^(admin::handlers::replication::target_repair
|
||||
setup = 'ecstore-base-stack'
|
||||
|
||||
[[profile.ci.scripts]]
|
||||
filter = 'package(rustfs-ecstore) | package(rustfs-s3select-api) | package(rustfs-scanner) | (package(rustfs) & test(/^(app::multipart_usecase::complete::tests::completion_absent_binding_refusal_order_baseline|app::multipart_usecase::complete::tests::concurrent_completions_share_durable_bucket_quota_reservations|app::object::delete::tests::compressed_delete_requests_update_observed_usage_without_releasing_quota_floor|app::object::internal_put::tests::internal_multipart_roundtrip_completes_and_abort_leaves_nothing|app::object::restore::tests::execute_restore_object_maps_failures_to_typed_s3_errors|storage::access::tests::(delete_object_access_captures_authorized_bucket_incarnation|copy_operations_reject_recreated_source_bucket_after_authorization|request_slot_keeps_bucket_policy_bound_to_its_store))$/))'
|
||||
filter = 'package(rustfs-ecstore) | package(rustfs-s3select-api) | package(rustfs-scanner) | (package(rustfs) & test(/^(app::multipart_usecase::complete::tests::completion_absent_binding_refusal_order_baseline|app::multipart_usecase::complete::tests::concurrent_completions_share_durable_bucket_quota_reservations|app::object::delete::tests::compressed_delete_requests_update_observed_usage_without_releasing_quota_floor|app::object::internal_put::tests::internal_multipart_roundtrip_completes_and_abort_leaves_nothing|app::object::restore::tests::execute_restore_object_maps_failures_to_typed_s3_errors|storage::access_owned::tests::generation_guards::(delete_object_access_captures_authorized_bucket_incarnation|copy_operations_reject_recreated_source_bucket_after_authorization|request_slot_keeps_bucket_policy_bound_to_its_store))$/))'
|
||||
setup = 'ecstore-base-stack'
|
||||
|
||||
[[profile.ci.scripts]]
|
||||
@@ -723,9 +723,8 @@ test-group = 'ecstore-serial-flaky'
|
||||
# fixture as the existing smoke modules.
|
||||
#
|
||||
# Dual-stack differential (rustfs/backlog#2740): `dual_stack_differential::`
|
||||
# starts two single-node servers from the same binary, one per
|
||||
# RUSTFS_S3_STACK value, on random ports with isolated temp dirs, and runs one
|
||||
# SDK script covering every operation of `impl S3 for FS` against both. Its
|
||||
# starts two single-node servers on random ports with isolated temp
|
||||
# dirs, and runs one SDK script covering every S3 operation against both. Its
|
||||
# comparator unit tests need no server. It meets the admission criteria
|
||||
# unchanged; the module clause admits a new differential test without another
|
||||
# filter edit.
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
# Adding a target is one more [[targets]] table, for example:
|
||||
#
|
||||
# [[targets]]
|
||||
# name = "candidate-gateway"
|
||||
# name = "candidate-tuned"
|
||||
# binary = "candidate"
|
||||
# env = { RUSTFS_S3_STACK = "gateway" }
|
||||
# env = { RUSTFS_EXAMPLE_SETTING = "on" }
|
||||
|
||||
schema = 1
|
||||
|
||||
|
||||
@@ -114,8 +114,14 @@
|
||||
}
|
||||
],
|
||||
"upgrade_sources": {
|
||||
"basis": "Exactly the two previous-release sources pinned in .github/workflows/e2e-upgrade.yml are exercised today (source.version / source.asset / source.sha256). No other N-1/N-2 compatibility is claimed, and these digests are not inferred from tags.",
|
||||
"basis": "The three previous-release sources pinned in .github/workflows/e2e-upgrade.yml are exercised today (source.version / source.asset / source.sha256). No other N-1/N-2 compatibility is claimed, and these digests are not inferred from tags.",
|
||||
"sources": [
|
||||
{
|
||||
"version": "1.0.5",
|
||||
"role": "gateway compatibility baseline",
|
||||
"artifact_name": "rustfs-linux-x86_64-gnu-v1.0.5.zip",
|
||||
"artifact_sha256": "5addae2f74756bf80104d0975e6347cda843bc2daffdfcd1f0cb80118b95cbd0"
|
||||
},
|
||||
{
|
||||
"version": "1.0.1",
|
||||
"role": "N-1",
|
||||
@@ -130,6 +136,6 @@
|
||||
}
|
||||
],
|
||||
"rollback_supported": false,
|
||||
"rollback_basis": "Only the bucket-config-rollback case (rollback_to_previous_release_reads_current_bucket_metadata) is exercised. Full data-plane rollback is not certified and is never a default claim."
|
||||
"rollback_basis": "The release upgrade lane checks bucket-config rollback. The hosted compatibility workflow also checks in-flight multipart rollback to 1.0.5. Full data-plane rollback is not certified and is never a default claim."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,8 +28,6 @@ rustfs/src/app/storage_api.rs
|
||||
rustfs/src/admin/router.rs
|
||||
rustfs/src/app/metadata_route.rs
|
||||
rustfs/src/server/http.rs
|
||||
rustfs/src/server/layer.rs
|
||||
rustfs/src/server/hybrid.rs
|
||||
rustfs/src/protocols/client.rs
|
||||
|
||||
# e2e oracle: the test target that verifies S3 behaviour against s3s
|
||||
|
||||
@@ -13,6 +13,6 @@
|
||||
# s3_error_lines lines holding s3_error!, same scope, minus those the script
|
||||
# header's rule clears (rustfs_s3_types's macro); fails closed
|
||||
# ecstore_files Rust files referencing s3s paths under crates/ecstore/src
|
||||
files=63
|
||||
s3_error_lines=209
|
||||
files=33
|
||||
s3_error_lines=89
|
||||
ecstore_files=0
|
||||
|
||||
@@ -57,6 +57,7 @@ rustfs-scanner 1392 20
|
||||
rustfs-scanner-metrics 90 0
|
||||
rustfs-security-governance 20 0
|
||||
rustfs-signer 34 0
|
||||
rustfs-sse 145 0
|
||||
rustfs-storage-api 34 0
|
||||
rustfs-targets 612 26
|
||||
rustfs-test-utils 1 0
|
||||
|
||||
@@ -34,6 +34,10 @@ If you want the Kafka-backed HA Tempo path, use `docker-compose-example-for-rust
|
||||
- **High Performance**: Optimized configurations for batching, compression, and memory management.
|
||||
- **Standardized Protocols**: Built entirely on OpenTelemetry standards.
|
||||
|
||||
## HTTP Request Latency Percentiles
|
||||
|
||||
The main RustFS dashboard shows request latency percentiles in milliseconds. The HTTP server request, response-body chunk, and response-body stream histograms export bucket boundaries in seconds. During a rolling upgrade or rollback that changes the bucket layout, compute percentiles from nodes that share one layout and from a query window entirely on that layout. The bundled dashboard and recording rules use a five-minute window. The mean from `_sum` divided by `_count` remains usable across the change.
|
||||
|
||||
## GET Performance Optimization Dashboards
|
||||
|
||||
Three pre-built Grafana dashboards are included for monitoring RustFS GET performance optimization rollout:
|
||||
|
||||
@@ -34,6 +34,10 @@
|
||||
- **高性能**: 针对批处理、压缩和内存管理进行了优化配置。
|
||||
- **标准化协议**: 完全基于 OpenTelemetry 标准构建。
|
||||
|
||||
## HTTP 请求延迟分位数
|
||||
|
||||
RustFS 主仪表盘以毫秒显示请求延迟分位数。HTTP 服务的请求耗时、响应体分块延迟和响应体流传输耗时直方图以秒为单位导出桶边界。滚动升级或回滚导致桶边界变化时,只对采用同一套桶边界的节点和时间窗口计算分位数。自带仪表盘和记录规则使用五分钟窗口。变更期间仍可用 `_sum` 除以 `_count` 计算平均值。
|
||||
|
||||
## GET 性能优化仪表盘
|
||||
|
||||
包含三个预构建的 Grafana 仪表盘,用于监控 RustFS GET 性能优化发布:
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
# Copyright 2026 RustFS Team
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
name: Both-stack leg
|
||||
description: Prove which S3 stack one e2e leg's servers selected and upload the leg for the summary (call with if always)
|
||||
|
||||
inputs:
|
||||
profile:
|
||||
description: The nextest profile the leg ran
|
||||
required: true
|
||||
stack:
|
||||
description: The stack the leg requested, legacy or gateway
|
||||
required: true
|
||||
logs:
|
||||
description: Directory or file holding the servers' output
|
||||
required: true
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Prove which stack the servers selected
|
||||
shell: bash
|
||||
env:
|
||||
PROFILE: ${{ inputs.profile }}
|
||||
STACK: ${{ inputs.stack }}
|
||||
LOGS: ${{ inputs.logs }}
|
||||
run: |
|
||||
# Outside the workspace: e2e_binary.py refuses a run whose source tree changed.
|
||||
mkdir -p "$RUNNER_TEMP/leg"
|
||||
junit="target/nextest/${PROFILE}/junit.xml"
|
||||
if [ -s "$junit" ]; then cp "$junit" "$RUNNER_TEMP/leg/junit.xml"; fi
|
||||
# A gateway leg stopped by its preflight has no output; the preflight's stack.json stays.
|
||||
if [ -e "$LOGS" ]; then python3 scripts/dual_stack.py stack --expect "$STACK" --out "$RUNNER_TEMP/leg/stack.json" "$LOGS"; fi
|
||||
|
||||
- name: Upload the leg
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: dual-stack-leg-${{ inputs.profile }}-${{ inputs.stack }}
|
||||
overwrite: true
|
||||
path: ${{ runner.temp }}/leg
|
||||
if-no-files-found: warn
|
||||
retention-days: 7
|
||||
@@ -1,56 +0,0 @@
|
||||
# Copyright 2026 RustFS Team
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
name: Both-stack summary
|
||||
description: Diff the legacy and gateway legs of this run (scripts/junit_diff.py) and upload one dated summary
|
||||
|
||||
inputs:
|
||||
profiles:
|
||||
description: Comma-separated nextest profiles whose two legs this run uploaded
|
||||
required: true
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Download the legs
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
pattern: dual-stack-leg-*
|
||||
path: legs
|
||||
|
||||
- name: Diff every profile and write the summary
|
||||
id: summary
|
||||
shell: bash
|
||||
env:
|
||||
PROFILES: ${{ inputs.profiles }}
|
||||
run: |
|
||||
# The shell runs with -e; the exit status is reported after the summary is written.
|
||||
set +e -u -o pipefail
|
||||
date="$(date -u +%F)"
|
||||
echo "date=${date}" >> "$GITHUB_OUTPUT"
|
||||
mkdir -p legs
|
||||
python3 scripts/dual_stack.py summary --profiles "$PROFILES" --legs legs --date "$date" --out-dir dual-stack
|
||||
status=$?
|
||||
if [ -f dual-stack/summary.md ]; then cat dual-stack/summary.md >> "$GITHUB_STEP_SUMMARY"; fi
|
||||
exit "$status"
|
||||
|
||||
- name: Upload the dated summary
|
||||
if: always() && steps.summary.outputs.date != ''
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: dual-stack-summary-${{ steps.summary.outputs.date }}
|
||||
overwrite: true
|
||||
path: dual-stack
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
@@ -814,7 +814,7 @@
|
||||
"monitor": "workflow",
|
||||
"max_age_hours": 36,
|
||||
"result_owner": "dual-stack-nightly.yml",
|
||||
"disposition": "both-stack JUnit diff of the two profiles only ci.yml runs; the gateway legs are report-only until T2.10",
|
||||
"disposition": "nightly run of the two e2e profiles only ci.yml runs, on the gateway stack, with the JUnit reports retained for 30 days",
|
||||
"failure_owner": "watchdog",
|
||||
"origin": "added"
|
||||
},
|
||||
|
||||
@@ -231,7 +231,7 @@ jobs:
|
||||
# --all-targets links the same test binaries as the reader lane.
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
run: |
|
||||
cargo build -p rustfs -p rustfs-ecstore --all-targets --features rio-v2
|
||||
cargo build -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2
|
||||
cargo build -p rustfs --bins --features rio-v2,e2e-test-hooks
|
||||
|
||||
# Readers: the swift and sftp legs of test-and-lint-protocols. Built in
|
||||
|
||||
+15
-177
@@ -92,7 +92,6 @@ jobs:
|
||||
connect: ${{ steps.scope.outputs.connect || 'true' }}
|
||||
packages: ${{ steps.scope.outputs.packages }}
|
||||
full_validation: ${{ steps.scope.outputs.full_validation || 'true' }}
|
||||
gateway_smoke: ${{ steps.scope.outputs.gateway_smoke || 'true' }}
|
||||
steps:
|
||||
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
with:
|
||||
@@ -119,7 +118,7 @@ jobs:
|
||||
echo "Base CI policy unavailable; running the full matrix."
|
||||
fi
|
||||
if ! grep -q '^plan=' "$GITHUB_OUTPUT" || ! grep -q '^plan_contract=8$' "$GITHUB_OUTPUT"; then
|
||||
printf '%s\n' 'mode=full' 'connect=true' 'full_validation=true' 'gateway_smoke=true' 'packages=' 'plan=' >> "$GITHUB_OUTPUT"
|
||||
printf '%s\n' 'mode=full' 'connect=true' 'full_validation=true' 'packages=' 'plan=' >> "$GITHUB_OUTPUT"
|
||||
echo "Base policy does not cover this workflow contract; retaining the full matrix."
|
||||
fi
|
||||
- name: Retain verification plan
|
||||
@@ -564,7 +563,7 @@ jobs:
|
||||
run: chmod go-w "$(realpath "$HOME")"
|
||||
|
||||
- name: Run rio-v2 clippy lints
|
||||
run: cargo clippy -p rustfs -p rustfs-ecstore --all-targets --features rio-v2 -- -D warnings
|
||||
run: cargo clippy -p rustfs -p rustfs-ecstore -p rustfs-sse --all-targets --features rio-v2 -- -D warnings
|
||||
|
||||
- name: Run rio-v2 feature tests
|
||||
shell: bash
|
||||
@@ -581,7 +580,7 @@ jobs:
|
||||
rm -f target/nextest/ci/junit.xml
|
||||
./scripts/ci/resource_sampler.sh start nextest-rio-v2
|
||||
trap './scripts/ci/resource_sampler.sh stop' EXIT
|
||||
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore --features rio-v2 \
|
||||
cargo nextest run --profile ci -p rustfs -p rustfs-ecstore -p rustfs-sse --features rio-v2 \
|
||||
2>&1 | tee artifacts/workspace/nextest.log
|
||||
cargo test -p rustfs --doc --features rio-v2
|
||||
|
||||
@@ -676,54 +675,6 @@ jobs:
|
||||
retention-days: 3
|
||||
if-no-files-found: warn
|
||||
|
||||
test-and-lint-gateway-stack:
|
||||
name: Test and Lint (gateway-stack)
|
||||
# The gateway S3 stack (rustfs/backlog#2734) sits behind the rustfs
|
||||
# `gateway-stack` feature, which no other pull-request lane lints or tests.
|
||||
# Unlike the dormant feature lanes above, this one runs for every code
|
||||
# change: each operation slice puts its handler tests and its refusal-matrix
|
||||
# row behind the feature, and a lane that ran only on demand would let them
|
||||
# rot behind a green pull request.
|
||||
if: needs.classify-changes.outputs.mode == 'full' && (github.event_name != 'pull_request' || github.event.action != 'closed')
|
||||
needs: [ quick-checks, classify-changes ]
|
||||
# Self-hosted for build scale and cache ownership: a workspace-scale Cargo
|
||||
# build that reads the ci-dev cache written on this image.
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 90
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Rust environment
|
||||
uses: ./.github/actions/setup
|
||||
with:
|
||||
rust-version: stable
|
||||
cache-shared-key: ci-dev-ea7eec74fe14
|
||||
cache-save-if: 'false'
|
||||
install-build-packaging-tools: 'false'
|
||||
|
||||
# A feature that does not compile fails here; nothing below is skipped
|
||||
# into a pass.
|
||||
- name: Run clippy with gateway-stack
|
||||
run: cargo clippy --locked -p rustfs --all-targets --features gateway-stack -- -D warnings
|
||||
|
||||
# The gateway stack's own tests: the assembly, the operation table and
|
||||
# its completeness, the shared handler sequence, the stack selection, and
|
||||
# the embedded server driven through the whole middleware stack. The
|
||||
# filter names modules, never operations.
|
||||
- name: Run tests with gateway-stack
|
||||
env:
|
||||
# The same bounded link concurrency as the other feature lanes.
|
||||
CARGO_BUILD_JOBS: "2"
|
||||
run: |
|
||||
cargo nextest run --profile ci --locked -p rustfs --features gateway-stack --no-tests fail \
|
||||
--status-level all --final-status-level all \
|
||||
-E 'test(/gateway_stack|gateway_handlers|server::stack::/) | binary(embedded_gateway_stack_test)'
|
||||
|
||||
build-rustfs-debug-binary:
|
||||
name: Build RustFS Debug Binary
|
||||
if: contains(fromJSON('["full", "e2e"]'), needs.classify-changes.outputs.mode) && (github.event_name != 'pull_request' || github.event.action != 'closed')
|
||||
@@ -986,8 +937,6 @@ jobs:
|
||||
# Retain the producer image and fixture paths until the runtime pilot passes.
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
RUSTFS_S3_STACK: legacy
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
@@ -1108,125 +1057,6 @@ jobs:
|
||||
path: ${{ runner.temp }}/rustfs-e2e-*/rustfs.log
|
||||
retention-days: 3
|
||||
|
||||
# The same e2e-smoke suite against the same debug binary with the gateway
|
||||
# S3 stack selected (rustfs/backlog#2734). Report-only: it is outside the
|
||||
# Test and Lint aggregate and becomes required at T2.10. The test-binary
|
||||
# download, identity, membership, run and completeness steps must stay
|
||||
# identical to e2e-tests; scripts/ci_gate.py enforces that.
|
||||
#
|
||||
# When it runs: every push to main or gateway/integration, merge group,
|
||||
# nightly schedule and manual dispatch, and every pull request that changes a
|
||||
# gateway-stack input (GATEWAY_SMOKE_PATHS and the rustfs-gateway pins in
|
||||
# scripts/ci_gate.py, published by Select CI scope as gateway_smoke).
|
||||
# Why it is skipped on every other pull request: until T2.10 the gateway
|
||||
# stack does not serve the whole smoke suite, so the lane fails on any
|
||||
# revision. A pull request that touches none of its inputs can neither cause
|
||||
# nor fix that failure, and a red check there says nothing about the change.
|
||||
# Skipped is the honest state; a failure must never be rendered green, so no
|
||||
# step here may carry continue-on-error. A selection that is missing or
|
||||
# unreadable runs the lane. At T2.10, when the lane becomes required, it
|
||||
# must run on every pull request again: delete the selection, do not extend
|
||||
# it.
|
||||
e2e-tests-gateway:
|
||||
name: e2e-smoke (gateway, report-only until T2.10)
|
||||
needs: [ classify-changes, build-rustfs-debug-binary ]
|
||||
if: github.event_name != 'pull_request' || needs.classify-changes.outputs.gateway_smoke != 'false'
|
||||
runs-on: sm-standard-2
|
||||
timeout-minutes: 30
|
||||
continue-on-error: true
|
||||
env:
|
||||
RUSTFS_S3_STACK: gateway
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Install verification runtime
|
||||
uses: ./.github/actions/test-runtime
|
||||
|
||||
- name: Download E2E test binaries
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: e2e-test-binaries
|
||||
path: ${{ runner.temp }}
|
||||
|
||||
- name: Verify E2E archive identity
|
||||
run: python3 scripts/ci_test_artifact.py verify --configuration e2e --archive "$RUNNER_TEMP/e2e-tests.tar.zst"
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install awscurl
|
||||
run: |
|
||||
python3 -m pip install --user --upgrade pip "awscurl==0.44"
|
||||
echo "AWSCURL_PATH=$HOME/.local/bin/awscurl" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Verify awscurl
|
||||
run: test -x "$AWSCURL_PATH"
|
||||
|
||||
# Download after the cache restore so the freshly built binary from the
|
||||
# build job always wins over anything restored into target/debug.
|
||||
- name: Download debug binary
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
name: rustfs-debug-binary
|
||||
path: target/debug
|
||||
|
||||
- name: Make binary executable
|
||||
run: chmod +x ./target/debug/rustfs
|
||||
|
||||
# Build the e2e test graph once. The archive is reused by the smoke
|
||||
# selection guard, security exact-count check, and run below, avoiding a
|
||||
# second compile of the same e2e_test target on cold runners (backlog#1645).
|
||||
- name: Verify e2e smoke test membership
|
||||
env:
|
||||
NEXTEST_ARCHIVE: ${{ runner.temp }}/e2e-tests.tar.zst
|
||||
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-smoke-list.json
|
||||
run: |
|
||||
cargo nextest list --profile e2e-smoke --archive-file "${NEXTEST_ARCHIVE}" --workspace-remap "$GITHUB_WORKSPACE" --extract-to "$GITHUB_WORKSPACE" --extract-overwrite --message-format json > "${NEXTEST_LISTING}"
|
||||
python3 ./scripts/check_test_wiring.py --check-profile e2e-smoke "${NEXTEST_LISTING}"
|
||||
./scripts/check_security_smoke_count.sh check "${NEXTEST_LISTING}"
|
||||
|
||||
# PR smoke subset of the in-repo e2e suite (backlog#1149 ci-4). The
|
||||
# profile.e2e-smoke default-filter in .config/nextest.toml is the single
|
||||
# wiring mechanism for e2e tests in CI — extend that filter instead of
|
||||
# adding new e2e jobs here. Each test spawns its own rustfs server on a
|
||||
# random port and reuses the downloaded debug binary above.
|
||||
- name: Run e2e smoke suite
|
||||
env:
|
||||
NEXTEST_ARCHIVE: ${{ runner.temp }}/e2e-tests.tar.zst
|
||||
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-smoke-logs
|
||||
SAMPLER_INTERVAL_SECS: "15"
|
||||
run: |
|
||||
./scripts/ci/resource_sampler.sh start e2e-smoke
|
||||
trap './scripts/ci/resource_sampler.sh stop' EXIT
|
||||
python3 scripts/e2e_binary.py run --features e2e-test-hooks -- cargo nextest run --profile e2e-smoke --cargo-metadata target/nextest/cargo-metadata.json --binaries-metadata target/nextest/binaries-metadata.json --workspace-remap "$GITHUB_WORKSPACE" --target-dir-remap "$GITHUB_WORKSPACE/target" \
|
||||
--status-level all --final-status-level all --failure-output final
|
||||
|
||||
- name: Verify e2e smoke execution completeness
|
||||
run: python3 scripts/ci_test_artifact.py evidence "$RUNNER_TEMP/rustfs-e2e-smoke-list.json" target/nextest/e2e-smoke/junit.xml
|
||||
|
||||
- name: Upload e2e smoke diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: e2e-smoke-gateway-diagnostics-${{ github.run_number }}-${{ github.run_attempt }}
|
||||
path: |
|
||||
${{ runner.temp }}/rustfs-e2e-smoke-logs/
|
||||
${{ runner.temp }}/rustfs-e2e-smoke-list.json
|
||||
if-no-files-found: warn
|
||||
|
||||
- name: Upload e2e smoke JUnit report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: e2e-smoke-gateway-junit-${{ github.run_number }}-${{ github.run_attempt }}
|
||||
path: target/nextest/e2e-smoke/junit.xml
|
||||
if-no-files-found: warn
|
||||
|
||||
e2e-full:
|
||||
name: End-to-End Tests (full merge gate)
|
||||
# Merge gate only (backlog#1149 ci-5): the never-automated user-visible
|
||||
@@ -1261,9 +1091,12 @@ jobs:
|
||||
- name: Verify E2E archive identity
|
||||
run: python3 scripts/ci_test_artifact.py verify --configuration e2e --archive "$RUNNER_TEMP/e2e-tests.tar.zst"
|
||||
|
||||
- name: Install network fault-injection tools
|
||||
- name: Install network fault-injection tools and the persistence test clock
|
||||
run: |
|
||||
sudo apt-get install -y iptables
|
||||
sudo apt-get install -y iptables libfaketime
|
||||
clock_library="$(dpkg-query -L libfaketime | grep -E '/libfaketime[.]so[.]1$')"
|
||||
test -f "$clock_library"
|
||||
echo "RUSTFS_PERSISTENCE_CLOCK_LIBRARY=$clock_library" >> "$GITHUB_ENV"
|
||||
sudo -n iptables --version
|
||||
# The endpoint-blackhole heal scenario needs CAP_NET_ADMIN. Containerised
|
||||
# runners can run iptables but not touch the rule set; the test then logs
|
||||
@@ -1370,8 +1203,14 @@ jobs:
|
||||
# default-filter in .config/nextest.toml is the single wiring mechanism —
|
||||
# extend that filter, never add ad-hoc e2e jobs here. Reuses the downloaded
|
||||
# debug binary; each test spawns its own rustfs server on a random port.
|
||||
- name: Download pinned release for persistence byte parity
|
||||
id: persistence-reference
|
||||
uses: ./.github/actions/reference-binary
|
||||
|
||||
- name: Run e2e full suite
|
||||
env:
|
||||
RUSTFS_PERSISTENCE_REFERENCE_BINARY: ${{ steps.persistence-reference.outputs.path }}
|
||||
RUSTFS_PERSISTENCE_XML_DIR: ${{ runner.temp }}/rustfs-persistence-xml
|
||||
CARGO_BIN_EXE_rustfs: ${{ runner.temp }}/rustfs-startup-cas-input/rustfs
|
||||
RUSTFS_E2E_STARTUP_CAS_BINARY: ${{ runner.temp }}/rustfs-startup-cas-input/rustfs
|
||||
RUSTFS_E2E_STARTUP_CAS_BUILD_MANIFEST: ${{ runner.temp }}/rustfs-startup-cas-input/rustfs.e2e-startup-cas-build.json
|
||||
@@ -1390,6 +1229,7 @@ jobs:
|
||||
path: |
|
||||
target/nextest/e2e-full/junit.xml
|
||||
${{ runner.temp }}/rustfs-e2e-full-list.json
|
||||
${{ runner.temp }}/rustfs-persistence-xml
|
||||
retention-days: 7
|
||||
|
||||
- name: Upload startup CAS evidence
|
||||
@@ -1612,7 +1452,6 @@ jobs:
|
||||
- fips-provider
|
||||
- test-and-lint-rio-v2
|
||||
- test-and-lint-protocols
|
||||
- test-and-lint-gateway-stack
|
||||
- build-rustfs-debug-binary
|
||||
- uring-integration
|
||||
- e2e-tests
|
||||
@@ -1648,7 +1487,6 @@ jobs:
|
||||
- core-contract
|
||||
- test-and-lint-rio-v2
|
||||
- test-and-lint-protocols
|
||||
- test-and-lint-gateway-stack
|
||||
- build-rustfs-debug-binary
|
||||
- build-rustfs-debug-binary-rio-v2
|
||||
- uring-integration
|
||||
|
||||
@@ -12,21 +12,18 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Nightly both-stack diff of the two e2e profiles only ci.yml runs, e2e-smoke
|
||||
# and e2e-full (rustfs/backlog#2772, T3.1). The other profiles carry a `stack`
|
||||
# dimension in their own workflows, where the existing lane is the legacy leg.
|
||||
# Nightly run of the two e2e profiles only ci.yml runs, e2e-smoke and e2e-full
|
||||
# (rustfs/backlog#2772, T3.1), on the gateway stack, which is the only S3 stack.
|
||||
# The workflow keeps its file and registry name from the period when it diffed two
|
||||
# stacks. Each leg uploads its JUnit report and server logs for 30 days; the one
|
||||
# comparison against the last legacy record (the `dual-stack-leg-<profile>-legacy`
|
||||
# artifacts of the final both-stack run) is made by hand with scripts/junit_diff.py.
|
||||
#
|
||||
# One build serves every leg. One preflight starts that binary with
|
||||
# RUSTFS_S3_STACK=gateway (scripts/dual_stack.py preflight); without a proven
|
||||
# gateway start the gateway legs do not run and the summary says `skipped:
|
||||
# gateway stack refuses startup: <why>`. Which stack a leg ran is read from the
|
||||
# servers' own start-up line. The gateway legs are report-only until T2.10.
|
||||
#
|
||||
# Left out of both stacks: `dual_stack_differential::` (servers with an explicit
|
||||
# Left out: `dual_stack_differential::` (servers with an explicit
|
||||
# stack), `fake_s3_target::`, the upgrade write-readiness cases and one deadline
|
||||
# case (no server), and `distributed_startup_regression_test::` (needs ci.yml's
|
||||
# hooks-binary manifest). Both e2e-full stacks use ci.yml's pinned mc and
|
||||
# Vault binaries and network fault-injection tools.
|
||||
# hooks-binary manifest). e2e-full uses ci.yml's pinned mc and Vault binaries
|
||||
# and network fault-injection tools.
|
||||
|
||||
name: dual-stack-nightly
|
||||
|
||||
@@ -50,13 +47,11 @@ defaults:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build once and probe the gateway stack
|
||||
name: Build once
|
||||
if: github.repository == 'rustfs/rustfs'
|
||||
# The runner and cache of ci.yml's build-rustfs-debug-binary.
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 60
|
||||
outputs:
|
||||
stacks: ${{ steps.preflight.outputs.stacks }}
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
@@ -86,47 +81,15 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
# Without a proven gateway start there is no gateway leg to run.
|
||||
- name: Gateway preflight
|
||||
id: preflight
|
||||
run: |
|
||||
if python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/preflight/stack.json"; then
|
||||
echo 'stacks=["legacy","gateway"]' >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo 'stacks=["legacy"]' >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
# The evidence stands in for a gateway leg that is skipped; a leg that runs overwrites it.
|
||||
- name: Upload the preflight evidence for e2e-smoke
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: dual-stack-leg-e2e-smoke-gateway
|
||||
path: ${{ runner.temp }}/preflight
|
||||
if-no-files-found: warn
|
||||
retention-days: 7
|
||||
|
||||
- name: Upload the preflight evidence for e2e-full
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: dual-stack-leg-e2e-full-gateway
|
||||
path: ${{ runner.temp }}/preflight
|
||||
if-no-files-found: warn
|
||||
retention-days: 7
|
||||
|
||||
leg:
|
||||
name: ${{ matrix.profile }} (${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
|
||||
name: ${{ matrix.profile }}
|
||||
needs: [ build ]
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 120
|
||||
# Report-only until T2.10: the gateway stack cannot serve the suites yet.
|
||||
continue-on-error: ${{ matrix.stack == 'gateway' }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
profile: [ e2e-smoke, e2e-full ]
|
||||
stack: ${{ fromJSON(needs.build.outputs.stacks) }}
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
@@ -208,10 +171,9 @@ jobs:
|
||||
run: |
|
||||
"$RUSTFS_TEST_VAULT_BIN" version
|
||||
|
||||
- name: Run the profile on the ${{ matrix.stack }} stack
|
||||
- name: Run the profile
|
||||
env:
|
||||
PROFILE: ${{ matrix.profile }}
|
||||
RUSTFS_S3_STACK: ${{ matrix.stack }}
|
||||
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/server-logs
|
||||
run: |
|
||||
chmod +x target/debug/rustfs
|
||||
@@ -220,23 +182,14 @@ jobs:
|
||||
filter="$filter & not test(=list_objects_v2_pagination_test::tests::test_list_objects_v2_deadline_rejects_unresponsive_peer)"
|
||||
python3 scripts/e2e_binary.py run --features e2e-test-hooks -- cargo nextest run --profile "$PROFILE" -p e2e_test -E "$filter"
|
||||
|
||||
- name: Prove the stack and upload the leg
|
||||
- name: Upload the leg
|
||||
if: always()
|
||||
uses: ./.github/actions/dual-stack-leg
|
||||
with: { profile: "${{ matrix.profile }}", stack: "${{ matrix.stack }}", logs: "${{ runner.temp }}/server-logs" }
|
||||
|
||||
summary:
|
||||
name: Both-stack diff summary
|
||||
needs: [ build, leg ]
|
||||
if: github.repository == 'rustfs/rustfs' && always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: ./.github/actions/dual-stack-summary
|
||||
with:
|
||||
profiles: e2e-smoke,e2e-full
|
||||
name: e2e-nightly-${{ matrix.profile }}
|
||||
overwrite: true
|
||||
path: |
|
||||
target/nextest/${{ matrix.profile }}/junit.xml
|
||||
${{ runner.temp }}/server-logs
|
||||
if-no-files-found: warn
|
||||
retention-days: 30
|
||||
|
||||
@@ -53,14 +53,11 @@ concurrency:
|
||||
jobs:
|
||||
distributed:
|
||||
if: github.repository == 'rustfs/rustfs'
|
||||
name: Distributed 4-node 4-disk e2e (${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
|
||||
name: Distributed 4-node 4-disk e2e
|
||||
# GitHub-hosted VM: loop and tmpfs mounts work here. sm-standard-4 is an
|
||||
# ARC pod and rejects both (`mount -o loop` ENOENT, tmpfs "read-only").
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 180
|
||||
# The gateway leg is report-only until T2.10.
|
||||
continue-on-error: ${{ matrix.stack == 'gateway' }}
|
||||
strategy: { fail-fast: false, matrix: { stack: [legacy, gateway] } }
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
NO_PROXY: 127.0.0.1,localhost
|
||||
@@ -132,11 +129,6 @@ jobs:
|
||||
run: |
|
||||
python3 scripts/e2e_binary.py build --bins --features e2e-test-hooks
|
||||
|
||||
# A gateway binary that refuses to start skips the suite; the summary says why.
|
||||
- name: Gateway preflight
|
||||
if: matrix.stack == 'gateway'
|
||||
run: python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/leg/stack.json"
|
||||
|
||||
- name: Verify distributed e2e membership
|
||||
env:
|
||||
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-distributed-list.json
|
||||
@@ -148,7 +140,6 @@ jobs:
|
||||
env:
|
||||
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-distributed-logs
|
||||
FILTER: ${{ inputs.filter }}
|
||||
RUSTFS_S3_STACK: ${{ matrix.stack }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rm -f target/nextest/e2e-distributed/junit.xml
|
||||
@@ -159,19 +150,11 @@ jobs:
|
||||
fi
|
||||
test -s target/nextest/e2e-distributed/junit.xml
|
||||
|
||||
- name: Prove the stack and upload the leg
|
||||
if: always()
|
||||
uses: ./.github/actions/dual-stack-leg
|
||||
with:
|
||||
profile: e2e-distributed
|
||||
stack: ${{ matrix.stack }}
|
||||
logs: ${{ runner.temp }}/rustfs-e2e-distributed-logs
|
||||
|
||||
- name: Upload distributed e2e diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: e2e-distributed-${{ github.run_number }}-${{ matrix.stack }}
|
||||
name: e2e-distributed-${{ github.run_number }}
|
||||
path: |
|
||||
target/nextest/e2e-distributed/junit.xml
|
||||
${{ runner.temp }}/rustfs-e2e-distributed-list.json
|
||||
@@ -191,20 +174,6 @@ jobs:
|
||||
fi
|
||||
done
|
||||
|
||||
dual-stack-summary:
|
||||
name: Both-stack diff summary
|
||||
needs: [distributed]
|
||||
if: github.repository == 'rustfs/rustfs' && always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: ./.github/actions/dual-stack-summary
|
||||
with:
|
||||
profiles: e2e-distributed
|
||||
|
||||
alert-on-failure:
|
||||
name: Alert on scheduled failure
|
||||
needs: [distributed]
|
||||
|
||||
@@ -54,18 +54,15 @@ concurrency:
|
||||
jobs:
|
||||
repl-nightly:
|
||||
if: github.repository == 'rustfs/rustfs'
|
||||
name: Replication e2e (nightly, ${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
|
||||
name: Replication e2e (nightly)
|
||||
# dual-node tests spawn two full rustfs servers each; the extra headroom
|
||||
# over the per-PR sm-standard-2 e2e job keeps the parallel process fan-out
|
||||
# from starving the runner. Mirrors the ILM serial lane's runner class.
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 45
|
||||
# The gateway leg is report-only until T2.10.
|
||||
continue-on-error: ${{ matrix.stack == 'gateway' }}
|
||||
strategy: { fail-fast: false, matrix: { stack: [legacy, gateway] } }
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
RUSTFS_BUILD_FEATURES: ${{ matrix.stack == 'gateway' && 'gateway-stack' || '' }}
|
||||
RUSTFS_BUILD_FEATURES: ""
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
@@ -99,11 +96,6 @@ jobs:
|
||||
run: |
|
||||
python3 scripts/e2e_binary.py build --bins --features "$RUSTFS_BUILD_FEATURES"
|
||||
|
||||
# A gateway binary that refuses to start skips the suite; the summary says why.
|
||||
- name: Gateway preflight
|
||||
if: matrix.stack == 'gateway'
|
||||
run: python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/leg/stack.json"
|
||||
|
||||
- name: Verify replication e2e membership
|
||||
env:
|
||||
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-repl-nightly-list.json
|
||||
@@ -114,22 +106,13 @@ jobs:
|
||||
- name: Run replication e2e nightly suite
|
||||
env:
|
||||
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-repl-nightly-logs
|
||||
RUSTFS_S3_STACK: ${{ matrix.stack }}
|
||||
run: python3 scripts/e2e_binary.py run --features "$RUSTFS_BUILD_FEATURES" -- cargo nextest run --profile e2e-repl-nightly -p e2e_test
|
||||
|
||||
- name: Prove the stack and upload the leg
|
||||
if: always()
|
||||
uses: ./.github/actions/dual-stack-leg
|
||||
with:
|
||||
profile: e2e-repl-nightly
|
||||
stack: ${{ matrix.stack }}
|
||||
logs: ${{ runner.temp }}/rustfs-e2e-repl-nightly-logs
|
||||
|
||||
- name: Upload nextest junit report
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: e2e-replication-nightly-junit-${{ github.run_number }}-${{ matrix.stack }}
|
||||
name: e2e-replication-nightly-junit-${{ github.run_number }}
|
||||
path: |
|
||||
target/nextest/e2e-repl-nightly/junit.xml
|
||||
${{ runner.temp }}/rustfs-e2e-repl-nightly-list.json
|
||||
@@ -139,12 +122,9 @@ jobs:
|
||||
|
||||
cluster-nightly:
|
||||
if: github.repository == 'rustfs/rustfs'
|
||||
name: Cluster fault e2e (nightly, ${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
|
||||
name: Cluster fault e2e (nightly)
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 90
|
||||
# The gateway leg is report-only until T2.10.
|
||||
continue-on-error: ${{ matrix.stack == 'gateway' }}
|
||||
strategy: { fail-fast: false, matrix: { stack: [legacy, gateway] } }
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
steps:
|
||||
@@ -165,11 +145,6 @@ jobs:
|
||||
run: |
|
||||
python3 scripts/e2e_binary.py build --bins --features e2e-test-hooks
|
||||
|
||||
# A gateway binary that refuses to start skips the suite; the summary says why.
|
||||
- name: Gateway preflight
|
||||
if: matrix.stack == 'gateway'
|
||||
run: python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/leg/stack.json"
|
||||
|
||||
- name: Verify cluster fault e2e membership
|
||||
env:
|
||||
NEXTEST_LISTING: ${{ runner.temp }}/rustfs-e2e-nightly-list.json
|
||||
@@ -181,22 +156,13 @@ jobs:
|
||||
env:
|
||||
CARGO_BIN_EXE_rustfs: ${{ github.workspace }}/target/debug/rustfs
|
||||
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-nightly-logs
|
||||
RUSTFS_S3_STACK: ${{ matrix.stack }}
|
||||
run: python3 scripts/e2e_binary.py run --features e2e-test-hooks -- cargo nextest run --profile e2e-nightly -p e2e_test
|
||||
|
||||
- name: Prove the stack and upload the leg
|
||||
if: always()
|
||||
uses: ./.github/actions/dual-stack-leg
|
||||
with:
|
||||
profile: e2e-nightly
|
||||
stack: ${{ matrix.stack }}
|
||||
logs: ${{ runner.temp }}/rustfs-e2e-nightly-logs
|
||||
|
||||
- name: Upload cluster fault diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: e2e-cluster-nightly-${{ github.run_number }}-${{ matrix.stack }}
|
||||
name: e2e-cluster-nightly-${{ github.run_number }}
|
||||
path: |
|
||||
target/nextest/e2e-nightly/junit.xml
|
||||
${{ runner.temp }}/rustfs-e2e-nightly-list.json
|
||||
@@ -206,15 +172,12 @@ jobs:
|
||||
|
||||
protocols-nightly:
|
||||
if: github.repository == 'rustfs/rustfs'
|
||||
name: Protocol e2e (nightly, ${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
|
||||
name: Protocol e2e (nightly)
|
||||
runs-on: sm-standard-4
|
||||
timeout-minutes: 90
|
||||
# The gateway leg is report-only until T2.10.
|
||||
continue-on-error: ${{ matrix.stack == 'gateway' }}
|
||||
strategy: { fail-fast: false, matrix: { stack: [legacy, gateway] } }
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
RUSTFS_BUILD_FEATURES: ${{ matrix.stack == 'gateway' && 'ftps,webdav,sftp,gateway-stack' || 'ftps,webdav,sftp' }}
|
||||
RUSTFS_BUILD_FEATURES: ftps,webdav,sftp
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
@@ -238,11 +201,6 @@ jobs:
|
||||
- name: Build protocol server
|
||||
run: python3 scripts/e2e_binary.py build --features "$RUSTFS_BUILD_FEATURES"
|
||||
|
||||
# A gateway binary that refuses to start skips the suite; the summary says why.
|
||||
- name: Gateway preflight
|
||||
if: matrix.stack == 'gateway'
|
||||
run: python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/leg/stack.json"
|
||||
|
||||
# The suite owns fixed protocol ports and serializes its internal cases.
|
||||
- name: Verify protocol e2e membership
|
||||
env:
|
||||
@@ -254,28 +212,16 @@ jobs:
|
||||
- name: Run protocol e2e nightly suite
|
||||
env:
|
||||
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-protocol-e2e-logs
|
||||
RUSTFS_S3_STACK: ${{ matrix.stack }}
|
||||
# These servers set no log level of their own; the stack proof reads their start-up line.
|
||||
RUST_LOG: rustfs=info
|
||||
# The servers inherit nextest's stdout (--no-capture): keep it where the stack proof reads it.
|
||||
run: |
|
||||
set -o pipefail
|
||||
mkdir -p "$RUSTFS_E2E_LOG_DIR"
|
||||
python3 scripts/e2e_binary.py run --features "$RUSTFS_BUILD_FEATURES" -- cargo nextest run -j 1 --profile e2e-protocols -p e2e_test --no-capture 2>&1 | tee "$RUSTFS_E2E_LOG_DIR/nextest.log"
|
||||
|
||||
- name: Prove the stack and upload the leg
|
||||
if: always()
|
||||
uses: ./.github/actions/dual-stack-leg
|
||||
with:
|
||||
profile: e2e-protocols
|
||||
stack: ${{ matrix.stack }}
|
||||
logs: ${{ runner.temp }}/rustfs-protocol-e2e-logs
|
||||
|
||||
- name: Upload protocol diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: e2e-protocol-nightly-${{ github.run_number }}-${{ matrix.stack }}
|
||||
name: e2e-protocol-nightly-${{ github.run_number }}
|
||||
path: |
|
||||
target/nextest/e2e-protocols/junit.xml
|
||||
${{ runner.temp }}/rustfs-e2e-protocols-list.json
|
||||
@@ -283,20 +229,6 @@ jobs:
|
||||
retention-days: 7
|
||||
if-no-files-found: warn
|
||||
|
||||
dual-stack-summary:
|
||||
name: Both-stack diff summary
|
||||
needs: [repl-nightly, cluster-nightly, protocols-nightly]
|
||||
if: github.repository == 'rustfs/rustfs' && always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: ./.github/actions/dual-stack-summary
|
||||
with:
|
||||
profiles: e2e-repl-nightly,e2e-nightly,e2e-protocols
|
||||
|
||||
alert-on-failure:
|
||||
name: Alert on scheduled failure
|
||||
needs: [repl-nightly, cluster-nightly, protocols-nightly]
|
||||
|
||||
@@ -90,11 +90,16 @@ jobs:
|
||||
- version: 1.0.1
|
||||
asset: rustfs-linux-x86_64-gnu-v1.0.1.zip
|
||||
sha256: 9742e183cb0dfb0d48fa909797af572fe47b7f827569036baa4156e0d3958ee5
|
||||
- version: 1.0.5
|
||||
asset: rustfs-linux-x86_64-gnu-v1.0.5.zip
|
||||
sha256: 5addae2f74756bf80104d0975e6347cda843bc2daffdfcd1f0cb80118b95cbd0
|
||||
revision: 34e6449ed90e3d3a106f6655342e0b3127f33082
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
UPGRADE_SOURCE_VERSION: ${{ matrix.source.version }}
|
||||
UPGRADE_SOURCE_ASSET: ${{ matrix.source.asset }}
|
||||
UPGRADE_SOURCE_SHA256: ${{ matrix.source.sha256 }}
|
||||
UPGRADE_SOURCE_REVISION: ${{ matrix.source.revision }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
@@ -132,6 +137,13 @@ jobs:
|
||||
unzip -q "$archive" -d "$SOURCE_DIR"
|
||||
chmod +x "$SOURCE_DIR/rustfs"
|
||||
test -x "$SOURCE_DIR/rustfs"
|
||||
if [[ -n "$UPGRADE_SOURCE_REVISION" ]]; then
|
||||
mkdir -p "$RUNNER_TEMP/rustfs-upgrade-logs"
|
||||
version_log="$RUNNER_TEMP/rustfs-upgrade-logs/source-version.txt"
|
||||
"$SOURCE_DIR/rustfs" --version | tee "$version_log"
|
||||
grep -Fx "rustfs $UPGRADE_SOURCE_VERSION" "$version_log"
|
||||
grep -Eq "^git commit[[:space:]]*:[[:space:]]*$UPGRADE_SOURCE_REVISION$" "$version_log"
|
||||
fi
|
||||
echo "RUSTFS_UPGRADE_SOURCE_BINARY=$SOURCE_DIR/rustfs" >> "$GITHUB_ENV"
|
||||
echo "RUSTFS_E2E_LOG_DIR=$RUNNER_TEMP/rustfs-upgrade-logs" >> "$GITHUB_ENV"
|
||||
|
||||
@@ -151,12 +163,14 @@ jobs:
|
||||
multipart-layout-upgrade:direct_upgrade_from_previous_release_preserves_multipart_layouts
|
||||
multipart-layout-baseline:previous_release_baseline_replicates_multipart_layouts
|
||||
)
|
||||
if [[ "$UPGRADE_SOURCE_VERSION" == "1.0.0-rc.5" ]]; then
|
||||
cases+=(odm-config-rollback:rc5_rollback_requires_restoring_odm_configuration)
|
||||
cases+=(checkpoint-upgrade:rc5_checkpoint_upgrade_rewinds_signed_progress_without_losing_objects)
|
||||
else
|
||||
cases+=(legacy-delete-reservation:stable_upgrade_deletes_foreign_reservations_without_losing_live_objects)
|
||||
fi
|
||||
case "$UPGRADE_SOURCE_VERSION" in
|
||||
1.0.0-rc.5)
|
||||
cases+=(odm-config-rollback:rc5_rollback_requires_restoring_odm_configuration)
|
||||
cases+=(checkpoint-upgrade:rc5_checkpoint_upgrade_rewinds_signed_progress_without_losing_objects) ;;
|
||||
1.0.1) cases+=(legacy-delete-reservation:stable_upgrade_deletes_foreign_reservations_without_losing_live_objects) ;;
|
||||
1.0.5) ;; # The bucket rollback case also completes an in-flight multipart upload.
|
||||
*) echo "::error::Unknown upgrade source $UPGRADE_SOURCE_VERSION"; exit 1 ;;
|
||||
esac
|
||||
status=0
|
||||
for entry in "${cases[@]}"; do
|
||||
artifact="${entry%%:*}"
|
||||
@@ -178,7 +192,7 @@ jobs:
|
||||
exit "$status"
|
||||
|
||||
- name: Run mixed-version MPU recovery
|
||||
if: ${{ !cancelled() && steps.verify_source.outcome == 'success' }}
|
||||
if: ${{ !cancelled() && steps.verify_source.outcome == 'success' && matrix.source.version != '1.0.5' }}
|
||||
timeout-minutes: 15
|
||||
env:
|
||||
NO_PROXY: 127.0.0.1,localhost,::1
|
||||
@@ -199,6 +213,24 @@ jobs:
|
||||
"$mpu_test" -- --exact --nocapture --test-threads=1 \
|
||||
2>&1 | tee "$RUSTFS_E2E_LOG_DIR/test.log"
|
||||
|
||||
- name: Verify gateway baseline G09 evidence
|
||||
if: ${{ success() && matrix.source.version == '1.0.5' }}
|
||||
shell: bash
|
||||
run: |
|
||||
for field in mixed_version_reader_evidence mixed_version_writer_evidence rollback_payload_evidence; do
|
||||
directory=mixed-version-upgrade
|
||||
if [[ "$field" == rollback_payload_evidence ]]; then directory=bucket-config-rollback; fi
|
||||
jq -e --arg field "$field" --arg current "$GITHUB_SHA" --arg previous "$UPGRADE_SOURCE_REVISION" \
|
||||
'.gate == "G09" and .field == $field and .current_revision == $current and .previous_revision == $previous
|
||||
and ($field != "rollback_payload_evidence" or .rollback_payload_replayed == true)' \
|
||||
"$RUNNER_TEMP/rustfs-upgrade-g09-evidence/$directory/G09-$field.json"
|
||||
done
|
||||
jq -e --arg current "$GITHUB_SHA" --arg previous "$UPGRADE_SOURCE_REVISION" \
|
||||
'.current_revision == $current and .previous_revision == $previous
|
||||
and .part_sizes == [5242880, 5242880, 4096] and .bytes == (.part_sizes | add)
|
||||
and (.rollback_read_sha256 | test("^[a-f0-9]{64}$")) and .rollback_read_sha256 == .roll_forward_read_sha256' \
|
||||
"$RUNNER_TEMP/rustfs-upgrade-g09-evidence/bucket-config-rollback/inflight-multipart-rollback.json"
|
||||
|
||||
- name: Upload scanner/heal G09 evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
|
||||
@@ -15,31 +15,20 @@
|
||||
# Gateway black-box acceptance lanes (rustfs/backlog#2775 T3.4, #2776 T3.5).
|
||||
#
|
||||
# Runs two suites of the rustfs/gateway repository against the candidate binary,
|
||||
# once per S3 stack (RUSTFS_S3_STACK=legacy and =gateway), one server per stack:
|
||||
# one server:
|
||||
#
|
||||
# - the conformance corpus, `--profile rustfs`. That profile describes the
|
||||
# gateway edge, so scripts/check_conformance_rulings.py judges the gateway
|
||||
# stack against .config/conformance-rulings.toml (red: an unruled failure, a
|
||||
# ruled case failing differently, a stale ruling, a skip on the server's own
|
||||
# answer) and publishes the legacy run as a reference that is never judged:
|
||||
# it only has to serve, stay up and complete;
|
||||
# - the client matrix, ci/compat/run_matrix.sh --external, judged per stack by
|
||||
# - the conformance corpus, `--profile rustfs`, judged by
|
||||
# scripts/check_conformance_rulings.py against .config/conformance-rulings.toml
|
||||
# (red: an unruled failure, a ruled case failing differently, a stale ruling,
|
||||
# a skip on the server's own answer);
|
||||
# - the client matrix, ci/compat/run_matrix.sh --external, judged by
|
||||
# scripts/compat_matrix_report.py (no `fail`, no `sut-unregistered`, every
|
||||
# client ran; a client that could not be installed is reported as skipped).
|
||||
# The legacy matrix is the baseline: every cell that passes on legacy must
|
||||
# pass on gateway (`compare`).
|
||||
#
|
||||
# The suites are checked out at the rustfs/gateway rev Cargo.toml pins, so the
|
||||
# suite and the framework under test never drift apart. The verdict of each
|
||||
# stack is computed from what the run left on disk (startup record, the stack
|
||||
# the server's own log names, runner exit code, liveness after the corpus,
|
||||
# report), never from the exit status of an earlier step. Needs
|
||||
# scripts/dual_stack.py and the `s3_stack` startup field of rustfs/rustfs#9367.
|
||||
#
|
||||
# The gateway stack is report-only until T2.10: its job may fail without failing
|
||||
# the workflow, and its summary says what it observed (did not start, or how many
|
||||
# cases ran, passed, failed and were answered 501). The stack comparison is
|
||||
# report-only for the same reason; its conformance half is information only.
|
||||
# suite and the framework under test never drift apart. The verdict is computed
|
||||
# from what the run left on disk (startup record, runner exit code, liveness
|
||||
# after the corpus, report), never from the exit status of an earlier step.
|
||||
#
|
||||
# Not a pull-request gate. Scheduled failures are owned by the scheduled-validation
|
||||
# watchdog (.github/scheduled-validations.json).
|
||||
@@ -166,21 +155,15 @@ jobs:
|
||||
retention-days: 1
|
||||
|
||||
acceptance:
|
||||
name: ${{ matrix.stack == 'gateway' && 'Acceptance (gateway, report-only until T2.10)' || 'Acceptance (legacy)' }}
|
||||
name: Acceptance
|
||||
needs: [ plan, build-candidate, build-gateway-tools ]
|
||||
# GitHub-hosted like the s3-tests targets of reference-parity.yml: the job
|
||||
# only runs prebuilt binaries and the pinned clients, none of which needs Docker.
|
||||
runs-on: ubuntu-latest
|
||||
# About 3x the 15 minutes the legacy job took in run 43325101234 (client install about
|
||||
# About 3x the 15 minutes the job took in run 43325101234 (client install about
|
||||
# 8, matrix about 3, corpus about 3), so a hung server costs 45 runner minutes, not more.
|
||||
timeout-minutes: 45
|
||||
continue-on-error: ${{ matrix.stack == 'gateway' }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
stack: [ legacy, gateway ]
|
||||
env:
|
||||
STACK: ${{ matrix.stack }}
|
||||
ENDPOINT: http://127.0.0.1:9000
|
||||
# The conformance suite signs with these fixed fixture credentials (the AWS
|
||||
# documentation example pair), so the candidate is started with them and the
|
||||
@@ -213,10 +196,8 @@ jobs:
|
||||
name: gateway-acceptance-tools
|
||||
path: tools
|
||||
|
||||
# Records `ready`, or what the process said when it exited, in lane/startup.txt. `ready`
|
||||
# also needs the server's own `server_starting` log event to name the requested stack
|
||||
# (its `s3_stack` field comes from rustfs/rustfs#9367; scripts/dual_stack.py reads it).
|
||||
- name: Start candidate (${{ matrix.stack }} stack)
|
||||
# Records `ready`, or what the process said when it exited, in lane/startup.txt.
|
||||
- name: Start candidate
|
||||
run: |
|
||||
set -uo pipefail
|
||||
chmod +x target/debug/rustfs tools/*
|
||||
@@ -224,7 +205,7 @@ jobs:
|
||||
target/debug/rustfs --version | tee lane/candidate-version.txt
|
||||
# The four directories share the runner's one disk; the bypass is the CI case the
|
||||
# physical-disk guard sanctions (as in mint.yml).
|
||||
RUSTFS_S3_STACK="$STACK" RUSTFS_UNSAFE_BYPASS_DISK_CHECK=true RUST_LOG=info target/debug/rustfs --address 127.0.0.1:9000 \
|
||||
RUSTFS_UNSAFE_BYPASS_DISK_CHECK=true RUST_LOG=info target/debug/rustfs --address 127.0.0.1:9000 \
|
||||
--access-key "$ACCESS_KEY" --secret-key "$SECRET_KEY" "$RUNNER_TEMP"/data/rustfs{0..3} \
|
||||
> lane/rustfs.log 2>&1 &
|
||||
pid=$!
|
||||
@@ -239,13 +220,8 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
if curl -sf "$ENDPOINT/health/ready" >/dev/null; then
|
||||
if python3 scripts/dual_stack.py stack --expect "$STACK" --out lane/stack.json lane/rustfs.log > /dev/null; then
|
||||
echo ready > lane/startup.txt
|
||||
exit 0
|
||||
fi
|
||||
echo "did not start: stack not observed" > lane/startup.txt
|
||||
cat lane/startup.txt
|
||||
exit 1
|
||||
echo ready > lane/startup.txt
|
||||
exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
@@ -338,58 +314,23 @@ jobs:
|
||||
run: |
|
||||
set -uo pipefail
|
||||
status=0
|
||||
python3 scripts/check_conformance_rulings.py --stack "$STACK" --run-dir lane | tee -a "$GITHUB_STEP_SUMMARY" || status=1
|
||||
python3 scripts/compat_matrix_report.py check --stack "$STACK" --run-dir lane | tee -a "$GITHUB_STEP_SUMMARY" || status=1
|
||||
python3 scripts/check_conformance_rulings.py --run-dir lane | tee -a "$GITHUB_STEP_SUMMARY" || status=1
|
||||
python3 scripts/compat_matrix_report.py check --run-dir lane | tee -a "$GITHUB_STEP_SUMMARY" || status=1
|
||||
exit "$status"
|
||||
|
||||
- name: Upload lane results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: gateway-acceptance-lane-${{ matrix.stack }}
|
||||
name: gateway-acceptance-lane
|
||||
overwrite: true
|
||||
path: |
|
||||
lane/*.txt
|
||||
lane/*.log
|
||||
lane/report.json
|
||||
lane/stack.json
|
||||
lane/compat/matrix.json
|
||||
lane/compat/probe.jsonl
|
||||
lane/compat/sut.log
|
||||
lane/compat/results/**
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
compare:
|
||||
name: Compare stacks (report-only until T2.10)
|
||||
needs: [ acceptance ]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Download lane results
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
pattern: gateway-acceptance-lane-*
|
||||
path: lanes
|
||||
|
||||
- name: Diff legacy and gateway
|
||||
run: |
|
||||
set -uo pipefail
|
||||
status=0
|
||||
{
|
||||
python3 scripts/check_conformance_rulings.py \
|
||||
--diff lanes/gateway-acceptance-lane-legacy lanes/gateway-acceptance-lane-gateway || status=1
|
||||
echo
|
||||
python3 scripts/compat_matrix_report.py diff \
|
||||
--legacy lanes/gateway-acceptance-lane-legacy --gateway lanes/gateway-acceptance-lane-gateway || status=1
|
||||
} > diff.md
|
||||
cat diff.md
|
||||
cat diff.md >> "$GITHUB_STEP_SUMMARY"
|
||||
exit "$status"
|
||||
|
||||
@@ -44,13 +44,6 @@
|
||||
# well inside the 120-minute budget and buys deterministic infra. The
|
||||
# docker-capable self-hosted `dind-sm-standard-2` label was the alternative but
|
||||
# has fewer cores and reintroduces fleet-state risk for no reliability gain.
|
||||
#
|
||||
# Stack dimension (rustfs/backlog#2774, T3.3): one image, run with RUSTFS_S3_STACK=legacy and
|
||||
# =gateway. `compare` (scripts/mint_stack_diff.py) holds the gate that every case legacy passes
|
||||
# passes on gateway with no new failure. The gateway leg and `compare` are report-only until
|
||||
# T2.10. A gateway server that refuses to start stops its leg at "Wait for RustFS ready", before
|
||||
# mint runs; the summary says `skipped: gateway stack refuses startup: <why>`. The stack is read
|
||||
# from the server's own start-up line (scripts/dual_stack.py stack).
|
||||
|
||||
name: mint
|
||||
|
||||
@@ -145,16 +138,8 @@ jobs:
|
||||
retention-days: 1
|
||||
|
||||
mint:
|
||||
name: mint (${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
|
||||
name: mint
|
||||
needs: [image]
|
||||
# Report-only until T2.10: the gateway stack cannot serve the suites yet.
|
||||
continue-on-error: ${{ matrix.stack == 'gateway' }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
stack: [legacy, gateway]
|
||||
env:
|
||||
STACK: ${{ matrix.stack }}
|
||||
# GitHub-hosted: reliably provides a running Docker daemon + buildx +
|
||||
# python3. See the header note (ci-2) for why the self-hosted sm-standard-4
|
||||
# label was abandoned (no docker.sock on the pod its only run landed on).
|
||||
@@ -194,7 +179,6 @@ jobs:
|
||||
-e RUSTFS_SECRET_KEY="${S3_SECRET_KEY}" \
|
||||
-e RUSTFS_VOLUMES="/data/rustfs{0...3}" \
|
||||
-e RUSTFS_UNSAFE_BYPASS_DISK_CHECK=true \
|
||||
-e RUSTFS_S3_STACK="${STACK}" \
|
||||
-e RUST_LOG=rustfs=info \
|
||||
-v /tmp/rustfs-mint:/data \
|
||||
rustfs-ci
|
||||
@@ -291,47 +275,13 @@ jobs:
|
||||
mkdir -p artifacts/rustfs-mint
|
||||
docker logs rustfs-mint > artifacts/rustfs-mint/rustfs.log 2>&1 || true
|
||||
|
||||
- name: Prove which stack the server selected
|
||||
if: always()
|
||||
run: python3 scripts/dual_stack.py stack --expect "${STACK}" --out artifacts/stack.json artifacts/rustfs-mint
|
||||
|
||||
- name: Upload artifacts
|
||||
if: always() && env.ACT != 'true'
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: mint-${{ matrix.stack }}
|
||||
name: mint
|
||||
path: artifacts/**
|
||||
|
||||
compare:
|
||||
name: Compare stacks (report-only until T2.10)
|
||||
needs: [mint]
|
||||
if: always()
|
||||
continue-on-error: true
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Download both legs
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
pattern: mint-{legacy,gateway}
|
||||
path: legs
|
||||
|
||||
# A leg that never uploaded leaves no directory: create both so that the
|
||||
# comparison reports "no result" for it instead of failing to find it.
|
||||
- name: Compare the stacks
|
||||
run: |
|
||||
# The shell runs with -e; the exit status is reported after the summary is written.
|
||||
set +e -u -o pipefail
|
||||
mkdir -p legs/mint-legacy legs/mint-gateway
|
||||
python3 scripts/mint_stack_diff.py legs/mint-legacy legs/mint-gateway | tee report.txt
|
||||
status="${PIPESTATUS[0]}"
|
||||
{ echo '## Mint: gateway versus legacy'; echo; echo '```'; cat report.txt; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
|
||||
exit "$status"
|
||||
|
||||
alert-on-failure:
|
||||
name: Alert on scheduled failure
|
||||
needs: [image, mint]
|
||||
|
||||
@@ -68,14 +68,11 @@ env:
|
||||
|
||||
jobs:
|
||||
minio-source:
|
||||
name: MinIO source (read-through, list-through, backfill, ${{ matrix.stack }}${{ matrix.stack == 'gateway' && ', report-only until T2.10' || '' }})
|
||||
name: MinIO source (read-through, list-through, backfill)
|
||||
# Keep this scheduled interoperability lane scoped to the upstream repo.
|
||||
if: github.repository == 'rustfs/rustfs'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
# The gateway leg is report-only until T2.10.
|
||||
continue-on-error: ${{ matrix.stack == 'gateway' }}
|
||||
strategy: { fail-fast: false, matrix: { stack: [legacy, gateway] } }
|
||||
env:
|
||||
NO_PROXY: 127.0.0.1,localhost
|
||||
# Fixed credentials of the container this job starts and throws away;
|
||||
@@ -140,11 +137,6 @@ jobs:
|
||||
- name: Build the RustFS binary under test
|
||||
run: python3 scripts/e2e_binary.py build --bins
|
||||
|
||||
# A gateway binary that refuses to start skips the suite; the summary says why.
|
||||
- name: Gateway preflight
|
||||
if: matrix.stack == 'gateway'
|
||||
run: python3 scripts/dual_stack.py preflight --binary target/debug/rustfs --out "$RUNNER_TEMP/leg/stack.json"
|
||||
|
||||
# The lane selects tests by module, so a rename would quietly shrink it.
|
||||
# The committed digest in .config/e2e-odm-interop-selection.txt fails
|
||||
# closed on that.
|
||||
@@ -155,18 +147,9 @@ jobs:
|
||||
|
||||
- name: Run the interop cases against MinIO
|
||||
env:
|
||||
RUSTFS_S3_STACK: ${{ matrix.stack }}
|
||||
RUSTFS_E2E_LOG_DIR: ${{ runner.temp }}/rustfs-e2e-logs
|
||||
run: python3 scripts/e2e_binary.py run -- cargo nextest run --profile e2e-odm-interop -p e2e_test --no-tests=fail
|
||||
|
||||
- name: Prove the stack and upload the leg
|
||||
if: always()
|
||||
uses: ./.github/actions/dual-stack-leg
|
||||
with:
|
||||
profile: e2e-odm-interop
|
||||
stack: ${{ matrix.stack }}
|
||||
logs: ${{ runner.temp }}/rustfs-e2e-logs
|
||||
|
||||
- name: Build the MinIO interop report
|
||||
if: always()
|
||||
uses: ./.github/actions/odm-interop-report
|
||||
@@ -190,7 +173,7 @@ jobs:
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: odm-interop-minio-${{ github.run_number }}-${{ github.run_attempt }}-${{ matrix.stack }}
|
||||
name: odm-interop-minio-${{ github.run_number }}-${{ github.run_attempt }}
|
||||
path: |
|
||||
artifacts/odm-interop/minio
|
||||
target/nextest/e2e-odm-interop/junit.xml
|
||||
@@ -316,20 +299,6 @@ jobs:
|
||||
target/nextest/e2e-odm-interop/junit.xml
|
||||
retention-days: 14
|
||||
|
||||
dual-stack-summary:
|
||||
name: Both-stack diff summary
|
||||
needs: [minio-source]
|
||||
if: github.repository == 'rustfs/rustfs' && always()
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: ./.github/actions/dual-stack-summary
|
||||
with:
|
||||
profiles: e2e-odm-interop
|
||||
|
||||
alert-on-failure:
|
||||
name: Alert on scheduled failure
|
||||
needs: [minio-source, cloud-source]
|
||||
|
||||
@@ -32,9 +32,9 @@
|
||||
#
|
||||
# The `differential` job adds the 73-operation dual-stack differential
|
||||
# (crates/e2e_test/src/dual_stack_differential, rustfs/backlog#2740) against the
|
||||
# same pinned reference: side A is the released binary (RUSTFS_E2E_REFERENCE_BINARY,
|
||||
# started without RUSTFS_S3_STACK), side B is the candidate built above on its
|
||||
# legacy stack. It reuses the candidate build artifact, never builds the candidate
|
||||
# same pinned reference: side A is the released binary (RUSTFS_E2E_REFERENCE_BINARY),
|
||||
# side B is the candidate built above.
|
||||
# It reuses the candidate build artifact, never builds the candidate
|
||||
# twice, and prints reference_side, version_a and version_b from the report the test
|
||||
# wrote; it fails when side A was not the reference or both sides report the same
|
||||
# version. Every (op, field, a, b) difference goes to the job summary. Report-only
|
||||
@@ -310,7 +310,7 @@ jobs:
|
||||
chmod +x target/debug/rustfs
|
||||
test -x "$REFERENCE_PATH"
|
||||
mkdir -p "$RUSTFS_E2E_LOG_DIR"
|
||||
# Side A: the released binary. Side B: the candidate on its legacy stack.
|
||||
# Side A: the released binary. Side B: the candidate.
|
||||
export RUSTFS_E2E_REFERENCE_BINARY="$REFERENCE_PATH"
|
||||
test_name='dual_stack_differential::tests::both_stacks_answer_every_operation_identically'
|
||||
python3 scripts/e2e_binary.py run --features e2e-test-hooks -- \
|
||||
|
||||
+1
-1
@@ -94,7 +94,7 @@ refactors.
|
||||
|--------|--------------------------|----------------|
|
||||
| Foundation | `checksums`, `common`, `config`, `data-usage`, `heal-contracts`, `scanner-metrics`, `utils` | Shared configuration, data-usage models, heal domain contracts, scanner telemetry types, utilities, and checksums. |
|
||||
| I/O and storage | `concurrency`, `ecstore`, `filemeta`, `heal`, `io-core`, `io-metrics`, `lifecycle`, `lock`, `object-capacity`, `object-data-cache`, `replication`, `rio`, `rio-v2`, `s3-client`, `scanner`, `storage-api` | Erasure-coded object storage, metadata, recovery, lifecycle, replication, locking, cache, I/O pipelines, and the engine-side S3 client for remote tier/transition targets. |
|
||||
| Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, TLS, and security contracts. |
|
||||
| Security and identity | `credentials`, `crypto`, `iam`, `keystone`, `kms`, `policy`, `security-governance`, `signer`, `sse`, `tls-runtime`, `trusted-proxies` | Credentials, authentication, authorization, encryption, key management, server-side encryption key resolution, TLS, and security contracts. |
|
||||
| Protocols and contracts | `extension-schema`, `madmin`, `protos`, `protocols`, `s3-ops`, `s3-types`, `s3select-api`, `s3select-query` | Admin, inter-node, S3, S3 Select, and optional protocol contracts. |
|
||||
| Operations and integration | `audit`, `notify`, `obs`, `targets`, `zip` | Auditing, observability, event delivery, notification targets, and archive support. |
|
||||
| Test support | `e2e_test`, `test-utils` | End-to-end validation and shared test bootstrap utilities. |
|
||||
|
||||
@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Deployment
|
||||
|
||||
- **The S3 protocol stack is now rustfs/gateway**, and it is the only S3 stack. The legacy s3s-based stack is removed, and so are the `RUSTFS_S3_STACK` environment variable and the `gateway-stack` cargo feature. There is no on-disk format change. `RUSTFS_S3_STACK` no longer selects anything: a server started with it set, to any value, refuses to start and prints `RUSTFS_S3_STACK is no longer supported; the gateway stack is the only S3 stack since <version>`, where `<version>` is the release's version. Remove the variable from service units, container environments, Helm values and orchestration files before upgrading. To roll back, follow the [S3 stack rollback procedure](docs/operations/s3-stack-rollback.md).
|
||||
|
||||
- Before upgrading, verify that the configured root access key is at least 3 bytes and the root secret key is at least 8 bytes. RustFS now rejects shorter values at startup and identifies the setting to update. Version 1.0.5 accepted these settings at startup and returned HTTP 500 when root requested STS credentials. Coordinate root credential changes across all nodes and clients. See [root credential rotation considerations](docs/operations/two-factor-auth.md#root-credentials-cannot-be-changed-at-runtime).
|
||||
|
||||
- Existing volumes created by older root-running container images must be writable by the non-root runtime identity before upgrading. The default container UID/GID is `10001:10001`; stop the affected instances, verify host mount paths, and for ordinary bind mounts run `sudo chown -R 10001:10001 /actual/data /actual/logs` on each RustFS data/log mount. Account for ACLs, NFS, Kubernetes, and rootless UID mappings. Image-build ownership changes do not migrate mounted data. See the Docker Quick Start in [README.md](README.md).
|
||||
@@ -114,6 +116,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Four-layer regression-prevention tests guard against silent feature deletion: compile-time module assertion, module-presence unit test, cross-module `Protocol` enum assertion, end-to-end SSH banner test against the running binary
|
||||
|
||||
### Changed
|
||||
- **Startup reports the state of `RUSTFS_SSE_S3_MASTER_KEY`**: the server now checks the local SSE-S3 master key when it starts and logs one `sse_local_master_key` event with `state` `loaded`, `not_set`, or `invalid`. An unusable value used to surface only as a `400 InvalidRequest` on the first SSE-S3 request served without a KMS; it is now logged as an error at startup with the reason. Startup still succeeds and request behavior is unchanged. The line "Using RUSTFS_SSE_S3_MASTER_KEY for SSE-S3 (KMS not configured)", logged when the key was first used, is replaced by this event.
|
||||
- **Scanner bucket walkers are no longer tied to the disk count**: a new scanner key `walkers_per_disk` (`RUSTFS_SCANNER_WALKERS_PER_DISK`, `1` through `16`, default `1`) spawns that many bucket walkers per local disk of an erasure set, so a single-disk deployment can walk several buckets at once instead of one bucket, one object at a time. The walkers of one disk share its scanner admission, so a peer still sees one scan session per physical disk, and remote disks keep one walker. The walker count is what `max_concurrent_disk_scans` caps and the disk count stays the floor; the `disk_concurrency_budget` log line now reports `walkers_per_disk`, `walkers`, and the `reason` for the effective limit. The default keeps today's I/O profile because a local disk cannot yet report whether it is rotational; the design intends a higher default on flash once it can (`docs/architecture/scanner-per-bucket-convergence.md`). As groundwork for pacing, the raw-enumeration page writer inserts into its building page in place and commits pages without copying them, and a regression test pins the cost of recording 20,000 entries in one prefix so the quadratic bookkeeping removed by [#8114](https://github.com/rustfs/rustfs/pull/8114) (rustfs#8113) cannot return. No persisted format, protocol or admin API changes beyond the additional config key, which older releases preserve and ignore.
|
||||
- **Encryption and KMS work merged since `1.0.0-rc.5`** (entries were missing from this section):
|
||||
- **Persisted KMS configuration secrets** are sealed field-by-field with `RUSTFS_KMS_CONFIG_SECRET`. **When the variable is unset the secrets are persisted in cleartext and the server only warns** (`persisted KMS configuration carries cleartext secrets`); it never refuses the write. Set it, identically, on every node, and re-save the configuration to seal an existing one.
|
||||
|
||||
Generated
+603
-527
File diff suppressed because it is too large
Load Diff
+54
-45
@@ -60,6 +60,7 @@ members = [
|
||||
"crates/security-governance", # Security governance contracts
|
||||
"crates/extension-schema", # Extension schema contracts
|
||||
"crates/signer", # client signer
|
||||
"crates/sse", # S3 server-side encryption key resolution and metadata
|
||||
"crates/storage-api", # Storage API contracts
|
||||
"crates/test-utils", # Shared test bootstrap helpers (dev-dependency only)
|
||||
"crates/targets", # Target-specific configurations and utilities
|
||||
@@ -71,6 +72,7 @@ members = [
|
||||
"crates/zip", # ZIP file handling and compression
|
||||
"crates/zstd-compat", # Fixed codec for dependencies requiring zstd 0.13
|
||||
]
|
||||
exclude = ["vendor/hyper"]
|
||||
resolver = "3"
|
||||
|
||||
[workspace.package]
|
||||
@@ -139,6 +141,7 @@ rustfs-scanner = { path = "crates/scanner", version = "1.0.5" }
|
||||
rustfs-security-governance = { path = "crates/security-governance", version = "1.0.5" }
|
||||
rustfs-extension-schema = { path = "crates/extension-schema", version = "1.0.5" }
|
||||
rustfs-signer = { path = "crates/signer", version = "1.0.5" }
|
||||
rustfs-sse = { path = "crates/sse", version = "1.0.5" }
|
||||
rustfs-storage-api = { path = "crates/storage-api", version = "1.0.5" }
|
||||
rustfs-trusted-proxies = { path = "crates/trusted-proxies", version = "1.0.5" }
|
||||
rustfs-targets = { path = "crates/targets", version = "1.0.5" }
|
||||
@@ -151,16 +154,16 @@ rustfs-zip = { path = "./crates/zip", version = "1.0.5" }
|
||||
# engine crates move onto from s3s (rustfs/backlog#2745). The one pin of the
|
||||
# gateway in this workspace; no crate may enable a `compat-s3s*` feature except
|
||||
# the s3s-facing edge of the rustfs binary.
|
||||
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "ab5242b092f60c22a6cbace3950117f4702de36a", version = "0.42.0", default-features = false }
|
||||
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "ab5242b092f60c22a6cbace3950117f4702de36a", version = "0.2.0", default-features = false }
|
||||
rustfs-gateway-types = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.42.0", default-features = false }
|
||||
rustfs-gateway-stream = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.2.0", default-features = false }
|
||||
# The gateway framework itself, consumed for its extension traits by the ring-2
|
||||
# adapter. `default-features = false` keeps the `server` feature, and with it the
|
||||
# server crate, out of the build.
|
||||
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "ab5242b092f60c22a6cbace3950117f4702de36a", version = "0.66.0", default-features = false }
|
||||
rustfs-gateway = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.66.0", default-features = false }
|
||||
# Test-only: builds the `EffectiveHost` a host-resolution test queries with.
|
||||
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "ab5242b092f60c22a6cbace3950117f4702de36a", default-features = false }
|
||||
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "ab5242b092f60c22a6cbace3950117f4702de36a", version = "0.63.0", default-features = false }
|
||||
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "ab5242b092f60c22a6cbace3950117f4702de36a", version = "0.13.0", default-features = false }
|
||||
rustfs-gateway-http = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", default-features = false }
|
||||
rustfs-gateway-core = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.63.0", default-features = false }
|
||||
rustfs-gateway-dialect-rustfs-admin = { git = "https://github.com/rustfs/gateway.git", rev = "60dcd2a55713dbcc9dbd6e165922e1a0df4473d7", version = "0.13.0", default-features = false }
|
||||
|
||||
# Async Runtime and Networking
|
||||
async-channel = "2.5.0"
|
||||
@@ -168,15 +171,15 @@ async_zip = { default-features = false, version = "0.0.19" }
|
||||
mysql_async = { default-features = false, version = "0.37.1" }
|
||||
async-compression = { version = "0.4.52" }
|
||||
async-trait = "0.1.92"
|
||||
async-nats = { version = "0.52.0", default-features = false }
|
||||
async-nats = { version = "0.53.0", default-features = false }
|
||||
axum = "0.8.9"
|
||||
futures = "0.3.34"
|
||||
futures-core = "0.3.34"
|
||||
futures-lite = "2.6.1"
|
||||
futures-util = "0.3.34"
|
||||
pollster = "1.0.1"
|
||||
pollster = "1.0.3"
|
||||
pulsar = { default-features = false, version = "=6.9.0" }
|
||||
lapin = { default-features = false, version = "4.12.3" }
|
||||
lapin = { default-features = false, version = "4.13.0" }
|
||||
hyper = { version = "1.12.0" }
|
||||
h2 = { version = "0.4.20" }
|
||||
hyper-rustls = { default-features = false, version = "0.27.10" }
|
||||
@@ -209,18 +212,19 @@ quinn = { version = "0.11.12", default-features = false, features = [
|
||||
] }
|
||||
|
||||
# Serialization and Data Formats
|
||||
apache-avro = { version = "0.22.0", features = ["snappy", "zstandard"] }
|
||||
bytes = { version = "1.12.1" }
|
||||
apache-avro = { version = "0.23.0", features = ["snappy", "zstandard"] }
|
||||
bytes = { version = "1.12.2" }
|
||||
csv-core = "0.1.13"
|
||||
bytesize = "2.7.0"
|
||||
byteorder = "1.5.0"
|
||||
flatbuffers = "25.12.19"
|
||||
form_urlencoded = "1.2.2"
|
||||
form_urlencoded = "1.2.3"
|
||||
prost = "0.14.6"
|
||||
quick-xml = "0.42.0"
|
||||
rmp = { version = "0.8.15" }
|
||||
rmp-serde = { version = "1.3.1" }
|
||||
serde = { version = "1.0.229" }
|
||||
serde-value = "0.7.0"
|
||||
serde_ignored = { version = "0.1" }
|
||||
serde_with = { version = "3", default-features = false, features = ["macros", "std"] }
|
||||
serde_json = { version = "1.0.154" }
|
||||
@@ -242,7 +246,7 @@ jsonwebtoken = { version = "12.0.0" }
|
||||
openidconnect = { default-features = false, version = "4.1.0" }
|
||||
pbkdf2 = "0.13.0"
|
||||
p256 = { version = "0.14.0", features = ["ecdsa", "pkcs8"] }
|
||||
rsa = { version = "=0.10.0-rc.18" }
|
||||
rsa = { version = "0.10.0", features = ["pkcs1v15"] }
|
||||
rustls = { default-features = false, version = "0.23.46" }
|
||||
rustls-native-certs = "0.8"
|
||||
rustls-pki-types = "1.16.0"
|
||||
@@ -250,13 +254,13 @@ x509-parser = "0.18.1"
|
||||
sha1 = "0.11.0"
|
||||
sha2 = "0.11.1"
|
||||
subtle = "2.6"
|
||||
zeroize = { version = "1.9.1" }
|
||||
zeroize = { version = "1.9.2" }
|
||||
proptest = "1"
|
||||
|
||||
# Time and Date
|
||||
chrono = { version = "0.4.45" }
|
||||
humantime = "2.4.0"
|
||||
jiff = { version = "0.2.43" }
|
||||
jiff = { version = "1.0.2" }
|
||||
time = { version = "0.3.55" }
|
||||
|
||||
# Database
|
||||
@@ -273,18 +277,18 @@ tar-codec = "0.0.16"
|
||||
tar-framing = "0.0.16"
|
||||
atoi = "3.1.1"
|
||||
atomic_enum = "0.3.0"
|
||||
aws-config = { version = "1.13.2" }
|
||||
aws-config = { version = "1.13.3" }
|
||||
aws-credential-types = { version = "1.3.1" }
|
||||
aws-sdk-kms = { default-features = false, version = "1.131.0" }
|
||||
aws-sdk-s3 = { default-features = false, version = "1.159.0" }
|
||||
aws-sdk-sts = { default-features = false, version = "1.126.0" }
|
||||
aws-sdk-kms = { default-features = false, version = "1.133.0" }
|
||||
aws-sdk-s3 = { default-features = false, version = "1.161.0" }
|
||||
aws-sdk-sts = { default-features = false, version = "1.128.0" }
|
||||
aws-smithy-async = { version = "1.3.1" }
|
||||
aws-smithy-http-client = { default-features = false, version = "1.5.2" }
|
||||
aws-smithy-runtime-api = { version = "1.21.0" }
|
||||
aws-smithy-http-client = { default-features = false, version = "1.5.3" }
|
||||
aws-smithy-runtime-api = { version = "1.22.0" }
|
||||
aws-smithy-types = { version = "1.9.4" }
|
||||
base64-simd = "0.8.0"
|
||||
brotli = "9.1.1"
|
||||
clap = { version = "4.6.7" }
|
||||
brotli = "9.1.3"
|
||||
clap = { version = "4.6.9" }
|
||||
const-str = { version = "1.1.0" }
|
||||
convert_case = "0.12.0"
|
||||
criterion = { version = "0.8" }
|
||||
@@ -292,16 +296,16 @@ crossbeam-queue = "0.3.14"
|
||||
crossbeam-channel = "0.5.17"
|
||||
crossbeam-deque = "0.8.8"
|
||||
crossbeam-utils = "0.8.23"
|
||||
datafusion = { default-features = false, version = "55.2.0" }
|
||||
datafusion = { default-features = false, version = "55.3.0" }
|
||||
derive_builder = "0.20.2"
|
||||
ed25519-dalek = "3.0.0"
|
||||
enumset = "1.1.15"
|
||||
faster-hex = "1.0.0"
|
||||
faster-hex = "2.0.0"
|
||||
flate2 = "1.1.11"
|
||||
glob = "0.3.4"
|
||||
google-cloud-storage = "1.22.0"
|
||||
google-cloud-auth = "1.19.0"
|
||||
hashbrown = { version = "0.17.1" }
|
||||
hashbrown = { version = "0.17.2" }
|
||||
# Base32 for RFC 6238 TOTP shared secrets (RFC 4648 unpadded, the alphabet
|
||||
# every authenticator app expects). Already in the graph transitively.
|
||||
data-encoding = "2.11.1"
|
||||
@@ -318,7 +322,7 @@ log = "0.4"
|
||||
memmap2 = "0.9.12"
|
||||
nixl-sys = { git = "https://github.com/houseme/nixl", rev = "cc636c83f13d692e85b67e55aed092413d16fb41" }
|
||||
lz4 = "1.28.1"
|
||||
lz4_flex = { version = "=0.14.0", default-features = false, features = ["std", "frame"] }
|
||||
lz4_flex = { version = "0.14.2", default-features = false, features = ["std", "frame"] }
|
||||
matchit = "0.9.2"
|
||||
md-5 = "0.11.0"
|
||||
mime_guess = "2.0.5"
|
||||
@@ -335,16 +339,16 @@ percent-encoding = "2.3.2"
|
||||
# CLI needs its own QR encoder. No default features: the image/render backends
|
||||
# pull in an image stack this only needs SVG and text output from.
|
||||
qrcode-rs = { version = "2.2.0", default-features = false, features = ["std", "svg"] }
|
||||
pin-project-lite = "0.2.17"
|
||||
pin-project-lite = "0.2.18"
|
||||
pretty_assertions = "1.4.1"
|
||||
rand = { version = "0.10.3" }
|
||||
rand = { version = "0.10.4" }
|
||||
ratelimit = "2.0.0"
|
||||
rayon = "1.12.0"
|
||||
rustfs-erasure-codec = { version = "9.1.0" }
|
||||
reed-solomon-simd = "3.1.0"
|
||||
regex = { version = "1.13.1" }
|
||||
regex = { version = "1.13.2" }
|
||||
rumqttc = { package = "rumqttc-next", version = "0.34.0" }
|
||||
redis = { version = "1.8.1" }
|
||||
redis = { version = "1.8.2" }
|
||||
rustify = { version = "0.7", default-features = false }
|
||||
rustix = { version = "1.1.6" }
|
||||
rust-embed = { version = "8.14.0" }
|
||||
@@ -358,13 +362,13 @@ legacy-s3s = { package = "s3s", git = "https://github.com/s3s-project/s3s", rev
|
||||
serial_test = "4.0.1"
|
||||
shadow-rs = { default-features = false, version = "2.0.0" }
|
||||
siphasher = "1.0.4"
|
||||
smallvec = { version = "1.16.5" }
|
||||
smallvec = { version = "1.16.6" }
|
||||
compact_str = "0.10.0"
|
||||
snap = "1.1.2"
|
||||
starshard = { version = "2.4.1" }
|
||||
strum = { version = "0.28.0" }
|
||||
sync_wrapper = "1.0.2"
|
||||
sysinfo = "0.40.3"
|
||||
sysinfo = "0.40.4"
|
||||
temp-env = "0.3.6"
|
||||
tempfile = "3.27.0"
|
||||
test-case = "3.4.1"
|
||||
@@ -376,23 +380,23 @@ tracing-error = "0.2.1"
|
||||
tracing-opentelemetry = { version = "0.34.0" }
|
||||
tracing-subscriber = { version = "0.3.23" }
|
||||
transform-stream = "0.3.1"
|
||||
url = "2.5.8"
|
||||
url = "2.5.9"
|
||||
urlencoding = "2.1.3"
|
||||
uuid = { version = "1.29.2" }
|
||||
uuid = { version = "1.29.3" }
|
||||
vaultrs = { version = "0.8.0" }
|
||||
tar = "0.4.46"
|
||||
walkdir = "2.5.0"
|
||||
walkdir = "2.5.1"
|
||||
winapi-util = "0.1.11"
|
||||
windows = { version = "0.62.2" }
|
||||
windows-sys = "0.61.2"
|
||||
xxhash-rust = { version = "0.8.19" }
|
||||
zip = "9.5.1"
|
||||
xxhash-rust = { version = "0.8.21" }
|
||||
zip = "9.8.1"
|
||||
zstd = "0.14.4"
|
||||
|
||||
# Observability and Metrics
|
||||
metrics = "0.24.6"
|
||||
metrics-util = "0.20"
|
||||
dial9 = { version = "0.5.8", default-features = false }
|
||||
dial9 = { version = "0.5.9", default-features = false }
|
||||
opentelemetry = { version = "0.33.1" }
|
||||
opentelemetry-appender-tracing = { version = "0.33.1" }
|
||||
opentelemetry-otlp = { version = "0.33.1" }
|
||||
@@ -403,12 +407,12 @@ opentelemetry-stdout = { version = "0.33.1" }
|
||||
pyroscope = { version = "2.1.5" }
|
||||
|
||||
# FTP and SFTP
|
||||
libunftp = { version = "0.25.0" }
|
||||
libunftp = { version = "0.25.1" }
|
||||
unftp-core = "0.1.1"
|
||||
suppaftp = { version = "12.2.1" }
|
||||
suppaftp = { version = "13.0.0" }
|
||||
rcgen = { version = "0.14.10", default-features = false, features = ["aws_lc_rs", "crypto", "pem"] }
|
||||
russh = { version = "0.65.1" }
|
||||
russh-sftp = "3.0.1"
|
||||
russh = { version = "0.65.4" }
|
||||
russh-sftp = "4.0.0"
|
||||
|
||||
# WebDAV
|
||||
dav-server = "0.12.0"
|
||||
@@ -416,12 +420,15 @@ dav-server = "0.12.0"
|
||||
# Performance Analysis and Memory Profiling
|
||||
rustfs-mimalloc = { version = "0.7.4" }
|
||||
# Preserve Unicode focus filters until rustfs/backlog#2302 is resolved.
|
||||
hotpath = { version = "0.31.2", default-features = false }
|
||||
hotpath = { version = "0.32.1", default-features = false }
|
||||
# Snapshot testing for output format regression detection
|
||||
insta = { version = "1.49" }
|
||||
|
||||
[workspace.metadata.cargo-shear]
|
||||
ignored = ["hotpath", "rustfs"]
|
||||
# The `#[path]` test modules under `rustfs/src/server/http/tests/` are linked by
|
||||
# rustc (including the `http.rs` + `http/` sibling-directory rule), but cargo-shear
|
||||
# resolves those nested `#[path]` attributes against the wrong base directory.
|
||||
ignored-paths = ["rustfs/src/server/http/tests/**/*.rs"]
|
||||
|
||||
[profile.dev]
|
||||
# Full debuginfo roughly doubles compile+link time and produces multi-GB
|
||||
@@ -456,4 +463,6 @@ strip = "none"
|
||||
|
||||
# Pin upstream fixes until compatible crates.io releases are available.
|
||||
[patch.crates-io]
|
||||
# Remove after Hyper releases HTTP/2 Expect support (hyperium/hyper#4217).
|
||||
hyper = { path = "vendor/hyper" }
|
||||
zstd = { path = "crates/zstd-compat" }
|
||||
|
||||
@@ -15,12 +15,11 @@ workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
hotpath = ["hotpath/hotpath", "hotpath/tokio", "rustfs-io-core/hotpath"]
|
||||
hotpath-alloc = ["hotpath", "hotpath/hotpath-alloc", "rustfs-io-core/hotpath-alloc"]
|
||||
hotpath-cpu = ["hotpath", "hotpath/hotpath-cpu", "rustfs-io-core/hotpath-cpu"]
|
||||
hotpath = ["rustfs-io-core/hotpath"]
|
||||
hotpath-alloc = ["hotpath", "rustfs-io-core/hotpath-alloc"]
|
||||
hotpath-cpu = ["hotpath", "rustfs-io-core/hotpath-cpu"]
|
||||
|
||||
[dependencies]
|
||||
hotpath.workspace = true
|
||||
# Internal crates
|
||||
rustfs-io-core = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
|
||||
@@ -129,6 +129,12 @@ when restoring `/rustfs/console` for a custom OEM build.
|
||||
- `RUSTFS_SCANNER_MAX_CONCURRENT_SET_SCANS` (canonical)
|
||||
- `RUSTFS_SCANNER_MAX_CONCURRENT_DISK_SCANS` (canonical)
|
||||
- `RUSTFS_SCANNER_WALKERS_PER_DISK` (canonical)
|
||||
- `RUSTFS_SCANNER_READ_ONLY_HANDOFF` (canonical, default `false`)
|
||||
|
||||
Read-only restart continuity:
|
||||
|
||||
- `RUSTFS_SCANNER_READ_ONLY_HANDOFF=true` enables reuse of unpublished scanner progress across verified read-only process restarts. Unset, false or invalid values disable both identity restoration and receipt creation. Existing receipts are still durably consumed before recovery starts, even when the feature is disabled.
|
||||
- Deploy receipt-aware readers to every possible writer before enabling this flag. Before rolling back to an older binary, disable it on every node, start each node with all its drives present, wait for readiness, and shut down cleanly. Do not start the older binary until every node completes this preparation. Direct rollback after enabling receipt writes is unsupported: older startup/recovery paths can write without durably invalidating the receipt. See [the receipt and rollback contract](../../docs/architecture/scanner-usage-publication.md#read-only-restart-continuity).
|
||||
|
||||
Scanner cycle budget controls:
|
||||
|
||||
|
||||
@@ -21,6 +21,11 @@ pub const APP_NAME: &str = "RustFS";
|
||||
/// Cargo package version for this workspace member.
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// Opt in to scanner checkpoint continuity across verified read-only restarts.
|
||||
/// Defaults to false. Enable only after all possible writers support receipt
|
||||
/// consumption; disable and restart before rolling back to an older writer.
|
||||
pub const ENV_SCANNER_READ_ONLY_HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
|
||||
|
||||
/// Default configuration logger level
|
||||
/// Default value: error
|
||||
/// Environment variable: RUSTFS_OBS_LOGGER_LEVEL
|
||||
|
||||
@@ -152,6 +152,33 @@ pub const DEFAULT_SHARD_INTEGRITY_WRITE: bool = false;
|
||||
pub const ENV_SHARD_INTEGRITY_FLEET_CONFIRMED: &str = "RUSTFS_SHARD_INTEGRITY_FLEET_CONFIRMED";
|
||||
pub const DEFAULT_SHARD_INTEGRITY_FLEET_CONFIRMED: bool = false;
|
||||
|
||||
/// Request parsing switch for the per-object erasure-code block-size hint.
|
||||
/// The default keeps the feature inert during rolling upgrades.
|
||||
pub const ENV_EC_BLOCK_SIZE_HINT_ENABLE: &str = "RUSTFS_EC_BLOCK_SIZE_HINT_ENABLE";
|
||||
pub const DEFAULT_EC_BLOCK_SIZE_HINT_ENABLE: bool = false;
|
||||
|
||||
/// Operator confirmation that every writer and reader in the fleet understands
|
||||
/// the persisted erasure block-size geometry.
|
||||
pub const ENV_EC_BLOCK_SIZE_HINT_FLEET_CONFIRMED: &str = "RUSTFS_EC_BLOCK_SIZE_HINT_FLEET_CONFIRMED";
|
||||
pub const DEFAULT_EC_BLOCK_SIZE_HINT_FLEET_CONFIRMED: bool = false;
|
||||
|
||||
/// Write new EC shards with a bounded bitrot frame size so Range GETs do not
|
||||
/// inherit the full persisted layout block as their physical read quantum.
|
||||
/// The marker is only emitted after the fleet confirmation gate is enabled;
|
||||
/// readers without this feature continue to consume legacy objects unchanged.
|
||||
pub const ENV_EC_READ_QUANTUM_ENABLE: &str = "RUSTFS_EC_READ_QUANTUM_ENABLE";
|
||||
pub const DEFAULT_EC_READ_QUANTUM_ENABLE: bool = false;
|
||||
|
||||
/// Operator confirmation that every reader and writer understands the
|
||||
/// persisted EC read-quantum marker and its per-frame bitrot layout.
|
||||
pub const ENV_EC_READ_QUANTUM_FLEET_CONFIRMED: &str = "RUSTFS_EC_READ_QUANTUM_FLEET_CONFIRMED";
|
||||
pub const DEFAULT_EC_READ_QUANTUM_FLEET_CONFIRMED: bool = false;
|
||||
|
||||
const _: () = assert!(!DEFAULT_EC_BLOCK_SIZE_HINT_ENABLE);
|
||||
const _: () = assert!(!DEFAULT_EC_BLOCK_SIZE_HINT_FLEET_CONFIRMED);
|
||||
const _: () = assert!(!DEFAULT_EC_READ_QUANTUM_ENABLE);
|
||||
const _: () = assert!(!DEFAULT_EC_READ_QUANTUM_FLEET_CONFIRMED);
|
||||
|
||||
const _: () = assert!(!DEFAULT_SHARD_INTEGRITY_WRITE);
|
||||
const _: () = assert!(!DEFAULT_SHARD_INTEGRITY_FLEET_CONFIRMED);
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ jsonwebtoken = { workspace = true, features = ["aws_lc_rs"] }
|
||||
base64-simd = { workspace = true }
|
||||
pbkdf2 = { workspace = true, optional = true }
|
||||
rand = { workspace = true, features = ["serde"] }
|
||||
rsa = { workspace = true, features = ["sha2"] }
|
||||
rsa = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
sha2 = { workspace = true, optional = true }
|
||||
thiserror.workspace = true
|
||||
|
||||
@@ -13,9 +13,9 @@
|
||||
// limitations under the License.
|
||||
|
||||
use rsa::{
|
||||
Pkcs1v15Encrypt, RsaPrivateKey, RsaPublicKey,
|
||||
Pkcs1v15Encrypt, PrivateKey, PublicKey,
|
||||
pkcs8::{DecodePrivateKey, DecodePublicKey},
|
||||
pss::{BlindedSigningKey, Signature, VerifyingKey},
|
||||
pss::{Signature, SigningKey, VerifyingKey},
|
||||
sha2::Sha256,
|
||||
signature::{RandomizedSigner, Verifier},
|
||||
traits::PublicKeyParts,
|
||||
@@ -37,7 +37,7 @@ pub struct Token {
|
||||
pub fn gencode(token: &Token, key: &str) -> Result<String> {
|
||||
let data = serde_json::to_vec(token)?;
|
||||
let mut rng = rand::rng();
|
||||
let public_key = RsaPublicKey::from_public_key_pem(key).map_err(Error::other)?;
|
||||
let public_key = PublicKey::from_public_key_pem(key).map_err(Error::other)?;
|
||||
let encrypted_data = public_key.encrypt(&mut rng, Pkcs1v15Encrypt, &data).map_err(Error::other)?;
|
||||
Ok(base64_simd::URL_SAFE_NO_PAD.encode_to_string(&encrypted_data))
|
||||
}
|
||||
@@ -51,7 +51,7 @@ pub fn parse(token: &str, key: &str) -> Result<Token> {
|
||||
let encrypted_data = base64_simd::URL_SAFE_NO_PAD
|
||||
.decode_to_vec(token.as_bytes())
|
||||
.map_err(Error::other)?;
|
||||
let private_key = RsaPrivateKey::from_pkcs8_pem(key).map_err(Error::other)?;
|
||||
let private_key = PrivateKey::from_pkcs8_pem(key).map_err(Error::other)?;
|
||||
let decrypted_data = private_key.decrypt(Pkcs1v15Encrypt, &encrypted_data).map_err(Error::other)?;
|
||||
serde_json::from_slice(&decrypted_data).map_err(Error::other)
|
||||
}
|
||||
@@ -63,8 +63,8 @@ pub fn parse(token: &str, key: &str) -> Result<Token> {
|
||||
pub fn sign_license_token(token: &Token, private_key_pem: &str) -> Result<String> {
|
||||
let payload = serde_json::to_vec(token)?;
|
||||
let mut rng = rand::rng();
|
||||
let private_key = RsaPrivateKey::from_pkcs8_pem(private_key_pem).map_err(Error::other)?;
|
||||
let signing_key = BlindedSigningKey::<Sha256>::new(private_key);
|
||||
let private_key = PrivateKey::from_pkcs8_pem(private_key_pem).map_err(Error::other)?;
|
||||
let signing_key = SigningKey::<Sha256>::new(private_key);
|
||||
let signature: Signature = signing_key.try_sign_with_rng(&mut rng, &payload).map_err(Error::other)?;
|
||||
let signature: Box<[u8]> = signature.into();
|
||||
|
||||
@@ -80,7 +80,7 @@ pub fn parse_signed_license_token(token: &str, public_key_pem: &str) -> Result<T
|
||||
let signed_payload = base64_simd::URL_SAFE_NO_PAD
|
||||
.decode_to_vec(token.as_bytes())
|
||||
.map_err(Error::other)?;
|
||||
let public_key = RsaPublicKey::from_public_key_pem(public_key_pem).map_err(Error::other)?;
|
||||
let public_key = PublicKey::from_public_key_pem(public_key_pem).map_err(Error::other)?;
|
||||
let signature_len = public_key.size();
|
||||
|
||||
if signed_payload.len() <= signature_len {
|
||||
@@ -103,7 +103,7 @@ pub fn parse_license_with_public_key(license: &str, public_key: &str) -> Result<
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rsa::{
|
||||
RsaPrivateKey,
|
||||
PrivateKey,
|
||||
pkcs8::{EncodePrivateKey, EncodePublicKey, LineEnding},
|
||||
};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
@@ -112,8 +112,8 @@ mod tests {
|
||||
fn test_sign_license_token_and_parse_signed_license_token() {
|
||||
let mut rng = rand::rng();
|
||||
let bits = 2048;
|
||||
let private_key = RsaPrivateKey::new(&mut rng, bits).expect("Failed to generate private key");
|
||||
let public_key = RsaPublicKey::from(&private_key);
|
||||
let private_key = PrivateKey::new(&mut rng, bits).expect("Failed to generate private key");
|
||||
let public_key = PublicKey::from(&private_key);
|
||||
|
||||
let private_key_pem = private_key
|
||||
.to_pkcs8_pem(LineEnding::LF)
|
||||
@@ -144,8 +144,8 @@ mod tests {
|
||||
fn test_legacy_gencode_and_parse_roundtrip() {
|
||||
let mut rng = rand::rng();
|
||||
let bits = 2048;
|
||||
let private_key = RsaPrivateKey::new(&mut rng, bits).expect("Failed to generate private key");
|
||||
let public_key = RsaPublicKey::from(&private_key);
|
||||
let private_key = PrivateKey::new(&mut rng, bits).expect("Failed to generate private key");
|
||||
let public_key = PublicKey::from(&private_key);
|
||||
|
||||
let private_key_pem = private_key
|
||||
.to_pkcs8_pem(LineEnding::LF)
|
||||
@@ -173,8 +173,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_parse_signed_license_token_rejects_tampered_payload() {
|
||||
let mut rng = rand::rng();
|
||||
let private_key = RsaPrivateKey::new(&mut rng, 2048).expect("Failed to generate private key");
|
||||
let public_key = RsaPublicKey::from(&private_key);
|
||||
let private_key = PrivateKey::new(&mut rng, 2048).expect("Failed to generate private key");
|
||||
let public_key = PublicKey::from(&private_key);
|
||||
let private_key_pem = private_key
|
||||
.to_pkcs8_pem(LineEnding::LF)
|
||||
.expect("failed to encode private key pem");
|
||||
@@ -206,8 +206,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_parse_signed_license_token_rejects_invalid_token() {
|
||||
let mut rng = rand::rng();
|
||||
let private_key = RsaPrivateKey::new(&mut rng, 2048).expect("Failed to generate private key");
|
||||
let public_key = RsaPublicKey::from(&private_key);
|
||||
let private_key = PrivateKey::new(&mut rng, 2048).expect("Failed to generate private key");
|
||||
let public_key = PublicKey::from(&private_key);
|
||||
let public_key_pem = public_key
|
||||
.to_public_key_pem(LineEnding::LF)
|
||||
.expect("failed to encode public key pem");
|
||||
|
||||
@@ -98,7 +98,6 @@ rustfs-madmin.workspace = true
|
||||
rustfs-filemeta.workspace = true
|
||||
bytes = { workspace = true, features = ["serde"] }
|
||||
aws-sdk-s3 = { workspace = true, default-features = false, features = ["sigv4a", "default-https-client", "rt-tokio"] }
|
||||
aws-sdk-sts = { workspace = true, default-features = false, features = ["default-https-client", "rt-tokio"] }
|
||||
aws-smithy-http-client = { workspace = true, default-features = false, features = ["rustls-aws-lc"] }
|
||||
aws-smithy-types.workspace = true
|
||||
async-trait = { workspace = true }
|
||||
@@ -124,13 +123,12 @@ urlencoding.workspace = true
|
||||
walkdir.workspace = true
|
||||
base64-simd = { workspace = true }
|
||||
rand = { workspace = true, features = ["serde"] }
|
||||
chrono = { workspace = true, features = ["serde"] }
|
||||
jiff = { workspace = true, features = ["serde"] }
|
||||
hex-simd = { workspace = true }
|
||||
md-5 = { workspace = true }
|
||||
prost.workspace = true
|
||||
sha2 = { workspace = true }
|
||||
rustfs-s3-types = { workspace = true }
|
||||
s3s = { workspace = true, features = ["minio"] }
|
||||
zstd.workspace = true
|
||||
time = { workspace = true, features = ["parsing", "formatting", "macros", "serde"] }
|
||||
rcgen.workspace = true
|
||||
@@ -140,8 +138,11 @@ rustls = { workspace = true, default-features = false, features = ["aws-lc-rs",
|
||||
clap = { workspace = true, features = ["derive", "env"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde-value.workspace = true
|
||||
s3s = { workspace = true, features = ["minio"] }
|
||||
async-compression = { workspace = true, features = ["tokio", "bzip2", "lz4", "xz"] }
|
||||
aws-config = { workspace = true }
|
||||
aws-sdk-sts = { workspace = true, default-features = false, features = ["default-https-client", "rt-tokio"] }
|
||||
opentelemetry-proto = { workspace = true }
|
||||
russh = { workspace = true, features = ["serde"] }
|
||||
russh-sftp = { workspace = true }
|
||||
|
||||
@@ -29,7 +29,7 @@ Registered in [`src/lib.rs`](src/lib.rs). Grouped by concern:
|
||||
| **distributed 4×4** | [`src/distributed/`](src/distributed) | Nightly `e2e-distributed` lane: S3, object lock/WORM, versioning, bucket/site replication, quota, expand/decommission/rebalance, concurrency, chaos, 4-node upgrade of historical data and IAM AK/SK. Map: [`docs/testing/distributed-e2e.md`](../../docs/testing/distributed-e2e.md) |
|
||||
| **chaos / reliability** | [`src/chaos.rs`](src/chaos.rs), `reliability_disk_fault_test`, `heal_erasure_disk_rebuild_test`, `server_startup_failfast_test` | Disk offline/replace/corrupt, EC rebuild, heal, fail-fast startup |
|
||||
| **upgrade compatibility** | `upgrade_compatibility_test` | Pinned previous-release writes followed by current-build reads on the same data directory |
|
||||
| **dual-stack differential** | `dual_stack_differential` | Two single-node servers answer one SDK script for all 73 S3 operations and every differing `(op, field, a, b)` is reported. Side A is the binary under test on `RUSTFS_S3_STACK=legacy`; side B runs `RUSTFS_E2E_STACK_B`. Set `RUSTFS_E2E_REFERENCE_BINARY` to a released `rustfs` binary to make side A that binary instead (started without `RUSTFS_S3_STACK`, which older releases do not know). A missing, non-file or non-executable path fails the run; it never skips or falls back to the same-binary mode. The report in `<target>/dual-stack/<run>.json` records `reference_side` and each side's `--version` output |
|
||||
| **dual-stack differential** | `dual_stack_differential` | Two single-node servers answer one SDK script for all 73 S3 operations and every differing `(op, field, a, b)` is reported. Both sides run the binary under test on its only (gateway) stack unless `RUSTFS_E2E_REFERENCE_BINARY` names a released `rustfs` binary, which then runs side A. A missing, non-file or non-executable path fails the run; it never skips or falls back to the same-binary mode. `RUSTFS_E2E_STACK_B_REGION` starts side B in another region to inject a difference. The report in `<target>/dual-stack/<run>.json` records `reference_side` and each side's `--version` output |
|
||||
|
||||
The external-tool `storage_metric_ownership_test` validates the OTLP/Collector/Prometheus path, including a rolling upgrade and node failures. See the [storage metrics guide](../../docs/operations/storage-metrics.md) for its required binaries and focused command.
|
||||
|
||||
@@ -211,6 +211,8 @@ the wiring source of truth. Committed test-ID digests under
|
||||
|
||||
**Endpoint blackhole scenario skipped** — `heal_erasure_disk_rebuild_test::tests::test_cluster_root_heal_recovers_after_target_endpoint_blackhole` installs a loopback `iptables` DROP rule and therefore needs `CAP_NET_ADMIN` (root or passwordless `sudo -n iptables`). A host where `iptables` is missing or cannot read the OUTPUT chain (typical inside an unprivileged container, where the nf_tables backend reports "Permission denied" even under `sudo`) logs a `heal_interruption_skipped` warning and returns without exercising heal. Set `RUSTFS_E2E_REQUIRE_NET_FAULT_INJECTION=1` on lanes that do provision the capability so a broken runner fails instead of skipping.
|
||||
|
||||
The full suite compares persisted bucket configurations and object records against the release pinned in `.config/reference-binary.toml`. Set `RUSTFS_PERSISTENCE_REFERENCE_BINARY` to the verified executable and `RUSTFS_PERSISTENCE_CLOCK_LIBRARY` to the absolute path of libfaketime (`libfaketime.so.1` on Linux or `libfaketime.1.dylib` on macOS). To retain the two sets of 13 XML documents for the gateway golden corpus, set `RUSTFS_PERSISTENCE_XML_DIR` to an output directory. CI includes them in the full suite's JUnit artifact.
|
||||
|
||||
**Reproduce a CI failure locally** — run the exact profile/lane:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -137,6 +137,40 @@ async fn test_bucket_policy_authenticated_user() -> Result<(), Box<dyn std::erro
|
||||
.await
|
||||
.map_err(|e| format!("DeleteObject failed: {}", e))?;
|
||||
|
||||
for (allowed, may_read) in [("s3:GetBucketPolicy", true), ("s3:PutBucketPolicy", false)] {
|
||||
let policy = serde_json::json!({
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Principal": { "AWS": [user_access] },
|
||||
"Action": allowed,
|
||||
"Resource": format!("arn:aws:s3:::{bucket_name}")
|
||||
}]
|
||||
})
|
||||
.to_string();
|
||||
admin_client
|
||||
.put_bucket_policy()
|
||||
.bucket(bucket_name)
|
||||
.policy(&policy)
|
||||
.send()
|
||||
.await?;
|
||||
let read = user_client.get_bucket_policy().bucket(bucket_name).send().await;
|
||||
let write = user_client
|
||||
.put_bucket_policy()
|
||||
.bucket(bucket_name)
|
||||
.policy(&policy)
|
||||
.send()
|
||||
.await;
|
||||
if may_read {
|
||||
read?;
|
||||
let denied = write.expect_err("GetBucketPolicy must not grant PutBucketPolicy");
|
||||
assert_eq!(denied.as_service_error().and_then(ProvideErrorMetadata::code), Some("AccessDenied"));
|
||||
} else {
|
||||
let denied = read.expect_err("PutBucketPolicy must not grant GetBucketPolicy");
|
||||
assert_eq!(denied.as_service_error().and_then(ProvideErrorMetadata::code), Some("AccessDenied"));
|
||||
write?;
|
||||
}
|
||||
}
|
||||
info!("Test Passed!");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -170,6 +170,15 @@ impl DiskFaultHarness {
|
||||
/// Start (or restart after [`Self::kill_server`]) the RustFS server with
|
||||
/// all volume directories and the same address.
|
||||
pub async fn start_server(&mut self) -> ChaosResult<()> {
|
||||
self.start_server_with_readiness(false).await
|
||||
}
|
||||
|
||||
/// Start a process once its node read-readiness probe passes.
|
||||
pub async fn start_server_at_read_quorum(&mut self) -> ChaosResult<()> {
|
||||
self.start_server_with_readiness(true).await
|
||||
}
|
||||
|
||||
async fn start_server_with_readiness(&mut self, read_quorum_only: bool) -> ChaosResult<()> {
|
||||
// The common helper always appends `env.temp_dir` as the final storage
|
||||
// path: point it at the last disk for startup and pass the remaining
|
||||
// disks explicitly, then restore it to the root so Drop cleans up
|
||||
@@ -181,7 +190,13 @@ impl DiskFaultHarness {
|
||||
let arg_refs: Vec<&str> = disk_args.iter().map(String::as_str).collect();
|
||||
let env_refs: Vec<(&str, &str)> = self.extra_env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||
|
||||
let result = self.env.start_rustfs_server_with_env(arg_refs, &env_refs).await;
|
||||
let result = if read_quorum_only {
|
||||
self.env
|
||||
.start_rustfs_server_with_env_at_read_quorum(arg_refs, &env_refs)
|
||||
.await
|
||||
} else {
|
||||
self.env.start_rustfs_server_with_env(arg_refs, &env_refs).await
|
||||
};
|
||||
self.env.temp_dir = self.root.to_string_lossy().to_string();
|
||||
result
|
||||
}
|
||||
|
||||
@@ -722,7 +722,7 @@ impl RustFSTestEnvironment {
|
||||
cleanup_existing: bool,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let binary_path = rustfs_binary_path();
|
||||
self.start_rustfs_server_inner_with_binary(&binary_path, extra_args, extra_env, cleanup_existing)
|
||||
self.start_rustfs_server_inner_with_binary(&binary_path, extra_args, extra_env, cleanup_existing, false)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -732,6 +732,7 @@ impl RustFSTestEnvironment {
|
||||
extra_args: Vec<&str>,
|
||||
extra_env: &[(&str, &str)],
|
||||
cleanup_existing: bool,
|
||||
read_quorum_only: bool,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
if cleanup_existing {
|
||||
self.cleanup_existing_processes().await?;
|
||||
@@ -756,7 +757,7 @@ impl RustFSTestEnvironment {
|
||||
self.process = Some(process);
|
||||
|
||||
// Wait for server to be ready
|
||||
self.wait_for_server_ready().await?;
|
||||
self.wait_for_server_ready_with_probe(read_quorum_only).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -770,7 +771,7 @@ impl RustFSTestEnvironment {
|
||||
extra_args: Vec<&str>,
|
||||
extra_env: &[(&str, &str)],
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
self.start_rustfs_server_inner_with_binary(binary_path, extra_args, extra_env, true)
|
||||
self.start_rustfs_server_inner_with_binary(binary_path, extra_args, extra_env, true, false)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -782,7 +783,7 @@ impl RustFSTestEnvironment {
|
||||
extra_args: Vec<&str>,
|
||||
extra_env: &[(&str, &str)],
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
self.start_rustfs_server_inner_with_binary(binary_path, extra_args, extra_env, false)
|
||||
self.start_rustfs_server_inner_with_binary(binary_path, extra_args, extra_env, false, false)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -800,6 +801,18 @@ impl RustFSTestEnvironment {
|
||||
self.start_rustfs_server_inner(extra_args, extra_env, true).await
|
||||
}
|
||||
|
||||
/// Start a degraded read-serving process using the node readiness probe.
|
||||
/// ListBuckets retains its namespace write-quorum requirement.
|
||||
pub async fn start_rustfs_server_with_env_at_read_quorum(
|
||||
&mut self,
|
||||
extra_args: Vec<&str>,
|
||||
extra_env: &[(&str, &str)],
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let binary_path = rustfs_binary_path();
|
||||
self.start_rustfs_server_inner_with_binary(&binary_path, extra_args, extra_env, true, true)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Start RustFS server without cleaning up other running RustFS processes.
|
||||
///
|
||||
/// This is useful for tests that need multiple independent RustFS instances
|
||||
@@ -828,8 +841,16 @@ impl RustFSTestEnvironment {
|
||||
/// Fails immediately if the spawned server process has already exited
|
||||
/// (e.g. a port bind failure) instead of polling out the full timeout.
|
||||
pub async fn wait_for_server_ready(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
self.wait_for_server_ready_with_probe(false).await
|
||||
}
|
||||
|
||||
async fn wait_for_server_ready_with_probe(
|
||||
&mut self,
|
||||
read_quorum_only: bool,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
info!("Waiting for RustFS server to be ready on {}", self.address);
|
||||
let client = self.create_s3_client();
|
||||
let health_client = HttpClient::builder().no_proxy().timeout(Duration::from_secs(2)).build()?;
|
||||
|
||||
for i in 0..60 {
|
||||
if let Some(process) = self.process.as_mut()
|
||||
@@ -838,7 +859,16 @@ impl RustFSTestEnvironment {
|
||||
return Err(format!("RustFS server process exited before becoming ready: {status}").into());
|
||||
}
|
||||
|
||||
if TcpStream::connect(&self.address).await.is_ok() && client.list_buckets().send().await.is_ok() {
|
||||
let ready = if read_quorum_only {
|
||||
health_client
|
||||
.get(format!("{}/minio/health/ready", self.url))
|
||||
.send()
|
||||
.await
|
||||
.is_ok_and(|response| response.status().is_success())
|
||||
} else {
|
||||
TcpStream::connect(&self.address).await.is_ok() && client.list_buckets().send().await.is_ok()
|
||||
};
|
||||
if ready {
|
||||
info!("✅ RustFS server is ready after {} attempts", i + 1);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@
|
||||
// limitations under the License.
|
||||
|
||||
//! Over-the-wire smoke net for the embedded console listener (backlog#1154
|
||||
//! peri-4). The console is a second HTTP listener that serves the full S3/admin
|
||||
//! surface plus the unauthenticated console routes under `/rustfs/console`;
|
||||
//! peri-4). The console is a second HTTP listener for the control-plane and
|
||||
//! unauthenticated console routes under `/rustfs/console`;
|
||||
//! before this test its behaviour was only covered by in-process router tests
|
||||
//! (`rustfs/src/admin/console.rs`), so a misconfiguration that exposed
|
||||
//! credentials through the public console endpoints or fail-opened the
|
||||
@@ -26,13 +26,13 @@
|
||||
//! * `/rustfs/console/license` exposes only the coarse `licensed` flag.
|
||||
//! * the console SPA prefix dispatches to the static handler, never to the
|
||||
//! S3 API (no S3 error XML), whether or not console assets are embedded.
|
||||
//! * unauthenticated requests to the admin API and the S3 root on the console
|
||||
//! listener are denied (403 AccessDenied) — the extra listener does not
|
||||
//! fail-open the protected surface.
|
||||
//! * unauthenticated admin API requests are denied with 403 AccessDenied.
|
||||
//! * S3 root/object requests on the console listener return an empty 404,
|
||||
//! including authenticated requests, before S3 dispatch.
|
||||
//! * a listener with the console disabled (the main S3 port here) does not
|
||||
//! serve the unauthenticated console endpoints at all.
|
||||
|
||||
use crate::common::{RustFSTestEnvironment, init_logging, local_http_client};
|
||||
use crate::common::{RustFSTestEnvironment, init_logging, local_http_client, signed_request_with_client};
|
||||
use std::error::Error;
|
||||
use tokio::time::{Duration, sleep};
|
||||
|
||||
@@ -166,19 +166,39 @@ async fn test_console_over_the_wire_smoke() -> TestResult {
|
||||
let admin_body = admin_response.text().await?;
|
||||
assert!(admin_body.contains("AccessDenied"), "admin denial must be AccessDenied: {admin_body}");
|
||||
|
||||
// The console listener serves no S3 surface at all: an object route is not found there,
|
||||
// signed or not, instead of reaching the S3 service and being denied by it.
|
||||
let s3_root_response = client.get(format!("{console_base}/")).send().await?;
|
||||
let signed_data_root = signed_request_with_client(
|
||||
&client,
|
||||
http::Method::GET,
|
||||
&format!("{}/", env.url),
|
||||
&env.access_key,
|
||||
&env.secret_key,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
s3_root_response.status(),
|
||||
reqwest::StatusCode::NOT_FOUND,
|
||||
"the S3 root must not be served on the console listener"
|
||||
);
|
||||
assert!(
|
||||
s3_root_response.text().await?.is_empty(),
|
||||
"the console listener must not answer an object route with an S3 document"
|
||||
signed_data_root.status(),
|
||||
reqwest::StatusCode::OK,
|
||||
"the same credentials must reach S3 on the data listener"
|
||||
);
|
||||
|
||||
for path in ["/", "/console-object-bucket/key"] {
|
||||
let url = format!("{console_base}{path}");
|
||||
for signed in [false, true] {
|
||||
let response = if signed {
|
||||
signed_request_with_client(&client, http::Method::GET, &url, &env.access_key, &env.secret_key, None, None).await?
|
||||
} else {
|
||||
client.get(&url).send().await?
|
||||
};
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
reqwest::StatusCode::NOT_FOUND,
|
||||
"S3 route {path}, signed={signed} must be isolated from the console listener"
|
||||
);
|
||||
assert!(response.bytes().await?.is_empty(), "isolated S3 routes must not reach a handler");
|
||||
}
|
||||
}
|
||||
|
||||
// --- console disabled on a listener means no console surface at all ------
|
||||
// The main S3 listener of this same process runs with the console disabled,
|
||||
// so its console paths must not answer with the unauthenticated console
|
||||
|
||||
@@ -26,7 +26,7 @@ use aws_sdk_s3::types::{
|
||||
DefaultRetention, ObjectLockConfiguration, ObjectLockEnabled, ObjectLockLegalHoldStatus, ObjectLockRetentionMode,
|
||||
ObjectLockRule,
|
||||
};
|
||||
use chrono::{Duration as ChronoDuration, Utc};
|
||||
use jiff::{SignedDuration, Timestamp};
|
||||
|
||||
fn delete_denied(error: &SdkError<DeleteObjectError>, context: &str) -> TestResult {
|
||||
let code = error.as_service_error().and_then(ProvideErrorMetadata::code);
|
||||
@@ -66,7 +66,7 @@ async fn four_node_four_drive_object_lock_worm_blocks_delete() -> TestResult {
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let retain_until = Utc::now() + ChronoDuration::days(1);
|
||||
let retain_until = Timestamp::now() + SignedDuration::from_hours(24);
|
||||
|
||||
let compliance_key = "compliance.bin";
|
||||
let compliance_version = put_object_with_retention(
|
||||
@@ -176,7 +176,10 @@ async fn four_node_default_retention_is_visible_and_non_lock_bucket_rejects_conf
|
||||
let retain_until = retention
|
||||
.retain_until_date()
|
||||
.ok_or("default retention omitted retain-until date")?;
|
||||
assert!(retain_until.secs() > Utc::now().timestamp(), "default retention is not in the future");
|
||||
assert!(
|
||||
retain_until.secs() > Timestamp::now().as_second(),
|
||||
"default retention is not in the future"
|
||||
);
|
||||
|
||||
let versioning = reader.get_bucket_versioning().bucket(&bucket).send().await?;
|
||||
assert_eq!(versioning.status().map(|status| status.as_str()), Some("Enabled"));
|
||||
|
||||
@@ -38,8 +38,8 @@ use aws_sdk_s3::types::{
|
||||
BucketVersioningStatus, CompletedMultipartUpload, CompletedPart, ObjectLockLegalHoldStatus, ObjectLockRetentionMode,
|
||||
VersioningConfiguration,
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use http::{Method, StatusCode};
|
||||
use jiff::Timestamp;
|
||||
use serde_json::Value;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -526,8 +526,8 @@ async fn put_multipart(client: &Client, bucket: &str, key: &str) -> TestResult<V
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn retention_deadline() -> TestResult<DateTime<Utc>> {
|
||||
DateTime::<Utc>::from_timestamp(Utc::now().timestamp() + 24 * 3600, 0).ok_or_else(|| "retention deadline out of range".into())
|
||||
fn retention_deadline() -> TestResult<Timestamp> {
|
||||
Ok(Timestamp::now() + jiff::SignedDuration::from_hours(24))
|
||||
}
|
||||
|
||||
/// Seed the deterministic inventory into the seed pool and record it.
|
||||
@@ -654,7 +654,7 @@ pub(crate) async fn seed_manifest(run: &TopologyRun) -> TestResult<TopologyManif
|
||||
let mut entry = ManifestEntry::body(&locked, &key, "compliance", Some(version_id.clone()), Some(version_id), &body);
|
||||
entry.retention = Some(RetentionRecord {
|
||||
mode: "COMPLIANCE".to_string(),
|
||||
retain_until_unix: retain_until.timestamp(),
|
||||
retain_until_unix: retain_until.as_second(),
|
||||
});
|
||||
entries.push(entry);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ use super::harness::{
|
||||
use crate::common::{
|
||||
AdminTransport, admin_add_canned_policy_via, admin_attach_user_policy_via, admin_create_user_via, init_logging,
|
||||
};
|
||||
use crate::upgrade_compatibility_test::wait_for_upgrade_write_readiness;
|
||||
use crate::upgrade_compatibility_test::{UpgradeSourceCapabilities, wait_for_upgrade_write_readiness};
|
||||
use aws_sdk_s3::Client;
|
||||
use aws_sdk_s3::error::ProvideErrorMetadata;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -427,7 +427,12 @@ async fn assert_history_and_iam(dist: &DistCluster, seed: &UpgradeSeed, context:
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn compare_degraded_legacy_list_parts(dist: &mut DistCluster, seed: &UpgradeSeed, previous: &Path) -> TestResult {
|
||||
async fn compare_degraded_legacy_list_parts(
|
||||
dist: &mut DistCluster,
|
||||
seed: &UpgradeSeed,
|
||||
previous: &Path,
|
||||
source: &UpgradeSourceCapabilities,
|
||||
) -> TestResult {
|
||||
let decoded = String::from_utf8(base64_simd::URL_SAFE_NO_PAD.decode_to_vec(seed.multipart_upload.as_bytes())?)?;
|
||||
let (_, upload_dir) = decoded.split_once('.').ok_or("legacy upload ID lacks deployment delimiter")?;
|
||||
let hash = sha256_hex(format!("{}/legacy-multipart.bin", seed.history_bucket).as_bytes());
|
||||
@@ -489,16 +494,22 @@ async fn compare_degraded_legacy_list_parts(dist: &mut DistCluster, seed: &Upgra
|
||||
// Three online disks retain metadata quorum but have no part directory;
|
||||
// the fourth disk is offline. A legacy empty response is not a proof that
|
||||
// the unavailable participant has no part.
|
||||
let legacy = legacy.expect("previous coordinator should expose its legacy empty-list behavior");
|
||||
assert!(legacy.parts().is_empty());
|
||||
let current = current.expect_err("current coordinator must not infer empty from missing directories and offline disks");
|
||||
assert_eq!(current.raw_response().expect("current S3 response").status().as_u16(), 503);
|
||||
// Since #9149, SlowDownRead is reserved for GET/HEAD object reads; a
|
||||
// ListParts read-quorum failure is reported as ServiceUnavailable.
|
||||
assert_eq!(
|
||||
current.as_service_error().and_then(|error| error.meta().code()),
|
||||
Some("ServiceUnavailable")
|
||||
);
|
||||
let mut quorum_errors =
|
||||
vec![current.expect_err("current coordinator must not infer empty from missing directories and offline disks")];
|
||||
if source.requires_list_parts_read_quorum {
|
||||
quorum_errors.push(legacy.expect_err("previous coordinator must require evidence from unavailable disks"));
|
||||
} else {
|
||||
assert!(
|
||||
legacy
|
||||
.expect("previous coordinator should expose its legacy empty-list behavior")
|
||||
.parts()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
for error in quorum_errors {
|
||||
assert_eq!(error.raw_response().expect("S3 response").status().as_u16(), 503);
|
||||
assert_eq!(error.as_service_error().and_then(|error| error.meta().code()), Some("ServiceUnavailable"));
|
||||
}
|
||||
dist.cluster.start_node_from_binary(3, previous).await?;
|
||||
wait_for_upgrade_write_readiness(&clients, &seed.history_bucket, "mixed-list-restored", CREDENTIAL_TIMEOUT).await?;
|
||||
for (path, before) in original_files {
|
||||
@@ -520,7 +531,7 @@ async fn compare_degraded_legacy_list_parts(dist: &mut DistCluster, seed: &Upgra
|
||||
assert_eq!(listed.parts()[0].e_tag(), Some(seed.multipart_etag.as_str()));
|
||||
}
|
||||
eprintln!(
|
||||
"MPU mixed degraded: one offline disk, three missing part directories; previous returned empty, current returned 503 SlowDownRead; original part restored on both"
|
||||
"MPU mixed degraded: one offline disk, three missing part directories; checked each coordinator against its release contract; original part restored on both"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -592,6 +603,7 @@ async fn replace_node_and_wait_for_write_readiness(dist: &mut DistCluster, seed:
|
||||
async fn four_node_rolling_upgrade_preserves_history_and_iam_credentials() -> TestResult {
|
||||
init_logging();
|
||||
let previous = source_binary()?;
|
||||
let source = UpgradeSourceCapabilities::from_binary(&previous).await?;
|
||||
let mut dist = DistCluster::new_stopped(DistLayout::FourNodeFourDisk).await?;
|
||||
dist.cluster.set_env("RUSTFS_STORAGE_CLASS_RRS", "EC:0");
|
||||
capture_upgrade_logs(&mut dist, "rolling-upgrade")?;
|
||||
@@ -601,7 +613,7 @@ async fn four_node_rolling_upgrade_preserves_history_and_iam_credentials() -> Te
|
||||
|
||||
replace_node_and_wait_for_write_readiness(&mut dist, &seed, 0).await?;
|
||||
assert_history_and_iam(&dist, &seed, "one-current-node").await?;
|
||||
compare_degraded_legacy_list_parts(&mut dist, &seed, &previous).await?;
|
||||
compare_degraded_legacy_list_parts(&mut dist, &seed, &previous, &source).await?;
|
||||
|
||||
for node_idx in [1, 2] {
|
||||
replace_node_and_wait_for_write_readiness(&mut dist, &seed, node_idx).await?;
|
||||
|
||||
@@ -12,21 +12,22 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Dual-stack differential: one `rustfs` binary, two processes, one SDK script (rustfs/backlog#2740).
|
||||
//! Differential: two `rustfs` processes, one SDK script (rustfs/backlog#2740).
|
||||
//!
|
||||
//! Stack A runs `RUSTFS_S3_STACK=legacy` of the binary under test, unless `RUSTFS_E2E_REFERENCE_BINARY`
|
||||
//! names a released binary: then A is that binary, started without `RUSTFS_S3_STACK` (older
|
||||
//! releases do not know it), and a bad path fails the run instead of falling back (see
|
||||
//! `reference`). The report names which side is the reference and the `--version` each side ran. Stack B runs the value of `RUSTFS_E2E_STACK_B`
|
||||
//! (default `legacy` until the gateway stack is assembled), and `RUSTFS_E2E_STACK_B_REGION`, when
|
||||
//! set, starts B in another region so that a difference can be injected by hand. Both servers
|
||||
//! Side B is the binary under test. Side A is the binary under test too, unless
|
||||
//! `RUSTFS_E2E_REFERENCE_BINARY` names a released binary: then A is that binary, and a bad path
|
||||
//! fails the run instead of falling back (see `reference`). The report names which side is the
|
||||
//! reference and the `--version` each side ran. `RUSTFS_E2E_STACK_B_REGION`, when set, starts B
|
||||
//! in another region so that a difference can be injected by hand. Neither side is given the
|
||||
//! retired stack selector: the binary under test refuses to start with it, and the gateway stack
|
||||
//! is its only S3 stack. Both servers
|
||||
//! answer the script in `scenarios`, which covers every operation of `impl S3 for FS`; `compare`
|
||||
//! reports each `(op, field, a, b)` on which the answers differ, and every run writes its report
|
||||
//! to `<target>/dual-stack/<run>.json`. Two processes, not two embedded servers: bucket metadata
|
||||
//! is process-global, so two stacks in one process would read each other's buckets.
|
||||
|
||||
mod compare;
|
||||
mod reference;
|
||||
pub(crate) mod reference;
|
||||
mod scenarios;
|
||||
|
||||
use crate::common::{RustFSTestEnvironment, init_logging, rustfs_binary_path, workspace_root};
|
||||
@@ -37,20 +38,18 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
type BoxError = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
||||
const STACK_A: &str = "legacy";
|
||||
/// Label of a side that runs the binary under test.
|
||||
const UNDER_TEST: &str = "under-test";
|
||||
/// Label of side A in the report when it is the released reference binary.
|
||||
const STACK_A_REFERENCE: &str = "reference";
|
||||
const ENV_STACK_B: &str = "RUSTFS_E2E_STACK_B";
|
||||
const ENV_STACK_B_REGION: &str = "RUSTFS_E2E_STACK_B_REGION";
|
||||
/// Becomes `gateway` once rustfs/backlog#2734 T2.5 assembles the gateway stack.
|
||||
const DEFAULT_STACK_B: &str = "legacy";
|
||||
/// The region the negative control gives stack A explicitly, so an inherited `RUSTFS_REGION`
|
||||
/// cannot erase the injected difference. Not `us-east-1`: that region answers GetBucketLocation
|
||||
/// with an empty LocationConstraint and re-creating an owned bucket with 200, so it would not
|
||||
/// report its own name and would add CreateBucket differences to the control.
|
||||
const CONTROL_REGION_A: &str = "us-west-2";
|
||||
const CONTROL_REGION_B: &str = "eu-west-1";
|
||||
/// `normal` cases the legacy stack must answer with a 2xx. The comparison alone cannot tell a
|
||||
/// `normal` cases side A must answer with a 2xx. The comparison alone cannot tell a
|
||||
/// script that exercises real behavior from one in which both stacks fail the same way. Five of
|
||||
/// the 73 fail on legacy by design of this script: PutBucketReplication (no registered remote
|
||||
/// target), GetBucketReplication (so no configuration), PutBucketNotificationConfiguration (no
|
||||
@@ -60,7 +59,6 @@ const MIN_NORMAL_SUCCESSES: usize = 68;
|
||||
|
||||
struct PairConfig {
|
||||
side_a: SideA,
|
||||
stack_b: String,
|
||||
region_a: Option<String>,
|
||||
region_b: Option<String>,
|
||||
}
|
||||
@@ -69,7 +67,6 @@ impl PairConfig {
|
||||
fn from_env() -> Result<Self, BoxError> {
|
||||
Ok(Self {
|
||||
side_a: SideA::from_env()?,
|
||||
stack_b: std::env::var(ENV_STACK_B).unwrap_or_else(|_| DEFAULT_STACK_B.to_owned()),
|
||||
region_a: None,
|
||||
region_b: std::env::var(ENV_STACK_B_REGION).ok(),
|
||||
})
|
||||
@@ -77,16 +74,16 @@ impl PairConfig {
|
||||
|
||||
fn stack_a_label(&self) -> &'static str {
|
||||
match self.side_a {
|
||||
SideA::SameBinary => STACK_A,
|
||||
SideA::SameBinary => UNDER_TEST,
|
||||
SideA::Reference(_) => STACK_A_REFERENCE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts one server of the binary under test on `stack`, overriding its region only when asked.
|
||||
async fn start_stack(stack: &str, region: Option<&str>) -> Result<RustFSTestEnvironment, BoxError> {
|
||||
/// Starts one server of the binary under test, overriding its region only when asked.
|
||||
async fn start_under_test(region: Option<&str>) -> Result<RustFSTestEnvironment, BoxError> {
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
let mut vars = vec![("RUSTFS_S3_STACK", stack)];
|
||||
let mut vars = Vec::new();
|
||||
if let Some(region) = region {
|
||||
vars.push(("RUSTFS_REGION", region));
|
||||
}
|
||||
@@ -94,8 +91,7 @@ async fn start_stack(stack: &str, region: Option<&str>) -> Result<RustFSTestEnvi
|
||||
Ok(env)
|
||||
}
|
||||
|
||||
/// Starts one server of a released binary. `RUSTFS_S3_STACK` is not passed: older releases do not
|
||||
/// know it and have exactly one stack.
|
||||
/// Starts one server of a released binary.
|
||||
async fn start_reference(binary: &Path, region: Option<&str>) -> Result<RustFSTestEnvironment, BoxError> {
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
let mut vars = Vec::new();
|
||||
@@ -111,11 +107,11 @@ async fn start_reference(binary: &Path, region: Option<&str>) -> Result<RustFSTe
|
||||
async fn spawn_pair(config: &PairConfig) -> Result<(RustFSTestEnvironment, RustFSTestEnvironment), BoxError> {
|
||||
let side_a = async {
|
||||
match &config.side_a {
|
||||
SideA::SameBinary => start_stack(STACK_A, config.region_a.as_deref()).await,
|
||||
SideA::SameBinary => start_under_test(config.region_a.as_deref()).await,
|
||||
SideA::Reference(binary) => start_reference(binary, config.region_a.as_deref()).await,
|
||||
}
|
||||
};
|
||||
tokio::try_join!(side_a, start_stack(&config.stack_b, config.region_b.as_deref()))
|
||||
tokio::try_join!(side_a, start_under_test(config.region_b.as_deref()))
|
||||
}
|
||||
|
||||
fn report_directory() -> PathBuf {
|
||||
@@ -160,7 +156,7 @@ async fn run_differential(label: &str, config: &PairConfig) -> Run {
|
||||
schema: 2,
|
||||
run: format!("{label}-{millis}-{}", std::process::id()),
|
||||
stack_a: config.stack_a_label().to_owned(),
|
||||
stack_b: config.stack_b.clone(),
|
||||
stack_b: UNDER_TEST.to_owned(),
|
||||
reference_side: matches!(config.side_a, SideA::Reference(_)).then_some("a"),
|
||||
version_a,
|
||||
version_b,
|
||||
@@ -235,7 +231,6 @@ mod tests {
|
||||
init_logging();
|
||||
let config = PairConfig {
|
||||
side_a: SideA::SameBinary,
|
||||
stack_b: STACK_A.to_owned(),
|
||||
region_a: Some(CONTROL_REGION_A.to_owned()),
|
||||
region_b: Some(CONTROL_REGION_B.to_owned()),
|
||||
};
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
//! Which binary side A of the differential runs, and what it reports about itself.
|
||||
//!
|
||||
//! `RUSTFS_E2E_REFERENCE_BINARY` names a released `rustfs` binary to use as the reference. Unset,
|
||||
//! side A is the binary under test on `RUSTFS_S3_STACK=legacy`. Set, it must resolve to an
|
||||
//! side A is the binary under test. Set, it must resolve to an
|
||||
//! executable file or the run fails: a reference that was asked for and silently replaced by the
|
||||
//! binary under test would report an agreement with itself as agreement with the release.
|
||||
|
||||
@@ -28,9 +28,9 @@ pub(super) const ENV_REFERENCE_BINARY: &str = "RUSTFS_E2E_REFERENCE_BINARY";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) enum SideA {
|
||||
/// Both sides are the binary under test; A runs `RUSTFS_S3_STACK=legacy`.
|
||||
/// Both sides are the binary under test.
|
||||
SameBinary,
|
||||
/// A is this released binary, started without `RUSTFS_S3_STACK`.
|
||||
/// A is this released binary.
|
||||
Reference(PathBuf),
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ fn is_executable(_metadata: &std::fs::Metadata) -> bool {
|
||||
|
||||
/// What `<binary> --version` printed, trimmed. Fails when the binary does not run, exits
|
||||
/// non-zero, or prints nothing, because an empty version would report nothing as observed.
|
||||
pub(super) async fn binary_version(binary: &Path) -> Result<String, BoxError> {
|
||||
pub(crate) async fn binary_version(binary: &Path) -> Result<String, BoxError> {
|
||||
let output = tokio::process::Command::new(binary).arg("--version").output().await?;
|
||||
if !output.status.success() {
|
||||
return Err(format!("{} --version failed with {}", binary.display(), output.status).into());
|
||||
|
||||
@@ -29,6 +29,7 @@ use aws_sdk_s3::primitives::ByteStream;
|
||||
use aws_sdk_s3::types::ServerSideEncryption;
|
||||
use base64_simd::STANDARD as BASE64;
|
||||
use http::header::{CONTENT_TYPE, HOST};
|
||||
use jiff::Timestamp;
|
||||
use md5::{Digest as Md5Digest, Md5};
|
||||
use rustfs_s3_types::Body;
|
||||
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
||||
@@ -386,7 +387,7 @@ pub async fn create_key_with_specific_id(key_dir: &str, key_id: &str) -> Result<
|
||||
"usage": "EncryptDecrypt",
|
||||
"status": "Active",
|
||||
"metadata": HashMap::<String, String>::new(),
|
||||
"created_at": format!("{}[UTC]", chrono::Utc::now().to_rfc3339()),
|
||||
"created_at": format!("{}[UTC]", Timestamp::now().strftime("%Y-%m-%dT%H:%M:%S%.fZ")),
|
||||
"rotated_at": serde_json::Value::Null,
|
||||
"created_by": "e2e-test",
|
||||
"encrypted_key_material": BASE64.encode_to_string(key_data),
|
||||
|
||||
@@ -31,12 +31,15 @@ pub mod chaos;
|
||||
#[cfg(test)]
|
||||
pub mod fake_s3_target;
|
||||
|
||||
// Dual-stack differential (rustfs/backlog#2740): one binary, two processes on
|
||||
// different RUSTFS_S3_STACK values, the same SDK script for every S3 operation,
|
||||
// Differential (rustfs/backlog#2740): two processes, the binary under test against
|
||||
// itself or a released reference binary, the same SDK script for every S3 operation,
|
||||
// compared on status, error code, allowlisted headers and typed body fields.
|
||||
#[cfg(test)]
|
||||
mod dual_stack_differential;
|
||||
|
||||
#[cfg(test)]
|
||||
mod persistence_parity;
|
||||
|
||||
// On-demand migration (backlog#2147): shared two-server environment, admin
|
||||
// wrappers, and the harness self-test (backlog#2151). Behavior scenarios are
|
||||
// added by later ODM tasks.
|
||||
|
||||
@@ -23,13 +23,13 @@ use aws_sdk_s3::primitives::ByteStream;
|
||||
use aws_sdk_s3::types::{
|
||||
ServerSideEncryption, ServerSideEncryptionByDefault, ServerSideEncryptionConfiguration, ServerSideEncryptionRule,
|
||||
};
|
||||
use chrono::{Duration as ChronoDuration, Utc};
|
||||
use flate2::{
|
||||
Compression,
|
||||
write::{GzEncoder, ZlibEncoder},
|
||||
};
|
||||
use http::HeaderValue;
|
||||
use http::header::{CONTENT_TYPE, HOST};
|
||||
use jiff::{SignedDuration, Timestamp};
|
||||
use md5::{Digest as Md5Digest, Md5};
|
||||
use rustfs_s3_types::Body;
|
||||
use rustfs_signer::constants::UNSIGNED_PAYLOAD;
|
||||
@@ -42,8 +42,8 @@ use tokio::io::AsyncWriteExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
fn encode_post_policy(conditions: Vec<serde_json::Value>) -> String {
|
||||
let expiration = (Utc::now() + ChronoDuration::hours(1))
|
||||
.format("%Y-%m-%dT%H:%M:%S.000Z")
|
||||
let expiration = (Timestamp::now() + SignedDuration::from_hours(1))
|
||||
.strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
||||
.to_string();
|
||||
let policy = serde_json::json!({
|
||||
"expiration": expiration,
|
||||
@@ -1543,6 +1543,30 @@ async fn test_anonymous_post_object_honors_success_action_status() -> Result<(),
|
||||
let uploaded = get_out.body.collect().await?.into_bytes();
|
||||
assert_eq!(uploaded.as_ref(), expected_body.as_slice(), "uploaded object body should match");
|
||||
|
||||
// An empty redirect is rejected when rendering the response, after storage succeeds.
|
||||
for (field, value, expected_status) in [
|
||||
("success_action_status", "200", reqwest::StatusCode::OK),
|
||||
("success_action_status", "204", reqwest::StatusCode::NO_CONTENT),
|
||||
("success_action_redirect", "", reqwest::StatusCode::BAD_REQUEST),
|
||||
] {
|
||||
let key = format!("{field}-{value}.txt");
|
||||
let form = reqwest::multipart::Form::new()
|
||||
.text("key", key.clone())
|
||||
.text(field, value)
|
||||
.part("file", reqwest::multipart::Part::bytes(expected_body.clone()).file_name("upload.txt"));
|
||||
let response = local_http_client()
|
||||
.post(format!("{}/{bucket}", env.url))
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await?;
|
||||
assert_eq!(response.status(), expected_status);
|
||||
if value.is_empty() {
|
||||
assert!(response.text().await?.contains("<Code>InvalidArgument</Code>"));
|
||||
}
|
||||
let stored = admin_client.get_object().bucket(bucket).key(key).send().await?;
|
||||
assert_eq!(stored.body.collect().await?.into_bytes().as_ref(), expected_body.as_slice());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -283,6 +283,7 @@ async fn test_cold_degraded_object_mutations_require_only_storage_quorum() -> Te
|
||||
#[tokio::test]
|
||||
async fn test_degraded_cluster_read_quorum_follows_erasure_layout() -> TestResult {
|
||||
crate::common::init_logging();
|
||||
assert_single_node_cold_start_with_missing_volume().await?;
|
||||
|
||||
for (node_count, parity) in [(3, 1), (4, 2), (6, 3), (6, 2), (4, 0)] {
|
||||
let read_quorum = node_count - parity;
|
||||
@@ -430,6 +431,138 @@ async fn test_degraded_cluster_read_quorum_follows_erasure_layout() -> TestResul
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn assert_single_node_cold_start_with_missing_volume() -> TestResult {
|
||||
for drive_count in [2, 3, 4] {
|
||||
let mut server = crate::chaos::DiskFaultHarness::new(drive_count).await?;
|
||||
server.set_env("RUSTFS_STORAGE_CLASS_STANDARD", format!("EC:{}", drive_count / 2));
|
||||
server.set_env("RUSTFS_PUT_RENAME_EARLY_ACK_ENABLE", "false");
|
||||
server.set_env("RUSTFS_OBS_METRICS_EXPORT_ENABLED", "false");
|
||||
server.set_env("RUSTFS_HEALTH_ENDPOINT_ENABLE", "true");
|
||||
server.set_env("RUST_LOG", "warn");
|
||||
server.start_server_at_read_quorum().await?;
|
||||
let client = server.env.create_s3_client();
|
||||
let client = Client::from_conf(
|
||||
client
|
||||
.config()
|
||||
.to_builder()
|
||||
.retry_config(aws_sdk_s3::config::retry::RetryConfig::standard().with_max_attempts(1))
|
||||
.build(),
|
||||
);
|
||||
let bucket = format!("missing-volume-{drive_count}");
|
||||
client.create_bucket().bucket(&bucket).send().await?;
|
||||
let small = vec![17; 4096];
|
||||
let large = vec![73; 8 * 1024 * 1024];
|
||||
for (key, body) in [("small", &small), ("large", &large)] {
|
||||
client
|
||||
.put_object()
|
||||
.bucket(&bucket)
|
||||
.key(key)
|
||||
.body(Bytes::copy_from_slice(body).into())
|
||||
.send()
|
||||
.await?;
|
||||
for disk in 0..drive_count {
|
||||
let census = crate::chaos::census_object_version_on_disk(server.disk_path(disk), &bucket, key, None)?;
|
||||
assert!(census.is_complete(), "seed shard must exist before restart: {census:?}");
|
||||
}
|
||||
}
|
||||
server.kill_server();
|
||||
let missing = drive_count - 1;
|
||||
server.take_disk_offline(missing)?;
|
||||
server.start_server_at_read_quorum().await?;
|
||||
|
||||
for (key, body) in [("small", &small), ("large", &large)] {
|
||||
assert_quorum_object_body(&client, &bucket, key, body).await?;
|
||||
let head = client.head_object().bucket(&bucket).key(key).send().await?;
|
||||
assert_eq!(head.content_length(), Some(i64::try_from(body.len())?));
|
||||
}
|
||||
let listing = client.list_objects_v2().bucket(&bucket).send().await?;
|
||||
let keys: Vec<_> = listing.contents().iter().filter_map(|object| object.key()).collect();
|
||||
assert_eq!(keys, ["large", "small"]);
|
||||
|
||||
let put = client
|
||||
.put_object()
|
||||
.bucket(&bucket)
|
||||
.key("degraded-write")
|
||||
.body(Bytes::from_static(b"degraded write").into())
|
||||
.send()
|
||||
.await;
|
||||
if drive_count == 2 {
|
||||
let error = put.expect_err("one of two drives cannot commit a new object");
|
||||
assert_eq!(error.raw_response().map(|response| response.status().as_u16()), Some(503));
|
||||
let error = client
|
||||
.delete_object()
|
||||
.bucket(&bucket)
|
||||
.key("large")
|
||||
.send()
|
||||
.await
|
||||
.expect_err("one of two drives cannot commit an object deletion");
|
||||
assert_eq!(error.raw_response().map(|response| response.status().as_u16()), Some(503));
|
||||
assert_quorum_object_body(&client, &bucket, "large", &large).await?;
|
||||
} else {
|
||||
put?;
|
||||
assert_quorum_object_body(&client, &bucket, "degraded-write", b"degraded write").await?;
|
||||
client.delete_object().bucket(&bucket).key("degraded-write").send().await?;
|
||||
}
|
||||
assert!(
|
||||
!server.disk_path(missing).exists(),
|
||||
"degraded startup and S3 operations must leave the root absent"
|
||||
);
|
||||
|
||||
if drive_count == 2 {
|
||||
server.kill_server();
|
||||
std::fs::create_dir(server.disk_path(missing))?;
|
||||
server.start_server_at_read_quorum().await?;
|
||||
for (key, body) in [("small", &small), ("large", &large)] {
|
||||
assert_quorum_object_body(&client, &bucket, key, body).await?;
|
||||
client.head_object().bucket(&bucket).key(key).send().await?;
|
||||
}
|
||||
assert_eq!(client.list_objects_v2().bucket(&bucket).send().await?.contents().len(), 2);
|
||||
let error = client
|
||||
.put_object()
|
||||
.bucket(&bucket)
|
||||
.key("empty-root-write")
|
||||
.body(Bytes::from_static(b"must remain unavailable").into())
|
||||
.send()
|
||||
.await
|
||||
.expect_err("an empty replacement cannot restore write quorum");
|
||||
assert_eq!(error.raw_response().map(|response| response.status().as_u16()), Some(503));
|
||||
assert!(
|
||||
!server
|
||||
.disk_path(missing)
|
||||
.join(crate::storage_api::RUSTFS_META_BUCKET)
|
||||
.join("format.json")
|
||||
.exists(),
|
||||
"read admission must not format the empty replacement"
|
||||
);
|
||||
}
|
||||
server.kill_server();
|
||||
server.bring_disk_online(missing)?;
|
||||
server.start_server_at_read_quorum().await?;
|
||||
for (key, body) in [("small", &small), ("large", &large)] {
|
||||
assert_quorum_object_body(&client, &bucket, key, body).await?;
|
||||
}
|
||||
for key in ["degraded-write", "empty-root-write"] {
|
||||
let error = client
|
||||
.head_object()
|
||||
.bucket(&bucket)
|
||||
.key(key)
|
||||
.send()
|
||||
.await
|
||||
.expect_err("rejected or deleted degraded write must stay absent after recovery");
|
||||
assert_eq!(error.raw_response().map(|response| response.status().as_u16()), Some(404));
|
||||
}
|
||||
client
|
||||
.put_object()
|
||||
.bucket(&bucket)
|
||||
.key("recovery-write")
|
||||
.body(Bytes::from_static(b"recovered write").into())
|
||||
.send()
|
||||
.await?;
|
||||
assert_quorum_object_body(&client, &bucket, "recovery-write", b"recovered write").await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_cold_start_read_quorum_follows_erasure_layout() -> TestResult {
|
||||
crate::common::init_logging();
|
||||
|
||||
@@ -29,7 +29,7 @@ use aws_sdk_s3::types::{
|
||||
DefaultRetention, ObjectLockConfiguration, ObjectLockEnabled, ObjectLockLegalHold, ObjectLockLegalHoldStatus, ObjectLockMode,
|
||||
ObjectLockRetention, ObjectLockRetentionMode, ObjectLockRule,
|
||||
};
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use jiff::{SignedDuration, Timestamp};
|
||||
use tracing::info;
|
||||
|
||||
use crate::common::RustFSTestEnvironment;
|
||||
@@ -126,10 +126,10 @@ pub async fn put_object_with_retention(
|
||||
key: &str,
|
||||
data: &[u8],
|
||||
mode: ObjectLockRetentionMode,
|
||||
retain_until: DateTime<Utc>,
|
||||
retain_until: Timestamp,
|
||||
) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
|
||||
// AWS SDK requires UTC time without timezone offset (e.g., "2026-01-24T11:20:14Z")
|
||||
let retain_until_str = retain_until.format("%Y-%m-%dT%H:%M:%SZ").to_string();
|
||||
let retain_until_str = retain_until.strftime("%Y-%m-%dT%H:%M:%SZ").to_string();
|
||||
let retain_until_datetime =
|
||||
aws_sdk_s3::primitives::DateTime::from_str(&retain_until_str, aws_sdk_s3::primitives::DateTimeFormat::DateTime)?;
|
||||
|
||||
@@ -181,10 +181,10 @@ pub async fn put_object_retention(
|
||||
key: &str,
|
||||
version_id: Option<&str>,
|
||||
mode: ObjectLockRetentionMode,
|
||||
retain_until: DateTime<Utc>,
|
||||
retain_until: Timestamp,
|
||||
bypass_governance: bool,
|
||||
) -> Result<(), Box<SdkError<PutObjectRetentionError>>> {
|
||||
let retain_until_datetime = aws_sdk_s3::primitives::DateTime::from_secs(retain_until.timestamp());
|
||||
let retain_until_datetime = aws_sdk_s3::primitives::DateTime::from_secs(retain_until.as_second());
|
||||
|
||||
let retention = ObjectLockRetention::builder()
|
||||
.mode(mode.clone())
|
||||
@@ -253,6 +253,6 @@ pub async fn delete_object_with_bypass(
|
||||
}
|
||||
|
||||
/// Calculate a future retain_until date
|
||||
pub fn future_retain_until(days: i64) -> DateTime<Utc> {
|
||||
Utc::now() + Duration::days(days)
|
||||
pub fn future_retain_until(days: i64) -> Timestamp {
|
||||
Timestamp::now() + SignedDuration::from_hours(days * 24)
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ use aws_sdk_s3::types::{
|
||||
CompletedMultipartUpload, CompletedPart, Delete, MetadataDirective, ObjectIdentifier, ObjectLockLegalHoldStatus,
|
||||
ObjectLockMode, ObjectLockRetentionMode,
|
||||
};
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use jiff::{SignedDuration, Timestamp};
|
||||
use tracing::info;
|
||||
|
||||
/// Initialize test logging
|
||||
@@ -67,7 +67,7 @@ async fn put_bucket_deny_policy(
|
||||
}
|
||||
|
||||
fn retention_timestamp(days: i64) -> aws_sdk_s3::primitives::DateTime {
|
||||
let retain_until = future_retain_until(days).format("%Y-%m-%dT%H:%M:%SZ").to_string();
|
||||
let retain_until = future_retain_until(days).strftime("%Y-%m-%dT%H:%M:%SZ").to_string();
|
||||
aws_sdk_s3::primitives::DateTime::from_str(&retain_until, aws_sdk_s3::primitives::DateTimeFormat::DateTime)
|
||||
.expect("retention timestamp should parse")
|
||||
}
|
||||
@@ -118,13 +118,14 @@ where
|
||||
);
|
||||
}
|
||||
|
||||
fn parse_s3_datetime(value: &aws_sdk_s3::primitives::DateTime) -> DateTime<Utc> {
|
||||
fn parse_s3_datetime(value: &aws_sdk_s3::primitives::DateTime) -> Timestamp {
|
||||
let formatted = value
|
||||
.fmt(DateTimeFormat::DateTime)
|
||||
.expect("S3 timestamp should format as RFC3339");
|
||||
DateTime::parse_from_rfc3339(&formatted)
|
||||
.expect("S3 timestamp should parse as RFC3339")
|
||||
.with_timezone(&Utc)
|
||||
let normalized = formatted
|
||||
.strip_suffix('Z')
|
||||
.map_or(formatted.clone(), |prefix| format!("{prefix}+00:00"));
|
||||
Timestamp::strptime("%Y-%m-%dT%H:%M:%S%.f%:z", normalized).expect("S3 timestamp should parse as RFC3339")
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -470,7 +471,7 @@ async fn test_get_object_retention_returns_configured_values() {
|
||||
let bucket = "test-get-retention";
|
||||
let key = "retained-object";
|
||||
let retain_until = future_retain_until(30);
|
||||
let retain_until_expected = retain_until.format("%Y-%m-%dT%H:%M:%SZ").to_string();
|
||||
let retain_until_expected = retain_until.strftime("%Y-%m-%dT%H:%M:%SZ").to_string();
|
||||
|
||||
env.create_object_lock_bucket(bucket).await.unwrap();
|
||||
|
||||
@@ -1924,7 +1925,7 @@ async fn test_copy_object_retention_uses_destination_policy() {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let copy_started = Utc::now();
|
||||
let copy_started = Timestamp::now();
|
||||
client
|
||||
.copy_object()
|
||||
.copy_source(format!("{src_bucket}/{src_key}"))
|
||||
@@ -1947,7 +1948,7 @@ async fn test_copy_object_retention_uses_destination_policy() {
|
||||
assert_eq!(retention.mode().map(|value| value.as_str()), Some("GOVERNANCE"));
|
||||
let retain_until = parse_s3_datetime(retention.retain_until_date().expect("retain-until date should be present"));
|
||||
assert!(
|
||||
retain_until < copy_started + Duration::days(3),
|
||||
retain_until < copy_started + SignedDuration::from_hours(3 * 24),
|
||||
"destination default retention should not inherit the source's longer retention"
|
||||
);
|
||||
|
||||
@@ -2008,7 +2009,7 @@ async fn test_copy_object_retention_uses_destination_policy() {
|
||||
.expect("explicit retain-until date should be present"),
|
||||
);
|
||||
assert!(
|
||||
explicit_retain_until > Utc::now() + Duration::days(20),
|
||||
explicit_retain_until > Timestamp::now() + SignedDuration::from_hours(20 * 24),
|
||||
"explicit retention should override the shorter bucket default"
|
||||
);
|
||||
|
||||
@@ -2088,7 +2089,7 @@ async fn test_multipart_default_retention_fixed_at_create() {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let create_started = Utc::now();
|
||||
let create_started = Timestamp::now();
|
||||
let create_output = client.create_multipart_upload().bucket(bucket).key(key).send().await.unwrap();
|
||||
let upload_id = create_output.upload_id().unwrap();
|
||||
|
||||
@@ -2131,7 +2132,7 @@ async fn test_multipart_default_retention_fixed_at_create() {
|
||||
assert_eq!(retention.mode().map(|value| value.as_str()), Some("GOVERNANCE"));
|
||||
let retain_until = parse_s3_datetime(retention.retain_until_date().expect("retain-until date should be present"));
|
||||
assert!(
|
||||
retain_until < create_started + Duration::days(3),
|
||||
retain_until < create_started + SignedDuration::from_hours(3 * 24),
|
||||
"CompleteMultipartUpload should keep the default retention calculated at create time"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,449 @@
|
||||
// Copyright 2024 RustFS Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Compare bytes produced by S3 writes to independent, single-drive volumes.
|
||||
|
||||
use crate::common::{RustFSTestEnvironment, admin_request, rustfs_binary_path, signed_s3_request_with_headers};
|
||||
use crate::dual_stack_differential::reference::binary_version;
|
||||
use crate::fake_s3_target::{FAKE_ACCESS_KEY, FAKE_SECRET_KEY, FakeS3Target};
|
||||
use crate::on_demand_migration::common::{ODM_ADMIN_ROUTE, ODM_MODULE_SWITCH_ENV, OdmSourceSpec};
|
||||
use crate::replication_extension_test::send_set_replication_target_request;
|
||||
use crate::storage_api::persistence_parity::{BucketMetadata, RUSTFS_META_BUCKET};
|
||||
use crate::upgrade_compatibility_test::{set_bucket_quota, write_multipart};
|
||||
use aws_sdk_s3::Client;
|
||||
use aws_sdk_s3::primitives::ByteStream;
|
||||
use aws_sdk_s3::types::{BucketCannedAcl, Tag, Tagging};
|
||||
use http::{HeaderMap, Method};
|
||||
use md5::{Digest, Md5};
|
||||
use rustfs_filemeta::{FileMeta, MetaObject};
|
||||
use serde_value::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
type Error = Box<dyn std::error::Error + Send + Sync>;
|
||||
const CONFIGS: &str = "persisted-configs";
|
||||
const OBJECTS: &str = "persisted-objects";
|
||||
const FIRST_PART_SIZE: usize = 5 * 1024 * 1024;
|
||||
const LOGS: &str = "rustfs-access-logs";
|
||||
|
||||
fn bucket_metadata(volume: &Path, bucket: &str) -> Result<BucketMetadata, Error> {
|
||||
let key = BucketMetadata::new(bucket).save_file_path();
|
||||
let object = volume.join(RUSTFS_META_BUCKET).join(&key);
|
||||
let meta = FileMeta::load(&std::fs::read(object.join("xl.meta"))?)?;
|
||||
let info = meta.into_fileinfo(RUSTFS_META_BUCKET, &key, "", true, false, true)?;
|
||||
info.validate_for_metadata_read()?;
|
||||
let [part] = info.parts.as_slice() else { return Err("bucket metadata must have one part".into()) };
|
||||
let size = usize::try_from(info.size)?;
|
||||
if info.erasure.data_blocks != 1 || size != part.size || size > info.erasure.block_size {
|
||||
return Err("bucket metadata exceeds the single-drive, single-stripe fixture".into());
|
||||
}
|
||||
let framed = if info.inline_data() {
|
||||
info.data.ok_or("missing inline bucket metadata")?.to_vec()
|
||||
} else {
|
||||
let directory = info.data_dir.ok_or("missing bucket metadata data directory")?;
|
||||
std::fs::read(object.join(directory.to_string()).join(format!("part.{}", part.number)))?
|
||||
};
|
||||
let algorithm = info.erasure.get_checksum_info(part.number).algorithm;
|
||||
let (digest, payload) = framed.split_at_checked(algorithm.size()).ok_or("truncated bucket metadata")?;
|
||||
if digest.is_empty() || payload.len() != size || algorithm.hash_encode(payload).as_ref() != digest {
|
||||
return Err("invalid bucket metadata shard checksum or size".into());
|
||||
}
|
||||
BucketMetadata::check_header(payload)?;
|
||||
let fields = &payload[4..];
|
||||
if bucket == CONFIGS {
|
||||
// The production decoder defaults a missing field to empty. Require the ACL field on disk
|
||||
// so dropping it cannot look like the expected zero-byte document.
|
||||
let keys: BTreeMap<&str, serde::de::IgnoredAny> = rmp_serde::from_slice(fields)?;
|
||||
if !keys.contains_key("BucketAclConfigJSON") {
|
||||
return Err("missing BucketAclConfigJSON field".into());
|
||||
}
|
||||
}
|
||||
Ok(BucketMetadata::unmarshal(fields)?)
|
||||
}
|
||||
|
||||
type VersionFields = BTreeMap<String, Value>;
|
||||
|
||||
fn read_object(volume: &Path, key: &str) -> Result<(MetaObject, VersionFields), Error> {
|
||||
let meta = FileMeta::load(&std::fs::read(volume.join(OBJECTS).join(key).join("xl.meta"))?)?;
|
||||
let [version] = meta.versions.as_slice() else {
|
||||
return Err(format!("{key}: expected one version").into());
|
||||
};
|
||||
let object = version.parse_version_meta()?.object.ok_or("missing V2 object")?;
|
||||
if object.mod_time.is_none() || object.data_dir.is_none_or(|id| id.is_nil()) {
|
||||
return Err(format!("{key}: missing modification time or data directory").into());
|
||||
}
|
||||
Ok((object, nonvolatile_fields(&version.meta, key)?))
|
||||
}
|
||||
|
||||
fn nonvolatile_fields(raw: &[u8], key: &str) -> Result<VersionFields, Error> {
|
||||
// The production reader skips unknown keys and supplies defaults for some missing keys.
|
||||
// Keep the raw maps so both the version envelope and V2Obj preserve every field and value.
|
||||
let mut fields: VersionFields = rmp_serde::from_slice(raw)?;
|
||||
let Some(Value::Map(object_fields)) = fields.get_mut("V2Obj") else {
|
||||
return Err(format!("{key}: missing raw V2Obj map").into());
|
||||
};
|
||||
for volatile in ["MTime", "DDir"] {
|
||||
let value = object_fields
|
||||
.get_mut(&Value::String(volatile.to_owned()))
|
||||
.ok_or_else(|| format!("{key}: missing {volatile}"))?;
|
||||
*value = Value::Unit;
|
||||
}
|
||||
Ok(fields)
|
||||
}
|
||||
|
||||
async fn put_xml(env: &RustFSTestEnvironment, query: &str, xml: &str) -> Result<(), Error> {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("content-md5", base64_simd::STANDARD.encode_to_string(Md5::digest(xml)).parse()?);
|
||||
let response = signed_s3_request_with_headers(
|
||||
Method::PUT,
|
||||
&format!("{}/{CONFIGS}?{query}", env.url),
|
||||
Some(xml.to_owned()),
|
||||
Some("application/xml"),
|
||||
&env.access_key,
|
||||
&env.secret_key,
|
||||
&headers,
|
||||
)
|
||||
.await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("PUT ?{query} failed with {}", response.status()).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Snapshot {
|
||||
configs: BTreeMap<&'static str, Vec<u8>>,
|
||||
objects: BTreeMap<&'static str, VersionFields>,
|
||||
multipart_files: BTreeMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
async fn capture(binary: &Path, target: &FakeS3Target, clock: &str, clock_library: &str) -> Result<Snapshot, Error> {
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
let queue = tempfile::tempdir()?;
|
||||
let clock_loader = if cfg!(target_os = "macos") {
|
||||
"DYLD_INSERT_LIBRARIES"
|
||||
} else {
|
||||
"LD_PRELOAD"
|
||||
};
|
||||
let options = [
|
||||
(clock_loader, clock_library),
|
||||
("DYLD_FORCE_FLAT_NAMESPACE", "1"),
|
||||
("FAKETIME", clock),
|
||||
("FAKETIME_DONT_FAKE_MONOTONIC", "1"),
|
||||
("TZ", "UTC"),
|
||||
("RUSTFS_NOTIFY_ENABLE", "true"),
|
||||
("RUSTFS_NOTIFY_WEBHOOK_ENABLE_PRIMARY", "on"),
|
||||
("RUSTFS_NOTIFY_WEBHOOK_ENDPOINT_PRIMARY", target.endpoint()),
|
||||
(
|
||||
"RUSTFS_NOTIFY_WEBHOOK_QUEUE_DIR_PRIMARY",
|
||||
queue.path().to_str().ok_or("non-UTF8 queue path")?,
|
||||
),
|
||||
("RUSTFS_OUTBOUND_ALLOW_ORIGINS", target.endpoint()),
|
||||
("RUSTFS_REPLICATION_ALLOW_LOOPBACK_TARGET", "true"),
|
||||
(ODM_MODULE_SWITCH_ENV, "true"),
|
||||
("RUSTFS_NEW_BUCKET_DURABILITY_MODE", "strict"),
|
||||
("RUSTFS_SCANNER_CYCLE", "1"),
|
||||
("RUSTFS_SCANNER_START_DELAY_SECS", "0"),
|
||||
];
|
||||
env.start_rustfs_server_from_binary_without_cleanup(binary, vec![], &options)
|
||||
.await?;
|
||||
let client = env.create_s3_client();
|
||||
write_configs(&env, &client, target).await?;
|
||||
write_objects(&client).await?;
|
||||
env.stop_server();
|
||||
read_snapshot(Path::new(&env.temp_dir))
|
||||
}
|
||||
|
||||
async fn write_configs(env: &RustFSTestEnvironment, client: &Client, target: &FakeS3Target) -> Result<(), Error> {
|
||||
env.create_test_bucket(LOGS).await?;
|
||||
env.create_test_bucket(OBJECTS).await?;
|
||||
env.create_test_bucket("persistence-warehouse").await?;
|
||||
env.create_test_bucket("persistence-migration").await?;
|
||||
client
|
||||
.create_bucket()
|
||||
.bucket(CONFIGS)
|
||||
.object_lock_enabled_for_bucket(true)
|
||||
.send()
|
||||
.await?;
|
||||
macro_rules! golden {
|
||||
($path:literal) => {
|
||||
include_str!(concat!("../../ecstore/tests/fixtures/bucket-config-goldens/", $path, ".in.xml"))
|
||||
};
|
||||
}
|
||||
let target_request = serde_json::json!({
|
||||
"endpoint": target.address(), "credentials": {"accessKey": FAKE_ACCESS_KEY, "secretKey": FAKE_SECRET_KEY},
|
||||
"targetbucket": "interop-dr", "type": "replication", "secure": false,
|
||||
"deploymentID": "0b6f3c2a-5e6a-4d2b-9c1e-7a8f9d0e1b2c"
|
||||
});
|
||||
let response = send_set_replication_target_request(env, CONFIGS, false, target_request).await?;
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("set remote target failed with {}", response.status()).into());
|
||||
}
|
||||
let target_arn: String = response.json().await?;
|
||||
let replication = golden!("replication/rustfs").replace("arn:rustfs:replication:", "arn:minio:replication:");
|
||||
if !replication.contains(&format!("<Bucket>{target_arn}</Bucket>")) {
|
||||
return Err("registered target does not match the golden replication destination".into());
|
||||
}
|
||||
for (query, xml) in [
|
||||
("versioning", golden!("versioning/minio")),
|
||||
("notification", golden!("notification/rustfs")),
|
||||
("replication", replication.as_str()),
|
||||
("lifecycle", golden!("lifecycle/minio")),
|
||||
("object-lock", golden!("object_lock/rustfs")),
|
||||
("encryption", golden!("encryption/minio")),
|
||||
("tagging", golden!("tagging/rustfs")),
|
||||
("cors", golden!("cors/rustfs")),
|
||||
("logging", golden!("logging/rustfs")),
|
||||
("website", golden!("website/rustfs")),
|
||||
("accelerate", golden!("accelerate/rustfs")),
|
||||
("requestPayment", golden!("request_payment/rustfs")),
|
||||
("publicAccessBlock", golden!("public_access_block/rustfs")),
|
||||
] {
|
||||
put_xml(env, query, xml).await?;
|
||||
}
|
||||
client
|
||||
.put_bucket_acl()
|
||||
.bucket(CONFIGS)
|
||||
.acl(BucketCannedAcl::Private)
|
||||
.send()
|
||||
.await?;
|
||||
let acl = client.get_bucket_acl().bucket(CONFIGS).send().await?;
|
||||
let owner = acl.owner().and_then(|owner| owner.id()).ok_or("ACL owner missing")?;
|
||||
let [grant] = acl.grants() else { return Err("expected exactly one ACL grant".into()) };
|
||||
let grantee = grant.grantee().ok_or("missing ACL grantee")?;
|
||||
if owner.is_empty()
|
||||
|| grant.permission().map(|p| p.as_str()) != Some("FULL_CONTROL")
|
||||
|| grantee.r#type().as_str() != "CanonicalUser"
|
||||
|| grantee.id().is_some()
|
||||
{
|
||||
return Err("GET ACL changed its canonical owner grant".into());
|
||||
}
|
||||
let policy = serde_json::json!({
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Deny", "Principal": "*", "Action": "s3:DeleteObject",
|
||||
"Resource": format!("arn:aws:s3:::{CONFIGS}/protected/*"),
|
||||
}],
|
||||
});
|
||||
client
|
||||
.put_bucket_policy()
|
||||
.bucket(CONFIGS)
|
||||
.policy(policy.to_string())
|
||||
.send()
|
||||
.await?;
|
||||
set_bucket_quota(env, CONFIGS, 16 * 1024 * 1024).await?;
|
||||
let migration = OdmSourceSpec::for_fake_source(target, "migration-source");
|
||||
for (path, body) in [
|
||||
("/iceberg/v1/buckets/persistence-warehouse".to_owned(), None),
|
||||
(format!("{ODM_ADMIN_ROUTE}/persistence-migration"), Some(migration.to_json().to_string())),
|
||||
] {
|
||||
let (status, _) = admin_request(&env.url, Method::PUT, &path, body, &env.access_key, &env.secret_key).await?;
|
||||
if !status.is_success() {
|
||||
return Err(format!("configuring {path} failed with {status}").into());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn write_objects(client: &Client) -> Result<(), Error> {
|
||||
for key in ["put", "tagged"] {
|
||||
client
|
||||
.put_object()
|
||||
.bucket(OBJECTS)
|
||||
.key(key)
|
||||
.metadata("purpose", "byte-parity")
|
||||
.body(ByteStream::from_static(b"persisted object contents"))
|
||||
.send()
|
||||
.await?;
|
||||
}
|
||||
client
|
||||
.copy_object()
|
||||
.bucket(OBJECTS)
|
||||
.key("copy")
|
||||
.copy_source(format!("{OBJECTS}/put"))
|
||||
.send()
|
||||
.await?;
|
||||
let tags = Tagging::builder()
|
||||
.tag_set(Tag::builder().key("type").value("persisted").build()?)
|
||||
.build()?;
|
||||
client
|
||||
.put_object_tagging()
|
||||
.bucket(OBJECTS)
|
||||
.key("tagged")
|
||||
.tagging(tags)
|
||||
.send()
|
||||
.await?;
|
||||
write_multipart(client, OBJECTS, "multipart", &[vec![0x31; FIRST_PART_SIZE], vec![0x32; 100]]).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_snapshot(volume: &Path) -> Result<Snapshot, Error> {
|
||||
let b = bucket_metadata(volume, CONFIGS)?;
|
||||
let configs = BTreeMap::from([
|
||||
("acl", b.bucket_acl_config_json),
|
||||
("accelerate", b.accelerate_config_xml),
|
||||
("cors", b.cors_config_xml),
|
||||
("encryption", b.encryption_config_xml),
|
||||
("lifecycle", b.lifecycle_config_xml),
|
||||
("logging", b.logging_config_xml),
|
||||
("notification", b.notification_config_xml),
|
||||
("object_lock", b.object_lock_config_xml),
|
||||
("public_access_block", b.public_access_block_config_xml),
|
||||
("request_payment", b.request_payment_config_xml),
|
||||
("tagging", b.tagging_config_xml),
|
||||
("versioning", b.versioning_config_xml),
|
||||
("website", b.website_config_xml),
|
||||
("durability", b.durability_config_json),
|
||||
("policy", b.policy_config_json),
|
||||
("quota", b.quota_config_json),
|
||||
("replication", b.replication_config_xml),
|
||||
("targets", b.bucket_targets_config_json),
|
||||
("table", bucket_metadata(volume, "persistence-warehouse")?.table_bucket_config_json),
|
||||
("odm", bucket_metadata(volume, "persistence-migration")?.on_demand_migration_config_json),
|
||||
]);
|
||||
let mut objects = BTreeMap::new();
|
||||
for key in ["put", "copy", "tagged"] {
|
||||
let (_, fields) = read_object(volume, key)?;
|
||||
objects.insert(key, fields);
|
||||
}
|
||||
let (multipart, _) = read_object(volume, "multipart")?;
|
||||
if multipart.part_numbers != [1, 2] || multipart.part_sizes != [FIRST_PART_SIZE, 100] {
|
||||
return Err("xl.meta does not describe both uploaded parts".into());
|
||||
}
|
||||
let directory = volume
|
||||
.join(OBJECTS)
|
||||
.join("multipart")
|
||||
.join(multipart.data_dir.ok_or("missing multipart data directory")?.to_string());
|
||||
let mut multipart_files = BTreeMap::new();
|
||||
for entry in std::fs::read_dir(directory)? {
|
||||
let entry = entry?;
|
||||
let name = entry.file_name().into_string().map_err(|_| "invalid multipart file name")?;
|
||||
if name.starts_with("part.") {
|
||||
let bytes = std::fs::read(entry.path())?;
|
||||
if bytes.is_empty() {
|
||||
return Err(format!("empty multipart file {name}").into());
|
||||
}
|
||||
multipart_files.insert(name, bytes);
|
||||
}
|
||||
}
|
||||
for name in ["part.1", "part.2", "part.1.meta", "part.2.meta"] {
|
||||
if !multipart_files.contains_key(name) {
|
||||
return Err(format!("missing multipart file {name}").into());
|
||||
}
|
||||
}
|
||||
Ok(Snapshot {
|
||||
configs,
|
||||
objects,
|
||||
multipart_files,
|
||||
})
|
||||
}
|
||||
|
||||
fn save_xml_samples(root: &Path, side: &str, snapshot: &Snapshot) -> Result<(), Error> {
|
||||
let directory = root.join(side);
|
||||
std::fs::create_dir_all(&directory)?;
|
||||
let families: [&str; 13] = [
|
||||
"accelerate",
|
||||
"cors",
|
||||
"encryption",
|
||||
"lifecycle",
|
||||
"logging",
|
||||
"notification",
|
||||
"object_lock",
|
||||
"public_access_block",
|
||||
"replication",
|
||||
"request_payment",
|
||||
"tagging",
|
||||
"versioning",
|
||||
"website",
|
||||
];
|
||||
for family in families {
|
||||
let bytes = snapshot
|
||||
.configs
|
||||
.get(family)
|
||||
.ok_or_else(|| format!("missing XML family {family}"))?;
|
||||
std::fs::write(directory.join(format!("{family}.xml")), bytes)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persistence_byte_parity() -> Result<(), Error> {
|
||||
let reference = PathBuf::from(
|
||||
std::env::var_os("RUSTFS_PERSISTENCE_REFERENCE_BINARY").ok_or("missing pinned RUSTFS_PERSISTENCE_REFERENCE_BINARY")?,
|
||||
);
|
||||
let candidate = rustfs_binary_path();
|
||||
if binary_version(&reference).await? == binary_version(&candidate).await? {
|
||||
return Err("reference and candidate binaries report identical build identities".into());
|
||||
}
|
||||
// The quota writer records the process wall clock inside its JSON document. Keep raw bytes
|
||||
// comparable while the SDK's signature clock and both servers' monotonic timers advance normally.
|
||||
let clock_library = std::env::var("RUSTFS_PERSISTENCE_CLOCK_LIBRARY")?;
|
||||
if !Path::new(&clock_library).is_absolute() || !Path::new(&clock_library).is_file() {
|
||||
return Err("RUSTFS_PERSISTENCE_CLOCK_LIBRARY must name an absolute libfaketime path".into());
|
||||
}
|
||||
let clock = time::OffsetDateTime::now_utc()
|
||||
.format(time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"))?;
|
||||
let target = FakeS3Target::start().await?;
|
||||
target.create_bucket("migration-source");
|
||||
target.create_bucket_with_object_lock("interop-dr");
|
||||
let reference = capture(&reference, &target, &clock, &clock_library).await?;
|
||||
let candidate = capture(&candidate, &target, &clock, &clock_library).await?;
|
||||
if let Some(directory) = std::env::var_os("RUSTFS_PERSISTENCE_XML_DIR") {
|
||||
save_xml_samples(Path::new(&directory), "reference", &reference)?;
|
||||
save_xml_samples(Path::new(&directory), "candidate", &candidate)?;
|
||||
}
|
||||
if reference.configs.len() != 20 || candidate.configs.len() != 20 {
|
||||
return Err("expected 13 XML and seven JSON fields on each side".into());
|
||||
}
|
||||
for (&field, expected) in &reference.configs {
|
||||
// Canned ACLs acknowledge the write and return one owner grant without persisting an ACL document.
|
||||
if expected.is_empty() != (field == "acl") || candidate.configs.get(field) != Some(expected) {
|
||||
return Err(format!("incorrect or different persisted bucket config: {field}").into());
|
||||
}
|
||||
}
|
||||
for (key, expected) in &reference.objects {
|
||||
if candidate.objects.get(key) != Some(expected) {
|
||||
return Err(format!("different persisted xl.meta fields: {key}").into());
|
||||
}
|
||||
}
|
||||
if candidate.multipart_files != reference.multipart_files {
|
||||
return Err("different multipart part files or part metadata".into());
|
||||
}
|
||||
eprintln!(
|
||||
"Compared {} bucket fields (canned ACL empty), {} full object records and multipart part files",
|
||||
reference.configs.len(),
|
||||
reference.objects.len()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_comparison_preserves_unknown_fields_and_absent_values() -> Result<(), Error> {
|
||||
let mut sample = serde_json::json!({"Type": 1, "v": 1, "V2Obj": {"DDir": vec![1; 16], "MTime": 1}});
|
||||
let fields = |value: &serde_json::Value| nonvolatile_fields(&rmp_serde::to_vec(value)?, "fixture");
|
||||
let original = fields(&sample)?;
|
||||
sample["V2Obj"]["DDir"] = serde_json::json!(vec![2; 16]);
|
||||
sample["V2Obj"]["MTime"] = serde_json::json!(2);
|
||||
assert_eq!(fields(&sample)?, original);
|
||||
sample["V2Obj"]["Future"] = serde_json::Value::Null;
|
||||
let with_nil = fields(&sample)?;
|
||||
assert_ne!(with_nil, original);
|
||||
sample["V2Obj"]["Future"] = serde_json::json!(false);
|
||||
let with_value = fields(&sample)?;
|
||||
assert_ne!(with_value, with_nil);
|
||||
sample["FutureEnvelope"] = serde_json::json!(1);
|
||||
assert_ne!(fields(&sample)?, with_value);
|
||||
assert!(fields(&serde_json::json!({"V2Obj": {"MTime": 1}})).is_err());
|
||||
Ok(())
|
||||
}
|
||||
@@ -573,6 +573,15 @@ impl NodeService for MinimalLockNodeService {
|
||||
Err(Status::unimplemented("lock-only test server"))
|
||||
}
|
||||
|
||||
type RenameDataBatchStream = ResponseStream<rustfs_protos::proto_gen::node_service::RenameDataBatchResult>;
|
||||
|
||||
async fn rename_data_batch(
|
||||
&self,
|
||||
_request: Request<rustfs_protos::proto_gen::node_service::RenameDataBatchRequest>,
|
||||
) -> Result<Response<Self::RenameDataBatchStream>, Status> {
|
||||
Err(Status::unimplemented("lock-only test server"))
|
||||
}
|
||||
|
||||
async fn rename_multipart_data(
|
||||
&self,
|
||||
_request: Request<rustfs_protos::proto_gen::node_service::RenameDataRequest>,
|
||||
|
||||
@@ -465,7 +465,7 @@ pub(crate) async fn set_replication_target_with_options(
|
||||
Ok(arn)
|
||||
}
|
||||
|
||||
async fn send_set_replication_target_request(
|
||||
pub(crate) async fn send_set_replication_target_request(
|
||||
source_env: &RustFSTestEnvironment,
|
||||
source_bucket: &str,
|
||||
update: bool,
|
||||
|
||||
@@ -57,6 +57,12 @@ pub(crate) mod replication_extension {
|
||||
pub(crate) use super::BucketTargetSys;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod persistence_parity {
|
||||
pub(crate) use super::RUSTFS_META_BUCKET;
|
||||
pub(crate) use rustfs_ecstore::api::bucket::metadata::BucketMetadata;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod upgrade_compatibility {
|
||||
pub(crate) use super::{DiskOption, Endpoint, RUSTFS_META_MULTIPART_BUCKET, new_disk};
|
||||
|
||||
@@ -46,9 +46,12 @@ type BoxError = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
||||
const SOURCE_BINARY_ENV: &str = "RUSTFS_UPGRADE_SOURCE_BINARY";
|
||||
const G09_EVIDENCE_DIR_ENV: &str = "RUSTFS_SCANNER_HEAL_G09_EVIDENCE_DIR";
|
||||
const RC2_COMMIT: &str = "e9f53180273b32a9c2b0aa8b5a384047bc7e875c";
|
||||
const RC5_COMMIT: &str = "40a2470feb567201165a5b809b7598bb4b1f68f5";
|
||||
const STABLE_1_0_1_COMMIT: &str = "6de965ae3c965a78ff819fbcd7acd4aa44177d92";
|
||||
const STABLE_1_0_4_COMMIT: &str = "46337942d55f3a8e6a97b147ca98d9ea8115555d";
|
||||
const STABLE_1_0_5_COMMIT: &str = "34e6449ed90e3d3a106f6655342e0b3127f33082";
|
||||
const STABLE_1_0_6_COMMIT: &str = "de9009d882644effc2628e777650025c3d8e7c65";
|
||||
const SSE_MASTER_KEY_ENV: &str = "RUSTFS_SSE_S3_MASTER_KEY";
|
||||
const SSE_MASTER_KEY: &str = "QkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkI=";
|
||||
const PLAIN_BUCKET: &str = "upgrade-plain-data";
|
||||
@@ -142,6 +145,41 @@ fn current_source_revision() -> Result<String, BoxError> {
|
||||
Ok(revision.to_string())
|
||||
}
|
||||
|
||||
pub(crate) struct UpgradeSourceCapabilities {
|
||||
supports_delete_recovery: bool,
|
||||
supports_multipart_publication: bool,
|
||||
pub(crate) requires_list_parts_read_quorum: bool,
|
||||
}
|
||||
|
||||
impl UpgradeSourceCapabilities {
|
||||
fn from_revision(revision: &str) -> Result<Self, BoxError> {
|
||||
// 1.0.4 supports the delete decision protocol (#8468). Version 1.0.5 also
|
||||
// shipped native MPU publication (#8919) and strict ListParts evidence (#9037, #9149).
|
||||
match revision {
|
||||
RC2_COMMIT | RC5_COMMIT | STABLE_1_0_1_COMMIT => Ok(Self {
|
||||
supports_delete_recovery: false,
|
||||
supports_multipart_publication: false,
|
||||
requires_list_parts_read_quorum: false,
|
||||
}),
|
||||
STABLE_1_0_4_COMMIT => Ok(Self {
|
||||
supports_delete_recovery: true,
|
||||
supports_multipart_publication: false,
|
||||
requires_list_parts_read_quorum: false,
|
||||
}),
|
||||
STABLE_1_0_5_COMMIT | STABLE_1_0_6_COMMIT => Ok(Self {
|
||||
supports_delete_recovery: true,
|
||||
supports_multipart_publication: true,
|
||||
requires_list_parts_read_quorum: true,
|
||||
}),
|
||||
_ => Err(format!("no pinned upgrade expectations for source revision {revision}").into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn from_binary(binary: &Path) -> Result<Self, BoxError> {
|
||||
Self::from_revision(&binary_source_revision(binary).await?)
|
||||
}
|
||||
}
|
||||
|
||||
async fn binary_source_revision(binary: &Path) -> Result<String, BoxError> {
|
||||
let output = tokio::process::Command::new(binary).arg("--version").output().await?;
|
||||
if !output.status.success() {
|
||||
@@ -225,6 +263,25 @@ mod g09_evidence_tests {
|
||||
use super::*;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn pinned_upgrade_sources_keep_distinct_delete_and_list_parts_contracts() -> TestResult {
|
||||
for (revision, delete_recovery, multipart_publication, list_parts_quorum) in [
|
||||
(RC2_COMMIT, false, false, false),
|
||||
(RC5_COMMIT, false, false, false),
|
||||
(STABLE_1_0_1_COMMIT, false, false, false),
|
||||
(STABLE_1_0_4_COMMIT, true, false, false),
|
||||
(STABLE_1_0_5_COMMIT, true, true, true),
|
||||
(STABLE_1_0_6_COMMIT, true, true, true),
|
||||
] {
|
||||
let source = UpgradeSourceCapabilities::from_revision(revision)?;
|
||||
assert_eq!(source.supports_delete_recovery, delete_recovery, "{revision}");
|
||||
assert_eq!(source.supports_multipart_publication, multipart_publication, "{revision}");
|
||||
assert_eq!(source.requires_list_parts_read_quorum, list_parts_quorum, "{revision}");
|
||||
}
|
||||
assert!(UpgradeSourceCapabilities::from_revision("ffffffffffffffffffffffffffffffffffffffff").is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_revision_parser_requires_lowercase_forty_byte_sha() -> TestResult {
|
||||
let binary = Path::new("rustfs");
|
||||
@@ -365,7 +422,7 @@ async fn complete_pending_multipart(
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn write_multipart(client: &Client, bucket: &str, key: &str, parts: &[Vec<u8>]) -> TestResult {
|
||||
pub(crate) async fn write_multipart(client: &Client, bucket: &str, key: &str, parts: &[Vec<u8>]) -> TestResult {
|
||||
let pending = stage_multipart(client, bucket, key, parts).await?;
|
||||
complete_pending_multipart(client, bucket, key, &pending).await?;
|
||||
Ok(())
|
||||
@@ -1011,8 +1068,7 @@ async fn exercise_mixed_cluster(
|
||||
vec![u8::try_from(MULTIPART_WORKERS - 1)?; 64 * 1024]
|
||||
);
|
||||
|
||||
// 1.0.4 already implements the delete decision protocol. Use a separate
|
||||
// old-writer key so the original seed still spans the entire rollout.
|
||||
// Use a separate old-writer key so the original seed still spans the entire rollout.
|
||||
if previous_has_delete_recovery {
|
||||
let key = format!(".upgrade-delete/{phase}/previous-writer");
|
||||
previous_client
|
||||
@@ -1702,6 +1758,129 @@ mod upgrade_write_readiness_tests {
|
||||
}
|
||||
}
|
||||
|
||||
async fn stop_scanner_handoff_server(env: &mut RustFSTestEnvironment) -> TestResult {
|
||||
let process = env.process.as_mut().ok_or("handoff server is not running")?;
|
||||
signal_process(process.id(), "TERM")?;
|
||||
tokio::time::timeout(Duration::from_secs(90), async {
|
||||
loop {
|
||||
if let Some(status) = process.try_wait()? {
|
||||
assert!(status.success(), "handoff shutdown failed: {status}");
|
||||
return Ok::<(), BoxError>(());
|
||||
}
|
||||
sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
})
|
||||
.await??;
|
||||
env.process.take();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn scanner_handoff_identity(env: &RustFSTestEnvironment) -> Result<String, BoxError> {
|
||||
let receipt: Value = serde_json::from_slice(&std::fs::read(Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown"))?)?;
|
||||
assert_eq!(receipt["schema"], 1);
|
||||
assert_eq!(receipt["owner"], env.address);
|
||||
Ok(receipt["checkpoint_instance_id"]
|
||||
.as_str()
|
||||
.ok_or("handoff receipt omitted checkpoint identity")?
|
||||
.to_owned())
|
||||
}
|
||||
|
||||
async fn assert_scanner_handoff_consumed(marker: &Path) -> TestResult {
|
||||
let marker = tokio::fs::read_to_string(marker).await?;
|
||||
// Heal may replace the startup marker with its ordinary timestamp before
|
||||
// readiness. Neither form carries the prior checkpoint identity.
|
||||
assert!(
|
||||
marker == "running" || marker.parse::<u64>().is_ok(),
|
||||
"readiness must expose an ordinary unclean marker, never a handoff receipt"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scanner_read_only_handoff_requires_explicit_opt_in() -> TestResult {
|
||||
const HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
|
||||
assert!(std::env::var_os(HANDOFF).is_none(), "this scenario tests the unset default");
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
let marker = Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown");
|
||||
env.start_rustfs_server_without_cleanup(vec![]).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert!(!marker.exists(), "the default must not create a receipt");
|
||||
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
let previous = scanner_handoff_identity(&env)?;
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
|
||||
assert_scanner_handoff_consumed(&marker).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert_eq!(scanner_handoff_identity(&env)?, previous, "opted-in read-only boots retain identity");
|
||||
|
||||
for disabled in ["invalid", "false"] {
|
||||
let before_disabled = scanner_handoff_identity(&env)?;
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, disabled)])
|
||||
.await?;
|
||||
assert_scanner_handoff_consumed(&marker).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert!(!marker.exists(), "disabled shutdown must not recreate the receipt");
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert_ne!(scanner_handoff_identity(&env)?, before_disabled, "opt-out breaks the prior lineage");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Exercise the receipt protocol in the existing pinned-release rollback lane.
|
||||
async fn assert_scanner_handoff_prepares_legacy_rollback(previous_binary: &Path) -> TestResult {
|
||||
const HANDOFF: &str = "RUSTFS_SCANNER_READ_ONLY_HANDOFF";
|
||||
let mut env = RustFSTestEnvironment::new().await?;
|
||||
let marker = Path::new(&env.temp_dir).join(".rustfs.sys/unclean-shutdown");
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
let previous = scanner_handoff_identity(&env)?;
|
||||
|
||||
// Complete the current reader's rollback preparation before any old writer
|
||||
// opens storage, including an old writer with all background services off.
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "false")])
|
||||
.await?;
|
||||
assert_scanner_handoff_consumed(&marker).await?;
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert!(!marker.exists());
|
||||
env.start_rustfs_server_from_binary_without_cleanup(
|
||||
previous_binary,
|
||||
vec![],
|
||||
&[
|
||||
("RUSTFS_SCANNER_ENABLED", "false"),
|
||||
("RUSTFS_HEAL_ENABLED", "false"),
|
||||
("RUSTFS_HEAL_AUTO_HEAL_ENABLE", "false"),
|
||||
("RUSTFS_HEAL_MRF_ENABLE", "false"),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
let client = env.create_s3_client();
|
||||
env.create_test_bucket("handoff-rollback").await?;
|
||||
client
|
||||
.put_object()
|
||||
.bucket("handoff-rollback")
|
||||
.key("legacy-write")
|
||||
.body(ByteStream::from_static(b"legacy writer survived rollback preparation"))
|
||||
.send()
|
||||
.await?;
|
||||
env.stop_server();
|
||||
assert!(!marker.exists(), "the legacy crash cannot resurrect a consumed receipt");
|
||||
|
||||
env.start_rustfs_server_without_cleanup_with_env(&[(HANDOFF, "true")]).await?;
|
||||
assert_eq!(
|
||||
read_object(&client, "handoff-rollback", "legacy-write", None).await?.1,
|
||||
b"legacy writer survived rollback preparation"
|
||||
);
|
||||
stop_scanner_handoff_server(&mut env).await?;
|
||||
assert_ne!(
|
||||
scanner_handoff_identity(&env)?,
|
||||
previous,
|
||||
"a legacy write must not retain the old lineage"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pins the published old writer's limitation and the supported recovery
|
||||
/// procedure. This is not a promise that mixed-version ODM is supported.
|
||||
/// Replace the loss assertion when ODM gains independent persistence;
|
||||
@@ -2293,7 +2472,7 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
|
||||
let previous_binary = source_binary()?;
|
||||
// Bind the expected protocol to the verified release source, never to the
|
||||
// DELETE result itself. The older CI source pins retain their 503 contract.
|
||||
let previous_has_delete_recovery = binary_source_revision(&previous_binary).await? == STABLE_1_0_4_COMMIT;
|
||||
let source = UpgradeSourceCapabilities::from_binary(&previous_binary).await?;
|
||||
let evidence_context = g09_evidence_context(&previous_binary).await?;
|
||||
let current_binary = rustfs_binary_path();
|
||||
let mut cluster = RustFSTestClusterEnvironment::new(MIXED_NODE_COUNT).await?;
|
||||
@@ -2315,17 +2494,21 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
|
||||
cluster.stop_node(0)?;
|
||||
cluster.start_node_from_binary(0, ¤t_binary).await?;
|
||||
let mut mixed_deleted_keys = Vec::new();
|
||||
if let Some(key) = exercise_mixed_cluster(&cluster, "one-current-node", 0, 1, previous_has_delete_recovery).await? {
|
||||
if let Some(key) = exercise_mixed_cluster(&cluster, "one-current-node", 0, 1, source.supports_delete_recovery).await? {
|
||||
mixed_deleted_keys.push(key);
|
||||
}
|
||||
// One controlled out-of-policy attempt proves fail-closed behavior below
|
||||
// native write quorum; positive MPU writers remain paused while mixed.
|
||||
assert_mixed_pending_refusal(&cluster, &pending, &sources).await?;
|
||||
let mixed_completion = if source.supports_multipart_publication {
|
||||
let clients = cluster.create_all_clients()?;
|
||||
Some(finish_pending_multipart(&clients, &pending, pending_parts.concat()).await?)
|
||||
} else {
|
||||
assert_mixed_pending_refusal(&cluster, &pending, &sources).await?;
|
||||
None
|
||||
};
|
||||
|
||||
for (node_idx, phase) in [(1, "two-current-nodes"), (2, "one-previous-node")] {
|
||||
cluster.stop_node(node_idx)?;
|
||||
cluster.start_node_from_binary(node_idx, ¤t_binary).await?;
|
||||
if let Some(key) = exercise_mixed_cluster(&cluster, phase, 0, 3, previous_has_delete_recovery).await? {
|
||||
if let Some(key) = exercise_mixed_cluster(&cluster, phase, 0, 3, source.supports_delete_recovery).await? {
|
||||
mixed_deleted_keys.push(key);
|
||||
}
|
||||
}
|
||||
@@ -2335,6 +2518,13 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
|
||||
let clients = cluster.create_all_clients()?;
|
||||
wait_for_drive_readmission(&clients, MIXED_BUCKET, "homogeneous-current", DRIVE_READMISSION_TIMEOUT).await?;
|
||||
let completed_pending = finish_pending_multipart(&clients, &pending, pending_parts.concat()).await?;
|
||||
if let Some(mixed) = mixed_completion {
|
||||
assert_eq!(
|
||||
completed_pending.version_id, mixed.version_id,
|
||||
"full upgrade changed the completed version"
|
||||
);
|
||||
assert_eq!(completed_pending.etag, mixed.etag, "full upgrade changed the completed ETag");
|
||||
}
|
||||
exercise_homogeneous_multipart(&cluster, "homogeneous-current").await?;
|
||||
verify_load_bodies(&clients, "homogeneous-previous", "multipart").await?;
|
||||
assert_mixed_deletes_visible(&clients, &mixed_deleted_keys).await?;
|
||||
@@ -2451,7 +2641,7 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
|
||||
"phases": phases,
|
||||
"objects_per_phase": objects_per_phase,
|
||||
"mixed_load": "plain-put",
|
||||
"mixed_delete_protocol_supported": previous_has_delete_recovery,
|
||||
"mixed_delete_protocol_supported": source.supports_delete_recovery,
|
||||
"mixed_deleted_keys": mixed_deleted_keys,
|
||||
"homogeneous_multipart_phases": ["homogeneous-previous", "homogeneous-current", "homogeneous-rollback"],
|
||||
"multipart_objects_per_homogeneous_phase": MULTIPART_WORKERS * MULTIPART_UPLOADS_PER_WORKER,
|
||||
@@ -2461,7 +2651,7 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
|
||||
"all nodes list every mixed-version object after homogeneous-current convergence",
|
||||
"the previous-release seed survives the baseline restart and every upgrade phase",
|
||||
"previous readers read every current-native MPU body after quiescent rollback",
|
||||
"same legacy upload resumes with identical body, ETag and version after full upgrade"
|
||||
"the same previous-release upload remains readable after full upgrade and rollback"
|
||||
],
|
||||
}),
|
||||
)?;
|
||||
@@ -2483,9 +2673,13 @@ async fn rolling_upgrade_from_previous_release_preserves_mixed_version_contracts
|
||||
"previous-release writer publishes objects readable by current node",
|
||||
"mixed phases retain 16x16 plain PUT writers while positive multipart writers are paused",
|
||||
"16x16 multipart load runs in homogeneous previous, current and rollback phases",
|
||||
"one-current-node Complete returns typed 503 and preserves actual source authority and parts",
|
||||
"the same legacy upload completes and replays once fully upgraded without adding a version",
|
||||
if previous_has_delete_recovery {
|
||||
if source.supports_multipart_publication {
|
||||
"one-current-node Complete and replay return the same version and ETag, and all readers agree on the body"
|
||||
} else {
|
||||
"one-current-node Complete returns typed 503 and preserves actual source authority and parts"
|
||||
},
|
||||
"fully upgraded readers see the same body, ETag and sole version after replay",
|
||||
if source.supports_delete_recovery {
|
||||
"mixed-version DELETE succeeds and stays absent through every reader after upgrade and rollback"
|
||||
} else {
|
||||
"modern DELETE fails closed and preserves every byte while old peers remain"
|
||||
@@ -2832,7 +3026,7 @@ async fn restart_from_binary(env: &mut RustFSTestEnvironment, binary: &Path, ser
|
||||
env.start_rustfs_server_from_binary(binary, vec![], server_env).await
|
||||
}
|
||||
|
||||
async fn set_bucket_quota(env: &RustFSTestEnvironment, bucket: &str, quota_bytes: u64) -> TestResult {
|
||||
pub(crate) async fn set_bucket_quota(env: &RustFSTestEnvironment, bucket: &str, quota_bytes: u64) -> TestResult {
|
||||
let path = format!("/rustfs/admin/v3/quota/{bucket}");
|
||||
let body = serde_json::json!({ "quota": quota_bytes, "quota_type": "HARD" }).to_string();
|
||||
let deadline = Instant::now() + QUOTA_READINESS_TIMEOUT;
|
||||
@@ -3386,9 +3580,12 @@ async fn direct_upgrade_from_previous_release_preserves_bucket_configuration() -
|
||||
#[tokio::test]
|
||||
#[ignore = "requires a pinned previous RustFS release binary"]
|
||||
async fn rollback_to_previous_release_reads_current_bucket_metadata() -> TestResult {
|
||||
use sha2::Digest;
|
||||
|
||||
init_logging();
|
||||
let previous_binary = source_binary()?;
|
||||
let evidence_context = g09_evidence_context(&previous_binary).await?;
|
||||
assert_scanner_handoff_prepares_legacy_rollback(&previous_binary).await?;
|
||||
|
||||
let replication_target = FakeS3Target::start().await?;
|
||||
replication_target.create_bucket(ROLLBACK_REPLICA_BUCKET);
|
||||
@@ -3423,6 +3620,16 @@ async fn rollback_to_previous_release_reads_current_bucket_metadata() -> TestRes
|
||||
let multipart_bytes = multipart_parts.concat();
|
||||
write_multipart(&new_client, ROLLBACK_BUCKET, multipart_key, &multipart_parts).await?;
|
||||
|
||||
// This release can finish an upload staged by the current gateway.
|
||||
let inflight = if binary_source_revision(&previous_binary).await? == STABLE_1_0_5_COMMIT {
|
||||
env.create_test_bucket(PENDING_MULTIPART_BUCKET).await?;
|
||||
let parts = [vec![1; LAYOUT_PART_SIZE], vec![2; LAYOUT_PART_SIZE], vec![3; 4096]];
|
||||
let pending = stage_multipart(&new_client, PENDING_MULTIPART_BUCKET, PENDING_MULTIPART_KEY, &parts).await?;
|
||||
Some((pending, parts.concat()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
restart_from_binary(&mut env, &previous_binary, &server_env).await?;
|
||||
let old_client = env.create_s3_client();
|
||||
|
||||
@@ -3438,6 +3645,16 @@ async fn rollback_to_previous_release_reads_current_bucket_metadata() -> TestRes
|
||||
assert_eq!(encryption, Some(ServerSideEncryption::Aes256));
|
||||
assert_eq!(body, multipart_bytes, "the multipart object did not survive the rollback");
|
||||
|
||||
let rollback_multipart = if let Some((pending, expected)) = inflight {
|
||||
assert_pending_parts(&old_client, &pending).await?;
|
||||
complete_pending_multipart(&old_client, PENDING_MULTIPART_BUCKET, PENDING_MULTIPART_KEY, &pending).await?;
|
||||
let (_, body) = read_object(&old_client, PENDING_MULTIPART_BUCKET, PENDING_MULTIPART_KEY, None).await?;
|
||||
assert_eq!(body, expected);
|
||||
Some((pending.part_sizes, body))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// A PUT on the rolled-back release must still honour the encryption
|
||||
// configuration it decoded out of the current build's metadata blob.
|
||||
let post_rollback_key = "rollback/written-after-rollback";
|
||||
@@ -3478,6 +3695,25 @@ async fn rollback_to_previous_release_reads_current_bucket_metadata() -> TestRes
|
||||
post_rollback_bytes
|
||||
);
|
||||
|
||||
if let Some((part_sizes, rollback_read)) = rollback_multipart {
|
||||
let (_, current_read) = read_object(¤t_again, PENDING_MULTIPART_BUCKET, PENDING_MULTIPART_KEY, None).await?;
|
||||
assert_eq!(current_read, rollback_read);
|
||||
if let Some(context) = &evidence_context {
|
||||
let evidence = serde_json::json!({
|
||||
"previous_revision": context.previous_revision,
|
||||
"current_revision": context.current_revision,
|
||||
"part_sizes": part_sizes,
|
||||
"bytes": current_read.len(),
|
||||
"rollback_read_sha256": hex_simd::encode_to_string(sha2::Sha256::digest(&rollback_read), hex_simd::AsciiCase::Lower),
|
||||
"roll_forward_read_sha256": hex_simd::encode_to_string(sha2::Sha256::digest(¤t_read), hex_simd::AsciiCase::Lower),
|
||||
});
|
||||
std::fs::write(
|
||||
context.directory.join("inflight-multipart-rollback.json"),
|
||||
serde_json::to_vec_pretty(&evidence)?,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(context) = evidence_context.as_ref() {
|
||||
write_g09_evidence(
|
||||
context,
|
||||
|
||||
@@ -154,7 +154,6 @@ arc-swap.workspace = true
|
||||
async-trait.workspace = true
|
||||
bytes = { workspace = true, features = ["serde"] }
|
||||
byteorder = { workspace = true }
|
||||
chrono = { workspace = true, features = ["serde"] }
|
||||
jiff = { workspace = true, features = ["serde"] }
|
||||
thiserror.workspace = true
|
||||
flatbuffers.workspace = true
|
||||
@@ -184,7 +183,6 @@ rmp.workspace = true
|
||||
rmp-serde.workspace = true
|
||||
tokio-util = { workspace = true, features = ["io", "compat", "rt"] }
|
||||
tokio-stream = { workspace = true, features = ["sync"] }
|
||||
hmac = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
hex-simd = { workspace = true }
|
||||
tempfile.workspace = true
|
||||
@@ -259,7 +257,6 @@ windows-sys = { workspace = true, features = [
|
||||
windows-sys = { workspace = true, features = ["Win32_System_Ioctl"] }
|
||||
|
||||
[dev-dependencies]
|
||||
s3s = { workspace = true, features = ["minio"] }
|
||||
aws-smithy-async.workspace = true
|
||||
rustfs-s3-ops.workspace = true
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "test-util", "fs"] }
|
||||
|
||||
@@ -503,7 +503,7 @@ pub mod disk {
|
||||
PoolMetaNativeInspection, PoolMetaNativeObject, PoolMetaNativeRecoveryRequest, PoolMetaNativeRecoveryResponse,
|
||||
QUOTA_MUTATION_FENCE_METADATA_SUFFIX, RUSTFS_META_BUCKET, RUSTFS_META_MULTIPART_BUCKET, RUSTFS_META_TMP_BUCKET,
|
||||
ReadMultipleReq, ReadMultipleResp, ReadOptions, RenameDataResp, STORAGE_FORMAT_FILE, SnapshotLeaseToken,
|
||||
UpdateMetadataOpts, VolumeInfo, WalkDirOptions, is_quota_mutation_fence_path, new_disk,
|
||||
UNCLEAN_SHUTDOWN_MARKER_PATH, UpdateMetadataOpts, VolumeInfo, WalkDirOptions, is_quota_mutation_fence_path, new_disk,
|
||||
validate_batch_read_version_item_count, validate_format_control_path,
|
||||
};
|
||||
pub use crate::disk::{
|
||||
@@ -615,15 +615,21 @@ pub mod object {
|
||||
};
|
||||
pub use crate::erasure::codec::shard_emit::ShardEmitter;
|
||||
pub use crate::object_api::{
|
||||
BLOCK_SIZE_V2, ERASURE_ALGORITHM, EncryptionResolutionError, EncryptionResolutionErrorKind, GetObjectBodyCacheHook,
|
||||
GetObjectBodyCacheHookLookup, GetObjectBodySource, GetObjectReadCondition, GetObjectReadMetadata, GetObjectReader,
|
||||
GetObjectSink, GetObjectSinkSegmentFactory, GetObjectSinkSegments, GetObjectSinkStream, GetObjectSinkWriter,
|
||||
NamespaceLockFence, ObjectEncryptionResolver, ObjectInfo, ObjectLockConfigSnapshot, ObjectMutationHook, ObjectOptions,
|
||||
PutObjReader, QuotaAdmission, RangedDecompressReader, ReadEncryptionMaterial, ReadEncryptionMode, ReadEncryptionRequest,
|
||||
BLOCK_SIZE_V2, ClientEcBlockSizeHint, DEFAULT_EC_BLOCK_SIZE, EC_BLOCK_SIZE_CANDIDATES, EC_BLOCK_SIZE_HINT_INTERNAL_KEY,
|
||||
EC_BLOCK_SIZE_HINT_INTERNAL_SUFFIX, EC_BLOCK_SIZE_HINT_METADATA_KEY, EC_BLOCK_SIZE_HINT_REASON_HEADER,
|
||||
EC_BLOCK_SIZE_HINT_STATUS_HEADER, EC_BLOCK_SIZE_INFO_INTERNAL_KEY, EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX,
|
||||
EC_BLOCK_SIZE_RESPONSE_HEADER, EC_READ_QUANTUM_INFO_INTERNAL_KEY, EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX,
|
||||
ERASURE_ALGORITHM, EcBlockSizeHintError, EcBlockSizeHintIgnoreReason, EcBlockSizeHintOutcome, EncryptionResolutionError,
|
||||
EncryptionResolutionErrorKind, GetObjectBodyCacheHook, GetObjectBodyCacheHookLookup, GetObjectBodySource,
|
||||
GetObjectReadCondition, GetObjectReadMetadata, GetObjectReader, GetObjectSink, GetObjectSinkSegmentFactory,
|
||||
GetObjectSinkSegments, GetObjectSinkStream, GetObjectSinkWriter, NamespaceLockFence, ObjectEncryptionResolver,
|
||||
ObjectInfo, ObjectLockConfigSnapshot, ObjectMutationHook, ObjectOptions, PutObjReader, QuotaAdmission,
|
||||
RangedDecompressReader, ReadEncryptionMaterial, ReadEncryptionMode, ReadEncryptionRequest, ResolvedEcBlockSize,
|
||||
SCANNER_PUBLICATION_LEASE_FENCE_METADATA_KEY, ScannerPublicationCommitScope, ScannerPublicationCommitStartError,
|
||||
ScannerPublicationCommitState, ShardIntegrityWriteMode, StreamConsumer, WriteCommitGuard, WriteCompletion,
|
||||
get_object_body_cache_plaintext_len, lookup_get_object_body_cache_hook, register_get_object_body_cache_hook,
|
||||
register_object_mutation_hook, unregister_get_object_body_cache_hook, unregister_object_mutation_hook,
|
||||
get_object_body_cache_plaintext_len, is_supported_ec_block_size, lookup_get_object_body_cache_hook,
|
||||
parse_ec_block_size_hint, register_get_object_body_cache_hook, register_object_mutation_hook, resolve_ec_block_size_hint,
|
||||
take_ec_block_size_hint, unregister_get_object_body_cache_hook, unregister_object_mutation_hook,
|
||||
with_get_object_read_condition,
|
||||
};
|
||||
pub use crate::store::{
|
||||
@@ -763,8 +769,8 @@ pub mod storage {
|
||||
pub use crate::store::external_rpc_disk;
|
||||
pub use crate::store::{
|
||||
BootstrapLocalTarget, ECStore, SCANNER_PUBLICATION_LEASE_TTL_MS, ScannerDataMovementPauseStatus, all_local_disk,
|
||||
all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, init_local_disks,
|
||||
init_local_disks_with_instance_ctx, init_lock_clients, prewarm_local_disk_id_map,
|
||||
all_local_disk_path, find_local_disk_by_ref, find_local_disk_by_ref_for_rpc, find_local_disk_by_ref_for_scanner_rpc,
|
||||
init_local_disks, init_local_disks_with_instance_ctx, init_lock_clients, prewarm_local_disk_id_map,
|
||||
prewarm_local_disk_id_map_with_instance_ctx,
|
||||
};
|
||||
pub use crate::store::{HealObjectAbsenceProof, HealObjectStorageResult};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1405,7 +1405,7 @@ impl BucketMetadata {
|
||||
/// | public access block | Fails closed in `get_public_access_block_config`: degrading grants the anonymous access the operator asked to block. |
|
||||
/// | quota | Fails closed in `get_quota_config`; the enforcement path in `quota::checker` already re-parses the raw JSON and refuses on error. |
|
||||
/// | lifecycle | `get_lifecycle_config` fails closed, so GetBucketLifecycle reports the fault instead of NoSuchLifecycleConfiguration. ILM, scanner and expiry-header consumers still degrade to "no rules": nothing is deleted or moved on the strength of an unreadable rule set, and the bucket keeps serving reads and writes. |
|
||||
/// | notification | `get_notification_config` fails closed, so GetBucketNotificationConfiguration reports the fault and startup leaves that one bucket's rules unchanged instead of clearing them; other buckets are unaffected. |
|
||||
/// | notification | `get_notification_config` fails closed, so GetBucketNotificationConfiguration reports the fault and startup skips that bucket's rule registration; metadata-bound server dispatch suppresses external delivery for the unreadable snapshot. Other buckets are unaffected. |
|
||||
/// | tagging, CORS, logging, website, accelerate, request payment | The getter fails closed so the matching GET API reports the fault instead of "not configured". Per-request consumers (CORS response headers) still degrade to "not configured", which is the restrictive direction. |
|
||||
/// | bucket ACL | Safe to degrade: it only shapes an optional response. |
|
||||
///
|
||||
|
||||
@@ -2612,6 +2612,10 @@ impl BucketMetadataSys {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn cached_metadata(&self) -> Vec<Arc<BucketMetadata>> {
|
||||
self.metadata_map.read().await.values().cloned().collect()
|
||||
}
|
||||
|
||||
pub async fn set(&self, bucket: String, bm: Arc<BucketMetadata>) {
|
||||
self.revoke_pending_bucket_creation(&bucket).await;
|
||||
bump_local_meta_mutation_gen();
|
||||
@@ -5760,6 +5764,64 @@ mod tests {
|
||||
assert_eq!(tags.tag_set.len(), WRITERS, "every concurrent rewrite must survive: {tags:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notification_snapshots_follow_periodic_refresh_after_lost_peer_signals() {
|
||||
let (dirs, store) = isolated_store_over_temp_disks().await;
|
||||
let writer = BucketMetadataSys::new(store.clone());
|
||||
let peer = Arc::new(RwLock::new(BucketMetadataSys::new(store.clone())));
|
||||
let bucket = "notification-periodic-snapshots";
|
||||
for dir in &dirs {
|
||||
std::fs::create_dir_all(dir.path().join(bucket)).expect("create empty fixture bucket");
|
||||
}
|
||||
let mut original = BucketMetadata::new(bucket);
|
||||
original.notification_config_xml = concat!(
|
||||
"<NotificationConfiguration><QueueConfiguration><Event>s3:ObjectCreated:Put</Event>",
|
||||
"<Queue>arn:rustfs:sqs:us-east-1:inert:webhook</Queue></QueueConfiguration></NotificationConfiguration>"
|
||||
)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
original.parse_all_configs().expect("parse inert subscription");
|
||||
writer
|
||||
.persist_new_and_set(original)
|
||||
.await
|
||||
.expect("persist initial subscription");
|
||||
peer.read().await.reload_from_store(bucket).await.expect("prime peer cache");
|
||||
let old = peer.read().await.get(bucket).await.expect("cached original snapshot");
|
||||
|
||||
let mut removed = (*old).clone();
|
||||
removed.notification_config_xml = b"<NotificationConfiguration/>".to_vec();
|
||||
removed.parse_all_configs().expect("parse removed subscription");
|
||||
writer
|
||||
.persist_new_and_set(removed)
|
||||
.await
|
||||
.expect("persist removal without peer callback");
|
||||
assert!(Arc::ptr_eq(&old, &peer.read().await.get(bucket).await.expect("peer remains stale")));
|
||||
|
||||
// Exercise the timer's actual one-pass entry point, not the peer RPC.
|
||||
refresh_buckets_metadata_once(peer.clone()).await;
|
||||
let snapshots = peer.read().await.cached_metadata().await;
|
||||
assert_eq!(snapshots.len(), 1);
|
||||
assert!(!Arc::ptr_eq(&old, &snapshots[0]));
|
||||
assert_eq!(old.bucket_incarnation_id, snapshots[0].bucket_incarnation_id);
|
||||
assert_eq!(snapshots[0].notification_config_xml, b"<NotificationConfiguration/>");
|
||||
assert!(
|
||||
snapshots[0]
|
||||
.notification_config
|
||||
.as_ref()
|
||||
.expect("parsed removal")
|
||||
.behavior()
|
||||
.queue_routes
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
for dir in &dirs {
|
||||
std::fs::remove_dir(dir.path().join(bucket)).expect("remove empty fixture bucket without peer callback");
|
||||
}
|
||||
refresh_buckets_metadata_once(peer.clone()).await;
|
||||
assert!(peer.read().await.cached_metadata().await.is_empty());
|
||||
assert!(peer.read().await.get(bucket).await.is_err());
|
||||
}
|
||||
|
||||
/// Pins the peer reload-notification contract (`reload_from_store`, the
|
||||
/// LoadBucketMetadata RPC path): only metadata actually read from
|
||||
/// persisted storage enters the cache. A load miss errors out and leaves
|
||||
|
||||
@@ -1070,8 +1070,9 @@ mod tests {
|
||||
.unwrap_or_else(|| panic!("signed request must contain {name}"))
|
||||
}
|
||||
|
||||
fn signing_time(headers: &[(String, String)]) -> chrono::NaiveDateTime {
|
||||
chrono::NaiveDateTime::parse_from_str(recorded_header(headers, "x-amz-date"), "%Y%m%dT%H%M%SZ")
|
||||
fn signing_time(headers: &[(String, String)]) -> jiff::Timestamp {
|
||||
let value = recorded_header(headers, "x-amz-date").trim_end_matches('Z');
|
||||
jiff::Timestamp::strptime("%Y%m%dT%H%M%S%z", format!("{value}+0000"))
|
||||
.expect("SDK signing timestamp must use the SigV4 format")
|
||||
}
|
||||
|
||||
@@ -1086,8 +1087,8 @@ mod tests {
|
||||
.map(|(key, value)| (key.to_string(), value.to_string()))
|
||||
.collect(),
|
||||
);
|
||||
let server_time = chrono::DateTime::<chrono::Utc>::from(self.clock.now()).naive_utc()
|
||||
+ chrono::Duration::seconds(self.skew_seconds);
|
||||
let server_time = jiff::Timestamp::try_from(self.clock.now()).expect("clock timestamp")
|
||||
+ jiff::SignedDuration::from_secs(self.skew_seconds);
|
||||
let (status, body) = if headers.len() == 1 {
|
||||
(
|
||||
403,
|
||||
@@ -1098,7 +1099,7 @@ mod tests {
|
||||
};
|
||||
let response = http::Response::builder()
|
||||
.status(status)
|
||||
.header("date", server_time.format("%a, %d %b %Y %H:%M:%S GMT").to_string())
|
||||
.header("date", server_time.strftime("%a, %d %b %Y %H:%M:%S GMT").to_string())
|
||||
.header("content-type", "application/xml")
|
||||
.header("content-length", body.len())
|
||||
.body(SdkBody::from(body))
|
||||
@@ -1136,7 +1137,7 @@ mod tests {
|
||||
for error_code in ["RequestTimeTooSkewed", "SignatureDoesNotMatch"] {
|
||||
for skew_seconds in [-600, 600] {
|
||||
let (client, headers, clock) = clock_skew_client(error_code, skew_seconds, REPLICATION_TARGET_RETRY_POLICY).await;
|
||||
let initial = chrono::DateTime::<chrono::Utc>::from(clock.now()).naive_utc();
|
||||
let initial = jiff::Timestamp::try_from(clock.now()).expect("clock timestamp");
|
||||
client
|
||||
.get_object()
|
||||
.bucket("bucket")
|
||||
@@ -1163,12 +1164,12 @@ mod tests {
|
||||
assert_eq!(signing_time(&headers[0]), initial, "the first attempt must use the injected clock");
|
||||
assert_eq!(
|
||||
signing_time(&headers[1]),
|
||||
initial + chrono::Duration::seconds(skew_seconds),
|
||||
initial + jiff::SignedDuration::from_secs(skew_seconds),
|
||||
"{error_code}: retry must apply the measured offset exactly"
|
||||
);
|
||||
assert_eq!(
|
||||
signing_time(&headers[2]),
|
||||
initial + chrono::Duration::seconds(skew_seconds + 17),
|
||||
initial + jiff::SignedDuration::from_secs(skew_seconds + 17),
|
||||
"{error_code}: the next operation must apply cached skew to the advanced signing clock"
|
||||
);
|
||||
let signature = |index: usize| {
|
||||
|
||||
@@ -251,10 +251,10 @@ const METRIC_VERSION_IDENTITY_DRIFT_TOTAL: &str = "rustfs_replication_version_id
|
||||
/// the condition discoverable in any recent window.
|
||||
const VERSION_IDENTITY_DRIFT_LOG_INTERVAL: TokioDuration = TokioDuration::from_secs(600);
|
||||
|
||||
/// When each target last reported version-identity drift, by ARN. Throttling is
|
||||
/// When each source bucket and ARN last reported version-identity drift. Throttling is
|
||||
/// advisory only — the metric still counts every drifting PUT.
|
||||
static VERSION_IDENTITY_WARNED_ARNS: LazyLock<StdMutex<HashMap<String, Instant>>> =
|
||||
LazyLock::new(|| StdMutex::new(HashMap::new()));
|
||||
type SourceTargetDriftTimes = HashMap<String, HashMap<String, Instant>>;
|
||||
static VERSION_IDENTITY_WARNED_ARNS: LazyLock<StdMutex<SourceTargetDriftTimes>> = LazyLock::new(|| StdMutex::new(HashMap::new()));
|
||||
|
||||
/// Version purges a target refused for a reason a retry cannot change on its
|
||||
/// own. Two shapes today:
|
||||
@@ -395,13 +395,13 @@ fn audit_target_version_identity(tgt_client: &TargetClient, source_version_id: &
|
||||
// below (`replica_head_fallback`) knows whether a 404 on a
|
||||
// version-addressed HEAD can mean "replica missing" on this target.
|
||||
if let Some(capability) = version_identity_capability_from_put(source_version_id, assigned_version_id) {
|
||||
ReplicationTargetStore::record_version_identity_capability(&tgt_client.arn, capability);
|
||||
tgt_client.record_version_identity_capability(capability);
|
||||
}
|
||||
if !version_identity_drifted(source_version_id, assigned_version_id) {
|
||||
return;
|
||||
}
|
||||
counter!(METRIC_VERSION_IDENTITY_DRIFT_TOTAL).increment(1);
|
||||
if !version_identity_drift_log_due(&tgt_client.arn, Instant::now()) {
|
||||
if !version_identity_drift_log_due(&tgt_client.source_bucket, &tgt_client.arn, Instant::now()) {
|
||||
return;
|
||||
}
|
||||
// `error`, not `warn`: the target silently refuses the addressing scheme
|
||||
@@ -424,14 +424,14 @@ fn audit_target_version_identity(tgt_client: &TargetClient, source_version_id: &
|
||||
/// Whether this ARN's version-identity drift is due to be logged again at
|
||||
/// `now`, re-arming the throttle when it is. Split out from the audit so the
|
||||
/// interval policy is testable without a target client.
|
||||
fn version_identity_drift_log_due(arn: &str, now: Instant) -> bool {
|
||||
fn version_identity_drift_log_due(bucket: &str, arn: &str, now: Instant) -> bool {
|
||||
let mut warned = VERSION_IDENTITY_WARNED_ARNS
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
match warned.get(arn) {
|
||||
match warned.get(bucket).and_then(|entries| entries.get(arn)) {
|
||||
Some(last) if now.duration_since(*last) < VERSION_IDENTITY_DRIFT_LOG_INTERVAL => false,
|
||||
_ => {
|
||||
warned.insert(arn.to_string(), now);
|
||||
warned.entry(bucket.to_owned()).or_default().insert(arn.to_owned(), now);
|
||||
true
|
||||
}
|
||||
}
|
||||
@@ -697,7 +697,7 @@ async fn replica_head_fallback(
|
||||
if let Some(ledger_version_id) = ledger_version_id {
|
||||
// A ledger entry is direct evidence of the identity contract; it
|
||||
// survives a restart while the runtime verdict cache does not.
|
||||
ReplicationTargetStore::record_version_identity_capability(&tgt_client.arn, VersionIdentityCapability::MintsOwn);
|
||||
tgt_client.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
match head_object_for_worker(tgt_client, &tgt_client.bucket, object, Some(ledger_version_id.to_string())).await {
|
||||
Ok(head) => {
|
||||
return Some(Ok(Some(LocatedReplica {
|
||||
@@ -717,7 +717,7 @@ async fn replica_head_fallback(
|
||||
if !(encrypted && content_identity.is_some()) {
|
||||
return Some(head_object_fallback(tgt_client, object).await);
|
||||
}
|
||||
} else if !ReplicationTargetStore::version_identity_capability(&tgt_client.arn).version_addressing_unreliable() {
|
||||
} else if !tgt_client.version_identity_capability().version_addressing_unreliable() {
|
||||
return None;
|
||||
}
|
||||
let siblings = content_identity?;
|
||||
@@ -989,14 +989,14 @@ async fn sync_drifted_replica_metadata(
|
||||
/// (no PUT is ever sent — the object stays on the normal MRF retry channel
|
||||
/// and re-audits once the verdict's TTL expires or replication-check
|
||||
/// re-probes the target) and returns `None`.
|
||||
async fn resolve_ssec_passthrough_gate(
|
||||
fn resolve_ssec_passthrough_gate(
|
||||
ssec: bool,
|
||||
tgt_client: &TargetClient,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
rinfo: &mut ReplicatedTargetInfo,
|
||||
) -> Option<bool> {
|
||||
let (capability, expired) = ReplicationTargetStore::ssec_passthrough_capability(&tgt_client.arn).await;
|
||||
let (capability, expired) = tgt_client.ssec_passthrough_capability();
|
||||
match ssec_passthrough_gate(ssec, capability, expired) {
|
||||
SsecPassthroughGate::Proceed => Some(false),
|
||||
SsecPassthroughGate::ProceedWithAudit => Some(true),
|
||||
@@ -1023,7 +1023,7 @@ async fn resolve_ssec_passthrough_gate(
|
||||
/// capability verdict for the target. Returns true when the SSE-C material
|
||||
/// provably survived; otherwise records `Unsupported` and settles `rinfo` as
|
||||
/// FAILED so the attempt never reports a silently unreadable COMPLETED.
|
||||
async fn settle_ssec_passthrough_evidence(
|
||||
fn settle_ssec_passthrough_evidence(
|
||||
head: &HeadObjectOutput,
|
||||
tgt_client: &TargetClient,
|
||||
bucket: &str,
|
||||
@@ -1031,10 +1031,10 @@ async fn settle_ssec_passthrough_evidence(
|
||||
rinfo: &mut ReplicatedTargetInfo,
|
||||
) -> bool {
|
||||
if ssec_passthrough_evidence_present(head) {
|
||||
ReplicationTargetStore::record_ssec_passthrough_capability(&tgt_client.arn, SsecPassthroughCapability::Supported).await;
|
||||
tgt_client.record_ssec_passthrough_capability(SsecPassthroughCapability::Supported);
|
||||
return true;
|
||||
}
|
||||
ReplicationTargetStore::record_ssec_passthrough_capability(&tgt_client.arn, SsecPassthroughCapability::Unsupported).await;
|
||||
tgt_client.record_ssec_passthrough_capability(SsecPassthroughCapability::Unsupported);
|
||||
rinfo.replication_status = ReplicationStatusType::Failed;
|
||||
rinfo.error = Some(ERR_REPLICATION_SSEC_PASSTHROUGH_UNSUPPORTED.to_string());
|
||||
warn!(
|
||||
@@ -1070,7 +1070,7 @@ async fn audit_ssec_passthrough_replica(
|
||||
// version, so the audit HEAD does not 4xx-loop on those objects.
|
||||
let version_id = resolve_read_api_version_id(version_id);
|
||||
match head_object_for_worker(tgt_client.as_ref(), &tgt_client.bucket, object, version_id).await {
|
||||
Ok(head) => settle_ssec_passthrough_evidence(&head, tgt_client, bucket, object, rinfo).await,
|
||||
Ok(head) => settle_ssec_passthrough_evidence(&head, tgt_client, bucket, object, rinfo),
|
||||
Err(e) => {
|
||||
rinfo.replication_status = ReplicationStatusType::Failed;
|
||||
rinfo.error = Some(format!("SSE-C passthrough audit HEAD failed: {e}"));
|
||||
@@ -1967,8 +1967,7 @@ async fn verify_resync_head_result(
|
||||
// source marker id; verify the marker on the latest version.
|
||||
DeleteMarkerHeadOutcome::Ambiguous => {
|
||||
let mints_own = rejects_source_version_id(&err)
|
||||
|| ReplicationTargetStore::version_identity_capability(&target_client.arn)
|
||||
.version_addressing_unreliable();
|
||||
|| target_client.version_identity_capability().version_addressing_unreliable();
|
||||
!(mints_own && latest_target_version_is_delete_marker(target_client, &roi.name).await)
|
||||
}
|
||||
DeleteMarkerHeadOutcome::Exists | DeleteMarkerHeadOutcome::Missing => false,
|
||||
@@ -3665,10 +3664,10 @@ async fn resolve_purge_replica(
|
||||
return PurgeReplicaResolution::LedgerCorrupt;
|
||||
}
|
||||
if let Some(assigned) = source.ledger.get(&tgt_client.arn) {
|
||||
ReplicationTargetStore::record_version_identity_capability(&tgt_client.arn, VersionIdentityCapability::MintsOwn);
|
||||
tgt_client.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
return PurgeReplicaResolution::Resolved(assigned.clone());
|
||||
}
|
||||
if !force_lookup && !ReplicationTargetStore::version_identity_capability(&tgt_client.arn).version_addressing_unreliable() {
|
||||
if !force_lookup && !tgt_client.version_identity_capability().version_addressing_unreliable() {
|
||||
return PurgeReplicaResolution::SourceVersion;
|
||||
}
|
||||
let etag = source.etag.as_deref().filter(|etag| !etag.trim().is_empty());
|
||||
@@ -3828,8 +3827,7 @@ async fn replicate_delete_to_target(
|
||||
// A target that mints its own version ids never holds the source marker
|
||||
// id, so a version-addressed pre-check cannot succeed there; the marker
|
||||
// is created by the versionless DELETE below.
|
||||
let version_addressable =
|
||||
!ReplicationTargetStore::version_identity_capability(&tgt_client.arn).version_addressing_unreliable();
|
||||
let version_addressable = !tgt_client.version_identity_capability().version_addressing_unreliable();
|
||||
if version_addressable
|
||||
&& !is_version_purge
|
||||
&& dobj.delete_object.delete_marker
|
||||
@@ -3846,7 +3844,7 @@ async fn replicate_delete_to_target(
|
||||
// The verdict is not known yet (e.g. no PUT since restart) and the
|
||||
// target rejected the source id: learn it as the PUT path does.
|
||||
Err(e) if rejects_source_version_id(e.as_ref()) => {
|
||||
ReplicationTargetStore::record_version_identity_capability(&tgt_client.arn, VersionIdentityCapability::MintsOwn);
|
||||
tgt_client.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
}
|
||||
Ok(head) if head.delete_marker == Some(true) => {
|
||||
// Some targets expose an existing marker as a successful HEAD
|
||||
@@ -3922,7 +3920,7 @@ async fn replicate_delete_to_target(
|
||||
let object = &dobj.delete_object.object_name;
|
||||
match resolve_purge_replica(&tgt_client, object, source, true).await {
|
||||
PurgeReplicaResolution::Resolved(assigned) => {
|
||||
ReplicationTargetStore::record_version_identity_capability(&tgt_client.arn, VersionIdentityCapability::MintsOwn);
|
||||
tgt_client.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
counter!(METRIC_VERSION_PURGE_REPLICA_TOTAL, "resolution" => "resolved").increment(1);
|
||||
version_id = Some(assigned);
|
||||
removed = tgt_client
|
||||
@@ -4626,7 +4624,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
|
||||
// N2 fail-closed: never PUT SSE-C ciphertext at a target known to drop
|
||||
// the passthrough transport headers, and never trust a convergence HEAD
|
||||
// against such a target — a previous broken replica matches by ETag.
|
||||
let Some(ssec_audit_required) = resolve_ssec_passthrough_gate(self.ssec, &tgt_client, &bucket, &object, &mut rinfo).await
|
||||
let Some(ssec_audit_required) = resolve_ssec_passthrough_gate(self.ssec, &tgt_client, &bucket, &object, &mut rinfo)
|
||||
else {
|
||||
send_local_event(EventArgs {
|
||||
event_name: EventName::ObjectReplicationNotTracked.to_string(),
|
||||
@@ -4747,9 +4745,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
|
||||
// An SSE-C replica only counts as converged when the same
|
||||
// HEAD proves its decryption material survived; a broken
|
||||
// ciphertext copy from an earlier attempt matches by ETag.
|
||||
if ssec_audit_required
|
||||
&& !settle_ssec_passthrough_evidence(&oi, &tgt_client, &bucket, &object, &mut rinfo).await
|
||||
{
|
||||
if ssec_audit_required && !settle_ssec_passthrough_evidence(&oi, &tgt_client, &bucket, &object, &mut rinfo) {
|
||||
return rinfo;
|
||||
}
|
||||
rinfo.replication_status = ReplicationStatusType::Completed;
|
||||
@@ -4784,7 +4780,6 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
|
||||
Ok(Some(located)) if located_replica_matches(identity.as_ref(), &located) => {
|
||||
if ssec_audit_required
|
||||
&& !settle_ssec_passthrough_evidence(&located.head, &tgt_client, &bucket, &object, &mut rinfo)
|
||||
.await
|
||||
{
|
||||
return rinfo;
|
||||
}
|
||||
@@ -4984,7 +4979,7 @@ impl ReplicateObjectInfoExt for ReplicateObjectInfo {
|
||||
|
||||
// N2 fail-closed: see the gate in `replicate_object` — the same policy
|
||||
// applies to the metadata/existing-object transport.
|
||||
let Some(ssec_audit_required) = resolve_ssec_passthrough_gate(self.ssec, &tgt_client, &bucket, &object, &mut rinfo).await
|
||||
let Some(ssec_audit_required) = resolve_ssec_passthrough_gate(self.ssec, &tgt_client, &bucket, &object, &mut rinfo)
|
||||
else {
|
||||
send_local_event(EventArgs {
|
||||
event_name: EventName::ObjectReplicationNotTracked.to_string(),
|
||||
@@ -5357,7 +5352,7 @@ async fn resolve_replicate_all_action(
|
||||
// An SSE-C replica only counts as converged when the same HEAD
|
||||
// proves its decryption material survived; a broken ciphertext
|
||||
// copy from an earlier attempt matches by ETag.
|
||||
if ssec_audit_required && !settle_ssec_passthrough_evidence(&oi, tgt_client, bucket, object, rinfo).await {
|
||||
if ssec_audit_required && !settle_ssec_passthrough_evidence(&oi, tgt_client, bucket, object, rinfo) {
|
||||
rinfo.duration = (OffsetDateTime::now_utc() - start_time).unsigned_abs();
|
||||
return None;
|
||||
}
|
||||
@@ -5432,7 +5427,7 @@ async fn resolve_replicate_all_action(
|
||||
}
|
||||
if replica_matches
|
||||
&& ssec_audit_required
|
||||
&& !settle_ssec_passthrough_evidence(oi, tgt_client, bucket, object, rinfo).await
|
||||
&& !settle_ssec_passthrough_evidence(oi, tgt_client, bucket, object, rinfo)
|
||||
{
|
||||
rinfo.duration = (OffsetDateTime::now_utc() - start_time).unsigned_abs();
|
||||
return None;
|
||||
@@ -6706,6 +6701,8 @@ mod tests {
|
||||
.build();
|
||||
|
||||
Arc::new(TargetClient {
|
||||
source_bucket: "source".to_owned(),
|
||||
capabilities: Default::default(),
|
||||
endpoint,
|
||||
credentials: None,
|
||||
bucket: "target-bucket".to_string(),
|
||||
@@ -6910,7 +6907,7 @@ mod tests {
|
||||
async fn heal_redrive_locates_replica_by_etag_on_target_that_mints_own_version_ids() {
|
||||
let (endpoint, server) = spawn_drifted_target_server(3);
|
||||
let target = test_target_client(endpoint);
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let (roi, object_info) = drifted_roi_and_object();
|
||||
let mut rinfo = replicate_all_target_info(&roi, &target);
|
||||
|
||||
@@ -6979,7 +6976,7 @@ mod tests {
|
||||
async fn resync_verification_counts_drifted_replica_as_replicated() {
|
||||
let (endpoint, server) = spawn_drifted_target_server(3);
|
||||
let target = test_target_client(endpoint);
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let (roi, _) = drifted_roi_and_object();
|
||||
let mut st = TargetReplicationResyncStatus::default();
|
||||
|
||||
@@ -7093,7 +7090,7 @@ mod tests {
|
||||
static VERSIONS: &[(&str, i64)] = &[(DRIFTED_ASSIGNED_VERSION_ID, 4)];
|
||||
let (endpoint, server) = spawn_computed_etag_target(3, VERSIONS);
|
||||
let target = test_target_client(endpoint);
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let (roi, object_info) = encrypted_roi_and_object(replica_written_secs() - 1);
|
||||
let mut rinfo = replicate_all_target_info(&roi, &target);
|
||||
|
||||
@@ -7115,7 +7112,7 @@ mod tests {
|
||||
static OTHER_SIZE: &[(&str, i64)] = &[(DRIFTED_ASSIGNED_VERSION_ID, 36)];
|
||||
let (endpoint, server) = spawn_computed_etag_target(2, OTHER_SIZE);
|
||||
let target = test_target_client(endpoint);
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let (roi, object_info) = encrypted_roi_and_object(replica_written_secs() - 1);
|
||||
let mut rinfo = replicate_all_target_info(&roi, &target);
|
||||
let action = resolve_heal_action(&target, &roi, object_info, &mut rinfo).await;
|
||||
@@ -7126,7 +7123,7 @@ mod tests {
|
||||
static SAME_SIZE: &[(&str, i64)] = &[(DRIFTED_ASSIGNED_VERSION_ID, 4)];
|
||||
let (endpoint, server) = spawn_computed_etag_target(2, SAME_SIZE);
|
||||
let target = test_target_client(endpoint);
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let (roi, object_info) = encrypted_roi_and_object(replica_written_secs() + 1);
|
||||
let mut rinfo = replicate_all_target_info(&roi, &target);
|
||||
let action = resolve_heal_action(&target, &roi, object_info, &mut rinfo).await;
|
||||
@@ -7139,7 +7136,7 @@ mod tests {
|
||||
static VERSIONS: &[(&str, i64)] = &[(DRIFTED_ASSIGNED_VERSION_ID, 4), ("another-minted-id", 4)];
|
||||
let (endpoint, server) = spawn_computed_etag_target(2, VERSIONS);
|
||||
let target = test_target_client(endpoint);
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let (roi, object_info) = encrypted_roi_and_object(replica_written_secs() - 1);
|
||||
let mut rinfo = replicate_all_target_info(&roi, &target);
|
||||
|
||||
@@ -7161,7 +7158,7 @@ mod tests {
|
||||
static VERSIONS: &[(&str, i64)] = &[(DRIFTED_ASSIGNED_VERSION_ID, 4)];
|
||||
let (endpoint, server) = spawn_computed_etag_target(2, VERSIONS);
|
||||
let target = test_target_client(endpoint);
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let (roi, mut object_info) = drifted_roi_and_object();
|
||||
object_info.mod_time = Some(OffsetDateTime::from_unix_timestamp(replica_written_secs() - 1).expect("valid timestamp"));
|
||||
let mut rinfo = replicate_all_target_info(&roi, &target);
|
||||
@@ -7179,7 +7176,7 @@ mod tests {
|
||||
static VERSIONS: &[(&str, i64)] = &[("null", 4)];
|
||||
let (endpoint, server) = spawn_computed_etag_target(2, VERSIONS);
|
||||
let target = test_target_client(endpoint);
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let (roi, object_info) = encrypted_roi_and_object(replica_written_secs() - 1);
|
||||
let mut rinfo = replicate_all_target_info(&roi, &target);
|
||||
|
||||
@@ -7264,7 +7261,7 @@ mod tests {
|
||||
static VERSIONS: &[(&str, i64)] = &[(DRIFTED_ASSIGNED_VERSION_ID, 4)];
|
||||
let (endpoint, server) = spawn_computed_etag_target(3, VERSIONS);
|
||||
let target = test_target_client(endpoint);
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let (roi, object_info) = encrypted_roi_and_object(replica_written_secs() - 1);
|
||||
let mut st = TargetReplicationResyncStatus::default();
|
||||
|
||||
@@ -7304,7 +7301,7 @@ mod tests {
|
||||
});
|
||||
let target = test_target_client(endpoint);
|
||||
register_test_target(&target).await;
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let dobj = version_purge_dobj(&target.arn);
|
||||
|
||||
let rinfo = replicate_delete_to_target(&dobj, target.clone(), Some(encrypted_purge_source())).await;
|
||||
@@ -7330,7 +7327,7 @@ mod tests {
|
||||
});
|
||||
let target = test_target_client(endpoint);
|
||||
register_test_target(&target).await;
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let dobj = version_purge_dobj(&target.arn);
|
||||
|
||||
let rinfo = replicate_delete_to_target(&dobj, target.clone(), Some(encrypted_purge_source())).await;
|
||||
@@ -7477,10 +7474,7 @@ mod tests {
|
||||
let rinfo = replicate_delete_to_target(&dobj, target.clone(), None).await;
|
||||
|
||||
assert_eq!(rinfo.replication_status, ReplicationStatusType::Completed, "{rinfo:?}");
|
||||
assert_eq!(
|
||||
ReplicationTargetStore::version_identity_capability(&target.arn),
|
||||
VersionIdentityCapability::MintsOwn
|
||||
);
|
||||
assert_eq!(target.version_identity_capability(), VersionIdentityCapability::MintsOwn);
|
||||
let seen = server.join().expect("test HTTP server should finish");
|
||||
assert_eq!(seen.len(), 2, "{seen:?}");
|
||||
assert!(seen[0].starts_with("HEAD "), "{seen:?}");
|
||||
@@ -7509,10 +7503,7 @@ mod tests {
|
||||
let rinfo = replicate_delete_to_target(&dobj, target.clone(), None).await;
|
||||
|
||||
assert_eq!(rinfo.replication_status, ReplicationStatusType::Failed, "{rinfo:?}");
|
||||
assert_ne!(
|
||||
ReplicationTargetStore::version_identity_capability(&target.arn),
|
||||
VersionIdentityCapability::MintsOwn
|
||||
);
|
||||
assert_ne!(target.version_identity_capability(), VersionIdentityCapability::MintsOwn);
|
||||
let seen = server.join().expect("test HTTP server should finish");
|
||||
assert_eq!(seen.len(), 1, "a denied HEAD must not trigger DELETE: {seen:?}");
|
||||
assert!(seen[0].starts_with("HEAD "), "{seen:?}");
|
||||
@@ -7531,7 +7522,7 @@ mod tests {
|
||||
});
|
||||
let target = test_target_client(endpoint);
|
||||
register_test_target(&target).await;
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let dobj = marker_creation_dobj(&target.arn);
|
||||
|
||||
let rinfo = replicate_delete_to_target(&dobj, target.clone(), None).await;
|
||||
@@ -7893,7 +7884,7 @@ mod tests {
|
||||
seen[0]
|
||||
);
|
||||
assert!(
|
||||
ReplicationTargetStore::version_identity_capability(&target.arn).version_addressing_unreliable(),
|
||||
target.version_identity_capability().version_addressing_unreliable(),
|
||||
"a ledger entry proves the target mints its own ids"
|
||||
);
|
||||
}
|
||||
@@ -7911,7 +7902,7 @@ mod tests {
|
||||
});
|
||||
let target = test_target_client(endpoint);
|
||||
register_test_target(&target).await;
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let dobj = version_purge_dobj(&target.arn);
|
||||
|
||||
let rinfo = replicate_delete_to_target(&dobj, target.clone(), Some(purge_source(&[]))).await;
|
||||
@@ -7938,7 +7929,7 @@ mod tests {
|
||||
});
|
||||
let target = test_target_client(endpoint);
|
||||
register_test_target(&target).await;
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let dobj = version_purge_dobj(&target.arn);
|
||||
assert!(!purge_backoff_active(&dobj));
|
||||
|
||||
@@ -7966,7 +7957,7 @@ mod tests {
|
||||
});
|
||||
let target = test_target_client(endpoint);
|
||||
register_test_target(&target).await;
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let dobj = version_purge_dobj(&target.arn);
|
||||
|
||||
let rinfo = replicate_delete_to_target(&dobj, target.clone(), Some(purge_source(&[]))).await;
|
||||
@@ -8038,7 +8029,7 @@ mod tests {
|
||||
assert!(seen[1].starts_with("GET "), "{}", seen[1]);
|
||||
assert!(seen[2].contains(DRIFTED_ASSIGNED_VERSION_ID), "{}", seen[2]);
|
||||
assert!(
|
||||
ReplicationTargetStore::version_identity_capability(&target.arn).version_addressing_unreliable(),
|
||||
target.version_identity_capability().version_addressing_unreliable(),
|
||||
"the located replica proves the target mints its own ids"
|
||||
);
|
||||
}
|
||||
@@ -8058,7 +8049,7 @@ mod tests {
|
||||
});
|
||||
let target = test_target_client(endpoint);
|
||||
register_test_target(&target).await;
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let dobj = version_purge_dobj(&target.arn);
|
||||
let source = Arc::new(VersionPurgeSource {
|
||||
etag: Some(DRIFTED_ETAG.to_string()),
|
||||
@@ -8099,7 +8090,7 @@ mod tests {
|
||||
}
|
||||
});
|
||||
let target = test_target_client(endpoint);
|
||||
ReplicationTargetStore::record_version_identity_capability(&target.arn, VersionIdentityCapability::MintsOwn);
|
||||
target.record_version_identity_capability(VersionIdentityCapability::MintsOwn);
|
||||
let (roi, object_info) = drifted_roi_and_object();
|
||||
let mut rinfo = replicate_all_target_info(&roi, &target);
|
||||
|
||||
@@ -8250,21 +8241,12 @@ mod tests {
|
||||
let target = test_target_client("http://127.0.0.1:1".to_string());
|
||||
let source = Uuid::new_v4().to_string();
|
||||
audit_target_version_identity(&target, &source, Some(DRIFTED_ASSIGNED_VERSION_ID));
|
||||
assert_eq!(
|
||||
ReplicationTargetStore::version_identity_capability(&target.arn),
|
||||
VersionIdentityCapability::MintsOwn
|
||||
);
|
||||
assert_eq!(target.version_identity_capability(), VersionIdentityCapability::MintsOwn);
|
||||
audit_target_version_identity(&target, &source, Some(&source));
|
||||
assert_eq!(
|
||||
ReplicationTargetStore::version_identity_capability(&target.arn),
|
||||
VersionIdentityCapability::Adopts
|
||||
);
|
||||
assert_eq!(target.version_identity_capability(), VersionIdentityCapability::Adopts);
|
||||
// An unversioned write carries no contract and must not overwrite it.
|
||||
audit_target_version_identity(&target, "null", None);
|
||||
assert_eq!(
|
||||
ReplicationTargetStore::version_identity_capability(&target.arn),
|
||||
VersionIdentityCapability::Adopts
|
||||
);
|
||||
assert_eq!(target.version_identity_capability(), VersionIdentityCapability::Adopts);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -9450,13 +9432,13 @@ mod tests {
|
||||
let arn = "arn:replication::drift-throttle-test";
|
||||
let start = Instant::now();
|
||||
|
||||
assert!(version_identity_drift_log_due(arn, start), "first drift must be reported");
|
||||
assert!(version_identity_drift_log_due("source", arn, start), "first drift must be reported");
|
||||
assert!(
|
||||
!version_identity_drift_log_due(arn, start + VERSION_IDENTITY_DRIFT_LOG_INTERVAL / 2),
|
||||
!version_identity_drift_log_due("source", arn, start + VERSION_IDENTITY_DRIFT_LOG_INTERVAL / 2),
|
||||
"a second drift inside the interval must stay throttled"
|
||||
);
|
||||
assert!(
|
||||
version_identity_drift_log_due(arn, start + VERSION_IDENTITY_DRIFT_LOG_INTERVAL),
|
||||
version_identity_drift_log_due("source", arn, start + VERSION_IDENTITY_DRIFT_LOG_INTERVAL),
|
||||
"drift must become visible again once the interval elapses, instead of \
|
||||
going silent for the rest of the process lifetime"
|
||||
);
|
||||
@@ -9466,9 +9448,10 @@ mod tests {
|
||||
fn version_identity_drift_throttles_each_target_independently() {
|
||||
let now = Instant::now();
|
||||
|
||||
assert!(version_identity_drift_log_due("arn:replication::drift-a", now));
|
||||
assert!(version_identity_drift_log_due("source", "arn:replication::drift-a", now));
|
||||
assert!(version_identity_drift_log_due("other-source", "arn:replication::drift-a", now));
|
||||
assert!(
|
||||
version_identity_drift_log_due("arn:replication::drift-b", now),
|
||||
version_identity_drift_log_due("source", "arn:replication::drift-b", now),
|
||||
"one target's report must not silence another's"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -197,31 +197,9 @@ impl ReplicationTargetStore {
|
||||
BucketTargetSys::get().mark_target_offline(target_client).await
|
||||
}
|
||||
|
||||
/// Returns the cached verdict and whether it has outlived its TTL.
|
||||
pub(crate) async fn ssec_passthrough_capability(arn: &str) -> (SsecPassthroughCapability, bool) {
|
||||
BucketTargetSys::get().ssec_passthrough_capability(arn).await
|
||||
}
|
||||
|
||||
pub(crate) async fn record_ssec_passthrough_capability(arn: &str, capability: SsecPassthroughCapability) {
|
||||
BucketTargetSys::get()
|
||||
.record_ssec_passthrough_capability(arn, capability)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn version_identity_capability(arn: &str) -> VersionIdentityCapability {
|
||||
BucketTargetSys::get().version_identity_capability(arn)
|
||||
}
|
||||
|
||||
pub(crate) fn record_version_identity_capability(arn: &str, capability: VersionIdentityCapability) {
|
||||
BucketTargetSys::get().record_version_identity_capability(arn, capability)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn register_test_target(target_client: &Arc<TargetClient>) {
|
||||
BucketTargetSys::get().arn_remotes_map.write().await.insert(
|
||||
target_client.arn.clone(),
|
||||
crate::bucket::bucket_target_sys::ArnTarget::with_client(target_client.clone()),
|
||||
);
|
||||
BucketTargetSys::get().register_test_client(target_client).await;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ const REDACTED_CREDENTIAL: &str = "<redacted>";
|
||||
const GO_YEAR_ONE_START_UNIX_SECONDS: i64 = -62_135_596_800;
|
||||
const GO_YEAR_TWO_START_UNIX_SECONDS: i64 = -62_104_060_800;
|
||||
|
||||
#[derive(Deserialize, Serialize, Default, Clone)]
|
||||
#[derive(Deserialize, Serialize, Default, Clone, PartialEq, Eq)]
|
||||
pub struct Credentials {
|
||||
#[serde(rename = "accessKey")]
|
||||
pub access_key: String,
|
||||
|
||||
@@ -21,7 +21,7 @@ use crate::cluster::rpc::{set_tonic_canonical_body_digest, set_tonic_mutation_bo
|
||||
use crate::error::{Error, Result};
|
||||
use crate::storage_api_contracts::internode::{
|
||||
SCANNER_ACTIVITY_LEGACY_PROTOCOL_VERSION, SCANNER_ACTIVITY_PREVIOUS_PROTOCOL_VERSION, SCANNER_ACTIVITY_PROTOCOL_VERSION,
|
||||
SCANNER_ACTIVITY_V6_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_MAX_ENTRIES,
|
||||
SCANNER_ACTIVITY_V6_PROTOCOL_VERSION, SCANNER_ACTIVITY_V7_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_MAX_ENTRIES,
|
||||
SCANNER_DIRTY_USAGE_SNAPSHOT_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_RPC_MAX_MESSAGE_SIZE,
|
||||
};
|
||||
use crate::{
|
||||
@@ -192,6 +192,7 @@ fn validate_signal_service_protocol(sig: u64, sub_sys: &str, protocol_version: u
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ScannerPeerActivity {
|
||||
pub instance_id: String,
|
||||
pub checkpoint_instance_id: Option<String>,
|
||||
pub namespace_generation: u64,
|
||||
pub maintenance_generation: u64,
|
||||
pub protocol_version: u32,
|
||||
@@ -354,6 +355,9 @@ fn decode_scanner_activity_with_verifier(
|
||||
challenge: &[u8; 16],
|
||||
verify_proof: impl FnOnce(&[u8], &[u8]) -> Result<()>,
|
||||
) -> Result<ScannerPeerActivity> {
|
||||
if response.protocol_version != SCANNER_ACTIVITY_PROTOCOL_VERSION && response.checkpoint_instance_id.is_some() {
|
||||
return Err(Error::other("legacy scanner activity peer returned unauthenticated checkpoint identity"));
|
||||
}
|
||||
let instance_id = &response.instance_id;
|
||||
if !scanner_instance_id_is_valid(instance_id) {
|
||||
return Err(Error::other("peer returned an invalid scanner activity instance ID"));
|
||||
@@ -423,7 +427,7 @@ fn decode_scanner_activity_with_verifier(
|
||||
None,
|
||||
)
|
||||
}
|
||||
SCANNER_ACTIVITY_PROTOCOL_VERSION => {
|
||||
SCANNER_ACTIVITY_V7_PROTOCOL_VERSION | SCANNER_ACTIVITY_PROTOCOL_VERSION => {
|
||||
if response.dirty_usage_pending && response.dirty_usage_generation == 0 {
|
||||
return Err(Error::other("scanner activity peer returned pending dirty usage without a generation"));
|
||||
}
|
||||
@@ -436,8 +440,20 @@ fn decode_scanner_activity_with_verifier(
|
||||
if movement_generation == u64::MAX {
|
||||
return Err(Error::other("scanner activity peer exhausted its movement generation"));
|
||||
}
|
||||
let canonical = rustfs_protos::canonical_scanner_activity_v7_response_body(challenge, &response)
|
||||
.map_err(|_| Error::other("scanner activity peer response is too large to authenticate"))?;
|
||||
let canonical = if response.protocol_version == SCANNER_ACTIVITY_PROTOCOL_VERSION {
|
||||
let instance = response
|
||||
.checkpoint_instance_id
|
||||
.as_deref()
|
||||
.filter(|instance| scanner_instance_id_is_valid(instance))
|
||||
.ok_or_else(|| Error::other("scanner activity peer omitted its checkpoint identity"))?;
|
||||
if instance.bytes().all(|byte| byte == b'0') {
|
||||
return Err(Error::other("scanner activity peer returned an empty checkpoint identity"));
|
||||
}
|
||||
rustfs_protos::canonical_scanner_activity_v8_response_body(challenge, &response)
|
||||
} else {
|
||||
rustfs_protos::canonical_scanner_activity_v7_response_body(challenge, &response)
|
||||
}
|
||||
.map_err(|_| Error::other("scanner activity peer response is too large to authenticate"))?;
|
||||
verify_proof(&canonical, &response.response_proof)?;
|
||||
(
|
||||
Some(
|
||||
@@ -458,6 +474,7 @@ fn decode_scanner_activity_with_verifier(
|
||||
};
|
||||
Ok(ScannerPeerActivity {
|
||||
instance_id: response.instance_id,
|
||||
checkpoint_instance_id: response.checkpoint_instance_id,
|
||||
namespace_generation: response.namespace_generation,
|
||||
maintenance_generation: response.maintenance_generation,
|
||||
protocol_version: response.protocol_version,
|
||||
@@ -2452,11 +2469,15 @@ impl PeerRestClient {
|
||||
.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_PROTOCOL_VERSION)
|
||||
.await;
|
||||
if result.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
|
||||
// A v6 peer cannot parse the v7 marker. Its authenticated
|
||||
// response is still decoded as untrusted terminal state, so the
|
||||
// scanner will defer publication until every peer is v7.
|
||||
self.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
|
||||
.await
|
||||
let previous = self
|
||||
.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_V7_PROTOCOL_VERSION)
|
||||
.await;
|
||||
if previous.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
|
||||
self.scanner_activity_request_with_protocol(String::new(), 0, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
|
||||
.await
|
||||
} else {
|
||||
previous
|
||||
}
|
||||
} else {
|
||||
result
|
||||
}
|
||||
@@ -2723,8 +2744,15 @@ impl PeerRestClient {
|
||||
.scanner_activity_request_with_protocol(instance_id.clone(), generation, SCANNER_ACTIVITY_PROTOCOL_VERSION)
|
||||
.await;
|
||||
if result.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
|
||||
self.scanner_activity_request_with_protocol(instance_id, generation, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
|
||||
.await
|
||||
let previous = self
|
||||
.scanner_activity_request_with_protocol(instance_id.clone(), generation, SCANNER_ACTIVITY_V7_PROTOCOL_VERSION)
|
||||
.await;
|
||||
if previous.as_ref().err().is_some_and(scanner_activity_protocol_unsupported) {
|
||||
self.scanner_activity_request_with_protocol(instance_id, generation, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION)
|
||||
.await
|
||||
} else {
|
||||
previous
|
||||
}
|
||||
} else {
|
||||
result
|
||||
}
|
||||
@@ -3680,6 +3708,7 @@ mod tests {
|
||||
#[test]
|
||||
fn scanner_scoped_dirty_usage_ack_reconciliation_requires_same_clean_instance() {
|
||||
let activity = |instance_id: &str, generation, pending| ScannerPeerActivity {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: instance_id.to_string(),
|
||||
namespace_generation: 1,
|
||||
maintenance_generation: 1,
|
||||
@@ -3961,9 +3990,44 @@ mod tests {
|
||||
.await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_checkpoint_identity_requires_v8_proof_and_preserves_rpc_epoch() {
|
||||
let response = ScannerActivityResponse {
|
||||
protocol_version: SCANNER_ACTIVITY_PROTOCOL_VERSION,
|
||||
instance_id: "1".repeat(32),
|
||||
checkpoint_instance_id: Some("2".repeat(32)),
|
||||
topology_digest: vec![7; 32].into(),
|
||||
movement_generation: Some(0),
|
||||
publication_blocked: Some(false),
|
||||
response_proof: b"proof".to_vec().into(),
|
||||
..Default::default()
|
||||
};
|
||||
let decoded = decode_test_scanner_activity(response.clone()).expect("authenticated v8");
|
||||
assert_eq!(decoded.instance_id, "1".repeat(32));
|
||||
assert_eq!(decoded.checkpoint_instance_id, Some("2".repeat(32)));
|
||||
for checkpoint_instance_id in [None, Some(String::new()), Some("0".repeat(32)), Some("A".repeat(32))] {
|
||||
let malformed = ScannerActivityResponse {
|
||||
checkpoint_instance_id,
|
||||
..response.clone()
|
||||
};
|
||||
assert!(decode_test_scanner_activity(malformed).is_err(), "invalid continuity must fail closed");
|
||||
}
|
||||
let v7 = ScannerActivityResponse {
|
||||
protocol_version: SCANNER_ACTIVITY_V7_PROTOCOL_VERSION,
|
||||
..response
|
||||
};
|
||||
assert!(decode_test_scanner_activity(v7.clone()).is_err(), "legacy proof does not bind continuity");
|
||||
let v7 = ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
..v7
|
||||
};
|
||||
assert!(decode_test_scanner_activity(v7).is_ok(), "v7 without continuity remains supported");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_activity_requires_restart_safe_peer_identity() {
|
||||
let legacy = decode_test_scanner_activity(ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -3980,6 +4044,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
legacy,
|
||||
ScannerPeerActivity {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -3994,6 +4059,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let previous = decode_test_scanner_activity(ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4010,6 +4076,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
previous,
|
||||
ScannerPeerActivity {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4024,6 +4091,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let v6 = decode_test_scanner_activity(ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4042,6 +4110,7 @@ mod tests {
|
||||
assert_eq!(v6.dirty_usage_generation, Some(11));
|
||||
|
||||
let malformed_topology = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4062,6 +4131,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let missing_instance = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: String::new(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4082,6 +4152,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let malformed_instance = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "ABCDEF0123456789ABCDEF0123456789".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4102,6 +4173,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let activity = decode_test_scanner_activity(ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4118,6 +4190,7 @@ mod tests {
|
||||
assert_eq!(
|
||||
activity,
|
||||
ScannerPeerActivity {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4132,6 +4205,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let missing_movement_generation = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4152,6 +4226,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let pending_without_generation = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4172,6 +4247,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let previous_with_dirty_usage = ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4192,6 +4268,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let legacy_with_topology = ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4212,6 +4289,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let unsupported_protocol = ScannerActivityResponse {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
@@ -4232,6 +4310,7 @@ mod tests {
|
||||
);
|
||||
|
||||
let missing_proof = ScannerActivityResponse {
|
||||
checkpoint_instance_id: Some("1123456789abcdef0123456789abcdef".to_owned()),
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 7,
|
||||
maintenance_generation: 3,
|
||||
|
||||
@@ -73,10 +73,11 @@ use rustfs_protos::proto_gen::node_service::{
|
||||
PreparePartTransactionRequest, ReadAllRequest, ReadMetadataRequest, ReadMultipleRequest, ReadMultipleResponse,
|
||||
ReadPartsRequest, ReadVersionRequest, ReadXlRequest, RecoverDeleteTransactionRequest,
|
||||
RecoverMultipartSourceRequest as RecoverMultipartSourceRpcRequest,
|
||||
RecoverMultipartSourceResponse as RecoverMultipartSourceRpcResponse, RenameDataRequest, RenameFileRequest,
|
||||
SettlePartTransactionRequest, SnapshotLeaseReleaseRequest, SnapshotLeaseRenewRequest, SnapshotLeaseRequest,
|
||||
SnapshotLeaseResponse, StatVolumeRequest, UpdateMetadataRequest, VerifyFileRequest, WriteAllRequest, WriteAllResponse,
|
||||
WriteFormatControlRequest, WriteMetadataRequest, node_service_client::NodeServiceClient,
|
||||
RecoverMultipartSourceResponse as RecoverMultipartSourceRpcResponse, RenameDataBatchItem, RenameDataBatchRequest,
|
||||
RenameDataBatchResult, RenameDataRequest, RenameFileRequest, SettlePartTransactionRequest, SnapshotLeaseReleaseRequest,
|
||||
SnapshotLeaseRenewRequest, SnapshotLeaseRequest, SnapshotLeaseResponse, StatVolumeRequest, UpdateMetadataRequest,
|
||||
VerifyFileRequest, WriteAllRequest, WriteAllResponse, WriteFormatControlRequest, WriteMetadataRequest,
|
||||
node_service_client::NodeServiceClient,
|
||||
};
|
||||
use rustfs_protos::{
|
||||
ChannelClass, ChannelRebuildReason, ConnectionEvictionLogLevel, evict_failed_connection_with_reason, prewarm_channel_class,
|
||||
@@ -104,7 +105,7 @@ use tokio::{
|
||||
time::timeout,
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tonic::{Code, Request, service::interceptor::InterceptedService};
|
||||
use tonic::{Code, Request, Streaming, service::interceptor::InterceptedService};
|
||||
use tracing::{debug, trace, warn};
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -1045,6 +1046,7 @@ pub struct RemoteDisk {
|
||||
/// Optional per-peer gate held through complete bulk-unary decoding and validation.
|
||||
bulk_body_admission: Option<Arc<Semaphore>>,
|
||||
bulk_body_wait_timeout: Duration,
|
||||
rename_admission: Option<Arc<Semaphore>>,
|
||||
}
|
||||
|
||||
/// Shortest gap between two failure warnings of one kind from one remote disk.
|
||||
@@ -1060,6 +1062,251 @@ struct BulkBodyAdmissionRegistry {
|
||||
static BULK_BODY_ADMISSION_REGISTRY: std::sync::LazyLock<StdMutex<BulkBodyAdmissionRegistry>> =
|
||||
std::sync::LazyLock::new(|| StdMutex::new(BulkBodyAdmissionRegistry::default()));
|
||||
|
||||
const ENV_RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH: &str = "RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH";
|
||||
const RENAME_ADMISSION_REGISTRY_CAPACITY: usize = 512;
|
||||
|
||||
#[derive(Default)]
|
||||
struct RenameAdmissionRegistry {
|
||||
peers: HashMap<String, Weak<Semaphore>>,
|
||||
overflow: Option<Arc<Semaphore>>,
|
||||
}
|
||||
|
||||
static RENAME_ADMISSION_REGISTRY: std::sync::LazyLock<StdMutex<RenameAdmissionRegistry>> =
|
||||
std::sync::LazyLock::new(|| StdMutex::new(RenameAdmissionRegistry::default()));
|
||||
|
||||
fn peer_rename_admission(addr: &str, enabled: bool) -> Option<Arc<Semaphore>> {
|
||||
if !enabled {
|
||||
return None;
|
||||
}
|
||||
let mut registry = RENAME_ADMISSION_REGISTRY
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if let Some(semaphore) = registry.peers.get(addr).and_then(Weak::upgrade) {
|
||||
return Some(semaphore);
|
||||
}
|
||||
if registry.peers.len() >= RENAME_ADMISSION_REGISTRY_CAPACITY {
|
||||
registry.peers.retain(|_, semaphore| semaphore.strong_count() > 0);
|
||||
}
|
||||
if registry.peers.len() >= RENAME_ADMISSION_REGISTRY_CAPACITY {
|
||||
return Some(Arc::clone(registry.overflow.get_or_insert_with(|| {
|
||||
Arc::new(Semaphore::new(rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT))
|
||||
})));
|
||||
}
|
||||
let semaphore = Arc::new(Semaphore::new(rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT));
|
||||
registry.peers.insert(addr.to_owned(), Arc::downgrade(&semaphore));
|
||||
Some(semaphore)
|
||||
}
|
||||
|
||||
struct RenameAdmissionGrant {
|
||||
permit: Option<OwnedSemaphorePermit>,
|
||||
batch: bool,
|
||||
}
|
||||
|
||||
impl RenameAdmissionGrant {
|
||||
fn release_one(&mut self) -> bool {
|
||||
self.permit.as_mut().is_some_and(|permit| permit.split(1).is_some())
|
||||
}
|
||||
|
||||
fn release_all(mut self) {
|
||||
drop(self.permit.take());
|
||||
}
|
||||
|
||||
fn quarantine_until(mut self, deadline: tokio::time::Instant) {
|
||||
let Some(permit) = self.permit.take() else {
|
||||
return;
|
||||
};
|
||||
let items = permit.num_permits();
|
||||
if items == 0 {
|
||||
return;
|
||||
}
|
||||
let hold = deadline.saturating_duration_since(tokio::time::Instant::now());
|
||||
rustfs_io_metrics::record_ecstore_rename_quarantine(self.batch, items, hold);
|
||||
let batch = self.batch;
|
||||
if let Ok(handle) = tokio::runtime::Handle::try_current() {
|
||||
handle.spawn(async move {
|
||||
tokio::time::sleep_until(deadline).await;
|
||||
drop(permit);
|
||||
rustfs_io_metrics::record_ecstore_rename_quarantine_released(batch, items);
|
||||
});
|
||||
} else {
|
||||
// Without a runtime there is no safe deadline task. Leaking until
|
||||
// process exit is safer than admitting work over a still-running mutation.
|
||||
rustfs_io_metrics::record_ecstore_rename_quarantine_no_runtime(batch, items);
|
||||
std::mem::forget(permit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct RenameBatchCallGuard {
|
||||
admission: Option<RenameAdmissionGrant>,
|
||||
deadline: tokio::time::Instant,
|
||||
dispatch_state: RenameAdmissionDispatchState,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum RenameAdmissionDispatchState {
|
||||
NotDispatched,
|
||||
MayHavePublished,
|
||||
}
|
||||
|
||||
impl RenameBatchCallGuard {
|
||||
fn mark_dispatched(&mut self) {
|
||||
self.dispatch_state = RenameAdmissionDispatchState::MayHavePublished;
|
||||
}
|
||||
|
||||
fn complete(mut self) {
|
||||
debug_assert_eq!(self.dispatch_state, RenameAdmissionDispatchState::MayHavePublished);
|
||||
if let Some(admission) = self.admission.take() {
|
||||
admission.release_all();
|
||||
}
|
||||
}
|
||||
|
||||
fn release_without_quarantine(mut self) {
|
||||
if let Some(admission) = self.admission.take() {
|
||||
admission.release_all();
|
||||
}
|
||||
}
|
||||
|
||||
fn into_stream(mut self, inner: Streaming<RenameDataBatchResult>, expected_mask: u16) -> RemoteRenameBatchStream {
|
||||
debug_assert_eq!(self.dispatch_state, RenameAdmissionDispatchState::MayHavePublished);
|
||||
RemoteRenameBatchStream {
|
||||
inner,
|
||||
expected_mask,
|
||||
seen_mask: 0,
|
||||
admission: self.admission.take(),
|
||||
deadline: self.deadline,
|
||||
terminal: false,
|
||||
stream_started_at: rustfs_io_metrics::put_stage_metrics_enabled().then(Instant::now),
|
||||
first_item_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RenameBatchCallGuard {
|
||||
fn drop(&mut self) {
|
||||
if self.dispatch_state == RenameAdmissionDispatchState::MayHavePublished
|
||||
&& let Some(admission) = self.admission.take()
|
||||
{
|
||||
admission.quarantine_until(self.deadline);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct RenameBatchClientItem<'a> {
|
||||
pub slot: usize,
|
||||
pub disk: String,
|
||||
pub file_info: &'a FileInfo,
|
||||
}
|
||||
|
||||
pub(crate) enum RenameBatchStartError {
|
||||
NotDispatched(Error),
|
||||
UnsupportedBeforeStream,
|
||||
MayHavePublished(Error),
|
||||
}
|
||||
|
||||
pub(crate) struct RemoteRenameBatchOutcome {
|
||||
pub slot: usize,
|
||||
pub result: Result<RenameDataResp>,
|
||||
}
|
||||
|
||||
pub(crate) struct RemoteRenameBatchStream {
|
||||
inner: Streaming<RenameDataBatchResult>,
|
||||
expected_mask: u16,
|
||||
seen_mask: u16,
|
||||
admission: Option<RenameAdmissionGrant>,
|
||||
deadline: tokio::time::Instant,
|
||||
terminal: bool,
|
||||
stream_started_at: Option<Instant>,
|
||||
first_item_at: Option<Instant>,
|
||||
}
|
||||
|
||||
impl RemoteRenameBatchStream {
|
||||
fn terminate_ambiguous(&mut self, error: Error) -> Error {
|
||||
if !self.terminal {
|
||||
let missing = (self.expected_mask & !self.seen_mask).count_ones() as usize;
|
||||
rustfs_io_metrics::record_ecstore_rename_batch_terminal_missing(missing);
|
||||
}
|
||||
self.terminal = true;
|
||||
if let Some(admission) = self.admission.take() {
|
||||
admission.quarantine_until(self.deadline);
|
||||
}
|
||||
error
|
||||
}
|
||||
|
||||
pub(crate) async fn next_outcome(&mut self) -> Result<Option<RemoteRenameBatchOutcome>> {
|
||||
if self.terminal {
|
||||
return Ok(None);
|
||||
}
|
||||
let response = match tokio::time::timeout_at(self.deadline, self.inner.message()).await {
|
||||
Err(_) => return Err(self.terminate_ambiguous(DiskError::Timeout)),
|
||||
Ok(Err(status)) => return Err(self.terminate_ambiguous(status.into())),
|
||||
Ok(Ok(None)) if self.seen_mask == self.expected_mask => {
|
||||
self.terminal = true;
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Ok(None)) => return Err(self.terminate_ambiguous(DiskError::Unexpected)),
|
||||
Ok(Ok(Some(response))) => response,
|
||||
};
|
||||
let Ok(slot) = usize::try_from(response.item_index) else {
|
||||
return Err(self.terminate_ambiguous(DiskError::Unexpected));
|
||||
};
|
||||
if slot >= 16 {
|
||||
return Err(self.terminate_ambiguous(DiskError::Unexpected));
|
||||
}
|
||||
let bit = 1_u16 << slot;
|
||||
if self.expected_mask & bit == 0 || self.seen_mask & bit != 0 {
|
||||
return Err(self.terminate_ambiguous(DiskError::Unexpected));
|
||||
}
|
||||
self.seen_mask |= bit;
|
||||
if self.admission.as_mut().is_some_and(|admission| !admission.release_one()) {
|
||||
return Err(self.terminate_ambiguous(DiskError::Unexpected));
|
||||
}
|
||||
if let Some(stream_started_at) = self.stream_started_at {
|
||||
let completed_at = Instant::now();
|
||||
match self.first_item_at {
|
||||
Some(first_item_at) if self.seen_mask == self.expected_mask => {
|
||||
rustfs_io_metrics::record_ecstore_rename_batch_client_first_to_last(
|
||||
completed_at.saturating_duration_since(first_item_at),
|
||||
);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
rustfs_io_metrics::record_ecstore_rename_batch_client_stream_to_first(
|
||||
completed_at.saturating_duration_since(stream_started_at),
|
||||
);
|
||||
self.first_item_at = Some(completed_at);
|
||||
if self.seen_mask == self.expected_mask {
|
||||
rustfs_io_metrics::record_ecstore_rename_batch_client_first_to_last(Duration::ZERO);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rustfs_io_metrics::record_ecstore_rename_batch_item_completed();
|
||||
let result = if response.success {
|
||||
if response.error.is_some() {
|
||||
Err(DiskError::FileCorrupt)
|
||||
} else {
|
||||
decode_msgpack_strict(&response.rename_data_resp_msgpack)
|
||||
}
|
||||
} else {
|
||||
Err(response.error.unwrap_or_default().into())
|
||||
};
|
||||
Ok(Some(RemoteRenameBatchOutcome { slot, result }))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RemoteRenameBatchStream {
|
||||
fn drop(&mut self) {
|
||||
if !self.terminal {
|
||||
let missing = (self.expected_mask & !self.seen_mask).count_ones() as usize;
|
||||
rustfs_io_metrics::record_ecstore_rename_batch_terminal_missing(missing);
|
||||
}
|
||||
if let Some(admission) = self.admission.take() {
|
||||
admission.quarantine_until(self.deadline);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct BulkBodyPermit {
|
||||
_metrics: rustfs_io_metrics::internode_metrics::InternodeBulkBodyAdmissionGuard,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
@@ -1226,6 +1473,10 @@ fn spawn_control_channel_prewarm(addr: String) {
|
||||
}
|
||||
|
||||
impl RemoteDisk {
|
||||
pub(crate) fn rename_stream_batch_enabled(&self) -> bool {
|
||||
self.rename_admission.is_some()
|
||||
}
|
||||
|
||||
async fn guarded_delete_versions_rpc(
|
||||
&self,
|
||||
volume: &str,
|
||||
@@ -1551,6 +1802,8 @@ impl RemoteDisk {
|
||||
rustfs_utils::get_env_bool(ENV_RUSTFS_DRIVE_ACTIVE_MONITORING, DEFAULT_RUSTFS_DRIVE_ACTIVE_MONITORING);
|
||||
let bulk_body_admission = peer_bulk_body_admission(&addr, bulk_body_concurrency_limit()?);
|
||||
let bulk_body_wait_timeout = bulk_body_wait_timeout();
|
||||
let rename_admission =
|
||||
peer_rename_admission(&addr, rustfs_utils::get_env_bool(ENV_RUSTFS_EXPERIMENTAL_RENAME_STREAM_BATCH, false));
|
||||
|
||||
let disk = Self {
|
||||
handle_id: Uuid::new_v4(),
|
||||
@@ -1573,6 +1826,7 @@ impl RemoteDisk {
|
||||
network_error_logs: rustfs_utils::LogThrottle::new(REMOTE_DISK_RPC_FAILURE_LOG_INTERVAL_MS),
|
||||
bulk_body_admission,
|
||||
bulk_body_wait_timeout,
|
||||
rename_admission,
|
||||
};
|
||||
record_drive_runtime_state(ep, RuntimeDriveHealthState::Online);
|
||||
|
||||
@@ -2308,6 +2562,54 @@ impl RemoteDisk {
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_peer_batch_with_timeout<T, F, Fut>(
|
||||
&self,
|
||||
op: &'static str,
|
||||
operation: F,
|
||||
timeout_duration: Duration,
|
||||
) -> Result<T>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: std::future::Future<Output = Result<T>>,
|
||||
{
|
||||
if timeout_duration == Duration::ZERO {
|
||||
self.record_timeout(op, timeout_duration);
|
||||
return Err(DiskError::Timeout);
|
||||
}
|
||||
match time::timeout(timeout_duration, operation()).await {
|
||||
Ok(operation_result) => {
|
||||
if operation_result.is_ok() {
|
||||
rustfs_io_metrics::internode_metrics::record_peer_reachable_if_offline(&self.addr);
|
||||
}
|
||||
let evict = operation_result
|
||||
.as_ref()
|
||||
.err()
|
||||
.is_some_and(|error| !error.is_metacache_output_stream_closed() && is_network_like_disk_error(error));
|
||||
self.handle_network_like_error(op, timeout_duration, &operation_result, FailureHealthAction::IgnoreFailure)
|
||||
.await;
|
||||
if evict {
|
||||
evict_failed_connection_with_reason(
|
||||
&self.addr,
|
||||
ChannelRebuildReason::RpcFailure,
|
||||
ConnectionEvictionLogLevel::Debug,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
operation_result
|
||||
}
|
||||
Err(_) => {
|
||||
self.record_timeout(op, timeout_duration);
|
||||
evict_failed_connection_with_reason(
|
||||
&self.addr,
|
||||
ChannelRebuildReason::OperationTimeout,
|
||||
ConnectionEvictionLogLevel::Debug,
|
||||
)
|
||||
.await;
|
||||
Err(DiskError::Timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record_timeout(&self, op: &'static str, timeout_duration: Duration) {
|
||||
counter!(
|
||||
"rustfs_drive_op_timeout_total",
|
||||
@@ -2494,6 +2796,38 @@ impl RemoteDisk {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn acquire_rename_admission_until(
|
||||
&self,
|
||||
item_count: usize,
|
||||
deadline: tokio::time::Instant,
|
||||
) -> Result<Option<RenameAdmissionGrant>> {
|
||||
let Some(semaphore) = &self.rename_admission else {
|
||||
return Ok(None);
|
||||
};
|
||||
if item_count == 0 || item_count > rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT {
|
||||
return Err(Error::other("invalid internode rename admission weight"));
|
||||
}
|
||||
if let Some(err) = self.offline_bypass_error() {
|
||||
return Err(err);
|
||||
}
|
||||
let weight = u32::try_from(item_count).map_err(Error::other)?;
|
||||
let started = rustfs_io_metrics::put_stage_metrics_enabled().then(Instant::now);
|
||||
let (result, timed_out) = match tokio::time::timeout_at(deadline, Arc::clone(semaphore).acquire_many_owned(weight)).await
|
||||
{
|
||||
Ok(Ok(permit)) => (Ok(permit), false),
|
||||
Ok(Err(_)) => (Err(Error::RemoteClientUnavailable("internode rename admission closed".to_owned())), false),
|
||||
Err(_) => (Err(DiskError::DiskOngoingReq), true),
|
||||
};
|
||||
if let Some(started) = started {
|
||||
rustfs_io_metrics::record_ecstore_rename_admission(item_count > 1, item_count, started.elapsed(), timed_out);
|
||||
}
|
||||
let permit = result?;
|
||||
Ok(Some(RenameAdmissionGrant {
|
||||
permit: Some(permit),
|
||||
batch: item_count > 1,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn get_bulk_client(&self) -> Result<NodeRpcClient> {
|
||||
if let Some(err) = self.offline_bypass_error() {
|
||||
return Err(err);
|
||||
@@ -2634,6 +2968,18 @@ fn decode_msgpack_or_json<T: DeserializeOwned>(binary: &[u8], json: &str, value_
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_msgpack_strict<T: DeserializeOwned>(binary: &[u8]) -> Result<T> {
|
||||
if binary.is_empty() {
|
||||
return Err(DiskError::FileCorrupt);
|
||||
}
|
||||
let mut cursor = Cursor::new(binary);
|
||||
let value = rmp_serde::from_read(&mut cursor).map_err(|_| DiskError::FileCorrupt)?;
|
||||
if cursor.position() != u64::try_from(binary.len()).map_err(Error::other)? {
|
||||
return Err(DiskError::FileCorrupt);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn decode_multipart_publication_response(binary: &[u8]) -> Result<RenameDataResp> {
|
||||
let result = if binary.len() > MultipartSourceOperation::max_wire_payload_bytes() {
|
||||
Err(DiskError::FileCorrupt)
|
||||
@@ -2831,6 +3177,97 @@ impl RemoteDisk {
|
||||
.await
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "trace", skip_all)]
|
||||
pub(crate) async fn start_rename_data_batch(
|
||||
&self,
|
||||
src_volume: &str,
|
||||
src_path: &str,
|
||||
dst_volume: &str,
|
||||
dst_path: &str,
|
||||
items: Vec<RenameBatchClientItem<'_>>,
|
||||
) -> std::result::Result<RemoteRenameBatchStream, RenameBatchStartError> {
|
||||
if self.rename_admission.is_none() || items.is_empty() || items.len() > 16 {
|
||||
return Err(RenameBatchStartError::NotDispatched(DiskError::UnsupportedDisk));
|
||||
}
|
||||
let deadline = tokio::time::Instant::now() + get_max_timeout_duration();
|
||||
let mut expected_mask = 0_u16;
|
||||
let mut request_items = Vec::with_capacity(items.len());
|
||||
for item in items {
|
||||
if item.slot >= 16 {
|
||||
return Err(RenameBatchStartError::NotDispatched(DiskError::Unexpected));
|
||||
}
|
||||
let bit = 1_u16 << item.slot;
|
||||
if expected_mask & bit != 0 {
|
||||
return Err(RenameBatchStartError::NotDispatched(DiskError::Unexpected));
|
||||
}
|
||||
expected_mask |= bit;
|
||||
let item_index = u32::try_from(item.slot)
|
||||
.map_err(Error::other)
|
||||
.map_err(RenameBatchStartError::NotDispatched)?;
|
||||
let file_info_msgpack = encode_file_info_msgpack(item.file_info).map_err(RenameBatchStartError::NotDispatched)?;
|
||||
request_items.push(RenameDataBatchItem {
|
||||
item_index,
|
||||
disk: item.disk,
|
||||
file_info_msgpack: file_info_msgpack.into(),
|
||||
});
|
||||
}
|
||||
let mut request = Request::new(RenameDataBatchRequest {
|
||||
src_volume: src_volume.to_owned(),
|
||||
src_path: src_path.to_owned(),
|
||||
dst_volume: dst_volume.to_owned(),
|
||||
dst_path: dst_path.to_owned(),
|
||||
items: request_items,
|
||||
});
|
||||
let canonical_body = rustfs_protos::canonical_rename_data_batch_request_body(request.get_ref())
|
||||
.map_err(Error::other)
|
||||
.map_err(RenameBatchStartError::NotDispatched)?;
|
||||
crate::cluster::rpc::set_tonic_canonical_body_digest(&mut request, &canonical_body)
|
||||
.map_err(Error::other)
|
||||
.map_err(RenameBatchStartError::NotDispatched)?;
|
||||
let mut client = match tokio::time::timeout_at(deadline, self.get_client()).await {
|
||||
Ok(result) => result.map_err(RenameBatchStartError::NotDispatched)?,
|
||||
Err(_) => return Err(RenameBatchStartError::NotDispatched(DiskError::Timeout)),
|
||||
};
|
||||
let admission = self
|
||||
.acquire_rename_admission_until(request.get_ref().items.len(), deadline)
|
||||
.await
|
||||
.map_err(RenameBatchStartError::NotDispatched)?;
|
||||
let guard = RenameBatchCallGuard {
|
||||
admission,
|
||||
deadline,
|
||||
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
|
||||
};
|
||||
let call_timeout = deadline.saturating_duration_since(tokio::time::Instant::now());
|
||||
if call_timeout == Duration::ZERO {
|
||||
guard.release_without_quarantine();
|
||||
return Err(RenameBatchStartError::NotDispatched(DiskError::Timeout));
|
||||
}
|
||||
let mut guard = guard;
|
||||
guard.mark_dispatched();
|
||||
let response = match self
|
||||
.execute_peer_batch_with_timeout(
|
||||
"rename_data_batch",
|
||||
|| async {
|
||||
match client.rename_data_batch(request).await {
|
||||
Ok(response) => Ok(response),
|
||||
Err(status) if status.code() == Code::Unimplemented => Err(DiskError::UnsupportedDisk),
|
||||
Err(status) => Err(status.into()),
|
||||
}
|
||||
},
|
||||
call_timeout,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Err(DiskError::UnsupportedDisk) => {
|
||||
guard.release_without_quarantine();
|
||||
return Err(RenameBatchStartError::UnsupportedBeforeStream);
|
||||
}
|
||||
Err(error) => return Err(RenameBatchStartError::MayHavePublished(error)),
|
||||
Ok(response) => response,
|
||||
};
|
||||
Ok(guard.into_stream(response.into_inner(), expected_mask))
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "trace", skip_all)]
|
||||
pub(crate) async fn rename_data_borrowed_with_fence(
|
||||
&self,
|
||||
@@ -2902,6 +3339,27 @@ impl RemoteDisk {
|
||||
let scanner_publication_lease = scanner_publication_lease_token
|
||||
.map(|token| Bytes::copy_from_slice(token.as_bytes()))
|
||||
.unwrap_or_default();
|
||||
let rename_deadline = tokio::time::Instant::now() + get_max_timeout_duration();
|
||||
let rename_admission = self.acquire_rename_admission_until(1, rename_deadline).await?;
|
||||
let mut rename_admission_guard = RenameBatchCallGuard {
|
||||
admission: rename_admission,
|
||||
deadline: rename_deadline,
|
||||
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
|
||||
};
|
||||
let rpc_kind = if multipart_rename {
|
||||
rustfs_io_metrics::ECSTORE_RENAME_RPC_KIND_MULTIPART
|
||||
} else if pool_meta_cas {
|
||||
rustfs_io_metrics::ECSTORE_RENAME_RPC_KIND_POOL_META_CAS
|
||||
} else if quota_fenced {
|
||||
rustfs_io_metrics::ECSTORE_RENAME_RPC_KIND_QUOTA_FENCE
|
||||
} else if incarnation_bound {
|
||||
rustfs_io_metrics::ECSTORE_RENAME_RPC_KIND_INCARNATION
|
||||
} else if scanner_publication_lease_token.is_some() {
|
||||
rustfs_io_metrics::ECSTORE_RENAME_RPC_KIND_SCANNER_LEASE
|
||||
} else {
|
||||
rustfs_io_metrics::ECSTORE_RENAME_RPC_KIND_ORDINARY
|
||||
};
|
||||
rustfs_io_metrics::record_ecstore_rename_remote_rpc(rpc_kind);
|
||||
let rpc_started = rustfs_io_metrics::put_stage_timer();
|
||||
let mut retried_dual_write = false;
|
||||
let response = loop {
|
||||
@@ -2958,6 +3416,7 @@ impl RemoteDisk {
|
||||
rustfs_io_metrics::PUT_STAGE_SET_DISK_RENAME_REMOTE_CLIENT_PREPARE,
|
||||
attempt_prepare_started,
|
||||
);
|
||||
rename_admission_guard.mark_dispatched();
|
||||
let result = rustfs_io_metrics::observe_put_stage_future(
|
||||
async {
|
||||
if multipart_rename {
|
||||
@@ -2988,6 +3447,7 @@ impl RemoteDisk {
|
||||
Err(status) => return Err(status.into()),
|
||||
}
|
||||
};
|
||||
rename_admission_guard.complete();
|
||||
let response_process_started = rustfs_io_metrics::put_stage_timer();
|
||||
let response_headers_started = rustfs_io_metrics::put_stage_timer();
|
||||
let _ = response.metadata().len();
|
||||
@@ -12963,6 +13423,127 @@ mod tests {
|
||||
.expect("shared gate remains open");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rename_admission_is_weighted_shared_and_released_per_item() {
|
||||
use std::future::Future;
|
||||
use std::task::{Context, Poll, Waker};
|
||||
|
||||
let first = peer_rename_admission("http://rename-peer-a", true).expect("enabled rename gate");
|
||||
let same = peer_rename_admission("http://rename-peer-a", true).expect("same peer rename gate");
|
||||
let other = peer_rename_admission("http://rename-peer-b", true).expect("other peer rename gate");
|
||||
assert!(Arc::ptr_eq(&first, &same));
|
||||
assert!(!Arc::ptr_eq(&first, &other));
|
||||
assert!(peer_rename_admission("http://rename-disabled", false).is_none());
|
||||
assert_eq!(first.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
|
||||
|
||||
let permit = Arc::clone(&first)
|
||||
.acquire_many_owned(4)
|
||||
.await
|
||||
.expect("weighted batch admission");
|
||||
let mut grant = RenameAdmissionGrant {
|
||||
permit: Some(permit),
|
||||
batch: true,
|
||||
};
|
||||
assert_eq!(first.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
|
||||
assert!(grant.release_one());
|
||||
assert_eq!(first.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3);
|
||||
drop(grant);
|
||||
assert_eq!(first.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
|
||||
|
||||
let held = Arc::clone(&first)
|
||||
.acquire_many_owned(u32::try_from(rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 3).expect("small limit"))
|
||||
.await
|
||||
.expect("reserve all but three permits");
|
||||
let mut waiting = Box::pin(Arc::clone(&same).acquire_many_owned(4));
|
||||
assert!(matches!(waiting.as_mut().poll(&mut Context::from_waker(Waker::noop())), Poll::Pending));
|
||||
assert_eq!(first.available_permits(), 0, "the FIFO waiter reserves currently available permits");
|
||||
drop(waiting);
|
||||
assert_eq!(
|
||||
first.available_permits(),
|
||||
3,
|
||||
"cancelling a queued weighted acquire must return its reservation"
|
||||
);
|
||||
let waiting = Box::pin(Arc::clone(&same).acquire_many_owned(4));
|
||||
drop(held);
|
||||
let acquired = tokio::time::timeout(Duration::from_secs(1), waiting)
|
||||
.await
|
||||
.expect("weighted waiter wakes")
|
||||
.expect("rename gate remains open");
|
||||
drop(acquired);
|
||||
assert_eq!(first.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn rename_admission_quarantine_holds_until_absolute_deadline() {
|
||||
let gate = peer_rename_admission("http://rename-quarantine-peer", true).expect("enabled rename gate");
|
||||
let permit = Arc::clone(&gate)
|
||||
.acquire_many_owned(4)
|
||||
.await
|
||||
.expect("weighted batch admission");
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
|
||||
RenameAdmissionGrant {
|
||||
permit: Some(permit),
|
||||
batch: true,
|
||||
}
|
||||
.quarantine_until(deadline);
|
||||
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
|
||||
|
||||
tokio::time::advance(Duration::from_millis(999)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
|
||||
tokio::time::advance(Duration::from_millis(1)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn rename_call_guard_quarantines_only_after_dispatch() {
|
||||
let gate = peer_rename_admission("http://rename-call-guard-peer", true).expect("enabled rename gate");
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(1);
|
||||
let permit = Arc::clone(&gate).acquire_many_owned(4).await.expect("pre-dispatch permits");
|
||||
drop(RenameBatchCallGuard {
|
||||
admission: Some(RenameAdmissionGrant {
|
||||
permit: Some(permit),
|
||||
batch: true,
|
||||
}),
|
||||
deadline,
|
||||
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
|
||||
});
|
||||
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
|
||||
|
||||
let permit = Arc::clone(&gate).acquire_many_owned(4).await.expect("dispatched permits");
|
||||
let mut guard = RenameBatchCallGuard {
|
||||
admission: Some(RenameAdmissionGrant {
|
||||
permit: Some(permit),
|
||||
batch: true,
|
||||
}),
|
||||
deadline,
|
||||
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
|
||||
};
|
||||
guard.mark_dispatched();
|
||||
drop(guard);
|
||||
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT - 4);
|
||||
tokio::time::advance(Duration::from_secs(1)).await;
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
|
||||
|
||||
let permit = Arc::clone(&gate)
|
||||
.acquire_many_owned(4)
|
||||
.await
|
||||
.expect("proven pre-mutation permits");
|
||||
let mut guard = RenameBatchCallGuard {
|
||||
admission: Some(RenameAdmissionGrant {
|
||||
permit: Some(permit),
|
||||
batch: true,
|
||||
}),
|
||||
deadline,
|
||||
dispatch_state: RenameAdmissionDispatchState::NotDispatched,
|
||||
};
|
||||
guard.mark_dispatched();
|
||||
guard.release_without_quarantine();
|
||||
assert_eq!(gate.available_permits(), rustfs_protos::INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_disk_builds_optional_complete_body_gate_from_configuration() {
|
||||
temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, Some("3"))], async {
|
||||
|
||||
@@ -12378,6 +12378,7 @@ struct DecommissionCapacityLockOrderBarrierState {
|
||||
external_heal_target_lock_attempted: tokio::sync::Notify,
|
||||
target_gate_retry_entered: tokio::sync::Notify,
|
||||
target_gate_retry_entries: AtomicUsize,
|
||||
target_gate_retry_pause: std::sync::OnceLock<tokio::sync::Semaphore>,
|
||||
target_gate_inline_retry_entered: tokio::sync::Notify,
|
||||
target_gate_inline_retry_entries: AtomicUsize,
|
||||
target_gate_exact_reloads: AtomicUsize,
|
||||
@@ -12425,6 +12426,7 @@ impl DecommissionCapacityLockOrderBarrier {
|
||||
external_heal_target_lock_attempted: tokio::sync::Notify::new(),
|
||||
target_gate_retry_entered: tokio::sync::Notify::new(),
|
||||
target_gate_retry_entries: AtomicUsize::new(0),
|
||||
target_gate_retry_pause: std::sync::OnceLock::new(),
|
||||
target_gate_inline_retry_entered: tokio::sync::Notify::new(),
|
||||
target_gate_inline_retry_entries: AtomicUsize::new(0),
|
||||
target_gate_exact_reloads: AtomicUsize::new(0),
|
||||
@@ -12520,6 +12522,13 @@ impl DecommissionCapacityLockOrderBarrier {
|
||||
.expect("decommission entries should observe target gate contention");
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
pub(crate) fn pause_target_gate_retries(&self) -> &tokio::sync::Semaphore {
|
||||
self.state
|
||||
.target_gate_retry_pause
|
||||
.get_or_init(|| tokio::sync::Semaphore::new(0))
|
||||
}
|
||||
|
||||
#[cfg(feature = "test-util")]
|
||||
pub(crate) fn target_gate_inline_retries(&self) -> usize {
|
||||
self.state.target_gate_inline_retry_entries.load(Ordering::Acquire)
|
||||
@@ -12630,6 +12639,9 @@ impl DecommissionCapacityLockOrderBarrier {
|
||||
#[cfg(test)]
|
||||
impl Drop for DecommissionCapacityLockOrderBarrier {
|
||||
fn drop(&mut self) {
|
||||
if let Some(pause) = self.state.target_gate_retry_pause.get() {
|
||||
pause.close();
|
||||
}
|
||||
self.state.owner_release.notify_one();
|
||||
self.state.external_object_capacity_probe_release.notify_one();
|
||||
self.state.external_object_commit_phase_release.notify_one();
|
||||
@@ -12758,7 +12770,7 @@ async fn pause_decommission_cancel_target_timeout(store_id: uuid::Uuid) {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn notify_decommission_target_gate_retry(store_id: uuid::Uuid) {
|
||||
async fn observe_decommission_target_gate_retry(store_id: uuid::Uuid) {
|
||||
let barrier = DECOMMISSION_CAPACITY_LOCK_ORDER_BARRIER
|
||||
.get_or_init(|| std::sync::Mutex::new(None))
|
||||
.lock()
|
||||
@@ -12769,6 +12781,11 @@ fn notify_decommission_target_gate_retry(store_id: uuid::Uuid) {
|
||||
if let Some(barrier) = barrier {
|
||||
barrier.target_gate_retry_entries.fetch_add(1, Ordering::AcqRel);
|
||||
barrier.target_gate_retry_entered.notify_one();
|
||||
if let Some(pause) = barrier.target_gate_retry_pause.get()
|
||||
&& let Ok(permit) = pause.acquire().await
|
||||
{
|
||||
permit.forget();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17638,7 +17655,7 @@ impl ECStore {
|
||||
target_busy_attempt: usize,
|
||||
) -> Result<Option<DecommissionCapacityTargetPermit>> {
|
||||
#[cfg(test)]
|
||||
notify_decommission_target_gate_retry(self.id);
|
||||
observe_decommission_target_gate_retry(self.id).await;
|
||||
let mut wait_attempt = target_busy_attempt;
|
||||
let target_guard = loop {
|
||||
let retry_delay =
|
||||
|
||||
@@ -8360,13 +8360,16 @@ mod decommission_lock_order_tests {
|
||||
.await
|
||||
.expect("hold the target gate before starting both waiters");
|
||||
let retry_observer = DecommissionCapacityLockOrderBarrier::install(other_store.id, other_store.id);
|
||||
// Both workers must observe the original gate as busy, but slow disk I/O
|
||||
// in the holder or first waiter must not consume the second waiter's retry budget.
|
||||
let retry_pause = retry_observer.pause_target_gate_retries();
|
||||
|
||||
let mut workers = Vec::new();
|
||||
let mut workers = tokio::task::JoinSet::new();
|
||||
for object in objects {
|
||||
let worker_store = Arc::clone(&other_store);
|
||||
let worker_bucket = bucket.clone();
|
||||
let source_set = other_store.pools[0].get_disks_by_key(object);
|
||||
workers.push(tokio::spawn(async move {
|
||||
workers.spawn(async move {
|
||||
worker_store
|
||||
.decommission_entry_for_test(
|
||||
0,
|
||||
@@ -8378,7 +8381,7 @@ mod decommission_lock_order_tests {
|
||||
source_set,
|
||||
)
|
||||
.await
|
||||
}));
|
||||
});
|
||||
}
|
||||
retry_observer.wait_until_target_gate_retries(2).await;
|
||||
assert_eq!(
|
||||
@@ -8425,6 +8428,7 @@ mod decommission_lock_order_tests {
|
||||
);
|
||||
|
||||
drop(target_guard);
|
||||
retry_pause.add_permits(1);
|
||||
retry_observer.wait_until_owner_paused().await;
|
||||
assert_eq!(
|
||||
retry_observer.target_gate_exact_reloads(),
|
||||
@@ -8443,6 +8447,13 @@ mod decommission_lock_order_tests {
|
||||
.expect("a pinned waiter must not hold the alternate target gate");
|
||||
drop(alternate_probe);
|
||||
retry_observer.release_owner();
|
||||
tokio::time::timeout(Duration::from_secs(30), workers.join_next())
|
||||
.await
|
||||
.expect("the pinned waiter should finish before the other retries")
|
||||
.expect("the pinned waiter must exist")
|
||||
.expect("the pinned waiter task should not panic")
|
||||
.expect("the pinned waiter migration should succeed");
|
||||
retry_pause.add_permits(1);
|
||||
retry_observer.wait_until_owner_paused().await;
|
||||
assert_eq!(
|
||||
retry_observer.target_gate_exact_reloads(),
|
||||
@@ -8462,13 +8473,12 @@ mod decommission_lock_order_tests {
|
||||
drop(original_probe);
|
||||
retry_observer.release_owner();
|
||||
|
||||
for worker in workers {
|
||||
tokio::time::timeout(Duration::from_secs(30), worker)
|
||||
.await
|
||||
.expect("same-target waiter should finish after permit transfer")
|
||||
.expect("same-target waiter task should not panic")
|
||||
.expect("same-target waiter migration should succeed");
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(30), workers.join_next())
|
||||
.await
|
||||
.expect("the reselected waiter should finish after permit transfer")
|
||||
.expect("the reselected waiter must exist")
|
||||
.expect("the reselected waiter task should not panic")
|
||||
.expect("the reselected waiter migration should succeed");
|
||||
assert_eq!(
|
||||
retry_observer.target_gate_exact_reloads(),
|
||||
2,
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
use crate::disk::cleanup_runtime;
|
||||
use crate::disk::io_admission::{
|
||||
AdmissionReader, BoxedChunkReader, DiskIoAdmission, DiskIoClass, DiskIoContext, current_disk_io_context,
|
||||
current_resource_unit, with_disk_io_context, with_disk_io_permit, with_optional_resource_unit,
|
||||
current_resource_unit, with_detached_disk_io_context, with_disk_io_context, with_disk_io_permit, with_optional_resource_unit,
|
||||
};
|
||||
use crate::disk::{
|
||||
CheckPartsResp, DataDirDeleteStatus, DeleteOptions, DiskAPI, DiskError, DiskInfo, DiskInfoOptions, DiskLocation, Endpoint,
|
||||
@@ -479,10 +479,13 @@ where
|
||||
if external_guard.is_none() {
|
||||
return operation().await;
|
||||
}
|
||||
tokio::spawn(with_optional_resource_unit(current_resource_unit(), async move {
|
||||
let _external_guard = external_guard;
|
||||
operation().await
|
||||
}))
|
||||
tokio::spawn(with_optional_resource_unit(
|
||||
current_resource_unit(),
|
||||
with_detached_disk_io_context(async move {
|
||||
let _external_guard = external_guard;
|
||||
operation().await
|
||||
}),
|
||||
))
|
||||
.await
|
||||
.map_err(|_| Error::other("owned mutation task failed"))?
|
||||
}
|
||||
@@ -1828,6 +1831,7 @@ impl LocalDiskWrapper {
|
||||
current_disk_io_context().unwrap_or_else(|| DiskIoContext {
|
||||
class: DiskIoClass::Foreground,
|
||||
cancellation: CancellationToken::new(),
|
||||
admission_deadline: None,
|
||||
admission: None,
|
||||
permit: None,
|
||||
resource_unit: current_resource_unit(),
|
||||
@@ -1870,10 +1874,10 @@ impl LocalDiskWrapper {
|
||||
|
||||
async fn acquire_disk_io_permit(&self) -> Result<Option<crate::disk::io_admission::DiskIoPermit>> {
|
||||
if let Some(context) = current_disk_io_context() {
|
||||
if let Some(permit) = context.permit
|
||||
if let Some(permit) = context.permit.as_ref()
|
||||
&& permit.is_for(&self.io_admission)
|
||||
{
|
||||
return Ok(Some(permit));
|
||||
return Ok(Some(permit.clone()));
|
||||
}
|
||||
if context
|
||||
.admission
|
||||
@@ -1883,9 +1887,8 @@ impl LocalDiskWrapper {
|
||||
return Ok(None);
|
||||
}
|
||||
if context.class == DiskIoClass::Background {
|
||||
return self
|
||||
.io_admission
|
||||
.background(&context.cancellation)
|
||||
return context
|
||||
.background_permit(&self.io_admission)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(DiskError::Io);
|
||||
@@ -4409,6 +4412,29 @@ mod tests {
|
||||
assert!(matches!(wrapper.read_all(volume, &body_path).await, Err(DiskError::FileNotFound)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn owned_mutation_retains_background_class_without_waiter_cancellation() {
|
||||
let cancellation = CancellationToken::new();
|
||||
let caller = cancellation.clone();
|
||||
let guard: Arc<dyn Send + Sync> = Arc::new(());
|
||||
crate::disk::with_background_disk_io(
|
||||
cancellation,
|
||||
run_owned_mutation(Some(guard), move || async move {
|
||||
caller.cancel();
|
||||
let context = current_disk_io_context().expect("publication owner retains background class");
|
||||
assert_eq!(context.class, DiskIoClass::Background);
|
||||
assert!(!context.cancellation.is_cancelled(), "waiter cancellation must not interrupt publication");
|
||||
assert!(
|
||||
context.admission_deadline.is_some(),
|
||||
"queued publication must retain a bounded admission lifetime"
|
||||
);
|
||||
Ok(())
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect("owned publication completes");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn owned_mutation_keeps_publication_guard_after_waiter_cancellation() {
|
||||
use rustfs_concurrency::adaptive::AdaptiveAdmission;
|
||||
|
||||
@@ -161,11 +161,24 @@ pub(crate) enum DiskIoClass {
|
||||
pub(crate) struct DiskIoContext {
|
||||
pub(crate) class: DiskIoClass,
|
||||
pub(crate) cancellation: CancellationToken,
|
||||
pub(crate) admission_deadline: Option<Instant>,
|
||||
pub(crate) admission: Option<Arc<DiskIoAdmission>>,
|
||||
pub(crate) permit: Option<DiskIoPermit>,
|
||||
pub(crate) resource_unit: Option<ResourceIoUnit>,
|
||||
}
|
||||
|
||||
impl DiskIoContext {
|
||||
pub(crate) async fn background_permit(&self, admission: &Arc<DiskIoAdmission>) -> io::Result<DiskIoPermit> {
|
||||
let acquire = admission.background_with_resource(&self.cancellation, self.resource_unit.clone());
|
||||
match self.admission_deadline {
|
||||
Some(deadline) => tokio::time::timeout_at(deadline, acquire)
|
||||
.await
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "owned background disk admission timed out"))?,
|
||||
None => acquire.await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark disk I/O issued by `future` as background work for local-disk admission.
|
||||
#[doc(hidden)]
|
||||
pub async fn with_background_disk_io<F: Future>(cancellation: CancellationToken, future: F) -> F::Output {
|
||||
@@ -173,6 +186,7 @@ pub async fn with_background_disk_io<F: Future>(cancellation: CancellationToken,
|
||||
DiskIoContext {
|
||||
class: DiskIoClass::Background,
|
||||
cancellation,
|
||||
admission_deadline: None,
|
||||
admission: None,
|
||||
permit: None,
|
||||
resource_unit: current_resource_unit(),
|
||||
@@ -245,6 +259,7 @@ pub(crate) async fn with_disk_io_permit<F: Future>(permit: Option<DiskIoPermit>,
|
||||
let mut context = current_disk_io_context().unwrap_or_else(|| DiskIoContext {
|
||||
class: DiskIoClass::Foreground,
|
||||
cancellation: CancellationToken::new(),
|
||||
admission_deadline: None,
|
||||
admission: None,
|
||||
permit: None,
|
||||
resource_unit: None,
|
||||
@@ -279,6 +294,34 @@ pub(crate) fn with_optional_disk_io_context<F: Future>(
|
||||
}
|
||||
}
|
||||
|
||||
/// An owned commit outlives its waiter. Retain an outer I/O class and physical
|
||||
/// ownership, but give admission its own cancellation lifetime. Leave per-disk
|
||||
/// scopes to the caller's existing ownership handoff: inheriting their class
|
||||
/// without a lease could wait behind the parent awaiting this commit.
|
||||
/// The drive timeout bounds only queued admission; an admitted mutation still
|
||||
/// drains to completion. Nested owners retain the original admission deadline.
|
||||
pub(crate) fn with_detached_disk_io_context<F: Future>(future: F) -> impl Future<Output = F::Output> {
|
||||
let context = current_disk_io_context()
|
||||
.filter(|context| context.admission.is_none() && context.permit.is_none())
|
||||
.map(|mut context| {
|
||||
context.cancellation = CancellationToken::new();
|
||||
let timeout = super::disk_store::get_max_timeout_duration();
|
||||
if context.class == DiskIoClass::Background
|
||||
&& !timeout.is_zero()
|
||||
&& let Some(deadline) = Instant::now().checked_add(timeout)
|
||||
{
|
||||
context.admission_deadline = Some(context.admission_deadline.map_or(deadline, |old| old.min(deadline)));
|
||||
}
|
||||
context
|
||||
});
|
||||
async move {
|
||||
match context {
|
||||
Some(context) => with_disk_io_context(context, future).await,
|
||||
None => future.await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn current_disk_io_context() -> Option<DiskIoContext> {
|
||||
DISK_IO_CONTEXT
|
||||
.try_with(|context| {
|
||||
@@ -297,17 +340,17 @@ pub(crate) async fn acquire_context_disk_io_permit() -> io::Result<Option<DiskIo
|
||||
let Some(context) = current_disk_io_context() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(admission) = context.admission else {
|
||||
let Some(admission) = context.admission.as_ref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if let Some(permit) = context.permit
|
||||
&& permit.is_for(&admission)
|
||||
if let Some(permit) = context.permit.as_ref()
|
||||
&& permit.is_for(admission)
|
||||
{
|
||||
return Ok(Some(permit));
|
||||
return Ok(Some(permit.clone()));
|
||||
}
|
||||
match context.class {
|
||||
DiskIoClass::Foreground => Ok(Some(admission.foreground())),
|
||||
DiskIoClass::Background => Ok(Some(admission.background(&context.cancellation).await?)),
|
||||
DiskIoClass::Background => Ok(Some(context.background_permit(admission).await?)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -381,6 +424,7 @@ impl DiskIoAdmission {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn background(self: &Arc<Self>, cancellation: &CancellationToken) -> std::io::Result<DiskIoPermit> {
|
||||
self.background_with_resource(cancellation, current_resource_unit()).await
|
||||
}
|
||||
@@ -663,11 +707,8 @@ impl<R> AdmissionReader<R> {
|
||||
let mut wait = self.wait.lock().unwrap_or_else(|error| error.into_inner());
|
||||
if wait.is_none() {
|
||||
let admission = self.admission.clone();
|
||||
let cancellation = self.context.cancellation.clone();
|
||||
let resource_unit = self.context.resource_unit.clone();
|
||||
*wait = Some(Box::pin(
|
||||
async move { admission.background_with_resource(&cancellation, resource_unit).await },
|
||||
));
|
||||
let context = self.context.clone();
|
||||
*wait = Some(Box::pin(async move { context.background_permit(&admission).await }));
|
||||
}
|
||||
let Some(wait_future) = wait.as_mut() else {
|
||||
return Poll::Ready(Err(io::Error::other("background disk I/O admission waiter is missing")));
|
||||
@@ -909,6 +950,7 @@ mod tests {
|
||||
let existing = DiskIoContext {
|
||||
class: DiskIoClass::Foreground,
|
||||
cancellation: cancellation.clone(),
|
||||
admission_deadline: None,
|
||||
admission: None,
|
||||
permit: None,
|
||||
resource_unit: None,
|
||||
@@ -954,6 +996,94 @@ mod tests {
|
||||
assert_eq!(gate.snapshot().active, 0);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn detached_commit_keeps_background_admission_after_waiter_cancellation() {
|
||||
let admission = DiskIoAdmission::new("detached-commit".to_string());
|
||||
let foreground = admission.foreground();
|
||||
let cancellation = CancellationToken::new();
|
||||
let worker_admission = admission.clone();
|
||||
with_background_disk_io(cancellation.clone(), async {
|
||||
let worker = tokio::spawn(with_detached_disk_io_context(async move {
|
||||
let context = current_disk_io_context().expect("owned commit retains its class");
|
||||
assert_eq!(context.class, DiskIoClass::Background);
|
||||
context.background_permit(&worker_admission).await
|
||||
}));
|
||||
wait_for_background_waiters(&admission, 1).await;
|
||||
cancellation.cancel();
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!worker.is_finished(), "caller cancellation must not abandon a queued commit");
|
||||
drop(foreground);
|
||||
let permit = tokio::time::timeout(Duration::from_secs(1), worker)
|
||||
.await
|
||||
.expect("commit admission should finish after foreground work")
|
||||
.expect("owned worker joins")
|
||||
.expect("owned commit survives waiter cancellation");
|
||||
assert_eq!(admission.background_admissions_for_tests(), 1);
|
||||
drop(permit);
|
||||
})
|
||||
.await;
|
||||
assert!(!admission.background_active_for_tests());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detached_commit_does_not_inherit_a_parent_disk_lease() {
|
||||
let admission = DiskIoAdmission::new("parent-lease".to_string());
|
||||
let cancellation = CancellationToken::new();
|
||||
let permit = admission.background(&cancellation).await.expect("parent disk admission");
|
||||
with_background_disk_io(
|
||||
cancellation,
|
||||
with_disk_io_permit(Some(permit), async {
|
||||
tokio::spawn(with_detached_disk_io_context(async {
|
||||
assert!(current_disk_io_context().is_none(), "do not queue behind the parent's disk lease");
|
||||
}))
|
||||
.await
|
||||
.expect("resource-only commit joins while parent keeps its disk lease");
|
||||
assert!(admission.background_active_for_tests());
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert!(!admission.background_active_for_tests());
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn detached_commit_bounds_queued_admission_without_extending_an_existing_deadline() {
|
||||
let admission = DiskIoAdmission::new("stalled-background-disk");
|
||||
let held = admission
|
||||
.background(&CancellationToken::new())
|
||||
.await
|
||||
.expect("existing native I/O");
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
let worker_admission = admission.clone();
|
||||
let error = with_background_disk_io(CancellationToken::new(), async {
|
||||
let mut context = current_disk_io_context().expect("background scope");
|
||||
context.admission_deadline = Some(deadline);
|
||||
with_disk_io_context(context, async {
|
||||
let worker = tokio::spawn(with_detached_disk_io_context(async move {
|
||||
let context = current_disk_io_context().expect("owned scope");
|
||||
assert_eq!(
|
||||
context.admission_deadline,
|
||||
Some(deadline),
|
||||
"nested ownership must not reset admission time"
|
||||
);
|
||||
context.background_permit(&worker_admission).await
|
||||
}));
|
||||
wait_for_background_waiters(&admission, 1).await;
|
||||
tokio::time::advance(Duration::from_secs(2)).await;
|
||||
worker
|
||||
.await
|
||||
.expect("owned admission worker")
|
||||
.expect_err("stalled disk must not retain queued commit")
|
||||
})
|
||||
.await
|
||||
})
|
||||
.await;
|
||||
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
|
||||
assert_eq!(admission.background_waiters.load(Ordering::Acquire), 0);
|
||||
assert!(admission.background_active_for_tests(), "timeout must not interrupt admitted native I/O");
|
||||
drop(held);
|
||||
assert!(!admission.background_active_for_tests());
|
||||
}
|
||||
|
||||
struct BlockingWorker(tokio::task::JoinHandle<()>);
|
||||
|
||||
async fn wait_for_background_waiters(admission: &DiskIoAdmission, expected: usize) {
|
||||
@@ -1072,6 +1202,7 @@ mod tests {
|
||||
DiskIoContext {
|
||||
class: DiskIoClass::Foreground,
|
||||
cancellation: CancellationToken::new(),
|
||||
admission_deadline: None,
|
||||
admission: None,
|
||||
permit: None,
|
||||
resource_unit: None,
|
||||
|
||||
@@ -79,12 +79,21 @@ impl BackgroundMemoryBudget {
|
||||
pub(crate) fn reserve(self: &Arc<Self>, bytes: usize) -> io::Result<Reservation> {
|
||||
let bytes = u64::try_from(bytes).map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?;
|
||||
let mut state = self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let used = state
|
||||
.used
|
||||
.checked_add(bytes)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::WouldBlock, BackgroundMemoryExhausted))?;
|
||||
if bytes != 0 && (Instant::now() >= state.valid_until || used > state.limit) {
|
||||
return Err(io::Error::new(io::ErrorKind::WouldBlock, BackgroundMemoryExhausted));
|
||||
let expired = Instant::now() >= state.valid_until;
|
||||
let exhausted = || {
|
||||
io::Error::new(
|
||||
io::ErrorKind::WouldBlock,
|
||||
BackgroundMemoryExhausted {
|
||||
requested: bytes,
|
||||
used: state.used,
|
||||
limit: state.limit,
|
||||
expired,
|
||||
},
|
||||
)
|
||||
};
|
||||
let used = state.used.checked_add(bytes).ok_or_else(exhausted)?;
|
||||
if bytes != 0 && (expired || used > state.limit) {
|
||||
return Err(exhausted());
|
||||
}
|
||||
state.used = used;
|
||||
Ok(Reservation {
|
||||
@@ -95,11 +104,20 @@ impl BackgroundMemoryBudget {
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct BackgroundMemoryExhausted;
|
||||
struct BackgroundMemoryExhausted {
|
||||
requested: u64,
|
||||
used: u64,
|
||||
limit: u64,
|
||||
expired: bool,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for BackgroundMemoryExhausted {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("background buffer memory budget exhausted")
|
||||
write!(
|
||||
formatter,
|
||||
"background buffer memory budget exhausted (requested={}, used={}, limit={}, expired={})",
|
||||
self.requested, self.used, self.limit, self.expired,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -321,6 +339,31 @@ impl io::Write for BackgroundEncodeBuffer {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn rejected_reservation_reports_capacity_and_expiration_without_charging() {
|
||||
let owner = BackgroundMemoryBudget::new();
|
||||
owner.set_sampled_limit(64, Duration::from_secs(3));
|
||||
let held = owner.reserve(32).expect("initial reservation fits");
|
||||
let error = owner.reserve(33).err().expect("one byte over remaining capacity");
|
||||
assert!(is_memory_pressure(&error));
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"background buffer memory budget exhausted (requested=33, used=32, limit=64, expired=false)"
|
||||
);
|
||||
assert_eq!(owner.snapshot().used, 32);
|
||||
|
||||
tokio::time::advance(Duration::from_secs(3)).await;
|
||||
let error = owner.reserve(1).err().expect("expired lease rejects a fitting request");
|
||||
assert!(is_memory_pressure(&error));
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"background buffer memory budget exhausted (requested=1, used=32, limit=64, expired=true)"
|
||||
);
|
||||
assert_eq!(owner.snapshot().used, 32);
|
||||
drop(held);
|
||||
assert_eq!(owner.snapshot().used, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_buffer_growth_retains_both_allocations_and_the_last_slice() {
|
||||
use std::io::Write;
|
||||
|
||||
@@ -140,6 +140,28 @@ pub(crate) fn admit(binding: &PhysicalDiskBinding) -> io::Result<()> {
|
||||
.unwrap_or(Ok(()))
|
||||
}
|
||||
|
||||
/// Wait only at the namespace RPC entry, before storage locks or native I/O.
|
||||
/// The caller owns the deadline; dropping this future releases its queue turn.
|
||||
pub(crate) async fn admit_scanner_preflight(binding: &PhysicalDiskBinding) -> io::Result<()> {
|
||||
let node = REMOTE_RESOURCES
|
||||
.try_with(|context| context.admitted.borrow().is_none().then(|| context.node.clone()))
|
||||
.ok()
|
||||
.flatten();
|
||||
let Some(node) = node else {
|
||||
return admit(binding);
|
||||
};
|
||||
let deferred = || io::Error::from(io::ErrorKind::WouldBlock);
|
||||
let plan = binding.plan().ok_or_else(deferred)?;
|
||||
let permit = plan.acquire(&node).await.ok_or_else(deferred)?;
|
||||
REMOTE_RESOURCES.with(|context| {
|
||||
let mut admitted = context.admitted.borrow_mut();
|
||||
if admitted.is_none() {
|
||||
*admitted = Some(permit);
|
||||
}
|
||||
});
|
||||
admit(binding)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -162,6 +184,76 @@ mod tests {
|
||||
node
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn scanner_preflight_cancellation_and_timeout_release_queued_capacity() {
|
||||
let node = node();
|
||||
let gate = AdaptiveAdmission::new(NonZeroU16::MIN, 1);
|
||||
let binding = PhysicalDiskBinding::default();
|
||||
binding.set_test_capacity(vec![gate.clone()]).expect("device plan");
|
||||
for deadline in [false, true] {
|
||||
let held = gate.try_acquire().expect("concurrent disk operation");
|
||||
with_remote_background_io(Some(RemoteBackgroundIo::new(node.clone())), async {
|
||||
let mut wait = Box::pin(admit_scanner_preflight(&binding));
|
||||
assert!(futures_util::poll!(&mut wait).is_pending());
|
||||
assert_eq!(node.snapshot().active, 0, "queued disk work cannot reserve node capacity");
|
||||
if deadline {
|
||||
assert!(tokio::time::timeout(std::time::Duration::from_secs(1), wait).await.is_err());
|
||||
} else {
|
||||
drop(wait);
|
||||
}
|
||||
drop(held);
|
||||
admit(&binding).expect("cancelled queue turn cannot block the immediate path");
|
||||
})
|
||||
.await;
|
||||
assert_eq!([node.snapshot().active, gate.snapshot().active], [0, 0]);
|
||||
assert_eq!([node.completed(), gate.completed()], [Some(0), Some(0)]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scanner_preflight_rejects_a_plan_replaced_while_waiting() {
|
||||
let node = node();
|
||||
let gate = AdaptiveAdmission::new(NonZeroU16::MIN, 1);
|
||||
let binding = PhysicalDiskBinding::default();
|
||||
binding.set_test_capacity(vec![gate.clone()]).expect("old plan");
|
||||
let held = gate.try_acquire().expect("busy disk");
|
||||
with_remote_background_io(Some(RemoteBackgroundIo::new(node.clone())), async {
|
||||
let wait = admit_scanner_preflight(&binding);
|
||||
tokio::pin!(wait);
|
||||
assert!(futures_util::poll!(&mut wait).is_pending());
|
||||
binding
|
||||
.set_test_capacity(vec![AdaptiveAdmission::new(NonZeroU16::MIN, 1)])
|
||||
.expect("new plan");
|
||||
drop(held);
|
||||
assert_eq!(wait.await.expect_err("old plan is invalid").kind(), io::ErrorKind::WouldBlock);
|
||||
assert!(resources().is_none());
|
||||
})
|
||||
.await;
|
||||
assert_eq!([node.snapshot().active, gate.snapshot().active], [0, 0]);
|
||||
assert_eq!(node.completed(), Some(0));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn scanner_preflight_never_waits_for_additional_devices_under_existing_admission() {
|
||||
let node = node();
|
||||
let first = PhysicalDiskBinding::default();
|
||||
let gate = AdaptiveAdmission::new(NonZeroU16::MIN, 1);
|
||||
first.set_test_capacity(vec![gate.clone()]).expect("first plan");
|
||||
let other = PhysicalDiskBinding::default();
|
||||
other
|
||||
.set_test_capacity(vec![AdaptiveAdmission::new(NonZeroU16::MIN, 0)])
|
||||
.expect("closed plan");
|
||||
with_remote_background_io(Some(RemoteBackgroundIo::new(node.clone())), async {
|
||||
admit(&first).expect("existing request admission");
|
||||
let other = admit_scanner_preflight(&other);
|
||||
tokio::pin!(other);
|
||||
assert!(matches!(futures_util::poll!(other), std::task::Poll::Ready(Err(error)) if error.kind() == io::ErrorKind::WouldBlock));
|
||||
assert_eq!([node.snapshot().active, gate.snapshot().active], [1, 1]);
|
||||
})
|
||||
.await;
|
||||
assert_eq!([node.snapshot().active, gate.snapshot().active], [0, 0]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn receiver_reuses_one_receipt_across_phases_and_releases_only_native_subsets() {
|
||||
let node = node();
|
||||
|
||||
@@ -3692,10 +3692,17 @@ pub(crate) fn has_delete_version_test_failpoints() -> bool {
|
||||
#[cfg(not(test))]
|
||||
pub(crate) fn has_delete_version_test_failpoints() -> bool {
|
||||
#[cfg(all(feature = "test-util", not(windows)))]
|
||||
if os::prepared_publication_test_hooks::has_any_hooks() {
|
||||
return true;
|
||||
let prepared_hooks = os::prepared_publication_test_hooks::has_any_hooks();
|
||||
#[cfg(not(all(feature = "test-util", not(windows))))]
|
||||
let prepared_hooks = false;
|
||||
#[cfg(feature = "e2e-test-hooks")]
|
||||
{
|
||||
prepared_hooks || std::env::var_os("RUSTFS_DELETE_RECOVERY_BARRIER_DIR").is_some()
|
||||
}
|
||||
#[cfg(not(feature = "e2e-test-hooks"))]
|
||||
{
|
||||
prepared_hooks
|
||||
}
|
||||
cfg!(feature = "e2e-test-hooks") && std::env::var_os("RUSTFS_DELETE_RECOVERY_BARRIER_DIR").is_some()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -3978,6 +3985,9 @@ enum SyncMode {
|
||||
FileOnly,
|
||||
}
|
||||
|
||||
// Keep 2 MiB of shard data plus up to 128 32-byte hashes in one file buffer.
|
||||
const SHARD_FILE_MAX_BUF_SIZE: usize = 2 * 1024 * 1024 + 4096;
|
||||
|
||||
#[allow(
|
||||
dead_code,
|
||||
reason = "reclaim bookkeeping fields written by Drop but never read back (backlog#1823)"
|
||||
@@ -4326,7 +4336,8 @@ async fn read_dir_entry_batch_with_walk_stall(
|
||||
}
|
||||
|
||||
impl FileCacheReclaimReader {
|
||||
fn new(inner: File, reclaim_offset: u64, reclaim_len: usize, reclaim_on_drop: bool, read_ahead: usize) -> Self {
|
||||
fn new(mut inner: File, reclaim_offset: u64, reclaim_len: usize, reclaim_on_drop: bool, read_ahead: usize) -> Self {
|
||||
inner.set_max_buf_size(SHARD_FILE_MAX_BUF_SIZE);
|
||||
#[cfg(target_os = "macos")]
|
||||
if reclaim_on_drop {
|
||||
let _ = set_fd_nocache(&inner);
|
||||
@@ -5216,7 +5227,8 @@ impl AsyncWrite for LazyLocalFileWriter {
|
||||
|
||||
#[cfg(test)]
|
||||
impl FileCacheReclaimWriter {
|
||||
fn new(inner: File, reclaim_len: usize, reclaim_on_shutdown: bool) -> Self {
|
||||
fn new(mut inner: File, reclaim_len: usize, reclaim_on_shutdown: bool) -> Self {
|
||||
inner.set_max_buf_size(SHARD_FILE_MAX_BUF_SIZE);
|
||||
#[cfg(target_os = "macos")]
|
||||
if reclaim_on_shutdown {
|
||||
let _ = set_fd_nocache(&inner);
|
||||
@@ -12476,9 +12488,13 @@ impl LocalDisk {
|
||||
// Files written here (format.json, ...) stay where they land — no
|
||||
// rename follows — so the new directory entry must be fsynced too.
|
||||
// System-critical volumes are pinned to strict by effective_durability;
|
||||
// only the legacy full-off switch (historical semantics) skips this.
|
||||
let durability = effective_durability(volume);
|
||||
let sync = durability.metadata_sync_mode();
|
||||
// A consumed shutdown receipt must never survive a later writer crash,
|
||||
// including when data-shard syncing is disabled.
|
||||
let sync = if volume == RUSTFS_META_BUCKET && path == super::UNCLEAN_SHUTDOWN_MARKER_PATH {
|
||||
SyncMode::FileAndDir
|
||||
} else {
|
||||
effective_durability(volume).metadata_sync_mode()
|
||||
};
|
||||
self.write_all_private(volume, path, data, sync, &volume_dir).await?;
|
||||
|
||||
Ok(())
|
||||
@@ -14742,12 +14758,38 @@ impl LocalDisk {
|
||||
}
|
||||
}
|
||||
|
||||
/// Batch positioned reads for local EC shard files in a single `spawn_blocking`.
|
||||
/// Shard windows at least this large are copy-bound: reading them concurrently
|
||||
/// beats one serial blocking pass, while smaller windows stay coalesced to save
|
||||
/// blocking-pool round trips.
|
||||
#[cfg(unix)]
|
||||
const LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES: usize = 512 * 1024;
|
||||
|
||||
/// Positioned reads for local EC shard files, returned in request order.
|
||||
///
|
||||
/// Collapses per-shard blocking-pool round-trips that dominate warm GET
|
||||
/// fan-out on single-node multi-disk topologies.
|
||||
/// Small windows share a single `spawn_blocking`, collapsing per-shard
|
||||
/// blocking-pool round-trips that dominate warm GET fan-out on single-node
|
||||
/// multi-disk topologies. When every window reaches
|
||||
/// `LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES`, each shard gets its own dispatch so
|
||||
/// copies and device reads proceed concurrently.
|
||||
#[cfg(unix)]
|
||||
pub(crate) async fn batch_shard_pread(requests: Vec<(std::path::PathBuf, usize, usize)>) -> Vec<Result<Bytes>> {
|
||||
if requests.len() < 2
|
||||
|| requests
|
||||
.iter()
|
||||
.any(|(_, _, length)| *length < LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES)
|
||||
{
|
||||
return batch_shard_pread_blocking(requests).await;
|
||||
}
|
||||
futures::future::join_all(requests.into_iter().map(|request| batch_shard_pread_blocking(vec![request])))
|
||||
.await
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Read every request in turn inside one `spawn_blocking`.
|
||||
#[cfg(unix)]
|
||||
async fn batch_shard_pread_blocking(requests: Vec<(std::path::PathBuf, usize, usize)>) -> Vec<Result<Bytes>> {
|
||||
let n = requests.len();
|
||||
let metrics = rustfs_io_metrics::LocalBatchReadMetrics::capture();
|
||||
let submitted = metrics.as_ref().map(|_| std::time::Instant::now());
|
||||
@@ -14755,7 +14797,7 @@ pub(crate) async fn batch_shard_pread(requests: Vec<(std::path::PathBuf, usize,
|
||||
let diagnostic = crate::diagnostics::batch_read_diagnostics::Sample::capture();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
use rustfs_io_metrics::LocalBatchReadStage;
|
||||
use std::os::unix::fs::{FileExt, OpenOptionsExt};
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
|
||||
// The disabled build expands directly to the original operation.
|
||||
macro_rules! diagnostic_stage {
|
||||
@@ -14823,25 +14865,48 @@ pub(crate) async fn batch_shard_pread(requests: Vec<(std::path::PathBuf, usize,
|
||||
metrics.as_deref(),
|
||||
LocalBatchReadStage::Read,
|
||||
|| {
|
||||
if offset == 0 {
|
||||
use std::io::Read as _;
|
||||
total = (&file)
|
||||
.take(u64::try_from(length).unwrap_or(u64::MAX))
|
||||
.read_to_end(&mut buf)
|
||||
.map_err(DiskError::from)?;
|
||||
if total < length {
|
||||
// Preload the requested window before reading it. Kernel
|
||||
// readahead is advisory and may still extend past the
|
||||
// window, so the tail is reclaimed after the read below.
|
||||
#[cfg(target_os = "linux")]
|
||||
if let (Ok(start), Ok(len)) = (u64::try_from(offset), u64::try_from(length)) {
|
||||
let _ = rustix::fs::fadvise(
|
||||
&file,
|
||||
start,
|
||||
std::num::NonZeroU64::new(len),
|
||||
rustix::fs::Advice::WillNeed,
|
||||
);
|
||||
}
|
||||
// `with_capacity` reserves exactly `length` bytes, so each
|
||||
// positioned read fills only the remaining requested span
|
||||
// without zero-initializing it first.
|
||||
while total < length {
|
||||
let position = u64::try_from(offset + total).map_err(|_| DiskError::FileCorrupt)?;
|
||||
let nbytes = match rustix::io::pread(&file, rustix::buffer::spare_capacity(&mut buf), position) {
|
||||
Ok(nbytes) => nbytes,
|
||||
Err(rustix::io::Errno::INTR) => continue,
|
||||
Err(err) => return Err(DiskError::from(std::io::Error::from(err))),
|
||||
};
|
||||
if nbytes == 0 {
|
||||
return Err(DiskError::FileCorrupt);
|
||||
}
|
||||
} else {
|
||||
buf.resize(length, 0);
|
||||
while total < length {
|
||||
let nbytes = file
|
||||
.read_at(&mut buf[total..], u64::try_from(offset + total).unwrap_or(u64::MAX))
|
||||
.map_err(DiskError::from)?;
|
||||
if nbytes == 0 {
|
||||
return Err(DiskError::FileCorrupt);
|
||||
}
|
||||
total += nbytes;
|
||||
total += nbytes;
|
||||
}
|
||||
// Keep a cold shard window from evicting unrelated data
|
||||
// when the kernel over-reads. The requested tail page is
|
||||
// retained because its final bytes may share a page with
|
||||
// the readahead range.
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Ok(page) = mmap_page_size() {
|
||||
let aligned_end = end
|
||||
.checked_add(page.saturating_sub(1))
|
||||
.map(|value| value / page * page)
|
||||
.unwrap_or(end);
|
||||
if aligned_end < meta.len()
|
||||
&& let Some(reclaim_len) = std::num::NonZeroU64::new(meta.len() - aligned_end)
|
||||
{
|
||||
let _ =
|
||||
rustix::fs::fadvise(&file, aligned_end, Some(reclaim_len), rustix::fs::Advice::DontNeed);
|
||||
}
|
||||
}
|
||||
Ok::<_, DiskError>(())
|
||||
@@ -15448,6 +15513,14 @@ impl DiskAPI for LocalDisk {
|
||||
)
|
||||
.map_err(DiskError::from)?;
|
||||
fi.validate(ValidationMode::RequireErasure)?;
|
||||
let frame_size = crate::object_api::persisted_ec_read_quantum(
|
||||
&fi.metadata,
|
||||
codec_erasure.block_size,
|
||||
codec_erasure.data_shards,
|
||||
codec_erasure.shard_size(),
|
||||
)
|
||||
.map_err(|_| DiskError::FileCorrupt)?
|
||||
.unwrap_or_else(|| codec_erasure.shard_size());
|
||||
for (i, part) in fi.parts.iter().enumerate() {
|
||||
let checksum_info = erasure.get_checksum_info(part.number);
|
||||
let checksum_algo = if fi.uses_legacy_checksum && checksum_info.algorithm == HashAlgorithm::HighwayHash256S {
|
||||
@@ -15469,7 +15542,7 @@ impl DiskAPI for LocalDisk {
|
||||
&part_path,
|
||||
codec_erasure.shard_file_size(part.size as i64) as usize,
|
||||
checksum_algo,
|
||||
codec_erasure.shard_size(),
|
||||
frame_size,
|
||||
)
|
||||
.await
|
||||
.err();
|
||||
@@ -15661,9 +15734,9 @@ impl DiskAPI for LocalDisk {
|
||||
let source_owner = self
|
||||
.multipart_source_owner(dst_volume, dst_path, true, false, usage_owner)
|
||||
.await?;
|
||||
let admission = self.multipart_source_admission(dst_volume, dst_path, true, false)?;
|
||||
let (src_volume_dir, src_file_path) = self.io_get_bucket_and_object_path(src_volume, src_path)?;
|
||||
let (dst_volume_dir, dst_file_path) = self.io_get_bucket_and_object_path(dst_volume, dst_path)?;
|
||||
let admission = self.multipart_source_admission_after_validated_part_path(dst_volume, dst_path)?;
|
||||
if !skip_access_checks(src_volume) {
|
||||
super::fs::access_std(&src_volume_dir).map_err(|err| to_access_error(err, DiskError::VolumeAccessDenied))?;
|
||||
}
|
||||
@@ -15949,29 +16022,10 @@ impl DiskAPI for LocalDisk {
|
||||
};
|
||||
|
||||
let prepare_result = (|| -> std::io::Result<(bool, bool)> {
|
||||
let old_data_absent = staging_path.join(PART_TRANSACTION_OLD_DATA_ABSENT);
|
||||
let old_meta_absent = staging_path.join(PART_TRANSACTION_OLD_META_ABSENT);
|
||||
let had_old_data = snapshot_part_transaction_file(
|
||||
&dst_file_path,
|
||||
txn_parent_fd.as_deref(),
|
||||
&staging_path.join(PART_TRANSACTION_OLD_DATA),
|
||||
txn_dir_fd.as_deref(),
|
||||
PART_TRANSACTION_OLD_DATA,
|
||||
&old_data_absent,
|
||||
PART_TRANSACTION_OLD_DATA_ABSENT,
|
||||
None,
|
||||
)?;
|
||||
let had_old_meta = snapshot_part_transaction_file(
|
||||
&dst_meta_path,
|
||||
txn_parent_fd.as_deref(),
|
||||
&staging_path.join(PART_TRANSACTION_OLD_META),
|
||||
txn_dir_fd.as_deref(),
|
||||
PART_TRANSACTION_OLD_META,
|
||||
&old_meta_absent,
|
||||
PART_TRANSACTION_OLD_META_ABSENT,
|
||||
(!had_old_data).then_some((PART_TRANSACTION_OLD_DATA_ABSENT, old_data_absent.as_path())),
|
||||
)?;
|
||||
|
||||
// Create new.meta first inside the private staging directory (which is
|
||||
// published atomically by rename_in_same_dir_fd below) so absent old-part
|
||||
// markers can share its immutable inode via linkat instead of allocating
|
||||
// a second inode with openat(O_CREAT) + close.
|
||||
let new_meta_path = staging_path.join(PART_TRANSACTION_NEW_META);
|
||||
let mut new_meta = create_new_in_dir_fd(txn_dir_fd.as_deref(), PART_TRANSACTION_NEW_META, &new_meta_path)?;
|
||||
std::io::Write::write_all(&mut new_meta, &meta)?;
|
||||
@@ -15988,6 +16042,30 @@ impl DiskAPI for LocalDisk {
|
||||
PART_TRANSACTION_PUBLISH_META,
|
||||
&staging_path.join(PART_TRANSACTION_PUBLISH_META),
|
||||
);
|
||||
|
||||
let old_data_absent = staging_path.join(PART_TRANSACTION_OLD_DATA_ABSENT);
|
||||
let old_meta_absent = staging_path.join(PART_TRANSACTION_OLD_META_ABSENT);
|
||||
let absent_link_source = Some((PART_TRANSACTION_NEW_META, new_meta_path.as_path()));
|
||||
let had_old_data = snapshot_part_transaction_file(
|
||||
&dst_file_path,
|
||||
txn_parent_fd.as_deref(),
|
||||
&staging_path.join(PART_TRANSACTION_OLD_DATA),
|
||||
txn_dir_fd.as_deref(),
|
||||
PART_TRANSACTION_OLD_DATA,
|
||||
&old_data_absent,
|
||||
PART_TRANSACTION_OLD_DATA_ABSENT,
|
||||
absent_link_source,
|
||||
)?;
|
||||
let had_old_meta = snapshot_part_transaction_file(
|
||||
&dst_meta_path,
|
||||
txn_parent_fd.as_deref(),
|
||||
&staging_path.join(PART_TRANSACTION_OLD_META),
|
||||
txn_dir_fd.as_deref(),
|
||||
PART_TRANSACTION_OLD_META,
|
||||
&old_meta_absent,
|
||||
PART_TRANSACTION_OLD_META_ABSENT,
|
||||
absent_link_source,
|
||||
)?;
|
||||
let sync_overwrite_backup = durability.syncs_recovery_protocol_state() && (had_old_data || had_old_meta);
|
||||
if sync_overwrite_backup {
|
||||
os::fsync_directory_handle_std(&staging_path, txn_dir_fd.as_deref())?;
|
||||
@@ -21664,6 +21742,108 @@ mod test {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_part_transaction_rolls_back_first_time_part_via_absent_markers() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let endpoint = Endpoint::try_from(dir.path().to_str().expect("utf8 path")).expect("endpoint");
|
||||
let disk = LocalDisk::new(&endpoint, false).await.expect("local disk");
|
||||
ensure_test_volume(&disk, "tmp").await;
|
||||
ensure_test_volume(&disk, "bucket").await;
|
||||
|
||||
let payload = Bytes::from_static(b"new data");
|
||||
let meta = Bytes::from(
|
||||
ObjectPartInfo {
|
||||
number: 1,
|
||||
size: payload.len(),
|
||||
..Default::default()
|
||||
}
|
||||
.marshal_msg()
|
||||
.expect("part metadata"),
|
||||
);
|
||||
disk.write_all("tmp", "upload/part.1", payload)
|
||||
.await
|
||||
.expect("new part should be staged");
|
||||
|
||||
disk.prepare_part_transaction("tmp", "upload/part.1", "bucket", "object/part.1", meta.clone())
|
||||
.await
|
||||
.expect("part transaction should be prepared");
|
||||
|
||||
let txn_rel = crate::disk::part_transaction_path("object/part.1");
|
||||
let txn_dir = disk.io_get_object_open_path("bucket", &txn_rel).expect("txn path");
|
||||
let new_meta_file = txn_dir.join(PART_TRANSACTION_NEW_META);
|
||||
let old_data_absent_file = txn_dir.join(PART_TRANSACTION_OLD_DATA_ABSENT);
|
||||
let old_meta_absent_file = txn_dir.join(PART_TRANSACTION_OLD_META_ABSENT);
|
||||
assert!(new_meta_file.is_file());
|
||||
assert!(old_data_absent_file.is_file());
|
||||
assert!(old_meta_absent_file.is_file());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let probe_src = dir.path().join("hardlink-probe.src");
|
||||
let probe_dst = dir.path().join("hardlink-probe.dst");
|
||||
std::fs::write(&probe_src, b"probe").expect("write hardlink probe");
|
||||
let hardlink_supported = std::fs::hard_link(&probe_src, &probe_dst).is_ok();
|
||||
let _ = std::fs::remove_file(&probe_dst);
|
||||
let _ = std::fs::remove_file(&probe_src);
|
||||
let new_stat = std::fs::symlink_metadata(&new_meta_file).expect("new.meta stat");
|
||||
let data_absent_stat = std::fs::symlink_metadata(&old_data_absent_file).expect("old.data.absent stat");
|
||||
let meta_absent_stat = std::fs::symlink_metadata(&old_meta_absent_file).expect("old.meta.absent stat");
|
||||
if hardlink_supported {
|
||||
assert_eq!((data_absent_stat.dev(), data_absent_stat.ino()), (new_stat.dev(), new_stat.ino()));
|
||||
assert_eq!((meta_absent_stat.dev(), meta_absent_stat.ino()), (new_stat.dev(), new_stat.ino()));
|
||||
assert_eq!(data_absent_stat.len(), meta.len() as u64);
|
||||
assert_eq!(meta_absent_stat.len(), meta.len() as u64);
|
||||
} else {
|
||||
assert_eq!(data_absent_stat.len(), 0);
|
||||
assert_eq!(meta_absent_stat.len(), 0);
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
disk.read_all("bucket", &format!("{txn_rel}/{PART_TRANSACTION_OLD_META_ABSENT}"))
|
||||
.await
|
||||
.is_ok(),
|
||||
"coordinator recovery reads old.meta.absent to detect first-time part transaction"
|
||||
);
|
||||
|
||||
disk.rename_part("tmp", "upload/part.1", "bucket", "object/part.1", meta.clone())
|
||||
.await
|
||||
.expect("part publication should succeed");
|
||||
disk.settle_part_transaction("bucket", "object/part.1", PartTransactionAction::Rollback)
|
||||
.await
|
||||
.expect("part transaction should roll back");
|
||||
|
||||
assert!(matches!(disk.read_all("bucket", "object/part.1").await, Err(DiskError::FileNotFound)));
|
||||
assert!(matches!(
|
||||
disk.read_all("bucket", "object/part.1.meta").await,
|
||||
Err(DiskError::FileNotFound)
|
||||
));
|
||||
assert!(!txn_dir.exists());
|
||||
|
||||
// Asymmetric state: old data exists without old metadata.
|
||||
disk.write_all("tmp", "upload/part.1", Bytes::from_static(b"new data 2"))
|
||||
.await
|
||||
.expect("stage replacement part");
|
||||
disk.write_all("bucket", "object/part.1", Bytes::from_static(b"orphan old data"))
|
||||
.await
|
||||
.expect("stage orphan old data");
|
||||
disk.prepare_part_transaction("tmp", "upload/part.1", "bucket", "object/part.1", meta)
|
||||
.await
|
||||
.expect("prepare with old data only");
|
||||
assert!(txn_dir.join(PART_TRANSACTION_OLD_DATA).is_file());
|
||||
assert!(txn_dir.join(PART_TRANSACTION_OLD_META_ABSENT).is_file());
|
||||
disk.settle_part_transaction("bucket", "object/part.1", PartTransactionAction::Rollback)
|
||||
.await
|
||||
.expect("rollback asymmetric part transaction");
|
||||
assert_eq!(
|
||||
disk.read_all("bucket", "object/part.1").await.expect("old data restored"),
|
||||
Bytes::from_static(b"orphan old data")
|
||||
);
|
||||
assert!(matches!(
|
||||
disk.read_all("bucket", "object/part.1.meta").await,
|
||||
Err(DiskError::FileNotFound)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shard_integrity_part_transaction_keeps_only_the_settled_generation() {
|
||||
use crate::io_support::shard_integrity::IntegrityBuilder;
|
||||
@@ -22383,6 +22563,33 @@ mod test {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[allow(clippy::await_holding_lock)]
|
||||
async fn shutdown_receipt_is_durable_with_legacy_sync_disabled() {
|
||||
let _mode = durability_mode_override::set(DurabilityMode::LegacyOff);
|
||||
let dir = tempfile::tempdir().expect("shutdown marker disk");
|
||||
let endpoint = Endpoint::try_from(dir.path().to_str().expect("disk path")).expect("local endpoint");
|
||||
let disk = LocalDisk::new(&endpoint, false).await.expect("local disk");
|
||||
ensure_test_volume(&disk, RUSTFS_META_BUCKET).await;
|
||||
disk.write_all(
|
||||
RUSTFS_META_BUCKET,
|
||||
crate::disk::UNCLEAN_SHUTDOWN_MARKER_PATH,
|
||||
Bytes::from_static(b"running"),
|
||||
)
|
||||
.await
|
||||
.expect("consume shutdown receipt");
|
||||
let parent = disk
|
||||
.get_object_path(RUSTFS_META_BUCKET, crate::disk::UNCLEAN_SHUTDOWN_MARKER_PATH)
|
||||
.expect("marker path")
|
||||
.parent()
|
||||
.expect("marker parent")
|
||||
.to_path_buf();
|
||||
assert!(
|
||||
os::fsync_dir_recorder::was_fsynced(&parent),
|
||||
"a stale clean receipt must not reappear after a crash"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[allow(clippy::await_holding_lock)]
|
||||
async fn test_write_all_public_still_fsyncs_parent_dir() {
|
||||
@@ -35072,6 +35279,80 @@ mod test {
|
||||
assert!(body.ends_with(b"abcdef"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn file_cache_reclaim_wrappers_round_trip_checksum_sized_file_buffers() {
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::io::IoSlice;
|
||||
|
||||
let dir = tempfile::tempdir().expect("create wrapper test directory");
|
||||
for checksum_bytes in [32, 64] {
|
||||
let wire_len = 2 * 1024 * 1024 + checksum_bytes;
|
||||
let content: Vec<_> = (0u8..=250).cycle().take(wire_len).collect();
|
||||
let path = dir.path().join(format!("frame-{checksum_bytes}"));
|
||||
let file = File::create(&path).await.expect("create writer file");
|
||||
let mut writer = FileCacheReclaimWriter::new(file, wire_len, true);
|
||||
let mut bufs = Vec::new();
|
||||
for frame in content.chunks(wire_len / (checksum_bytes / 32)) {
|
||||
bufs.push(IoSlice::new(&frame[..32]));
|
||||
bufs.push(IoSlice::new(&frame[32..]));
|
||||
}
|
||||
let accepted = writer.write_vectored(&bufs).await.expect("accept checksum and data slices");
|
||||
assert_eq!(accepted, wire_len, "checksum overhead must fit alongside 2 MiB of data");
|
||||
let tail = b"short final tail!";
|
||||
writer.write_all(tail).await.expect("write after the accepted frame");
|
||||
writer.flush().await.expect("flush pending writes");
|
||||
writer.shutdown().await.expect("finish writes before cache reclaim");
|
||||
writer.inner.sync_all().await.expect("sync the completed test file");
|
||||
|
||||
let file = File::open(&path).await.expect("reopen completed file");
|
||||
let mut reader = FileCacheReclaimReader::new(file, 0, wire_len + tail.len(), true, 0);
|
||||
let mut actual = vec![0; wire_len];
|
||||
let read = reader
|
||||
.read(&mut actual)
|
||||
.await
|
||||
.expect("read the complete large frame in one request");
|
||||
assert_eq!(read, wire_len, "the file buffer must read checksum overhead alongside 2 MiB of data");
|
||||
assert_eq!(actual, content, "large reads must preserve every accepted byte");
|
||||
assert_eq!(Sha256::digest(&actual), Sha256::digest(&content), "frame digest must survive file I/O");
|
||||
let mut actual_tail = [0; 32];
|
||||
assert_eq!(
|
||||
reader
|
||||
.read_exact(&mut actual_tail)
|
||||
.await
|
||||
.expect_err("short tail must report EOF")
|
||||
.kind(),
|
||||
std::io::ErrorKind::UnexpectedEof
|
||||
);
|
||||
assert_eq!(&actual_tail[..tail.len()], tail, "short read must preserve the available tail");
|
||||
assert_eq!(reader.read(&mut [0; 1]).await.expect("read at EOF"), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[tokio::test]
|
||||
async fn file_cache_reclaim_writer_propagates_shutdown_error_after_acceptance() {
|
||||
use std::io::IoSlice;
|
||||
|
||||
let file = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open("/dev/full")
|
||||
.await
|
||||
.expect("open full device");
|
||||
let payload = vec![31; 2 * 1024 * 1024 + 64];
|
||||
let mut writer = FileCacheReclaimWriter::new(file, payload.len(), true);
|
||||
let accepted = writer
|
||||
.write_vectored(&[IoSlice::new(&payload[..32]), IoSlice::new(&payload[32..])])
|
||||
.await
|
||||
.expect("Tokio may accept bytes before the blocking write fails");
|
||||
assert_eq!(accepted, payload.len(), "the expanded buffer must accept the complete frame");
|
||||
let error = writer
|
||||
.shutdown()
|
||||
.await
|
||||
.expect_err("accepted bytes must not hide a failed blocking write");
|
||||
assert_eq!(error.raw_os_error(), Some(libc::ENOSPC));
|
||||
assert!(!writer.reclaimed, "failed shutdown must not run successful-write cache reclaim");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tokio::test]
|
||||
async fn macos_nocache_helpers_accept_tokio_and_std_files() {
|
||||
@@ -40395,6 +40676,46 @@ mod test {
|
||||
assert_eq!(recorder.histogram_values(stages, &[("stage", "queue_wait")]).len(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn local_batch_reads_large_windows_per_shard_and_coalesces_small_windows() {
|
||||
use crate::test_metrics::CapturingRecorder;
|
||||
|
||||
let dir = tempfile::tempdir().expect("dispatch shape directory");
|
||||
let large = LOCAL_BATCH_PARALLEL_MIN_SHARD_BYTES;
|
||||
let paths: Vec<_> = (0..2)
|
||||
.map(|index| {
|
||||
let path = dir.path().join(format!("shard-{index}"));
|
||||
std::fs::write(&path, vec![u8::try_from(index).expect("small shard index"); large + 64])
|
||||
.expect("write dispatch shape shard");
|
||||
path
|
||||
})
|
||||
.collect();
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("dispatch shape runtime");
|
||||
let previous = rustfs_io_metrics::get_stage_metrics_enabled();
|
||||
rustfs_io_metrics::set_get_stage_metrics_enabled(true);
|
||||
let dispatches = |length: usize| {
|
||||
let recorder = CapturingRecorder::default();
|
||||
let requests = paths.iter().map(|path| (path.clone(), 64, length)).collect();
|
||||
let results = metrics::with_local_recorder(&recorder, || runtime.block_on(batch_shard_pread(requests)));
|
||||
for (index, result) in results.iter().enumerate() {
|
||||
let bytes = result.as_ref().expect("window inside the shard");
|
||||
assert_eq!(bytes.len(), length);
|
||||
assert!(bytes.iter().all(|byte| usize::from(*byte) == index), "results keep request order");
|
||||
}
|
||||
recorder.histogram_values("rustfs_io_get_object_local_batch_shards", &[])
|
||||
};
|
||||
let large_shape = dispatches(large);
|
||||
let small_shape = dispatches(large - 1);
|
||||
rustfs_io_metrics::set_get_stage_metrics_enabled(previous);
|
||||
|
||||
assert_eq!(large_shape, vec![1.0, 1.0], "copy-bound windows must not serialize in one worker");
|
||||
assert_eq!(small_shape, vec![2.0], "small windows must share one blocking dispatch");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn local_batch_read_metrics_survive_caller_cancellation() {
|
||||
@@ -40511,6 +40832,81 @@ mod test {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn test_batch_shard_pread_returns_exact_multi_page_windows() {
|
||||
let dir = tempfile::tempdir().expect("multi-page window fixture");
|
||||
let path = dir.path().join("shard");
|
||||
let window = 1024 * 1024 + 32;
|
||||
let content: Vec<u8> = (0..3 * window).map(|i| (i % 251) as u8).collect();
|
||||
std::fs::write(&path, &content).expect("write multi-page shard");
|
||||
let unaligned = 2 * window + 7;
|
||||
// Windows of one and two q frames, at zero and nonzero offsets.
|
||||
let windows = [
|
||||
(0, window),
|
||||
(window, window),
|
||||
(unaligned, content.len() - unaligned),
|
||||
(0, 2 * window),
|
||||
(window - 5, 2 * window),
|
||||
];
|
||||
let results = batch_shard_pread(
|
||||
windows
|
||||
.iter()
|
||||
.map(|&(offset, length)| (path.clone(), offset, length))
|
||||
.collect(),
|
||||
)
|
||||
.await;
|
||||
for (result, (offset, length)) in results.iter().zip(windows) {
|
||||
let bytes = result.as_ref().expect("window inside the shard");
|
||||
assert_eq!(bytes.len(), length, "window at {offset} must not over-read");
|
||||
assert_eq!(bytes.as_ref(), &content[offset..offset + length], "window at {offset}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A cold batch read must bring in only its window. Without an exact hint,
|
||||
/// kernel readahead sizes the first request from the read size, so a 16 KiB
|
||||
/// window at offset 0 caches several times its pages and a 2 MiB window
|
||||
/// almost twice its pages.
|
||||
#[cfg(target_os = "linux")]
|
||||
#[tokio::test]
|
||||
async fn test_batch_shard_pread_cold_read_caches_only_its_window() {
|
||||
use rustix::fs::{Advice, fadvise};
|
||||
|
||||
let dir = tempfile::tempdir().expect("cold window fixture");
|
||||
let path = dir.path().join("shard");
|
||||
std::fs::write(&path, vec![5u8; 8 << 20]).expect("write cold window shard");
|
||||
std::fs::File::open(&path)
|
||||
.expect("open shard for sync")
|
||||
.sync_all()
|
||||
.expect("clean pages before eviction");
|
||||
let page = mmap_page_size().expect("page size should be available") as usize;
|
||||
let evict = || {
|
||||
let file = std::fs::File::open(&path).expect("open shard for eviction");
|
||||
fadvise(&file, 0, None, Advice::DontNeed).expect("evict shard pages");
|
||||
};
|
||||
evict();
|
||||
assert_eq!(
|
||||
resident_pages(&path),
|
||||
0,
|
||||
"the temporary filesystem must be able to drop page cache, otherwise residency is unobservable"
|
||||
);
|
||||
for length in [16 * 1024 + 32, 2 * 1024 * 1024 + 64] {
|
||||
evict();
|
||||
let results = batch_shard_pread(vec![(path.clone(), 0, length)]).await;
|
||||
assert_eq!(results[0].as_ref().expect("cold window read").len(), length);
|
||||
let window_pages = length.div_ceil(page);
|
||||
let resident = resident_pages(&path);
|
||||
assert!(
|
||||
resident >= window_pages,
|
||||
"the window itself must be resident: {resident} < {window_pages}"
|
||||
);
|
||||
assert!(
|
||||
resident <= window_pages + window_pages / 8 + 4,
|
||||
"a {length}-byte cold read cached {resident} pages for a {window_pages}-page window"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn test_batch_shard_pread_basic() {
|
||||
|
||||
@@ -1700,7 +1700,10 @@ impl LocalDisk {
|
||||
) -> Result<(Vec<DeleteTransactionId>, Option<DiscoverySession>)> {
|
||||
let lease = os::acquire_namespace_mutation_lease_with_owner(path, None).await;
|
||||
self.validate_delete_discovery_owner(&session)?;
|
||||
os::run_blocking_namespace_operation(lease, move || session.advance(limit))
|
||||
// A discovery page can lstat thousands of entries on a cold tree. The
|
||||
// one-worker foreground lane also serves GET metadata reads, so a page
|
||||
// there stalls every read on this disk until the walk finishes.
|
||||
os::run_blocking_namespace_operation_with_sync(lease, true, move || session.advance(limit))
|
||||
.await
|
||||
.map_err(|error| to_file_error(error).into())
|
||||
}
|
||||
@@ -4489,6 +4492,38 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_discovery_runs_while_foreground_metadata_lane_is_busy() {
|
||||
let (_temp, disk, _info, _original) = fixture().await;
|
||||
let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
|
||||
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
|
||||
let queue = disk.blocking_queue.clone();
|
||||
let foreground = tokio::spawn(async move {
|
||||
queue
|
||||
.run_cancellable(move |_| {
|
||||
let _ = entered_tx.send(());
|
||||
let _ = release_rx.recv();
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
});
|
||||
entered_rx.await.expect("foreground metadata worker entered");
|
||||
let page = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(10),
|
||||
disk.delete_recovery_discover("recovery", None, None, 128),
|
||||
)
|
||||
.await;
|
||||
release_tx.send(()).expect("release foreground metadata worker");
|
||||
foreground
|
||||
.await
|
||||
.expect("foreground metadata job joins")
|
||||
.expect("foreground metadata job succeeds");
|
||||
let page = page
|
||||
.expect("bucket discovery must not wait behind the foreground metadata lane")
|
||||
.expect("bucket discovery succeeds");
|
||||
assert!(page.transactions.is_empty(), "fixture holds no delete transactions");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_recovery_live_write_backup_preserves_delete_evidence() {
|
||||
let (_temp, disk, info, original) = fixture().await;
|
||||
|
||||
@@ -122,17 +122,27 @@ fn validate_certificate_shape(
|
||||
}
|
||||
|
||||
impl LocalDisk {
|
||||
// Give readonly inspection its own future layout while retaining one
|
||||
// selected Box per request and constructing it outside caller poll frames.
|
||||
// Separate inspection, abort and recovery layouts, and construct the
|
||||
// selected boxed future outside caller poll frames.
|
||||
#[inline(never)]
|
||||
pub(super) fn recover_multipart_source_native(
|
||||
&self,
|
||||
request: MultipartSourceRequest,
|
||||
) -> impl std::future::Future<Output = Result<MultipartSourceResponse>> + Send + '_ {
|
||||
if matches!(&request.operation, MultipartSourceOperation::Inspect { .. }) {
|
||||
futures::future::Either::Left(Box::pin(self.inspect_multipart_source_native(request)))
|
||||
} else {
|
||||
futures::future::Either::Right(Box::pin(self.recover_multipart_source_native_inner(request)))
|
||||
match &request.operation {
|
||||
MultipartSourceOperation::Inspect { .. } => {
|
||||
futures::future::Either::Left(Box::pin(self.inspect_multipart_source_native(request)))
|
||||
}
|
||||
MultipartSourceOperation::UpgradeLegacy { .. }
|
||||
| MultipartSourceOperation::PrepareAbort { .. }
|
||||
| MultipartSourceOperation::CommitAbort { .. }
|
||||
| MultipartSourceOperation::DeleteAborted { .. }
|
||||
| MultipartSourceOperation::ConfirmCleanupTarget { .. } => futures::future::Either::Right(
|
||||
futures::future::Either::Left(Box::pin(self.abort_multipart_source_native(request))),
|
||||
),
|
||||
_ => futures::future::Either::Right(futures::future::Either::Right(Box::pin(
|
||||
self.recover_multipart_source_native_inner(request),
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,20 +190,24 @@ impl LocalDisk {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn abort_multipart_source_native(&self, request: MultipartSourceRequest) -> Result<MultipartSourceResponse> {
|
||||
request.validate()?;
|
||||
let store = self.open_multipart_source_store(&request.path, None).await?;
|
||||
self.recover_multipart_abort_owned(store, request.operation).await
|
||||
}
|
||||
|
||||
async fn recover_multipart_source_native_inner(&self, request: MultipartSourceRequest) -> Result<MultipartSourceResponse> {
|
||||
request.validate()?;
|
||||
// Source RW ownership precedes source namespace, target metadata, and
|
||||
// target publication ownership. Every filesystem tail retains it.
|
||||
let store = self.open_multipart_source_store(&request.path, None).await?;
|
||||
match request.operation {
|
||||
operation @ (MultipartSourceOperation::UpgradeLegacy { .. }
|
||||
MultipartSourceOperation::Inspect { .. }
|
||||
| MultipartSourceOperation::UpgradeLegacy { .. }
|
||||
| MultipartSourceOperation::PrepareAbort { .. }
|
||||
| MultipartSourceOperation::CommitAbort { .. }
|
||||
| MultipartSourceOperation::DeleteAborted { .. }
|
||||
| MultipartSourceOperation::ConfirmCleanupTarget { .. }) => {
|
||||
self.recover_multipart_abort_owned(store, operation).await
|
||||
}
|
||||
MultipartSourceOperation::Inspect { .. } => Err(DiskError::UnsupportedDisk),
|
||||
| MultipartSourceOperation::ConfirmCleanupTarget { .. } => Err(DiskError::UnsupportedDisk),
|
||||
MultipartSourceOperation::Claim { expected, round } => {
|
||||
let loaded = store.load().await?;
|
||||
require_expected(&loaded, &expected)?;
|
||||
|
||||
@@ -316,11 +316,18 @@ pub(super) fn put_active_multipart_source_head(source: impl AsRef<Path>, raw: By
|
||||
}
|
||||
|
||||
fn stamp_matches_active_disk(source: &Path, expected_head_stamp: FileStamp) -> bool {
|
||||
FileStamp::from_path(&source.join(STORAGE_FORMAT_FILE)) == Some(expected_head_stamp)
|
||||
&& !(cfg!(test)
|
||||
&& (source.join(STATE).exists()
|
||||
|| source.join(crate::disk::MULTIPART_RECOVERY_DIR).exists()
|
||||
|| source.join(".mpu-completions").exists()))
|
||||
let stamp_matches = FileStamp::from_path(&source.join(STORAGE_FORMAT_FILE)) == Some(expected_head_stamp);
|
||||
#[cfg(test)]
|
||||
{
|
||||
stamp_matches
|
||||
&& !source.join(STATE).exists()
|
||||
&& !source.join(crate::disk::MULTIPART_RECOVERY_DIR).exists()
|
||||
&& !source.join(".mpu-completions").exists()
|
||||
}
|
||||
#[cfg(not(test))]
|
||||
{
|
||||
stamp_matches
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn get_active_multipart_source_head(source: &Path) -> Option<(Bytes, FileInfo)> {
|
||||
@@ -600,11 +607,13 @@ impl SourceStore {
|
||||
let disk_id = self.disk_id;
|
||||
let physical_slot = self.physical_slot;
|
||||
let disk_ids = self.disk_ids.clone();
|
||||
// Keep the loaded state out of each blocking-queue and oneshot poll frame.
|
||||
os::run_blocking_namespace_operation(self.lease.clone(), move || {
|
||||
Ok(load_source(&source, &base, &root, &path, disk_id, physical_slot, &disk_ids))
|
||||
Ok(load_source(&source, &base, &root, &path, disk_id, physical_slot, &disk_ids).map(Box::new))
|
||||
})
|
||||
.await
|
||||
.map_err(DiskError::from)?
|
||||
.map(|loaded| *loaded)
|
||||
}
|
||||
pub async fn persist(&self, state: &SourceState) -> Result<()> {
|
||||
self.persist_with_source_sync(state, false).await.map(|_| ())
|
||||
|
||||
@@ -320,7 +320,9 @@ impl Drop for MultipartCommitStaging {
|
||||
impl LocalDisk {
|
||||
pub(crate) fn has_clean_active_multipart_source(&self, upload_or_part_path: &str, part_path: bool) -> bool {
|
||||
let root = upload_scope_root(upload_or_part_path, part_path);
|
||||
let Ok(source) = self.io_get_object_path(RUSTFS_META_MULTIPART_BUCKET, root) else {
|
||||
// Advisory skip-recovery probe: only keys ACTIVE_MULTIPART_SOURCE_HEADS and
|
||||
// checks the cached xl.meta stamp; mutating stages re-validate via multipart_source_admission.
|
||||
let Ok(source) = self.io_get_object_open_path(RUSTFS_META_MULTIPART_BUCKET, root) else {
|
||||
return false;
|
||||
};
|
||||
super::multipart_source_state::has_clean_active_multipart_source(&source)
|
||||
@@ -345,6 +347,38 @@ impl LocalDisk {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Constructs `MultipartSourceAdmission` for a part path after the caller has
|
||||
/// already validated `(volume, path)` via `io_get_bucket_and_object_path`.
|
||||
pub(super) fn multipart_source_admission_after_validated_part_path(
|
||||
&self,
|
||||
volume: &str,
|
||||
path: &str,
|
||||
) -> Result<Option<MultipartSourceAdmission>> {
|
||||
reject_noncanonical_scope(&self.root, self.io_root(), volume, path)?;
|
||||
if volume != RUSTFS_META_MULTIPART_BUCKET {
|
||||
return Ok(None);
|
||||
}
|
||||
let scope = upload_scope_root(path, true);
|
||||
let trimmed = path.trim_end_matches('/');
|
||||
let source =
|
||||
if !scope.is_empty() && (trimmed == scope || trimmed.strip_prefix(scope).is_some_and(|rest| rest.starts_with('/'))) {
|
||||
let open_path = self.io_get_object_open_path(volume, scope)?;
|
||||
#[cfg(debug_assertions)]
|
||||
if let Ok(full_path) = self.io_get_object_path(volume, scope) {
|
||||
debug_assert_eq!(open_path, full_path);
|
||||
}
|
||||
open_path
|
||||
} else {
|
||||
self.io_get_object_path(volume, scope)?
|
||||
};
|
||||
Ok(Some(MultipartSourceAdmission {
|
||||
source,
|
||||
base: self.io_root().to_path_buf(),
|
||||
publication_root: self.publication_root.clone(),
|
||||
initial: false,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) async fn multipart_source_owner(
|
||||
&self,
|
||||
volume: &str,
|
||||
@@ -1449,6 +1483,39 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn multipart_source_admission_after_validated_part_path_matches_full_admission() {
|
||||
let (_root, disk, _, _) = fixture().await;
|
||||
let sha_upload = format!("{}/{}/{}/part.1", "a".repeat(64), Uuid::new_v4(), Uuid::new_v4());
|
||||
let fixture_upload = format!("upload/{}/part.1", Uuid::new_v4());
|
||||
let direct_part = format!("{}/part.1", Uuid::new_v4());
|
||||
for path in [&sha_upload, &fixture_upload, &direct_part] {
|
||||
let (_, _) = disk
|
||||
.io_get_bucket_and_object_path(RUSTFS_META_MULTIPART_BUCKET, path)
|
||||
.expect("validated part path");
|
||||
let fast = disk
|
||||
.multipart_source_admission_after_validated_part_path(RUSTFS_META_MULTIPART_BUCKET, path)
|
||||
.expect("fast admission")
|
||||
.expect("multipart admission present");
|
||||
let full = disk
|
||||
.multipart_source_admission(RUSTFS_META_MULTIPART_BUCKET, path, true, false)
|
||||
.expect("full admission")
|
||||
.expect("multipart admission present");
|
||||
assert_eq!(fast.source(), full.source());
|
||||
}
|
||||
assert!(
|
||||
disk.multipart_source_admission_after_validated_part_path("bucket", "object/part.1")
|
||||
.expect("non-multipart volume")
|
||||
.is_none()
|
||||
);
|
||||
for noncanonical in ["a/../b/part.1", "a//b/part.1", "/a/b/part.1"] {
|
||||
assert!(matches!(
|
||||
disk.multipart_source_admission_after_validated_part_path(RUSTFS_META_MULTIPART_BUCKET, noncanonical),
|
||||
Err(DiskError::ConditionalDeleteConflict)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn multipart_source_cache_publication_holds_source_lock_against_concurrent_retirement() {
|
||||
|
||||
@@ -45,7 +45,7 @@ pub use local::pool_meta_native::{PoolMetaNativeCasCondition, PoolMetaNativeFile
|
||||
pub(crate) use io_admission::{DiskIoClass, test_resource_units};
|
||||
pub(crate) use io_admission::{
|
||||
PhysicalHealBinding, acquire_context_disk_io_permit, current_disk_io_context, current_resource_unit, has_resource_io_scope,
|
||||
with_optional_disk_io_context, with_optional_resource_unit,
|
||||
with_detached_disk_io_context, with_optional_disk_io_context, with_optional_resource_unit,
|
||||
};
|
||||
|
||||
pub const RUSTFS_META_BUCKET: &str = ".rustfs.sys";
|
||||
@@ -77,6 +77,8 @@ pub fn validate_format_control_path(path: &str) -> Result<()> {
|
||||
/// Per-disk marker present while an erasure-set heal is rebuilding this disk.
|
||||
/// `LocalDisk::disk_info` reports `healing = true` while the file exists.
|
||||
pub const HEALING_MARKER_PATH: &str = "healing.bin";
|
||||
/// Boot-time crash fence and clean scanner continuity receipt.
|
||||
pub const UNCLEAN_SHUTDOWN_MARKER_PATH: &str = "unclean-shutdown";
|
||||
pub const STORAGE_FORMAT_FILE: &str = "xl.meta";
|
||||
pub const STORAGE_FORMAT_FILE_BACKUP: &str = "xl.meta.bkp";
|
||||
/// Original upload authority after it stops admitting active part mutations.
|
||||
|
||||
@@ -417,11 +417,15 @@ pub(crate) mod prepared_publication_test_hooks {
|
||||
}
|
||||
|
||||
pub(crate) fn has_any_hooks() -> bool {
|
||||
let before_publication = !BEFORE_PUBLICATION.lock().is_empty();
|
||||
#[cfg(test)]
|
||||
if !RENAME_DESTINATIONS.lock().is_empty() || !HARDLINK_DESTINATIONS.lock().is_empty() {
|
||||
return true;
|
||||
{
|
||||
before_publication || !RENAME_DESTINATIONS.lock().is_empty() || !HARDLINK_DESTINATIONS.lock().is_empty()
|
||||
}
|
||||
#[cfg(not(test))]
|
||||
{
|
||||
before_publication
|
||||
}
|
||||
!BEFORE_PUBLICATION.lock().is_empty()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -53,6 +53,8 @@ pub(crate) struct DecodeOutcome {
|
||||
pub(crate) error: Option<std::io::Error>,
|
||||
pub(crate) exact_quorum: bool,
|
||||
pub(crate) repair: ShardReadRepair,
|
||||
pub(crate) frame_count: usize,
|
||||
pub(crate) read_dispatch_count: usize,
|
||||
}
|
||||
|
||||
type ShardIndexes = SmallVec<[usize; INLINE_SHARD_SLOTS]>;
|
||||
@@ -835,6 +837,58 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a reconstruction-verifying reader for one q-aligned slice of a
|
||||
/// logical EC block. The underlying erasure geometry still determines the
|
||||
/// number of data and parity readers, while `read_shard_size` describes the
|
||||
/// smaller byte vector that Reed-Solomon should reconstruct for this range.
|
||||
///
|
||||
/// The q-range caller opens every reader at the same logical shard offset,
|
||||
/// so this reader only needs one local stripe and no global shard cursor.
|
||||
fn new_for_quantized_decode(
|
||||
readers: Vec<Option<BitrotReader<R>>>,
|
||||
e: Erasure,
|
||||
read_shard_size: usize,
|
||||
metrics_path: Option<&'static str>,
|
||||
read_costs: Option<Vec<ShardReadCost>>,
|
||||
) -> Self {
|
||||
let mut reader = if let Some(read_costs) = read_costs {
|
||||
Self::new_with_metrics_path_read_costs_timeout_and_reconstruction_verification(
|
||||
readers,
|
||||
e,
|
||||
0,
|
||||
0,
|
||||
metrics_path,
|
||||
read_costs,
|
||||
get_object_disk_read_timeout(),
|
||||
true,
|
||||
)
|
||||
} else {
|
||||
Self::new_with_metrics_path_read_timeout_and_reconstruction_verification(
|
||||
readers,
|
||||
e,
|
||||
0,
|
||||
0,
|
||||
metrics_path,
|
||||
get_object_disk_read_timeout(),
|
||||
true,
|
||||
)
|
||||
};
|
||||
reader.offset = 0;
|
||||
reader.shard_size = read_shard_size;
|
||||
reader.shard_file_size = read_shard_size;
|
||||
// A q-range is already bounded to the exact shard frames needed by the
|
||||
// client request. Keep healthy reads demand-bound as well: read the
|
||||
// data quorum and retain parity as stripe-aligned reserves for a failed
|
||||
// data reader. The ordinary GET rollout remains controlled by its
|
||||
// deployment gate, while this bounded path avoids paying parity I/O for
|
||||
// every small Range request.
|
||||
reader.demand_bound_lockstep = true;
|
||||
for (index, engaged) in reader.engaged.iter_mut().enumerate() {
|
||||
*engaged = index < reader.data_shards;
|
||||
}
|
||||
reader
|
||||
}
|
||||
|
||||
pub(crate) fn with_repair_evidence(mut self, evidence: Arc<ShardReadRepair>) -> Self {
|
||||
self.repair_evidence = Some(evidence);
|
||||
self
|
||||
@@ -999,6 +1053,15 @@ where
|
||||
state.into_parts()
|
||||
}
|
||||
|
||||
pub(crate) fn read_shape(&self) -> (usize, usize) {
|
||||
self.readers.iter().flatten().fold((0, 0), |(frames, dispatches), reader| {
|
||||
(
|
||||
frames.saturating_add(reader.last_frame_count()),
|
||||
dispatches.saturating_add(reader.last_read_dispatch_count()),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
async fn read_into_state(&mut self, state: &mut StripeReadState) {
|
||||
// On the reconstruction-verifying GET path, read every live shard reader
|
||||
// in lockstep so all readers advance one block per stripe and stay
|
||||
@@ -1834,6 +1897,9 @@ where
|
||||
// fail a stripe that later reaches a real quorum.
|
||||
self.engaged[i] = false;
|
||||
} else {
|
||||
if let Some(evidence) = &self.repair_evidence {
|
||||
evidence.observe(&[Some(e.clone())]);
|
||||
}
|
||||
errs[i] = Some(e);
|
||||
// Lockstep cannot safely reuse a reader after any
|
||||
// error, even when the low-level classifier called it
|
||||
@@ -2443,6 +2509,301 @@ impl Erasure {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Decode a range that was opened as one q-aligned slice of every data
|
||||
/// shard. The caller supplies the output offset within the concatenated
|
||||
/// q-slices (`shard_index * read_shard_size + offset_in_shard`). Keeping
|
||||
/// this path separate from `decode_inner` preserves the normal full-shard
|
||||
/// reader geometry for legacy and full-object GETs.
|
||||
/// `allow_direct_data_shard` requires the caller to have established its
|
||||
/// metadata/open quorum and enabled frame authentication; policies requiring
|
||||
/// reconstruction evidence must leave it false.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn decode_quantized_range_with_stripe_handles_and_reopeners<W, R>(
|
||||
&self,
|
||||
writer: &mut W,
|
||||
mut readers: Vec<Option<BitrotReader<R>>>,
|
||||
output_offset: usize,
|
||||
length: usize,
|
||||
read_shard_size: usize,
|
||||
read_costs: Option<Vec<ShardReadCost>>,
|
||||
mut deferred_handles: Vec<Option<DeferredReaderStripeHandle>>,
|
||||
mut deferred_reopeners: Vec<Option<DeferredReaderReopener<R>>>,
|
||||
allow_direct_data_shard: bool,
|
||||
) -> DecodeOutcome
|
||||
where
|
||||
W: AsyncWrite + Send + Sync + Unpin,
|
||||
R: crate::erasure::coding::ShardSource,
|
||||
{
|
||||
if readers.len() != self.data_shards + self.parity_shards {
|
||||
record_get_object_pipeline_failure(GET_STAGE_RANGE, GetObjectFailureReason::RangeOrLengthInvalid);
|
||||
return DecodeOutcome {
|
||||
error: Some(io::Error::new(ErrorKind::InvalidInput, "Invalid number of readers")),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
if read_shard_size == 0 {
|
||||
record_get_object_pipeline_failure(GET_STAGE_RANGE, GetObjectFailureReason::RangeOrLengthInvalid);
|
||||
return DecodeOutcome {
|
||||
error: Some(io::Error::new(ErrorKind::InvalidInput, "quantized shard size must be non-zero")),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
let Some(required_len) = output_offset.checked_add(length) else {
|
||||
record_get_object_pipeline_failure(GET_STAGE_RANGE, GetObjectFailureReason::RangeOrLengthInvalid);
|
||||
return DecodeOutcome {
|
||||
error: Some(io::Error::new(ErrorKind::InvalidInput, "quantized output range overflows")),
|
||||
..Default::default()
|
||||
};
|
||||
};
|
||||
let Some(max_len) = self.data_shards.checked_mul(read_shard_size) else {
|
||||
record_get_object_pipeline_failure(GET_STAGE_RANGE, GetObjectFailureReason::RangeOrLengthInvalid);
|
||||
return DecodeOutcome {
|
||||
error: Some(io::Error::new(ErrorKind::InvalidInput, "quantized shard geometry overflows")),
|
||||
..Default::default()
|
||||
};
|
||||
};
|
||||
if required_len > max_len {
|
||||
record_get_object_pipeline_failure(GET_STAGE_RANGE, GetObjectFailureReason::RangeOrLengthInvalid);
|
||||
return DecodeOutcome {
|
||||
error: Some(io::Error::new(ErrorKind::InvalidInput, "quantized output range exceeds shard geometry")),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
if length == 0 {
|
||||
return DecodeOutcome::default();
|
||||
}
|
||||
|
||||
let metrics_path = Some(GET_OBJECT_PATH_LEGACY_DUPLEX);
|
||||
let target_shard = output_offset / read_shard_size;
|
||||
let within_shard = output_offset % read_shard_size;
|
||||
// The caller has already established the normal metadata and reader-
|
||||
// open quorum. A healthy systematic shard can serve a single-shard
|
||||
// range after authenticating every frame in its opened q-slice. Other
|
||||
// data shards contain no requested bytes; read them only if this shard
|
||||
// fails and reconstruction becomes necessary. Protected layouts and
|
||||
// policies requiring reconstruction evidence keep the quorum decoder.
|
||||
if allow_direct_data_shard
|
||||
&& !self.uses_legacy_codec()
|
||||
&& length <= read_shard_size - within_shard
|
||||
&& readers.iter().flatten().all(|reader| reader.integrity_proof().is_none())
|
||||
&& let Some(mut direct_reader) = readers[target_shard].take()
|
||||
{
|
||||
let stripe_read_stage_start = get_stage_timer_if_enabled(rustfs_io_metrics::get_stage_metrics_enabled());
|
||||
let read_cost = read_costs
|
||||
.as_ref()
|
||||
.and_then(|costs| costs.get(target_shard))
|
||||
.copied()
|
||||
.unwrap_or(ShardReadCost::Unknown);
|
||||
let read_timeout = get_object_disk_read_timeout();
|
||||
let mut direct_read = Box::pin(read_shard_result(
|
||||
target_shard,
|
||||
read_cost,
|
||||
&mut direct_reader,
|
||||
None,
|
||||
read_shard_size,
|
||||
self.data_shards,
|
||||
read_timeout,
|
||||
metrics_path,
|
||||
));
|
||||
let initial_result = if let Some(delay) = shard_read_hedge_delay(read_timeout) {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut direct_read => Some(result.0),
|
||||
_ = tokio::time::sleep(delay) => None,
|
||||
}
|
||||
} else {
|
||||
Some((&mut direct_read).await.0)
|
||||
};
|
||||
let repair = Arc::new(ShardReadRepair::default());
|
||||
let mut outcome = DecodeOutcome::default();
|
||||
let selected_data;
|
||||
match initial_result {
|
||||
Some(Ok(data)) => selected_data = Some((data, within_shard)),
|
||||
initial_result => {
|
||||
// Keep a pending target alive through its real deadline.
|
||||
// The hedge only admits competing reconstruction; it is
|
||||
// not evidence that this healthy source is missing.
|
||||
if let Some(handle) = deferred_handles.get_mut(target_shard) {
|
||||
*handle = None;
|
||||
}
|
||||
if let Some(reopener) = deferred_reopeners.get_mut(target_shard) {
|
||||
*reopener = None;
|
||||
}
|
||||
if let Some(Err(error)) = &initial_result {
|
||||
repair.observe(&[Some(error.clone())]);
|
||||
}
|
||||
// Buffer at most one requested data-shard slice. Neither
|
||||
// contender writes to the downstream until authenticated
|
||||
// direct bytes or a complete verified quorum has won.
|
||||
let mut fallback_data = Vec::with_capacity(length);
|
||||
let mut fallback = Box::pin(self.decode_quantized_range_quorum(
|
||||
&mut fallback_data,
|
||||
readers,
|
||||
output_offset,
|
||||
length,
|
||||
read_shard_size,
|
||||
read_costs,
|
||||
deferred_handles,
|
||||
deferred_reopeners,
|
||||
Some(target_shard),
|
||||
Arc::clone(&repair),
|
||||
));
|
||||
if initial_result.is_some() {
|
||||
outcome = (&mut fallback).await;
|
||||
drop(fallback);
|
||||
selected_data = (outcome.written == length).then_some((fallback_data.into(), 0));
|
||||
} else {
|
||||
let race = tokio::select! {
|
||||
biased;
|
||||
result = &mut direct_read => Ok(result.0),
|
||||
outcome = &mut fallback => Err(outcome),
|
||||
};
|
||||
match race {
|
||||
Ok(Ok(data)) => {
|
||||
drop(fallback);
|
||||
selected_data = Some((data, within_shard));
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
repair.observe(&[Some(error)]);
|
||||
outcome = (&mut fallback).await;
|
||||
drop(fallback);
|
||||
selected_data = (outcome.written == length).then_some((fallback_data.into(), 0));
|
||||
}
|
||||
Err(fallback_outcome) => {
|
||||
drop(fallback);
|
||||
if fallback_outcome.written == length {
|
||||
outcome = fallback_outcome;
|
||||
selected_data = Some((fallback_data.into(), 0));
|
||||
} else {
|
||||
// A failed alternative quorum must not vote
|
||||
// away a still-pending healthy target.
|
||||
match (&mut direct_read).await.0 {
|
||||
Ok(data) => selected_data = Some((data, within_shard)),
|
||||
Err(error) => {
|
||||
repair.observe(&[Some(error)]);
|
||||
outcome = fallback_outcome;
|
||||
selected_data = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(direct_read);
|
||||
outcome.frame_count = outcome.frame_count.saturating_add(direct_reader.last_frame_count());
|
||||
outcome.read_dispatch_count = outcome
|
||||
.read_dispatch_count
|
||||
.saturating_add(direct_reader.last_read_dispatch_count());
|
||||
outcome.repair = repair.snapshot();
|
||||
record_get_stage_duration_if_enabled(GET_OBJECT_PATH_LEGACY_DUPLEX, GET_STAGE_STRIPE_READ, stripe_read_stage_start);
|
||||
if let Some((data, start)) = selected_data {
|
||||
let emit_stage_start = get_stage_timer_if_enabled(rustfs_io_metrics::get_stage_metrics_enabled());
|
||||
let result = writer.write_all(&data[start..start + length]).await;
|
||||
record_get_stage_duration_if_enabled(GET_OBJECT_PATH_LEGACY_DUPLEX, GET_STAGE_EMIT, emit_stage_start);
|
||||
if let Err(error) = result {
|
||||
outcome.written = 0;
|
||||
outcome.error = Some(error);
|
||||
} else {
|
||||
outcome.written = length;
|
||||
}
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
self.decode_quantized_range_quorum(
|
||||
writer,
|
||||
readers,
|
||||
output_offset,
|
||||
length,
|
||||
read_shard_size,
|
||||
read_costs,
|
||||
deferred_handles,
|
||||
deferred_reopeners,
|
||||
None,
|
||||
Arc::new(ShardReadRepair::default()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn decode_quantized_range_quorum<W, R>(
|
||||
&self,
|
||||
writer: &mut W,
|
||||
readers: Vec<Option<BitrotReader<R>>>,
|
||||
output_offset: usize,
|
||||
length: usize,
|
||||
read_shard_size: usize,
|
||||
read_costs: Option<Vec<ShardReadCost>>,
|
||||
deferred_handles: Vec<Option<DeferredReaderStripeHandle>>,
|
||||
deferred_reopeners: Vec<Option<DeferredReaderReopener<R>>>,
|
||||
pending_target: Option<usize>,
|
||||
repair: Arc<ShardReadRepair>,
|
||||
) -> DecodeOutcome
|
||||
where
|
||||
W: AsyncWrite + Send + Sync + Unpin,
|
||||
R: crate::erasure::coding::ShardSource,
|
||||
{
|
||||
let metrics_path = Some(GET_OBJECT_PATH_LEGACY_DUPLEX);
|
||||
let mut reader =
|
||||
ParallelReader::new_for_quantized_decode(readers, self.clone(), read_shard_size, metrics_path, read_costs)
|
||||
.with_deferred_parity_handles(deferred_handles)
|
||||
.with_deferred_parity_reopeners(deferred_reopeners)
|
||||
.with_repair_evidence(Arc::clone(&repair));
|
||||
let integrity = reader.integrity.clone();
|
||||
// The q-range reader still verifies each bitrot frame. Requiring an
|
||||
// additional reconstruction source for a healthy range would defeat
|
||||
// demand-bound parity and turn every request back into an all-shard
|
||||
// read; parity is admitted by the lockstep reader only when data is
|
||||
// missing or fails verification.
|
||||
let require_surplus_source = false;
|
||||
|
||||
let stripe_read_stage_start = get_stage_timer_if_enabled(rustfs_io_metrics::get_stage_metrics_enabled());
|
||||
let (mut shards, mut errs) = reader.read().await;
|
||||
if let Some(target_shard) = pending_target {
|
||||
// This slot is owned by the direct contender, rather than missing
|
||||
// from storage. Clear only its synthetic error; actual successful
|
||||
// shards still determine the reconstruction quorum below.
|
||||
errs[target_shard] = None;
|
||||
}
|
||||
let (frame_count, read_dispatch_count) = reader.read_shape();
|
||||
record_get_stage_duration_if_enabled(GET_OBJECT_PATH_LEGACY_DUPLEX, GET_STAGE_STRIPE_READ, stripe_read_stage_start);
|
||||
let exact_quorum = shards.iter().filter(|shard| shard.is_some()).count() == self.data_shards;
|
||||
let mut written = 0;
|
||||
let mut ret_err = None;
|
||||
let flow = self
|
||||
.emit_decoded_stripe(
|
||||
writer,
|
||||
&mut shards,
|
||||
&errs,
|
||||
output_offset,
|
||||
length,
|
||||
&mut written,
|
||||
&mut ret_err,
|
||||
&repair,
|
||||
rustfs_io_metrics::get_stage_metrics_enabled(),
|
||||
require_surplus_source,
|
||||
integrity.as_ref(),
|
||||
0,
|
||||
)
|
||||
.await;
|
||||
if matches!(flow, StripeFlow::Continue) {
|
||||
reader.recycle_shards(&mut shards);
|
||||
}
|
||||
if ret_err.is_none() && written < length {
|
||||
ret_err = Some(Error::LessData.into());
|
||||
}
|
||||
|
||||
DecodeOutcome {
|
||||
written,
|
||||
error: ret_err,
|
||||
exact_quorum,
|
||||
repair: repair.snapshot(),
|
||||
frame_count,
|
||||
read_dispatch_count,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconstruct and emit one already-read stripe.
|
||||
///
|
||||
/// This is the shared per-stripe body used by both the serial legacy loop
|
||||
@@ -2893,6 +3254,8 @@ impl Erasure {
|
||||
error: ret_err,
|
||||
exact_quorum,
|
||||
repair,
|
||||
frame_count: 0,
|
||||
read_dispatch_count: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3046,6 +3409,372 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
async fn quantized_counting_readers(
|
||||
erasure: &Erasure,
|
||||
data: &[u8],
|
||||
frame_size: usize,
|
||||
slice_offset: usize,
|
||||
slice_length: usize,
|
||||
corrupt_shard: Option<usize>,
|
||||
) -> (Vec<Option<BitrotReader<CountingShardReader>>>, Vec<Arc<AtomicUsize>>) {
|
||||
let shards = erasure.encode_data(data).expect("quantized fixture must encode");
|
||||
let mut readers = Vec::with_capacity(shards.len());
|
||||
let mut counters = Vec::with_capacity(shards.len());
|
||||
for shard in shards {
|
||||
let mut writer = BitrotWriter::new(Vec::new(), frame_size, HashAlgorithm::HighwayHash256S);
|
||||
for frame in shard[slice_offset..slice_offset + slice_length].chunks(frame_size) {
|
||||
writer.write(frame).await.expect("quantized fixture frame must write");
|
||||
}
|
||||
let mut encoded = writer.into_inner();
|
||||
if corrupt_shard == Some(readers.len()) {
|
||||
*encoded.last_mut().expect("fixture has a frame payload") ^= 0x80;
|
||||
}
|
||||
let bytes_read = Arc::new(AtomicUsize::new(0));
|
||||
readers.push(Some(BitrotReader::new_with_frame_size(
|
||||
CountingShardReader {
|
||||
inner: Cursor::new(encoded),
|
||||
bytes_read: Arc::clone(&bytes_read),
|
||||
},
|
||||
erasure.shard_size(),
|
||||
frame_size,
|
||||
HashAlgorithm::HighwayHash256S,
|
||||
false,
|
||||
)));
|
||||
counters.push(bytes_read);
|
||||
}
|
||||
(readers, counters)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quantized_direct_reads_only_the_requested_authenticated_data_shard() {
|
||||
let data = b"abcdefghijklmnop";
|
||||
let erasure = Erasure::new(2, 2, data.len());
|
||||
let (readers, counters) = quantized_counting_readers(&erasure, data, 4, 0, 4, None).await;
|
||||
let mut output = Vec::new();
|
||||
let outcome = erasure
|
||||
.decode_quantized_range_with_stripe_handles_and_reopeners(
|
||||
&mut output,
|
||||
readers,
|
||||
5,
|
||||
2,
|
||||
4,
|
||||
None,
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(outcome.error.is_none(), "authenticated direct range must succeed: {:?}", outcome.error);
|
||||
assert_eq!(outcome.written, 2);
|
||||
assert_eq!(output, &data[9..11]);
|
||||
assert_eq!(outcome.frame_count, 1);
|
||||
assert_eq!(outcome.read_dispatch_count, 1);
|
||||
for (index, counter) in counters.iter().enumerate() {
|
||||
assert_eq!(
|
||||
counter.load(Ordering::SeqCst),
|
||||
if index == 1 {
|
||||
HashAlgorithm::HighwayHash256S.size() + 4
|
||||
} else {
|
||||
0
|
||||
},
|
||||
"healthy direct range must not read unrequested shard {index}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quantized_direct_can_be_disabled_without_changing_range_bytes() {
|
||||
let data = b"abcdefghijklmnop";
|
||||
let erasure = Erasure::new(2, 2, data.len());
|
||||
let (readers, counters) = quantized_counting_readers(&erasure, data, 4, 0, 4, None).await;
|
||||
let mut output = Vec::new();
|
||||
let outcome = erasure
|
||||
.decode_quantized_range_with_stripe_handles_and_reopeners(
|
||||
&mut output,
|
||||
readers,
|
||||
5,
|
||||
2,
|
||||
4,
|
||||
None,
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(outcome.error.is_none(), "quorum decoder range must succeed: {:?}", outcome.error);
|
||||
assert_eq!(output, &data[9..11]);
|
||||
assert!(counters[0].load(Ordering::SeqCst) > 0, "disabled direct path must read the data quorum");
|
||||
assert!(
|
||||
counters[1].load(Ordering::SeqCst) > 0,
|
||||
"disabled direct path must read the requested data shard"
|
||||
);
|
||||
assert_eq!(counters[2].load(Ordering::SeqCst), 0);
|
||||
assert_eq!(counters[3].load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quantized_direct_verifies_every_frame_before_emitting_and_recovers_corruption() {
|
||||
let data = b"abcdefghijklmnop";
|
||||
let erasure = Erasure::new(2, 2, data.len());
|
||||
for corrupt in [false, true] {
|
||||
let (readers, counters) = quantized_counting_readers(&erasure, data, 4, 0, 8, corrupt.then_some(0)).await;
|
||||
let mut output = Vec::new();
|
||||
let outcome = erasure
|
||||
.decode_quantized_range_with_stripe_handles_and_reopeners(
|
||||
&mut output,
|
||||
readers,
|
||||
2,
|
||||
6,
|
||||
8,
|
||||
None,
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
outcome.written, 6,
|
||||
"corrupt={corrupt}: authenticated or reconstructed range must complete"
|
||||
);
|
||||
assert_eq!(output, &data[2..8], "corrupt={corrupt}: no corrupt prefix may reach the writer");
|
||||
assert_eq!(
|
||||
outcome.repair.needed(false),
|
||||
corrupt,
|
||||
"observed corruption must survive successful reconstruction"
|
||||
);
|
||||
assert_eq!(
|
||||
counters[0].load(Ordering::SeqCst),
|
||||
2 * (HashAlgorithm::HighwayHash256S.size() + 4),
|
||||
"target must authenticate both frames exactly once, including the failing second frame"
|
||||
);
|
||||
if !corrupt {
|
||||
assert_eq!(outcome.frame_count, 2);
|
||||
assert_eq!(counters[1].load(Ordering::SeqCst), 0);
|
||||
} else {
|
||||
assert!(
|
||||
counters[1].load(Ordering::SeqCst) > 0,
|
||||
"reconstruction must read the remaining data shard"
|
||||
);
|
||||
assert!(counters[2].load(Ordering::SeqCst) + counters[3].load(Ordering::SeqCst) > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quantized_direct_missing_target_reconstructs_the_same_slice() {
|
||||
let data = b"abcdefghijklmnop";
|
||||
let erasure = Erasure::new(2, 2, data.len());
|
||||
let (mut readers, counters) = quantized_counting_readers(&erasure, data, 4, 4, 4, None).await;
|
||||
readers[1] = None;
|
||||
let mut output = Vec::new();
|
||||
let outcome = erasure
|
||||
.decode_quantized_range_with_stripe_handles_and_reopeners(
|
||||
&mut output,
|
||||
readers,
|
||||
5,
|
||||
2,
|
||||
4,
|
||||
None,
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(outcome.written, 2, "missing target must reconstruct from a read quorum");
|
||||
assert_eq!(output, &data[13..15], "fallback must remain aligned to the nonzero q slice");
|
||||
assert_eq!(counters[1].load(Ordering::SeqCst), 0);
|
||||
assert!(counters[0].load(Ordering::SeqCst) > 0);
|
||||
assert!(counters[2].load(Ordering::SeqCst) + counters[3].load(Ordering::SeqCst) > 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quantized_direct_unrecoverable_corruption_emits_no_bytes() {
|
||||
let data = b"abcdefghijklmnop";
|
||||
let erasure = Erasure::new(2, 2, data.len());
|
||||
let (mut readers, _) = quantized_counting_readers(&erasure, data, 4, 0, 4, Some(0)).await;
|
||||
readers[1] = None;
|
||||
readers[3] = None;
|
||||
let mut output = Vec::new();
|
||||
let outcome = erasure
|
||||
.decode_quantized_range_with_stripe_handles_and_reopeners(
|
||||
&mut output,
|
||||
readers,
|
||||
1,
|
||||
2,
|
||||
4,
|
||||
None,
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(outcome.error.is_some(), "insufficient reconstruction quorum must fail");
|
||||
assert_eq!(outcome.written, 0);
|
||||
assert!(output.is_empty(), "unverified data must never be emitted");
|
||||
assert!(outcome.repair.needed(false), "failed direct read must retain corruption evidence");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quantized_direct_preserves_writer_failure() {
|
||||
let data = b"abcdefghijklmnop";
|
||||
let erasure = Erasure::new(2, 2, data.len());
|
||||
let (readers, _) = quantized_counting_readers(&erasure, data, 4, 0, 4, None).await;
|
||||
let outcome = erasure
|
||||
.decode_quantized_range_with_stripe_handles_and_reopeners(
|
||||
&mut FailingEmitWriter,
|
||||
readers,
|
||||
1,
|
||||
2,
|
||||
4,
|
||||
None,
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(outcome.error.expect("writer failure must escape").kind(), ErrorKind::BrokenPipe);
|
||||
assert_eq!(outcome.written, 0);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
#[serial_test::serial]
|
||||
async fn quantized_direct_stalled_target_recovers_without_waiting_for_disk_timeout() {
|
||||
let data = b"abcdefghijklmnop";
|
||||
let erasure = Erasure::new(2, 2, data.len());
|
||||
let (readers, _) = quantized_counting_readers(&erasure, data, 4, 4, 4, None).await;
|
||||
let slow_until = TokioInstant::now() + Duration::from_secs(60);
|
||||
let readers = readers
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, reader)| {
|
||||
let bytes = reader.expect("fixture reader").inner_ref().inner.get_ref().clone();
|
||||
let source = if index == 1 {
|
||||
TestShardReader::ReadyAt {
|
||||
cursor: Cursor::new(bytes),
|
||||
ready_at: slow_until,
|
||||
sleep: None,
|
||||
}
|
||||
} else {
|
||||
TestShardReader::Ready(Cursor::new(bytes))
|
||||
};
|
||||
Some(BitrotReader::new_with_frame_size(
|
||||
source,
|
||||
erasure.shard_size(),
|
||||
4,
|
||||
HashAlgorithm::HighwayHash256S,
|
||||
false,
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let mut output = Vec::new();
|
||||
let started = TokioInstant::now();
|
||||
let outcome = temp_env::async_with_vars([(rustfs_config::ENV_OBJECT_DISK_READ_TIMEOUT, Some("30"))], async {
|
||||
erasure
|
||||
.decode_quantized_range_with_stripe_handles_and_reopeners(
|
||||
&mut output,
|
||||
readers,
|
||||
5,
|
||||
2,
|
||||
4,
|
||||
None,
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(outcome.written, 2, "fast parity must recover the stalled q slice");
|
||||
assert_eq!(output, &data[13..15], "timeout recovery must retain the original q offset");
|
||||
assert!(!outcome.repair.needed(true), "a hedged healthy target is not a missing storage shard");
|
||||
assert!(
|
||||
started.elapsed() <= Duration::from_millis(150),
|
||||
"direct attempt must admit reconstruction by the existing 100 ms hedge, elapsed={:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
#[serial_test::serial]
|
||||
async fn quantized_direct_pending_healthy_target_survives_missing_or_corrupt_parity() {
|
||||
let data = b"abcdefghijklmnop";
|
||||
let erasure = Erasure::new(2, 2, data.len());
|
||||
for corrupt_parity in [false, true] {
|
||||
let (readers, _) = quantized_counting_readers(&erasure, data, 4, 4, 4, None).await;
|
||||
let started = TokioInstant::now();
|
||||
let ready_at = started + Duration::from_millis(200);
|
||||
let readers = readers
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, reader)| {
|
||||
let mut bytes = reader.expect("fixture reader").inner_ref().inner.get_ref().clone();
|
||||
if index >= erasure.data_shards {
|
||||
if !corrupt_parity {
|
||||
return None;
|
||||
}
|
||||
*bytes.last_mut().expect("parity payload") ^= 0x80;
|
||||
}
|
||||
let source = if index == 1 {
|
||||
TestShardReader::ReadyAt {
|
||||
cursor: Cursor::new(bytes),
|
||||
ready_at,
|
||||
sleep: None,
|
||||
}
|
||||
} else {
|
||||
TestShardReader::Ready(Cursor::new(bytes))
|
||||
};
|
||||
Some(BitrotReader::new_with_frame_size(
|
||||
source,
|
||||
erasure.shard_size(),
|
||||
4,
|
||||
HashAlgorithm::HighwayHash256S,
|
||||
false,
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let mut output = Vec::new();
|
||||
let outcome = temp_env::async_with_vars([(rustfs_config::ENV_OBJECT_DISK_READ_TIMEOUT, Some("30"))], async {
|
||||
erasure
|
||||
.decode_quantized_range_with_stripe_handles_and_reopeners(
|
||||
&mut output,
|
||||
readers,
|
||||
5,
|
||||
2,
|
||||
4,
|
||||
None,
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(
|
||||
outcome.error.is_none(),
|
||||
"corrupt_parity={corrupt_parity}: healthy target must remain eligible"
|
||||
);
|
||||
assert_eq!(outcome.written, 2);
|
||||
assert_eq!(output, &data[13..15], "a failed competing quorum must not emit or duplicate range bytes");
|
||||
assert!(
|
||||
started.elapsed() >= Duration::from_millis(200) && started.elapsed() <= Duration::from_millis(250),
|
||||
"corrupt_parity={corrupt_parity}: wait for the healthy target, not the 30 s disk deadline"
|
||||
);
|
||||
assert_eq!(
|
||||
outcome.repair.needed(false),
|
||||
corrupt_parity,
|
||||
"actual observed parity corruption must survive a successful direct winner"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a production-shaped reader set: data shards as opened stream
|
||||
/// readers, parity shards as *unopened* deferred readers carrying stripe
|
||||
/// handles (mirroring `fill_deferred_bitrot_readers`). `truncate` shortens
|
||||
@@ -3305,6 +4034,12 @@ mod tests {
|
||||
|
||||
assert_eq!(defaulted.read_costs, vec![ShardReadCost::Unknown; 3]);
|
||||
assert!(defaulted.verify_reconstruction);
|
||||
|
||||
let quantized: ParallelReader<Cursor<Vec<u8>>> =
|
||||
ParallelReader::new_for_quantized_decode(vec![None, None, None], Erasure::new(2, 1, 64), 16, None, None);
|
||||
assert!(quantized.verify_reconstruction);
|
||||
assert!(quantized.demand_bound_lockstep);
|
||||
assert_eq!(quantized.engaged.as_slice(), &[true, true, false]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -39,7 +39,7 @@ use std::pin::Pin;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Instant;
|
||||
use tokio::io::{AsyncRead, ReadBuf};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, ReadBuf};
|
||||
use tracing::debug;
|
||||
|
||||
#[cfg(all(test, feature = "hotpath"))]
|
||||
@@ -142,6 +142,7 @@ struct BitrotReaderSource {
|
||||
path: String,
|
||||
offset: usize,
|
||||
length: usize,
|
||||
small_shard: bool,
|
||||
use_mmap_read: bool,
|
||||
stage_metrics: Option<BitrotReaderStageMetrics>,
|
||||
}
|
||||
@@ -155,6 +156,7 @@ impl BitrotReaderSource {
|
||||
&self.path,
|
||||
self.offset,
|
||||
self.length,
|
||||
self.small_shard,
|
||||
self.use_mmap_read,
|
||||
self.stage_metrics.map(|metrics| metrics.path),
|
||||
)
|
||||
@@ -170,6 +172,7 @@ async fn open_reader_source(
|
||||
path: &str,
|
||||
offset: usize,
|
||||
length: usize,
|
||||
small_shard: bool,
|
||||
use_mmap_read: bool,
|
||||
metrics_path: Option<&'static str>,
|
||||
) -> disk::error::Result<Option<BoxedObjectReader>> {
|
||||
@@ -182,14 +185,45 @@ async fn open_reader_source(
|
||||
} else if let Some(disk) = disk {
|
||||
#[cfg(test)]
|
||||
crate::set_disk::disk_call_counters::record_shard_open(path, false);
|
||||
open_disk_reader(disk, bucket, path, offset, length, use_mmap_read, metrics_path)
|
||||
.await
|
||||
.map(Some)
|
||||
let buffer_stream = small_shard && length >= MIN_BUFFERED_STREAM_BYTES;
|
||||
let reader = open_disk_reader(disk, bucket, path, offset, length, use_mmap_read, metrics_path).await?;
|
||||
let reader = if buffer_stream && matches!(reader, ShardReader::Stream(_)) && disk.is_local() {
|
||||
buffer_local_shard_stream(reader, length)?
|
||||
} else {
|
||||
reader
|
||||
};
|
||||
Ok(Some(reader))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
const MIN_BUFFERED_STREAM_BYTES: usize = 1024 * 1024;
|
||||
|
||||
fn buffer_local_shard_stream(reader: ShardReader, length: usize) -> disk::error::Result<ShardReader> {
|
||||
if length < MIN_BUFFERED_STREAM_BYTES {
|
||||
return Ok(reader);
|
||||
}
|
||||
let ShardReader::Stream(reader) = reader else {
|
||||
return Ok(reader);
|
||||
};
|
||||
let limit = u64::try_from(length).map_err(|_| DiskError::FileCorrupt)?;
|
||||
if disk::has_resource_io_scope() {
|
||||
// ResourceFileReader reserves its buffer on demand. Prefetching here would
|
||||
// enlarge that reservation and allocate a second, unaccounted buffer.
|
||||
return Ok(ShardReader::Stream(Box::new(reader.take(limit))));
|
||||
}
|
||||
// Small layout stripes otherwise dispatch a blocking file read per frame.
|
||||
// Short ranges keep direct reads: the caller's conservative stream span
|
||||
// can include an extra stripe beyond the final requested block. Long
|
||||
// streams stay bounded to that span; prefetched frames still authenticate
|
||||
// individually when consumed by the bitrot reader.
|
||||
Ok(ShardReader::Stream(Box::new(tokio::io::BufReader::with_capacity(
|
||||
256 * 1024,
|
||||
reader.take(limit),
|
||||
))))
|
||||
}
|
||||
|
||||
struct FirstReadMetricsReader {
|
||||
inner: FileReader,
|
||||
metrics_path: &'static str,
|
||||
@@ -555,6 +589,29 @@ fn bitrot_encoded_range(offset: usize, length: usize, shard_size: usize, checksu
|
||||
adjust_shard_read_params(offset, length, shard_size, &checksum_algo)
|
||||
}
|
||||
|
||||
pub(crate) fn bitrot_encoded_range_with_frame_size(
|
||||
offset: usize,
|
||||
length: usize,
|
||||
shard_size: usize,
|
||||
frame_size: usize,
|
||||
checksum_algo: HashAlgorithm,
|
||||
) -> (usize, usize) {
|
||||
if frame_size == shard_size {
|
||||
return bitrot_encoded_range(offset, length, shard_size, checksum_algo);
|
||||
}
|
||||
|
||||
// A frame-aligned range may begin inside a logical shard. Skip the hashes
|
||||
// in preceding logical shards as well as those before this frame.
|
||||
let frames_per_shard = shard_size.div_ceil(frame_size);
|
||||
let hash_size = checksum_algo.size();
|
||||
let logical_shards = offset / shard_size;
|
||||
let within_shard = offset % shard_size;
|
||||
let frame_index = within_shard / frame_size;
|
||||
let physical_offset = logical_shards * (shard_size + frames_per_shard * hash_size) + within_shard + frame_index * hash_size;
|
||||
let physical_length = length + length.div_ceil(frame_size) * hash_size;
|
||||
(physical_offset, physical_length)
|
||||
}
|
||||
|
||||
/// Adjusts a raw (offset, length) pair to account for per-shard checksum overhead.
|
||||
/// Returns (adjusted_offset, adjusted_length).
|
||||
pub(crate) fn adjust_shard_read_params(
|
||||
@@ -686,12 +743,44 @@ pub(crate) async fn create_bitrot_reader_from_bytes_with_stage_metrics(
|
||||
skip_verify: bool,
|
||||
use_mmap_read: bool,
|
||||
stage_metrics: Option<BitrotReaderStageMetrics>,
|
||||
) -> disk::error::Result<Option<BitrotReader<ShardReader>>> {
|
||||
create_bitrot_reader_from_bytes_with_frame_size_and_stage_metrics(
|
||||
inline_data,
|
||||
disk,
|
||||
bucket,
|
||||
path,
|
||||
offset,
|
||||
length,
|
||||
shard_size,
|
||||
shard_size,
|
||||
checksum_algo,
|
||||
skip_verify,
|
||||
use_mmap_read,
|
||||
stage_metrics,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn create_bitrot_reader_from_bytes_with_frame_size_and_stage_metrics(
|
||||
inline_data: Option<Bytes>,
|
||||
disk: Option<&DiskStore>,
|
||||
bucket: &str,
|
||||
path: &str,
|
||||
offset: usize,
|
||||
length: usize,
|
||||
shard_size: usize,
|
||||
frame_size: usize,
|
||||
checksum_algo: HashAlgorithm,
|
||||
skip_verify: bool,
|
||||
use_mmap_read: bool,
|
||||
stage_metrics: Option<BitrotReaderStageMetrics>,
|
||||
) -> disk::error::Result<Option<BitrotReader<ShardReader>>> {
|
||||
let stage_metrics = stage_metrics.filter(|_| rustfs_io_metrics::get_stage_metrics_enabled());
|
||||
let stage_metrics_enabled = stage_metrics.is_some();
|
||||
|
||||
let reader_construction_start = stage_metrics_enabled.then(Instant::now);
|
||||
let (offset, length) = bitrot_encoded_range(offset, length, shard_size, checksum_algo.clone());
|
||||
let (offset, length) = bitrot_encoded_range_with_frame_size(offset, length, shard_size, frame_size, checksum_algo.clone());
|
||||
if let Some(metrics) = stage_metrics {
|
||||
record_get_stage_duration_if_enabled(metrics.path, metrics.reader_construction_stage, reader_construction_start);
|
||||
}
|
||||
@@ -704,6 +793,7 @@ pub(crate) async fn create_bitrot_reader_from_bytes_with_stage_metrics(
|
||||
path,
|
||||
offset,
|
||||
length,
|
||||
shard_size != 0 && shard_size <= 128 * 1024,
|
||||
use_mmap_read,
|
||||
stage_metrics.map(|metrics| metrics.path),
|
||||
)
|
||||
@@ -713,7 +803,8 @@ pub(crate) async fn create_bitrot_reader_from_bytes_with_stage_metrics(
|
||||
}
|
||||
|
||||
let bitrot_reader_init_start = stage_metrics_enabled.then(Instant::now);
|
||||
let reader = reader.map(|reader| BitrotReader::new(reader, shard_size, checksum_algo, skip_verify));
|
||||
let reader =
|
||||
reader.map(|reader| BitrotReader::new_with_frame_size(reader, shard_size, frame_size, checksum_algo, skip_verify));
|
||||
if let Some(metrics) = stage_metrics {
|
||||
record_get_stage_duration_if_enabled(metrics.path, metrics.bitrot_reader_init_stage, bitrot_reader_init_start);
|
||||
}
|
||||
@@ -766,8 +857,38 @@ pub(crate) fn create_deferred_bitrot_reader_with_stripe_handle(
|
||||
skip_verify: bool,
|
||||
use_mmap_read: bool,
|
||||
) -> (BitrotReader<ShardReader>, DeferredReaderStripeHandle) {
|
||||
let stripe_stride = shard_size + checksum_algo.size();
|
||||
let (offset, length) = bitrot_encoded_range(offset, length, shard_size, checksum_algo.clone());
|
||||
create_deferred_bitrot_reader_with_stripe_handle_and_frame_size(
|
||||
inline_data,
|
||||
disk,
|
||||
bucket,
|
||||
path,
|
||||
offset,
|
||||
length,
|
||||
shard_size,
|
||||
shard_size,
|
||||
checksum_algo,
|
||||
skip_verify,
|
||||
use_mmap_read,
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn create_deferred_bitrot_reader_with_stripe_handle_and_frame_size(
|
||||
inline_data: Option<Bytes>,
|
||||
disk: Option<DiskStore>,
|
||||
bucket: &str,
|
||||
path: &str,
|
||||
offset: usize,
|
||||
length: usize,
|
||||
shard_size: usize,
|
||||
frame_size: usize,
|
||||
checksum_algo: HashAlgorithm,
|
||||
skip_verify: bool,
|
||||
use_mmap_read: bool,
|
||||
) -> (BitrotReader<ShardReader>, DeferredReaderStripeHandle) {
|
||||
let frames_per_shard = shard_size.div_ceil(frame_size);
|
||||
let stripe_stride = shard_size + frames_per_shard * checksum_algo.size();
|
||||
let (offset, length) = bitrot_encoded_range_with_frame_size(offset, length, shard_size, frame_size, checksum_algo.clone());
|
||||
let inline_source = inline_data.is_some();
|
||||
let source = BitrotReaderSource {
|
||||
inline_data,
|
||||
@@ -776,6 +897,7 @@ pub(crate) fn create_deferred_bitrot_reader_with_stripe_handle(
|
||||
path: if inline_source { String::new() } else { path.to_string() },
|
||||
offset,
|
||||
length,
|
||||
small_shard: shard_size != 0 && shard_size <= 128 * 1024,
|
||||
use_mmap_read,
|
||||
stage_metrics: None,
|
||||
};
|
||||
@@ -785,7 +907,13 @@ pub(crate) fn create_deferred_bitrot_reader_with_stripe_handle(
|
||||
// The deferred parity reader opens its source lazily, so it cannot hand out an
|
||||
// in-memory block up front; it stays on the streaming path. Parity shards are
|
||||
// only read when a data shard fails, so the fast path is not needed here.
|
||||
let reader = BitrotReader::new(ShardReader::Stream(Box::new(deferred)), shard_size, checksum_algo, skip_verify);
|
||||
let reader = BitrotReader::new_with_frame_size(
|
||||
ShardReader::Stream(Box::new(deferred)),
|
||||
shard_size,
|
||||
frame_size,
|
||||
checksum_algo,
|
||||
skip_verify,
|
||||
);
|
||||
(reader, handle)
|
||||
}
|
||||
|
||||
@@ -876,6 +1004,184 @@ mod tests {
|
||||
use super::*;
|
||||
use rustfs_rio::ChunkReader;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct CountingWindowReader {
|
||||
source: Cursor<Vec<u8>>,
|
||||
reads: Arc<AtomicUsize>,
|
||||
bytes: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl AsyncRead for CountingWindowReader {
|
||||
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, out: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
|
||||
let before = out.filled().len();
|
||||
let result = Pin::new(&mut self.source).poll_read(cx, out);
|
||||
self.reads.fetch_add(1, Ordering::Relaxed);
|
||||
self.bytes.fetch_add(out.filled().len() - before, Ordering::Relaxed);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn buffered_local_shard_stream_coalesces_reads_without_crossing_window() {
|
||||
const SHARD: usize = 32 * 1024;
|
||||
const TAIL: usize = 12_001;
|
||||
let algo = HashAlgorithm::HighwayHash256S;
|
||||
let data = vec![37; 37 * SHARD + TAIL];
|
||||
let mut encoded = Vec::new();
|
||||
{
|
||||
let mut writer = crate::erasure::coding::BitrotWriter::new(&mut encoded, SHARD, algo.clone());
|
||||
for chunk in data.chunks(SHARD) {
|
||||
writer.write(chunk).await.expect("encode full shards and short tail");
|
||||
}
|
||||
}
|
||||
let window = encoded.len();
|
||||
encoded.extend_from_slice(&vec![99; 100_000]);
|
||||
let reads = Arc::new(AtomicUsize::new(0));
|
||||
let bytes = Arc::new(AtomicUsize::new(0));
|
||||
let source = ShardReader::Stream(Box::new(CountingWindowReader {
|
||||
source: Cursor::new(encoded),
|
||||
reads: Arc::clone(&reads),
|
||||
bytes: Arc::clone(&bytes),
|
||||
}));
|
||||
let source = buffer_local_shard_stream(source, window).expect("buffer the exact local window");
|
||||
let mut reader = BitrotReader::new(source, SHARD, algo, false);
|
||||
let mut actual = Vec::new();
|
||||
for chunk in data.chunks(SHARD) {
|
||||
reader
|
||||
.read_appending(&mut actual, chunk.len())
|
||||
.await
|
||||
.expect("verify each buffered shard");
|
||||
}
|
||||
assert_eq!(actual, data);
|
||||
assert_eq!(
|
||||
bytes.load(Ordering::Relaxed),
|
||||
window,
|
||||
"prefetch must not consume the sentinel beyond the window"
|
||||
);
|
||||
assert_eq!(
|
||||
reads.load(Ordering::Relaxed),
|
||||
5,
|
||||
"thirty-eight logical reads should share five bounded source reads"
|
||||
);
|
||||
let mut extra = vec![0; 1];
|
||||
assert_eq!(
|
||||
reader.read(&mut extra).await.expect_err("window ended").kind(),
|
||||
io::ErrorKind::UnexpectedEof
|
||||
);
|
||||
assert_eq!(bytes.load(Ordering::Relaxed), window);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn buffered_local_shard_stream_still_rejects_corrupt_prefetched_frame() {
|
||||
const SHARD: usize = 32 * 1024;
|
||||
let algo = HashAlgorithm::HighwayHash256S;
|
||||
let payload = vec![73; SHARD];
|
||||
let mut encoded = Vec::new();
|
||||
{
|
||||
let mut writer = crate::erasure::coding::BitrotWriter::new(&mut encoded, SHARD, algo.clone());
|
||||
for _ in 0..33 {
|
||||
writer.write(&payload).await.expect("encode fixture shards");
|
||||
}
|
||||
}
|
||||
encoded[SHARD + algo.size() + algo.size() + 7] ^= 1;
|
||||
let window = encoded.len();
|
||||
let reads = Arc::new(AtomicUsize::new(0));
|
||||
let bytes = Arc::new(AtomicUsize::new(0));
|
||||
let source = buffer_local_shard_stream(
|
||||
ShardReader::Stream(Box::new(CountingWindowReader {
|
||||
source: Cursor::new(encoded),
|
||||
reads: Arc::clone(&reads),
|
||||
bytes: Arc::clone(&bytes),
|
||||
})),
|
||||
window,
|
||||
)
|
||||
.expect("buffer corruption fixture");
|
||||
let mut reader = BitrotReader::new(source, SHARD, algo, false);
|
||||
let mut output = vec![0xa5; SHARD];
|
||||
reader.read(&mut output).await.expect("first frame is valid");
|
||||
assert_eq!(output, payload);
|
||||
assert_eq!(reads.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(
|
||||
bytes.load(Ordering::Relaxed),
|
||||
256 * 1024,
|
||||
"long stream must prefetch the corrupt second frame"
|
||||
);
|
||||
output.fill(0xa5);
|
||||
assert_eq!(
|
||||
reader
|
||||
.read(&mut output)
|
||||
.await
|
||||
.expect_err("corrupt second frame must fail")
|
||||
.kind(),
|
||||
io::ErrorKind::InvalidData
|
||||
);
|
||||
assert!(
|
||||
output.iter().all(|byte| *byte == 0xa5),
|
||||
"corrupt prefetched data must not escape verification"
|
||||
);
|
||||
assert_eq!(
|
||||
reads.load(Ordering::Relaxed),
|
||||
1,
|
||||
"corrupt prefetched frame must fail without another source read"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn buffered_local_shard_stream_does_not_prefetch_conservative_short_range_tail() {
|
||||
const BLOCK: usize = 256 * 1024;
|
||||
const SHARD: usize = BLOCK / 2;
|
||||
let algo = HashAlgorithm::HighwayHash256S;
|
||||
let erasure = crate::erasure::coding::Erasure::new(2, 2, BLOCK);
|
||||
// An aligned 1 MiB Range consumes four data-shard frames, while the
|
||||
// existing reader planner conservatively opens five logical shards.
|
||||
let logical_window = erasure.shard_file_offset(0, 4 * BLOCK, 6 * BLOCK);
|
||||
assert_eq!(logical_window, 5 * SHARD);
|
||||
let (_, wire_window) = adjust_shard_read_params(0, logical_window, SHARD, &algo);
|
||||
let payload = vec![73; SHARD];
|
||||
let mut encoded = Vec::new();
|
||||
{
|
||||
let mut writer = crate::erasure::coding::BitrotWriter::new(&mut encoded, SHARD, algo.clone());
|
||||
for _ in 0..4 {
|
||||
writer.write(&payload).await.expect("encode requested range frames");
|
||||
}
|
||||
writer
|
||||
.write(&vec![99; SHARD])
|
||||
.await
|
||||
.expect("encode unrequested conservative tail frame");
|
||||
}
|
||||
assert_eq!(encoded.len(), wire_window);
|
||||
let reads = Arc::new(AtomicUsize::new(0));
|
||||
let bytes = Arc::new(AtomicUsize::new(0));
|
||||
let source = buffer_local_shard_stream(
|
||||
ShardReader::Stream(Box::new(CountingWindowReader {
|
||||
source: Cursor::new(encoded),
|
||||
reads: Arc::clone(&reads),
|
||||
bytes: Arc::clone(&bytes),
|
||||
})),
|
||||
wire_window,
|
||||
)
|
||||
.expect("open conservative short range stream");
|
||||
let mut reader = BitrotReader::new(source, SHARD, algo.clone(), false);
|
||||
let mut output = Vec::new();
|
||||
for _ in 0..4 {
|
||||
reader
|
||||
.read_appending(&mut output, SHARD)
|
||||
.await
|
||||
.expect("read and authenticate requested frame");
|
||||
}
|
||||
assert_eq!(output, payload.repeat(4));
|
||||
assert_eq!(
|
||||
bytes.load(Ordering::Relaxed),
|
||||
4 * (SHARD + algo.size()),
|
||||
"four decoded frames must not prefetch the unrequested fifth frame"
|
||||
);
|
||||
assert_eq!(
|
||||
reads.load(Ordering::Relaxed),
|
||||
4,
|
||||
"short range should retain direct per-frame source reads"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bitrot_create_file_size_grows_known_length_by_checksums() {
|
||||
@@ -1068,6 +1374,96 @@ mod tests {
|
||||
(disk, dir)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resource_scoped_local_shard_reads_on_demand_within_its_window() {
|
||||
use crate::disk::{BackgroundMemoryBudget, test_resource_units, with_optional_resource_unit};
|
||||
|
||||
let (disk, _dir) = local_test_disk().await;
|
||||
let window = MIN_BUFFERED_STREAM_BYTES;
|
||||
disk.make_volume("test-bucket").await.expect("create volume");
|
||||
disk.write_all("test-bucket", "obj/shard", Bytes::from(vec![37; window + 1]))
|
||||
.await
|
||||
.expect("write shard with a byte beyond the window");
|
||||
let budget = BackgroundMemoryBudget::new();
|
||||
budget.set_sampled_limit(128 * 1024, std::time::Duration::from_secs(60));
|
||||
let (resources, _) = test_resource_units(1);
|
||||
let mut reader = with_optional_resource_unit(
|
||||
Some(resources.with_memory_budget(budget.clone())),
|
||||
open_reader_source(None, Some(&disk), "test-bucket", "obj/shard", 0, window, true, false, None),
|
||||
)
|
||||
.await
|
||||
.expect("open resource-scoped shard")
|
||||
.expect("local reader");
|
||||
let mut chunk = [0u8; 8192];
|
||||
let mut total = 0;
|
||||
loop {
|
||||
let n = reader.read(&mut chunk).await.expect("read without a 256 KiB prefetch grant");
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
assert!(chunk[..n].iter().all(|&byte| byte == 37));
|
||||
total += n;
|
||||
}
|
||||
assert_eq!(total, window);
|
||||
drop(reader);
|
||||
assert_eq!(budget.snapshot().used, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deferred_local_opener_applies_buffer_gate_to_current_window() {
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
const SHARD: usize = 128 * 1024;
|
||||
const WINDOW: usize = 1024 * 1024;
|
||||
let (disk, _dir) = local_test_disk().await;
|
||||
let payload: Vec<_> = (0u8..=250).cycle().take(2 * WINDOW + 1).collect();
|
||||
disk.make_volume("test-bucket").await.expect("create test volume");
|
||||
disk.write_all("test-bucket", "obj/buffer-gate", Bytes::from(payload.clone()))
|
||||
.await
|
||||
.expect("write source with bytes beyond every requested window");
|
||||
for (shard_size, length, advance, expected_end) in [
|
||||
(SHARD, WINDOW, 0, WINDOW),
|
||||
(SHARD + 1, WINDOW, 0, payload.len()),
|
||||
(SHARD, WINDOW + SHARD, 1, WINDOW + SHARD),
|
||||
(SHARD, WINDOW, 1, payload.len()),
|
||||
] {
|
||||
let (_reader, handle) = create_deferred_bitrot_reader_with_stripe_handle(
|
||||
None,
|
||||
Some(disk.clone()),
|
||||
"test-bucket",
|
||||
"obj/buffer-gate",
|
||||
0,
|
||||
length,
|
||||
shard_size,
|
||||
HashAlgorithm::None,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
assert!(handle.advance_stripes(advance), "advance the unopened source");
|
||||
let source = {
|
||||
let mut state = handle.state.lock().expect("lock pending reader state");
|
||||
let DeferredObjectReaderState::Pending(source) = &mut *state else {
|
||||
panic!("advancing stripes must leave the source unopened");
|
||||
};
|
||||
source.take().expect("pending source must be available")
|
||||
};
|
||||
let mut source = source
|
||||
.open()
|
||||
.await
|
||||
.expect("open advanced local source")
|
||||
.expect("disk source must produce a reader");
|
||||
let mut actual = Vec::new();
|
||||
source.read_to_end(&mut actual).await.expect("read the opened source");
|
||||
// Unbuffered local streams expose the file remainder; buffered streams
|
||||
// must stop at the current encoded window, including after an advance.
|
||||
assert_eq!(
|
||||
actual.as_slice(),
|
||||
&payload[advance * shard_size..expected_end],
|
||||
"wrong buffering boundary for shard {shard_size}, advance {advance}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "hotpath")]
|
||||
async fn remote_test_disk(transport: TestRemoteDataTransport) -> (DiskStore, TestRemoteDataTransport) {
|
||||
use crate::disk::endpoint::Endpoint;
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
//! Request and storage contracts for the per-object erasure-code block size.
|
||||
//!
|
||||
//! The request hint is deliberately kept separate from persisted file
|
||||
//! metadata. Application code resolves the hint and writes the selected
|
||||
//! value to the transient marker below; the set layer consumes that marker
|
||||
//! before constructing `FileInfo`. Readers use the block size persisted in
|
||||
//! `FileInfo::erasure`, never the request metadata.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
/// The historical RustFS erasure block size.
|
||||
pub const DEFAULT_EC_BLOCK_SIZE: usize = 1024 * 1024;
|
||||
|
||||
/// The only block sizes accepted for new objects.
|
||||
pub const EC_BLOCK_SIZE_CANDIDATES: [usize; 4] = [64 * 1024, 256 * 1024, 1024 * 1024, 4 * 1024 * 1024];
|
||||
|
||||
/// User metadata key after the `x-amz-meta-` prefix has been removed.
|
||||
pub const EC_BLOCK_SIZE_HINT_METADATA_KEY: &str = "rustfs-ec-block-size-hint";
|
||||
|
||||
/// Internal marker passed from the request layer to the storage writer.
|
||||
/// It is always removed before user metadata is persisted.
|
||||
pub const EC_BLOCK_SIZE_HINT_INTERNAL_SUFFIX: &str = "ec-block-size-hint";
|
||||
pub const EC_BLOCK_SIZE_HINT_INTERNAL_KEY: &str = "x-rustfs-internal-ec-block-size-hint";
|
||||
|
||||
/// Internal projection copied into `ObjectInfo` for response construction.
|
||||
/// The projection is filtered from S3 user metadata.
|
||||
pub const EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX: &str = "ec-block-size";
|
||||
pub const EC_BLOCK_SIZE_INFO_INTERNAL_KEY: &str = "x-rustfs-internal-ec-block-size";
|
||||
|
||||
pub const EC_BLOCK_SIZE_RESPONSE_HEADER: &str = "x-rustfs-effective-ec-block-size";
|
||||
pub const EC_BLOCK_SIZE_HINT_STATUS_HEADER: &str = "x-rustfs-layout-hint-status";
|
||||
pub const EC_BLOCK_SIZE_HINT_REASON_HEADER: &str = "x-rustfs-layout-hint-reason";
|
||||
|
||||
/// Persisted marker for the per-shard bitrot frame size used by new EC
|
||||
/// objects. The value is internal metadata and is always written through the
|
||||
/// RustFS/MinIO compatibility-key pair.
|
||||
pub const EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX: &str = "ec-read-quantum";
|
||||
pub const EC_READ_QUANTUM_INFO_INTERNAL_KEY: &str = "x-rustfs-internal-ec-read-quantum";
|
||||
|
||||
/// Keep the physical read quantum bounded even when an object chooses a large
|
||||
/// layout block. The smaller entries cover the candidate layouts whose shard
|
||||
/// size is below the target quantum.
|
||||
pub const EC_READ_QUANTUM_CANDIDATES: [usize; 9] = [
|
||||
1024 * 1024,
|
||||
512 * 1024,
|
||||
256 * 1024,
|
||||
128 * 1024,
|
||||
64 * 1024,
|
||||
32 * 1024,
|
||||
16 * 1024,
|
||||
8 * 1024,
|
||||
4 * 1024,
|
||||
];
|
||||
|
||||
const EC_READ_QUANTUM_LEGACY_CANDIDATES: [usize; 7] =
|
||||
[256 * 1024, 128 * 1024, 64 * 1024, 32 * 1024, 16 * 1024, 8 * 1024, 4 * 1024];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EcReadQuantumMetadataError {
|
||||
ConflictingValues,
|
||||
InvalidValue,
|
||||
UnsupportedGeometry,
|
||||
}
|
||||
|
||||
impl fmt::Display for EcReadQuantumMetadataError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::ConflictingValues => "EC read quantum metadata has conflicting compatibility values",
|
||||
Self::InvalidValue => "EC read quantum metadata is not a supported decimal value",
|
||||
Self::UnsupportedGeometry => "EC read quantum metadata does not match the object geometry",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for EcReadQuantumMetadataError {}
|
||||
|
||||
/// A syntactically valid request value. It may still be outside the
|
||||
/// supported candidate set.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ClientEcBlockSizeHint {
|
||||
pub requested_bytes: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EcBlockSizeHintError {
|
||||
Empty,
|
||||
TooLong,
|
||||
NonAsciiDecimal,
|
||||
Zero,
|
||||
Overflow,
|
||||
}
|
||||
|
||||
impl fmt::Display for EcBlockSizeHintError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let message = match self {
|
||||
Self::Empty => "value is empty",
|
||||
Self::TooLong => "value has more than 20 digits",
|
||||
Self::NonAsciiDecimal => "value must contain only ASCII decimal digits",
|
||||
Self::Zero => "value must be greater than zero",
|
||||
Self::Overflow => "value does not fit in an unsigned 64-bit integer",
|
||||
};
|
||||
f.write_str(message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for EcBlockSizeHintError {}
|
||||
|
||||
/// Parse the strict wire representation required by the SPEC.
|
||||
pub fn parse_ec_block_size_hint(value: &str) -> Result<ClientEcBlockSizeHint, EcBlockSizeHintError> {
|
||||
if value.is_empty() {
|
||||
return Err(EcBlockSizeHintError::Empty);
|
||||
}
|
||||
if value.len() > 20 {
|
||||
return Err(EcBlockSizeHintError::TooLong);
|
||||
}
|
||||
if !value.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return Err(EcBlockSizeHintError::NonAsciiDecimal);
|
||||
}
|
||||
let requested_bytes = value.parse::<u64>().map_err(|_| EcBlockSizeHintError::Overflow)?;
|
||||
if requested_bytes == 0 {
|
||||
return Err(EcBlockSizeHintError::Zero);
|
||||
}
|
||||
Ok(ClientEcBlockSizeHint { requested_bytes })
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EcBlockSizeHintIgnoreReason {
|
||||
Disabled,
|
||||
FleetNotConfirmed,
|
||||
UnsupportedSize,
|
||||
IneligibleWrite,
|
||||
}
|
||||
|
||||
impl EcBlockSizeHintIgnoreReason {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Disabled => "disabled",
|
||||
Self::FleetNotConfirmed => "fleet-unconfirmed",
|
||||
Self::UnsupportedSize => "unsupported-size",
|
||||
Self::IneligibleWrite => "unsupported-write-mode",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EcBlockSizeHintOutcome {
|
||||
NoHint,
|
||||
Applied,
|
||||
Ignored(EcBlockSizeHintIgnoreReason),
|
||||
}
|
||||
|
||||
impl EcBlockSizeHintOutcome {
|
||||
pub const fn status_header(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::NoHint => None,
|
||||
Self::Applied => Some("applied"),
|
||||
Self::Ignored(_) => Some("ignored"),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn reason_header(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::Ignored(reason) => Some(reason.as_str()),
|
||||
Self::NoHint | Self::Applied => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ResolvedEcBlockSize {
|
||||
pub effective_block_size: usize,
|
||||
pub outcome: EcBlockSizeHintOutcome,
|
||||
}
|
||||
|
||||
/// Resolve a request hint after authentication and eligibility checks.
|
||||
///
|
||||
/// Disabled and fleet-unconfirmed requests deliberately do not parse the
|
||||
/// value. In those rollout phases the header remains ordinary user metadata,
|
||||
/// including when its value would be malformed.
|
||||
pub fn resolve_ec_block_size_hint(
|
||||
raw_hint: Option<&str>,
|
||||
feature_enabled: bool,
|
||||
fleet_confirmed: bool,
|
||||
eligible_write: bool,
|
||||
) -> Result<ResolvedEcBlockSize, EcBlockSizeHintError> {
|
||||
let Some(raw_hint) = raw_hint else {
|
||||
return Ok(ResolvedEcBlockSize {
|
||||
effective_block_size: DEFAULT_EC_BLOCK_SIZE,
|
||||
outcome: EcBlockSizeHintOutcome::NoHint,
|
||||
});
|
||||
};
|
||||
|
||||
if !feature_enabled {
|
||||
return Ok(ResolvedEcBlockSize {
|
||||
effective_block_size: DEFAULT_EC_BLOCK_SIZE,
|
||||
outcome: EcBlockSizeHintOutcome::Ignored(EcBlockSizeHintIgnoreReason::Disabled),
|
||||
});
|
||||
}
|
||||
if !fleet_confirmed {
|
||||
return Ok(ResolvedEcBlockSize {
|
||||
effective_block_size: DEFAULT_EC_BLOCK_SIZE,
|
||||
outcome: EcBlockSizeHintOutcome::Ignored(EcBlockSizeHintIgnoreReason::FleetNotConfirmed),
|
||||
});
|
||||
}
|
||||
|
||||
let hint = parse_ec_block_size_hint(raw_hint)?;
|
||||
let Some(effective_block_size) = usize::try_from(hint.requested_bytes)
|
||||
.ok()
|
||||
.filter(|size| EC_BLOCK_SIZE_CANDIDATES.contains(size))
|
||||
else {
|
||||
return Ok(ResolvedEcBlockSize {
|
||||
effective_block_size: DEFAULT_EC_BLOCK_SIZE,
|
||||
outcome: EcBlockSizeHintOutcome::Ignored(EcBlockSizeHintIgnoreReason::UnsupportedSize),
|
||||
});
|
||||
};
|
||||
|
||||
if !eligible_write {
|
||||
return Ok(ResolvedEcBlockSize {
|
||||
effective_block_size: DEFAULT_EC_BLOCK_SIZE,
|
||||
outcome: EcBlockSizeHintOutcome::Ignored(EcBlockSizeHintIgnoreReason::IneligibleWrite),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(ResolvedEcBlockSize {
|
||||
effective_block_size,
|
||||
outcome: EcBlockSizeHintOutcome::Applied,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_supported_ec_block_size(value: usize) -> bool {
|
||||
EC_BLOCK_SIZE_CANDIDATES.contains(&value)
|
||||
}
|
||||
|
||||
/// Return whether the storage writer rollout is enabled and fleet-confirmed.
|
||||
/// Read it on the write path so each new object uses the active process
|
||||
/// environment values.
|
||||
pub fn ec_read_quantum_write_enabled() -> bool {
|
||||
rustfs_utils::get_env_bool(rustfs_config::ENV_EC_READ_QUANTUM_ENABLE, rustfs_config::DEFAULT_EC_READ_QUANTUM_ENABLE)
|
||||
&& rustfs_utils::get_env_bool(
|
||||
rustfs_config::ENV_EC_READ_QUANTUM_FLEET_CONFIRMED,
|
||||
rustfs_config::DEFAULT_EC_READ_QUANTUM_FLEET_CONFIRMED,
|
||||
)
|
||||
}
|
||||
|
||||
/// Select a frame size that preserves exact EC geometry. A candidate must be
|
||||
/// a divisor of both the physical shard size and the logical layout block
|
||||
/// divided across data shards; this keeps every complete layout stripe aligned
|
||||
/// and leaves only the final object stripe short.
|
||||
pub fn select_ec_read_quantum(block_size: usize, data_shards: usize, shard_size: usize) -> Option<usize> {
|
||||
if block_size == 0 || data_shards == 0 || shard_size == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Small layouts benefit from half-shard frames because their common range
|
||||
// requests otherwise pull a complete data-plus-parity stripe. Larger
|
||||
// layouts use a coarser target to cap authenticated-frame count during
|
||||
// upload: the 1 MiB layout fits one frame per shard and the 4 MiB layout
|
||||
// uses two 1 MiB frames per shard. A 4 MiB range still avoids the legacy
|
||||
// multi-megabyte stripe read while PUT avoids paying for eight hashes per
|
||||
// shard.
|
||||
let target = if block_size <= 256 * 1024 {
|
||||
shard_size / 2
|
||||
} else {
|
||||
1024 * 1024
|
||||
};
|
||||
EC_READ_QUANTUM_CANDIDATES.into_iter().find(|candidate| {
|
||||
*candidate <= target && ec_read_quantum_matches_geometry(*candidate, block_size, data_shards, shard_size)
|
||||
})
|
||||
}
|
||||
|
||||
fn select_legacy_ec_read_quantum(block_size: usize, data_shards: usize, shard_size: usize) -> Option<usize> {
|
||||
if block_size == 0 || data_shards == 0 || shard_size == 0 {
|
||||
return None;
|
||||
}
|
||||
EC_READ_QUANTUM_LEGACY_CANDIDATES
|
||||
.into_iter()
|
||||
.find(|candidate| ec_read_quantum_matches_geometry(*candidate, block_size, data_shards, shard_size))
|
||||
}
|
||||
|
||||
fn ec_read_quantum_matches_geometry(quantum: usize, block_size: usize, data_shards: usize, shard_size: usize) -> bool {
|
||||
quantum > 0
|
||||
&& quantum <= shard_size
|
||||
&& EC_READ_QUANTUM_CANDIDATES.contains(&quantum)
|
||||
&& shard_size.is_multiple_of(quantum)
|
||||
&& quantum
|
||||
.checked_mul(data_shards)
|
||||
.is_some_and(|logical_quantum| block_size.is_multiple_of(logical_quantum))
|
||||
}
|
||||
|
||||
/// Resolve a persisted marker. Absence is the legacy layout-frame format;
|
||||
/// presence with a malformed or conflicting value is an error so a damaged
|
||||
/// metadata record cannot silently reinterpret the shard stream.
|
||||
pub fn persisted_ec_read_quantum(
|
||||
metadata: &HashMap<String, String>,
|
||||
block_size: usize,
|
||||
data_shards: usize,
|
||||
shard_size: usize,
|
||||
) -> Result<Option<usize>, EcReadQuantumMetadataError> {
|
||||
let present = rustfs_utils::http::metadata_compat::contains_key_str(metadata, EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX);
|
||||
let Some(value) = rustfs_utils::http::metadata_compat::get_consistent_str(metadata, EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX)
|
||||
else {
|
||||
return if present {
|
||||
Err(EcReadQuantumMetadataError::ConflictingValues)
|
||||
} else {
|
||||
Ok(None)
|
||||
};
|
||||
};
|
||||
let quantum = value.parse::<usize>().map_err(|_| EcReadQuantumMetadataError::InvalidValue)?;
|
||||
// Accept markers written by the previous selector as well as the current
|
||||
// smaller target. Existing 64 KiB and 256 KiB objects may carry a
|
||||
// full-shard marker and must remain readable after the rollout changes.
|
||||
let current = select_ec_read_quantum(block_size, data_shards, shard_size);
|
||||
let legacy = select_legacy_ec_read_quantum(block_size, data_shards, shard_size);
|
||||
if current != Some(quantum) && legacy != Some(quantum) {
|
||||
return Err(EcReadQuantumMetadataError::UnsupportedGeometry);
|
||||
}
|
||||
Ok(Some(quantum))
|
||||
}
|
||||
|
||||
pub fn insert_ec_read_quantum(metadata: &mut HashMap<String, String>, quantum: usize) {
|
||||
rustfs_utils::http::metadata_compat::insert_str(metadata, EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX, quantum.to_string());
|
||||
}
|
||||
|
||||
/// Consume a trusted transient marker from storage options.
|
||||
pub fn take_ec_block_size_hint(metadata: &mut std::collections::HashMap<String, String>) -> Option<usize> {
|
||||
let value = rustfs_utils::http::metadata_compat::get_consistent_str(metadata, EC_BLOCK_SIZE_HINT_INTERNAL_SUFFIX)
|
||||
.map(ToOwned::to_owned);
|
||||
rustfs_utils::http::metadata_compat::remove_str(metadata, EC_BLOCK_SIZE_HINT_INTERNAL_SUFFIX);
|
||||
let value = value?;
|
||||
let parsed = value.parse::<usize>().ok()?;
|
||||
is_supported_ec_block_size(parsed).then_some(parsed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parser_accepts_decimal_values_and_rejects_wire_variants() {
|
||||
assert_eq!(parse_ec_block_size_hint("65536").unwrap().requested_bytes, 65_536);
|
||||
for value in ["", "0", "+65536", "65_536", "65536 ", "1.0", "128"] {
|
||||
assert!(parse_ec_block_size_hint(value).is_err(), "{value:?} must be rejected");
|
||||
}
|
||||
assert_eq!(parse_ec_block_size_hint("18446744073709551615").unwrap().requested_bytes, u64::MAX);
|
||||
assert!(matches!(
|
||||
parse_ec_block_size_hint("18446744073709551616"),
|
||||
Err(EcBlockSizeHintError::Overflow)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolver_applies_each_candidate_only_when_rollout_and_write_are_eligible() {
|
||||
for candidate in EC_BLOCK_SIZE_CANDIDATES {
|
||||
let result = resolve_ec_block_size_hint(Some(&candidate.to_string()), true, true, true).unwrap();
|
||||
assert_eq!(result.effective_block_size, candidate);
|
||||
assert_eq!(result.outcome, EcBlockSizeHintOutcome::Applied);
|
||||
}
|
||||
assert_eq!(
|
||||
resolve_ec_block_size_hint(Some("131072"), true, true, true).unwrap().outcome,
|
||||
EcBlockSizeHintOutcome::Ignored(EcBlockSizeHintIgnoreReason::UnsupportedSize)
|
||||
);
|
||||
let ineligible = resolve_ec_block_size_hint(Some("65536"), true, true, false).unwrap();
|
||||
assert_eq!(
|
||||
ineligible.outcome,
|
||||
EcBlockSizeHintOutcome::Ignored(EcBlockSizeHintIgnoreReason::IneligibleWrite)
|
||||
);
|
||||
assert_eq!(ineligible.outcome.reason_header(), Some("unsupported-write-mode"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_and_unconfirmed_rollouts_do_not_turn_malformed_metadata_into_errors() {
|
||||
for (enabled, fleet, reason) in [
|
||||
(false, false, EcBlockSizeHintIgnoreReason::Disabled),
|
||||
(true, false, EcBlockSizeHintIgnoreReason::FleetNotConfirmed),
|
||||
] {
|
||||
let result = resolve_ec_block_size_hint(Some("not-a-number"), enabled, fleet, true).unwrap();
|
||||
assert_eq!(result.effective_block_size, DEFAULT_EC_BLOCK_SIZE);
|
||||
assert_eq!(result.outcome, EcBlockSizeHintOutcome::Ignored(reason));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transient_marker_is_consumed_only_for_supported_candidates() {
|
||||
let mut metadata = std::collections::HashMap::new();
|
||||
rustfs_utils::http::metadata_compat::insert_str(&mut metadata, EC_BLOCK_SIZE_HINT_INTERNAL_SUFFIX, "262144".to_string());
|
||||
assert_eq!(take_ec_block_size_hint(&mut metadata), Some(262_144));
|
||||
assert!(!metadata.contains_key(EC_BLOCK_SIZE_HINT_INTERNAL_KEY));
|
||||
assert!(!metadata.contains_key("x-minio-internal-ec-block-size-hint"));
|
||||
|
||||
let mut unsupported =
|
||||
std::collections::HashMap::from([(EC_BLOCK_SIZE_HINT_INTERNAL_KEY.to_string(), "131072".to_string())]);
|
||||
assert_eq!(take_ec_block_size_hint(&mut unsupported), None);
|
||||
assert!(!unsupported.contains_key(EC_BLOCK_SIZE_HINT_INTERNAL_KEY));
|
||||
|
||||
let mut conflicting = std::collections::HashMap::from([
|
||||
(EC_BLOCK_SIZE_HINT_INTERNAL_KEY.to_string(), "65536".to_string()),
|
||||
("x-minio-internal-ec-block-size-hint".to_string(), "262144".to_string()),
|
||||
]);
|
||||
assert_eq!(take_ec_block_size_hint(&mut conflicting), None);
|
||||
assert!(conflicting.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_quantum_stays_aligned_with_layout_geometry() {
|
||||
// Two data shards produce the same compact geometry used by the
|
||||
// persisted 64 KiB, 256 KiB, 1 MiB and 4 MiB candidates. Large
|
||||
// layouts deliberately use coarser frames to keep PUT overhead bounded.
|
||||
assert_eq!(select_ec_read_quantum(64 * 1024, 2, 32 * 1024), Some(16 * 1024));
|
||||
assert_eq!(select_ec_read_quantum(256 * 1024, 2, 128 * 1024), Some(64 * 1024));
|
||||
assert_eq!(select_ec_read_quantum(1024 * 1024, 2, 512 * 1024), Some(512 * 1024));
|
||||
assert_eq!(select_ec_read_quantum(4 * 1024 * 1024, 2, 2 * 1024 * 1024), Some(1024 * 1024));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persisted_read_quantum_rejects_conflicts_and_bad_geometry() {
|
||||
let mut metadata = HashMap::new();
|
||||
insert_ec_read_quantum(&mut metadata, 256 * 1024);
|
||||
assert_eq!(
|
||||
persisted_ec_read_quantum(&metadata, 4 * 1024 * 1024, 2, 2 * 1024 * 1024),
|
||||
Ok(Some(256 * 1024))
|
||||
);
|
||||
|
||||
metadata.clear();
|
||||
insert_ec_read_quantum(&mut metadata, 1024 * 1024);
|
||||
assert_eq!(
|
||||
persisted_ec_read_quantum(&metadata, 4 * 1024 * 1024, 2, 2 * 1024 * 1024),
|
||||
Ok(Some(1024 * 1024))
|
||||
);
|
||||
|
||||
metadata.insert("x-minio-internal-ec-read-quantum".to_owned(), "128".to_owned());
|
||||
assert_eq!(
|
||||
persisted_ec_read_quantum(&metadata, 4 * 1024 * 1024, 2, 2 * 1024 * 1024),
|
||||
Err(EcReadQuantumMetadataError::ConflictingValues)
|
||||
);
|
||||
|
||||
metadata.clear();
|
||||
insert_ec_read_quantum(&mut metadata, 32 * 1024);
|
||||
assert_eq!(persisted_ec_read_quantum(&metadata, 64 * 1024, 2, 32 * 1024), Ok(Some(32 * 1024)));
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,7 @@ pub(crate) fn legacy_encrypted_range_seek_enabled() -> bool {
|
||||
}
|
||||
|
||||
mod body_cache_hook;
|
||||
pub mod ec_block_layout;
|
||||
mod encryption;
|
||||
mod hook_slot;
|
||||
mod multipart_completion_binding;
|
||||
@@ -123,6 +124,7 @@ pub use body_cache_hook::{
|
||||
pub(crate) use body_cache_hook::{
|
||||
get_object_body_cache_hook, get_object_body_cache_hook_suppressed, without_get_object_body_cache_hook,
|
||||
};
|
||||
pub use ec_block_layout::*;
|
||||
pub use encryption::{
|
||||
EncryptionResolutionError, EncryptionResolutionErrorKind, ObjectEncryptionResolver, ReadEncryptionMaterial,
|
||||
ReadEncryptionMode, ReadEncryptionRequest,
|
||||
|
||||
@@ -1953,6 +1953,17 @@ impl Clone for ObjectInfo {
|
||||
}
|
||||
|
||||
impl ObjectInfo {
|
||||
/// Return the persisted EC block size exposed by the response-side
|
||||
/// projection. Callers must not infer this value from request metadata.
|
||||
pub fn effective_ec_block_size(&self) -> Option<usize> {
|
||||
rustfs_utils::http::metadata_compat::get_consistent_str(
|
||||
&self.user_defined,
|
||||
crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX,
|
||||
)
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
.filter(|value| *value > 0)
|
||||
}
|
||||
|
||||
pub(crate) fn shard_integrity_write_mode(&self) -> ShardIntegrityWriteMode {
|
||||
// Any declaration requires protection. Malformed declarations remain
|
||||
// errors in the source reader and must never select the legacy path.
|
||||
@@ -2266,9 +2277,10 @@ impl ObjectInfo {
|
||||
|
||||
let inlined = fi.inline_data();
|
||||
let free_version = fi.tier_free_version();
|
||||
let is_remote = fi.is_remote();
|
||||
let metadata = std::mem::take(&mut fi.metadata);
|
||||
let parts = std::mem::take(&mut fi.parts);
|
||||
Self::from_file_info_parts(&fi, inlined, free_version, metadata, parts, bucket, object, version_id)
|
||||
Self::from_file_info_parts(&fi, inlined, free_version, is_remote, metadata, parts, bucket, object, version_id)
|
||||
}
|
||||
|
||||
pub(crate) fn from_file_info_with_version_id(
|
||||
@@ -2281,6 +2293,7 @@ impl ObjectInfo {
|
||||
fi,
|
||||
fi.inline_data(),
|
||||
fi.tier_free_version(),
|
||||
fi.is_remote(),
|
||||
fi.metadata.clone(),
|
||||
fi.parts.clone(),
|
||||
bucket,
|
||||
@@ -2294,6 +2307,7 @@ impl ObjectInfo {
|
||||
fi: &FileInfo,
|
||||
inlined: bool,
|
||||
free_version: bool,
|
||||
is_remote: bool,
|
||||
mut metadata: HashMap<String, String>,
|
||||
parts: Vec<ObjectPartInfo>,
|
||||
bucket: &str,
|
||||
@@ -2369,6 +2383,17 @@ impl ObjectInfo {
|
||||
};
|
||||
|
||||
clean_metadata(&mut metadata);
|
||||
// The frame quantum is a storage-layout detail. Keep it in
|
||||
// FileInfo for the reader, but never expose the internal marker as
|
||||
// ordinary S3 metadata.
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut metadata, crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX);
|
||||
if !fi.deleted && !is_remote && fi.erasure.block_size > 0 {
|
||||
rustfs_utils::http::metadata_compat::insert_str(
|
||||
&mut metadata,
|
||||
crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX,
|
||||
fi.erasure.block_size.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let storage_class = Some(
|
||||
storageclass::effective_class(
|
||||
@@ -3342,6 +3367,54 @@ mod tests {
|
||||
assert_eq!(info.version_id, None, "a normalized absent version must not be rewritten to nil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_file_info_projects_persisted_ec_block_size_for_responses() {
|
||||
let mut fi = FileInfo::new("bucket/object", 4, 2);
|
||||
fi.size = 1;
|
||||
fi.erasure.block_size = 64 * 1024;
|
||||
|
||||
let info = ObjectInfo::from_file_info(&fi, "bucket", "object", false);
|
||||
|
||||
assert_eq!(info.effective_ec_block_size(), Some(64 * 1024));
|
||||
assert_eq!(
|
||||
info.user_defined
|
||||
.get(crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_KEY)
|
||||
.map(String::as_str),
|
||||
Some("65536")
|
||||
);
|
||||
|
||||
fi.erasure.block_size = 131_072;
|
||||
let info = ObjectInfo::from_file_info(&fi, "bucket", "object", false);
|
||||
assert_eq!(info.effective_ec_block_size(), Some(131_072));
|
||||
|
||||
fi.transition_status = rustfs_filemeta::TRANSITION_COMPLETE.to_string();
|
||||
let info = ObjectInfo::from_file_info(&fi, "bucket", "remote-object", false);
|
||||
assert_eq!(info.effective_ec_block_size(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_owned_file_info_preserves_restored_ec_block_size_projection() {
|
||||
let mut fi = FileInfo::new("bucket/object", 4, 2);
|
||||
fi.size = 1;
|
||||
fi.erasure.block_size = 64 * 1024;
|
||||
fi.transition_status = rustfs_filemeta::TRANSITION_COMPLETE.to_string();
|
||||
let restore = rustfs_filemeta::RestoreStatus {
|
||||
is_restore_in_progress: Some(false),
|
||||
restore_expiry_date: Some(OffsetDateTime::now_utc() + time::Duration::days(1)),
|
||||
};
|
||||
fi.metadata.insert(metadata_keys::RESTORE.to_string(), restore.to_string());
|
||||
assert!(!fi.is_remote(), "the restored source has a local copy");
|
||||
|
||||
let borrowed = ObjectInfo::from_file_info(&fi, "bucket", "object", false);
|
||||
let owned = ObjectInfo::from_owned_file_info(fi, "bucket", "object", false);
|
||||
|
||||
assert_eq!(owned.effective_ec_block_size(), Some(64 * 1024));
|
||||
assert_eq!(owned.user_defined, borrowed.user_defined);
|
||||
for key in ["x-rustfs-internal-ec-block-size", "x-minio-internal-ec-block-size"] {
|
||||
assert_eq!(owned.user_defined.get(key).map(String::as_str), Some("65536"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_file_info_reports_effective_storage_class_for_legacy_metadata() {
|
||||
for legacy_label in [
|
||||
|
||||
@@ -1045,6 +1045,13 @@ impl InstanceContext {
|
||||
self.local_disk_map.clone()
|
||||
}
|
||||
|
||||
/// Snapshot the boot-time disk registry before a store is published.
|
||||
/// Missing local drives remain explicit so startup receipts cannot treat
|
||||
/// an available subset as the complete instance inventory.
|
||||
pub async fn local_disk_inventory(&self) -> Vec<Option<DiskStore>> {
|
||||
self.local_disk_map.read().await.values().cloned().collect()
|
||||
}
|
||||
|
||||
/// Handle to this instance's local disk-id→endpoint map.
|
||||
pub(crate) fn local_disk_id_map(&self) -> Arc<RwLock<HashMap<Uuid, String>>> {
|
||||
self.local_disk_id_map.clone()
|
||||
|
||||
@@ -604,10 +604,10 @@ pub(crate) async fn initialize_local_disk_maps(
|
||||
|
||||
let disk = match new_disk(ep, opt).await {
|
||||
Ok(disk) => disk,
|
||||
Err(crate::disk::error::DiskError::FileAccessDenied) => {
|
||||
// LocalDisk already logged the filesystem cause and repair
|
||||
// hint. Keep this slot unavailable so ECStore initialization
|
||||
// can apply its existing fatal-error and quorum rules.
|
||||
Err(crate::disk::error::DiskError::FileAccessDenied | crate::disk::error::DiskError::VolumeNotFound) => {
|
||||
// Preserve the configured slot when a local volume is unavailable.
|
||||
// LocalDisk logs the cause; format loading retains authority
|
||||
// over fatal errors and quorum. Never create a missing root.
|
||||
global_local_disk_map.insert(ep.to_string(), None);
|
||||
continue;
|
||||
}
|
||||
@@ -888,6 +888,95 @@ mod tests {
|
||||
disk_map.keys().collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn missing_local_volume_preserves_offline_slot_without_creating_root() {
|
||||
use crate::disk::{DiskOption, error::DiskError};
|
||||
use crate::layout::endpoints::{EndpointServerPools, PoolEndpoints};
|
||||
|
||||
for drive_count in [2, 3, 4] {
|
||||
let directory = tempfile::tempdir().expect("create volume parent");
|
||||
let mut endpoints = Vec::new();
|
||||
for index in 0..drive_count {
|
||||
let path = directory.path().join(format!("disk{index}"));
|
||||
if index != 0 {
|
||||
std::fs::create_dir(&path).expect("create surviving volume");
|
||||
}
|
||||
let mut endpoint = Endpoint::try_from(path.to_str().expect("UTF-8 path")).expect("local endpoint");
|
||||
endpoint.set_pool_index(0);
|
||||
endpoint.set_set_index(0);
|
||||
endpoint.set_disk_index(index);
|
||||
endpoints.push(endpoint);
|
||||
}
|
||||
let missing = endpoints[0].to_string();
|
||||
let pools = EndpointServerPools(vec![PoolEndpoints {
|
||||
legacy: false,
|
||||
set_count: 1,
|
||||
drives_per_set: drive_count,
|
||||
endpoints: endpoints.into(),
|
||||
cmd_line: "missing-volume".into(),
|
||||
platform: "test".into(),
|
||||
}]);
|
||||
let ctx = Arc::new(crate::runtime::instance::InstanceContext::new());
|
||||
let options = DiskOption {
|
||||
cleanup: true,
|
||||
health_check: false,
|
||||
};
|
||||
super::initialize_local_disk_maps(&ctx, pools.clone(), &options)
|
||||
.await
|
||||
.expect("missing volume should remain offline for quorum evaluation");
|
||||
let map = ctx.local_disk_map();
|
||||
let map = map.read().await;
|
||||
assert_eq!(map.len(), drive_count);
|
||||
assert!(matches!(map.get(&missing), Some(None)));
|
||||
assert_eq!(map.values().flatten().count(), drive_count - 1);
|
||||
drop(map);
|
||||
let drives = ctx.local_disk_set_drives();
|
||||
let drives = drives.read().await;
|
||||
assert_eq!(drives[0][0].len(), drive_count);
|
||||
assert!(drives[0][0][0].is_none());
|
||||
assert!(drives[0][0][1..].iter().all(Option::is_some));
|
||||
drop(drives);
|
||||
|
||||
let (disks, errors) = crate::store::init_format::init_disks(&ctx, &pools.0[0].endpoints, &options).await;
|
||||
assert!(disks[0].is_none());
|
||||
assert_eq!(errors[0], Some(DiskError::VolumeNotFound));
|
||||
assert!(disks[1..].iter().all(Option::is_some));
|
||||
assert!(errors[1..].iter().all(Option::is_none));
|
||||
assert!(!directory.path().join("disk0").exists(), "startup must not create a missing mount root");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_local_volume_still_fails_registry_initialization() {
|
||||
use crate::disk::DiskOption;
|
||||
use crate::layout::endpoints::{EndpointServerPools, PoolEndpoints};
|
||||
|
||||
let directory = tempfile::tempdir().expect("create volume parent");
|
||||
let path = directory.path().join("regular-file");
|
||||
std::fs::write(&path, b"preserve existing file").expect("create invalid volume");
|
||||
let mut endpoint = Endpoint::try_from(path.to_str().expect("UTF-8 path")).expect("local endpoint");
|
||||
endpoint.set_pool_index(0);
|
||||
endpoint.set_set_index(0);
|
||||
endpoint.set_disk_index(0);
|
||||
let pools = EndpointServerPools(vec![PoolEndpoints {
|
||||
legacy: false,
|
||||
set_count: 1,
|
||||
drives_per_set: 1,
|
||||
endpoints: vec![endpoint].into(),
|
||||
cmd_line: "invalid-volume".into(),
|
||||
platform: "test".into(),
|
||||
}]);
|
||||
let ctx = Arc::new(crate::runtime::instance::InstanceContext::new());
|
||||
let options = DiskOption {
|
||||
cleanup: true,
|
||||
health_check: false,
|
||||
};
|
||||
super::initialize_local_disk_maps(&ctx, pools, &options)
|
||||
.await
|
||||
.expect_err("a non-directory volume must retain its initialization error");
|
||||
assert_eq!(std::fs::read(&path).expect("read existing file"), b"preserve existing file");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn multipart_invalid_registry_pool_index_has_no_authority_or_registry_effect() {
|
||||
use crate::disk::DiskOption;
|
||||
|
||||
@@ -15,8 +15,6 @@
|
||||
use crate::diagnostics::admin_server_info::get_local_server_property;
|
||||
use crate::runtime::sources as runtime_sources;
|
||||
use crate::storage_api_contracts::admin::StorageAdminApi;
|
||||
#[cfg(test)]
|
||||
use chrono::Utc;
|
||||
use jiff::Timestamp;
|
||||
use rustfs_heal_contracts::heal_channel::DriveState;
|
||||
use rustfs_io_metrics::internode_metrics::global_internode_metrics;
|
||||
@@ -600,10 +598,6 @@ mod test {
|
||||
use serial_test::serial;
|
||||
use std::time::Duration;
|
||||
|
||||
fn chrono_to_jiff_timestamp(timestamp: chrono::DateTime<Utc>) -> jiff::Timestamp {
|
||||
jiff::Timestamp::try_from(std::time::SystemTime::from(timestamp)).expect("test timestamp should fit in jiff")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tes_types() {
|
||||
let t = MetricType::ALL;
|
||||
@@ -685,10 +679,10 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn scanner_metrics_mapping_preserves_partial_source_status() {
|
||||
let current_started = Utc::now() - chrono::Duration::seconds(5);
|
||||
let current_started = Timestamp::now() - jiff::SignedDuration::from_secs(5);
|
||||
let scanner = to_madmin_scanner_metrics(rustfs_scanner_metrics::metrics::ScannerMetricsReport {
|
||||
current_cycle_active: true,
|
||||
current_started: chrono_to_jiff_timestamp(current_started),
|
||||
current_started,
|
||||
last_cycle_partial_source: "usage".to_string(),
|
||||
last_cycle_partial_source_code: 1,
|
||||
cycle_timeout_total: 3,
|
||||
@@ -703,7 +697,7 @@ mod test {
|
||||
});
|
||||
|
||||
assert_eq!(scanner.current_cycle_active, Some(true));
|
||||
assert_eq!(scanner.current_started, chrono_to_jiff_timestamp(current_started));
|
||||
assert_eq!(scanner.current_started, current_started);
|
||||
assert_eq!(scanner.last_cycle_partial_source, "usage");
|
||||
assert_eq!(scanner.last_cycle_partial_source_code, 1);
|
||||
assert_eq!(scanner.cycle_timeout_total, 3);
|
||||
@@ -723,8 +717,8 @@ mod test {
|
||||
async fn collect_local_metrics_preserves_scanner_cycle_started_time() {
|
||||
let previous_init_time = *rustfs_scanner_metrics::GLOBAL_INIT_TIME.read().await;
|
||||
let previous_cycle = global_metrics().get_cycle().await;
|
||||
let init_time = Utc::now() - chrono::Duration::hours(1);
|
||||
let cycle_started = Utc::now() - chrono::Duration::seconds(5);
|
||||
let init_time = Timestamp::now() - jiff::SignedDuration::from_hours(1);
|
||||
let cycle_started = Timestamp::now() - jiff::SignedDuration::from_secs(5);
|
||||
*rustfs_scanner_metrics::GLOBAL_INIT_TIME.write().await = Some(init_time);
|
||||
let cycle = CurrentCycle {
|
||||
current: 0,
|
||||
@@ -748,7 +742,7 @@ mod test {
|
||||
aggregated.merge(decoded);
|
||||
let scanner = aggregated.aggregated.scanner.expect("scanner metrics");
|
||||
assert_eq!(scanner.current_cycle_active, Some(true));
|
||||
assert_eq!(scanner.current_started, chrono_to_jiff_timestamp(cycle_started));
|
||||
assert_eq!(scanner.current_started, cycle_started);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -5958,6 +5958,7 @@ mod tests {
|
||||
#[test]
|
||||
fn scanner_dirty_usage_acknowledgement_preserves_newer_pending_work() {
|
||||
let activity = |dirty_usage_pending| ScannerPeerActivity {
|
||||
checkpoint_instance_id: None,
|
||||
instance_id: "0123456789abcdef0123456789abcdef".to_string(),
|
||||
namespace_generation: 1,
|
||||
maintenance_generation: 1,
|
||||
|
||||
@@ -355,6 +355,34 @@ pub(super) fn validate_rebalance_disk_stats_coverage(disk_stats: &[DiskStat]) ->
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn select_rebalance_sources(meta: &mut RebalanceMeta, pool_meta: &PoolMeta, now: OffsetDateTime) {
|
||||
// Placement excludes suspended pools. Counting their free space can make
|
||||
// every writable pool a source and leave the run without a destination.
|
||||
let mut total_free = 0;
|
||||
let mut total_capacity = 0;
|
||||
for (idx, stat) in meta.pool_stats.iter().enumerate() {
|
||||
if !pool_meta.is_suspended(idx) {
|
||||
total_free += stat.init_free_space;
|
||||
total_capacity += stat.init_capacity;
|
||||
}
|
||||
}
|
||||
meta.percent_free_goal = percent_free_ratio(total_free, total_capacity);
|
||||
|
||||
for (idx, stat) in meta.pool_stats.iter_mut().enumerate() {
|
||||
if !pool_meta.is_suspended(idx)
|
||||
&& should_pool_participate(stat.init_free_space, stat.init_capacity, meta.percent_free_goal)
|
||||
{
|
||||
stat.participating = true;
|
||||
stat.info = RebalanceInfo {
|
||||
start_time: Some(now),
|
||||
status: RebalStatus::Started,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
}
|
||||
meta.stopped_at = (!meta.pool_stats.iter().any(|stat| stat.participating)).then_some(now);
|
||||
}
|
||||
|
||||
fn pool_rebalance_status_from_meta(meta: Option<&RebalanceMeta>, pool_index: usize) -> (RebalStatus, bool) {
|
||||
meta.and_then(|meta| meta.pool_stats.get(pool_index))
|
||||
.filter(|pool_stat| pool_stat.participating)
|
||||
@@ -584,7 +612,8 @@ impl ECStore {
|
||||
async fn save_rebalance_activation_meta_with_merge<S>(
|
||||
&self,
|
||||
pool: Arc<S>,
|
||||
local_snapshot: &RebalanceMeta,
|
||||
local_snapshot: &mut RebalanceMeta,
|
||||
now: OffsetDateTime,
|
||||
stage: &str,
|
||||
) -> Result<()>
|
||||
where
|
||||
@@ -600,6 +629,7 @@ impl ECStore {
|
||||
.load_runtime_pool_meta_under_activation_fence(&mut pool_meta_guard, &activation_fence, stage)
|
||||
.await?;
|
||||
ensure_rebalance_activation_pool_meta_allowed(&pool_meta)?;
|
||||
select_rebalance_sources(local_snapshot, &pool_meta, now);
|
||||
|
||||
merge_and_save_rebalance_meta_no_lock(
|
||||
pool,
|
||||
@@ -963,16 +993,11 @@ impl ECStore {
|
||||
|
||||
let mut disk_stats = vec![DiskStat::default(); self.pools.len()];
|
||||
|
||||
let mut total_cap = 0;
|
||||
let mut total_free = 0;
|
||||
for disk in si.disks.iter() {
|
||||
if disk.pool_index < 0 || disk_stats.len() <= disk.pool_index as usize {
|
||||
continue;
|
||||
}
|
||||
|
||||
total_cap += disk.total_space;
|
||||
total_free += disk.available_space;
|
||||
|
||||
disk_stats[disk.pool_index as usize].total_space += disk.total_space;
|
||||
disk_stats[disk.pool_index as usize].available_space += disk.available_space;
|
||||
}
|
||||
@@ -980,50 +1005,29 @@ impl ECStore {
|
||||
#[cfg(test)]
|
||||
if let Some(overridden) = take_rebalance_disk_stats_override_for_test(self.id) {
|
||||
disk_stats = overridden;
|
||||
total_cap = disk_stats.iter().map(|stat| stat.total_space).sum();
|
||||
total_free = disk_stats.iter().map(|stat| stat.available_space).sum();
|
||||
}
|
||||
|
||||
let percent_free_goal = percent_free_ratio(total_free, total_cap);
|
||||
validate_rebalance_disk_stats_coverage(&disk_stats)?;
|
||||
|
||||
let mut pool_stats = Vec::with_capacity(self.pools.len());
|
||||
|
||||
let now = self.next_scanner_data_movement_update(OffsetDateTime::now_utc()).await;
|
||||
|
||||
for disk_stat in disk_stats.iter() {
|
||||
let mut pool_stat = RebalanceStats {
|
||||
init_free_space: disk_stat.available_space,
|
||||
init_capacity: disk_stat.total_space,
|
||||
buckets: bucktes.clone(),
|
||||
rebalanced_buckets: Vec::with_capacity(bucktes.len()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if should_pool_participate(disk_stat.available_space, disk_stat.total_space, percent_free_goal) {
|
||||
pool_stat.participating = true;
|
||||
pool_stat.info = RebalanceInfo {
|
||||
start_time: Some(now),
|
||||
status: RebalStatus::Started,
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
|
||||
pool_stats.push(pool_stat);
|
||||
}
|
||||
|
||||
let has_participating_pool = pool_stats.iter().any(|pool_stat| pool_stat.participating);
|
||||
let meta = RebalanceMeta {
|
||||
let mut meta = RebalanceMeta {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
stopped_at: (!has_participating_pool).then_some(now),
|
||||
percent_free_goal,
|
||||
pool_stats,
|
||||
pool_stats: disk_stats
|
||||
.iter()
|
||||
.map(|stat| RebalanceStats {
|
||||
init_free_space: stat.available_space,
|
||||
init_capacity: stat.total_space,
|
||||
buckets: bucktes.clone(),
|
||||
rebalanced_buckets: Vec::with_capacity(bucktes.len()),
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let pool = clone_first_arc(&self.pools, "init_rebalance_meta: no pools available")?;
|
||||
resolve_rebalance_meta_save_result(
|
||||
self.save_rebalance_activation_meta_with_merge(pool, &meta, "init_rebalance_meta")
|
||||
self.save_rebalance_activation_meta_with_merge(pool, &mut meta, now, "init_rebalance_meta")
|
||||
.await,
|
||||
"init_rebalance_meta",
|
||||
)?;
|
||||
@@ -2669,6 +2673,46 @@ mod tests {
|
||||
.await;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebalance_selects_sources_only_among_writable_pools_after_decommission() {
|
||||
let now = OffsetDateTime::UNIX_EPOCH;
|
||||
let pool_meta = PoolMeta {
|
||||
pools: (0..4)
|
||||
.map(|id| crate::core::pools::PoolStatus {
|
||||
id,
|
||||
cmd_line: format!("pool-{id}"),
|
||||
last_update: now,
|
||||
decommission: (id == 0).then(|| crate::core::pools::PoolDecommissionInfo {
|
||||
start_time: Some(now),
|
||||
complete: true,
|
||||
..Default::default()
|
||||
}),
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
// A retired pool can be either emptier or fuller than the live pools.
|
||||
for retired_free in [100, 40] {
|
||||
let mut meta = RebalanceMeta {
|
||||
pool_stats: [retired_free, 94, 95, 96]
|
||||
.map(|free| RebalanceStats {
|
||||
init_capacity: 100,
|
||||
init_free_space: free,
|
||||
..Default::default()
|
||||
})
|
||||
.to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
select_rebalance_sources(&mut meta, &pool_meta, now);
|
||||
assert_eq!(meta.percent_free_goal, 0.95);
|
||||
assert_eq!(
|
||||
meta.pool_stats.iter().map(|p| p.info.status).collect::<Vec<_>>(),
|
||||
[RebalStatus::None, RebalStatus::Started, RebalStatus::None, RebalStatus::None]
|
||||
);
|
||||
assert!(meta.stopped_at.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rebalance_activation_rejects_persisted_decommission_despite_idle_local_snapshot() {
|
||||
let persisted = PoolMeta {
|
||||
|
||||
@@ -118,6 +118,16 @@ pub(crate) async fn test_two_pool_stores(
|
||||
test_pool_stores_with_contexts(rebalance_meta, false, 2, 2).await
|
||||
}
|
||||
|
||||
/// Two pools whose sets have three drives each: EC:1, quorum 2 of 3.
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn test_two_pool_stores_with_three_drive_sets() -> (
|
||||
Vec<tempfile::TempDir>,
|
||||
std::sync::Arc<crate::store::ECStore>,
|
||||
std::sync::Arc<crate::store::ECStore>,
|
||||
) {
|
||||
test_pool_stores_with_contexts(None, false, 2, 3).await
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "test-util"))]
|
||||
pub(crate) async fn test_three_pool_stores(
|
||||
rebalance_meta: Option<RebalanceMeta>,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -29,11 +29,21 @@ use sha2::Digest;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct FileInfoIdentityGroup {
|
||||
hash: [u8; 32],
|
||||
key: FileInfoQuorumKey,
|
||||
count: usize,
|
||||
mod_time: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
/// Metadata identity used when selecting a quorum member. The historical
|
||||
/// content hash remains unchanged for compatibility with diagnostics and
|
||||
/// external callers; this second digest prevents two objects with the same
|
||||
/// metadata but different decode geometry from sharing a quorum.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
struct FileInfoQuorumKey {
|
||||
content_hash: [u8; 32],
|
||||
decode_layout_hash: [u8; 32],
|
||||
}
|
||||
|
||||
impl SetDisks {
|
||||
/// Read one key's complete version stack without enumerating its parent.
|
||||
pub(crate) async fn read_object_versions_for_lifecycle(
|
||||
@@ -670,7 +680,7 @@ impl SetDisks {
|
||||
continue;
|
||||
}
|
||||
|
||||
let key = Self::file_info_quorum_hash(meta);
|
||||
let key = Self::file_info_quorum_key(meta);
|
||||
|
||||
let count = identity_counts.entry(key).or_insert(0);
|
||||
*count += 1;
|
||||
@@ -922,6 +932,26 @@ impl SetDisks {
|
||||
key
|
||||
}
|
||||
|
||||
fn file_info_quorum_key(meta: &FileInfo) -> FileInfoQuorumKey {
|
||||
let mut hasher = Sha256::new();
|
||||
Self::update_hash_str(&mut hasher, &meta.erasure.algorithm);
|
||||
hasher.update([u8::from(meta.uses_legacy_checksum)]);
|
||||
hasher.update(meta.erasure.data_blocks.to_le_bytes());
|
||||
hasher.update(meta.erasure.parity_blocks.to_le_bytes());
|
||||
hasher.update(meta.erasure.block_size.to_le_bytes());
|
||||
hasher.update(meta.erasure.distribution.len().to_le_bytes());
|
||||
for disk_index in &meta.erasure.distribution {
|
||||
hasher.update(disk_index.to_le_bytes());
|
||||
}
|
||||
let digest = hasher.finalize();
|
||||
let mut decode_layout_hash = [0u8; 32];
|
||||
decode_layout_hash.copy_from_slice(digest.as_slice());
|
||||
FileInfoQuorumKey {
|
||||
content_hash: Self::file_info_quorum_hash(meta),
|
||||
decode_layout_hash,
|
||||
}
|
||||
}
|
||||
|
||||
/// Hash the per-target delete-marker versions through their normalized form
|
||||
/// so the dual internal prefixes carrying the same mapping share one
|
||||
/// identity, while a genuine disagreement between disks still changes the
|
||||
@@ -1012,14 +1042,14 @@ impl SetDisks {
|
||||
continue;
|
||||
}
|
||||
|
||||
let hash = Self::file_info_quorum_hash(meta);
|
||||
if let Some(group) = groups.iter_mut().find(|group| group.hash == hash) {
|
||||
let key = Self::file_info_quorum_key(meta);
|
||||
if let Some(group) = groups.iter_mut().find(|group| group.key == key) {
|
||||
group.count += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
groups.push(FileInfoIdentityGroup {
|
||||
hash,
|
||||
key,
|
||||
count: 1,
|
||||
mod_time: meta.mod_time,
|
||||
});
|
||||
@@ -1032,7 +1062,7 @@ impl SetDisks {
|
||||
disks: &[Option<DiskStore>],
|
||||
parts_metadata: &[FileInfo],
|
||||
errs: &[Option<DiskError>],
|
||||
hash: [u8; 32],
|
||||
key: FileInfoQuorumKey,
|
||||
quorum: usize,
|
||||
) -> disk::error::Result<(Vec<Option<DiskStore>>, FileInfo)> {
|
||||
let mut online_disks = vec![None; disks.len()];
|
||||
@@ -1040,7 +1070,7 @@ impl SetDisks {
|
||||
let mut count = 0;
|
||||
|
||||
for (i, ((meta, err), disk)) in parts_metadata.iter().zip(errs.iter()).zip(disks.iter()).enumerate() {
|
||||
if err.is_some() || !file_info_is_valid_for_metadata(meta) || Self::file_info_quorum_hash(meta) != hash {
|
||||
if err.is_some() || !file_info_is_valid_for_metadata(meta) || Self::file_info_quorum_key(meta) != key {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1081,7 +1111,7 @@ impl SetDisks {
|
||||
let mut older_start = 0;
|
||||
while older_start < groups.len() && groups[older_start].mod_time == latest_mod_time {
|
||||
if groups[older_start].count >= write_quorum {
|
||||
return Self::pick_fileinfo_identity(disks, parts_metadata, errs, groups[older_start].hash, write_quorum);
|
||||
return Self::pick_fileinfo_identity(disks, parts_metadata, errs, groups[older_start].key, write_quorum);
|
||||
}
|
||||
older_start += 1;
|
||||
}
|
||||
@@ -1092,7 +1122,7 @@ impl SetDisks {
|
||||
|
||||
for group in groups.iter().skip(older_start) {
|
||||
if group.count >= read_quorum {
|
||||
return Self::pick_fileinfo_identity(disks, parts_metadata, errs, group.hash, read_quorum);
|
||||
return Self::pick_fileinfo_identity(disks, parts_metadata, errs, group.key, read_quorum);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1186,7 +1216,7 @@ impl SetDisks {
|
||||
let mod_valid = mod_time == &meta.mod_time;
|
||||
|
||||
if etag_only || mod_valid {
|
||||
meta_hashes[i] = Some(Self::file_info_quorum_hash(meta));
|
||||
meta_hashes[i] = Some(Self::file_info_quorum_key(meta));
|
||||
} else {
|
||||
debug!(
|
||||
index = i,
|
||||
@@ -1607,6 +1637,33 @@ mod tests {
|
||||
assert_ne!(SetDisks::file_info_quorum_hash(&left), SetDisks::file_info_quorum_hash(&right));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_geometry_is_required_for_fileinfo_quorum_selection() {
|
||||
let mod_time = OffsetDateTime::from_unix_timestamp(1_705_312_300).expect("valid timestamp");
|
||||
let mut base = metadata_quorum_test_fileinfo(mod_time, 1);
|
||||
base.erasure.block_size = 64 * 1024;
|
||||
let mut same_layout = vec![base; 3];
|
||||
for (index, fi) in same_layout.iter_mut().enumerate() {
|
||||
fi.erasure.index = index + 1;
|
||||
}
|
||||
let mut different_layout = same_layout[2].clone();
|
||||
different_layout.erasure.block_size = 256 * 1024;
|
||||
|
||||
assert_eq!(
|
||||
SetDisks::file_info_quorum_hash(&same_layout[0]),
|
||||
SetDisks::file_info_quorum_hash(&different_layout),
|
||||
"the compatibility hash remains unchanged when only decode geometry differs"
|
||||
);
|
||||
|
||||
same_layout[2] = different_layout;
|
||||
let selected = SetDisks::find_file_info_in_quorum(&same_layout, &Some(mod_time), &None, 2)
|
||||
.expect("the two matching geometries should form a quorum");
|
||||
assert_eq!(selected.erasure.block_size, 64 * 1024);
|
||||
let err = SetDisks::find_file_info_in_quorum(&same_layout, &Some(mod_time), &None, 3)
|
||||
.expect_err("mixed block sizes must never be combined into a quorum");
|
||||
assert_eq!(err, DiskError::ErasureReadQuorum);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn purge_pending_quorum_hash_keeps_erasure_layouts_separate() {
|
||||
let mod_time = OffsetDateTime::from_unix_timestamp(1_705_312_300).expect("valid timestamp");
|
||||
|
||||
@@ -81,7 +81,7 @@ use crate::erasure::codec::bridge::{
|
||||
use crate::erasure::coding;
|
||||
use crate::error::{Error, Result, is_err_version_not_found};
|
||||
use crate::error::{GenericError, ObjectApiError, is_err_object_not_found};
|
||||
use crate::io_support::bitrot::{create_bitrot_reader_from_bytes, create_bitrot_writer, create_bitrot_writer_with_orig_volume};
|
||||
use crate::io_support::bitrot::{create_bitrot_writer, create_bitrot_writer_with_orig_volume};
|
||||
use crate::object_api::ObjectOptions;
|
||||
use crate::object_api::get_object_body_cache_hook;
|
||||
use crate::object_api::object_api_utils::get_raw_etag;
|
||||
@@ -6222,6 +6222,7 @@ fn known_put_object_storage_size(data_size: i64) -> i64 {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn build_inline_bitrot_readers<'a>(
|
||||
files: impl Iterator<Item = &'a FileInfo> + Send,
|
||||
@@ -6232,11 +6233,37 @@ async fn build_inline_bitrot_readers<'a>(
|
||||
shard_size: usize,
|
||||
checksum_algo: &HashAlgorithm,
|
||||
skip_verify_bitrot: bool,
|
||||
) -> disk::error::Result<Vec<Option<InlineBitrotReader>>> {
|
||||
build_inline_bitrot_readers_with_frame_size(
|
||||
files,
|
||||
total_shards,
|
||||
bucket,
|
||||
object,
|
||||
read_length,
|
||||
shard_size,
|
||||
shard_size,
|
||||
checksum_algo,
|
||||
skip_verify_bitrot,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn build_inline_bitrot_readers_with_frame_size<'a>(
|
||||
files: impl Iterator<Item = &'a FileInfo> + Send,
|
||||
total_shards: usize,
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
read_length: usize,
|
||||
shard_size: usize,
|
||||
frame_size: usize,
|
||||
checksum_algo: &HashAlgorithm,
|
||||
skip_verify_bitrot: bool,
|
||||
) -> disk::error::Result<Vec<Option<InlineBitrotReader>>> {
|
||||
let mut readers = Vec::with_capacity(total_shards);
|
||||
for file in files.take(total_shards) {
|
||||
let reader = if let Some(data) = &file.data {
|
||||
create_bitrot_reader_from_bytes(
|
||||
crate::io_support::bitrot::create_bitrot_reader_from_bytes_with_frame_size_and_stage_metrics(
|
||||
Some(data.clone()),
|
||||
None,
|
||||
bucket,
|
||||
@@ -6244,9 +6271,72 @@ async fn build_inline_bitrot_readers<'a>(
|
||||
0,
|
||||
read_length,
|
||||
shard_size,
|
||||
frame_size,
|
||||
checksum_algo.clone(),
|
||||
skip_verify_bitrot,
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
readers.push(reader);
|
||||
}
|
||||
Ok(readers)
|
||||
}
|
||||
|
||||
#[allow(dead_code, reason = "compatibility wrapper for the legacy shard geometry")]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn build_inline_bitrot_readers_from_refs(
|
||||
files: &[&FileInfo],
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
read_length: usize,
|
||||
shard_size: usize,
|
||||
checksum_algo: &HashAlgorithm,
|
||||
skip_verify_bitrot: bool,
|
||||
) -> disk::error::Result<Vec<Option<InlineBitrotReader>>> {
|
||||
build_inline_bitrot_readers_from_refs_with_frame_size(
|
||||
files,
|
||||
bucket,
|
||||
object,
|
||||
read_length,
|
||||
shard_size,
|
||||
shard_size,
|
||||
checksum_algo,
|
||||
skip_verify_bitrot,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn build_inline_bitrot_readers_from_refs_with_frame_size(
|
||||
files: &[&FileInfo],
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
read_length: usize,
|
||||
shard_size: usize,
|
||||
frame_size: usize,
|
||||
checksum_algo: &HashAlgorithm,
|
||||
skip_verify_bitrot: bool,
|
||||
) -> disk::error::Result<Vec<Option<InlineBitrotReader>>> {
|
||||
let mut readers = Vec::with_capacity(files.len());
|
||||
for file in files {
|
||||
let reader = if let Some(data) = &file.data {
|
||||
crate::io_support::bitrot::create_bitrot_reader_from_bytes_with_frame_size_and_stage_metrics(
|
||||
Some(data.clone()),
|
||||
None,
|
||||
bucket,
|
||||
object,
|
||||
0,
|
||||
read_length,
|
||||
shard_size,
|
||||
frame_size,
|
||||
checksum_algo.clone(),
|
||||
skip_verify_bitrot,
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
@@ -6289,14 +6379,31 @@ fn try_decode_inline_data_shards(
|
||||
if shard_size == 0 {
|
||||
return None;
|
||||
}
|
||||
let frame_size = crate::object_api::persisted_ec_read_quantum(&fi.metadata, fi.erasure.block_size, data_shards, shard_size)
|
||||
.ok()?
|
||||
.unwrap_or(shard_size);
|
||||
if frame_size == 0 {
|
||||
return None;
|
||||
}
|
||||
let checksum_algo = part_checksum_algorithm(fi, part.number);
|
||||
let hash_size = checksum_algo.size();
|
||||
let stride = shard_size.checked_add(hash_size)?;
|
||||
let part_size = inline_erasure_shard_file_size(part.size, fi.erasure.block_size, data_shards, fi.uses_legacy_checksum);
|
||||
let encoded_size = part_size
|
||||
.div_ceil(shard_size)
|
||||
.checked_mul(hash_size)?
|
||||
.checked_add(part_size)?;
|
||||
let encoded_size = if frame_size == shard_size {
|
||||
part_size
|
||||
.div_ceil(shard_size)
|
||||
.checked_mul(hash_size)?
|
||||
.checked_add(part_size)?
|
||||
} else {
|
||||
let mut remaining = part_size;
|
||||
let mut total = 0usize;
|
||||
while remaining > 0 {
|
||||
let payload = remaining.min(frame_size);
|
||||
total = total.checked_add(hash_size)?.checked_add(payload)?;
|
||||
remaining -= payload;
|
||||
}
|
||||
total
|
||||
};
|
||||
let stride = frame_size.checked_add(hash_size)?;
|
||||
// Metadata early-stop can cache this body, so require exact framing even
|
||||
// when the caller explicitly skips bitrot digest verification.
|
||||
for file in data_files.iter().take(data_shards) {
|
||||
@@ -6312,26 +6419,54 @@ fn try_decode_inline_data_shards(
|
||||
disk_call_counters::record(_object, disk_call_counters::KIND_BODY_DECODE, 0);
|
||||
}
|
||||
let mut body = Vec::with_capacity(object_size);
|
||||
for (frame, offset) in (0..object_size).step_by(fi.erasure.block_size).enumerate() {
|
||||
let block_length = fi.erasure.block_size.min(object_size - offset);
|
||||
let read_length =
|
||||
inline_erasure_shard_file_size(block_length, fi.erasure.block_size, data_shards, fi.uses_legacy_checksum);
|
||||
if read_length == 0 || read_length > shard_size {
|
||||
if frame_size == shard_size {
|
||||
for (frame, offset) in (0..object_size).step_by(fi.erasure.block_size).enumerate() {
|
||||
let block_length = fi.erasure.block_size.min(object_size - offset);
|
||||
let read_length =
|
||||
inline_erasure_shard_file_size(block_length, fi.erasure.block_size, data_shards, fi.uses_legacy_checksum);
|
||||
if read_length == 0 || read_length > shard_size {
|
||||
return None;
|
||||
}
|
||||
let start = frame.checked_mul(stride)?;
|
||||
let end = start.checked_add(hash_size)?.checked_add(read_length)?;
|
||||
let mut remaining = block_length;
|
||||
for file in data_files.iter().take(block_length.div_ceil(read_length)) {
|
||||
let block = file.data.as_deref()?.get(start..end)?;
|
||||
let data = coding::verified_bitrot_frame(&checksum_algo, skip_verify_bitrot, block).ok()?;
|
||||
let take = remaining.min(data.len());
|
||||
body.extend_from_slice(&data[..take]);
|
||||
remaining -= take;
|
||||
}
|
||||
if remaining != 0 {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let read_length = part_size;
|
||||
let shards_needed = object_size.div_ceil(read_length.max(1)).max(1);
|
||||
if shards_needed > data_shards {
|
||||
return None;
|
||||
}
|
||||
let start = frame.checked_mul(stride)?;
|
||||
let end = start.checked_add(hash_size)?.checked_add(read_length)?;
|
||||
let mut remaining = block_length;
|
||||
for file in data_files.iter().take(block_length.div_ceil(read_length)) {
|
||||
let block = file.data.as_deref()?.get(start..end)?;
|
||||
let data = coding::verified_bitrot_frame(&checksum_algo, skip_verify_bitrot, block).ok()?;
|
||||
let take = remaining.min(data.len());
|
||||
body.extend_from_slice(&data[..take]);
|
||||
remaining -= take;
|
||||
}
|
||||
if remaining != 0 {
|
||||
return None;
|
||||
for file in data_files.iter().take(shards_needed) {
|
||||
let raw = file.data.as_deref()?;
|
||||
let mut remaining = read_length;
|
||||
let mut cursor = 0usize;
|
||||
while remaining > 0 {
|
||||
let payload_len = remaining.min(frame_size);
|
||||
let frame_need = hash_size.checked_add(payload_len)?;
|
||||
let end = cursor.checked_add(frame_need)?;
|
||||
let block = raw.get(cursor..end)?;
|
||||
let data = coding::verified_bitrot_frame(&checksum_algo, skip_verify_bitrot, block).ok()?;
|
||||
body.extend_from_slice(data);
|
||||
cursor = end;
|
||||
remaining -= payload_len;
|
||||
}
|
||||
if body.len() >= object_size {
|
||||
body.truncate(object_size);
|
||||
return Some(Bytes::from(body));
|
||||
}
|
||||
}
|
||||
return None;
|
||||
}
|
||||
Some(Bytes::from(body))
|
||||
}
|
||||
@@ -17333,8 +17468,12 @@ mod tests {
|
||||
source.metadata_only = true;
|
||||
source.etag = Some("metadata-copy-etag".to_string());
|
||||
|
||||
let dst_opts = ObjectOptions {
|
||||
object_lock_config_snapshot: Some(Arc::new(ObjectLockConfigSnapshot::new(ObjectLockConfigState::ConfirmedAbsent))),
|
||||
..opts.clone()
|
||||
};
|
||||
let copied = set_disks
|
||||
.copy_object(bucket, object, bucket, object, &mut source, &opts, &opts)
|
||||
.copy_object(bucket, object, bucket, object, &mut source, &opts, &dst_opts)
|
||||
.await
|
||||
.expect("metadata self-copy should succeed");
|
||||
assert_eq!(copied.user_defined.get("x-amz-meta-copy-check").map(String::as_str), Some("present"));
|
||||
|
||||
@@ -52,7 +52,7 @@ fn pin_object_heal_future<F: std::future::Future>(build: impl FnOnce() -> F) ->
|
||||
use crate::disk::DataDirDeleteStatus;
|
||||
use crate::disk::DiskAPI;
|
||||
use crate::disk::local::{DELETE_DATA_DIR_MARKER_PREFIX, metadata_less_part_file};
|
||||
use crate::io_support::bitrot::{create_bitrot_reader_from_bytes, object_mmap_read_enabled};
|
||||
use crate::io_support::bitrot::{create_bitrot_reader_from_bytes_with_frame_size_and_stage_metrics, object_mmap_read_enabled};
|
||||
use crate::storage_api_contracts::namespace::NamespaceLocking as _;
|
||||
use rustfs_common::mrf_channel::MrfDeleteMarkerPurge;
|
||||
use rustfs_common::trace_bus::{TraceEvent, TraceFunc, TraceKind, trace_emit};
|
||||
@@ -1703,6 +1703,14 @@ impl SetDisks {
|
||||
if !latest_meta.deleted && !latest_meta.is_remote() {
|
||||
let stage_result: disk::error::Result<Option<DiskError>> = async {
|
||||
let erasure_info = latest_meta.erasure.clone();
|
||||
let frame_size = crate::object_api::persisted_ec_read_quantum(
|
||||
&latest_meta.metadata,
|
||||
erasure.block_size,
|
||||
erasure.data_shards,
|
||||
erasure.shard_size(),
|
||||
)
|
||||
.map_err(|_| DiskError::FileCorrupt)?
|
||||
.unwrap_or_else(|| erasure.shard_size());
|
||||
let mut writer_failures = HealWriterFailures::new(disks_to_heal_count);
|
||||
|
||||
for (part_index, part) in latest_meta.parts.iter().enumerate() {
|
||||
@@ -1745,7 +1753,7 @@ impl SetDisks {
|
||||
&format!("part.{}", part.number),
|
||||
]),
|
||||
erasure.shard_file_size(part.size as i64),
|
||||
erasure.shard_size(),
|
||||
frame_size,
|
||||
HashAlgorithm::HighwayHash256S,
|
||||
)
|
||||
.await
|
||||
@@ -1812,7 +1820,7 @@ impl SetDisks {
|
||||
checksum_info.algorithm
|
||||
};
|
||||
|
||||
match create_bitrot_reader_from_bytes(
|
||||
match create_bitrot_reader_from_bytes_with_frame_size_and_stage_metrics(
|
||||
metadata.data.clone(),
|
||||
Some(disk),
|
||||
bucket,
|
||||
@@ -1820,9 +1828,11 @@ impl SetDisks {
|
||||
0,
|
||||
till_offset,
|
||||
erasure.shard_size(),
|
||||
frame_size,
|
||||
checksum_algo.clone(),
|
||||
false,
|
||||
use_mmap_read,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -3975,7 +3985,10 @@ mod heal_result_report_tests {
|
||||
use crate::disk::error::DiskError;
|
||||
use crate::disk::format::FormatV3;
|
||||
use crate::disk::local::RESERVED_DELETE_DATA_DIR_MARKER_PREFIX;
|
||||
use crate::disk::{DiskAPI as _, DiskOption, DiskStore, RUSTFS_META_TMP_BUCKET, ReadOptions, STORAGE_FORMAT_FILE, new_disk};
|
||||
use crate::disk::{
|
||||
CHECK_PART_SUCCESS, DiskAPI as _, DiskOption, DiskStore, RUSTFS_META_TMP_BUCKET, ReadOptions, STORAGE_FORMAT_FILE,
|
||||
new_disk,
|
||||
};
|
||||
use crate::error::Error;
|
||||
use crate::object_api::{ObjectOptions, PutObjReader};
|
||||
use crate::set_disk::ops::object::hermetic_set_disks_support::{
|
||||
@@ -5653,6 +5666,231 @@ mod heal_result_report_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn bounded_quantum_shards_pass_disk_verification_and_deep_heal() {
|
||||
let (_dirs, disks, set) = hermetic_set_disks_isolated(4).await;
|
||||
let bucket = "bounded-quantum-healthy";
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("create bounded-quantum test bucket");
|
||||
}
|
||||
|
||||
for (block_size, quantum) in [
|
||||
(64 * 1024, Some(16 * 1024)),
|
||||
(1024 * 1024, None),
|
||||
(4 * 1024 * 1024, Some(1024 * 1024)),
|
||||
] {
|
||||
let object = format!("block-{block_size}");
|
||||
let mut options = ObjectOptions {
|
||||
no_lock: true,
|
||||
..Default::default()
|
||||
};
|
||||
options
|
||||
.user_defined
|
||||
.insert(crate::object_api::EC_BLOCK_SIZE_HINT_INTERNAL_KEY.to_owned(), block_size.to_string());
|
||||
temp_env::async_with_vars(
|
||||
[
|
||||
(rustfs_config::ENV_EC_READ_QUANTUM_ENABLE, Some("true")),
|
||||
(rustfs_config::ENV_EC_READ_QUANTUM_FLEET_CONFIRMED, Some("true")),
|
||||
(rustfs_config::ENV_SHARD_INTEGRITY_WRITE, Some("false")),
|
||||
],
|
||||
async {
|
||||
set.put_object(bucket, &object, &mut PutObjReader::from_vec(vec![0x6d; 4 * 1024 * 1024 + 123]), &options)
|
||||
.await
|
||||
.expect("write non-inline bounded-quantum fixture");
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
for (disk_index, disk) in disks.iter().enumerate() {
|
||||
let metadata = disk
|
||||
.read_version("", bucket, &object, "", &ReadOptions::default())
|
||||
.await
|
||||
.expect("read persisted bounded-quantum layout");
|
||||
assert!(metadata.data.is_none(), "verification must open physical shards");
|
||||
let erasure = &metadata.erasure;
|
||||
assert_eq!(
|
||||
crate::object_api::persisted_ec_read_quantum(
|
||||
&metadata.metadata,
|
||||
erasure.block_size,
|
||||
erasure.data_blocks,
|
||||
erasure.shard_size(),
|
||||
)
|
||||
.expect("stored frame geometry must be valid"),
|
||||
quantum,
|
||||
);
|
||||
let verified = disk
|
||||
.verify_file(bucket, &object, &metadata)
|
||||
.await
|
||||
.expect("verify healthy physical shard");
|
||||
assert_eq!(verified.results, vec![CHECK_PART_SUCCESS], "block size {block_size}");
|
||||
if disk_index == 0 && block_size == 64 * 1024 {
|
||||
let mut invalid = metadata.clone();
|
||||
crate::object_api::insert_ec_read_quantum(&mut invalid.metadata, 1);
|
||||
assert_eq!(
|
||||
disk.verify_file(bucket, &object, &invalid)
|
||||
.await
|
||||
.expect_err("unsupported frame geometry must fail closed"),
|
||||
DiskError::FileCorrupt,
|
||||
);
|
||||
invalid = metadata.clone();
|
||||
invalid
|
||||
.metadata
|
||||
.insert("x-minio-internal-ec-read-quantum".to_owned(), "32768".to_owned());
|
||||
assert_eq!(
|
||||
disk.verify_file(bucket, &object, &invalid)
|
||||
.await
|
||||
.expect_err("conflicting frame markers must not select a plausible layout"),
|
||||
DiskError::FileCorrupt,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let (result, error) = set
|
||||
.heal_object(
|
||||
bucket,
|
||||
&object,
|
||||
"",
|
||||
&HealOpts {
|
||||
no_lock: true,
|
||||
scan_mode: HealScanMode::Deep,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("deep scan should accept persisted bounded-quantum data");
|
||||
assert!(error.is_none(), "healthy bounded-quantum object must not require recovery: {error:?}");
|
||||
assert_eq!(result.drives_healed(), Some(0));
|
||||
assert!(
|
||||
result
|
||||
.after
|
||||
.drives
|
||||
.iter()
|
||||
.all(|drive| drive.state == DriveState::Ok.to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn bounded_quantum_heal_restores_exact_frames_and_range_bytes() {
|
||||
use crate::storage_api_contracts::range::HTTPRangeSpec;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
let (dirs, disks, set) = hermetic_set_disks_isolated(4).await;
|
||||
let bucket = "bounded-quantum-recovery";
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket)
|
||||
.await
|
||||
.expect("create bounded-quantum recovery bucket");
|
||||
}
|
||||
let payload: Vec<u8> = (0..4 * 1024 * 1024 + 123)
|
||||
.map(|index| u8::try_from(index % 251).expect("fixture byte"))
|
||||
.collect();
|
||||
for (block_size, quantum) in [(64 * 1024, 16 * 1024), (4 * 1024 * 1024, 1024 * 1024)] {
|
||||
for scan_mode in [HealScanMode::Normal, HealScanMode::Deep] {
|
||||
let object = format!("block-{block_size}-{}", scan_mode.as_str());
|
||||
let mut options = ObjectOptions {
|
||||
no_lock: true,
|
||||
..Default::default()
|
||||
};
|
||||
options
|
||||
.user_defined
|
||||
.insert(crate::object_api::EC_BLOCK_SIZE_HINT_INTERNAL_KEY.to_owned(), block_size.to_string());
|
||||
temp_env::async_with_vars(
|
||||
[
|
||||
(rustfs_config::ENV_EC_READ_QUANTUM_ENABLE, Some("true")),
|
||||
(rustfs_config::ENV_EC_READ_QUANTUM_FLEET_CONFIRMED, Some("true")),
|
||||
(rustfs_config::ENV_SHARD_INTEGRITY_WRITE, Some("false")),
|
||||
],
|
||||
async {
|
||||
set.put_object(bucket, &object, &mut PutObjReader::from_vec(payload.clone()), &options)
|
||||
.await
|
||||
.expect("write bounded-quantum recovery fixture");
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let original = disks[0]
|
||||
.read_version("", bucket, &object, "", &ReadOptions::default())
|
||||
.await
|
||||
.expect("read original shard layout");
|
||||
let path = dirs[0]
|
||||
.path()
|
||||
.join(bucket)
|
||||
.join(&object)
|
||||
.join(original.data_dir.expect("external shard data directory").to_string())
|
||||
.join("part.1");
|
||||
let original_bytes = tokio::fs::read(&path).await.expect("snapshot encoded shard");
|
||||
tokio::fs::remove_file(&path).await.expect("remove task-owned shard");
|
||||
|
||||
let (result, error) = set
|
||||
.heal_object(
|
||||
bucket,
|
||||
&object,
|
||||
"",
|
||||
&HealOpts {
|
||||
no_lock: true,
|
||||
scan_mode,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("bounded-quantum heal should finish");
|
||||
assert!(error.is_none(), "bounded-quantum recovery must retain a read quorum: {error:?}");
|
||||
assert_eq!(result.drives_healed(), Some(1));
|
||||
let repaired = disks[0]
|
||||
.read_version("", bucket, &object, "", &ReadOptions::default())
|
||||
.await
|
||||
.expect("read repaired shard metadata");
|
||||
assert_eq!(
|
||||
crate::object_api::persisted_ec_read_quantum(
|
||||
&repaired.metadata,
|
||||
repaired.erasure.block_size,
|
||||
repaired.erasure.data_blocks,
|
||||
repaired.erasure.shard_size(),
|
||||
)
|
||||
.expect("healed frame marker must match its geometry"),
|
||||
Some(quantum),
|
||||
);
|
||||
let repaired_path = dirs[0]
|
||||
.path()
|
||||
.join(bucket)
|
||||
.join(&object)
|
||||
.join(repaired.data_dir.expect("repaired shard data directory").to_string())
|
||||
.join("part.1");
|
||||
assert_eq!(tokio::fs::read(repaired_path).await.expect("read restored frames"), original_bytes);
|
||||
assert_eq!(
|
||||
disks[0]
|
||||
.verify_file(bucket, &object, &repaired)
|
||||
.await
|
||||
.expect("verify repaired shard")
|
||||
.results,
|
||||
vec![CHECK_PART_SUCCESS],
|
||||
);
|
||||
|
||||
for (range, expected) in [
|
||||
(None, payload.as_slice()),
|
||||
(
|
||||
Some(HTTPRangeSpec {
|
||||
start: 16 * 1024 - 37,
|
||||
end: 64 * 1024 + 85,
|
||||
is_suffix_length: false,
|
||||
}),
|
||||
&payload[16 * 1024 - 37..64 * 1024 + 86],
|
||||
),
|
||||
] {
|
||||
let mut reader = set
|
||||
.get_object_reader(bucket, &object, range, Default::default(), &options)
|
||||
.await
|
||||
.expect("healed object must serve full and cross-frame range reads");
|
||||
let mut body = Vec::new();
|
||||
reader.stream.read_to_end(&mut body).await.expect("read healed object body");
|
||||
assert_eq!(body, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn deep_heal_legacy_verification_error_cannot_certify_healthy() {
|
||||
|
||||
@@ -123,14 +123,14 @@ async fn create_part_writers(
|
||||
disks: &[Option<DiskStore>],
|
||||
path: &str,
|
||||
length: i64,
|
||||
shard_size: usize,
|
||||
frame_size: usize,
|
||||
) -> (Vec<Option<BitrotWriterWrapper>>, Vec<Option<DiskError>>) {
|
||||
join_all(disks.iter().map(|disk| async move {
|
||||
let Some(disk) = disk else {
|
||||
return (None, Some(DiskError::DiskNotFound));
|
||||
};
|
||||
#[cfg(test)]
|
||||
if let Some(result) = multipart_writer_test_hook::create_writer(disk, path, length, shard_size).await {
|
||||
if let Some(result) = multipart_writer_test_hook::create_writer(disk, path, length, frame_size).await {
|
||||
return match result {
|
||||
Ok(writer) => (Some(writer), None),
|
||||
Err(error) => (None, Some(error)),
|
||||
@@ -143,7 +143,7 @@ async fn create_part_writers(
|
||||
RUSTFS_META_TMP_BUCKET,
|
||||
path,
|
||||
length,
|
||||
shard_size,
|
||||
frame_size,
|
||||
HashAlgorithm::HighwayHash256S,
|
||||
)
|
||||
.await
|
||||
@@ -1151,6 +1151,10 @@ impl SetDisks {
|
||||
upload_id: upload_id.to_owned(),
|
||||
user_defined: {
|
||||
strip_internal_multipart_metadata(&mut fi.metadata);
|
||||
rustfs_utils::http::metadata_compat::remove_str(
|
||||
&mut fi.metadata,
|
||||
crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX,
|
||||
);
|
||||
fi.metadata.clone()
|
||||
},
|
||||
..Default::default()
|
||||
@@ -2826,13 +2830,21 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
let erasure =
|
||||
Arc::new(coding::Erasure::try_new(fi.erasure.data_blocks, fi.erasure.parity_blocks, fi.erasure.block_size)
|
||||
.map_err(Error::from)?);
|
||||
let frame_size = crate::object_api::persisted_ec_read_quantum(
|
||||
&fi.metadata,
|
||||
erasure.block_size,
|
||||
erasure.data_shards,
|
||||
erasure.shard_size(),
|
||||
)
|
||||
.map_err(|error| Error::other(error.to_string()))?
|
||||
.unwrap_or_else(|| erasure.shard_size());
|
||||
let writer_setup_stage_start = rustfs_io_metrics::put_stage_metrics_enabled().then(Instant::now);
|
||||
|
||||
let (mut writers, errors) = create_part_writers(
|
||||
&shuffle_disks,
|
||||
&tmp_part_path,
|
||||
erasure.shard_file_size(data.size()),
|
||||
erasure.shard_size(),
|
||||
frame_size,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -3283,6 +3295,10 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
user_defined: {
|
||||
let mut metadata = fi.metadata.clone();
|
||||
strip_internal_multipart_metadata(&mut metadata);
|
||||
rustfs_utils::http::metadata_compat::remove_str(
|
||||
&mut metadata,
|
||||
crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX,
|
||||
);
|
||||
metadata
|
||||
},
|
||||
..Default::default()
|
||||
@@ -3460,8 +3476,10 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
let disks = self.get_disks_internal().await;
|
||||
|
||||
let mut user_defined = opts.user_defined.clone();
|
||||
let requested_ec_block_size = crate::object_api::take_ec_block_size_hint(&mut user_defined);
|
||||
strip_native_controls(&mut user_defined);
|
||||
rustfs_utils::http::remove_str(&mut user_defined, SUFFIX_INLINE_DATA);
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX);
|
||||
rustfs_filemeta::shard_integrity::clear_integrity_metadata(&mut user_defined);
|
||||
if protect_upload {
|
||||
rustfs_utils::http::insert_str(
|
||||
@@ -3507,6 +3525,20 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
)?;
|
||||
|
||||
let mut fi = FileInfo::new([bucket, object].join("/").as_str(), data_drives, parity_drives);
|
||||
if let Some(block_size) = requested_ec_block_size {
|
||||
fi.erasure.block_size = block_size;
|
||||
}
|
||||
|
||||
if !protect_upload && crate::object_api::ec_read_quantum_write_enabled() {
|
||||
let erasure = coding::Erasure::try_new(fi.erasure.data_blocks, fi.erasure.parity_blocks, fi.erasure.block_size)
|
||||
.map_err(Error::from)?;
|
||||
if let Some(frame_size) =
|
||||
crate::object_api::select_ec_read_quantum(fi.erasure.block_size, erasure.data_shards, erasure.shard_size())
|
||||
&& frame_size != erasure.shard_size()
|
||||
{
|
||||
crate::object_api::insert_ec_read_quantum(&mut user_defined, frame_size);
|
||||
}
|
||||
}
|
||||
|
||||
fi.version_id = if let Some(vid) = &opts.version_id {
|
||||
Some(Uuid::parse_str(vid)?)
|
||||
@@ -3629,6 +3661,9 @@ impl crate::storage_api_contracts::multipart::MultipartOperations for SetDisks {
|
||||
upload_id,
|
||||
checksum_algo: user_defined.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM).cloned(),
|
||||
checksum_type: user_defined.get(rustfs_rio::RUSTFS_MULTIPART_CHECKSUM_TYPE).cloned(),
|
||||
effective_ec_block_size: Some(
|
||||
u64::try_from(fi.erasure.block_size).map_err(|_| Error::other("invalid EC block size"))?,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5356,6 +5391,48 @@ mod tests {
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::{Notify, RwLock};
|
||||
|
||||
#[tokio::test]
|
||||
async fn multipart_upload_persists_block_size_for_later_parts_and_completion() {
|
||||
use crate::storage_api_contracts::multipart::MultipartOperations as _;
|
||||
|
||||
let (_temp_dirs, disks, set_disks) = hermetic_set_disks(4).await;
|
||||
let bucket = "ec-block-size-multipart";
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("bucket volume should be created");
|
||||
}
|
||||
|
||||
let mut create_opts = ObjectOptions::default();
|
||||
create_opts
|
||||
.user_defined
|
||||
.insert(crate::object_api::EC_BLOCK_SIZE_HINT_INTERNAL_KEY.to_string(), "65536".to_string());
|
||||
let upload = set_disks
|
||||
.new_multipart_upload(bucket, "object", &create_opts)
|
||||
.await
|
||||
.expect("multipart upload should be created");
|
||||
assert_eq!(upload.effective_ec_block_size, Some(65_536));
|
||||
|
||||
let mut part_reader = PutObjReader::from_vec(vec![0x61; 5 * 1024 * 1024]);
|
||||
let part = set_disks
|
||||
.put_object_part(bucket, "object", &upload.upload_id, 1, &mut part_reader, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("part must use the block size persisted at upload creation");
|
||||
let completed = set_disks
|
||||
.complete_multipart_upload(
|
||||
bucket,
|
||||
"object",
|
||||
&upload.upload_id,
|
||||
vec![CompletePart {
|
||||
part_num: 1,
|
||||
etag: part.etag.clone(),
|
||||
..Default::default()
|
||||
}],
|
||||
&ObjectOptions::default(),
|
||||
)
|
||||
.await
|
||||
.expect("upload should complete using its stored layout");
|
||||
assert_eq!(completed.effective_ec_block_size(), Some(65_536));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn multipart_writer_setup_opens_disks_concurrently_and_preserves_error_slots() {
|
||||
use crate::cluster::rpc::internode_data_transport::{
|
||||
|
||||
@@ -43,26 +43,26 @@ use super::super::{
|
||||
ReplicationObjectBridge, Result, SET_DISK_COMMIT_TAIL_WARN_THRESHOLD_MS, SLASH_SEPARATOR, SUFFIX_ACTUAL_SIZE,
|
||||
SUFFIX_COMPRESSION, SUFFIX_COMPRESSION_SIZE, SUFFIX_RESTORE_COPYBACK, SUFFIX_RESTORE_OPERATION_ID,
|
||||
SUFFIX_RESTORE_WORKER_LOCK, SetDisks, SmallWritePath, StorageError, TRANSITION_COMPLETE, UpdateMetadataOpts, Uuid,
|
||||
WriteLayout, adaptive_duplex_buffer_size, build_get_object_info, build_inline_bitrot_readers, check_object_lock_delete,
|
||||
check_object_lock_for_deletion_with_state, check_object_lock_retention_update, classify_get_codec_streaming_object_class,
|
||||
classify_put_write_path, classify_storage_error, collect_inline_data_shard_fileinfos_by_index, contains_key_str,
|
||||
create_bitrot_writer_with_orig_volume, debug, delete_file_info_version_id, disk, ensure_delete_commit_locks_held, error,
|
||||
explicit_delete_removed_marker, finish_set_disk_read_lock, get_codec_streaming_reader_gate_with_plan,
|
||||
get_object_body_cache_hook, get_raw_etag, get_small_object_direct_memory_decision_with_threshold_and_plan,
|
||||
get_small_object_direct_memory_threshold, get_stage_timer_if_enabled, get_str,
|
||||
get_transitioned_object_reader_with_tier_manager, insert_str, is_deadlock_detection_enabled, is_err_object_not_found,
|
||||
is_err_version_not_found, is_explicit_null_version, is_get_codec_streaming_base_enabled,
|
||||
is_get_small_object_direct_memory_enabled, is_lock_optimization_enabled, issue3031_diag_enabled, join_all,
|
||||
known_put_object_storage_size, part_checksum_algorithm, path_join_buf, put_restore_opts, record_compression_total_memory,
|
||||
record_get_codec_streaming_gate_decision, record_get_direct_memory_decision, record_get_object_pipeline_failure,
|
||||
record_get_object_pipeline_failure_for_path, record_get_object_reader_path_observation, record_get_stage_duration_if_enabled,
|
||||
record_lock_acquire, reduce_write_quorum_errs, release_materialized_read_lock, replication_write_may_pass_worm_gate,
|
||||
republishes_data_movement_delete_marker, require_restore_operation_id, resolve_delete_version_state,
|
||||
resolve_tiered_decommission_write_quorum_result, resolve_write_layout, restore_commit_operation_id_from_metadata,
|
||||
restore_operation_id_from_metadata, send_event, set_disk_delete_creates_delete_marker,
|
||||
should_force_delete_marker_for_missing_version, should_inline_put, should_persist_encryption_original_size,
|
||||
should_preserve_delete_replication_state, should_use_inline_fast_path_with_plan, take_prepared_get_object_metadata,
|
||||
to_object_err, try_decode_inline_data_shards, warn,
|
||||
WriteLayout, adaptive_duplex_buffer_size, build_get_object_info, build_inline_bitrot_readers_with_frame_size,
|
||||
check_object_lock_delete, check_object_lock_for_deletion_with_state, check_object_lock_retention_update,
|
||||
classify_get_codec_streaming_object_class, classify_put_write_path, classify_storage_error,
|
||||
collect_inline_data_shard_fileinfos_by_index, contains_key_str, create_bitrot_writer_with_orig_volume, debug,
|
||||
delete_file_info_version_id, disk, ensure_delete_commit_locks_held, error, explicit_delete_removed_marker,
|
||||
finish_set_disk_read_lock, get_codec_streaming_reader_gate_with_plan, get_object_body_cache_hook, get_raw_etag,
|
||||
get_small_object_direct_memory_decision_with_threshold_and_plan, get_small_object_direct_memory_threshold,
|
||||
get_stage_timer_if_enabled, get_str, get_transitioned_object_reader_with_tier_manager, insert_str,
|
||||
is_deadlock_detection_enabled, is_err_object_not_found, is_err_version_not_found, is_explicit_null_version,
|
||||
is_get_codec_streaming_base_enabled, is_get_small_object_direct_memory_enabled, is_lock_optimization_enabled,
|
||||
issue3031_diag_enabled, join_all, known_put_object_storage_size, part_checksum_algorithm, path_join_buf, put_restore_opts,
|
||||
record_compression_total_memory, record_get_codec_streaming_gate_decision, record_get_direct_memory_decision,
|
||||
record_get_object_pipeline_failure, record_get_object_pipeline_failure_for_path, record_get_object_reader_path_observation,
|
||||
record_get_stage_duration_if_enabled, record_lock_acquire, reduce_write_quorum_errs, release_materialized_read_lock,
|
||||
replication_write_may_pass_worm_gate, republishes_data_movement_delete_marker, require_restore_operation_id,
|
||||
resolve_delete_version_state, resolve_tiered_decommission_write_quorum_result, resolve_write_layout,
|
||||
restore_commit_operation_id_from_metadata, restore_operation_id_from_metadata, send_event,
|
||||
set_disk_delete_creates_delete_marker, should_force_delete_marker_for_missing_version, should_inline_put,
|
||||
should_persist_encryption_original_size, should_preserve_delete_replication_state, should_use_inline_fast_path_with_plan,
|
||||
take_prepared_get_object_metadata, to_object_err, try_decode_inline_data_shards, warn,
|
||||
};
|
||||
use super::bitrot_self_verify::{BitrotSelfVerifyTarget, drop_failed_writer_disks, verify_written_bitrot_shards};
|
||||
use super::delete_recovery::DeleteRecoveryContext;
|
||||
@@ -3170,6 +3170,8 @@ impl crate::storage_api_contracts::object::ObjectIO for SetDisks {
|
||||
let read_length = erasure.shard_file_offset(0, object_size, object_size);
|
||||
let total_shards = data_shards + fi.erasure.parity_blocks;
|
||||
let (_disks, files) = Self::shuffle_disks_and_parts_metadata_by_index(disks, files, fi);
|
||||
let frame_size = crate::set_disk::read::read_frame_size_for_file_info(fi, &erasure)
|
||||
.map_err(|error| to_object_err(error, vec![bucket, object]))?;
|
||||
|
||||
// Check if we have enough inline data shards
|
||||
let inline_count = files
|
||||
@@ -3180,13 +3182,14 @@ impl crate::storage_api_contracts::object::ObjectIO for SetDisks {
|
||||
|
||||
if inline_count >= data_shards {
|
||||
let reader_setup_stage_start = rustfs_io_metrics::get_stage_metrics_enabled().then(Instant::now);
|
||||
let readers = build_inline_bitrot_readers(
|
||||
let readers = build_inline_bitrot_readers_with_frame_size(
|
||||
files.iter(),
|
||||
total_shards,
|
||||
bucket,
|
||||
object,
|
||||
read_length,
|
||||
erasure.shard_size(),
|
||||
frame_size,
|
||||
&checksum_algo,
|
||||
opts.skip_verify_bitrot,
|
||||
)
|
||||
@@ -4600,6 +4603,11 @@ impl SetDisks {
|
||||
|
||||
let expected_restore_operation_id = restore_commit_operation_id_from_metadata(&opts.user_defined)?;
|
||||
let mut user_defined = opts.user_defined.clone();
|
||||
let requested_ec_block_size = crate::object_api::take_ec_block_size_hint(&mut user_defined);
|
||||
// This is a request-to-writer marker. It must never become ordinary
|
||||
// object metadata, even when the caller supplied it through an
|
||||
// internal path.
|
||||
rustfs_utils::http::metadata_compat::remove_str(&mut user_defined, crate::object_api::EC_BLOCK_SIZE_INFO_INTERNAL_SUFFIX);
|
||||
rustfs_filemeta::shard_integrity::clear_integrity_metadata(&mut user_defined);
|
||||
if let Some(eval_metadata) = &opts.eval_metadata {
|
||||
merge_evaluated_metadata(&mut user_defined, eval_metadata)?;
|
||||
@@ -4645,6 +4653,9 @@ impl SetDisks {
|
||||
// }
|
||||
|
||||
let mut fi = FileInfo::new([bucket, object].join("/").as_str(), data_drives, parity_drives);
|
||||
if let Some(block_size) = requested_ec_block_size {
|
||||
fi.erasure.block_size = block_size;
|
||||
}
|
||||
|
||||
fi.version_id = {
|
||||
if let Some(ref vid) = opts.version_id {
|
||||
@@ -4731,6 +4742,21 @@ impl SetDisks {
|
||||
let collect_stage_timing = rustfs_io_metrics::put_stage_metrics_enabled() || issue3031_diag_enabled();
|
||||
let shard_file_size = shard_file_size_raw;
|
||||
let shard_size = erasure.shard_size();
|
||||
// Large layout blocks are still useful for sequential writes, but
|
||||
// they should not force every Range GET to verify/read that whole
|
||||
// shard. New unprotected, non-inline objects may opt into the
|
||||
// bounded per-frame format; legacy and protected writes retain the
|
||||
// historical framing so their existing readers and proofs remain
|
||||
// byte-for-byte compatible.
|
||||
let frame_size = if !is_inline_buffer && !protect_write && crate::object_api::ec_read_quantum_write_enabled() {
|
||||
crate::object_api::select_ec_read_quantum(fi.erasure.block_size, erasure.data_shards, shard_size)
|
||||
.unwrap_or(shard_size)
|
||||
} else {
|
||||
shard_size
|
||||
};
|
||||
if frame_size != shard_size {
|
||||
crate::object_api::insert_ec_read_quantum(&mut user_defined, frame_size);
|
||||
}
|
||||
let write_path = classify_put_write_path(is_inline_buffer, put_object_size, fi.erasure.block_size);
|
||||
let direct_inline_commit = matches!(write_path, SmallWritePath::Inline);
|
||||
rustfs_io_metrics::record_put_object_path(write_path.metric_label());
|
||||
@@ -4770,7 +4796,7 @@ impl SetDisks {
|
||||
RUSTFS_META_TMP_BUCKET,
|
||||
&tmp_obj,
|
||||
shard_file_size,
|
||||
shard_size,
|
||||
frame_size,
|
||||
HashAlgorithm::HighwayHash256S,
|
||||
)
|
||||
.await
|
||||
@@ -6575,7 +6601,7 @@ impl SetDisks {
|
||||
let diagnostic_context = crate::cluster::rpc::runtime_sources::ReadVersionDiagnosticContext::capture_entry(
|
||||
rustfs_io_metrics::internode_metrics::ReadVersionEntrySource::PutCommitOwner,
|
||||
);
|
||||
let result = tokio::spawn(async move {
|
||||
let result = tokio::spawn(crate::disk::with_detached_disk_io_context(async move {
|
||||
let commit = Box::pin(commit(commit_submit_to_closure_enter_started, Some(child_token)));
|
||||
#[cfg(feature = "diagnostic-read-version-caller")]
|
||||
return crate::cluster::rpc::runtime_sources::with_read_version_diagnostic_context(
|
||||
@@ -6586,7 +6612,7 @@ impl SetDisks {
|
||||
.await;
|
||||
#[cfg(not(feature = "diagnostic-read-version-caller"))]
|
||||
commit.await
|
||||
})
|
||||
}))
|
||||
.await
|
||||
.map_err(|err| Error::other(format!("put_object commit task failed: {err}")))?;
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from(
|
||||
@@ -10066,6 +10092,15 @@ impl crate::storage_api_contracts::object::ObjectOperations for SetDisks {
|
||||
};
|
||||
let mut replacement_metadata = (*src_info.user_defined).clone();
|
||||
rustfs_filemeta::shard_integrity::clear_integrity_metadata(&mut replacement_metadata);
|
||||
if src_info.version_only {
|
||||
// Shared shard files retain the selected version's persisted framing.
|
||||
let suffix = crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX;
|
||||
rustfs_utils::http::remove_str(&mut replacement_metadata, suffix);
|
||||
if rustfs_utils::http::contains_key_str(&fi.metadata, suffix) {
|
||||
let quantum = rustfs_utils::http::get_consistent_str(&fi.metadata, suffix).ok_or(Error::FileCorrupt)?;
|
||||
rustfs_utils::http::insert_str(&mut replacement_metadata, suffix, quantum.to_owned());
|
||||
}
|
||||
}
|
||||
for suffix in [
|
||||
rustfs_filemeta::shard_integrity::SUFFIX_SHARD_INTEGRITY,
|
||||
rustfs_filemeta::shard_integrity::SUFFIX_INLINE_INTEGRITY,
|
||||
@@ -13859,6 +13894,61 @@ mod replication_quota_safety_tests {
|
||||
use super::*;
|
||||
use std::io::Cursor;
|
||||
|
||||
#[tokio::test]
|
||||
async fn put_object_persists_transient_ec_block_size_without_leaking_marker_metadata() {
|
||||
let (_temp_dirs, disks, set_disks) = hermetic_set_disks(4).await;
|
||||
let bucket = "ec-block-size-marker";
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("bucket volume should be created");
|
||||
}
|
||||
|
||||
for block_size in crate::object_api::EC_BLOCK_SIZE_CANDIDATES {
|
||||
let object = format!("object-{block_size}");
|
||||
let mut opts = ObjectOptions::default();
|
||||
opts.user_defined
|
||||
.insert(crate::object_api::EC_BLOCK_SIZE_HINT_INTERNAL_KEY.to_string(), block_size.to_string());
|
||||
let payload = vec![0x61; 4096];
|
||||
let mut reader = PutObjReader::from_vec(payload.clone());
|
||||
set_disks
|
||||
.put_object(bucket, &object, &mut reader, &opts)
|
||||
.await
|
||||
.expect("object with a supported block-size marker should be written");
|
||||
|
||||
let info = set_disks
|
||||
.get_object_info(bucket, &object, &ObjectOptions::default())
|
||||
.await
|
||||
.expect("written object metadata should be readable");
|
||||
assert_eq!(info.effective_ec_block_size(), Some(block_size));
|
||||
assert!(
|
||||
!info
|
||||
.user_defined
|
||||
.contains_key(crate::object_api::EC_BLOCK_SIZE_HINT_INTERNAL_KEY)
|
||||
);
|
||||
|
||||
let mut object_reader = set_disks
|
||||
.get_object_reader(
|
||||
bucket,
|
||||
&object,
|
||||
Some(HTTPRangeSpec {
|
||||
is_suffix_length: false,
|
||||
start: 128,
|
||||
end: 511,
|
||||
}),
|
||||
HeaderMap::new(),
|
||||
&ObjectOptions::default(),
|
||||
)
|
||||
.await
|
||||
.expect("persisted block size should decode range reads");
|
||||
let mut restored = Vec::new();
|
||||
object_reader
|
||||
.stream
|
||||
.read_to_end(&mut restored)
|
||||
.await
|
||||
.expect("range read should complete");
|
||||
assert_eq!(restored, payload[128..512]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_put_future_keeps_commit_state_off_the_caller_stack() {
|
||||
let (_temp_dirs, _disks, set_disks) = hermetic_set_disks(4).await;
|
||||
@@ -17182,7 +17272,12 @@ mod metadata_mutation_generation_tests {
|
||||
copy_object,
|
||||
&mut copy_info,
|
||||
&ObjectOptions::default(),
|
||||
&ObjectOptions::default(),
|
||||
&ObjectOptions {
|
||||
object_lock_config_snapshot: Some(Arc::new(ObjectLockConfigSnapshot::new(
|
||||
ObjectLockConfigState::ConfirmedAbsent,
|
||||
))),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("metadata COPY should succeed");
|
||||
@@ -17285,8 +17380,17 @@ mod metadata_mutation_generation_tests {
|
||||
version_id: old.version_id.map(|id| id.to_string()),
|
||||
versioned: true,
|
||||
mod_time: Some(old_time),
|
||||
object_lock_config_snapshot: Some(Arc::new(ObjectLockConfigSnapshot::new(
|
||||
ObjectLockConfigState::ConfirmedAbsent,
|
||||
))),
|
||||
..Default::default()
|
||||
};
|
||||
let dst_opts = ObjectOptions {
|
||||
object_lock_config_snapshot: Some(Arc::new(ObjectLockConfigSnapshot::new(
|
||||
ObjectLockConfigState::ConfirmedAbsent,
|
||||
))),
|
||||
..opts.clone()
|
||||
};
|
||||
let mut source = set.get_object_info(bucket, object, &opts).await.expect("read old metadata");
|
||||
assert_eq!(source.user_tags.as_str(), tags);
|
||||
assert_eq!(source.expires, Some(expires));
|
||||
@@ -17295,7 +17399,7 @@ mod metadata_mutation_generation_tests {
|
||||
source.metadata_only = true;
|
||||
Arc::make_mut(&mut source.user_defined)
|
||||
.insert(metadata_keys::RESTORE.to_string(), "ongoing-request=\"true\"".to_string());
|
||||
set.copy_object(bucket, object, bucket, object, &mut source, &opts, &opts)
|
||||
set.copy_object(bucket, object, bucket, object, &mut source, &opts, &dst_opts)
|
||||
.await
|
||||
.expect("restore metadata update");
|
||||
let restored = set
|
||||
@@ -17360,7 +17464,11 @@ mod metadata_mutation_generation_tests {
|
||||
let metadata = Arc::make_mut(&mut source.user_defined);
|
||||
metadata.insert(AMZ_OBJECT_TAGGING.to_string(), "new=value".to_string());
|
||||
metadata.insert("expires".to_string(), expires.format(&Rfc3339).expect("expiry"));
|
||||
set.copy_object(bucket, "object", bucket, "object", &mut source, &opts, &opts)
|
||||
let dst_opts = ObjectOptions {
|
||||
object_lock_config_snapshot: Some(Arc::new(ObjectLockConfigSnapshot::new(ObjectLockConfigState::ConfirmedAbsent))),
|
||||
..Default::default()
|
||||
};
|
||||
set.copy_object(bucket, "object", bucket, "object", &mut source, &opts, &dst_opts)
|
||||
.await
|
||||
.expect("explicit metadata wins over externalized fields");
|
||||
let mut copied = set.get_object_info(bucket, "object", &opts).await.expect("copied metadata");
|
||||
@@ -17371,7 +17479,7 @@ mod metadata_mutation_generation_tests {
|
||||
copied.metadata_only = true;
|
||||
copied.user_tags = Arc::new(String::new());
|
||||
copied.expires = None;
|
||||
set.copy_object(bucket, "object", bucket, "object", &mut copied, &opts, &opts)
|
||||
set.copy_object(bucket, "object", bucket, "object", &mut copied, &opts, &dst_opts)
|
||||
.await
|
||||
.expect("explicit empty replacement");
|
||||
let cleared = set.get_object_info(bucket, "object", &opts).await.expect("cleared metadata");
|
||||
@@ -17388,6 +17496,10 @@ mod metadata_mutation_generation_tests {
|
||||
}
|
||||
|
||||
let valid_object = "valid-sidecar";
|
||||
let dst_opts = ObjectOptions {
|
||||
object_lock_config_snapshot: Some(Arc::new(ObjectLockConfigSnapshot::new(ObjectLockConfigState::ConfirmedAbsent))),
|
||||
..Default::default()
|
||||
};
|
||||
let (mut valid_source, _) = put_and_prime(&set_disks, bucket, valid_object, b"valid sidecar body").await;
|
||||
persist_part_checksum_sidecar(&set_disks, bucket, valid_object, r#"[[1,[["CRC32C","AAAAAA=="]]]]"#).await;
|
||||
valid_source.metadata_only = true;
|
||||
@@ -17400,7 +17512,7 @@ mod metadata_mutation_generation_tests {
|
||||
valid_object,
|
||||
&mut valid_source,
|
||||
&ObjectOptions::default(),
|
||||
&ObjectOptions::default(),
|
||||
&dst_opts,
|
||||
)
|
||||
.await
|
||||
.expect("metadata-only copy should preserve a valid checksum sidecar");
|
||||
@@ -17473,7 +17585,7 @@ mod metadata_mutation_generation_tests {
|
||||
conflicting_object,
|
||||
&mut conflicting_source,
|
||||
&ObjectOptions::default(),
|
||||
&ObjectOptions::default(),
|
||||
&dst_opts,
|
||||
)
|
||||
.await
|
||||
.expect_err("metadata-only copy must reject conflicting checksum aliases");
|
||||
@@ -24984,6 +25096,64 @@ mod put_object_tmp_cleanup_tests {
|
||||
wait_for_tmp_workspace_to_drain(&dirs, "cancelled full-tail commit should release staging ownership").await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn background_put_retains_disk_admission_across_owned_commit() {
|
||||
use crate::disk::with_background_disk_io;
|
||||
|
||||
let (_dirs, disks, set) = hermetic_set_disks(4).await;
|
||||
let object = "background-cache-commit";
|
||||
let barriers: Vec<_> = (0..disks.len())
|
||||
.map(|index| rename_fanout_barrier::arm(object, index, rename_fanout_barrier::PHASE_RENAME))
|
||||
.collect();
|
||||
let writer = Arc::clone(&set);
|
||||
let put = tokio::spawn(async move {
|
||||
with_background_disk_io(CancellationToken::new(), async {
|
||||
let mut reader = PutObjReader::from_vec(b"scanner checkpoint".to_vec());
|
||||
writer
|
||||
.put_object(
|
||||
RUSTFS_META_BUCKET,
|
||||
object,
|
||||
&mut reader,
|
||||
&ObjectOptions {
|
||||
write_completion: WriteCompletion::TailDrained,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await
|
||||
});
|
||||
for barrier in &barriers {
|
||||
tokio::time::timeout(Duration::from_secs(30), barrier.wait_until_paused())
|
||||
.await
|
||||
.expect("every disk reaches the commit boundary");
|
||||
}
|
||||
let local_disks: Vec<_> = disks
|
||||
.iter()
|
||||
.map(|disk| match disk.as_ref() {
|
||||
disk::Disk::Local(local) => local,
|
||||
disk::Disk::Remote(_) => panic!("hermetic fixture must use local disks"),
|
||||
})
|
||||
.collect();
|
||||
let before: Vec<_> = local_disks
|
||||
.iter()
|
||||
.map(|disk| disk.background_io_admissions_for_tests())
|
||||
.collect();
|
||||
for barrier in barriers {
|
||||
barrier.release();
|
||||
}
|
||||
put.await.expect("owned put task").expect("background checkpoint commits");
|
||||
for ((disk, local), before) in disks.iter().zip(local_disks).zip(before) {
|
||||
assert!(
|
||||
local.background_io_admissions_for_tests() > before,
|
||||
"the detached rename must retain background admission on every disk"
|
||||
);
|
||||
disk.read_version("", RUSTFS_META_BUCKET, object, "", &ReadOptions::default())
|
||||
.await
|
||||
.expect("committed checkpoint remains readable");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial(capacity_dirty_scope)]
|
||||
async fn borrowed_write_context_rejects_wrong_namespace_and_cache_flag() {
|
||||
@@ -25519,6 +25689,9 @@ mod put_object_tmp_cleanup_tests {
|
||||
&ObjectOptions {
|
||||
no_lock: true,
|
||||
namespace_lock_fence: Some(NamespaceLockFence::lost_for_test()),
|
||||
object_lock_config_snapshot: Some(Arc::new(ObjectLockConfigSnapshot::new(
|
||||
ObjectLockConfigState::ConfirmedAbsent,
|
||||
))),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
@@ -25880,6 +26053,168 @@ mod put_object_tmp_cleanup_tests {
|
||||
.expect("version delete must not be wedged by cleared lock metadata");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn version_only_copy_preserves_quantized_shared_data() {
|
||||
assert_version_only_copy_frame_metadata(true).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial_test::serial]
|
||||
async fn version_only_copy_ignores_injected_frame_markers() {
|
||||
assert_version_only_copy_frame_metadata(false).await;
|
||||
}
|
||||
|
||||
async fn assert_version_only_copy_frame_metadata(quantized: bool) {
|
||||
const BLOCK: usize = 64 * 1024;
|
||||
const FRAME: usize = 16 * 1024;
|
||||
let (_dirs, disks, set) = hermetic_set_disks(4).await;
|
||||
let bucket = "copy-version-frame-metadata";
|
||||
let object = if quantized {
|
||||
"quantized"
|
||||
} else {
|
||||
"legacy-with-injected-marker"
|
||||
};
|
||||
for disk in &disks {
|
||||
disk.make_volume(bucket).await.expect("create version-only copy bucket");
|
||||
}
|
||||
let payload: Vec<u8> = (0..2 * BLOCK + 17)
|
||||
.map(|index| u8::try_from(index % 251).expect("bounded fixture byte"))
|
||||
.collect();
|
||||
let mut put_options = ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
};
|
||||
put_options
|
||||
.user_defined
|
||||
.insert(crate::object_api::EC_BLOCK_SIZE_HINT_INTERNAL_KEY.to_owned(), BLOCK.to_string());
|
||||
let enabled = if quantized { "true" } else { "false" };
|
||||
let source = temp_env::async_with_vars(
|
||||
[
|
||||
(rustfs_config::ENV_EC_READ_QUANTUM_ENABLE, Some(enabled)),
|
||||
(rustfs_config::ENV_EC_READ_QUANTUM_FLEET_CONFIRMED, Some(enabled)),
|
||||
(rustfs_config::ENV_SHARD_INTEGRITY_WRITE, Some("false")),
|
||||
],
|
||||
async {
|
||||
set.put_object(bucket, object, &mut PutObjReader::from_vec(payload.clone()), &put_options)
|
||||
.await
|
||||
.expect("write physical source version")
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let source_version = source.version_id.expect("source version ID").to_string();
|
||||
let source_options = ObjectOptions {
|
||||
version_id: Some(source_version.clone()),
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut source_info = set
|
||||
.get_object_info(bucket, object, &source_options)
|
||||
.await
|
||||
.expect("project source metadata");
|
||||
assert!(!rustfs_utils::http::contains_key_str(
|
||||
&source_info.user_defined,
|
||||
crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX
|
||||
));
|
||||
let mut source_data_dirs = Vec::new();
|
||||
for disk in &disks {
|
||||
let fi = disk
|
||||
.read_version("", bucket, object, &source_version, &crate::disk::ReadOptions::default())
|
||||
.await
|
||||
.expect("read source physical layout");
|
||||
assert!(!fi.inline_data(), "fixture must share real shard files");
|
||||
assert_eq!(fi.erasure.block_size, BLOCK);
|
||||
assert_eq!(
|
||||
crate::object_api::persisted_ec_read_quantum(
|
||||
&fi.metadata,
|
||||
BLOCK,
|
||||
fi.erasure.data_blocks,
|
||||
fi.erasure.shard_size(),
|
||||
)
|
||||
.expect("source frame geometry"),
|
||||
quantized.then_some(FRAME)
|
||||
);
|
||||
source_data_dirs.push(fi.data_dir);
|
||||
}
|
||||
if !quantized {
|
||||
// Replacement metadata cannot change the format of reused bytes.
|
||||
crate::object_api::insert_ec_read_quantum(Arc::make_mut(&mut source_info.user_defined), FRAME);
|
||||
}
|
||||
source_info.version_only = true;
|
||||
let copied = temp_env::async_with_vars(
|
||||
[
|
||||
(rustfs_config::ENV_EC_READ_QUANTUM_ENABLE, Some("false")),
|
||||
(rustfs_config::ENV_EC_READ_QUANTUM_FLEET_CONFIRMED, Some("false")),
|
||||
],
|
||||
async {
|
||||
set.copy_object(
|
||||
bucket,
|
||||
object,
|
||||
bucket,
|
||||
object,
|
||||
&mut source_info,
|
||||
&source_options,
|
||||
&ObjectOptions {
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("version-only copy must commit a new version")
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let copy_version = copied.version_id.expect("copied version ID").to_string();
|
||||
assert_ne!(copy_version, source_version);
|
||||
assert!(!rustfs_utils::http::contains_key_str(
|
||||
&copied.user_defined,
|
||||
crate::object_api::EC_READ_QUANTUM_INFO_INTERNAL_SUFFIX
|
||||
));
|
||||
for version in [&source_version, ©_version] {
|
||||
let mut reader = set
|
||||
.get_object_reader(
|
||||
bucket,
|
||||
object,
|
||||
None,
|
||||
HeaderMap::new(),
|
||||
&ObjectOptions {
|
||||
version_id: Some(version.clone()),
|
||||
versioned: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("source and copied version must open");
|
||||
let mut actual = Vec::new();
|
||||
reader
|
||||
.stream
|
||||
.read_to_end(&mut actual)
|
||||
.await
|
||||
.expect("shared frames must remain readable");
|
||||
assert_eq!(actual, payload);
|
||||
}
|
||||
for (disk, source_data_dir) in disks.iter().zip(source_data_dirs) {
|
||||
let fi = disk
|
||||
.read_version("", bucket, object, ©_version, &crate::disk::ReadOptions::default())
|
||||
.await
|
||||
.expect("read copied version layout");
|
||||
assert_eq!(fi.data_dir, source_data_dir, "version-only copy must reuse source data");
|
||||
assert_eq!(
|
||||
crate::object_api::persisted_ec_read_quantum(
|
||||
&fi.metadata,
|
||||
BLOCK,
|
||||
fi.erasure.data_blocks,
|
||||
fi.erasure.shard_size(),
|
||||
)
|
||||
.expect("copied frame geometry"),
|
||||
quantized.then_some(FRAME)
|
||||
);
|
||||
for key in ["x-rustfs-internal-ec-read-quantum", "x-minio-internal-ec-read-quantum"] {
|
||||
assert_eq!(fi.metadata.get(key).map(String::as_str), quantized.then_some("16384"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn version_only_copy_checks_the_destination_version_object_lock() {
|
||||
let (_temp_dirs, disk_stores, set_disks) = hermetic_set_disks(4).await;
|
||||
|
||||
@@ -17,11 +17,11 @@ use super::{
|
||||
GetObjectFileInfo, GetObjectMetadataCacheCapability, GetObjectMetadataCacheEntry, GetObjectMetadataCacheGeneration,
|
||||
GetObjectMetadataCacheKey, GetObjectMetadataCacheLookupKey, GetObjectReadPolicy, HashAlgorithm, LOG_COMPONENT_ECSTORE,
|
||||
LOG_SUBSYSTEM_SET_DISK, OBJECT_OP_IGNORED_ERRS, ObjectInfo, ObjectOptions, RUSTFS_META_BUCKET, ReadOptions, Result, SetDisks,
|
||||
StorageError, adaptive_duplex_buffer_size, build_get_codec_streaming_decode_engine, build_inline_bitrot_readers,
|
||||
collect_inline_data_shard_fileinfos_by_index, debug, error, get_codec_streaming_metrics_path,
|
||||
get_codec_streaming_multipart_max_parts, get_object_read_policy, is_codec_streaming_multipart_enabled,
|
||||
is_multipart_reader_setup_prefetch_enabled, object_fits_single_block, part_checksum_algorithm, reduce_read_quorum_errs,
|
||||
to_object_err, try_read_inline_data_shards_direct, warn,
|
||||
StorageError, adaptive_duplex_buffer_size, build_get_codec_streaming_decode_engine,
|
||||
build_inline_bitrot_readers_from_refs_with_frame_size, collect_inline_data_shard_fileinfos_by_index, debug, error,
|
||||
get_codec_streaming_metrics_path, get_codec_streaming_multipart_max_parts, get_object_read_policy,
|
||||
is_codec_streaming_multipart_enabled, is_multipart_reader_setup_prefetch_enabled, object_fits_single_block,
|
||||
part_checksum_algorithm, reduce_read_quorum_errs, to_object_err, try_read_inline_data_shards_direct, warn,
|
||||
};
|
||||
use crate::diagnostics::get::{
|
||||
GET_DIRECT_MEMORY_SUBPATH_DISK_DATA_BLOCKS, GET_DIRECT_MEMORY_SUBPATH_INLINE_BUFFERED, GET_METADATA_CACHE_DECISION_HIT,
|
||||
@@ -148,16 +148,17 @@ use super::core::io_primitives::{
|
||||
BitrotReaderSetup, BitrotReaderSetupAttribution, BitrotReaderSetupMode, DeferredReaderReopener, EVENT_SET_DISK_READ,
|
||||
GetCodecStreamingReaderBuildOutcome, MetadataCacheLookup, ObjectBitrotReader, ReadRepairAdmissionSubmitter,
|
||||
ReadRepairHealSubmission, SLOW_OBJECT_READ_LOG_THRESHOLD, codec_streaming_reader_setup_fallback_reason,
|
||||
create_bitrot_readers_until_quorum_with_preference, create_data_block_bitrot_readers, resolved_read_repair_version_id,
|
||||
send_read_repair_heal_request, shard_read_costs_for_disks, submit_read_repair_heal, submit_read_repair_heal_with_submitter,
|
||||
create_bitrot_readers_until_quorum_with_preference_and_frame_size, create_data_block_bitrot_readers_with_frame_size,
|
||||
resolved_read_repair_version_id, send_read_repair_heal_request, shard_read_costs_for_disks, submit_read_repair_heal,
|
||||
submit_read_repair_heal_with_submitter,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use super::core::io_primitives::{
|
||||
ENV_RUSTFS_GET_CODEC_STREAMING_DATA_BLOCKS_FIRST_READER_SETUP, ENV_RUSTFS_GET_DATA_BLOCKS_FIRST_READER_SETUP,
|
||||
MultipartCodecStreamingReader, ReadRepairAdmissionFuture, ReadRepairAdmissionOutcome, collect_read_multiple_results,
|
||||
collect_read_parts_results, create_bitrot_readers_until_quorum, create_bitrot_readers_until_quorum_all_shards,
|
||||
release_read_repair_heal_reservation, reserve_read_repair_heal, resolve_read_part_from_responses, shard_read_cost_for_disk,
|
||||
shard_read_cost_for_endpoint,
|
||||
create_bitrot_readers_until_quorum_with_preference, release_read_repair_heal_reservation, reserve_read_repair_heal,
|
||||
resolve_read_part_from_responses, shard_read_cost_for_disk, shard_read_cost_for_endpoint,
|
||||
};
|
||||
#[cfg(test)]
|
||||
use super::core::metadata_quorum::{MetadataEarlyStopDecision, MetadataQuorumAccumulator};
|
||||
@@ -1475,6 +1476,7 @@ impl SetDisks {
|
||||
}
|
||||
|
||||
let erasure = erasure_cache.get_for_file_info(fi)?;
|
||||
let frame_size = read_frame_size_for_file_info(fi, &erasure)?;
|
||||
|
||||
let checksum_algo = part_checksum_algorithm(fi, part.number);
|
||||
let read_length = erasure.shard_file_offset(0, object_size, object_size);
|
||||
@@ -1491,13 +1493,13 @@ impl SetDisks {
|
||||
};
|
||||
|
||||
let reader_setup_stage_start = Instant::now();
|
||||
let mut readers = build_inline_bitrot_readers(
|
||||
data_files.iter().copied(),
|
||||
data_files.len(),
|
||||
let mut readers = build_inline_bitrot_readers_from_refs_with_frame_size(
|
||||
&data_files,
|
||||
bucket,
|
||||
object,
|
||||
read_length,
|
||||
erasure.shard_size(),
|
||||
frame_size,
|
||||
&checksum_algo,
|
||||
skip_verify_bitrot,
|
||||
)
|
||||
@@ -1550,7 +1552,7 @@ impl SetDisks {
|
||||
let use_mmap_read = object_mmap_read_enabled();
|
||||
|
||||
let reader_setup_stage_start = Instant::now();
|
||||
let mut reader_setup = create_data_block_bitrot_readers(
|
||||
let mut reader_setup = create_data_block_bitrot_readers_with_frame_size(
|
||||
&files,
|
||||
&disks,
|
||||
bucket,
|
||||
@@ -1559,6 +1561,7 @@ impl SetDisks {
|
||||
0,
|
||||
read_length,
|
||||
erasure.shard_size(),
|
||||
frame_size,
|
||||
checksum_algo,
|
||||
skip_verify_bitrot,
|
||||
use_mmap_read,
|
||||
@@ -1710,6 +1713,7 @@ impl SetDisks {
|
||||
);
|
||||
|
||||
let erasure = erasure_cache.get_for_file_info(&fi)?;
|
||||
let frame_size = read_frame_size_for_file_info(&fi, &erasure)?;
|
||||
|
||||
let part_indices: Vec<usize> = (part_index..=last_part_index).collect();
|
||||
debug!(bucket, object, ?part_indices, "Multipart part indices to stream");
|
||||
@@ -1722,6 +1726,39 @@ impl SetDisks {
|
||||
let use_mmap_read = object_mmap_read_enabled();
|
||||
let files = Arc::new(files);
|
||||
let disks = Arc::new(disks);
|
||||
|
||||
// A small Range GET only needs the authenticated q-aligned slice that
|
||||
// contains each requested data-shard segment. Permit one complete
|
||||
// logical block as well as a single physical shard: the 64 KiB layout
|
||||
// has 32 KiB shards, so a normal 64 KiB range otherwise bypasses the
|
||||
// bounded reader and reopens parity on the legacy path.
|
||||
if frame_size != erasure.shard_size() && length > 0 && length <= erasure.block_size {
|
||||
return Self::read_quantized_range(
|
||||
bucket,
|
||||
object,
|
||||
writer,
|
||||
&fi,
|
||||
files.as_ref(),
|
||||
disks.as_ref(),
|
||||
&erasure,
|
||||
frame_size,
|
||||
length,
|
||||
part_index,
|
||||
last_part_index,
|
||||
part_offset,
|
||||
skip_verify_bitrot,
|
||||
suppress_read_repair,
|
||||
prefer_data_blocks_first_reader_setup,
|
||||
require_reconstruction_surplus,
|
||||
pool_index,
|
||||
set_index,
|
||||
metrics_path,
|
||||
metrics_object_class,
|
||||
metrics_size_bucket,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let prefetch_enabled = multipart_reader_setup_prefetch_enabled(get_object_read_policy());
|
||||
let mut prefetched: Option<(usize, PrefetchedReaderSetup)> = None;
|
||||
|
||||
@@ -1774,6 +1811,7 @@ impl SetDisks {
|
||||
part_number,
|
||||
read_offset,
|
||||
read_length,
|
||||
frame_size,
|
||||
checksum_algo,
|
||||
};
|
||||
let mut setup_result = None;
|
||||
@@ -1829,6 +1867,7 @@ impl SetDisks {
|
||||
part_number: next_number,
|
||||
read_offset: 0,
|
||||
read_length: erasure.shard_file_offset(0, next_length, next_size),
|
||||
frame_size,
|
||||
checksum_algo: part_checksum_algorithm(&fi, next_number),
|
||||
};
|
||||
let files = Arc::clone(&files);
|
||||
@@ -2011,7 +2050,9 @@ impl SetDisks {
|
||||
error: err,
|
||||
exact_quorum,
|
||||
repair,
|
||||
..
|
||||
} = erasure
|
||||
.clone()
|
||||
.decode_with_stripe_handles_and_reopeners_with_diagnostics(
|
||||
writer,
|
||||
readers,
|
||||
@@ -2147,6 +2188,284 @@ impl SetDisks {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
/// Read a small q-enabled range one data-shard segment at a time. Each setup
|
||||
/// opens the same q-aligned logical slice on every shard, so Reed-Solomon sees
|
||||
/// equal-length vectors while the caller receives only the requested bytes.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn read_quantized_range<W>(
|
||||
bucket: &str,
|
||||
object: &str,
|
||||
writer: &mut W,
|
||||
fi: &FileInfo,
|
||||
files: &[FileInfo],
|
||||
disks: &[Option<DiskStore>],
|
||||
erasure: &coding::Erasure,
|
||||
frame_size: usize,
|
||||
length: usize,
|
||||
part_index: usize,
|
||||
last_part_index: usize,
|
||||
mut part_offset: usize,
|
||||
skip_verify_bitrot: bool,
|
||||
suppress_read_repair: bool,
|
||||
prefer_data_blocks_first_reader_setup: bool,
|
||||
require_reconstruction_surplus: bool,
|
||||
pool_index: usize,
|
||||
set_index: usize,
|
||||
metrics_path: &'static str,
|
||||
metrics_object_class: &'static str,
|
||||
metrics_size_bucket: &'static str,
|
||||
) -> Result<()>
|
||||
where
|
||||
W: AsyncWrite + Send + Sync + Unpin + 'static,
|
||||
{
|
||||
let logical_shard_size = erasure.shard_size();
|
||||
if frame_size == 0
|
||||
|| logical_shard_size == 0
|
||||
|| erasure.block_size == 0
|
||||
|| erasure.data_shards == 0
|
||||
|| !logical_shard_size.is_multiple_of(frame_size)
|
||||
{
|
||||
return Err(Error::other("invalid EC read quantum geometry"));
|
||||
}
|
||||
|
||||
let use_mmap_read = object_mmap_read_enabled();
|
||||
let quantum_label = quantized_range_quantum_label(frame_size);
|
||||
rustfs_io_metrics::record_get_object_quantized_range_request(
|
||||
metrics_path,
|
||||
metrics_object_class,
|
||||
metrics_size_bucket,
|
||||
quantum_label,
|
||||
u64::try_from(length).unwrap_or(u64::MAX),
|
||||
);
|
||||
let mut total_read = 0usize;
|
||||
for current_part in part_index..=last_part_index {
|
||||
if total_read == length {
|
||||
break;
|
||||
}
|
||||
|
||||
let part_number = fi.parts[current_part].number;
|
||||
let part_size = fi.parts[current_part].size;
|
||||
let part_remaining = quantized_part_remaining(part_size, part_offset)?;
|
||||
let part_length = part_remaining.min(length - total_read);
|
||||
let mut segment_offset = part_offset;
|
||||
let mut segment_remaining = part_length;
|
||||
|
||||
while segment_remaining > 0 {
|
||||
rustfs_io_metrics::record_get_object_quantized_range_segment(
|
||||
metrics_path,
|
||||
metrics_object_class,
|
||||
metrics_size_bucket,
|
||||
quantum_label,
|
||||
);
|
||||
let block_index = segment_offset / erasure.block_size;
|
||||
let within_block = segment_offset % erasure.block_size;
|
||||
let block_data_start = block_index
|
||||
.checked_mul(erasure.block_size)
|
||||
.ok_or_else(|| Error::other("EC read quantum block offset overflows"))?;
|
||||
if block_data_start >= part_size {
|
||||
return Err(Error::other("EC read quantum block offset exceeds part size"));
|
||||
}
|
||||
let block_data_len = (part_size - block_data_start).min(erasure.block_size);
|
||||
let block_shard_size = coding::calc_shard_size(block_data_len, erasure.data_shards);
|
||||
if block_shard_size == 0 {
|
||||
return Err(Error::other("EC read quantum block has zero shard length"));
|
||||
}
|
||||
let shard_index = within_block / block_shard_size;
|
||||
if shard_index >= erasure.data_shards {
|
||||
return Err(Error::other("EC read quantum data shard index is out of range"));
|
||||
}
|
||||
let within_shard = within_block % block_shard_size;
|
||||
let block_remaining = erasure.block_size - within_block;
|
||||
if within_shard >= block_shard_size {
|
||||
return Err(Error::other("EC read quantum shard offset exceeds encoded block"));
|
||||
}
|
||||
let shard_remaining = block_shard_size - within_shard;
|
||||
let block_data_remaining = block_data_len - within_block;
|
||||
let block_segment_length = segment_remaining.min(block_data_remaining);
|
||||
let read_full_block = shard_index == 0 && within_shard < frame_size && block_segment_length > shard_remaining;
|
||||
let (segment_length, read_shard_size, read_offset, output_offset) = if read_full_block {
|
||||
// A range that begins in the first q-frame of shard 0 and
|
||||
// crosses into shard 1 already requires all frames of
|
||||
// shard 0. Group its data-shard segments into one decode so
|
||||
// we do not reopen the block's shards a second time.
|
||||
let read_offset = block_index
|
||||
.checked_mul(logical_shard_size)
|
||||
.ok_or_else(|| Error::other("EC read quantum offset overflows"))?;
|
||||
(block_segment_length, block_shard_size, read_offset, within_block)
|
||||
} else {
|
||||
let segment_length = segment_remaining.min(block_remaining).min(shard_remaining);
|
||||
if segment_length == 0 {
|
||||
return Err(Error::other("EC read quantum segment is empty"));
|
||||
}
|
||||
|
||||
let q_base = (within_shard / frame_size) * frame_size;
|
||||
let relative_offset = within_shard - q_base;
|
||||
let covered = relative_offset
|
||||
.checked_add(segment_length)
|
||||
.ok_or_else(|| Error::other("EC read quantum segment overflows"))?;
|
||||
let frame_count = covered.div_ceil(frame_size);
|
||||
let frame_aligned_size = frame_count
|
||||
.checked_mul(frame_size)
|
||||
.ok_or_else(|| Error::other("EC read quantum frame size overflows"))?;
|
||||
let read_shard_size = frame_aligned_size.min(block_shard_size - q_base);
|
||||
let read_offset = block_index
|
||||
.checked_mul(logical_shard_size)
|
||||
.and_then(|base| base.checked_add(q_base))
|
||||
.ok_or_else(|| Error::other("EC read quantum offset overflows"))?;
|
||||
let output_offset = shard_index
|
||||
.checked_mul(read_shard_size)
|
||||
.and_then(|base| base.checked_add(relative_offset))
|
||||
.ok_or_else(|| Error::other("EC read quantum output offset overflows"))?;
|
||||
(segment_length, read_shard_size, read_offset, output_offset)
|
||||
};
|
||||
|
||||
let spec = PartReaderSetupSpec {
|
||||
integrity: fi.parts[current_part].integrity.clone(),
|
||||
part_number,
|
||||
read_offset,
|
||||
read_length: read_shard_size,
|
||||
frame_size,
|
||||
checksum_algo: part_checksum_algorithm(fi, part_number),
|
||||
};
|
||||
let (reader_setup, reader_setup_elapsed) = setup_multipart_part_readers(
|
||||
files,
|
||||
disks,
|
||||
bucket,
|
||||
object,
|
||||
spec,
|
||||
logical_shard_size,
|
||||
erasure.data_shards,
|
||||
erasure.parity_shards,
|
||||
skip_verify_bitrot,
|
||||
use_mmap_read,
|
||||
prefer_data_blocks_first_reader_setup,
|
||||
metrics_path,
|
||||
metrics_object_class,
|
||||
metrics_size_bucket,
|
||||
)
|
||||
.await;
|
||||
rustfs_io_metrics::record_get_object_quantized_range_reader_setup(
|
||||
metrics_path,
|
||||
metrics_object_class,
|
||||
metrics_size_bucket,
|
||||
quantum_label,
|
||||
);
|
||||
rustfs_io_metrics::record_get_object_shard_reader_setup_duration(reader_setup_elapsed.as_secs_f64());
|
||||
rustfs_io_metrics::record_get_object_stage_duration_by_size(
|
||||
metrics_path,
|
||||
GET_STAGE_READER_SETUP,
|
||||
metrics_object_class,
|
||||
metrics_size_bucket,
|
||||
reader_setup_elapsed.as_secs_f64(),
|
||||
);
|
||||
|
||||
let available_shards = reader_setup.available_shards();
|
||||
if available_shards < erasure.data_shards {
|
||||
return Err(DiskError::ErasureReadQuorum.into());
|
||||
}
|
||||
|
||||
let quorum_window_bytes = read_shard_size
|
||||
.saturating_mul(available_shards)
|
||||
.try_into()
|
||||
.unwrap_or(u64::MAX);
|
||||
rustfs_io_metrics::record_get_object_quantized_range_quorum_window_bytes(
|
||||
metrics_path,
|
||||
metrics_object_class,
|
||||
metrics_size_bucket,
|
||||
quantum_label,
|
||||
quorum_window_bytes,
|
||||
);
|
||||
|
||||
let missing_shards = reader_setup.completed_failed_shards();
|
||||
if !suppress_read_repair && missing_shards > 0 && available_shards >= erasure.data_shards {
|
||||
let version_id = fi.version_id.as_ref().map(ToString::to_string);
|
||||
submit_read_repair_heal(
|
||||
bucket,
|
||||
object,
|
||||
version_id.as_deref(),
|
||||
pool_index,
|
||||
set_index,
|
||||
Some(part_number),
|
||||
"missing_shards",
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let unattempted_data_shards = !reader_setup.data_shards_attempted(erasure.data_shards);
|
||||
let read_costs = coding::decode::should_collect_shard_read_costs().then(|| shard_read_costs_for_disks(disks));
|
||||
let readers = reader_setup.readers;
|
||||
let deferred_stripe_handles = reader_setup.deferred_stripe_handles;
|
||||
let deferred_reopeners = reader_setup.deferred_reopeners;
|
||||
let outcome = erasure
|
||||
.clone()
|
||||
.decode_quantized_range_with_stripe_handles_and_reopeners(
|
||||
writer,
|
||||
readers,
|
||||
output_offset,
|
||||
segment_length,
|
||||
read_shard_size,
|
||||
read_costs,
|
||||
deferred_stripe_handles,
|
||||
deferred_reopeners,
|
||||
!skip_verify_bitrot
|
||||
&& !require_reconstruction_surplus
|
||||
&& part_checksum_algorithm(fi, part_number).size() > 0,
|
||||
)
|
||||
.await;
|
||||
rustfs_io_metrics::record_get_object_quantized_range_frames(
|
||||
metrics_path,
|
||||
metrics_object_class,
|
||||
metrics_size_bucket,
|
||||
quantum_label,
|
||||
u64::try_from(outcome.frame_count).unwrap_or(u64::MAX),
|
||||
);
|
||||
rustfs_io_metrics::record_get_object_quantized_range_read_dispatches(
|
||||
metrics_path,
|
||||
metrics_object_class,
|
||||
metrics_size_bucket,
|
||||
quantum_label,
|
||||
u64::try_from(outcome.read_dispatch_count).unwrap_or(u64::MAX),
|
||||
);
|
||||
let mut repair_needed = outcome.repair.needed(!unattempted_data_shards);
|
||||
if require_reconstruction_surplus && outcome.exact_quorum && outcome.error.is_none() {
|
||||
return Err(Error::other("two-phase read completed with exact reconstruction quorum"));
|
||||
}
|
||||
if let Some(error) = outcome.error {
|
||||
let disk_error: DiskError = error.into();
|
||||
let mut has_error = true;
|
||||
if outcome.written == segment_length {
|
||||
let should_enqueue_heal = matches!(disk_error, DiskError::FileCorrupt)
|
||||
|| (matches!(disk_error, DiskError::FileNotFound) && !unattempted_data_shards);
|
||||
if should_enqueue_heal {
|
||||
repair_needed = true;
|
||||
has_error = false;
|
||||
}
|
||||
}
|
||||
if has_error {
|
||||
return Err(disk_error.into());
|
||||
}
|
||||
}
|
||||
if outcome.written != segment_length {
|
||||
return Err(Error::other("quantized range returned fewer bytes than requested"));
|
||||
}
|
||||
if !suppress_read_repair && repair_needed {
|
||||
DecodeReadRepairContext::new(bucket, object, fi.version_id, pool_index, set_index, part_number, false)
|
||||
.submit()
|
||||
.await;
|
||||
}
|
||||
|
||||
total_read += segment_length;
|
||||
segment_offset += segment_length;
|
||||
segment_remaining -= segment_length;
|
||||
}
|
||||
part_offset = 0;
|
||||
}
|
||||
|
||||
if total_read != length {
|
||||
return Err(StorageError::LessData);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[hotpath::measure(impl_type = "SetDisks")]
|
||||
@@ -2426,6 +2745,7 @@ impl SetDisks {
|
||||
if part_length > part_size {
|
||||
return Err(Error::other("codec streaming reader part length exceeds part size"));
|
||||
}
|
||||
let frame_size = read_frame_size_for_file_info(fi, erasure)?;
|
||||
let checksum_algo = part_checksum_algorithm(fi, part_number);
|
||||
let use_mmap_read = object_mmap_read_enabled();
|
||||
let till_offset = erasure.shard_file_offset(part_offset, part_length, part_size);
|
||||
@@ -2441,7 +2761,7 @@ impl SetDisks {
|
||||
});
|
||||
let reader_setup_stage_start = get_stage_timer_if_enabled(stage_metrics_enabled);
|
||||
let read_costs = coding::decode::should_collect_shard_read_costs().then(|| shard_read_costs_for_disks(disks));
|
||||
let mut reader_setup = create_bitrot_readers_until_quorum_with_preference(
|
||||
let mut reader_setup = create_bitrot_readers_until_quorum_with_preference_and_frame_size(
|
||||
files,
|
||||
disks,
|
||||
bucket,
|
||||
@@ -2450,6 +2770,7 @@ impl SetDisks {
|
||||
read_offset,
|
||||
read_length,
|
||||
erasure.shard_size(),
|
||||
frame_size,
|
||||
checksum_algo,
|
||||
skip_verify_bitrot,
|
||||
use_mmap_read,
|
||||
@@ -2712,9 +3033,59 @@ struct PartReaderSetupSpec {
|
||||
part_number: usize,
|
||||
read_offset: usize,
|
||||
read_length: usize,
|
||||
frame_size: usize,
|
||||
checksum_algo: HashAlgorithm,
|
||||
}
|
||||
|
||||
/// Resolve the physical authenticated frame size for a persisted object while
|
||||
/// keeping the original EC layout geometry for offsets and reconstruction.
|
||||
pub(in crate::set_disk) fn read_frame_size_for_file_info(fi: &FileInfo, erasure: &coding::Erasure) -> Result<usize> {
|
||||
let Some(quantum) =
|
||||
crate::object_api::persisted_ec_read_quantum(&fi.metadata, erasure.block_size, erasure.data_shards, erasure.shard_size())
|
||||
.map_err(|error| Error::other(error.to_string()))?
|
||||
else {
|
||||
return Ok(erasure.shard_size());
|
||||
};
|
||||
|
||||
if erasure.uses_legacy_codec() {
|
||||
return Err(Error::other("EC read quantum marker is unsupported for legacy erasure objects"));
|
||||
}
|
||||
if fi.parts.iter().any(|part| part.integrity.is_some()) {
|
||||
return Err(Error::other("EC read quantum marker cannot be combined with protected shard integrity"));
|
||||
}
|
||||
Ok(quantum)
|
||||
}
|
||||
|
||||
fn quantized_range_quantum_label(frame_size: usize) -> &'static str {
|
||||
const Q_4KIB: usize = 4 * 1024;
|
||||
const Q_8KIB: usize = 8 * 1024;
|
||||
const Q_16KIB: usize = 16 * 1024;
|
||||
const Q_32KIB: usize = 32 * 1024;
|
||||
const Q_64KIB: usize = 64 * 1024;
|
||||
const Q_128KIB: usize = 128 * 1024;
|
||||
const Q_256KIB: usize = 256 * 1024;
|
||||
const Q_512KIB: usize = 512 * 1024;
|
||||
const Q_1MIB: usize = 1024 * 1024;
|
||||
match frame_size {
|
||||
Q_4KIB => "4kib",
|
||||
Q_8KIB => "8kib",
|
||||
Q_16KIB => "16kib",
|
||||
Q_32KIB => "32kib",
|
||||
Q_64KIB => "64kib",
|
||||
Q_128KIB => "128kib",
|
||||
Q_256KIB => "256kib",
|
||||
Q_512KIB => "512kib",
|
||||
Q_1MIB => "1mib",
|
||||
_ => "other",
|
||||
}
|
||||
}
|
||||
|
||||
fn quantized_part_remaining(part_size: usize, part_offset: usize) -> Result<usize> {
|
||||
part_size
|
||||
.checked_sub(part_offset)
|
||||
.ok_or_else(|| Error::other("EC read quantum part offset exceeds part size"))
|
||||
}
|
||||
|
||||
fn multipart_reader_setup_prefetch_enabled(policy: GetObjectReadPolicy) -> bool {
|
||||
policy.allows_multipart_setup_prefetch() && is_multipart_reader_setup_prefetch_enabled()
|
||||
}
|
||||
@@ -2840,7 +3211,7 @@ async fn setup_multipart_part_readers(
|
||||
metrics_size_bucket: &'static str,
|
||||
) -> (BitrotReaderSetup, Duration) {
|
||||
let started = Instant::now();
|
||||
let mut setup = create_bitrot_readers_until_quorum_with_preference(
|
||||
let mut setup = create_bitrot_readers_until_quorum_with_preference_and_frame_size(
|
||||
files,
|
||||
disks,
|
||||
bucket,
|
||||
@@ -2849,6 +3220,7 @@ async fn setup_multipart_part_readers(
|
||||
spec.read_offset,
|
||||
spec.read_length,
|
||||
shard_size,
|
||||
spec.frame_size,
|
||||
spec.checksum_algo,
|
||||
skip_verify_bitrot,
|
||||
use_mmap_read,
|
||||
@@ -6292,6 +6664,54 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quantized_part_remaining_rejects_offsets_past_part_end() {
|
||||
assert_eq!(quantized_part_remaining(1024, 768).expect("valid part offset"), 256);
|
||||
assert!(quantized_part_remaining(1024, 1025).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quantized_range_preserves_typed_quorum_and_short_read_errors() {
|
||||
let erasure = coding::Erasure::new(2, 2, 64 * 1024);
|
||||
let disks = vec![None; erasure.total_shard_count()];
|
||||
for (part_size, expected) in [(1, StorageError::ErasureReadQuorum), (0, StorageError::LessData)] {
|
||||
let mut fi = FileInfo::new(CODEC_STREAMING_TEST_OBJECT, 2, 2);
|
||||
fi.size = 1;
|
||||
fi.erasure.block_size = erasure.block_size;
|
||||
fi.erasure.distribution = (1..=erasure.total_shard_count()).collect();
|
||||
fi.add_object_part(1, "fixture-etag".to_string(), part_size, None, 1, None, None);
|
||||
let files = vec![fi.clone(); erasure.total_shard_count()];
|
||||
let mut output = Vec::new();
|
||||
let error = SetDisks::read_quantized_range(
|
||||
CODEC_STREAMING_TEST_BUCKET,
|
||||
CODEC_STREAMING_TEST_OBJECT,
|
||||
&mut output,
|
||||
&fi,
|
||||
&files,
|
||||
&disks,
|
||||
&erasure,
|
||||
16 * 1024,
|
||||
1,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
0,
|
||||
0,
|
||||
GET_OBJECT_PATH_SET_DISK,
|
||||
"plain",
|
||||
"small",
|
||||
)
|
||||
.await
|
||||
.expect_err("unreadable quantized range must fail");
|
||||
assert_eq!(error, expected);
|
||||
assert!(output.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_read_repair_submitter(
|
||||
_request: rustfs_heal_contracts::heal_channel::HealChannelRequest,
|
||||
) -> ReadRepairAdmissionFuture {
|
||||
@@ -6402,6 +6822,227 @@ mod tests {
|
||||
(dirs, disks)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn quantized_range_preserves_frame_shard_block_and_odd_tail_boundaries() {
|
||||
const BLOCK_SIZE: usize = 64 * 1024;
|
||||
const FRAME_SIZE: usize = 16 * 1024;
|
||||
const TAIL_SIZE: usize = 17_409;
|
||||
let payload: Vec<u8> = (0..BLOCK_SIZE + TAIL_SIZE)
|
||||
.map(|index| u8::try_from(index % 251).expect("fixture byte fits u8"))
|
||||
.collect();
|
||||
let erasure = coding::Erasure::new(2, 2, BLOCK_SIZE);
|
||||
let mut encoded = vec![Vec::new(); erasure.total_shard_count()];
|
||||
for block in payload.chunks(BLOCK_SIZE) {
|
||||
for (index, shard) in erasure
|
||||
.encode_data(block)
|
||||
.expect("fixture block encodes")
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let mut writer = BitrotWriter::new(Vec::new(), FRAME_SIZE, HashAlgorithm::HighwayHash256S);
|
||||
for frame in shard.chunks(FRAME_SIZE) {
|
||||
writer.write(frame).await.expect("fixture frame writes");
|
||||
}
|
||||
encoded[index].extend(writer.into_inner());
|
||||
}
|
||||
}
|
||||
let mut fi = FileInfo::new(CODEC_STREAMING_TEST_OBJECT, 2, 2);
|
||||
fi.volume = CODEC_STREAMING_TEST_BUCKET.to_string();
|
||||
fi.size = i64::try_from(payload.len()).expect("fixture size fits i64");
|
||||
fi.erasure.block_size = BLOCK_SIZE;
|
||||
fi.erasure.distribution = (1..=erasure.total_shard_count()).collect();
|
||||
crate::object_api::insert_ec_read_quantum(&mut fi.metadata, FRAME_SIZE);
|
||||
fi.add_object_part(1, "fixture-etag".to_string(), payload.len(), None, fi.size, None, None);
|
||||
let files: Vec<FileInfo> = encoded
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, bytes)| {
|
||||
let mut file = fi.clone();
|
||||
file.erasure.index = index + 1;
|
||||
file.data = Some(Bytes::copy_from_slice(bytes));
|
||||
file
|
||||
})
|
||||
.collect();
|
||||
let (_dirs, disks) = local_test_disks(erasure.total_shard_count(), CODEC_STREAMING_TEST_BUCKET).await;
|
||||
|
||||
for damage in ["healthy", "corrupt-tail", "missing-data"] {
|
||||
let mut files = files.clone();
|
||||
let mut disks = disks.clone();
|
||||
if damage == "corrupt-tail" {
|
||||
let mut bytes = files[0].data.take().expect("tail shard fixture").to_vec();
|
||||
*bytes.last_mut().expect("odd tail byte") ^= 0x80;
|
||||
files[0].data = Some(Bytes::from(bytes));
|
||||
} else if damage == "missing-data" {
|
||||
disks[0] = None;
|
||||
}
|
||||
for (offset, length) in [
|
||||
(3, 29),
|
||||
(FRAME_SIZE - 3, 9),
|
||||
(erasure.shard_size() - 3, 9),
|
||||
(BLOCK_SIZE - 3, 9),
|
||||
(BLOCK_SIZE + TAIL_SIZE.div_ceil(2) - 3, 9),
|
||||
(BLOCK_SIZE, TAIL_SIZE),
|
||||
(payload.len() - 7, 7),
|
||||
(0, payload.len()),
|
||||
] {
|
||||
let mut output = Vec::new();
|
||||
SetDisks::get_object_with_fileinfo(
|
||||
CODEC_STREAMING_TEST_BUCKET,
|
||||
CODEC_STREAMING_TEST_OBJECT,
|
||||
Arc::new(ErasureCache::new()),
|
||||
offset,
|
||||
i64::try_from(length).expect("range length fits i64"),
|
||||
&mut output,
|
||||
fi.clone(),
|
||||
files.clone(),
|
||||
&disks,
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
GET_OBJECT_PATH_SET_DISK,
|
||||
"plain",
|
||||
"small",
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("{damage}, offset={offset}, length={length}: range must recover: {error}"));
|
||||
assert_eq!(
|
||||
output,
|
||||
payload[offset..offset + length],
|
||||
"{damage}, offset={offset}, length={length}: frame/shard/block/tail order must stay exact"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn quantized_range_direct_memory_and_cross_shard_header_offset_coalesce() {
|
||||
const BLOCK_SIZE: usize = 64 * 1024;
|
||||
const FRAME_SIZE: usize = 16 * 1024;
|
||||
let payload: Vec<u8> = (0..BLOCK_SIZE)
|
||||
.map(|index| u8::try_from(index % 251).expect("fixture byte fits u8"))
|
||||
.collect();
|
||||
let erasure = coding::Erasure::new(2, 2, BLOCK_SIZE);
|
||||
let mut encoded = vec![Vec::new(); erasure.total_shard_count()];
|
||||
for (index, shard) in erasure
|
||||
.encode_data(&payload)
|
||||
.expect("fixture block encodes")
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let mut writer = BitrotWriter::new(Vec::new(), FRAME_SIZE, HashAlgorithm::HighwayHash256S);
|
||||
for frame in shard.chunks(FRAME_SIZE) {
|
||||
writer.write(frame).await.expect("fixture frame writes");
|
||||
}
|
||||
encoded[index].extend(writer.into_inner());
|
||||
}
|
||||
|
||||
let mut fi = FileInfo::new(CODEC_STREAMING_TEST_OBJECT, 2, 2);
|
||||
fi.volume = CODEC_STREAMING_TEST_BUCKET.to_string();
|
||||
fi.name = CODEC_STREAMING_TEST_OBJECT.to_string();
|
||||
fi.size = i64::try_from(payload.len()).expect("fixture size fits i64");
|
||||
fi.is_latest = true;
|
||||
fi.version_id = Some(Uuid::nil());
|
||||
fi.data_dir = Some(Uuid::nil());
|
||||
fi.mod_time = Some(time::OffsetDateTime::UNIX_EPOCH);
|
||||
fi.metadata.insert("etag".to_string(), "fixture-etag".to_string());
|
||||
fi.erasure.block_size = BLOCK_SIZE;
|
||||
fi.erasure.distribution = (1..=erasure.total_shard_count()).collect();
|
||||
crate::object_api::insert_ec_read_quantum(&mut fi.metadata, FRAME_SIZE);
|
||||
fi.add_object_part(1, "fixture-etag".to_string(), payload.len(), fi.mod_time, fi.size, None, None);
|
||||
fi.set_inline_data();
|
||||
|
||||
let files: Vec<FileInfo> = encoded
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, bytes)| {
|
||||
let mut file = fi.clone();
|
||||
file.erasure.index = index + 1;
|
||||
file.data = Some(Bytes::copy_from_slice(bytes));
|
||||
file
|
||||
})
|
||||
.collect();
|
||||
let head_fi = files[0].clone();
|
||||
let (_dirs, disks) = local_test_disks(erasure.total_shard_count(), CODEC_STREAMING_TEST_BUCKET).await;
|
||||
|
||||
let body = SetDisks::try_get_object_direct_data_shards_with_fileinfo(
|
||||
CODEC_STREAMING_TEST_BUCKET,
|
||||
CODEC_STREAMING_TEST_OBJECT,
|
||||
Arc::new(ErasureCache::new()),
|
||||
&head_fi,
|
||||
&files,
|
||||
&disks,
|
||||
false,
|
||||
"plain",
|
||||
"small",
|
||||
)
|
||||
.await
|
||||
.expect("bounded-quantum direct-memory read should not error")
|
||||
.expect("healthy bounded-quantum single-block object should use direct-memory fast path");
|
||||
assert_eq!(body.as_ref(), payload.as_slice());
|
||||
|
||||
let mut corrupted_files = files.clone();
|
||||
let mut shard0 = corrupted_files[0].data.take().expect("shard 0 fixture").to_vec();
|
||||
*shard0.last_mut().expect("second frame byte") ^= 0x80;
|
||||
corrupted_files[0].data = Some(Bytes::from(shard0));
|
||||
let corrupted_head = corrupted_files[0].clone();
|
||||
let fallback = SetDisks::try_get_object_direct_data_shards_with_fileinfo(
|
||||
CODEC_STREAMING_TEST_BUCKET,
|
||||
CODEC_STREAMING_TEST_OBJECT,
|
||||
Arc::new(ErasureCache::new()),
|
||||
&corrupted_head,
|
||||
&corrupted_files,
|
||||
&disks,
|
||||
false,
|
||||
"plain",
|
||||
"small",
|
||||
)
|
||||
.await
|
||||
.expect("corrupted bounded-quantum direct-memory read should return Ok(None) for parity fallback");
|
||||
assert!(fallback.is_none(), "corrupted second frame must fail closed in direct-memory path");
|
||||
|
||||
// A 32 KiB Range GET starting at offset 4 (skipping a 4-byte framing header)
|
||||
// starts in the first q-frame of shard 0 and crosses into shard 1. It must
|
||||
// coalesce into 1 quantized block decode instead of opening the shards twice.
|
||||
let calls = crate::set_disk::disk_call_counters::observe(CODEC_STREAMING_TEST_OBJECT);
|
||||
let mut range_out = Vec::new();
|
||||
SetDisks::read_quantized_range(
|
||||
CODEC_STREAMING_TEST_BUCKET,
|
||||
CODEC_STREAMING_TEST_OBJECT,
|
||||
&mut range_out,
|
||||
&fi,
|
||||
&files,
|
||||
&disks,
|
||||
&erasure,
|
||||
FRAME_SIZE,
|
||||
32 * 1024,
|
||||
0,
|
||||
0,
|
||||
4,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
0,
|
||||
0,
|
||||
GET_OBJECT_PATH_SET_DISK,
|
||||
"plain",
|
||||
"small",
|
||||
)
|
||||
.await
|
||||
.expect("coalesced cross-shard range read must succeed");
|
||||
assert_eq!(range_out, payload[4..4 + 32 * 1024]);
|
||||
assert_eq!(
|
||||
calls.total(crate::set_disk::disk_call_counters::KIND_INLINE_SHARD_OPEN),
|
||||
2,
|
||||
"cross-shard range starting in frame 0 of shard 0 must open each data shard only once"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shard_read_cost_for_endpoint_maps_topology_classes() {
|
||||
let local_hosts = vec!["node-a:9000".to_string()];
|
||||
@@ -11043,7 +11684,12 @@ mod dangling_read_tests {
|
||||
object,
|
||||
&mut source,
|
||||
&ObjectOptions::default(),
|
||||
&ObjectOptions::default(),
|
||||
&ObjectOptions {
|
||||
object_lock_config_snapshot: Some(Arc::new(crate::object_api::ObjectLockConfigSnapshot::new(
|
||||
crate::bucket::metadata_sys::ObjectLockConfigState::ConfirmedAbsent,
|
||||
))),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("a CopyObject source without a version id must resolve like a latest GET");
|
||||
|
||||
@@ -36,6 +36,12 @@ pub(crate) struct ShardReadRepair {
|
||||
}
|
||||
|
||||
impl ShardReadRepair {
|
||||
pub(crate) fn snapshot(&self) -> Self {
|
||||
Self {
|
||||
observed: AtomicU8::new(self.observed.load(Ordering::Acquire)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn observe(&self, errors: &[Option<Error>]) {
|
||||
let flags = errors.iter().flatten().fold(0, |flags, error| {
|
||||
flags
|
||||
|
||||
@@ -33,9 +33,10 @@ pub(crate) mod internode {
|
||||
PUT_FILE_AUTH_TRAILER_MAC_LEN, PUT_FILE_AUTH_TRAILER_MAGIC, PUT_FILE_AUTH_V1, PUT_FILE_CAPABILITY_CHALLENGE_QUERY,
|
||||
PUT_FILE_CAPABILITY_QUERY, PUT_FILE_CAPABILITY_VERSION, PUT_FILE_NONCE_QUERY, PUT_FILE_SERVER_EPOCH_QUERY,
|
||||
PutFileCapabilityResponse, SCANNER_ACTIVITY_LEGACY_PROTOCOL_VERSION, SCANNER_ACTIVITY_PREVIOUS_PROTOCOL_VERSION,
|
||||
SCANNER_ACTIVITY_PROTOCOL_VERSION, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_MAX_ENTRIES,
|
||||
SCANNER_DIRTY_USAGE_SNAPSHOT_PROTOCOL_VERSION, SCANNER_DIRTY_USAGE_SNAPSHOT_RPC_MAX_MESSAGE_SIZE,
|
||||
WALK_DIR_BODY_SHA256_QUERY, WALK_DIR_STREAM_COMPLETION_QUERY, WALK_DIR_STREAM_COMPLETION_V1,
|
||||
SCANNER_ACTIVITY_PROTOCOL_VERSION, SCANNER_ACTIVITY_V6_PROTOCOL_VERSION, SCANNER_ACTIVITY_V7_PROTOCOL_VERSION,
|
||||
SCANNER_DIRTY_USAGE_SNAPSHOT_MAX_ENTRIES, SCANNER_DIRTY_USAGE_SNAPSHOT_PROTOCOL_VERSION,
|
||||
SCANNER_DIRTY_USAGE_SNAPSHOT_RPC_MAX_MESSAGE_SIZE, WALK_DIR_BODY_SHA256_QUERY, WALK_DIR_STREAM_COMPLETION_QUERY,
|
||||
WALK_DIR_STREAM_COMPLETION_V1,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user