diff --git a/.github/scheduled-validations.json b/.github/scheduled-validations.json index 09d1eb481f..35eee57caa 100644 --- a/.github/scheduled-validations.json +++ b/.github/scheduled-validations.json @@ -296,6 +296,34 @@ "origin": "baseline", "alert_contract": "scheduled-validation" }, + { + "workflow": ".github/workflows/rdma-feature-check.yml", + "name": "S3-over-RDMA feature check", + "roles": [ + "pr", + "periodic", + "manual" + ], + "events": [ + "pull_request", + "schedule", + "workflow_dispatch" + ], + "cadence": "weekly", + "timezone": "UTC", + "schedule": [ + "37 5 * * 1" + ], + "owner": "@overtrue", + "policy": "active", + "monitor": "workflow", + "max_age_hours": 192, + "result_owner": "rdma-feature-check.yml", + "disposition": "compiles the nixl feature and runs rustfs-nixl unit tests on Linux; the feature is off in every other build", + "failure_owner": "workflow", + "origin": "added", + "alert_contract": "scheduled-validation" + }, { "workflow": ".github/workflows/rustfs-validation-sweep.yml", "name": "RustFS Validation Sweep", diff --git a/.github/workflows/rdma-feature-check.yml b/.github/workflows/rdma-feature-check.yml new file mode 100644 index 0000000000..8fcec76d44 --- /dev/null +++ b/.github/workflows/rdma-feature-check.yml @@ -0,0 +1,91 @@ +name: S3-over-RDMA feature check + +# The `nixl` and `cuobject` features are off in every other build, so the code +# behind them is compiled nowhere else. This job compiles the `nixl` half on +# Linux and runs rustfs-nixl's unit tests; nixl-sys builds through its stub +# fallback, so no NIXL SDK is needed. +# The cuObject half needs the NVIDIA cuObject SDK and is not compiled here. +# Not a required check and not part of the `Test and Lint` aggregate. + +on: + pull_request: + paths: + - "crates/nixl/**" + - "crates/cuobject/**" + - "rustfs/src/storage/rpc/nixl*" + - "rustfs/src/app/object/cuobject.rs" + - "rustfs/src/app/object/get.rs" + - "rustfs/src/app/object/put.rs" + - "rustfs/src/app/multipart_usecase/upload_part.rs" + - "Cargo.toml" + - "rustfs/Cargo.toml" + - ".github/workflows/rdma-feature-check.yml" + schedule: + - cron: "37 5 * * 1" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: rdma-feature-check-${{ github.ref }} + cancel-in-progress: true + +jobs: + nixl-check: + name: cargo check and unit tests (nixl) + runs-on: sm-standard-4 + timeout-minutes: 60 + 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-feat-nixl + cache-save-if: 'false' + install-build-packaging-tools: 'false' + + - name: Install only missing native build tools + run: | + packages=() + command -v g++ >/dev/null || packages+=(g++) + ldconfig -p | grep -q 'libclang' || packages+=(libclang-dev) + if (( ${#packages[@]} )); then + sudo apt-get update + sudo apt-get install --no-install-recommends -y "${packages[@]}" + fi + + - name: Check the nixl feature build + run: cargo check --locked -p rustfs --features nixl + + # These unit tests use a fake sysfs and plain host memory; none needs an + # RDMA device or the NIXL libraries. + - name: Run the rustfs-nixl unit tests + run: cargo test --locked -p rustfs-nixl --features sys + + alert-on-failure: + name: Alert on scheduled failure + needs: [nixl-check] + # Only scheduled runs open or update the tracking issue; pull-request and + # manual runs stay quiet. + if: always() && github.event_name == 'schedule' && contains(needs.*.result, 'failure') + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + persist-credentials: false + - name: Open or update failure-tracking issue + uses: ./.github/actions/schedule-failure-issue + with: + github-token: ${{ secrets.BACKLOG_ISSUE_TOKEN }} diff --git a/Cargo.lock b/Cargo.lock index 05f79377bd..b876f18a2a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1004,7 +1004,7 @@ version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b744eed18cd75d814effdf2aba2880f912abe0fe1c327b361341d31aba9a7005" dependencies = [ - "bindgen", + "bindgen 0.73.2", "cc", "cmake", "dunce", @@ -1618,6 +1618,35 @@ dependencies = [ "serde", ] +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bindgen" +version = "0.71.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3" +dependencies = [ + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease 0.2.37", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bindgen" version = "0.73.2" @@ -1633,7 +1662,7 @@ dependencies = [ "quote", "regex", "rustc-hash", - "shlex", + "shlex 2.0.1", "syn 3.0.10", ] @@ -1766,6 +1795,15 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + [[package]] name = "blocking" version = "1.7.0" @@ -2087,7 +2125,7 @@ dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex", + "shlex 2.0.1", ] [[package]] @@ -2771,6 +2809,27 @@ dependencies = [ "subtle", ] +[[package]] +name = "cuobject" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "486fec9045f8057131bf4bba71fbb87bf9dd3e44f853622cf7fa42713f3a108c" +dependencies = [ + "cuobject-sys", + "memmap2", + "thiserror 2.0.21", +] + +[[package]] +name = "cuobject-sys" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edc615b2a037eb0d80180d202f809629155742db9c9e94b9f7696b1100a7d52f" +dependencies = [ + "bindgen 0.73.2", + "cc", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -6956,6 +7015,23 @@ dependencies = [ "libc", ] +[[package]] +name = "nixl-sys" +version = "1.5.2" +source = "git+https://github.com/ai-dynamo/nixl?tag=v1.5.2#e72c52c78478d2e1ca9e9c57b872114e113ad767" +dependencies = [ + "anyhow", + "bincode", + "bindgen 0.71.1", + "cc", + "libc", + "os_info", + "pkg-config", + "serde", + "thiserror 2.0.21", + "tracing", +] + [[package]] name = "nkeys" version = "0.4.5" @@ -7187,6 +7263,27 @@ dependencies = [ "objc2-encode", ] +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "objc2", + "objc2-foundation", +] + [[package]] name = "objc2-core-foundation" version = "0.3.2" @@ -7198,6 +7295,51 @@ dependencies = [ "objc2", ] +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-location" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", +] + [[package]] name = "objc2-encode" version = "4.1.0" @@ -7211,7 +7353,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.2", + "block2", + "libc", "objc2", + "objc2-core-foundation", ] [[package]] @@ -7224,6 +7369,17 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", +] + [[package]] name = "objc2-open-directory" version = "0.3.2" @@ -7235,6 +7391,18 @@ dependencies = [ "objc2-foundation", ] +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", +] + [[package]] name = "objc2-system-configuration" version = "0.3.2" @@ -7244,6 +7412,37 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-location", + "objc2-core-text", + "objc2-foundation", + "objc2-quartz-core", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e" +dependencies = [ + "objc2", + "objc2-foundation", +] + [[package]] name = "object" version = "0.36.7" @@ -7508,6 +7707,22 @@ dependencies = [ "num-traits", ] +[[package]] +name = "os_info" +version = "3.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b" +dependencies = [ + "android_system_properties", + "log", + "nix 0.31.3", + "objc2", + "objc2-foundation", + "objc2-ui-kit", + "serde", + "windows-sys 0.61.2", +] + [[package]] name = "ouroboros" version = "0.18.5" @@ -9645,6 +9860,7 @@ dependencies = [ "rustfs-config", "rustfs-credentials", "rustfs-crypto", + "rustfs-cuobject", "rustfs-data-usage", "rustfs-ecstore", "rustfs-extension-schema", @@ -9666,6 +9882,7 @@ dependencies = [ "rustfs-madmin", "rustfs-mimalloc", "rustfs-mimalloc-sys", + "rustfs-nixl", "rustfs-notify", "rustfs-object-capacity", "rustfs-object-data-cache", @@ -9849,6 +10066,17 @@ dependencies = [ "time", ] +[[package]] +name = "rustfs-cuobject" +version = "1.0.5" +dependencies = [ + "bytes", + "cuobject", + "parking_lot 0.13.0", + "thiserror 2.0.21", + "tokio", +] + [[package]] name = "rustfs-data-usage" version = "1.0.5" @@ -10552,6 +10780,20 @@ dependencies = [ "cc", ] +[[package]] +name = "rustfs-nixl" +version = "1.0.5" +dependencies = [ + "base64-simd", + "bytes", + "memmap2", + "nixl-sys", + "parking_lot 0.13.0", + "thiserror 2.0.21", + "tokio", + "tracing", +] + [[package]] name = "rustfs-notify" version = "1.0.5" @@ -12108,6 +12350,12 @@ dependencies = [ "dirs", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -14522,7 +14770,7 @@ version = "2.1.3+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f729a06d0257428fd9d997ac8db7e1407bd0262ab016b085b36bc52957c0052d" dependencies = [ - "bindgen", + "bindgen 0.73.2", "cc", "pkg-config", ] diff --git a/Cargo.toml b/Cargo.toml index b0fc1c9fe9..7fec98c059 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,8 @@ members = [ "crates/connect-symbol-catalog", # Release-only CPU profile symbol catalog generator "crates/credentials", # Credential management system "crates/crypto", # Cryptography and security features + "crates/cuobject", # NVIDIA cuObject S3-over-RDMA staging and transfers (optional) + "crates/nixl", # NIXL/UCX S3-over-RDMA server side (optional) "crates/ecstore", # Erasure coding storage implementation "crates/e2e_test", # End-to-end test suite "crates/filemeta", # File metadata management @@ -104,6 +106,8 @@ rustfs-config = { path = "./crates/config", version = "1.0.5" } rustfs-concurrency = { path = "./crates/concurrency", version = "1.0.5" } rustfs-credentials = { path = "crates/credentials", version = "1.0.5" } rustfs-crypto = { path = "crates/crypto", version = "1.0.5" } +rustfs-cuobject = { path = "crates/cuobject", version = "1.0.5" } +rustfs-nixl = { path = "crates/nixl", version = "1.0.5" } rustfs-ecstore = { path = "crates/ecstore", version = "1.0.5" } rustfs-filemeta = { path = "crates/filemeta", version = "1.0.5" } rustfs-iam = { path = "crates/iam", version = "1.0.5" } @@ -304,6 +308,7 @@ hostname = "0.4.2" ipnetwork = { version = "0.21.1" } lazy_static = "1.5.1" libc = "0.2.191" +cuobject = "0.1.0" libsystemd = "0.7.2" local-ip-address = "0.6.13" log = "0.4" diff --git a/crates/config/src/constants/internode.rs b/crates/config/src/constants/internode.rs index d04e265689..8f75aad72d 100644 --- a/crates/config/src/constants/internode.rs +++ b/crates/config/src/constants/internode.rs @@ -333,8 +333,130 @@ pub const DEFAULT_INTERNODE_DATA_TRANSPORT: &str = "tcp-http"; /// Legacy alias for "tcp-http". Both values select the TCP/HTTP transport backend. pub const INTERNODE_DATA_TRANSPORT_TCP: &str = "tcp"; +/// Internode reads whose data moves over NIXL/UCX (InfiniBand rails or RoCE by +/// LID/GID, no IP needed); requests, writes and walks stay on TCP/HTTP. Requires +/// a binary built with the `nixl` feature and `RUSTFS_NIXL_ENABLE`; until the +/// NIXL agent is up, and for any read it cannot serve, it uses TCP/HTTP. +pub const INTERNODE_DATA_TRANSPORT_NIXL: &str = "nixl"; + /// Known internode transport backend names accepted by the config parser. -pub const KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS: &[&str] = &[DEFAULT_INTERNODE_DATA_TRANSPORT, INTERNODE_DATA_TRANSPORT_TCP]; +pub const KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS: &[&str] = &[ + DEFAULT_INTERNODE_DATA_TRANSPORT, + INTERNODE_DATA_TRANSPORT_TCP, + INTERNODE_DATA_TRANSPORT_NIXL, +]; + +/// Check the configured RDMA devices at startup and leave out any that is down, +/// slower than its peers, or loses its link during a short watch. +pub const ENV_RUSTFS_NIXL_DEVICE_CHECK: &str = "RUSTFS_NIXL_DEVICE_CHECK"; +pub const DEFAULT_RUSTFS_NIXL_DEVICE_CHECK: bool = true; +/// Leave out a device whose link dropped this many times more since boot than +/// the quietest device of its link layer; 0 skips this test. +pub const ENV_RUSTFS_NIXL_DEVICE_MAX_LINK_DROPS: &str = "RUSTFS_NIXL_DEVICE_MAX_LINK_DROPS"; +pub const DEFAULT_RUSTFS_NIXL_DEVICE_MAX_LINK_DROPS: u64 = 16; +/// How long the startup device check watches the link counters; 0 skips the watch. +pub const ENV_RUSTFS_NIXL_DEVICE_FLAP_WINDOW_MS: &str = "RUSTFS_NIXL_DEVICE_FLAP_WINDOW_MS"; +pub const DEFAULT_RUSTFS_NIXL_DEVICE_FLAP_WINDOW_MS: u64 = 3_000; + +/// NIXL internode reads in flight per remote shard stream. +pub const ENV_RUSTFS_NIXL_INTERNODE_DEPTH: &str = "RUSTFS_NIXL_INTERNODE_DEPTH"; +pub const DEFAULT_RUSTFS_NIXL_INTERNODE_DEPTH: usize = 4; + +/// Whether S3 GETs and PUTs carrying the NIXL headers are served over NIXL/UCX +/// S3-over-RDMA (requires a build with the `nixl` feature and libnixl). The +/// pipeline settings below (`RUSTFS_CUOBJECT_GET_FANOUT*`, `_INFLIGHT_WRITES`, +/// `_SHARD_ARENA_BYTES`) apply to this transport as well. +pub const ENV_RUSTFS_NIXL_ENABLE: &str = "RUSTFS_NIXL_ENABLE"; +pub const DEFAULT_RUSTFS_NIXL_ENABLE: bool = false; +/// This node's NIXL agent name; defaults to `rustfs-`. +pub const ENV_RUSTFS_NIXL_AGENT_NAME: &str = "RUSTFS_NIXL_AGENT_NAME"; +/// Comma-separated UCX device names (`mlx5_9,mlx5_10`; NIXL adds the port); empty lets UCX use every device. +pub const ENV_RUSTFS_NIXL_UCX_DEVICES: &str = "RUSTFS_NIXL_UCX_DEVICES"; +/// UCX progress workers of the agent. +pub const ENV_RUSTFS_NIXL_NUM_WORKERS: &str = "RUSTFS_NIXL_NUM_WORKERS"; +pub const DEFAULT_RUSTFS_NIXL_NUM_WORKERS: u32 = 1; +/// Staging chunk size per transfer descriptor to a client. +pub const ENV_RUSTFS_NIXL_CHUNK_BYTES: &str = "RUSTFS_NIXL_CHUNK_BYTES"; +pub const DEFAULT_RUSTFS_NIXL_CHUNK_BYTES: usize = 16 * 1024 * 1024; +/// Registered staging memory of the agent. +pub const ENV_RUSTFS_NIXL_POOL_BYTES: &str = "RUSTFS_NIXL_POOL_BYTES"; +pub const DEFAULT_RUSTFS_NIXL_POOL_BYTES: usize = 1024 * 1024 * 1024; +/// Transfers in flight per node at most. +pub const ENV_RUSTFS_NIXL_MAX_INFLIGHT: &str = "RUSTFS_NIXL_MAX_INFLIGHT"; +pub const DEFAULT_RUSTFS_NIXL_MAX_INFLIGHT: usize = 256; +/// A transfer that has not completed after this many seconds fails the request. +pub const ENV_RUSTFS_NIXL_TRANSFER_TIMEOUT_SECS: &str = "RUSTFS_NIXL_TRANSFER_TIMEOUT_SECS"; +pub const DEFAULT_RUSTFS_NIXL_TRANSFER_TIMEOUT_SECS: u64 = 60; + +/// Whether S3 GETs carrying an `x-amz-rdma-token` are served over cuObject S3-over-RDMA +/// (requires a build with the `cuobject` feature and libcuobjserver). +pub const ENV_RUSTFS_CUOBJECT_ENABLE: &str = "RUSTFS_CUOBJECT_ENABLE"; +pub const DEFAULT_RUSTFS_CUOBJECT_ENABLE: bool = false; + +/// Comma-separated RDMA-capable IP addresses that get a cuObject server each. +/// Defaults to the hosts of this node's own endpoints. +pub const ENV_RUSTFS_CUOBJECT_ADDRS: &str = "RUSTFS_CUOBJECT_ADDRS"; + +/// UDP/RDMA control port of the cuObject servers. +pub const ENV_RUSTFS_CUOBJECT_PORT: &str = "RUSTFS_CUOBJECT_PORT"; +pub const DEFAULT_RUSTFS_CUOBJECT_PORT: u16 = 18515; + +/// Staging chunk size per RDMA write to a client. +pub const ENV_RUSTFS_CUOBJECT_CHUNK_BYTES: &str = "RUSTFS_CUOBJECT_CHUNK_BYTES"; +pub const DEFAULT_RUSTFS_CUOBJECT_CHUNK_BYTES: usize = 16 * 1024 * 1024; + +/// Registered staging memory per cuObject server. +pub const ENV_RUSTFS_CUOBJECT_POOL_BYTES: &str = "RUSTFS_CUOBJECT_POOL_BYTES"; +pub const DEFAULT_RUSTFS_CUOBJECT_POOL_BYTES: usize = 1024 * 1024 * 1024; + +/// Dynamically connected initiators per cuObject server (concurrent client connections). +/// Staging chunks (RDMA writes) kept in flight per GET, so decoding never waits +/// for the write of the previous chunk; each costs one chunk of the pool. +pub const ENV_RUSTFS_CUOBJECT_INFLIGHT_WRITES: &str = "RUSTFS_CUOBJECT_INFLIGHT_WRITES"; +pub const DEFAULT_RUSTFS_CUOBJECT_INFLIGHT_WRITES: usize = 3; + +/// Staging chunks (RDMA reads from the client buffer) kept in flight per +/// RDMA PUT body, so ingest never waits on one chunk's round trip at a time; +/// each costs one chunk of the pool. +pub const ENV_RUSTFS_CUOBJECT_PUT_READ_AHEAD: &str = "RUSTFS_CUOBJECT_PUT_READ_AHEAD"; +pub const DEFAULT_RUSTFS_CUOBJECT_PUT_READ_AHEAD: usize = 4; + +/// Concurrent erasure-block-aligned segments one cuObject GET is split into +/// on the server (each segment decodes and RDMA-writes its own stripes), so a +/// single stream keeps several stripes in flight. 1 disables the fan-out. +pub const ENV_RUSTFS_CUOBJECT_GET_FANOUT: &str = "RUSTFS_CUOBJECT_GET_FANOUT"; +pub const DEFAULT_RUSTFS_CUOBJECT_GET_FANOUT: usize = 8; + +/// Smallest segment worth its own producer (rounded up to whole erasure +/// blocks): each segment pays a reader setup per part it touches, so short +/// requests stay sequential. +pub const ENV_RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES: &str = "RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES"; +pub const DEFAULT_RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES: u64 = 192 * 1024 * 1024; + +/// Segment producers a node runs across all its cuObject GETs: each new GET +/// gets a fair share (budget / open GETs, at least 1, at most the fan-out) +/// and never waits for one, so many-stream load degrades to sequential GETs +/// instead of a reader-setup storm. +pub const ENV_RUSTFS_CUOBJECT_GET_FANOUT_BUDGET: &str = "RUSTFS_CUOBJECT_GET_FANOUT_BUDGET"; +pub const DEFAULT_RUSTFS_CUOBJECT_GET_FANOUT_BUDGET: usize = 16; + +/// Registered host memory the erasure decoder reads shards into so a +/// cuObject GET can RDMA-write data shards straight from those buffers +/// (zero-copy emit); 0 keeps the staging copy. Blocks are +/// `RUSTFS_ERASURE_SHARD_BYTES` (4 MiB when unset); objects with larger +/// shards fall back to heap buffers and the staging copy. +pub const ENV_RUSTFS_CUOBJECT_SHARD_ARENA_BYTES: &str = "RUSTFS_CUOBJECT_SHARD_ARENA_BYTES"; +pub const DEFAULT_RUSTFS_CUOBJECT_SHARD_ARENA_BYTES: usize = 0; + +pub const ENV_RUSTFS_CUOBJECT_NUM_DCIS: &str = "RUSTFS_CUOBJECT_NUM_DCIS"; +pub const DEFAULT_RUSTFS_CUOBJECT_NUM_DCIS: u32 = 128; + +/// Complete cuObject transfers through the library's asynchronous mode: the +/// write is submitted with a handle and the task waits on the channel's +/// completion descriptor instead of holding a blocking thread for the whole +/// transfer. `false` keeps one blocking library call per transfer. +pub const ENV_RUSTFS_CUOBJECT_ASYNC_TRANSFERS: &str = "RUSTFS_CUOBJECT_ASYNC_TRANSFERS"; +pub const DEFAULT_RUSTFS_CUOBJECT_ASYNC_TRANSFERS: bool = true; #[cfg(test)] mod tests { @@ -465,6 +587,6 @@ mod tests { assert_eq!(ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, "RUSTFS_INTERNODE_DATA_TRANSPORT"); assert_eq!(DEFAULT_INTERNODE_DATA_TRANSPORT, "tcp-http"); assert_eq!(INTERNODE_DATA_TRANSPORT_TCP, "tcp"); - assert_eq!(KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS, &["tcp-http", "tcp"]); + assert_eq!(KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS, &["tcp-http", "tcp", "nixl"]); } } diff --git a/crates/cuobject/Cargo.toml b/crates/cuobject/Cargo.toml new file mode 100644 index 0000000000..f80a164902 --- /dev/null +++ b/crates/cuobject/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "rustfs-cuobject" +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true +homepage.workspace = true +description = "RustFS staging pool and transfers for NVIDIA cuObject S3-over-RDMA (GPUDirect object loading)" +keywords = ["rdma", "cuobject", "gpudirect", "s3"] +categories = ["network-programming"] +documentation = "https://docs.rs/rustfs-cuobject/latest/rustfs_cuobject/" + +[lints] +workspace = true + +[dependencies] +bytes = { workspace = true, optional = true } +cuobject = { workspace = true, default-features = false, optional = true } +parking_lot = { workspace = true, optional = true } +thiserror = { workspace = true, optional = true } +tokio = { workspace = true, features = ["net", "rt-multi-thread", "sync", "time"], optional = true } + +[features] +# Compiles the cuObject server bindings (needs the NVIDIA cuObject SDK). +server = ["dep:bytes", "dep:cuobject", "cuobject/server", "dep:parking_lot", "dep:thiserror", "dep:tokio"] diff --git a/crates/cuobject/src/lib.rs b/crates/cuobject/src/lib.rs new file mode 100644 index 0000000000..b379eb5608 --- /dev/null +++ b/crates/cuobject/src/lib.rs @@ -0,0 +1,775 @@ +// 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. + +//! Server side of NVIDIA cuObject S3-over-RDMA. +//! +//! A client that supports the protocol (NVIDIA cuObject, NIXL's object plugin, +//! …) sends an ordinary S3 GET with an `x-amz-rdma-token` header describing a +//! registered client buffer (host or GPU memory). Instead of streaming the +//! body over HTTP, the server RDMA-writes the object bytes into that buffer +//! through NVIDIA's `libcuobjserver` and answers with an empty body plus +//! `x-amz-rdma-reply` and `x-amz-rdma-bytes-transferred`. +//! +//! The library bindings come from the [`cuobject`] crate. This crate owns +//! RustFS's pool of registered, page-aligned host staging buffers: the regular +//! read path fills a staging chunk and +//! [`CuObjectServer::write_to_client_owned`] pushes it. +//! +//! Everything below needs the `server` feature, which compiles the +//! NVIDIA cuObject server bindings; without it the crate is empty, so a +//! workspace build does not need the cuObject SDK. +#![cfg(feature = "server")] + +use bytes::Bytes; +use cuobject::{Channel, Completion, RegisteredBuffer, Server, ServerOptions, SgBuffer, SgEntry, Source}; +use std::collections::VecDeque; +use std::net::IpAddr; +use std::num::NonZeroUsize; +use std::sync::Arc; +use std::time::Duration; +use thiserror::Error; +use tokio::io::Interest; +use tokio::io::unix::AsyncFd; +use tokio::sync::Semaphore; + +/// Header carrying the client's RDMA descriptor on a request. +pub const RDMA_TOKEN_HEADER: &str = cuobject::TOKEN_HEADER; +/// Header carrying the transfer status on the response (HTTP-style code). +pub const RDMA_REPLY_HEADER: &str = cuobject::REPLY_HEADER; +/// Header carrying the payload byte count moved over RDMA. +pub const RDMA_BYTES_TRANSFERRED_HEADER: &str = cuobject::BYTES_TRANSFERRED_HEADER; +/// Reply code for a declined transfer (the client then errors or falls back). +pub const RDMA_REPLY_NOT_IMPLEMENTED: u16 = cuobject::REPLY_NOT_IMPLEMENTED; +/// Largest single `handleGetObject` the library accepts. +pub const MAX_RDMA_OP_BYTES: usize = cuobject::MAX_TRANSFER_BYTES; +/// Default RDMA control port of the cuObject server. +pub const DEFAULT_PORT: u16 = cuobject::DEFAULT_PORT; +/// Most ranges one scatter-gather transfer may carry (the library's `max_sge`). +pub const MAX_SG_RANGES: usize = cuobject::DEFAULT_MAX_SG_ENTRIES; + +/// Version of the cuObject server headers the bindings were built against, as +/// (major, minor). +pub fn library_version() -> (u32, u32) { + cuobject::header_version() +} + +#[derive(Debug, Error)] +pub enum CuObjectError { + #[error("cuobject {op} failed: {source}")] + Os { + op: &'static str, + #[source] + source: std::io::Error, + }, + #[error("cuobject rdma token is malformed: {0}")] + Token(String), + #[error("cuobject rdma token buffer ({buffer} bytes) is smaller than the response ({needed} bytes)")] + TokenTooSmall { buffer: u64, needed: u64 }, + #[error("cuobject rejected the request: {0}")] + Invalid(&'static str), + #[error("cuobject transfer failed with verbs status {verbs_status}: {source}")] + Transfer { + verbs_status: i32, + #[source] + source: std::io::Error, + }, + #[error("cuobject transfer moved {moved} of {expected} bytes")] + ShortTransfer { moved: u64, expected: u64 }, + #[error("cuobject staging pool exhausted")] + PoolExhausted, + #[error("cuobject library offers no completion descriptor for channel {0}")] + AsyncUnavailable(u16), + #[error("cuobject read source failed: {0}")] + Source(#[source] std::io::Error), +} + +impl From for CuObjectError { + fn from(error: cuobject::Error) -> Self { + match error { + cuobject::Error::Library { op, source } => Self::Os { op, source }, + cuobject::Error::Transfer { verbs_status, source } => Self::Transfer { verbs_status, source }, + cuobject::Error::InvalidArgument(reason) => Self::Invalid(reason), + cuobject::Error::InvalidToken(reason) => Self::Token(reason.to_owned()), + cuobject::Error::TokenTooSmall { buffer, needed } => Self::TokenTooSmall { buffer, needed }, + cuobject::Error::AsyncUnavailable(channel) => Self::AsyncUnavailable(channel), + other => Self::Os { + op: "cuobject", + source: std::io::Error::other(other), + }, + } + } +} + +/// Parsed `x-amz-rdma-token`. +/// +/// Wire format (cuObject RDMA descriptor protocol): colon-separated hex +/// fields `addr:size:rkey:lid:dctn:gid_present:gid`; only the leading +/// address and size are interpreted here, the library consumes the rest. +#[derive(Debug, Clone)] +pub struct RdmaToken { + inner: cuobject::RdmaToken, + /// Start of the client buffer (a copy of the parsed field). + pub remote_addr: u64, + /// Length of the client buffer (a copy of the parsed field). + pub buffer_len: u64, +} + +impl RdmaToken { + pub fn parse(raw: &str) -> Result { + let inner = cuobject::RdmaToken::parse(raw)?; + Ok(Self { + remote_addr: inner.remote_addr(), + buffer_len: inner.buffer_len(), + inner, + }) + } + + pub fn as_str(&self) -> &str { + self.inner.as_str() + } +} + +/// Tuning for one server instance. +#[derive(Debug, Clone)] +pub struct CuObjectConfig { + pub port: u16, + pub num_dcis: i32, + pub cq_depth: u32, + /// Size of one staging buffer; one RDMA write moves at most this much. + pub chunk_bytes: usize, + /// Total registered staging memory per server instance. + pub pool_bytes: usize, + /// Complete transfers through the library's asynchronous mode (submit, + /// then wait on the channel's completion descriptor) instead of one + /// blocking library call per transfer. + pub async_transfers: bool, +} + +impl Default for CuObjectConfig { + fn default() -> Self { + Self { + port: DEFAULT_PORT, + num_dcis: 128, + cq_depth: 640, + chunk_bytes: 64 * 1024 * 1024, + pool_bytes: 1024 * 1024 * 1024, + async_transfers: true, + } + } +} + +struct Staging { + buffer: RegisteredBuffer>, + free: parking_lot::Mutex>, + permits: Semaphore, + chunk_bytes: usize, +} + +/// One cuObject server bound to the RDMA device that owns an IP address. +pub struct CuObjectServer { + server: Arc, + staging: Staging, + addr: IpAddr, + port: u16, + /// One permit per library channel (DC initiator): a transfer waits here + /// instead of failing with `EBUSY` when every channel is in use. + channels: Arc, + async_transfers: bool, +} + +impl std::fmt::Debug for CuObjectServer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CuObjectServer") + .field("addr", &self.addr) + .field("port", &self.port) + .field("chunk_bytes", &self.staging.chunk_bytes) + .finish() + } +} + +/// Several byte ranges of one [`RegisteredArena`], sent in order as one +/// RDMA operation (at most [`MAX_SG_RANGES`]). +pub struct ArenaRanges { + pub arena: Arc, + /// `(local_offset, len)` pairs, in stream order. + pub ranges: Vec<(usize, usize)>, +} + +impl ArenaRanges { + pub fn total_len(&self) -> usize { + self.ranges.iter().map(|(_, len)| *len).sum() + } +} + +/// A byte range of a [`RegisteredArena`] to send from. +pub struct ArenaRange { + pub arena: Arc, + pub local_offset: usize, + pub len: usize, +} + +/// Host memory registered with one server, owned by the caller (see +/// [`CuObjectServer::register_arena`]). +pub struct RegisteredArena { + buffer: RegisteredBuffer>, + server: Arc, + id: u64, +} + +impl RegisteredArena { + /// Length of the registered memory. + pub fn len(&self) -> usize { + self.buffer.len() + } + + pub fn is_empty(&self) -> bool { + self.buffer.is_empty() + } + + /// Process-unique id of this registration. + pub fn id(&self) -> u64 { + self.id + } + + /// The server this memory is registered with. + pub fn server(&self) -> &Arc { + &self.server + } + + /// Raw pointer to the start of the registered memory. The memory lives as + /// long as this arena; callers hand out disjoint ranges of it and never + /// touch a range while a transfer sends it. + pub fn as_mut_ptr(&self) -> *mut u8 { + self.buffer.as_mut_ptr() + } +} + +impl std::fmt::Debug for RegisteredArena { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RegisteredArena") + .field("id", &self.id) + .field("len", &self.len()) + .finish() + } +} + +/// A reserved staging chunk; returned to the pool on drop. +/// +/// The chunk's index is unique while it is reserved, so its range of the +/// staging buffer has one owner. Transfers take the chunk by value, so no +/// Rust borrow of the range overlaps an RDMA operation on it. +pub struct StagingChunk { + server: Arc, + index: usize, + len: usize, +} + +impl StagingChunk { + pub fn capacity(&self) -> usize { + self.server.staging.chunk_bytes + } + + /// Bytes currently staged. + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Copies `data` at `self.len()` and advances the staged length. + pub fn append(&mut self, data: &[u8]) -> Result<(), CuObjectError> { + if self.len + data.len() > self.capacity() { + return Err(CuObjectError::Invalid("staging append exceeds chunk")); + } + self.spare_mut()?[..data.len()].copy_from_slice(data); + self.len += data.len(); + Ok(()) + } + + pub fn clear(&mut self) { + self.len = 0; + } + + pub fn is_full(&self) -> bool { + self.len >= self.capacity() + } + + /// The bytes staged so far. + #[allow(unsafe_code)] + pub fn staged(&self) -> Result<&[u8], CuObjectError> { + // SAFETY: the range lies in this chunk (see the type docs); `&self` + // excludes `spare_mut`, and transfers own the chunk they move. + Ok(unsafe { self.server.staging.buffer.slice(self.start(), self.len)? }) + } + + /// The unfilled remainder of the chunk, for a reader to fill directly. + #[allow(unsafe_code)] + pub fn spare_mut(&mut self) -> Result<&mut [u8], CuObjectError> { + let len = self.capacity() - self.len; + // SAFETY: the range lies in this chunk (see the type docs) and + // `&mut self` excludes every other borrow of it. + Ok(unsafe { self.server.staging.buffer.slice_mut(self.start() + self.len, len)? }) + } + + /// Marks `n` more bytes of the spare area as staged. + pub fn advance(&mut self, n: usize) -> Result<(), CuObjectError> { + if self.len + n > self.capacity() { + return Err(CuObjectError::Invalid("staging advance exceeds chunk")); + } + self.len += n; + Ok(()) + } + + fn start(&self) -> usize { + self.index * self.capacity() + } +} + +impl Drop for StagingChunk { + fn drop(&mut self) { + self.server.staging.free.lock().push_back(self.index); + self.server.staging.permits.add_permits(1); + } +} + +/// The local side of one GET, owned by the transfer until the DMA finished. +enum Local { + /// A range of the staging buffer, inside a chunk the transfer also owns. + Staging { offset: usize, len: usize }, + /// A range of a caller-owned arena. + Arena { + arena: Arc, + offset: usize, + len: usize, + }, + /// Several ranges of a caller-owned arena, sent as one operation. + ArenaList { + arena: Arc, + entries: Vec, + }, +} + +impl Local { + fn len(&self) -> usize { + match self { + Self::Staging { len, .. } | Self::Arena { len, .. } => *len, + Self::ArenaList { entries, .. } => entries.iter().map(|entry| entry.size).sum(), + } + } +} + +/// Why an asynchronous GET did not complete. +enum AsyncFailure { + /// The library has no completion descriptor; nothing was submitted. + Unavailable, + /// The GET failed, or was never submitted; nothing is in flight. + Failed(CuObjectError), + /// Waiting failed after submission: the NIC may still read the memory. + InFlight(CuObjectError), +} + +impl From for AsyncFailure { + fn from(error: cuobject::Error) -> Self { + Self::Failed(error.into()) + } +} + +/// The handle of the one GET in flight on an asynchronous channel. +const ASYNC_HANDLE: NonZeroUsize = NonZeroUsize::MIN; + +impl CuObjectServer { + /// Creates the server and its registered staging pool. + pub fn new(addr: IpAddr, config: &CuObjectConfig) -> Result, CuObjectError> { + if config.chunk_bytes == 0 || config.chunk_bytes > MAX_RDMA_OP_BYTES || config.pool_bytes < config.chunk_bytes { + return Err(CuObjectError::Invalid("invalid staging configuration")); + } + let mut options = ServerOptions::default(); + // A non-positive count keeps the library default. + options.num_dcis = u32::try_from(config.num_dcis).unwrap_or(0); + options.cq_depth = config.cq_depth; + let server = Arc::new(Server::new(addr, config.port, &options)?); + let chunks = config.pool_bytes / config.chunk_bytes; + let buffer = RegisteredBuffer::new(Arc::clone(&server), chunks * config.chunk_bytes)?; + Ok(Arc::new(Self { + channels: Arc::new(Semaphore::new(usize::try_from(config.num_dcis).unwrap_or(1).max(1))), + async_transfers: config.async_transfers, + server, + staging: Staging { + buffer, + free: parking_lot::Mutex::new((0..chunks).collect()), + permits: Semaphore::new(chunks), + chunk_bytes: config.chunk_bytes, + }, + addr, + port: config.port, + })) + } + + pub fn addr(&self) -> IpAddr { + self.addr + } + + pub fn port(&self) -> u16 { + self.port + } + + pub fn chunk_bytes(&self) -> usize { + self.staging.chunk_bytes + } + + /// Reserves one staging chunk, waiting up to `timeout` for a free one. + pub async fn reserve(self: &Arc, timeout: Duration) -> Result { + let permit = tokio::time::timeout(timeout, self.staging.permits.acquire()) + .await + .map_err(|_| CuObjectError::PoolExhausted)? + .map_err(|_| CuObjectError::PoolExhausted)?; + permit.forget(); + let index = self.staging.free.lock().pop_front().ok_or(CuObjectError::PoolExhausted)?; + Ok(StagingChunk { + server: Arc::clone(self), + index, + len: 0, + }) + } + + /// Reserves one staging chunk without waiting; `None` when the pool is empty. + pub fn try_reserve(self: &Arc) -> Option { + let permit = self.staging.permits.try_acquire().ok()?; + permit.forget(); + let index = self.staging.free.lock().pop_front()?; + Some(StagingChunk { + server: Arc::clone(self), + index, + len: 0, + }) + } + + /// Staging chunks currently free in the pool (a hint; another reservation may win). + pub fn available_chunks(&self) -> usize { + self.staging.permits.available_permits() + } + + /// Registers `len` bytes of zero-filled, page-aligned host memory with this + /// server for callers that manage the memory themselves (a shard arena the + /// decoder reads into and the server RDMA-writes from without staging). + pub fn register_arena(self: &Arc, len: usize) -> Result, CuObjectError> { + let buffer = RegisteredBuffer::new(Arc::clone(&self.server), len)?; + static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + Ok(Arc::new(RegisteredArena { + buffer, + server: Arc::clone(self), + id: NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + })) + } + + /// RDMA-writes the staged bytes of `chunk` to `token.remote_addr + + /// remote_offset`. The transfer owns the chunk until the DMA finished, so + /// cancelling the awaiting future can never release the staging slot under + /// an in-flight write. Returns the chunk with the byte count for reuse. + pub async fn write_to_client_owned( + self: &Arc, + key: &str, + token: &RdmaToken, + remote_offset: u64, + chunk: StagingChunk, + ) -> Result<(u64, StagingChunk), CuObjectError> { + if chunk.is_empty() { + return Ok((0, chunk)); + } + let local = Local::Staging { + offset: chunk.start(), + len: chunk.len(), + }; + self.get_owned(key, token, remote_offset, local, chunk).await + } + + /// RDMA-writes `source.len` bytes at `source.local_offset` of + /// `source.arena` to `token.remote_addr + remote_offset`, keeping `keep` + /// alive until the DMA finished (the caller passes whatever owns the arena + /// bytes). The arena must have been registered with this server. + pub async fn write_to_client_from_arena_owned( + self: &Arc, + key: &str, + token: &RdmaToken, + remote_offset: u64, + source: ArenaRange, + keep: T, + ) -> Result<(u64, T), CuObjectError> { + if source.len == 0 { + return Ok((0, keep)); + } + let local = Local::Arena { + arena: source.arena, + offset: source.local_offset, + len: source.len, + }; + self.get_owned(key, token, remote_offset, local, keep).await + } + + /// RDMA-writes all of `source.ranges` (in order, as one operation) to + /// `token.remote_addr + remote_offset`, keeping `keep` alive until the DMA + /// finished. The arena must have been registered with this server. + pub async fn write_to_client_sg_owned( + self: &Arc, + key: &str, + token: &RdmaToken, + remote_offset: u64, + source: ArenaRanges, + keep: T, + ) -> Result<(u64, T), CuObjectError> { + if source.ranges.len() > MAX_SG_RANGES { + return Err(CuObjectError::Invalid("too many scatter-gather ranges")); + } + if source.total_len() == 0 { + return Ok((0, keep)); + } + let entries = source + .ranges + .iter() + .map(|&(offset, size)| SgEntry { + offset: offset as u64, + size, + }) + .collect(); + let local = Local::ArenaList { + arena: source.arena, + entries, + }; + self.get_owned(key, token, remote_offset, local, keep).await + } + + /// RDMA-reads `len` bytes from `token.remote_addr + remote_offset` into the + /// (empty) `chunk`, owning it for the whole DMA like + /// [`Self::write_to_client_owned`]. On success the chunk holds `len` staged + /// bytes. + pub async fn read_from_client_owned( + self: &Arc, + key: &str, + token: &RdmaToken, + remote_offset: u64, + len: usize, + mut chunk: StagingChunk, + ) -> Result { + chunk.clear(); + if len == 0 { + return Ok(chunk); + } + if len > chunk.capacity() { + return Err(CuObjectError::Invalid("read exceeds the staging chunk")); + } + let server = Arc::clone(self); + let key = key.to_owned(); + let token = token.inner.clone(); + let channel_permit = self.channel_permit().await?; + tokio::task::spawn_blocking(move || { + let _channel_permit = channel_permit; + let mut channel = Channel::lease(Arc::clone(&server.server))?; + let moved = channel.put(&key, &token, remote_offset, &server.staging.buffer, chunk.start(), len)?; + check_moved(moved as u64, len as u64)?; + chunk.advance(len)?; + Ok(chunk) + }) + .await + .map_err(|error| join_error("read task", error))? + } + + async fn channel_permit(&self) -> Result { + Arc::clone(&self.channels) + .acquire_owned() + .await + .map_err(|_| CuObjectError::Invalid("server closed")) + } + + /// RDMA-writes `local` to the client and hands `keep` back once the DMA + /// finished. The transfer runs in a task of its own that owns `local`, + /// `keep` and the channel, so dropping this future never releases memory + /// the NIC may still read. + async fn get_owned( + self: &Arc, + key: &str, + token: &RdmaToken, + remote_offset: u64, + local: Local, + keep: T, + ) -> Result<(u64, T), CuObjectError> { + let expected = local.len() as u64; + let server = Arc::clone(self); + let key = key.to_owned(); + let token = token.inner.clone(); + let channel_permit = self.channel_permit().await?; + tokio::spawn(async move { + if server.async_transfers { + match server.get_async(&key, &token, remote_offset, &local).await { + Ok(()) => { + drop(channel_permit); + return Ok((expected, keep)); + } + Err(AsyncFailure::Unavailable) => {} + Err(AsyncFailure::Failed(error)) => return Err(error), + Err(AsyncFailure::InFlight(error)) => { + // The NIC may still read this memory: never release it. + std::mem::forget(local); + std::mem::forget(keep); + return Err(error); + } + } + } + tokio::task::spawn_blocking(move || { + let _channel_permit = channel_permit; + let mut channel = Channel::lease(Arc::clone(&server.server))?; + let mut list = None; + let source = server.source(&local, &mut list)?; + let moved = channel.get(&key, &token, remote_offset, source)?; + check_moved(moved as u64, expected)?; + // `keep` (the chunk or the arena owner) is released only here. + Ok((expected, keep)) + }) + .await + .map_err(|error| join_error("write task", error))? + }) + .await + .map_err(|error| join_error("write task", error))? + } + + /// Moves `local` with the library's asynchronous mode: the GET is + /// submitted on a channel of its own and the task waits on that channel's + /// completion descriptor instead of holding a blocking thread. + // SAFETY: the allowance covers only this function; its two unsafe calls + // each state the invariant they rely on. + #[allow(unsafe_code)] + async fn get_async( + &self, + key: &str, + token: &cuobject::RdmaToken, + remote_offset: u64, + local: &Local, + ) -> Result<(), AsyncFailure> { + let mut channel = Channel::lease(Arc::clone(&self.server))?; + let fd = match channel.completion_fd() { + Ok(fd) => fd, + Err(cuobject::Error::AsyncUnavailable(_)) => return Err(AsyncFailure::Unavailable), + Err(error) => return Err(error.into()), + }; + // SAFETY: the library owns the descriptor and keeps it open while the + // server lives; `fd` holds the server, and nothing here closes or + // replaces the descriptor while it is registered. + let completions = unsafe { AsyncFd::register_with_interest(fd, Interest::READABLE) }.map_err(|error| { + AsyncFailure::Failed(CuObjectError::Os { + op: "completion fd", + source: error.into_parts().1, + }) + })?; + let mut list = None; + let source = self.source(local, &mut list).map_err(AsyncFailure::Failed)?; + // SAFETY: the memory behind `source` belongs to `local`, owned by the + // calling task together with the transfer's `keep`; staging chunks and + // arena ranges given to a transfer are not borrowed by anyone else. + // This function returns only after the completion carrying the handle + // was drained, except through `InFlight`, where the channel and the + // list are leaked here and the caller leaks `local` and `keep`. + unsafe { channel.get_async(key, token, remote_offset, source, ASYNC_HANDLE) }?; + let mut events = [Completion::default(); 8]; + loop { + let mut ready = match completions.readable().await { + Ok(ready) => ready, + Err(source) => { + std::mem::forget(list); + std::mem::forget(channel); + return Err(AsyncFailure::InFlight(CuObjectError::Os { + op: "completion wait", + source, + })); + } + }; + loop { + let landed = match channel.process_completions(&mut events) { + Ok(landed) => landed, + Err(error) => { + std::mem::forget(list); + std::mem::forget(channel); + return Err(AsyncFailure::InFlight(error.into())); + } + }; + if let Some(done) = events[..landed].iter().find(|event| event.handle() == ASYNC_HANDLE.get()) { + // A completion carries no byte count: success moved the whole range. + return done + .result() + .map_err(|source| AsyncFailure::Failed(CuObjectError::Transfer { verbs_status: 0, source })); + } + if landed < events.len() { + break; + } + } + ready.clear_ready(); + } + } + + /// The library view of `local`; a scatter-gather list is built into `list`. + fn source<'a: 'l, 'l>( + &'a self, + local: &'a Local, + list: &'l mut Option>>, + ) -> Result>, CuObjectError> { + Ok(match local { + Local::Staging { offset, len } => Source::Range { + buffer: &self.staging.buffer, + offset: *offset, + len: *len, + }, + Local::Arena { arena, offset, len } => Source::Range { + buffer: &arena.buffer, + offset: *offset, + len: *len, + }, + Local::ArenaList { arena, entries } => Source::List(list.insert(arena.buffer.sg_buffer(entries)?)), + }) + } +} + +fn check_moved(moved: u64, expected: u64) -> Result { + if moved != expected { + return Err(CuObjectError::ShortTransfer { moved, expected }); + } + Ok(moved) +} + +fn join_error(op: &'static str, error: tokio::task::JoinError) -> CuObjectError { + CuObjectError::Os { + op, + source: std::io::Error::other(error), + } +} + +/// Copies owned bytes into staging; convenience for callers holding `Bytes`. +pub fn fill_chunk(chunk: &mut StagingChunk, data: &Bytes) -> Result<(), CuObjectError> { + chunk.append(data) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn token_parses_leading_fields_and_rejects_garbage() { + let token = + RdmaToken::parse("0000f52eddc00000:00100000:001824d2:0000:002873:1:00000000000000000000ffff0a0d5410").expect("token"); + assert_eq!(token.remote_addr, 0x0000_f52e_ddc0_0000); + assert_eq!(token.buffer_len, 0x0010_0000); + assert!(matches!(RdmaToken::parse("nothex:00100000:1:2:3:4:5"), Err(CuObjectError::Token(_)))); + assert!(RdmaToken::parse("0000f52eddc00000:00000000:1:2:3:4:5").is_err()); + assert!(RdmaToken::parse("0000f52eddc00000:00100000").is_err()); + } +} diff --git a/crates/ecstore/src/api/mod.rs b/crates/ecstore/src/api/mod.rs index fbb07787f2..04a622d980 100644 --- a/crates/ecstore/src/api/mod.rs +++ b/crates/ecstore/src/api/mod.rs @@ -684,6 +684,15 @@ pub mod rpc { InternodeDataTransport, InternodeDataTransportCapabilities, NsScannerCapabilityRequest, NsScannerStreamRequest, ReadStreamRequest, TcpHttpInternodeDataTransport, WalkDirStreamRequest, WriteStreamRequest, }; + /// Internode shard reads over NIXL: the receive-pool seam the binary fills + /// and the wire names its serving handler shares with the transport. + pub mod nixl { + pub use crate::cluster::rpc::nixl_internode::{ + NIXL_AGENT_QUERY, NIXL_BUFFER_QUERY, NIXL_BUFFERS_QUERY, NIXL_BYTES_HEADER, NIXL_METADATA_HEADER, + NIXL_METADATA_SHA256_QUERY, NIXL_NONCE_QUERY, NixlRecvBuffer, NixlRecvPool, READ_FILE_NIXL_PATH, + WRITE_FILE_NIXL_PATH, install_nixl_recv_pool, + }; + } pub use crate::cluster::rpc::{ AuthenticatedChannel, KMS_SIGNAL_SUBSYSTEM, LocalPeerS3Client, MAX_NETWORK_PROBE_BYTES, MAX_NETWORK_PROBE_DURATION, NetworkPeerProbeClient, NetworkPeerProbeError, NetworkPeerProbeMeasurement, NetworkPeerTarget, PEER_RESTDRY_RUN, diff --git a/crates/ecstore/src/cluster/rpc/http_auth.rs b/crates/ecstore/src/cluster/rpc/http_auth.rs index 553069b6f9..d4b4c5968e 100644 --- a/crates/ecstore/src/cluster/rpc/http_auth.rs +++ b/crates/ecstore/src/cluster/rpc/http_auth.rs @@ -60,7 +60,7 @@ use time::OffsetDateTime; use tracing::{error, info, warn}; use uuid::Uuid; -const SIGNATURE_HEADER: &str = "x-rustfs-signature"; +pub(crate) const SIGNATURE_HEADER: &str = "x-rustfs-signature"; pub const RPC_BACKGROUND_ADMISSION_HEADER: &str = "x-rustfs-rpc-background-admission"; const RPC_BACKGROUND_ADMISSION_V1: &str = "v1"; const RPC_BACKGROUND_ADMISSION_DOMAIN: &[u8] = b"rustfs-rpc-background-admission-v1\0"; diff --git a/crates/ecstore/src/cluster/rpc/internode_data_transport.rs b/crates/ecstore/src/cluster/rpc/internode_data_transport.rs index 48c3bece6f..59e2304f97 100644 --- a/crates/ecstore/src/cluster/rpc/internode_data_transport.rs +++ b/crates/ecstore/src/cluster/rpc/internode_data_transport.rs @@ -32,8 +32,8 @@ use crate::storage_api_contracts::internode::{ use async_trait::async_trait; use http::{HeaderMap, HeaderValue, Method, header::CONTENT_TYPE}; use rustfs_config::{ - DEFAULT_INTERNODE_DATA_TRANSPORT, ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, INTERNODE_DATA_TRANSPORT_TCP, - KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS, + DEFAULT_INTERNODE_DATA_TRANSPORT, ENV_RUSTFS_INTERNODE_DATA_TRANSPORT, INTERNODE_DATA_TRANSPORT_NIXL, + INTERNODE_DATA_TRANSPORT_TCP, KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS, }; use rustfs_rio::{ ChunkReaderBox, HttpChunkReader, HttpReader, HttpWriter, HttpWriterMemoryReservation, HttpWriterMemoryReserver, @@ -65,7 +65,7 @@ const NS_SCANNER_PATH: &str = "/rustfs/rpc/ns_scanner"; const NS_SCANNER_MAX_CAPABILITY_RESPONSE_SIZE: usize = 1024; const PUT_FILE_MAX_CAPABILITY_RESPONSE_SIZE: usize = 1024; const PUT_FILE_LEGACY_CAPABILITY_TTL: Duration = Duration::from_secs(30); -const PUT_FILE_V1_CAPABILITY_TTL: Duration = Duration::from_secs(30); +pub(super) const PUT_FILE_V1_CAPABILITY_TTL: Duration = Duration::from_secs(30); const PUT_FILE_CAPABILITY_PROBE_TIMEOUT: Duration = Duration::from_secs(5); const CONTENT_TYPE_JSON: &str = "application/json"; const CONTENT_TYPE_MSGPACK: &str = "application/msgpack"; @@ -91,7 +91,7 @@ fn unsupported_transport_message(transport: &str) -> String { } #[derive(Debug, Clone, Copy)] -enum PutFileCapabilityState { +pub(super) enum PutFileCapabilityState { LegacyUntil(Instant), V1 { server_epoch: Uuid, revalidate_after: Instant }, } @@ -120,8 +120,8 @@ struct PutFileCapabilityFlight { } #[derive(Debug, Default)] -struct PutFileCapabilityCacheState { - cached: Option, +pub(super) struct PutFileCapabilityCacheState { + pub(super) cached: Option, generation: u64, in_flight: Option, rejected_server_epoch: Option, @@ -130,12 +130,12 @@ struct PutFileCapabilityCacheState { // The registry lock is released before taking an entry lock. Entry guards cover // only cache transitions, never a probe or await; poll-based writers must be // able to reject an epoch atomically with those transitions. -type PutFileCapabilityCacheEntry = Arc>; +pub(super) type PutFileCapabilityCacheEntry = Arc>; static PUT_FILE_CAPABILITY_CACHE: LazyLock>> = LazyLock::new(|| parking_lot::RwLock::new(HashMap::new())); -fn put_file_capability_cache_entry(endpoint: &str) -> PutFileCapabilityCacheEntry { +pub(super) fn put_file_capability_cache_entry(endpoint: &str) -> PutFileCapabilityCacheEntry { if let Some(entry) = PUT_FILE_CAPABILITY_CACHE.read().get(endpoint).cloned() { return entry; } @@ -157,7 +157,7 @@ fn fresh_put_file_capability(state: Option, now: Instant } } -fn reject_put_file_server_epoch(endpoint: &str, server_epoch: Uuid) { +pub(super) fn reject_put_file_server_epoch(endpoint: &str, server_epoch: Uuid) { let entry = PUT_FILE_CAPABILITY_CACHE.read().get(endpoint).cloned(); if let Some(entry) = entry { let mut state = entry.write(); @@ -647,7 +647,7 @@ impl TcpHttpInternodeDataTransport { Ok(response) } - async fn put_file_auth_capability(&self, endpoint: &str) -> Result> { + pub(super) async fn put_file_auth_capability(&self, endpoint: &str) -> Result> { resolve_put_file_auth_capability(endpoint, || async { tokio::time::timeout(PUT_FILE_CAPABILITY_PROBE_TIMEOUT, self.probe_put_file_auth(endpoint)) .await @@ -777,7 +777,7 @@ fn verify_put_file_capability_response(challenge: Uuid, body: &[u8]) -> Result String { +pub(super) fn build_read_file_stream_url(request: &ReadStreamRequest) -> String { format!( "{}{}?disk={}&volume={}&path={}&offset={}&length={}", request.endpoint, @@ -827,7 +827,7 @@ fn build_put_file_capability_url(endpoint: &str, challenge: Uuid) -> String { ) } -struct PutFileAuthWriter { +pub(super) struct PutFileAuthWriter { inner: W, url: String, nonce: Uuid, @@ -840,7 +840,7 @@ struct PutFileAuthWriter { } impl PutFileAuthWriter { - fn new(inner: W, url: String, nonce: Uuid, endpoint: String, server_epoch: Uuid) -> Self { + pub(super) fn new(inner: W, url: String, nonce: Uuid, endpoint: String, server_epoch: Uuid) -> Self { Self { inner, url, @@ -1051,7 +1051,7 @@ fn build_ns_scanner_capability_url(request: &NsScannerCapabilityRequest, challen ) } -fn json_headers() -> HeaderMap { +pub(super) fn json_headers() -> HeaderMap { let mut headers = HeaderMap::new(); headers.insert(CONTENT_TYPE, HeaderValue::from_static(CONTENT_TYPE_JSON)); headers @@ -1074,6 +1074,9 @@ fn build_internode_data_transport_result( { Ok(Arc::new(TcpHttpInternodeDataTransport)) } + Some(transport) if transport.eq_ignore_ascii_case(INTERNODE_DATA_TRANSPORT_NIXL) => { + Ok(Arc::new(super::nixl_internode::NixlInternodeDataTransport::from_env())) + } Some(transport) => Err(unsupported_transport_message(transport)), } } @@ -2732,13 +2735,24 @@ mod tests { fn transport_config_known_backends_are_current_oss_values() { assert_eq!( KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS, - &[DEFAULT_INTERNODE_DATA_TRANSPORT, INTERNODE_DATA_TRANSPORT_TCP] + &[ + DEFAULT_INTERNODE_DATA_TRANSPORT, + INTERNODE_DATA_TRANSPORT_TCP, + INTERNODE_DATA_TRANSPORT_NIXL + ] ); for configured in KNOWN_INTERNODE_DATA_TRANSPORT_BACKENDS { let transport = build_internode_data_transport(Some(configured)).unwrap(); + // NIXL builds everywhere and serves reads over TCP/HTTP until a node + // installs its receive pool; every other known name is the TCP transport. + let expected = if *configured == INTERNODE_DATA_TRANSPORT_NIXL { + INTERNODE_DATA_TRANSPORT_NIXL + } else { + DEFAULT_INTERNODE_DATA_TRANSPORT + }; - assert_eq!(transport.name(), DEFAULT_INTERNODE_DATA_TRANSPORT); + assert_eq!(transport.name(), expected); } } diff --git a/crates/ecstore/src/cluster/rpc/mod.rs b/crates/ecstore/src/cluster/rpc/mod.rs index 756a32de6f..eed9799872 100644 --- a/crates/ecstore/src/cluster/rpc/mod.rs +++ b/crates/ecstore/src/cluster/rpc/mod.rs @@ -20,6 +20,7 @@ pub(crate) mod context_propagation; pub(crate) mod http_auth; pub(crate) mod internode_data_transport; mod network_probe; +pub(crate) mod nixl_internode; pub(crate) mod peer_rest_client; pub(crate) mod peer_s3_client; pub(crate) mod remote_disk; diff --git a/crates/ecstore/src/cluster/rpc/nixl_internode.rs b/crates/ecstore/src/cluster/rpc/nixl_internode.rs new file mode 100644 index 0000000000..e9f9fcff6b --- /dev/null +++ b/crates/ecstore/src/cluster/rpc/nixl_internode.rs @@ -0,0 +1,928 @@ +// 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. + +//! Internode shard reads whose bytes move over NIXL/UCX. +//! +//! The reading node keeps a pool of receive buffers registered with its NIXL +//! agent. For every chunk of a remote shard stream it sends a signed request +//! over the existing internode HTTP control plane naming the shard range, its +//! agent, one registered buffer and a digest of its agent metadata; the serving +//! node reads the range into its own registered staging memory and writes it +//! into that buffer with a NIXL WRITE, then answers with the byte count. The +//! buffer reaches the decoder as a zero-copy `Bytes`. Several chunk requests +//! run per stream so request latency overlaps the transfers. +//! +//! UCX addresses ports by LID or GID, so this works on InfiniBand rails that +//! have no IP addresses. Writes, walks and any stream whose first chunk cannot +//! be served this way use the TCP/HTTP transport. +//! +//! Buffer safety: the serving node may still write into a buffer whose request +//! was abandoned (a dropped reader, chunks past the end of the file). Such +//! buffers are held for [`ABANDONED_BUFFER_HOLD`] before they return to the +//! pool, which covers the serving node's transfer timeout. + +use super::internode_data_transport::{ + InternodeDataTransport, InternodeDataTransportCapabilities, NsScannerCapabilityRequest, NsScannerStreamRequest, + ReadStreamRequest, TcpHttpInternodeDataTransport, WalkDirStreamRequest, WriteStreamRequest, build_read_file_stream_url, + json_headers, +}; +use crate::cluster::rpc::build_auth_headers; +use crate::disk::error::Result; +use crate::disk::{FileReader, FileWriter}; +use crate::storage_api_contracts::internode::NsScannerCapabilityResponse; +use async_trait::async_trait; +use bytes::Bytes; +use futures::future::BoxFuture; +use futures::stream::{FuturesOrdered, Stream}; +use http::{HeaderValue, Method}; +use rustfs_config::{DEFAULT_RUSTFS_NIXL_INTERNODE_DEPTH, ENV_RUSTFS_NIXL_INTERNODE_DEPTH}; +use rustfs_rio::{ChunkReader, ChunkReaderBox}; +use std::io; +use std::pin::Pin; +use std::sync::{Arc, OnceLock}; +use std::task::{Context, Poll}; +use std::time::Duration; +use tokio::io::{AsyncRead, ReadBuf}; +use tracing::debug; +use uuid::Uuid; + +/// Internode route of a NIXL chunk read. +pub const READ_FILE_NIXL_PATH: &str = "/rustfs/rpc/read_file_nixl"; +/// Internode route of a NIXL shard write: the disk's node pulls the named buffers. +pub const WRITE_FILE_NIXL_PATH: &str = "/rustfs/rpc/write_file_nixl"; +/// Comma-separated buffers a NIXL shard write pulls, in file order (signed). +pub const NIXL_BUFFERS_QUERY: &str = "nixl_buffers"; +/// One-time nonce of a NIXL shard write (signed; recorded to refuse replays). +pub const NIXL_NONCE_QUERY: &str = "nixl_nonce"; +/// Buffers a writer fills before it sends a segment; a part's shard file +/// usually fits in one. +const WRITE_SEGMENT_BUFFERS: usize = 4; +/// The route the URL builder emits, replaced by [`READ_FILE_NIXL_PATH`]. +const READ_FILE_STREAM_PATH: &str = "/rustfs/rpc/read_file_stream"; +/// Query parameters of a NIXL chunk read (signed with the URL). +pub const NIXL_AGENT_QUERY: &str = "nixl_agent"; +pub const NIXL_BUFFER_QUERY: &str = "nixl_buffer"; +pub const NIXL_METADATA_SHA256_QUERY: &str = "nixl_md"; +/// The reader's agent metadata, base64; must hash to the signed digest. +pub const NIXL_METADATA_HEADER: &str = "x-rustfs-nixl-metadata"; +/// Bytes the serving node wrote into the buffer; fewer than asked means end of file. +pub const NIXL_BYTES_HEADER: &str = "x-rustfs-nixl-bytes"; + +/// How long a buffer whose request was abandoned stays out of the pool. +pub const ABANDONED_BUFFER_HOLD: Duration = Duration::from_secs(120); +/// Request timeout when the caller sets no stall timeout. +const DEFAULT_CHUNK_TIMEOUT: Duration = Duration::from_secs(60); +const EVENT_NIXL_INTERNODE_FALLBACK: &str = "nixl_internode_fallback"; +const LOG_COMPONENT_INTERNODE: &str = "internode"; +const LOG_SUBSYSTEM_NIXL: &str = "nixl"; + +/// Receive buffers registered with this node's NIXL agent. +pub trait NixlRecvPool: Send + Sync + 'static { + /// This node's agent name. + fn agent_name(&self) -> &str; + /// This node's agent metadata, base64. + fn metadata_base64(&self) -> &str; + /// Lowercase hex SHA-256 of the raw agent metadata. + fn metadata_sha256_hex(&self) -> &str; + /// Size of one receive buffer; one chunk request moves at most this much. + fn chunk_bytes(&self) -> usize; + /// One free buffer, waiting for one when the pool is busy. + fn reserve(&self) -> BoxFuture<'static, io::Result>>; +} + +/// One registered buffer, back in the pool when dropped. Reads land in it; +/// writes stage shard bytes in it for the disk's node to pull. +pub trait NixlRecvBuffer: Send + Sync + 'static { + /// `::
:` as the serving node parses it. + fn descriptor(&self) -> String; + /// The same for the first `len` bytes. + fn descriptor_for(&self, len: usize) -> String; + /// The whole buffer, writable. + fn spare_mut(&mut self) -> &mut [u8]; + /// The first `len` bytes as an owned, zero-copy `Bytes`. + fn into_bytes(self: Box, len: usize) -> io::Result; +} + +static RECV_POOL: OnceLock> = OnceLock::new(); + +/// Installs this node's receive pool; only the first installation wins. +pub fn install_nixl_recv_pool(pool: Arc) -> bool { + RECV_POOL.set(pool).is_ok() +} + +fn recv_pool() -> Option> { + RECV_POOL.get().cloned() +} + +/// Internode transport that reads shard streams over NIXL and delegates +/// everything else to TCP/HTTP. +#[derive(Debug)] +pub struct NixlInternodeDataTransport { + tcp: TcpHttpInternodeDataTransport, + depth: usize, +} + +impl NixlInternodeDataTransport { + pub fn from_env() -> Self { + Self { + tcp: TcpHttpInternodeDataTransport, + depth: rustfs_utils::get_env_usize(ENV_RUSTFS_NIXL_INTERNODE_DEPTH, DEFAULT_RUSTFS_NIXL_INTERNODE_DEPTH).clamp(1, 64), + } + } + + /// A NIXL chunk reader for `request` with its first chunk already landed, + /// or `None` when this read should use TCP/HTTP. + async fn open_nixl(&self, request: &ReadStreamRequest) -> Option { + let pool = recv_pool()?; + if request.length == 0 { + // Unbounded reads need the file size; TCP/HTTP streams them. + return None; + } + let mut reader = NixlChunkReader::new(pool, request.clone(), self.depth); + match futures::future::poll_fn(|cx| reader.state_mut().poll_chunk(cx, usize::MAX)).await { + Ok(Some(first)) => { + reader.state_mut().current = first; + Some(reader) + } + Ok(None) => Some(reader), + Err(error) => { + debug!( + event = EVENT_NIXL_INTERNODE_FALLBACK, + component = LOG_COMPONENT_INTERNODE, + subsystem = LOG_SUBSYSTEM_NIXL, + result = "fallback", + endpoint = %request.endpoint, + error = %error, + "nixl internode read fell back to tcp" + ); + None + } + } + } +} + +#[async_trait] +impl InternodeDataTransport for NixlInternodeDataTransport { + async fn open_read(&self, request: ReadStreamRequest) -> Result { + match self.open_nixl(&request).await { + Some(reader) => Ok(Box::new(reader)), + None => self.tcp.open_read(request).await, + } + } + + async fn open_read_fresh(&self, request: ReadStreamRequest) -> Result { + match self.open_nixl(&request).await { + Some(reader) => Ok(Box::new(reader)), + None => self.tcp.open_read_fresh(request).await, + } + } + + async fn open_read_chunks(&self, request: ReadStreamRequest) -> Result> { + match self.open_nixl(&request).await { + Some(reader) => Ok(Some(Box::new(reader))), + None => self.tcp.open_read_chunks(request).await, + } + } + + async fn open_read_chunks_fresh(&self, request: ReadStreamRequest) -> Result> { + match self.open_nixl(&request).await { + Some(reader) => Ok(Some(Box::new(reader))), + None => self.tcp.open_read_chunks_fresh(request).await, + } + } + + async fn open_write(&self, request: WriteStreamRequest) -> Result { + match recv_pool() { + Some(pool) => Ok(Box::new(NixlFileWriter::new(pool, request))), + None => self.tcp.open_write(request).await, + } + } + + async fn open_walk_dir(&self, request: WalkDirStreamRequest) -> Result { + self.tcp.open_walk_dir(request).await + } + + async fn open_ns_scanner(&self, request: NsScannerStreamRequest) -> Result { + self.tcp.open_ns_scanner(request).await + } + + async fn probe_ns_scanner(&self, request: NsScannerCapabilityRequest) -> Result { + self.tcp.probe_ns_scanner(request).await + } + + async fn probe_ns_scanner_capability(&self, request: NsScannerCapabilityRequest) -> Result { + self.tcp.probe_ns_scanner_capability(request).await + } + + fn name(&self) -> &'static str { + "nixl" + } + + fn capabilities(&self) -> InternodeDataTransportCapabilities { + InternodeDataTransportCapabilities::tcp_http() + } +} + +/// A receive buffer lent to one chunk request. Unless the request completed, +/// dropping it holds the buffer out of the pool for [`ABANDONED_BUFFER_HOLD`] +/// because the serving node may still be writing into it. +struct LentBuffer { + buffer: Option>, +} + +impl LentBuffer { + fn complete(mut self, len: usize) -> io::Result { + let buffer = self.buffer.take().expect("buffer present until completion"); + buffer.into_bytes(len) + } + + /// The peer is done with the buffer: back to the pool now. + fn release(mut self) { + drop(self.buffer.take()); + } +} + +impl Drop for LentBuffer { + fn drop(&mut self) { + if let Some(buffer) = self.buffer.take() { + match tokio::runtime::Handle::try_current() { + Ok(handle) => { + handle.spawn(async move { + tokio::time::sleep(ABANDONED_BUFFER_HOLD).await; + drop(buffer); + }); + } + // No runtime to wait on: never hand the memory back. + Err(_) => std::mem::forget(buffer), + } + } + } +} + +/// Fetches one chunk: the requested length and the bytes that landed. +async fn fetch_chunk(pool: Arc, request: ReadStreamRequest, timeout: Duration) -> io::Result<(usize, Bytes)> { + let buffer = LentBuffer { + buffer: Some(pool.reserve().await?), + }; + let descriptor = buffer.buffer.as_ref().map(|buffer| buffer.descriptor()).unwrap_or_default(); + let mut url = build_read_file_stream_url(&request).replacen(READ_FILE_STREAM_PATH, READ_FILE_NIXL_PATH, 1); + url.push_str(&format!( + "&{NIXL_AGENT_QUERY}={}&{NIXL_BUFFER_QUERY}={}&{NIXL_METADATA_SHA256_QUERY}={}", + urlencoding::encode(pool.agent_name()), + urlencoding::encode(&descriptor), + pool.metadata_sha256_hex() + )); + let mut headers = json_headers(); + headers.insert( + NIXL_METADATA_HEADER, + HeaderValue::from_str(pool.metadata_base64()) + .map_err(|_| io::Error::other("nixl agent metadata is not a header value"))?, + ); + build_auth_headers(&url, &Method::GET, &mut headers)?; + let (status, response_headers, _) = rustfs_rio::internode_http_request(&url, Method::GET, headers, Some(timeout)).await?; + if !status.is_success() { + debug!( + component = LOG_COMPONENT_INTERNODE, + subsystem = LOG_SUBSYSTEM_NIXL, + result = "failed", + status = status.as_u16(), + "nixl internode read refused by peer" + ); + return Err(io::Error::other("nixl internode read refused by peer")); + } + let landed = response_headers + .get(NIXL_BYTES_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .ok_or_else(|| io::Error::other("nixl internode read reply lacks the byte count"))?; + if landed > request.length { + return Err(io::Error::other("nixl internode read reports more bytes than requested")); + } + Ok((request.length, buffer.complete(landed)?)) +} + +type ChunkFuture = BoxFuture<'static, io::Result<(usize, Bytes)>>; + +struct ReaderState { + pool: Arc, + base: ReadStreamRequest, + next: usize, + end: usize, + chunk: usize, + depth: usize, + timeout: Duration, + inflight: FuturesOrdered, + current: Bytes, + done: bool, +} + +impl ReaderState { + fn refill(&mut self) { + while !self.done && self.inflight.len() < self.depth && self.next < self.end { + let len = self.chunk.min(self.end - self.next); + let mut request = self.base.clone(); + request.offset = self.next; + request.length = len; + self.next += len; + self.inflight + .push_back(Box::pin(fetch_chunk(Arc::clone(&self.pool), request, self.timeout))); + } + } + + fn poll_chunk(&mut self, cx: &mut Context<'_>, max: usize) -> Poll>> { + loop { + if !self.current.is_empty() { + let take = self.current.len().min(max.max(1)); + return Poll::Ready(Ok(Some(self.current.split_to(take)))); + } + if self.done { + return Poll::Ready(Ok(None)); + } + self.refill(); + match Pin::new(&mut self.inflight).poll_next(cx) { + Poll::Ready(Some(Ok((asked, bytes)))) => { + if bytes.len() < asked { + // End of file: later chunks hold nothing; their buffers + // are held back as they are dropped. + self.done = true; + self.inflight = FuturesOrdered::new(); + } + if bytes.is_empty() { + self.done = true; + return Poll::Ready(Ok(None)); + } + self.current = bytes; + } + Poll::Ready(Some(Err(error))) => { + self.done = true; + self.inflight = FuturesOrdered::new(); + return Poll::Ready(Err(error)); + } + Poll::Ready(None) => { + self.done = true; + return Poll::Ready(Ok(None)); + } + Poll::Pending => return Poll::Pending, + } + } + } +} + +/// A remote shard stream read over NIXL in pipelined chunks. +pub struct NixlChunkReader { + // The mutex only makes the reader `Sync`; every access goes through `&mut self`. + state: std::sync::Mutex, +} + +impl NixlChunkReader { + fn new(pool: Arc, request: ReadStreamRequest, depth: usize) -> Self { + let chunk = pool.chunk_bytes().max(1); + let timeout = request.stall_timeout.unwrap_or(DEFAULT_CHUNK_TIMEOUT); + Self { + state: std::sync::Mutex::new(ReaderState { + next: request.offset, + end: request.offset.saturating_add(request.length), + pool, + base: request, + chunk, + depth, + timeout, + inflight: FuturesOrdered::new(), + current: Bytes::new(), + done: false, + }), + } + } + + fn state_mut(&mut self) -> &mut ReaderState { + self.state.get_mut().unwrap_or_else(|poisoned| poisoned.into_inner()) + } +} + +impl ChunkReader for NixlChunkReader { + fn poll_read_chunk(self: Pin<&mut Self>, cx: &mut Context<'_>, max: usize) -> Poll>> { + self.get_mut().state_mut().poll_chunk(cx, max) + } +} + +impl AsyncRead for NixlChunkReader { + fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll> { + if buf.remaining() == 0 { + return Poll::Ready(Ok(())); + } + match self.get_mut().state_mut().poll_chunk(cx, buf.remaining()) { + Poll::Ready(Ok(Some(bytes))) => { + buf.put_slice(&bytes); + Poll::Ready(Ok(())) + } + Poll::Ready(Ok(None)) => Poll::Ready(Ok(())), + Poll::Ready(Err(error)) => Poll::Ready(Err(error)), + Poll::Pending => Poll::Pending, + } + } +} + +/// Sends one segment of a shard write: the disk's node pulls `buffers` (in +/// file order) and writes them at the end of the file, creating it unless +/// `append`. The buffers return to the pool only after the node answered. +async fn send_segment( + pool: Arc, + request: WriteStreamRequest, + buffers: Vec<(LentBuffer, usize)>, + append: bool, + last: bool, + timeout: Duration, +) -> io::Result<()> { + let total: usize = buffers.iter().map(|(_, len)| *len).sum(); + let descriptors = buffers + .iter() + .map(|(buffer, len)| { + buffer + .buffer + .as_ref() + .map(|buffer| buffer.descriptor_for(*len)) + .unwrap_or_default() + }) + .collect::>() + .join(","); + let url = format!( + "{}{WRITE_FILE_NIXL_PATH}?disk={}&volume={}&path={}&append={append}&size={}&last={last}&{NIXL_NONCE_QUERY}={}&{NIXL_AGENT_QUERY}={}&{NIXL_BUFFERS_QUERY}={}&{NIXL_METADATA_SHA256_QUERY}={}", + request.endpoint, + urlencoding::encode(&request.disk), + urlencoding::encode(&request.volume), + urlencoding::encode(&request.path), + request.size, + Uuid::new_v4(), + urlencoding::encode(pool.agent_name()), + urlencoding::encode(&descriptors), + pool.metadata_sha256_hex() + ); + let mut headers = json_headers(); + headers.insert( + NIXL_METADATA_HEADER, + HeaderValue::from_str(pool.metadata_base64()) + .map_err(|_| io::Error::other("nixl agent metadata is not a header value"))?, + ); + build_auth_headers(&url, &Method::PUT, &mut headers)?; + let request_started = rustfs_io_metrics::put_stage_timer(); + let (status, response_headers, body) = rustfs_rio::internode_http_request(&url, Method::PUT, headers, Some(timeout)).await?; + rustfs_io_metrics::record_put_object_stage_duration_from("nixl_write_segment_request", request_started); + if !status.is_success() { + debug!( + component = LOG_COMPONENT_INTERNODE, + subsystem = LOG_SUBSYSTEM_NIXL, + result = "failed", + status = status.as_u16(), + body_len = body.len(), + "nixl internode write refused by peer" + ); + return Err(io::Error::other("nixl internode write refused by peer")); + } + let written = response_headers + .get(NIXL_BYTES_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()); + if written != Some(total) { + debug!( + component = LOG_COMPONENT_INTERNODE, + subsystem = LOG_SUBSYSTEM_NIXL, + result = "failed", + written = ?written, + total, + "nixl internode write stored a different byte count" + ); + return Err(io::Error::other("nixl internode write stored a different byte count")); + } + for (buffer, _) in buffers { + buffer.release(); + } + Ok(()) +} + +type SegmentFuture = BoxFuture<'static, io::Result<()>>; +type ReserveFuture = BoxFuture<'static, io::Result>>; + +struct WriterState { + pool: Arc, + base: WriteStreamRequest, + timeout: Duration, + current: Option<(LentBuffer, usize)>, + filled: Vec<(LentBuffer, usize)>, + reserving: Option, + sending: Option, + segments_sent: usize, + shut_down: bool, +} + +impl WriterState { + fn start_segment(&mut self, last: bool) { + let buffers = std::mem::take(&mut self.filled); + let append = self.base.append || self.segments_sent > 0; + self.segments_sent += 1; + self.sending = Some(Box::pin(send_segment( + Arc::clone(&self.pool), + self.base.clone(), + buffers, + append, + last, + self.timeout, + ))); + } + + fn poll_sending(&mut self, cx: &mut Context<'_>) -> Poll> { + match self.sending.as_mut() { + None => Poll::Ready(Ok(())), + Some(sending) => match sending.as_mut().poll(cx) { + Poll::Pending => Poll::Pending, + Poll::Ready(result) => { + self.sending = None; + Poll::Ready(result) + } + }, + } + } + + fn poll_write(&mut self, cx: &mut Context<'_>, data: &[u8]) -> Poll> { + if self.shut_down { + return Poll::Ready(Err(io::Error::other("nixl internode writer is shut down"))); + } + if data.is_empty() { + return Poll::Ready(Ok(0)); + } + if let Err(error) = futures::ready!(self.poll_sending(cx)) { + return Poll::Ready(Err(error)); + } + while self.current.is_none() { + let pool = Arc::clone(&self.pool); + let reserving = self.reserving.get_or_insert_with(|| pool.reserve()); + match reserving.as_mut().poll(cx) { + Poll::Ready(buffer) => { + self.reserving = None; + self.current = Some((LentBuffer { buffer: Some(buffer?) }, 0)); + } + Poll::Pending if !self.filled.is_empty() => { + // Send held buffers before waiting for capacity that their acknowledgement releases. + self.reserving = None; + self.start_segment(false); + futures::ready!(self.poll_sending(cx))?; + } + Poll::Pending => return Poll::Pending, + } + } + let (lent, filled) = self.current.as_mut().expect("buffer reserved above"); + let spare = lent.buffer.as_mut().expect("lent buffer present").spare_mut(); + let n = data.len().min(spare.len() - *filled); + spare[*filled..*filled + n].copy_from_slice(&data[..n]); + *filled += n; + if *filled == spare.len() { + let full = self.current.take().expect("current buffer"); + self.filled.push(full); + if self.filled.len() >= WRITE_SEGMENT_BUFFERS { + self.start_segment(false); + } + } + Poll::Ready(Ok(n)) + } + + fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll> { + if !self.shut_down { + if let Err(error) = futures::ready!(self.poll_sending(cx)) { + return Poll::Ready(Err(error)); + } + if let Some((buffer, filled)) = self.current.take() { + if filled > 0 { + self.filled.push((buffer, filled)); + } else { + buffer.release(); + } + } + self.shut_down = true; + if !self.filled.is_empty() || self.segments_sent == 0 { + // The last segment; with nothing written at all it still creates the file. + self.start_segment(true); + } + } + self.poll_sending(cx) + } +} + +/// A remote shard file written through NIXL: bytes are staged in registered +/// buffers and the disk's node pulls them, a segment at a time. +pub struct NixlFileWriter { + // The mutex only makes the writer `Sync`; every access goes through `&mut self`. + state: std::sync::Mutex, +} + +impl NixlFileWriter { + fn new(pool: Arc, request: WriteStreamRequest) -> Self { + Self { + state: std::sync::Mutex::new(WriterState { + pool, + base: request, + timeout: DEFAULT_CHUNK_TIMEOUT, + current: None, + filled: Vec::new(), + reserving: None, + sending: None, + segments_sent: 0, + shut_down: false, + }), + } + } + + fn state_mut(&mut self) -> &mut WriterState { + self.state.get_mut().unwrap_or_else(|poisoned| poisoned.into_inner()) + } +} + +impl tokio::io::AsyncWrite for NixlFileWriter { + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, data: &[u8]) -> Poll> { + self.get_mut().state_mut().poll_write(cx, data) + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + // Bytes stay staged until a segment fills or the writer shuts down; a + // flush only waits for a segment already on its way. + self.get_mut().state_mut().poll_sending(cx) + } + + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.get_mut().state_mut().poll_shutdown(cx) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct CountingBuffer { + released: Arc, + } + + impl NixlRecvBuffer for CountingBuffer { + fn descriptor(&self) -> String { + "dram:0:0x1000:16".to_owned() + } + + fn descriptor_for(&self, len: usize) -> String { + format!("dram:0:0x1000:{len}") + } + + fn spare_mut(&mut self) -> &mut [u8] { + &mut [] + } + + fn into_bytes(self: Box, len: usize) -> io::Result { + Ok(Bytes::from(vec![7u8; len])) + } + } + + impl Drop for CountingBuffer { + fn drop(&mut self) { + self.released.fetch_add(1, Ordering::SeqCst); + } + } + + /// A buffer backed by a plain vector, for the writer's staging logic. + struct VecBuffer(Vec); + + impl NixlRecvBuffer for VecBuffer { + fn descriptor(&self) -> String { + self.descriptor_for(self.0.len()) + } + + fn descriptor_for(&self, len: usize) -> String { + format!("dram:0:0x2000:{len}") + } + + fn spare_mut(&mut self) -> &mut [u8] { + &mut self.0 + } + + fn into_bytes(self: Box, len: usize) -> io::Result { + Ok(Bytes::copy_from_slice(&self.0[..len])) + } + } + + struct VecPool; + + impl NixlRecvPool for VecPool { + fn agent_name(&self) -> &str { + "test-agent" + } + + fn metadata_base64(&self) -> &str { + "" + } + + fn metadata_sha256_hex(&self) -> &str { + "" + } + + fn chunk_bytes(&self) -> usize { + 8 + } + + fn reserve(&self) -> BoxFuture<'static, io::Result>> { + Box::pin(async { Ok(Box::new(VecBuffer(vec![0; 8])) as Box) }) + } + } + + #[tokio::test] + async fn the_writer_stages_bytes_in_order_until_a_segment_fills() { + use tokio::io::AsyncWriteExt; + let request = WriteStreamRequest { + endpoint: "http://127.0.0.1:1".to_owned(), + disk: "disk".to_owned(), + volume: "volume".to_owned(), + path: "path".to_owned(), + append: false, + size: 20, + }; + let mut writer = NixlFileWriter::new(Arc::new(VecPool), request); + let data: Vec = (0u8..20).collect(); + writer + .write_all(&data) + .await + .expect("staging never sends below a full segment"); + let state = writer.state_mut(); + assert!(state.sending.is_none(), "two full 8-byte buffers stay below the four-buffer segment"); + let staged: Vec = state + .filled + .iter_mut() + .chain(state.current.iter_mut()) + .flat_map(|(lent, len)| lent.buffer.as_mut().expect("buffer").spare_mut()[..*len].to_vec()) + .collect(); + assert_eq!(staged, data); + assert_eq!(state.filled.len(), 2); + assert_eq!(state.current.as_ref().map(|(_, len)| *len), Some(4)); + } + + struct LimitedBuffer { + bytes: VecBuffer, + _permit: tokio::sync::OwnedSemaphorePermit, + } + + impl NixlRecvBuffer for LimitedBuffer { + fn descriptor(&self) -> String { + self.bytes.descriptor() + } + + fn descriptor_for(&self, len: usize) -> String { + self.bytes.descriptor_for(len) + } + + fn spare_mut(&mut self) -> &mut [u8] { + self.bytes.spare_mut() + } + + fn into_bytes(self: Box, len: usize) -> io::Result { + Ok(Bytes::copy_from_slice(&self.bytes.0[..len])) + } + } + + struct LimitedPool(Arc); + + impl NixlRecvPool for LimitedPool { + fn agent_name(&self) -> &str { + "test-agent" + } + + fn metadata_base64(&self) -> &str { + "" + } + + fn metadata_sha256_hex(&self) -> &str { + "" + } + + fn chunk_bytes(&self) -> usize { + 8 + } + + fn reserve(&self) -> ReserveFuture { + let permits = Arc::clone(&self.0); + Box::pin(async move { + let permit = permits.acquire_owned().await.map_err(io::Error::other)?; + Ok(Box::new(LimitedBuffer { + bytes: VecBuffer(vec![0; 8]), + _permit: permit, + }) as Box) + }) + } + } + + #[tokio::test] + async fn the_writer_sends_staged_bytes_when_the_pool_is_full() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + crate::runtime::sources::ensure_test_rpc_secret(); + for chunks in 1..=3 { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("segment listener"); + let address = listener.local_addr().expect("segment address"); + let server = tokio::spawn(async move { + let mut received = 0; + while received < 40 { + let (mut socket, _) = listener.accept().await.expect("segment connection"); + let mut request = Vec::new(); + while !request.windows(4).any(|bytes| bytes == b"\r\n\r\n") { + let mut bytes = [0; 1024]; + let n = socket.read(&mut bytes).await.expect("segment request"); + assert!(n > 0 && request.len() < 16384, "bounded request headers"); + request.extend_from_slice(&bytes[..n]); + } + let request = std::str::from_utf8(&request).expect("request text"); + let target = request.split_whitespace().nth(1).expect("request target"); + let url = url::Url::parse(&format!("http://{address}{target}")).expect("segment URL"); + let descriptors = url + .query_pairs() + .find(|(name, _)| name == NIXL_BUFFERS_QUERY) + .expect("buffers") + .1; + let bytes: usize = descriptors + .split(',') + .map(|descriptor| { + descriptor + .rsplit(':') + .next() + .expect("buffer length") + .parse::() + .expect("numeric length") + }) + .sum(); + assert!(bytes > 0 && bytes <= chunks * 8); + received += bytes; + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-length: 0\r\nconnection: close\r\nx-rustfs-nixl-bytes: {bytes}\r\n\r\n" + ); + socket.write_all(response.as_bytes()).await.expect("segment acknowledgement"); + } + received + }); + let pool = Arc::new(LimitedPool(Arc::new(tokio::sync::Semaphore::new(chunks)))); + let request = WriteStreamRequest { + endpoint: format!("http://{address}"), + disk: "disk".to_owned(), + volume: "volume".to_owned(), + path: "path".to_owned(), + append: false, + size: 40, + }; + let mut writer = NixlFileWriter::new(pool.clone(), request); + let result = tokio::time::timeout(Duration::from_secs(5), async { + writer.write_all(&[7; 40]).await?; + writer.shutdown().await + }) + .await; + if result.is_err() { + server.abort(); + } + result + .expect("a writer must dispatch before exhausting its pool") + .expect("shard write"); + assert_eq!(server.await.expect("segment server"), 40); + assert_eq!(pool.0.available_permits(), chunks, "acknowledged buffers return to the pool"); + } + } + + #[tokio::test(start_paused = true)] + async fn abandoned_buffers_return_only_after_the_hold() { + let released = Arc::new(AtomicUsize::new(0)); + let lent = LentBuffer { + buffer: Some(Box::new(CountingBuffer { + released: Arc::clone(&released), + })), + }; + drop(lent); + tokio::task::yield_now().await; + assert_eq!(released.load(Ordering::SeqCst), 0, "an abandoned buffer must not return at once"); + tokio::time::sleep(ABANDONED_BUFFER_HOLD + Duration::from_secs(1)).await; + tokio::task::yield_now().await; + assert_eq!(released.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn completed_buffers_return_with_their_bytes() { + let released = Arc::new(AtomicUsize::new(0)); + let lent = LentBuffer { + buffer: Some(Box::new(CountingBuffer { + released: Arc::clone(&released), + })), + }; + let bytes = lent.complete(5).expect("bytes"); + assert_eq!(bytes.len(), 5); + assert_eq!(released.load(Ordering::SeqCst), 1); + } +} diff --git a/crates/io-metrics/src/internode_metrics.rs b/crates/io-metrics/src/internode_metrics.rs index a21a49a936..08a55e4661 100644 --- a/crates/io-metrics/src/internode_metrics.rs +++ b/crates/io-metrics/src/internode_metrics.rs @@ -43,6 +43,7 @@ pub const INTERNODE_OPERATION_GRPC_FORCE_UNLOCK: &str = "grpc_force_unlock"; pub const INTERNODE_OPERATION_GRPC_OTHER: &str = "grpc_other"; pub const INTERNODE_TRANSPORT_BACKEND_TCP_HTTP: &str = "tcp-http"; pub const INTERNODE_TRANSPORT_BACKEND_GRPC: &str = "grpc"; +pub const INTERNODE_TRANSPORT_BACKEND_RDMA: &str = "rdma"; pub const INTERNODE_TRANSPORT_BACKEND_UNKNOWN: &str = "unknown"; /// Direction of a msgpack/JSON codec decode, for the JSON-fallback counter: a server decoding a diff --git a/crates/nixl/Cargo.toml b/crates/nixl/Cargo.toml new file mode 100644 index 0000000000..3562597253 --- /dev/null +++ b/crates/nixl/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "rustfs-nixl" +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +version.workspace = true +homepage.workspace = true +description = "Server side of RustFS S3-over-RDMA GETs and PUTs on NIXL (UCX backend): GPU-side and CPU-side NICs by GID, no IPoIB" +keywords = ["rdma", "nixl", "ucx", "gpudirect", "s3"] +categories = ["network-programming"] +documentation = "https://docs.rs/rustfs-nixl/latest/rustfs_nixl/" + +[lints] +workspace = true + +# NIXL/UCX only exists on Linux, and nixl-sys needs a C++ compiler and libclang +# to build. Everything is behind the `sys` feature (enabled by the rustfs `nixl` +# feature) and Linux: without both the crate is empty, so no default or +# workspace build touches vendor C/C++ tooling. +[target.'cfg(target_os = "linux")'.dependencies] +base64-simd = { workspace = true, optional = true } +bytes = { workspace = true, optional = true } +memmap2 = { workspace = true, optional = true } +nixl-sys = { git = "https://github.com/ai-dynamo/nixl", tag = "v1.5.2", optional = true } +parking_lot = { workspace = true, optional = true } +thiserror = { workspace = true, optional = true } +tokio = { workspace = true, features = ["rt-multi-thread", "sync", "time"], optional = true } +tracing = { workspace = true, optional = true } + +[features] +# Compiles the NIXL bindings (nixl-sys: C++ compiler and libclang; the NIXL +# libraries are optional, nixl-sys falls back to a dlopen stub without them). +sys = ["dep:base64-simd", "dep:bytes", "dep:memmap2", "dep:nixl-sys", "dep:parking_lot", "dep:thiserror", "dep:tokio", "dep:tracing"] diff --git a/crates/nixl/src/devices.rs b/crates/nixl/src/devices.rs new file mode 100644 index 0000000000..12b42ac4af --- /dev/null +++ b/crates/nixl/src/devices.rs @@ -0,0 +1,313 @@ +// 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. + +//! Startup health check of the RDMA devices a NIXL agent may use. +//! +//! UCX keeps using a device whose link is down or flapping, and a transfer +//! striped over such a lane fails; NIXL then drops the whole peer. The check +//! reads sysfs (`/sys/class/infiniband//ports/1/...`) and leaves out a +//! device that +//! +//! 1. is missing, or whose port is not `ACTIVE` with physical state `LinkUp`; +//! 2. runs below the best rate among the candidates of its link layer (a +//! degraded 400G port among 800G rails); +//! 3. has lost its link more than `max_link_drops` times more often since boot +//! than the quietest device of its link layer (a rail that flaps every few +//! minutes rarely drops inside a short watch, but its history shows it; +//! comparing with the quietest peer ignores events that hit every rail, +//! such as a switch reboot); +//! 4. loses its link (`counters/link_downed` rises) during the watch window. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +/// Where the kernel exposes RDMA devices. +pub const DEFAULT_SYSFS_ROOT: &str = "/sys/class/infiniband"; + +/// The outcome: devices to use, and devices left out with the reason. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct DeviceCheck { + pub kept: Vec, + pub excluded: Vec<(String, String)>, +} + +#[derive(Debug, Clone)] +struct PortState { + active: bool, + link_up: bool, + rate_gbps: u64, + link_layer: String, + link_downed: Option, +} + +fn read_trimmed(path: &Path) -> Option { + std::fs::read_to_string(path).ok().map(|value| value.trim().to_owned()) +} + +fn read_port(root: &Path, device: &str) -> Option { + let port = root.join(device).join("ports").join("1"); + let state = read_trimmed(&port.join("state"))?; + let phys_state = read_trimmed(&port.join("phys_state")).unwrap_or_default(); + let rate_gbps = read_trimmed(&port.join("rate")) + .and_then(|rate| rate.split_whitespace().next().and_then(|value| value.parse::().ok())) + .map(|rate| rate as u64) + .unwrap_or(0); + Some(PortState { + active: state.contains("ACTIVE"), + link_up: phys_state.contains("LinkUp"), + rate_gbps, + link_layer: read_trimmed(&port.join("link_layer")).unwrap_or_default(), + link_downed: read_trimmed(&port.join("counters").join("link_downed")).and_then(|value| value.parse().ok()), + }) +} + +/// Every RDMA device under `root`, sorted. +fn all_devices(root: &Path) -> Vec { + let mut devices: Vec = std::fs::read_dir(root) + .map(|entries| { + entries + .filter_map(|entry| entry.ok()) + .filter_map(|entry| entry.file_name().into_string().ok()) + .collect() + }) + .unwrap_or_default(); + devices.sort(); + devices +} + +/// Checks `candidates` (every device under `root` when empty): link history +/// against `max_link_drops` (0 skips that test), then a watch of the link +/// counters for `flap_window` (no watch when zero). Blocks for the window. +pub fn check_devices(root: &Path, candidates: &[String], max_link_drops: u64, flap_window: Duration) -> DeviceCheck { + let candidates = if candidates.is_empty() { + all_devices(root) + } else { + candidates.to_vec() + }; + let mut check = DeviceCheck::default(); + let mut healthy: Vec<(String, PortState)> = Vec::new(); + for device in candidates { + match read_port(root, &device) { + None => check.excluded.push((device, "missing".to_owned())), + Some(port) if !port.active => check.excluded.push((device, "port not active".to_owned())), + Some(port) if !port.link_up => check.excluded.push((device, "physical link not up".to_owned())), + Some(port) => healthy.push((device, port)), + } + } + + let mut best_rate: HashMap = HashMap::new(); + for (_, port) in &healthy { + let best = best_rate.entry(port.link_layer.clone()).or_default(); + *best = (*best).max(port.rate_gbps); + } + let mut rated: Vec<(String, PortState)> = Vec::new(); + for (device, port) in healthy { + let best = best_rate.get(&port.link_layer).copied().unwrap_or(0); + if port.rate_gbps < best { + check + .excluded + .push((device, format!("rate {} Gb/s below {} Gb/s of its peers", port.rate_gbps, best))); + } else { + rated.push((device, port)); + } + } + + if max_link_drops > 0 { + let mut quietest: HashMap = HashMap::new(); + for (_, port) in &rated { + if let Some(drops) = port.link_downed { + let entry = quietest.entry(port.link_layer.clone()).or_insert(drops); + *entry = (*entry).min(drops); + } + } + let mut steady = Vec::with_capacity(rated.len()); + for (device, port) in rated { + match (port.link_downed, quietest.get(&port.link_layer)) { + (Some(drops), Some(&floor)) if drops - floor > max_link_drops => check + .excluded + .push((device, format!("link dropped {drops} times since boot, {floor} on its quietest peer"))), + _ => steady.push((device, port)), + } + } + rated = steady; + } + + if !flap_window.is_zero() && !rated.is_empty() { + std::thread::sleep(flap_window); + } + for (device, before) in rated { + if flap_window.is_zero() { + check.kept.push(device); + continue; + } + match read_port(root, &device) { + None => check.excluded.push((device, "disappeared during the link watch".to_owned())), + Some(after) if !after.active || !after.link_up => check + .excluded + .push((device, "link went down during the link watch".to_owned())), + Some(after) => match (before.link_downed, after.link_downed) { + (Some(start), Some(end)) if end > start => check.excluded.push(( + device, + format!( + "link dropped {} time(s) during the {} ms link watch", + end - start, + flap_window.as_millis() + ), + )), + _ => check.kept.push(device), + }, + } + } + check +} + +/// `check_devices` on the kernel's sysfs tree. +pub fn check_system_devices(candidates: &[String], max_link_drops: u64, flap_window: Duration) -> DeviceCheck { + check_devices(&PathBuf::from(DEFAULT_SYSFS_ROOT), candidates, max_link_drops, flap_window) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(0); + + struct FakeSysfs(PathBuf); + + impl FakeSysfs { + fn new() -> Self { + let root = std::env::temp_dir().join(format!( + "rustfs-nixl-devices-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&root).expect("fake sysfs root"); + Self(root) + } + + fn device(&self, name: &str, state: &str, phys: &str, rate: &str, layer: &str, downed: u64) { + let port = self.0.join(name).join("ports").join("1"); + std::fs::create_dir_all(port.join("counters")).expect("port dir"); + std::fs::write(port.join("state"), format!("{state}\n")).expect("state"); + std::fs::write(port.join("phys_state"), format!("{phys}\n")).expect("phys_state"); + std::fs::write(port.join("rate"), format!("{rate}\n")).expect("rate"); + std::fs::write(port.join("link_layer"), format!("{layer}\n")).expect("link_layer"); + self.set_downed(name, downed); + } + + fn set_downed(&self, name: &str, downed: u64) { + let path = self.0.join(name).join("ports").join("1").join("counters").join("link_downed"); + std::fs::write(path, format!("{downed}\n")).expect("link_downed"); + } + } + + impl Drop for FakeSysfs { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + const UP: (&str, &str) = ("4: ACTIVE", "5: LinkUp"); + + #[test] + fn keeps_healthy_rails_and_names_why_others_are_left_out() { + let fs = FakeSysfs::new(); + fs.device("mlx5_0", UP.0, UP.1, "800 Gb/sec (4X XDR)", "InfiniBand", 0); + fs.device("mlx5_5", "1: DOWN", "3: Disabled", "10 Gb/sec (4X SDR)", "InfiniBand", 4); + fs.device("mlx5_7", "2: INIT", UP.1, "800 Gb/sec (4X XDR)", "InfiniBand", 0); + fs.device("mlx5_8", UP.0, UP.1, "400 Gb/sec (4X NDR)", "InfiniBand", 0); + fs.device("mlx5_6", UP.0, UP.1, "400 Gb/sec (4X NDR)", "Ethernet", 0); + let wanted: Vec = ["mlx5_0", "mlx5_5", "mlx5_7", "mlx5_8", "mlx5_6", "mlx5_99"] + .iter() + .map(|name| (*name).to_owned()) + .collect(); + let check = check_devices(&fs.0, &wanted, 0, Duration::ZERO); + assert_eq!(check.kept, vec!["mlx5_0".to_owned(), "mlx5_6".to_owned()]); + let reasons: HashMap<_, _> = check.excluded.into_iter().collect(); + assert_eq!(reasons["mlx5_5"], "port not active"); + assert_eq!(reasons["mlx5_7"], "port not active"); + assert!(reasons["mlx5_8"].starts_with("rate 400 Gb/s below 800"), "{}", reasons["mlx5_8"]); + assert_eq!(reasons["mlx5_99"], "missing"); + assert!(!reasons.contains_key("mlx5_6"), "a RoCE port is not compared with InfiniBand rates"); + } + + #[test] + fn an_empty_list_means_every_device() { + let fs = FakeSysfs::new(); + fs.device("mlx5_1", UP.0, UP.1, "800 Gb/sec (4X XDR)", "InfiniBand", 0); + fs.device("mlx5_0", UP.0, UP.1, "800 Gb/sec (4X XDR)", "InfiniBand", 0); + let check = check_devices(&fs.0, &[], 0, Duration::ZERO); + assert_eq!(check.kept, vec!["mlx5_0".to_owned(), "mlx5_1".to_owned()]); + assert!(check.excluded.is_empty()); + } + + #[test] + fn a_link_that_drops_during_the_watch_is_left_out() { + let fs = FakeSysfs::new(); + fs.device("mlx5_8", UP.0, UP.1, "800 Gb/sec (4X XDR)", "InfiniBand", 52); + fs.device("mlx5_9", UP.0, UP.1, "800 Gb/sec (4X XDR)", "InfiniBand", 22); + let root = fs.0.clone(); + let flapper = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(50)); + let path = root + .join("mlx5_8") + .join("ports") + .join("1") + .join("counters") + .join("link_downed"); + std::fs::write(path, "53\n").expect("bump link_downed"); + }); + let wanted = vec!["mlx5_8".to_owned(), "mlx5_9".to_owned()]; + let check = check_devices(&fs.0, &wanted, 0, Duration::from_millis(300)); + flapper.join().expect("flapper"); + assert_eq!(check.kept, vec!["mlx5_9".to_owned()], "an old link_downed count alone does not exclude"); + assert_eq!(check.excluded.len(), 1); + assert_eq!(check.excluded[0].0, "mlx5_8"); + assert!(check.excluded[0].1.starts_with("link dropped 1 time(s)"), "{}", check.excluded[0].1); + } + + #[test] + fn a_rail_with_a_long_drop_history_is_left_out() { + let fs = FakeSysfs::new(); + for (name, drops) in [ + ("mlx5_0", 0), + ("mlx5_7", 0), + ("mlx5_8", 68), + ("mlx5_9", 22), + ("mlx5_10", 4), + ("mlx5_13", 4), + ] { + fs.device(name, UP.0, UP.1, "800 Gb/sec (4X XDR)", "InfiniBand", drops); + } + let wanted: Vec = ["mlx5_0", "mlx5_7", "mlx5_8", "mlx5_9", "mlx5_10", "mlx5_13"] + .iter() + .map(|name| (*name).to_owned()) + .collect(); + let check = check_devices(&fs.0, &wanted, 16, Duration::ZERO); + assert_eq!(check.kept, vec!["mlx5_0", "mlx5_7", "mlx5_10", "mlx5_13"]); + let reasons: HashMap<_, _> = check.excluded.into_iter().collect(); + assert_eq!(reasons["mlx5_8"], "link dropped 68 times since boot, 0 on its quietest peer"); + assert_eq!(reasons["mlx5_9"], "link dropped 22 times since boot, 0 on its quietest peer"); + + // Events that hit every rail (a switch reboot) exclude nothing. + let fs = FakeSysfs::new(); + for name in ["mlx5_0", "mlx5_7"] { + fs.device(name, UP.0, UP.1, "800 Gb/sec (4X XDR)", "InfiniBand", 40); + } + let wanted = vec!["mlx5_0".to_owned(), "mlx5_7".to_owned()]; + assert_eq!(check_devices(&fs.0, &wanted, 16, Duration::ZERO).kept, wanted); + } +} diff --git a/crates/nixl/src/lib.rs b/crates/nixl/src/lib.rs new file mode 100644 index 0000000000..65c3f6ec72 --- /dev/null +++ b/crates/nixl/src/lib.rs @@ -0,0 +1,1025 @@ +//! Server side of RustFS S3-over-RDMA on NIXL with the UCX backend. +//! +//! A GET carrying the NIXL headers is served by the ordinary read path, and +//! the bytes are moved into the client's registered buffer with NIXL WRITE +//! transfers instead of an HTTP body; a PUT carrying them is read out of the +//! client's buffer with READ transfers. UCX addresses every device by its +//! GID, LID and queue-pair numbers exchanged in the agent metadata, so the +//! GPU-side InfiniBand rails work without IPoIB or a subnet administrator +//! and the CPU-side RoCE ports work without rdma_cm. +//! +//! The client sends three headers with the request: +//! +//! * [`NIXL_AGENT_HEADER`]: its agent name; +//! * [`NIXL_METADATA_HEADER`]: its agent metadata, base64 (may be omitted on +//! later requests once this server has loaded that agent); +//! * [`NIXL_BUFFER_HEADER`]: `::
:`, the +//! registered buffer the object (or range) lands in from offset 0. +//! +//! The reply carries [`RDMA_REPLY_HEADER`] and +//! [`RDMA_BYTES_TRANSFERRED_HEADER`] exactly like the cuObject transport, so a +//! client treats both the same. +//! +//! Everything here needs the `sys` feature (the NIXL bindings) and Linux, where +//! NIXL/UCX exists; without both this crate is empty. +#![cfg(all(feature = "sys", target_os = "linux"))] + +use bytes::Bytes; +use nixl_sys::{Agent, AgentConfig, Backend, MemType, OptArgs, Params, ThreadSync, XferDescList, XferOp, XferStatus}; + +pub mod devices; +mod mem; + +use mem::HostBuffer; +use std::collections::{HashMap, VecDeque}; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; +use std::time::Duration; +use thiserror::Error; +use tokio::sync::Semaphore; + +/// The client's NIXL agent name. +pub const NIXL_AGENT_HEADER: &str = "x-rustfs-nixl-agent"; +/// The client's NIXL agent metadata, base64. +pub const NIXL_METADATA_HEADER: &str = "x-rustfs-nixl-metadata"; +/// The client's registered buffer: `::
:`. +pub const NIXL_BUFFER_HEADER: &str = "x-rustfs-nixl-buffer"; +/// Reply status of the transfer; the same header the cuObject transport uses. +pub const RDMA_REPLY_HEADER: &str = "x-amz-rdma-reply"; +/// Bytes moved into (or out of) the client's buffer. +pub const RDMA_BYTES_TRANSFERRED_HEADER: &str = "x-amz-rdma-bytes-transferred"; +/// Reply status when the server cannot serve the transfer. +pub const RDMA_REPLY_NOT_IMPLEMENTED: u16 = 501; +/// Largest single staging chunk; one transfer moves at most this much per descriptor. +pub const MAX_RDMA_OP_BYTES: usize = 1024 * 1024 * 1024; +/// Ranges a scatter-gather write may carry; NIXL takes one descriptor per range. +pub const MAX_SG_RANGES: usize = 64; +/// The NIXL release this crate is pinned to (`nixl-sys` tag). +pub const NIXL_LIBRARY_VERSION: &str = "1.5.2"; + +#[derive(Debug, Error)] +pub enum NixlError { + #[error("nixl {op} failed: {source}")] + Nixl { + op: &'static str, + #[source] + source: nixl_sys::NixlError, + }, + #[error("nixl {op} failed: {source}")] + Os { + op: &'static str, + #[source] + source: std::io::Error, + }, + #[error("nixl rdma token is malformed: {0}")] + Token(String), + #[error("nixl rdma token buffer ({buffer} bytes) is smaller than the response ({needed} bytes)")] + TokenTooSmall { buffer: u64, needed: u64 }, + #[error("nixl transfer did not complete within {0:?}")] + TransferTimeout(Duration), + #[error("nixl transfer moved {moved} of {expected} bytes")] + ShortTransfer { moved: u64, expected: u64 }, + #[error("nixl staging pool exhausted")] + PoolExhausted, + #[error("nixl read source failed: {0}")] + Source(#[source] std::io::Error), +} + +fn nixl_err(op: &'static str) -> impl FnOnce(nixl_sys::NixlError) -> NixlError { + move |source| NixlError::Nixl { op, source } +} + +/// Where the client's buffer lives. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClientMemory { + Dram, + Vram, +} + +impl ClientMemory { + fn mem_type(self) -> MemType { + match self { + Self::Dram => MemType::Dram, + Self::Vram => MemType::Vram, + } + } +} + +/// The client's transfer target, parsed from the request headers. +#[derive(Debug, Clone)] +pub struct RdmaToken { + raw: String, + /// The client's agent name. + pub agent: String, + /// The client's agent metadata when the request carried it. + pub metadata: Option>, + pub memory: ClientMemory, + pub device: u64, + pub remote_addr: u64, + pub buffer_len: u64, +} + +fn parse_number(field: &str, what: &str) -> Result { + let field = field.trim(); + let parsed = match field.strip_prefix("0x").or_else(|| field.strip_prefix("0X")) { + Some(hex) => u64::from_str_radix(hex, 16), + None => field.parse::(), + }; + parsed.map_err(|_| NixlError::Token(format!("{what} is not a number"))) +} + +impl RdmaToken { + /// Builds a token from the three request headers. + pub fn from_headers(agent: &str, metadata_base64: Option<&str>, buffer: &str) -> Result { + let agent = agent.trim(); + if agent.is_empty() || agent.len() > 128 || !agent.bytes().all(|b| b.is_ascii_graphic()) { + return Err(NixlError::Token("agent name is empty, too long or not printable ASCII".to_owned())); + } + let metadata = match metadata_base64.map(str::trim).filter(|value| !value.is_empty()) { + Some(encoded) => Some( + base64_simd::STANDARD + .decode_to_vec(encoded) + .map_err(|_| NixlError::Token("agent metadata is not base64".to_owned()))?, + ), + None => None, + }; + let mut fields = buffer.trim().split(':'); + let memory = match fields.next().map(|value| value.trim().to_ascii_lowercase()).as_deref() { + Some("dram") | Some("host") => ClientMemory::Dram, + Some("vram") | Some("gpu") => ClientMemory::Vram, + _ => return Err(NixlError::Token("buffer memory type must be dram or vram".to_owned())), + }; + let device = parse_number( + fields + .next() + .ok_or_else(|| NixlError::Token("missing buffer device".to_owned()))?, + "buffer device", + )?; + let remote_addr = parse_number( + fields + .next() + .ok_or_else(|| NixlError::Token("missing buffer address".to_owned()))?, + "buffer address", + )?; + let buffer_len = parse_number( + fields + .next() + .ok_or_else(|| NixlError::Token("missing buffer length".to_owned()))?, + "buffer length", + )?; + if buffer_len == 0 { + return Err(NixlError::Token("zero-length buffer".to_owned())); + } + if remote_addr.checked_add(buffer_len).is_none() { + return Err(NixlError::Token("buffer address overflow".to_owned())); + } + Ok(Self { + raw: format!("{agent}:{}", buffer.trim()), + agent: agent.to_owned(), + metadata, + memory, + device, + remote_addr, + buffer_len, + }) + } + + /// Agent name and buffer, for logs. + pub fn as_str(&self) -> &str { + &self.raw + } +} + +#[derive(Debug, Clone)] +pub struct NixlConfig { + /// This server's agent name; must be unique in the cluster. + pub agent_name: String, + /// UCX device names (`mlx5_9`, ...; NIXL appends the port); empty lets UCX use every device it finds. + pub ucx_devices: Vec, + /// UCX progress workers. + pub num_workers: u32, + /// Size of one staging buffer; one transfer descriptor moves at most this much. + pub chunk_bytes: usize, + /// Total registered staging memory. + pub pool_bytes: usize, + /// Transfers in flight per server at most. + pub max_inflight: usize, + /// Pause between completion polls once spinning stops. + pub poll_interval: Duration, + /// A transfer that has not completed after this long fails the request. + pub transfer_timeout: Duration, + /// Run NIXL's progress thread (see `NixlServer::create_agent`). + pub progress_thread: bool, +} + +impl Default for NixlConfig { + fn default() -> Self { + Self { + agent_name: "rustfs".to_owned(), + ucx_devices: Vec::new(), + num_workers: 1, + chunk_bytes: 64 * 1024 * 1024, + pool_bytes: 1024 * 1024 * 1024, + max_inflight: 256, + poll_interval: Duration::from_micros(50), + transfer_timeout: Duration::from_secs(60), + progress_thread: true, + } + } +} + +/// Registered memory the erasure decode path can emit from in place +/// (the shard arena); scatter-gather writes name ranges of it. +pub struct RegisteredArena { + buffer: HostBuffer, + _registration: nixl_sys::RegistrationHandle, + server: Arc, + len: usize, + id: u64, +} + +impl RegisteredArena { + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + pub fn id(&self) -> u64 { + self.id + } + + pub fn server(&self) -> &Arc { + &self.server + } + + pub fn as_mut_ptr(&self) -> *mut u8 { + self.buffer.as_mut_ptr() + } +} + +impl std::fmt::Debug for RegisteredArena { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RegisteredArena") + .field("id", &self.id) + .field("len", &self.len) + .finish() + } +} + +/// Ranges of one arena, written to consecutive client offsets in one transfer. +pub struct ArenaRanges { + pub arena: Arc, + pub ranges: Vec<(usize, usize)>, +} + +impl ArenaRanges { + pub fn total_len(&self) -> usize { + self.ranges.iter().map(|(_, len)| *len).sum() + } +} + +pub struct ArenaRange { + pub arena: Arc, + pub local_offset: usize, + pub len: usize, +} + +struct Staging { + buffer: HostBuffer, + _registration: nixl_sys::RegistrationHandle, + free: parking_lot::Mutex>, + permits: Semaphore, + chunk_bytes: usize, +} + +/// One registered staging chunk, exclusively owned until dropped. +pub struct StagingChunk { + server: Arc, + index: usize, + len: usize, +} + +impl StagingChunk { + pub fn capacity(&self) -> usize { + self.server.staging.chunk_bytes + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + pub fn append(&mut self, data: &[u8]) -> Result<(), NixlError> { + if self.len + data.len() > self.server.staging.chunk_bytes { + return Err(NixlError::Token("staging append exceeds chunk".to_owned())); + } + let offset = self.index * self.server.staging.chunk_bytes + self.len; + self.server.staging.buffer.write(offset, data)?; + self.len += data.len(); + Ok(()) + } + + pub fn clear(&mut self) { + self.len = 0; + } + + pub fn is_full(&self) -> bool { + self.len >= self.server.staging.chunk_bytes + } + + pub fn staged(&self) -> Result<&[u8], NixlError> { + let offset = self.index * self.server.staging.chunk_bytes; + self.server.staging.buffer.slice(offset, self.len) + } + + pub fn spare_mut(&mut self) -> Result<&mut [u8], NixlError> { + let offset = self.index * self.server.staging.chunk_bytes + self.len; + let len = self.server.staging.chunk_bytes - self.len; + self.server.staging.buffer.slice_mut(offset, len) + } + + pub fn advance(&mut self, n: usize) -> Result<(), NixlError> { + if self.len + n > self.server.staging.chunk_bytes { + return Err(NixlError::Token("staging advance exceeds chunk".to_owned())); + } + self.len += n; + Ok(()) + } + + fn local_addr(&self) -> usize { + self.server.staging.buffer.addr() + self.index * self.server.staging.chunk_bytes + } + + /// Address of the chunk in registered memory, for a peer's transfer descriptor. + pub fn addr(&self) -> usize { + self.local_addr() + } +} + +impl AsRef<[u8]> for StagingChunk { + /// The staged bytes; empty if the chunk's range were ever out of the pool + /// (it cannot be: the index comes from the pool). + fn as_ref(&self) -> &[u8] { + self.staged().unwrap_or(&[]) + } +} + +impl Drop for StagingChunk { + fn drop(&mut self) { + self.server.staging.free.lock().push_back(self.index); + self.server.staging.permits.add_permits(1); + } +} + +/// Copies `data` into the chunk. +pub fn fill_chunk(chunk: &mut StagingChunk, data: &Bytes) -> Result<(), NixlError> { + chunk.append(data) +} + +/// The NIXL release the server is built against, as (major, minor). +pub fn library_version() -> (u32, u32) { + let mut parts = NIXL_LIBRARY_VERSION.split('.').map(|part| part.parse::().unwrap_or(0)); + (parts.next().unwrap_or(0), parts.next().unwrap_or(0)) +} + +/// Timeout of the NIXL progress thread's poll() between passes, in microseconds. +const PROGRESS_THREAD_POLL_US: u64 = 1_000; + +/// One NIXL agent with the UCX backend, a registered staging pool and the +/// remote agents it has loaded. +pub struct NixlServer { + engine: Arc, + staging: Staging, + /// Transfers queued for the completion thread; bounded by `inflight`. + jobs: std::sync::mpsc::Sender, + inflight: Arc, + name: String, + devices: Vec, +} + +/// The agent and everything the completion thread touches. +/// +/// All posting and polling happens on that one thread: the binding takes a +/// process-wide lock on every agent call, and with hundreds of request tasks +/// each spinning on the status of their own transfer the lock became a convoy +/// that throttled the whole node. One thread posts the queued transfers, +/// polls the in-flight ones in a tight loop (which also progresses UCX) and +/// wakes the waiting task through a oneshot channel. +struct Engine { + agent: Agent, + backend: Backend, + /// Remote agents loaded so far, by name, with a hash of the metadata that + /// was loaded (a client that restarts sends new metadata). + remotes: parking_lot::Mutex>, + poll_interval: Duration, + transfer_timeout: Duration, +} + +type BuildLists = Box Result<(XferDescList<'static>, XferDescList<'static>), NixlError> + Send>; + +/// The memory a transfer reads or writes, owned by the completion thread +/// while the library may still touch it and handed back on completion. +type KeepAlive = Box; + +/// One transfer for the completion thread. +struct Job { + op: XferOp, + token: RdmaToken, + build: BuildLists, + keep: KeepAlive, + done: tokio::sync::oneshot::Sender>, +} + +/// A posted transfer the completion thread is polling. +struct Pending { + request: nixl_sys::XferRequest, + /// The remote agent, forgotten if the transfer fails. + agent: String, + keep: Option, + done: Option>>, + deadline: std::time::Instant, +} + +impl std::fmt::Debug for NixlServer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("NixlServer") + .field("name", &self.name) + .field("devices", &self.devices) + .field("chunk_bytes", &self.staging.chunk_bytes) + .finish() + } +} + +fn metadata_hash(metadata: &[u8]) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + metadata.hash(&mut hasher); + hasher.finish() +} + +impl NixlServer { + /// Creates the agent, the UCX backend and the staging pool. + pub fn new(config: &NixlConfig) -> Result, NixlError> { + if config.chunk_bytes == 0 || config.chunk_bytes > MAX_RDMA_OP_BYTES || config.pool_bytes < config.chunk_bytes { + return Err(NixlError::Token("invalid staging configuration".to_owned())); + } + // Request tasks post and poll transfers from every runtime thread. The + // binding serializes its calls with a lock of its own, but the agent is + // configured for concurrent use as well (reader-writer locking, UCX + // workers in multi-thread mode) so correctness does not rest on that + // detail; a UCX without thread support gets the strict mode instead. + let agent = match Self::create_agent(config, ThreadSync::Rw) { + Ok(agent) => agent, + Err(err) => { + tracing::warn!(error = %err, "NIXL agent with rw synchronization failed; using strict"); + Self::create_agent(config, ThreadSync::Strict)? + } + }; + let mut params = Params::from(std::iter::empty::<(&str, &str)>()).map_err(nixl_err("params"))?; + if !config.ucx_devices.is_empty() { + params + .set("device_list", &config.ucx_devices.join(",")) + .map_err(nixl_err("device_list"))?; + } + let backend = agent.create_backend("UCX", ¶ms).map_err(nixl_err("ucx backend"))?; + let chunks = config.pool_bytes / config.chunk_bytes; + let buffer = HostBuffer::new(chunks * config.chunk_bytes)?; + let mut opt_args = OptArgs::new().map_err(nixl_err("opt args"))?; + opt_args.add_backend(&backend).map_err(nixl_err("opt args backend"))?; + let registration = agent + .register_memory(&buffer, Some(&opt_args)) + .map_err(nixl_err("register staging"))?; + let engine = Arc::new(Engine { + agent, + backend, + remotes: parking_lot::Mutex::new(HashMap::new()), + poll_interval: config.poll_interval, + transfer_timeout: config.transfer_timeout, + }); + let (jobs, queue) = std::sync::mpsc::channel(); + let worker = Arc::clone(&engine); + std::thread::Builder::new() + .name("nixl-xfer".to_owned()) + .spawn(move || worker.run(queue)) + .map_err(|source| NixlError::Os { + op: "spawn transfer thread", + source, + })?; + Ok(Arc::new(Self { + engine, + staging: Staging { + buffer, + _registration: registration, + free: parking_lot::Mutex::new((0..chunks).collect()), + permits: Semaphore::new(chunks), + chunk_bytes: config.chunk_bytes, + }, + jobs, + inflight: Arc::new(Semaphore::new(config.max_inflight.max(1))), + name: config.agent_name.clone(), + devices: config.ucx_devices.clone(), + })) + } + + fn create_agent(config: &NixlConfig, thread_sync: ThreadSync) -> Result { + // NIXL's progress thread keeps the UCX worker answering peers while this + // node has no transfer of its own in flight: a node that is the target + // of RDMA writes (internode reads into its buffers) must still complete + // connection handshakes and keepalives, or its peers declare it dead. + // The thread sleeps in poll() on the worker's event descriptor between + // passes; the delay is that poll's timeout (rounded up to whole + // milliseconds). Zero, the binding's default, makes it spin on the + // worker and starve every other caller of the worker lock. + let agent_config = AgentConfig { + num_workers: config.num_workers.max(1), + thread_sync, + enable_prog_thread: config.progress_thread, + pthr_delay_us: PROGRESS_THREAD_POLL_US, + ..AgentConfig::default() + }; + Agent::new_configured(&config.agent_name, &agent_config).map_err(nixl_err("agent")) + } + + pub fn name(&self) -> &str { + &self.name + } + + /// This agent's metadata, for a client that wants to address the server. + pub fn local_metadata(&self) -> Result, NixlError> { + self.engine.agent.get_local_md().map_err(nixl_err("local metadata")) + } + + pub fn chunk_bytes(&self) -> usize { + self.staging.chunk_bytes + } + + pub async fn reserve(self: &Arc, timeout: Duration) -> Result { + let permit = tokio::time::timeout(timeout, self.staging.permits.acquire()) + .await + .map_err(|_| NixlError::PoolExhausted)? + .map_err(|_| NixlError::PoolExhausted)?; + permit.forget(); + let index = self.staging.free.lock().pop_front().ok_or(NixlError::PoolExhausted)?; + Ok(StagingChunk { + server: Arc::clone(self), + index, + len: 0, + }) + } + + pub fn try_reserve(self: &Arc) -> Option { + let permit = self.staging.permits.try_acquire().ok()?; + permit.forget(); + let index = self.staging.free.lock().pop_front()?; + Some(StagingChunk { + server: Arc::clone(self), + index, + len: 0, + }) + } + + pub fn available_chunks(&self) -> usize { + self.staging.permits.available_permits() + } + + /// Registers `len` bytes of host memory the decode path can emit from. + pub fn register_arena(self: &Arc, len: usize) -> Result, NixlError> { + let buffer = HostBuffer::new(len)?; + let mut opt_args = OptArgs::new().map_err(nixl_err("opt args"))?; + opt_args + .add_backend(&self.engine.backend) + .map_err(nixl_err("opt args backend"))?; + let registration = self + .engine + .agent + .register_memory(&buffer, Some(&opt_args)) + .map_err(nixl_err("register arena"))?; + static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + Ok(Arc::new(RegisteredArena { + buffer, + _registration: registration, + server: Arc::clone(self), + len, + id: NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + })) + } + + fn client_window(token: &RdmaToken, remote_offset: u64, len: u64) -> Result { + let end = remote_offset + .checked_add(len) + .ok_or_else(|| NixlError::Token("remote offset overflow".to_owned()))?; + if end > token.buffer_len { + return Err(NixlError::TokenTooSmall { + buffer: token.buffer_len, + needed: end, + }); + } + token + .remote_addr + .checked_add(remote_offset) + .ok_or_else(|| NixlError::Token("remote address overflow".to_owned())) + } + + /// Runs one transfer to completion on the completion thread and hands + /// `keep` back. `build` produces the local and remote descriptor lists + /// (pairing up by index) there, so no NIXL object crosses an await and + /// the future stays `Send` for the spawned pipelines. `keep` owns every + /// buffer the transfer touches: it returns with the result, and a + /// transfer that times out keeps it on the thread until the library + /// completes the transfer, so the memory is never reused under a write + /// that is still running. + async fn transfer(&self, op: XferOp, token: &RdmaToken, keep: K, build: B) -> Result + where + B: FnOnce() -> Result<(XferDescList<'static>, XferDescList<'static>), NixlError> + Send + 'static, + K: std::any::Any + Send + 'static, + { + let _inflight = Arc::clone(&self.inflight) + .acquire_owned() + .await + .map_err(|_| NixlError::Token("server closed".to_owned()))?; + let (done, completion) = tokio::sync::oneshot::channel(); + self.jobs + .send(Job { + op, + token: token.clone(), + build: Box::new(build), + keep: Box::new(keep), + done, + }) + .map_err(|_| NixlError::Token("transfer thread stopped".to_owned()))?; + let keep = completion + .await + .map_err(|_| NixlError::Token("transfer thread stopped".to_owned()))??; + keep.downcast::() + .map(|boxed| *boxed) + .map_err(|_| NixlError::Token("transfer returned another keep-alive".to_owned())) + } + + fn remote_list_for(memory: ClientMemory, device: u64, addr: u64, len: usize) -> Result, NixlError> { + let mut list = XferDescList::new(memory.mem_type()).map_err(nixl_err("remote descriptors"))?; + let addr = usize::try_from(addr).map_err(|_| NixlError::Token("remote address exceeds the platform".to_owned()))?; + list.add_desc(addr, len, device); + Ok(list) + } + + fn local_list(addr: usize, len: usize) -> Result, NixlError> { + let mut list = XferDescList::new(MemType::Dram).map_err(nixl_err("local descriptors"))?; + list.add_desc(addr, len, 0); + Ok(list) + } + + /// Writes the chunk's staged bytes at `offset` of the client's buffer and + /// hands the chunk back. + pub async fn write_to_client_owned( + self: &Arc, + _key: &str, + token: &RdmaToken, + offset: u64, + chunk: StagingChunk, + ) -> Result<(u64, StagingChunk), NixlError> { + let len = chunk.len(); + if len == 0 { + return Ok((0, chunk)); + } + let remote_addr = Self::client_window(token, offset, len as u64)?; + let (local_addr, memory, device) = (chunk.local_addr(), token.memory, token.device); + let chunk = self + .transfer(XferOp::Write, token, chunk, move || { + Ok(( + Self::local_list(local_addr, len)?, + Self::remote_list_for(memory, device, remote_addr, len)?, + )) + }) + .await?; + Ok((len as u64, chunk)) + } + + /// Writes one arena range at `remote_offset`; `keep` stays alive for the transfer. + pub async fn write_to_client_from_arena_owned( + self: &Arc, + _key: &str, + token: &RdmaToken, + remote_offset: u64, + source: ArenaRange, + keep: T, + ) -> Result<(u64, T), NixlError> { + if !Arc::ptr_eq(&source.arena.server, self) { + return Err(NixlError::Token("arena is registered with another server".to_owned())); + } + if source.len == 0 { + return Ok((0, keep)); + } + if source + .local_offset + .checked_add(source.len) + .is_none_or(|end| end > source.arena.len) + { + return Err(NixlError::Token("arena range outside the arena".to_owned())); + } + let remote_addr = Self::client_window(token, remote_offset, source.len as u64)?; + let (local_addr, len, memory, device) = + (source.arena.buffer.addr() + source.local_offset, source.len, token.memory, token.device); + let keep = self + .transfer(XferOp::Write, token, (source, keep), move || { + Ok(( + Self::local_list(local_addr, len)?, + Self::remote_list_for(memory, device, remote_addr, len)?, + )) + }) + .await? + .1; + Ok((len as u64, keep)) + } + + /// Writes several arena ranges to consecutive client offsets starting at + /// `remote_offset` in one transfer; `keep` stays alive for the transfer. + pub async fn write_to_client_sg_owned( + self: &Arc, + _key: &str, + token: &RdmaToken, + remote_offset: u64, + source: ArenaRanges, + keep: T, + ) -> Result<(u64, T), NixlError> { + if !Arc::ptr_eq(&source.arena.server, self) { + return Err(NixlError::Token("arena is registered with another server".to_owned())); + } + if source.ranges.len() > MAX_SG_RANGES { + return Err(NixlError::Token("too many scatter-gather ranges".to_owned())); + } + let total = source.total_len(); + if total == 0 { + return Ok((0, keep)); + } + let remote_base = Self::client_window(token, remote_offset, total as u64)?; + let remote_base = + usize::try_from(remote_base).map_err(|_| NixlError::Token("remote address exceeds the platform".to_owned()))?; + let arena_base = source.arena.buffer.addr(); + for (local_offset, len) in &source.ranges { + if local_offset.checked_add(*len).is_none_or(|end| end > source.arena.len) { + return Err(NixlError::Token("arena range outside the arena".to_owned())); + } + } + let (ranges, memory, device) = (source.ranges.clone(), token.memory, token.device); + let keep = self + .transfer(XferOp::Write, token, (source, keep), move || { + let mut local = XferDescList::new(MemType::Dram).map_err(nixl_err("local descriptors"))?; + let mut remote = XferDescList::new(memory.mem_type()).map_err(nixl_err("remote descriptors"))?; + let mut cursor = 0usize; + for (local_offset, len) in &ranges { + local.add_desc(arena_base + local_offset, *len, 0); + remote.add_desc(remote_base + cursor, *len, device); + cursor += len; + } + Ok((local, remote)) + }) + .await? + .1; + Ok((total as u64, keep)) + } + + /// Reads up to the chunk's capacity from `offset` of the client's buffer + /// into the chunk (RDMA PUT) and hands the chunk back filled. + pub async fn read_from_client_owned( + self: &Arc, + _key: &str, + token: &RdmaToken, + offset: u64, + len: usize, + mut chunk: StagingChunk, + ) -> Result { + if len == 0 { + chunk.clear(); + return Ok(chunk); + } + if len > chunk.capacity() { + return Err(NixlError::Token("read exceeds the staging chunk".to_owned())); + } + let remote_addr = Self::client_window(token, offset, len as u64)?; + chunk.clear(); + let (local_addr, memory, device) = (chunk.local_addr(), token.memory, token.device); + let mut chunk = self + .transfer(XferOp::Read, token, chunk, move || { + Ok(( + Self::local_list(local_addr, len)?, + Self::remote_list_for(memory, device, remote_addr, len)?, + )) + }) + .await?; + chunk.advance(len)?; + Ok(chunk) + } +} + +impl Engine { + /// Loads the client's agent metadata unless this exact metadata is already loaded. + fn ensure_remote(&self, token: &RdmaToken) -> Result<(), NixlError> { + let Some(metadata) = &token.metadata else { + if self.remotes.lock().contains_key(&token.agent) { + return Ok(()); + } + return Err(NixlError::Token(format!( + "agent {:?} is unknown to this server; send {NIXL_METADATA_HEADER}", + token.agent + ))); + }; + let hash = metadata_hash(metadata); + if self.remotes.lock().get(&token.agent) == Some(&hash) { + return Ok(()); + } + // A peer that was loaded before (and dropped after a failed transfer, or + // restarted with new metadata) must be invalidated first: NIXL refuses + // to load an agent it still holds. For a new agent this is a no-op error. + let _ = self.agent.invalidate_remote_md(&token.agent); + let loaded = self + .agent + .load_remote_md(metadata) + .map_err(nixl_err("load remote metadata"))?; + if loaded != token.agent { + return Err(NixlError::Token(format!( + "metadata belongs to agent {loaded:?}, request names {:?}", + token.agent + ))); + } + self.remotes.lock().insert(token.agent.clone(), hash); + Ok(()) + } + + /// Posts one transfer; `None` when it completed before returning. + fn post(&self, op: XferOp, token: &RdmaToken, build: BuildLists) -> Result, NixlError> { + self.ensure_remote(token)?; + let (local, remote) = build()?; + let mut opt_args = OptArgs::new().map_err(nixl_err("opt args"))?; + opt_args.add_backend(&self.backend).map_err(nixl_err("opt args backend"))?; + let request = self + .agent + .create_xfer_req(op, &local, &remote, &token.agent, Some(&opt_args)) + .map_err(nixl_err("create transfer"))?; + // The binding answers `true` while the transfer is still in progress + // and `false` when it completed before returning. + let in_progress = self + .agent + .post_xfer_req(&request, Some(&opt_args)) + .map_err(nixl_err("post transfer"))?; + Ok(in_progress.then_some(request)) + } + + /// Forgets `agent` after a failed transfer, so the next request reloads its + /// metadata and reconnects instead of failing against a peer NIXL dropped. + fn forget_remote(&self, agent: &str) { + self.remotes.lock().remove(agent); + } + + fn admit(&self, job: Job, pending: &mut Vec) { + match self.post(job.op, &job.token, job.build) { + Ok(Some(request)) => pending.push(Pending { + request, + agent: job.token.agent.clone(), + keep: Some(job.keep), + done: Some(job.done), + deadline: std::time::Instant::now() + self.transfer_timeout, + }), + Ok(None) => { + let _ = job.done.send(Ok(job.keep)); + } + Err(err) => { + self.forget_remote(&job.token.agent); + let _ = job.done.send(Err(err)); + } + } + } + + /// The completion thread: posts queued transfers and polls the in-flight + /// ones until the server is dropped. + fn run(self: Arc, queue: std::sync::mpsc::Receiver) { + let mut pending: Vec = Vec::new(); + // Transfers past their deadline: the task was told, the request stays + // alive until the library completes it so its buffers are never + // reused under a transfer that is still running. + let mut expired: Vec = Vec::new(); + let mut idle_polls = 0u32; + loop { + // Take new work: block when nothing is in flight. + if pending.is_empty() && expired.is_empty() { + match queue.recv() { + Ok(job) => self.admit(job, &mut pending), + Err(_) => return, + } + } + loop { + match queue.try_recv() { + Ok(job) => self.admit(job, &mut pending), + Err(std::sync::mpsc::TryRecvError::Empty) => break, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + if pending.is_empty() && expired.is_empty() { + return; + } + break; + } + } + } + let now = std::time::Instant::now(); + let mut progressed = false; + let mut index = 0; + while index < pending.len() { + match self.agent.get_xfer_status(&pending[index].request) { + Ok(XferStatus::Success) => { + progressed = true; + let mut transfer = pending.swap_remove(index); + Self::finish(&mut transfer, Ok(())); + } + Ok(XferStatus::InProgress) if now >= pending[index].deadline => { + // The task gets the error; the request and the buffers it + // references stay here until the library completes it. + let mut transfer = pending.swap_remove(index); + Self::finish(&mut transfer, Err(NixlError::TransferTimeout(self.transfer_timeout))); + tracing::warn!( + agent = %"nixl", + timeout_ms = self.transfer_timeout.as_millis() as u64, + "nixl transfer timed out; its request is kept until the library completes it" + ); + expired.push(transfer); + } + Ok(XferStatus::InProgress) => index += 1, + Err(err) => { + progressed = true; + let mut transfer = pending.swap_remove(index); + self.forget_remote(&transfer.agent); + Self::finish(&mut transfer, Err(nixl_err("transfer status")(err))); + } + } + } + expired.retain(|transfer| matches!(self.agent.get_xfer_status(&transfer.request), Ok(XferStatus::InProgress))); + if progressed { + idle_polls = 0; + } else { + idle_polls = idle_polls.saturating_add(1); + if idle_polls > 64 { + std::thread::sleep(self.poll_interval); + } else { + std::thread::yield_now(); + } + } + } + } + + fn finish(transfer: &mut Pending, result: Result<(), NixlError>) { + let Some(done) = transfer.done.take() else { + return; + }; + let result = match result { + // The buffers go back with a completed transfer; a caller that + // stopped waiting drops them here, after the library is done. + Ok(()) => Ok(transfer.keep.take().expect("buffers travel with the transfer")), + Err(err) => Err(err), + }; + let _ = done.send(result); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn token_parses_memory_device_address_and_length() { + let token = RdmaToken::from_headers("loader-7", None, "vram:4:0x7f0000000000:1073741824").expect("token"); + assert_eq!(token.agent, "loader-7"); + assert_eq!(token.memory, ClientMemory::Vram); + assert_eq!(token.device, 4); + assert_eq!(token.remote_addr, 0x7f00_0000_0000); + assert_eq!(token.buffer_len, 1 << 30); + assert!(token.metadata.is_none()); + let host = RdmaToken::from_headers("a", Some("AQID"), "dram:0:4096:0x100").expect("token"); + assert_eq!(host.memory, ClientMemory::Dram); + assert_eq!(host.metadata.as_deref(), Some(&[1u8, 2, 3][..])); + } + + #[test] + fn token_rejects_malformed_headers() { + assert!(RdmaToken::from_headers("", None, "vram:0:1:1").is_err()); + assert!(RdmaToken::from_headers("a", None, "disk:0:1:1").is_err()); + assert!(RdmaToken::from_headers("a", None, "vram:0:1:0").is_err()); + assert!(RdmaToken::from_headers("a", None, "vram:0:0xffffffffffffffff:2").is_err()); + assert!(RdmaToken::from_headers("a", Some("not base64!"), "vram:0:1:1").is_err()); + assert!(RdmaToken::from_headers("a", None, "vram:0:1").is_err()); + } + + #[test] + fn client_window_checks_the_buffer_bounds() { + let token = RdmaToken::from_headers("a", None, "dram:0:1000:100").expect("token"); + assert_eq!(NixlServer::client_window(&token, 40, 60).expect("fits"), 1040); + assert!(matches!( + NixlServer::client_window(&token, 50, 60), + Err(NixlError::TokenTooSmall { + buffer: 100, + needed: 110 + }) + )); + } +} diff --git a/crates/nixl/src/mem.rs b/crates/nixl/src/mem.rs new file mode 100644 index 0000000000..25c532eb97 --- /dev/null +++ b/crates/nixl/src/mem.rs @@ -0,0 +1,112 @@ +//! Page-aligned host memory handed to NIXL for registration. The unsafe +//! surface of the crate lives here: disjoint range views and the +//! memory-region trait the binding needs. + +// SAFETY: the allowance is scoped to this module: the two range views state +// their invariant inline, and `as_ptr` is the binding's required unsafe +// trait method returning the mapping's own pointer. +#![allow(unsafe_code)] + +use crate::NixlError; +use memmap2::{MmapMut, MmapRaw}; +use nixl_sys::{MemType, MemoryRegion, NixlDescriptor}; + +/// Page-aligned, zero-filled host memory registered with the agent. An +/// anonymous mapping, so the pool stays outside the global allocator; held as +/// `MmapRaw` because chunks write through `&self`. +pub(crate) struct HostBuffer { + map: MmapRaw, +} + +impl std::fmt::Debug for HostBuffer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("HostBuffer").field("len", &self.len()).finish() + } +} + +impl HostBuffer { + pub(crate) fn new(len: usize) -> Result { + let map = MmapMut::map_anon(len.max(1)).map_err(|source| NixlError::Os { + op: "staging allocation", + source, + })?; + Ok(Self { map: map.into() }) + } + + pub(crate) fn len(&self) -> usize { + self.map.len() + } + + pub(crate) fn addr(&self) -> usize { + self.map.as_ptr() as usize + } + + pub(crate) fn as_mut_ptr(&self) -> *mut u8 { + self.map.as_mut_ptr() + } + + pub(crate) fn check(&self, offset: usize, len: usize) -> Result<(), NixlError> { + if offset.checked_add(len).is_none_or(|end| end > self.len()) { + return Err(NixlError::Token("staging range outside the buffer".to_owned())); + } + Ok(()) + } + + pub(crate) fn slice(&self, offset: usize, len: usize) -> Result<&[u8], NixlError> { + self.check(offset, len)?; + // SAFETY: the range is inside the mapping; callers own disjoint ranges. + Ok(unsafe { std::slice::from_raw_parts(self.map.as_ptr().add(offset), len) }) + } + + #[allow(clippy::mut_from_ref, reason = "chunk ranges are disjoint and owned by one chunk at a time")] + pub(crate) fn slice_mut(&self, offset: usize, len: usize) -> Result<&mut [u8], NixlError> { + self.check(offset, len)?; + // SAFETY: as above; the caller holds the only handle to this range. + Ok(unsafe { std::slice::from_raw_parts_mut(self.map.as_mut_ptr().add(offset), len) }) + } + + pub(crate) fn write(&self, offset: usize, data: &[u8]) -> Result<(), NixlError> { + self.slice_mut(offset, data.len())?.copy_from_slice(data); + Ok(()) + } +} + +impl MemoryRegion for HostBuffer { + unsafe fn as_ptr(&self) -> *const u8 { + self.map.as_ptr() + } + + fn size(&self) -> usize { + self.len() + } +} + +impl NixlDescriptor for HostBuffer { + fn mem_type(&self) -> MemType { + MemType::Dram + } + + fn device_id(&self) -> u64 { + 0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn buffer_is_page_aligned_zeroed_and_bounds_checked() { + let buffer = HostBuffer::new(3 * 4096 + 5).expect("map"); + assert_eq!(buffer.len(), 3 * 4096 + 5); + assert_eq!(buffer.addr() % 4096, 0); + assert!(buffer.slice(0, buffer.len()).expect("whole").iter().all(|&b| b == 0)); + + buffer.write(4096, b"chunk").expect("write"); + assert_eq!(buffer.slice(4096, 5).expect("read"), b"chunk"); + assert!(buffer.slice(buffer.len() - 1, 2).is_err()); + assert!(buffer.write(usize::MAX, b"x").is_err()); + + assert_eq!(HostBuffer::new(0).expect("empty").len(), 1); + } +} diff --git a/crates/rio/src/http_reader.rs b/crates/rio/src/http_reader.rs index 5c7078f9ec..a3a1e90373 100644 --- a/crates/rio/src/http_reader.rs +++ b/crates/rio/src/http_reader.rs @@ -706,6 +706,33 @@ const fn http_client_cache() -> &'static arc_swap::ArcSwapOp &CLIENT_CACHE } +/// Sends one internode request with the pooled internode client and returns +/// its status, headers and body. Meant for small control exchanges whose data +/// moves out of band (for example over NIXL); large bodies use `HttpReader`. +pub async fn internode_http_request( + url: &str, + method: Method, + headers: HeaderMap, + timeout: Option, +) -> io::Result<(reqwest::StatusCode, HeaderMap, Bytes)> { + let client = get_http_client::(url).await?; + let mut request = client.request(method.clone(), url).headers(headers); + if let Some(timeout) = timeout { + request = request.timeout(timeout); + } + let response = request + .send() + .await + .map_err(|err| io::Error::other(format!("internode {method} request failed: {err}")))?; + let status = response.status(); + let headers = response.headers().clone(); + let body = response + .bytes() + .await + .map_err(|err| io::Error::other(format!("internode {method} response body failed: {err}")))?; + Ok((status, headers, body)) +} + async fn get_http_client(url: &str) -> io::Result { let tuning = internode_http_client_tuning(); // Reuse HTTP connection pools while honoring the configured internode proxy diff --git a/docs/README.md b/docs/README.md index ee5a225cdb..1fcc0e17fc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,7 @@ collection: - [Read-only BTF declaration inspection](operations/btf-prototype-inspection.md) — bounded prototypes and scalar member layouts, explicit void handling, and independent native references. - [Internode HTTP streaming transport](operations/internode-http-transport.md) — protocol selection, pooled connection isolation, and distributed read validation. +- [cuObject S3-over-RDMA GET](operations/cuobject-s3-over-rdma.md) — optional `cuobject` feature: GET straight into client GPU/host memory via `x-amz-rdma-token`; build, settings, wire contract. - [Erasure shard size](operations/erasure-shard-size.md) — `RUSTFS_ERASURE_SHARD_BYTES`: larger, aligned shards for new objects; rules and memory cost. - [Object data cache fill on PUT](operations/object-data-cache-fill-on-put.md) — `RUSTFS_OBJECT_DATA_CACHE_FILL_ON_PUT`: insert plain streaming PUT bodies so the first GET hits. diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 4ac6d32e5f..c2265219fe 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -58,6 +58,7 @@ Required headings and strings in these files are asserted by `scripts/check_arch | [kms-bulk-rekey-contract.md](kms-bulk-rekey-contract.md) | changing the bulk envelope re-wrap sweep, its admin endpoints, the re-wrap primitive, or which objects a rekey may touch | | [remote-credential-sealing-adr.md](remote-credential-sealing-adr.md) | adding, reading, or persisting a stored remote credential (replication target, remote tier, on-demand migration source), or needing the sealed-envelope format, the mixed-version rules, or the reason this is worth doing in one deployment and not in another | | [tier-stats-contract.md](tier-stats-contract.md) | changing what `GET /rustfs/admin/v3/tier-stats` returns, adding a tier accounting source, or wiring a metric to a remote tier request | +| [s3-over-rdma-llm-serving.md](s3-over-rdma-llm-serving.md) | you change the RDMA or NIXL data path, the large-PUT path, or a per-bucket ETag setting, or you build or run a client that loads model weights or offloads KV cache to RustFS over RDMA, such as the SGLang weight loader and HiCache backend | ## Support and compatibility matrices (release-facing, keep current) diff --git a/docs/architecture/s3-over-rdma-llm-serving.md b/docs/architecture/s3-over-rdma-llm-serving.md new file mode 100644 index 0000000000..3ec700a004 --- /dev/null +++ b/docs/architecture/s3-over-rdma-llm-serving.md @@ -0,0 +1,62 @@ +# S3 over RDMA for LLM serving + +**Use this when:** you change the RDMA or NIXL data path, the large-PUT path, or a per-bucket ETag setting, or you build a client that loads model weights or offloads KV cache to RustFS over RDMA. + +This document describes the design and the invariants of RustFS's S3-over-RDMA data path. It does not repeat settings or the wire format. Those live in the operations guides: + +- [nixl-s3-over-rdma.md](../operations/nixl-s3-over-rdma.md): NIXL build, settings, wire contract, device check, internode NIXL, large-PUT tuning, per-bucket ETag API. +- [cuobject-s3-over-rdma.md](../operations/cuobject-s3-over-rdma.md): the cuObject transport. + +## Goals + +- Move object bytes between RustFS and GPU or host memory with one-sided RDMA, while the request stays an ordinary signed S3 call. Authentication, authorization, range resolution, quota and erasure coding stay unchanged. +- Serve the two LLM-serving workloads at line rate: + - **Model weight loading:** about 1.5 TB per replica, read many times. + - **KV-cache offload:** many 10-60 MB objects written once per prefill and read back by any node. +- Run the whole data plane, including internode shard traffic, on GPU-side InfiniBand rails that have no IP addresses. + +## Server components + +| Layer | Code | Role | +|---|---|---| +| Client last hop, cuObject | `crates/cuobject/src/lib.rs`, `rustfs/src/app/object/cuobject.rs` | First transport: `x-amz-rdma-token`, NVIDIA cuObject server library through the `cuobject` bindings from crates.io. Kept as a compile-time alternative. | +| Client last hop, NIXL | `crates/nixl/src/lib.rs` (`RdmaToken::from_headers`, `ensure_remote`), `crates/nixl/src/mem.rs` | NIXL/UCX transport selected by the `nixl` feature. The client names a registered `dram` or `vram` buffer; the server WRITEs (GET) or READs (PUT) it. | +| Shared pipeline | `rustfs/src/app/object/cuobject.rs` | Segment fan-out of large GETs, staging chunks, shard arena, completion handling. The same pipeline serves both transports; only the transfer layer differs. | +| Device health | `crates/nixl/src/devices.rs` | Startup check that leaves out RDMA devices that are down, slow or flapping. | +| Internode, NIXL | `crates/ecstore/src/cluster/rpc/nixl_internode.rs`, `rustfs/src/storage/rpc/nixl_read.rs` | `RUSTFS_INTERNODE_DATA_TRANSPORT=nixl`: signed control request over HTTP, data over NIXL, for shard reads and writes. | +| Transport selection | `crates/ecstore/src/cluster/rpc/internode_data_transport.rs` | `tcp-http`, `tcp` or `nixl`. Internode RDMA runs over NIXL. | +| Erasure read path | `crates/ecstore/src/erasure/codec/shard_buf.rs`, `crates/ecstore/src/erasure/codec/shard_emit.rs`, `crates/ecstore/src/erasure/coding/bitrot.rs` | Two buffer generations per shard slot, zero-copy emit from registered shard buffers, bitrot verification off the decode task. | +| PUT path | `rustfs/src/app/object/put.rs`, `rustfs/src/app/multipart_usecase.rs`, `crates/rio/src/etag_reader.rs` (`with_md5_offload`), `crates/rio/src/hash_reader.rs` (`EtagAlgorithm`) | Zero-copy RDMA PutObject body, read-ahead, zero-copy UploadPart chunks, ETag MD5 on a blocking-pool thread, per-bucket XXH3 ETags. | +| Per-bucket ETag | `crates/ecstore/src/bucket/etag.rs` (`set_bucket_xxh3_etag`, `bucket_uses_xxh3_etag`), `rustfs/src/admin/handlers/etag.rs` | `etag.json` bucket-metadata entry; admin `GET/PUT/DELETE /rustfs/admin/v3/bucket-etag/{bucket}`. | +| Per-bucket durability | `crates/ecstore/src/bucket/durability.rs` | Existing `strict`, `relaxed` or `none` override. A KV-cache bucket is the intended user of a relaxed tier. | + +## Design decisions + +- **Signed S3 request, RDMA payload.** The client sends a normal signed S3 request whose body is empty. Three headers name its NIXL agent, its agent metadata and one registered buffer. The reply comes back only after the last transfer completed, so the client may use its buffer as soon as the response arrives. Clients sign with `UNSIGNED-PAYLOAD`, because the payload never crosses HTTP. +- **NIXL/UCX replaced cuObject as the default.** UCX addresses devices by GID, LID and queue-pair numbers carried in the agent metadata. That works on the GPU-side InfiniBand rails without IPoIB or a subnet manager, and on RoCE without `rdma_cm`. cuObject stays as a compile-time alternative. +- **GPU or host memory.** A `vram:::` buffer works when the client's NIC can reach GPU memory (GPUDirect over dma-buf with the open NVIDIA driver; `nvidia_peermem` is not needed). The server does not need to know which kind it is writing into. +- **Ranges are first class.** A ranged GET lands at offset 0 of the named buffer. Clients split large objects into ranged requests spread over servers to raise parallelism. +- **Internode traffic on the same rails.** With `nixl` internode transport, every shard read and write between servers also moves over NIXL. The control request stays on the internode HTTP connection and binds the transfer with a signed metadata digest (and a one-time nonce for writes), so a replayed request cannot redirect a transfer. +- **Large PUTs are CPU-bound, not link-bound.** The fixes went to the CPU path: offloaded MD5, zero-copy bodies and allocator settings. The admission limit stays at 32 large PUTs per server; raising it to 64 or 128 gained nothing. +- **Per-bucket settings instead of process-wide switches.** XXH3 ETags and relaxed durability suit a KV-cache bucket and break assumptions of ordinary S3 clients, so both are bucket properties. A request that carries Content-MD5 always gets an MD5 ETag. + +## Invariants + +- `Agent::post_xfer_req` in `nixl-sys` returns `true` while a transfer is in progress. Treating `true` as done refills staging chunks under the NIC and corrupts data. Verify any transport change with one round into a zeroed buffer, because repeated rounds mask the bug. +- Every agent runs NIXL's progress thread, including agents that only receive RDMA writes; peers otherwise declare it dead. +- A client exports its agent metadata after registering every buffer it will name. The server reloads metadata when its hash changes, so a request that still carries an older copy can make the server swap back to it. Register all buffers before the first transfer. +- A registered buffer that an abandoned request named stays out of the pool longer than the peer's transfer timeout. +- Direct-I/O shard writers must be shut down at the end of every NIXL write segment (`finish_segment_file` in `rustfs/src/storage/rpc/nixl_read.rs`); otherwise the trailing sub-alignment bytes are lost. +- A multipart upload keeps the ETag algorithm its bucket had when the upload was created. + +## Clients + +Clients live outside this repository. Two LLM-serving clients were built against this path and shaped its requirements: + +- **Model weight loading into GPU memory.** The loader plans a checkpoint into whole-tensor units, fetches each unit with several ranged NIXL GETs spread over the servers straight into GPU memory, and shares it with the other ranks over NCCL. No checkpoint byte touches disk or host memory, so ranged GETs into `vram` buffers and many concurrent requests per client are the hot path. +- **KV-cache offload.** A hierarchical-cache backend writes groups of KV pages (tens of MB each) once per prefill and reads them back from any node. It needs cheap existence checks, PUTs that return only after the bytes are durable enough for the bucket's durability setting, and ETags that do not cost an MD5 per object, hence per-bucket XXH3 ETags and relaxed durability. + +## Open items + +- **Stable per-model namespace in KV object names.** Clients should key KV objects by model ID, revision and KV dtype rather than a local path, and use a bucket per model. +- **Write admission for bursts.** Large-PUT admission stays at 32 per server; clients that offload KV in bursts should cap their own concurrent PUTs below it. diff --git a/docs/operations/cuobject-s3-over-rdma.md b/docs/operations/cuobject-s3-over-rdma.md new file mode 100644 index 0000000000..75cd87a826 --- /dev/null +++ b/docs/operations/cuobject-s3-over-rdma.md @@ -0,0 +1,122 @@ +# cuObject S3-over-RDMA GET (last hop into client memory) + +RustFS can serve `GetObject` over NVIDIA's cuObject protocol: the client +(for example the NIXL `OBJ` plugin used by the SGLang `--load-format rdma` +loader) registers its GPU or host buffer with the cuObject client library, +puts the resulting RDMA token in the `x-amz-rdma-token` request header, and +RustFS writes the object bytes straight into that buffer with one-sided RDMA +writes. The HTTP response carries no body. + +This is the Phase 1 "last hop" of the S3-over-RDMA plan. It is independent of +the internode shard transport selected by `RUSTFS_INTERNODE_DATA_TRANSPORT`; +either can be enabled on its own. + +## Build + +The feature links NVIDIA's cuObject *server* library (`libcuobjserver`, part +of the CUDA apt repository as `libcuobjserver` / `libcuobjserver-dev`) through +the [`cuobject`](https://crates.io/crates/cuobject) bindings; their +`cuobject-sys` build script generates the FFI with bindgen (needs libclang) +and compiles a C++ wrapper over the library. It is off by default and +Linux-only: + +```bash +# CUOBJSERVER_ROOT points at a prefix holding include/cuobjserver.h and lib/libcuobjserver.so +CUOBJSERVER_ROOT=/usr cargo build --release -p rustfs --features cuobject +``` + +The binary dynamically links `libcuobjserver.so.2`; keep it on the library +path at run time. Without the feature every setting below is ignored and +tokens are left untouched, so the client falls back to a normal HTTP GET. + +## Settings + +| Variable | Default | Meaning | +| --- | --- | --- | +| `RUSTFS_CUOBJECT_ENABLE` | `false` | Start the cuObject servers and honour `x-amz-rdma-token`. | +| `RUSTFS_CUOBJECT_ADDRS` | local endpoint hosts | Comma-separated RDMA (RoCE/IB) IPs to serve from; one cuObject server per address. | +| `RUSTFS_CUOBJECT_PORT` | `18515` | cuObject control port; the client never dials it directly with the DC transport. | +| `RUSTFS_CUOBJECT_CHUNK_BYTES` | `16 MiB` | Staging chunk: the object is streamed into registered host memory in chunks of this size and each chunk is written to the client with one RDMA operation. Max 1 GiB. | +| `RUSTFS_CUOBJECT_INFLIGHT_WRITES` | `3` | Staging chunks per GET: while one chunk is being RDMA-written the decoder keeps filling the next ones, so the stripe loop never waits for a write. Each costs one chunk of the pool; a busy pool degrades to fewer chunks rather than failing the GET. | +| `RUSTFS_CUOBJECT_POOL_BYTES` | `1 GiB` | Registered staging pool per server; bounds concurrent RDMA GETs to about `pool / (chunk x inflight)`. | +| `RUSTFS_CUOBJECT_NUM_DCIS` | `128` | DC initiators the server library opens. | +| `RUSTFS_CUOBJECT_ASYNC_TRANSFERS` | `true` | Complete transfers through the library's asynchronous mode: the write is submitted with a handle and the task waits on the channel's completion descriptor, so no blocking thread is held per transfer. `false` keeps one blocking library call per transfer. | + +Invalid settings or a server library failure stop startup. A node whose +endpoint host is not an RDMA-capable address logs `cuobject_service_state +state=skipped` and serves plain HTTP. + +## Wire contract + +Request: a normal SigV4-signed `GET` with `x-amz-content-sha256: +UNSIGNED-PAYLOAD`, a `Range` header covering the client buffer, and +`x-amz-rdma-token: ::::::`. + +Response: the usual `GetObject` headers (ETag included) with an empty body +and `Content-Length: 0`, plus: + +- `x-amz-rdma-reply`: `200` for a full object, `206` for a range (matches the + HTTP status, which is `206` whenever a range was requested). +- `x-amz-rdma-bytes-transferred`: bytes written into the client buffer; absent + when zero. + +Writes are pipelined: chunk N is written by its own task while the decoder +fills chunk N+1; completions are collected in issue order. Each chunk is +owned by its blocking write until the DMA returns, so on a failure the GET +waits for the outstanding writes before their chunks return to the pool; +a staging slot is never reused while the NIC may still read it. + +A malformed token is ignored (the GET is served over HTTP); the client treats +the missing reply header as "declined". A token buffer smaller than the +response is rejected with `InvalidRange`; RDMA write failures surface as +`InternalError` and nothing is sent over HTTP. Stage metrics record the +transfer under `s3_handler/rdma_transfer`. + +## PUT and UploadPart over RDMA + +A `PutObject` or `UploadPart` with an empty HTTP body and +`x-amz-rdma-token` (SigV4-signed, `x-amz-content-sha256: UNSIGNED-PAYLOAD`, +`Content-Length: 0`) takes its bytes from the client's registered buffer: the +object (or part) length is the token's buffer length, RustFS RDMA-reads it +into staging chunks one chunk ahead of the writer, and the bytes then go +through the ordinary PUT pipeline (checksums, erasure encode, fill-on-PUT +when enabled). The response is the usual one plus `x-amz-rdma-reply: 200` +and `x-amz-rdma-bytes-transferred`. A malformed token is ignored and the +empty body is stored as an empty object, exactly as without the feature; +the NIXL client treats a reply without `x-amz-rdma-reply` as declined. + +## Validation + +1. `RUSTFS_CUOBJECT_ENABLE=true RUSTFS_CUOBJECT_ADDRS=` on each node + and confirm `cuobject_service_state state=started` in the log. +2. On the client, point `CUFILE_ENV_PATH_JSON` at a `cufile.json` whose + `rdma_dev_addr_list` names the client's RDMA IP. +3. Run the SGLang loader with `--load-format rdma` and + `"accelerated": true` in `--model-loader-extra-config`; the NIXL `OBJ` + backend then advertises `VRAM_SEG` and every tensor arrives in GPU memory + without an HTTP body. + +The generic `x-amz-rdma-token` client lives in NIXL 1.6.0 (git `2ff2509f`, +2026-11-02) or newer. The published `nixl-cu13` 1.5.2 wheel ships only the +Dell vendor engine, so with it `accelerated=true` fails at GPU staging +registration; build NIXL from source with `aws-cpp-sdk-s3`, `aws-cpp-sdk-s3-crt` +and a `cuobjclient-.pc` on `PKG_CONFIG_PATH`, then run with +`PYTHONPATH=/lib/python3/dist-packages` and +`NIXL_PLUGIN_DIR=/lib//plugins`. + +### Results (four servers on RoCE, 2026-11-03) + +Direct cuObject client (one GET of the 988 MB model file, RDMA write into +GPU memory, byte-exact against the HTTP body): + +| Path | Throughput | +| --- | --- | +| RDMA GET into GPU memory | 2.1-2.2 GB/s | +| RDMA GET into pinned host memory | 2.2 GB/s | +| HTTP GET into host memory (same client) | 1.9-2.3 GB/s | + +Both paths are bound by the single client link and the erasure-coded read +from four trays; the RDMA path removes the HTTP body copy and the host-to-GPU +copy. Inside the SGLang loader (NIXL, 256 MiB VRAM staging) the model loaded +at 3.0 GB/s; the error paths (undersized token buffer -> `InvalidRange`, +malformed token -> plain HTTP body) behave as described above. diff --git a/docs/operations/nixl-s3-over-rdma.md b/docs/operations/nixl-s3-over-rdma.md new file mode 100644 index 0000000000..7e22d343b7 --- /dev/null +++ b/docs/operations/nixl-s3-over-rdma.md @@ -0,0 +1,214 @@ +# S3-over-RDMA on NIXL/UCX + +RustFS can serve S3 GETs and PUTs over RDMA with NIXL (NVIDIA Inference Xfer +Library) and its UCX backend instead of the cuObject library described in +[cuobject-s3-over-rdma.md](cuobject-s3-over-rdma.md). The request stays an +ordinary signed S3 call; the client adds its NIXL agent name, agent metadata +and registered buffer in headers, the server moves the bytes with NIXL WRITE +(GET) or READ (PUT) transfers, and the reply carries the same +`x-amz-rdma-reply` and `x-amz-rdma-bytes-transferred` headers as the cuObject +transport. UCX addresses every device by the GID, LID and queue-pair numbers +in the agent metadata, so the GPU-side InfiniBand rails work without IPoIB or +a subnet administrator and the CPU-side RoCE ports work without rdma_cm. + +The server-side pipeline (segment fan-out, staging chunks, shard arena, +per-write stages) is the one the cuObject transport uses; only the transfer +layer differs. The two transports are compile-time alternatives: a build with +the `nixl` feature uses NIXL for every RDMA request, even when `cuobject` is +also enabled. + +## Build + +- Cargo feature `nixl` on the `rustfs` crate (`--features rdma,nixl`); the + `rustfs-nixl` crate depends on the `nixl-sys` binding from the NIXL + repository at tag `v1.5.2`. +- `NIXL_PREFIX` points at a prefix with `include/` (the NIXL C++ headers of + that tag) and `lib/` holding `libnixl.so`, `libnixl_build.so`, + `libnixl_common.so`, `libserdes.so`, `libstream.so` and + `lib/plugins/libplugin_UCX.so`. The `nixl-cu13` wheel ships the libraries + (under `site-packages/.nixl_cu13.mesonpy.libs/`); the headers come from the + repository. `bindgen` needs `libclang` at build time. +- At run time the server needs `LD_LIBRARY_PATH` on that `lib/` and + `NIXL_PLUGIN_DIR` on `lib/plugins`. + +## Settings + +| Variable | Default | Meaning | +|---|---|---| +| `RUSTFS_NIXL_ENABLE` | `false` | Serve requests that carry the NIXL headers over NIXL. | +| `RUSTFS_NIXL_AGENT_NAME` | `rustfs-` | This node's agent name; must be unique in the cluster. | +| `RUSTFS_NIXL_UCX_DEVICES` | all devices | Comma-separated UCX device names (`mlx5_9,mlx5_10`; NIXL adds the port); pin the agent to the rails that reach the clients. With `UCX_MAX_RMA_RAILS=2` in the server's environment, UCX stripes every write across two of these ports and the client must have registered its buffer on both of them, or the transfer fails and the GET is declined. | +| `RUSTFS_NIXL_NUM_WORKERS` | `1` | UCX progress workers of the agent. | +| `RUSTFS_NIXL_CHUNK_BYTES` | `16 MiB` | Staging chunk, one transfer descriptor at most. | +| `RUSTFS_NIXL_POOL_BYTES` | `1 GiB` | Registered staging memory. | +| `RUSTFS_NIXL_MAX_INFLIGHT` | `256` | Transfers in flight per node. | +| `RUSTFS_NIXL_TRANSFER_TIMEOUT_SECS` | `60` | A transfer that has not completed by then fails the request instead of hanging it. | +| `RUSTFS_NIXL_DEVICE_CHECK` | `true` | Check the devices at startup and leave out unhealthy ones (see below). | +| `RUSTFS_NIXL_DEVICE_MAX_LINK_DROPS` | `16` | Leave out a device whose link dropped this many times more since boot than the quietest device of its link layer; `0` skips this test. | +| `RUSTFS_NIXL_DEVICE_FLAP_WINDOW_MS` | `3000` | How long the startup check watches the link counters; `0` skips the watch. | +| `RUSTFS_INTERNODE_DATA_TRANSPORT` | `tcp-http` | `nixl` moves internode shard reads over NIXL too (see below). | +| `RUSTFS_NIXL_INTERNODE_DEPTH` | `4` | Internode chunk requests in flight per remote shard stream. | +| `RUSTFS_CUOBJECT_PUT_READ_AHEAD` | `4` | Staging chunks read from the client's buffer ahead of the PUT body's consumer; each holds one chunk of the pool. | + +The pipeline settings `RUSTFS_CUOBJECT_GET_FANOUT`, +`RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES`, `RUSTFS_CUOBJECT_GET_FANOUT_BUDGET`, +`RUSTFS_CUOBJECT_INFLIGHT_WRITES` and `RUSTFS_CUOBJECT_SHARD_ARENA_BYTES` +apply unchanged. + +### Large-object PUT tuning + +Several settings outside the NIXL variables decide PUT throughput on large hosts: + +- `RUSTFS_RUNTIME_WORKER_THREADS`: the runtime defaults to at most 16 worker threads, sized for small-object PUTs. A large PUT runs its part's MD5 and erasure encoding inline on those workers in bursts of 20-70 ms, so with 16 workers a task woken by a finished NIXL transfer waits behind them while most cores stay idle. On the 256-core staging servers 128 workers doubled 16-stream PUT throughput (12.5 to 26 GB/s). +- `MIMALLOC_ALLOW_THP=0`: with transparent huge pages in `madvise` mode, the allocator's huge-page requests for the per-stripe buffers send the kernel into direct compaction, which took about a third of the CPU during PUTs. +- `MIMALLOC_PURGE_DELAY=-1`: the allocator keeps freed memory for reuse instead of returning it to the kernel. Every PUT allocates and frees tens of megabytes of stripe and staging buffers, and returning them made the kernel fault in and zero fresh pages, shoot down TLBs and compact memory under its zone lock. Keeping them raised a 4-client PUT of 57 MB objects from about 14 to about 18 GB/s on two servers. The process's resident memory then stays at its peak. +- `RUSTFS_OBJECT_DATA_CACHE_FILL_ON_PUT=false` for write-heavy buckets such as an LLM KV cache: fill-on-put copies every PUT body that fits the cache entry limit into the object data cache, which cost about 30-40 ms per 57 MB object. Without it, an RDMA PutObject body also stays in the staging chunks it was read into (no copy). +- `RUSTFS_OBJECT_ETAG_MD5_OFFLOAD_MIN_BYTES` (default 8 MiB, `0` turns it off): bodies at least this large compute their ETag MD5 on a blocking-pool thread while the body streams into the erasure encoder, instead of inline before it. The ETag and the Content-MD5 check are unchanged; the PUT fails before commit on a mismatch. +- `RUSTFS_OBJECT_DIRECT_IO_WRITE_ENABLE=true`: shard files are written with O_DIRECT instead of through the page cache, which otherwise costs a copy into freshly allocated, zeroed cache pages, zone-lock contention and compaction on every write. With four PUT clients on two servers (57 MB objects) it more than doubled the aggregate (7 to 16-21 GB/s) while reads of the just-written objects, now served by the drives, stayed within about 10%. The NIXL internode shard writes finish every file with a writer shutdown, which the direct writer needs to write its trailing sub-alignment bytes. +- A per-bucket XXH3 ETag for buckets whose clients never treat the ETag as an MD5, such as an LLM KV cache: objects written to the bucket without Content-MD5 get an XXH3-128 ETag in the same 32-hex-digit form, an order of magnitude cheaper to compute. It halved the single-stream PUT of 57 MB objects (105 to 55 ms) but did not raise the saturated aggregate. Other buckets keep MD5 ETags, so ordinary S3 clients (rclone checksums, SDKs that verify an upload against the returned ETag) are unaffected. See "Per-bucket ETag algorithm" below. + +`RUSTFS_OBS_PUT_STAGE_METRICS_ENABLED=true` together with `RUSTFS_OBS_GET_STAGE_LOCAL_SUMMARY_ENABLED=true` writes the PUT and erasure stage timings (body wait, encode, internode segment writes, part commit phases) into the local stage summary file without a metrics exporter. + +### Per-bucket ETag algorithm + +A bucket's ETag algorithm is stored as a RustFS extension entry (`etag.json`) in its bucket metadata and set through the admin API with `ConfigUpdateAdminAction`: + +```bash +# Use XXH3-128 ETags for objects written to the bucket without Content-MD5 +curl -X PUT "http:///rustfs/admin/v3/bucket-etag/" -d '{"algorithm":"xxh3"}' # md5 | xxh3 + +# Read it back ("algorithm": null means no setting: MD5 ETags) +curl "http:///rustfs/admin/v3/bucket-etag/" + +# Clear it (MD5 ETags again) +curl -X DELETE "http:///rustfs/admin/v3/bucket-etag/" +``` + +- It applies to PutObject and UploadPart; CopyObject, tier restore and internal writes keep MD5. +- A request that carries Content-MD5 always gets an MD5 ETag and the exact check. Some SDKs add Content-MD5 to every PutObject and UploadPart on their own (boto3 before 1.36, for example), so their objects keep MD5 ETags, and the MD5 cost, even in an XXH3 bucket; the writer that should benefit must not send it. +- A multipart upload keeps the algorithm the bucket had when the upload was created, so all its parts hash alike; the multipart ETag is formed from the part ETags as usual. +- The setting propagates like the per-bucket durability override: immediately on the node that applied it, to peers through the bucket-metadata reload notification, and at the latest with the 15-minute metadata refresh. Objects already written keep their ETags. + +## Wire contract + +Request headers (GET, PUT, UploadPart): + +| Header | Value | +|---|---| +| `x-rustfs-nixl-agent` | The client's agent name (printable ASCII, up to 128 bytes). | +| `x-rustfs-nixl-metadata` | The client's agent metadata (`get_local_md`), base64. May be omitted once this server has loaded that agent; a server that does not know the agent declines the request. A restarted client sends new metadata, which replaces the old. | +| `x-rustfs-nixl-buffer` | `::
:`: the registered buffer the object (or the requested range) lands in from offset 0, or is read from for a PUT. Address and length are decimal or `0x` hex. | + +Reply headers: `x-amz-rdma-reply` (`200`, `206` for a range, `501` when the +transfer could not run), `x-amz-rdma-bytes-transferred`. The HTTP body is +empty; the reply is sent after the last transfer completed, so the client may +read its buffer as soon as the response arrives. The server never needs the +client to load the server's metadata. + +## Device health check + +UCX keeps using a device whose link is down or flapping, and a transfer +striped over that lane fails; NIXL then drops the whole peer. Before the +agent is created the server reads `/sys/class/infiniband//ports/1` for +every device in `RUSTFS_NIXL_UCX_DEVICES` (every RDMA device on the node +when the list is empty) and leaves out a device that + +1. is missing, or whose port is not `ACTIVE` with physical state `LinkUp`; +2. runs below the best rate of the candidates of its link layer; +3. lost its link more than `RUSTFS_NIXL_DEVICE_MAX_LINK_DROPS` times more + often since boot than the quietest device of its link layer (a rail + that flaps every few minutes rarely drops inside a short watch, and + comparing with the quietest peer ignores events that hit every rail, + such as a switch reboot); +4. loses its link during the watch window. + +One log line (`event=cuobject_service_state state=device_check`) lists the +kept devices and every excluded one with its reason, as a warning when any +is excluded. If no device passes, startup fails. The check runs once; a +device that fails later stays in use until the next restart. Clients choose +their own devices. + +## Internode reads and writes over NIXL + +With `RUSTFS_INTERNODE_DATA_TRANSPORT=nixl` the shard reads and writes between +servers also move over NIXL, so a cluster can run its whole data plane on the +GPU-side InfiniBand rails, which have no IP addresses. The control request +stays on the internode HTTP connection; only the data moves over the rails. + +- For each chunk of a remote shard stream the reading node sends a signed + `GET /rustfs/rpc/read_file_nixl` with the usual disk, volume, path, offset + and length, plus its agent name (`nixl_agent`), one buffer registered with + its agent (`nixl_buffer`, same format as `x-rustfs-nixl-buffer`) and the + SHA-256 of its agent metadata (`nixl_md`). The metadata itself travels in + `x-rustfs-nixl-metadata` and must hash to the signed digest, so a replayed + request cannot point the transfer at another endpoint. +- The serving node reads the range with `pread` into one of its registered + staging chunks, writes it into the named buffer with a NIXL WRITE and + answers `200` with `x-rustfs-nixl-bytes` (fewer than asked means end of + file). The buffer reaches the decoder as a zero-copy `Bytes`. +- `RUSTFS_NIXL_INTERNODE_DEPTH` (default `4`) chunk requests run per stream; + a chunk is one staging chunk (`RUSTFS_NIXL_CHUNK_BYTES`). +- Shard writes: the writing node stages the file's bytes in registered + buffers and, once the file is complete (or every four buffers for a large + file), sends a signed `PUT /rustfs/rpc/write_file_nixl` naming them + (`nixl_buffers`, in file order), its agent, the metadata digest and a + one-time `nixl_nonce`. The disk's node records the nonce (a replay is + refused), pulls every buffer with a NIXL READ and writes it through the + same disk writer as the TCP path (create, or append for later segments), + checks the declared size on the last segment and flushes. The buffers + return to the writer's pool only after the node answered. +- Directory walks, unbounded reads and any read stream whose first chunk + fails use TCP/HTTP, which also keeps its typed errors (file not found and + so on). A build without the `nixl` feature answers the route with `404`, + which the reader treats the same way. +- A receive buffer whose request was abandoned (a dropped reader, chunks past + the end of the file) stays out of the pool for two minutes, longer than + the serving node's transfer timeout, because the peer may still write it. +- Every node's agent runs NIXL's progress thread. A node that is the target + of RDMA writes must keep answering UCX connection handshakes and + keepalives even with no transfer of its own in flight; without it peers + declare the node dead and NIXL drops the agent ("remote agent ... was + disconnected after transfer request creation"). After any failed + transfer the server forgets the peer and reloads its metadata on the next + request. + +Rails: name every rail of the node in `RUSTFS_NIXL_UCX_DEVICES`, minus any +that is down, and set `UCX_MAX_RMA_RAILS=8` so host-memory transfers stripe +across them; GPU clients register only their GPU's rail. + +## Implementation notes + +- `Agent::post_xfer_req` in the `nixl-sys` binding returns `true` while the + transfer is still in progress and `false` when it completed before + returning. The server polls `get_xfer_status` only in the first case. The + opposite reading treats every transfer as complete at post time, refills + the staging chunk before the NIC has read it, and the client receives the + next chunk's bytes at the earlier offset; the reply also arrives before the + data. Repeated rounds of the same object hide that, so a verification run + uses one round into a zeroed buffer. +- A client that never polls its agent needs NIXL's progress thread (the + binding's `Agent::new` enables it; `new_configured` only with + `enable_prog_thread`), because the server's endpoint finishes its UCX + connection handshake only when the client's worker progresses. Without it + every transfer to that client stays in progress until the timeout. +- The binding serializes every agent call with a lock of its own; the agent + is nevertheless created with reader-writer synchronization so correctness + does not rest on that detail. +- Transfers are posted and polled by one completion thread (`nixl-xfer`); + request tasks wait on a oneshot. The binding takes a process-wide lock on + every agent call, and hundreds of tasks each spinning on their own + transfer's status made that lock a convoy. +- Keep the page cache for served shards (`RUSTFS_OBJECT_FILE_CACHE_RECLAIM_READ_ENABLE=false`) + and size the staging pool for the load (`RUSTFS_NIXL_POOL_BYTES`, 8 GiB + for 16 concurrent streams). +- The chunk-reuse contract can be checked without RustFS: a writer fills a + remote buffer from a small pool of chunks, refilling each as soon as NIXL + reports its transfer complete, and the target verifies every word against + its offset. + +## Validation + +Check a transport change with a client that fetches an object into a +zero-filled GPU or host buffer through this contract and compares it with a +plain HTTP GET of the same object. Verify with a single round: later rounds +rewrite the same bytes and mask a transfer that completed early. diff --git a/rustfs/Cargo.toml b/rustfs/Cargo.toml index a18e2e1f85..b45541d1e1 100644 --- a/rustfs/Cargo.toml +++ b/rustfs/Cargo.toml @@ -90,6 +90,10 @@ rio-v2 = ["rustfs-ecstore/rio-v2"] # release build; the stack refuses to compile without debug assertions, and # `scripts/check_connect_release_boundary.py` keeps every release-reachable feature from enabling it. gateway-stack = ["dep:rustfs-gateway", "dep:rustfs-gateway-adapter", "dep:rustfs-gateway-stream"] +# Linux-only cuObject S3-over-RDMA GET into client (GPU) memory; needs libcuobjserver. +cuobject = ["dep:rustfs-cuobject", "rustfs-cuobject/server"] +# NIXL/UCX transport for S3-over-RDMA; replaces cuobject when both are enabled. +nixl = ["dep:rustfs-nixl", "rustfs-nixl/sys"] pyroscope = ["rustfs-obs/pyroscope", "dep:pyroscope", "dep:object", "dep:symbolic-demangle"] # Tokio runtime telemetry. Requires `--cfg tokio_unstable`; use `make build-profiling`. dial9 = ["rustfs-obs/dial9"] @@ -258,6 +262,8 @@ rustfs-config = { workspace = true, features = ["notify", "server-config-model"] rustfs-crypto = { workspace = true } rustfs-credentials = { workspace = true } rustfs-ecstore = { workspace = true } +rustfs-cuobject = { workspace = true, optional = true } +rustfs-nixl = { workspace = true, optional = true } rustfs-filemeta.workspace = true rustfs-iam = { workspace = true } rustfs-keystone = { workspace = true } diff --git a/rustfs/src/app/multipart_usecase/upload_part.rs b/rustfs/src/app/multipart_usecase/upload_part.rs index 20ce24881c..eb909fee78 100644 --- a/rustfs/src/app/multipart_usecase/upload_part.rs +++ b/rustfs/src/app/multipart_usecase/upload_part.rs @@ -142,6 +142,20 @@ impl DefaultMultipartUsecase { reject_veeam_sosapi_mutation(|| self.object_store(), &bucket, &key).await?; validate_table_catalog_object_mutation(&bucket, &key).await?; + // cuObject S3-over-RDMA UploadPart: an empty HTTP body plus + // `x-amz-rdma-token` means the part bytes are read from the client's + // registered buffer (see `object::cuobject::rdma_put_body`). + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + let (body, content_length, rdma_put) = match crate::app::object::cuobject::rdma_token_for_request(&req.headers) { + Some(token) if content_length.unwrap_or(0) == 0 => { + let (body, total) = crate::app::object::cuobject::rdma_put_body(&bucket, &key, &token, true)?; + let total = i64::try_from(total).map_err(|_| S3Error::new(S3ErrorCode::EntityTooLarge))?; + (Some(body), Some(total), Some(total)) + } + _ => (body, content_length, None), + }; + #[cfg(not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")))] + let rdma_put: Option = None; let size = resolve_upload_part_size(content_length, body.as_ref())?; if let Some(size) = size { reject_oversize_single_upload(size)?; @@ -412,7 +426,20 @@ impl DefaultMultipartUsecase { // XXHash3/64/128 and SHA-512 have no typed UploadPartOutput field; echo the // server-computed part checksum as a raw response header (#1261). - let upload_part_extra_checksum_headers = crate::app::object_usecase::additional_checksum_echo_pairs(&opts.want_checksum); + #[cfg_attr( + not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")), + allow(unused_mut, reason = "mutated only by the cuObject RDMA branch") + )] + let mut upload_part_extra_checksum_headers = + crate::app::object_usecase::additional_checksum_echo_pairs(&opts.want_checksum); + #[cfg(not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")))] + let _ = rdma_put; + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + if let Some(moved) = rdma_put { + upload_part_extra_checksum_headers.push((crate::app::object::cuobject::RDMA_REPLY_HEADER, "200".to_owned())); + upload_part_extra_checksum_headers + .push((crate::app::object::cuobject::RDMA_BYTES_TRANSFERRED_HEADER, moved.to_string())); + } let output = UploadPartOutput { server_side_encryption: requested_sse.map(ServerSideEncryption::from), diff --git a/rustfs/src/app/object/cuobject.rs b/rustfs/src/app/object/cuobject.rs new file mode 100644 index 0000000000..b977a1fd94 --- /dev/null +++ b/rustfs/src/app/object/cuobject.rs @@ -0,0 +1,1471 @@ +// 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. + +//! S3-over-RDMA GET through NVIDIA cuObject (`--features cuobject`). +//! +//! A GET carrying `x-amz-rdma-token` is served by the ordinary read path up to +//! the final byte stream; those bytes are staged in registered host memory and +//! RDMA-written into the client's buffer instead of streamed over HTTP. One +//! cuObject server exists per configured RDMA address; requests round-robin +//! over them. Everything before the body (authentication, range resolution, +//! decryption, decompression, erasure decode, bitrot verification) is shared +//! with the HTTP path, so the data is identical; only the last hop differs. + +use crate::app::storage_api::object_usecase::io::DynReader; +use crate::app::storage_api::object_usecase::runtime::get_global_endpoints_opt; +#[cfg(not(feature = "nixl"))] +use crate::app::storage_api::object_usecase::runtime::global_rustfs_port; +use bytes::Bytes; +use futures::Stream; +use http::HeaderMap; +use rustfs_config::{ + DEFAULT_ERASURE_SHARD_BYTES, DEFAULT_RUSTFS_CUOBJECT_GET_FANOUT, DEFAULT_RUSTFS_CUOBJECT_GET_FANOUT_BUDGET, + DEFAULT_RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES, DEFAULT_RUSTFS_CUOBJECT_INFLIGHT_WRITES, + DEFAULT_RUSTFS_CUOBJECT_PUT_READ_AHEAD, DEFAULT_RUSTFS_CUOBJECT_SHARD_ARENA_BYTES, ENV_ERASURE_SHARD_BYTES, + ENV_RUSTFS_CUOBJECT_GET_FANOUT, ENV_RUSTFS_CUOBJECT_GET_FANOUT_BUDGET, ENV_RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES, + ENV_RUSTFS_CUOBJECT_INFLIGHT_WRITES, ENV_RUSTFS_CUOBJECT_PUT_READ_AHEAD, ENV_RUSTFS_CUOBJECT_SHARD_ARENA_BYTES, +}; +/// The transport this build moves bytes with: NIXL/UCX when the `nixl` +/// feature is on, otherwise NVIDIA cuObject. Both crates expose the same +/// surface, so the pipeline below is written once against these names. +#[cfg(feature = "nixl")] +pub(crate) mod transport { + pub(crate) use rustfs_nixl::{ + ArenaRanges, MAX_RDMA_OP_BYTES, MAX_SG_RANGES, NIXL_AGENT_HEADER, NIXL_BUFFER_HEADER, NIXL_METADATA_HEADER, + NixlError as Error, NixlServer as Server, RDMA_BYTES_TRANSFERRED_HEADER, RDMA_REPLY_HEADER, RdmaToken, RegisteredArena, + StagingChunk, library_version, + }; +} +#[cfg(not(feature = "nixl"))] +pub(crate) mod transport { + pub(crate) use rustfs_cuobject::{ + ArenaRanges, CuObjectError as Error, CuObjectServer as Server, MAX_RDMA_OP_BYTES, MAX_SG_RANGES, + RDMA_BYTES_TRANSFERRED_HEADER, RDMA_REPLY_HEADER, RDMA_TOKEN_HEADER, RdmaToken, RegisteredArena, StagingChunk, + library_version, + }; +} +use crate::app::storage_api::object_usecase::rdma::{RegisteredSlabArena, ShardBuf, ShardEmitter, install_shard_arena}; +use crate::app::storage_api::s3::dto::StreamingBlob; +use crate::app::storage_api::s3::stream::{ByteStream, RemainingLength}; +use crate::app::storage_api::s3::{S3Error, S3ErrorCode, S3Result, StdError}; +use rustfs_utils::{get_env_bool, get_env_opt_str, get_env_u64, get_env_usize}; +use std::collections::VecDeque; +use std::io; +#[cfg(not(feature = "nixl"))] +use std::net::IpAddr; +use std::ops::Range; +use std::pin::Pin; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, OnceLock}; +use std::task::{Context, Poll}; +use std::time::{Duration, Instant}; +use tokio::io::{AsyncReadExt, AsyncWrite}; +use tokio::task::JoinHandle; +use tracing::{info, warn}; +use transport::{Error as CuObjectError, RdmaToken, RegisteredArena, Server as CuObjectServer, StagingChunk}; +pub(crate) use transport::{RDMA_BYTES_TRANSFERRED_HEADER, RDMA_REPLY_HEADER}; + +const LOG_COMPONENT_OBJECT: &str = "object"; +const LOG_SUBSYSTEM_CUOBJECT: &str = "cuobject"; +const EVENT_CUOBJECT_SERVICE_STATE: &str = "cuobject_service_state"; +const EVENT_CUOBJECT_GET_REJECTED: &str = "cuobject_get_rejected"; +const STAGING_RESERVE_TIMEOUT: Duration = Duration::from_secs(30); + +static SERVICE: OnceLock> = OnceLock::new(); + +pub(crate) struct CuObjectService { + servers: Vec>, + inflight_writes: usize, + /// Staging chunks read ahead from the client per RDMA PUT body. + put_read_ahead: usize, + /// Segments one GET is split into on the server; 1 keeps the body sequential. + get_fanout: usize, + /// Smallest segment worth its own producer, in bytes. + get_fanout_min_bytes: u64, + /// Segment producers the node may run across all its cuObject GETs. + get_fanout_budget: usize, + /// Permits for the extra producers (beyond each GET's first) within that budget. + get_fanout_permits: Arc, + /// cuObject GETs currently open on this node, for the fair share. + active_gets: Arc, + /// Registered memory the erasure decoder reads shards into, so GETs can + /// RDMA-write data shards straight from the shard buffers (zero-copy emit). + shard_arena: Option>, + next: AtomicUsize, +} + +impl CuObjectService { + fn pick(&self) -> &Arc { + let index = self.next.fetch_add(1, Ordering::Relaxed) % self.servers.len(); + &self.servers[index] + } +} + +fn local_endpoint_hosts() -> Vec { + get_global_endpoints_opt() + .map(|pools| { + pools + .as_ref() + .iter() + .flat_map(|pool| pool.endpoints.as_ref().iter()) + .filter(|endpoint| endpoint.is_local) + .filter_map(|endpoint| endpoint.url.host_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() +} + +#[cfg(not(feature = "nixl"))] +async fn resolve_addrs() -> io::Result> { + use rustfs_config::ENV_RUSTFS_CUOBJECT_ADDRS; + use std::collections::BTreeSet; + + let mut ips = BTreeSet::new(); + match get_env_opt_str(ENV_RUSTFS_CUOBJECT_ADDRS) { + Some(raw) => { + for entry in raw.split(',').map(str::trim).filter(|entry| !entry.is_empty()) { + let ip: IpAddr = entry.parse().map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidInput, + format!("{ENV_RUSTFS_CUOBJECT_ADDRS} entry {entry:?} is not an IP address"), + ) + })?; + ips.insert(ip); + } + } + None => { + for host in local_endpoint_hosts() { + let host = host.trim_matches(|c| c == '[' || c == ']').to_owned(); + if let Ok(ip) = host.parse::() { + if !ip.is_unspecified() && !ip.is_loopback() { + ips.insert(ip); + } + continue; + } + for addr in tokio::net::lookup_host((host.as_str(), global_rustfs_port())).await? { + if !addr.ip().is_loopback() { + ips.insert(addr.ip()); + } + } + } + } + } + Ok(ips.into_iter().collect()) +} + +/// Whether the RDMA transport of this build is switched on. +#[cfg(not(feature = "nixl"))] +fn transport_enabled() -> bool { + get_env_bool(rustfs_config::ENV_RUSTFS_CUOBJECT_ENABLE, rustfs_config::DEFAULT_RUSTFS_CUOBJECT_ENABLE) +} + +#[cfg(feature = "nixl")] +fn transport_enabled() -> bool { + get_env_bool(rustfs_config::ENV_RUSTFS_NIXL_ENABLE, rustfs_config::DEFAULT_RUSTFS_NIXL_ENABLE) +} + +/// The transport servers of this node plus (control port, chunk bytes, pool +/// bytes) for the startup log; an empty list means the node has nowhere to +/// serve RDMA from and keeps serving over HTTP only. +#[cfg(not(feature = "nixl"))] +async fn build_servers() -> io::Result<(Vec>, u16, usize, usize)> { + use rustfs_config::{ + DEFAULT_RUSTFS_CUOBJECT_ASYNC_TRANSFERS, DEFAULT_RUSTFS_CUOBJECT_CHUNK_BYTES, DEFAULT_RUSTFS_CUOBJECT_NUM_DCIS, + DEFAULT_RUSTFS_CUOBJECT_POOL_BYTES, DEFAULT_RUSTFS_CUOBJECT_PORT, ENV_RUSTFS_CUOBJECT_ASYNC_TRANSFERS, + ENV_RUSTFS_CUOBJECT_CHUNK_BYTES, ENV_RUSTFS_CUOBJECT_NUM_DCIS, ENV_RUSTFS_CUOBJECT_POOL_BYTES, ENV_RUSTFS_CUOBJECT_PORT, + }; + use rustfs_cuobject::CuObjectConfig; + use rustfs_utils::get_env_u16; + + let config = CuObjectConfig { + port: get_env_u16(ENV_RUSTFS_CUOBJECT_PORT, DEFAULT_RUSTFS_CUOBJECT_PORT), + num_dcis: i32::try_from(get_env_usize(ENV_RUSTFS_CUOBJECT_NUM_DCIS, DEFAULT_RUSTFS_CUOBJECT_NUM_DCIS as usize)) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, format!("{ENV_RUSTFS_CUOBJECT_NUM_DCIS} is too large")))?, + chunk_bytes: get_env_usize(ENV_RUSTFS_CUOBJECT_CHUNK_BYTES, DEFAULT_RUSTFS_CUOBJECT_CHUNK_BYTES), + pool_bytes: get_env_usize(ENV_RUSTFS_CUOBJECT_POOL_BYTES, DEFAULT_RUSTFS_CUOBJECT_POOL_BYTES), + async_transfers: get_env_bool(ENV_RUSTFS_CUOBJECT_ASYNC_TRANSFERS, DEFAULT_RUSTFS_CUOBJECT_ASYNC_TRANSFERS), + ..CuObjectConfig::default() + }; + if config.chunk_bytes == 0 || config.chunk_bytes > transport::MAX_RDMA_OP_BYTES || config.pool_bytes < config.chunk_bytes { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("{ENV_RUSTFS_CUOBJECT_CHUNK_BYTES}/{ENV_RUSTFS_CUOBJECT_POOL_BYTES} are inconsistent"), + )); + } + let addrs = resolve_addrs().await?; + let mut servers = Vec::with_capacity(addrs.len()); + for addr in addrs { + let config = config.clone(); + let server = tokio::task::spawn_blocking(move || CuObjectServer::new(addr, &config)) + .await + .map_err(io::Error::other)? + .map_err(|error| io::Error::other(format!("cuobject server on {addr}: {error}")))?; + servers.push(server); + } + Ok((servers, config.port, config.chunk_bytes, config.pool_bytes)) +} + +/// One NIXL agent per node with the UCX backend; no address is needed, the +/// agent metadata carries every device. +#[cfg(feature = "nixl")] +async fn build_servers() -> io::Result<(Vec>, u16, usize, usize)> { + use rustfs_config::{ + DEFAULT_RUSTFS_NIXL_CHUNK_BYTES, DEFAULT_RUSTFS_NIXL_DEVICE_CHECK, DEFAULT_RUSTFS_NIXL_DEVICE_FLAP_WINDOW_MS, + DEFAULT_RUSTFS_NIXL_DEVICE_MAX_LINK_DROPS, DEFAULT_RUSTFS_NIXL_MAX_INFLIGHT, DEFAULT_RUSTFS_NIXL_NUM_WORKERS, + DEFAULT_RUSTFS_NIXL_POOL_BYTES, DEFAULT_RUSTFS_NIXL_TRANSFER_TIMEOUT_SECS, ENV_RUSTFS_NIXL_AGENT_NAME, + ENV_RUSTFS_NIXL_CHUNK_BYTES, ENV_RUSTFS_NIXL_DEVICE_CHECK, ENV_RUSTFS_NIXL_DEVICE_FLAP_WINDOW_MS, + ENV_RUSTFS_NIXL_DEVICE_MAX_LINK_DROPS, ENV_RUSTFS_NIXL_MAX_INFLIGHT, ENV_RUSTFS_NIXL_NUM_WORKERS, + ENV_RUSTFS_NIXL_POOL_BYTES, ENV_RUSTFS_NIXL_TRANSFER_TIMEOUT_SECS, ENV_RUSTFS_NIXL_UCX_DEVICES, + }; + use rustfs_nixl::NixlConfig; + + let agent_name = get_env_opt_str(ENV_RUSTFS_NIXL_AGENT_NAME).unwrap_or_else(|| { + let host = local_endpoint_hosts().into_iter().next().unwrap_or_else(|| "node".to_owned()); + format!("rustfs-{}", host.trim_matches(|c| c == '[' || c == ']')) + }); + let ucx_devices: Vec = get_env_opt_str(ENV_RUSTFS_NIXL_UCX_DEVICES) + .unwrap_or_default() + .split(',') + .map(str::trim) + .filter(|device| !device.is_empty()) + .map(str::to_owned) + .collect(); + let ucx_devices = if get_env_bool(ENV_RUSTFS_NIXL_DEVICE_CHECK, DEFAULT_RUSTFS_NIXL_DEVICE_CHECK) { + checked_nixl_devices( + ucx_devices, + get_env_u64(ENV_RUSTFS_NIXL_DEVICE_MAX_LINK_DROPS, DEFAULT_RUSTFS_NIXL_DEVICE_MAX_LINK_DROPS), + Duration::from_millis(get_env_u64( + ENV_RUSTFS_NIXL_DEVICE_FLAP_WINDOW_MS, + DEFAULT_RUSTFS_NIXL_DEVICE_FLAP_WINDOW_MS, + )), + ) + .await? + } else { + ucx_devices + }; + let config = NixlConfig { + agent_name, + ucx_devices, + num_workers: u32::try_from(get_env_usize(ENV_RUSTFS_NIXL_NUM_WORKERS, DEFAULT_RUSTFS_NIXL_NUM_WORKERS as usize)) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, format!("{ENV_RUSTFS_NIXL_NUM_WORKERS} is too large")))?, + chunk_bytes: get_env_usize(ENV_RUSTFS_NIXL_CHUNK_BYTES, DEFAULT_RUSTFS_NIXL_CHUNK_BYTES), + pool_bytes: get_env_usize(ENV_RUSTFS_NIXL_POOL_BYTES, DEFAULT_RUSTFS_NIXL_POOL_BYTES), + max_inflight: get_env_usize(ENV_RUSTFS_NIXL_MAX_INFLIGHT, DEFAULT_RUSTFS_NIXL_MAX_INFLIGHT), + transfer_timeout: Duration::from_secs( + get_env_u64(ENV_RUSTFS_NIXL_TRANSFER_TIMEOUT_SECS, DEFAULT_RUSTFS_NIXL_TRANSFER_TIMEOUT_SECS).max(1), + ), + ..NixlConfig::default() + }; + if config.chunk_bytes == 0 || config.chunk_bytes > transport::MAX_RDMA_OP_BYTES || config.pool_bytes < config.chunk_bytes { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("{ENV_RUSTFS_NIXL_CHUNK_BYTES}/{ENV_RUSTFS_NIXL_POOL_BYTES} are inconsistent"), + )); + } + let (chunk_bytes, pool_bytes) = (config.chunk_bytes, config.pool_bytes); + let server = tokio::task::spawn_blocking(move || CuObjectServer::new(&config)) + .await + .map_err(io::Error::other)? + .map_err(|error| io::Error::other(format!("nixl agent: {error}")))?; + Ok((vec![server], 0, chunk_bytes, pool_bytes)) +} + +/// Starts the RDMA transport servers of this node when the transport is +/// enabled (`RUSTFS_CUOBJECT_ENABLE` or `RUSTFS_NIXL_ENABLE`). +/// +/// Invalid settings and server construction failures fail startup; a node +/// without RDMA addresses logs and serves GETs over HTTP only. +pub(crate) async fn init_cuobject_service() -> io::Result<()> { + if !transport_enabled() { + return Ok(()); + } + let inflight_writes = get_env_usize(ENV_RUSTFS_CUOBJECT_INFLIGHT_WRITES, DEFAULT_RUSTFS_CUOBJECT_INFLIGHT_WRITES).max(1); + let put_read_ahead = get_env_usize(ENV_RUSTFS_CUOBJECT_PUT_READ_AHEAD, DEFAULT_RUSTFS_CUOBJECT_PUT_READ_AHEAD).max(1); + let get_fanout = get_env_usize(ENV_RUSTFS_CUOBJECT_GET_FANOUT, DEFAULT_RUSTFS_CUOBJECT_GET_FANOUT).max(1); + let get_fanout_min_bytes = + get_env_u64(ENV_RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES, DEFAULT_RUSTFS_CUOBJECT_GET_FANOUT_MIN_BYTES); + let get_fanout_budget = get_env_usize(ENV_RUSTFS_CUOBJECT_GET_FANOUT_BUDGET, DEFAULT_RUSTFS_CUOBJECT_GET_FANOUT_BUDGET) + .min(tokio::sync::Semaphore::MAX_PERMITS); + let (servers, port, chunk_bytes, pool_bytes) = build_servers().await?; + if servers.is_empty() { + info!( + event = EVENT_CUOBJECT_SERVICE_STATE, + component = LOG_COMPONENT_OBJECT, + subsystem = LOG_SUBSYSTEM_CUOBJECT, + state = "skipped", + reason = "no_rdma_address", + "rdma transport service not started: no local endpoint host or RUSTFS_CUOBJECT_ADDRS" + ); + return Ok(()); + } + let shard_arena = install_cuobject_shard_arena(&servers).await?; + #[cfg(feature = "nixl")] + install_nixl_recv_pool(&servers)?; + let (major, minor) = transport::library_version(); + info!( + event = EVENT_CUOBJECT_SERVICE_STATE, + component = LOG_COMPONENT_OBJECT, + subsystem = LOG_SUBSYSTEM_CUOBJECT, + state = "started", + server_count = servers.len(), + port, + chunk_bytes, + pool_bytes, + inflight_writes, + put_read_ahead, + get_fanout, + get_fanout_min_bytes, + get_fanout_budget, + shard_arena_bytes = shard_arena.as_ref().map_or(0, |arena| arena.len()), + library = format_args!("{major}.{minor}"), + "s3-over-rdma transport service started" + ); + #[cfg(feature = "nixl")] + if let Some(server) = servers.first() { + crate::storage::rpc::nixl_read::install_nixl_server(Arc::clone(server)); + } + let _ = SERVICE.set(Arc::new(CuObjectService { + servers, + inflight_writes, + put_read_ahead, + get_fanout, + get_fanout_min_bytes, + get_fanout_budget, + get_fanout_permits: Arc::new(tokio::sync::Semaphore::new(get_fanout_budget)), + active_gets: Arc::new(AtomicUsize::new(0)), + shard_arena, + next: AtomicUsize::new(0), + })); + Ok(()) +} + +/// Registers the shard arena (`RUSTFS_CUOBJECT_SHARD_ARENA_BYTES`) with the +/// first server and installs it as the process-wide shard buffer source. +async fn install_cuobject_shard_arena(servers: &[Arc]) -> io::Result>> { + let bytes = get_env_usize(ENV_RUSTFS_CUOBJECT_SHARD_ARENA_BYTES, DEFAULT_RUSTFS_CUOBJECT_SHARD_ARENA_BYTES); + let Some(server) = servers.first() else { + return Ok(None); + }; + if bytes == 0 { + return Ok(None); + } + let block_len = match get_env_usize(ENV_ERASURE_SHARD_BYTES, DEFAULT_ERASURE_SHARD_BYTES) { + 0 => 4 * 1024 * 1024, + shard => shard, + }; + if bytes < block_len { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("{ENV_RUSTFS_CUOBJECT_SHARD_ARENA_BYTES} is smaller than one shard block ({block_len} bytes)"), + )); + } + let server = Arc::clone(server); + // Registration pins the memory; keep it off the runtime threads. + let arena = tokio::task::spawn_blocking(move || server.register_arena(bytes)) + .await + .map_err(io::Error::other)? + .map_err(|error| io::Error::other(format!("cuobject shard arena: {error}")))?; + let slab = build_slab_arena(&arena, block_len); + if !install_shard_arena(slab) { + warn!( + event = EVENT_CUOBJECT_SERVICE_STATE, + component = LOG_COMPONENT_OBJECT, + subsystem = LOG_SUBSYSTEM_CUOBJECT, + state = "arena_already_installed", + "cuobject shard arena not installed: another shard arena is active" + ); + return Ok(None); + } + Ok(Some(arena)) +} + +/// Leaves out the RDMA devices that are down, slower than their peers, or flap +/// (a long drop history, or a drop during a short watch); `RUSTFS_NIXL_DEVICE_CHECK`. An empty list +/// means every device on the node. Fails when no device passes. +#[cfg(feature = "nixl")] +async fn checked_nixl_devices(candidates: Vec, max_link_drops: u64, flap_window: Duration) -> io::Result> { + let check = + tokio::task::spawn_blocking(move || rustfs_nixl::devices::check_system_devices(&candidates, max_link_drops, flap_window)) + .await + .map_err(io::Error::other)?; + let kept = check.kept.join(","); + let excluded = check + .excluded + .iter() + .map(|(device, reason)| format!("{device} ({reason})")) + .collect::>() + .join(", "); + if check.kept.is_empty() { + tracing::error!( + event = EVENT_CUOBJECT_SERVICE_STATE, + component = LOG_COMPONENT_OBJECT, + subsystem = LOG_SUBSYSTEM_CUOBJECT, + state = "device_check", + result = "failed", + excluded = %excluded, + "no healthy rdma device for the nixl agent" + ); + return Err(io::Error::other(format!("no healthy RDMA device for NIXL; left out: {excluded}"))); + } + if check.excluded.is_empty() { + info!( + event = EVENT_CUOBJECT_SERVICE_STATE, + component = LOG_COMPONENT_OBJECT, + subsystem = LOG_SUBSYSTEM_CUOBJECT, + state = "device_check", + result = "ok", + kept = %kept, + "nixl rdma devices checked" + ); + } else { + warn!( + event = EVENT_CUOBJECT_SERVICE_STATE, + component = LOG_COMPONENT_OBJECT, + subsystem = LOG_SUBSYSTEM_CUOBJECT, + state = "device_check", + result = "degraded", + kept = %kept, + excluded = %excluded, + "nixl rdma devices left out" + ); + } + Ok(check.kept) +} + +/// Receive buffers for internode NIXL reads: staging chunks of this node's agent. +#[cfg(feature = "nixl")] +struct NixlRecvPoolAdapter { + server: Arc, + metadata_base64: String, + metadata_sha256_hex: String, +} + +#[cfg(feature = "nixl")] +struct NixlRecvChunk(StagingChunk); + +#[cfg(feature = "nixl")] +impl crate::app::storage_api::object_usecase::rdma::NixlRecvBuffer for NixlRecvChunk { + fn descriptor(&self) -> String { + self.descriptor_for(self.0.capacity()) + } + + fn descriptor_for(&self, len: usize) -> String { + format!("dram:0:{:#x}:{}", self.0.addr(), len.min(self.0.capacity())) + } + + fn spare_mut(&mut self) -> &mut [u8] { + // A reserved chunk starts empty, so its spare area is the whole chunk. + self.0.spare_mut().unwrap_or(&mut []) + } + + fn into_bytes(self: Box, len: usize) -> io::Result { + let mut chunk = self.0; + chunk.clear(); + chunk.advance(len).map_err(io::Error::other)?; + Ok(bytes::Bytes::from_owner(chunk)) + } +} + +#[cfg(feature = "nixl")] +impl crate::app::storage_api::object_usecase::rdma::NixlRecvPool for NixlRecvPoolAdapter { + fn agent_name(&self) -> &str { + self.server.name() + } + + fn metadata_base64(&self) -> &str { + &self.metadata_base64 + } + + fn metadata_sha256_hex(&self) -> &str { + &self.metadata_sha256_hex + } + + fn chunk_bytes(&self) -> usize { + self.server.chunk_bytes() + } + + fn reserve( + &self, + ) -> futures::future::BoxFuture<'static, io::Result>> + { + let server = Arc::clone(&self.server); + Box::pin(async move { + let chunk = server.reserve(STAGING_RESERVE_TIMEOUT).await.map_err(io::Error::other)?; + Ok(Box::new(NixlRecvChunk(chunk)) as Box) + }) + } +} + +/// Lets internode reads use this node's agent and staging pool +/// (`RUSTFS_INTERNODE_DATA_TRANSPORT=nixl`). +#[cfg(feature = "nixl")] +fn install_nixl_recv_pool(servers: &[Arc]) -> io::Result<()> { + let Some(server) = servers.first() else { + return Ok(()); + }; + let metadata = server + .local_metadata() + .map_err(|error| io::Error::other(format!("nixl agent metadata: {error}")))?; + let adapter = NixlRecvPoolAdapter { + server: Arc::clone(server), + metadata_base64: base64_simd::STANDARD.encode_to_string(&metadata), + metadata_sha256_hex: crate::storage::rpc::nixl_read::sha256_hex(&metadata), + }; + crate::app::storage_api::object_usecase::rdma::install_nixl_recv_pool(Arc::new(adapter)); + Ok(()) +} + +/// Wraps the registered memory as a block arena. The arena owns a clone of +/// the registration, so the memory outlives every block handed out. +#[allow(unsafe_code)] +fn build_slab_arena(arena: &Arc, block_len: usize) -> Arc { + // SAFETY: `as_mut_ptr` addresses `len` bytes of host memory owned by the + // registration, which the slab keeps alive through the boxed clone; the + // slab hands out disjoint blocks of it. + unsafe { RegisteredSlabArena::new(arena.as_mut_ptr(), arena.len(), block_len, arena.id(), Box::new(Arc::clone(arena))) } +} + +/// The cuObject token: one opaque header from the client library. +#[cfg(not(feature = "nixl"))] +fn parse_rdma_token(headers: &HeaderMap) -> Option> { + let raw = headers.get(transport::RDMA_TOKEN_HEADER)?.to_str().ok()?; + Some(RdmaToken::parse(raw)) +} + +/// The NIXL token: agent name, optional agent metadata and the client buffer. +#[cfg(feature = "nixl")] +fn parse_rdma_token(headers: &HeaderMap) -> Option> { + let agent = headers.get(transport::NIXL_AGENT_HEADER)?.to_str().ok()?; + let buffer = headers.get(transport::NIXL_BUFFER_HEADER)?.to_str().ok()?; + let metadata = headers + .get(transport::NIXL_METADATA_HEADER) + .and_then(|value| value.to_str().ok()); + Some(RdmaToken::from_headers(agent, metadata, buffer)) +} + +/// The parsed RDMA token of a GET that must be served over RDMA. +/// +/// Returns `None` when the header is absent, the service is not running, or +/// the token is malformed; in the last two cases the response carries no +/// `x-amz-rdma-reply`, which the client reads as "declined". +pub(crate) fn rdma_token_for_request(headers: &HeaderMap) -> Option { + SERVICE.get()?; + match parse_rdma_token(headers)? { + Ok(token) => Some(token), + Err(error) => { + warn!( + event = EVENT_CUOBJECT_GET_REJECTED, + component = LOG_COMPONENT_OBJECT, + subsystem = LOG_SUBSYSTEM_CUOBJECT, + result = "declined", + reason = "token_malformed", + error = %error, + "cuobject get declined" + ); + None + } + } +} + +fn transfer_error(context: &str, error: CuObjectError) -> S3Error { + S3Error::with_message(S3ErrorCode::InternalError, format!("rdma get {context}: {error}")) +} + +/// Pipelines RDMA writes behind the decode stream: up to `inflight` staging +/// chunks are filled and written concurrently, writes complete in issue order, +/// and the first failure aborts the GET. +struct WritePipeline { + server: Arc, + object: String, + token: RdmaToken, + free: Vec, + writes: VecDeque>>, + issued: u64, + moved: u64, +} + +impl WritePipeline { + async fn new(server: Arc, object: String, token: RdmaToken, inflight: usize) -> S3Result { + // The first chunk must be reserved; extra chunks are best effort so a + // busy pool degrades to a shallower pipeline instead of failing the GET. + let mut free = vec![ + server + .reserve(STAGING_RESERVE_TIMEOUT) + .await + .map_err(|error| transfer_error("staging", error))?, + ]; + while free.len() < inflight { + match server.reserve(Duration::ZERO).await { + Ok(chunk) => free.push(chunk), + Err(_) => break, + } + } + Ok(Self { + server, + object, + token, + free, + writes: VecDeque::new(), + issued: 0, + moved: 0, + }) + } + + /// Returns an empty chunk, waiting for the oldest write when none is free. + async fn take(&mut self) -> S3Result { + if self.free.is_empty() { + self.reap_oldest().await?; + } + Ok(self.free.pop().expect("a chunk is free after reaping")) + } + + /// Starts the RDMA write of `chunk` at the next client offset. + fn submit(&mut self, chunk: StagingChunk) { + if chunk.is_empty() { + self.free.push(chunk); + return; + } + let len = chunk.len() as u64; + let offset = self.issued; + self.issued += len; + let server = Arc::clone(&self.server); + let object = self.object.clone(); + let token = self.token.clone(); + // The blocking write owns the chunk until the DMA completes, so neither a + // cancelled task nor an aborted pipeline can return the slot early. + self.writes.push_back(tokio::spawn( + async move { server.write_to_client_owned(&object, &token, offset, chunk).await }, + )); + } + + async fn reap_oldest(&mut self) -> S3Result<()> { + let Some(handle) = self.writes.pop_front() else { + return Ok(()); + }; + let (written, mut chunk) = handle + .await + .map_err(|error| S3Error::with_message(S3ErrorCode::InternalError, format!("rdma get write task: {error}")))? + .map_err(|error| transfer_error("write", error))?; + self.moved += written; + chunk.clear(); + self.free.push(chunk); + Ok(()) + } + + /// Waits for every outstanding write; returns the bytes moved. + async fn finish(mut self) -> S3Result { + while !self.writes.is_empty() { + self.reap_oldest().await?; + } + Ok(self.moved) + } + + /// Waits for the outstanding writes on error. Their DMAs cannot be + /// cancelled, and each chunk is released only when its write returns, so + /// draining here is what keeps a staging slot from being reused while the + /// NIC still reads it; results are ignored because the GET already failed. + async fn abort(&mut self) { + for handle in self.writes.drain(..) { + let _ = handle.await; + } + } +} + +/// Streams the response into staging chunks, submitting each full chunk to the +/// write pipeline so decoding keeps running while earlier chunks are written. +async fn fill_pipeline( + pipeline: &mut WritePipeline, + stream: DynReader, + buffered_body: Option, + expected: u64, +) -> S3Result<()> { + let mut chunk = pipeline.take().await?; + match buffered_body { + Some(bytes) => { + let mut rest = &bytes[..]; + while !rest.is_empty() { + let take = rest.len().min(chunk.capacity() - chunk.len()); + chunk + .append(&rest[..take]) + .map_err(|error| transfer_error("staging", error))?; + rest = &rest[take..]; + if chunk.is_full() { + pipeline.submit(chunk); + chunk = pipeline.take().await?; + } + } + } + None => { + let mut stream = stream; + // Stop at the committed response length: readers may be unbounded. + let mut remaining = expected; + while remaining > 0 { + let spare = chunk.spare_mut().map_err(|error| transfer_error("staging", error))?; + let want = spare.len().min(usize::try_from(remaining).unwrap_or(usize::MAX)); + let read = stream + .read(&mut spare[..want]) + .await + .map_err(|error| transfer_error("read", CuObjectError::Source(error)))?; + if read == 0 { + break; + } + chunk.advance(read).map_err(|error| transfer_error("staging", error))?; + remaining -= read as u64; + if chunk.is_full() { + pipeline.submit(chunk); + chunk = pipeline.take().await?; + } + } + } + } + pipeline.submit(chunk); + Ok(()) +} + +/// Moves the response bytes into the client's buffer; returns the payload byte count. +pub(crate) async fn serve_get_over_rdma( + stream: DynReader, + buffered_body: Option, + response_content_length: i64, + bucket: &str, + key: &str, + token: &RdmaToken, +) -> S3Result { + let service = SERVICE + .get() + .ok_or_else(|| S3Error::with_message(S3ErrorCode::NotImplemented, "rdma get is not enabled"))?; + let expected = u64::try_from(response_content_length).unwrap_or(0); + if expected > token.buffer_len { + return Err(S3Error::with_message( + S3ErrorCode::InvalidRange, + format!( + "rdma token buffer ({} bytes) is smaller than the response ({expected} bytes)", + token.buffer_len + ), + )); + } + let server = Arc::clone(service.pick()); + let started = Instant::now(); + let object = format!("{bucket}/{key}"); + let mut pipeline = WritePipeline::new(server, object, token.clone(), service.inflight_writes).await?; + let moved = match fill_pipeline(&mut pipeline, stream, buffered_body, expected).await { + Ok(()) => pipeline.finish().await?, + Err(error) => { + pipeline.abort().await; + return Err(error); + } + }; + if moved != expected { + return Err(S3Error::with_message( + S3ErrorCode::InternalError, + format!("rdma get moved {moved} of {expected} bytes"), + )); + } + rustfs_io_metrics::record_get_object_stage_duration( + super::GET_OBJECT_STAGE_PATH_S3_HANDLER, + "rdma_transfer", + started.elapsed().as_secs_f64(), + ); + Ok(moved) +} + +/// Request body of a cuObject PUT: the object bytes are RDMA-read from the +/// client's buffer into staging, one chunk ahead of the consumer, and handed +/// to the normal PUT pipeline as an ordinary byte stream. +struct RdmaPutBody { + inner: Pin> + Send + Sync + 'static>>, + remaining: usize, +} + +impl Stream for RdmaPutBody { + type Item = Result; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let next = self.inner.as_mut().poll_next(cx); + if let Poll::Ready(Some(Ok(bytes))) = &next { + self.remaining = self.remaining.saturating_sub(bytes.len()); + } + next + } + + fn size_hint(&self) -> (usize, Option) { + (self.remaining, Some(self.remaining)) + } +} + +impl ByteStream for RdmaPutBody { + fn remaining_length(&self) -> RemainingLength { + RemainingLength::new_exact(self.remaining) + } +} + +type StagedRead = JoinHandle>; + +/// The staged bytes of `chunk`: with `zero_copy`, a `Bytes` that owns the +/// chunk (it returns to the pool when the last clone drops), otherwise a copy. +#[cfg(feature = "nixl")] +fn staged_bytes(chunk: StagingChunk, zero_copy: bool) -> io::Result { + if zero_copy { + return Ok(Bytes::from_owner(chunk)); + } + Ok(Bytes::copy_from_slice(chunk.staged().map_err(io::Error::other)?)) +} + +/// The staged bytes of `chunk`, copied (the cuObject chunk is not a byte owner). +#[cfg(not(feature = "nixl"))] +fn staged_bytes(chunk: StagingChunk, _zero_copy: bool) -> io::Result { + Ok(Bytes::copy_from_slice(chunk.staged().map_err(io::Error::other)?)) +} + +fn spawn_staged_read(server: &Arc, object: &str, token: &RdmaToken, offset: u64, len: usize) -> StagedRead { + let server = Arc::clone(server); + let object = object.to_owned(); + let token = token.clone(); + tokio::spawn(async move { + let chunk = server.reserve(STAGING_RESERVE_TIMEOUT).await?; + server.read_from_client_owned(&object, &token, offset, len, chunk).await + }) +} + +/// Builds the streaming body for a PUT whose bytes live in the client's RDMA +/// buffer (`x-amz-rdma-token`, empty HTTP body). The object length is the +/// token's buffer length. Returns the body and that length. +/// +/// With `zero_copy` the body's chunks are the staging chunks themselves, so a +/// consumer that keeps a chunk keeps it out of the pool: only callers whose +/// body is consumed and dropped with the request (UploadPart) may set it. +/// PutObject may hand its body to the object data cache, so it copies. +pub(crate) fn rdma_put_body(bucket: &str, key: &str, token: &RdmaToken, zero_copy: bool) -> S3Result<(StreamingBlob, u64)> { + let service = SERVICE + .get() + .ok_or_else(|| S3Error::with_message(S3ErrorCode::NotImplemented, "rdma put is not enabled"))?; + let server = Arc::clone(service.pick()); + let read_ahead = service.put_read_ahead; + let total = token.buffer_len; + let chunk_bytes = server.chunk_bytes(); + let object = format!("{bucket}/{key}"); + let token = token.clone(); + // Keep `read_ahead` RDMA reads in flight, so the reads of the following + // chunks overlap the consumer's work on this one. The first ones start + // now, overlapping the request's setup. + let fill = move |server: &Arc, + object: &str, + token: &RdmaToken, + pending: &mut VecDeque, + next_offset: &mut u64| { + while pending.len() < read_ahead && *next_offset < total { + let len = usize::try_from((total - *next_offset).min(chunk_bytes as u64)).unwrap_or(chunk_bytes); + pending.push_back(spawn_staged_read(server, object, token, *next_offset, len)); + *next_offset += len as u64; + } + }; + let mut pending = VecDeque::with_capacity(read_ahead); + let mut next_offset = 0u64; + fill(&server, &object, &token, &mut pending, &mut next_offset); + // State: (reads in flight in offset order, offset of the next read to start). + let stream = futures::stream::try_unfold((pending, next_offset), move |(mut pending, mut next_offset)| { + let server = Arc::clone(&server); + let object = object.clone(); + let token = token.clone(); + async move { + fill(&server, &object, &token, &mut pending, &mut next_offset); + let Some(read) = pending.pop_front() else { + return Ok(None); + }; + let wait_started = rustfs_io_metrics::put_stage_timer(); + let chunk = read + .await + .map_err(|error| io::Error::other(format!("rdma put read task: {error}")))? + .map_err(|error| io::Error::other(format!("rdma put read: {error}")))?; + rustfs_io_metrics::record_put_object_stage_duration_from("rdma_put_body_wait", wait_started); + let bytes = staged_bytes(chunk, zero_copy)?; + Ok::<_, io::Error>(Some((bytes, (pending, next_offset)))) + } + }); + let stream = futures::TryStreamExt::map_err(stream, |error: io::Error| -> StdError { Box::new(error) }); + let body = RdmaPutBody { + inner: Box::pin(stream), + remaining: usize::try_from(total) + .map_err(|_| S3Error::with_message(S3ErrorCode::EntityTooLarge, "rdma put too large"))?, + }; + Ok((StreamingBlob::new(body), total)) +} + +/// State shared by the segment writers of one RDMA GET: the server, the +/// client token, the GET's staging chunks (free list), and the segments that +/// were opened, so the handler can finish or abort all of them. +struct SinkShared { + server: Arc, + object: String, + token: RdmaToken, + inflight_writes: usize, + free: std::sync::Mutex>, + /// Segments waiting for a chunk; woken one at a time as chunks return. + waiters: std::sync::Mutex>, + segments: std::sync::Mutex>>>, + /// The shard arena registered with this sink's server, if any: data shards + /// read into it are RDMA-written in place instead of through staging. + arena: Option>, +} + +impl SinkShared { + fn lock_free(&self) -> std::sync::MutexGuard<'_, Vec> { + self.free.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + fn lock_segments(&self) -> std::sync::MutexGuard<'_, Vec>>> { + self.segments.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// Opens a segment whose first byte lands at `remote_offset` in the client buffer. + fn open_segment(self: &Arc, remote_offset: u64) -> StagingSink { + let state = Arc::new(std::sync::Mutex::new(SegmentState { + current: None, + writes: VecDeque::new(), + issued: remote_offset, + moved: 0, + pending: Vec::new(), + pending_ranges: Vec::new(), + })); + self.lock_segments().push(Arc::clone(&state)); + StagingSink { + shared: Arc::clone(self), + state, + } + } + + /// Opens a segment as the writer handed to the storage layer: the staging + /// stream, plus the zero-copy shard emitter when the arena is available. + fn open_segment_writer( + self: &Arc, + remote_offset: u64, + ) -> crate::app::storage_api::object_usecase::StorageGetObjectSinkWriter { + let sink = self.open_segment(remote_offset); + match &self.arena { + Some(arena) => { + let emitter = StagingShardEmitter { + shared: Arc::clone(self), + state: Arc::clone(&sink.state), + arena: Arc::clone(arena), + }; + crate::app::storage_api::object_usecase::StorageGetObjectSinkWriter::with_emitter( + Box::new(sink), + Box::new(emitter), + ) + } + None => crate::app::storage_api::object_usecase::StorageGetObjectSinkWriter::new(Box::new(sink)), + } + } + + /// Reserves up to `count` more chunks from the pool without waiting. + fn top_up(&self, count: usize) { + let mut free = self.lock_free(); + for _ in 0..count { + match self.server.try_reserve() { + Some(chunk) => free.push(chunk), + None => break, + } + } + } + + /// Returns a chunk to the GET's free list and wakes one waiting segment. + fn release(&self, mut chunk: StagingChunk) { + chunk.clear(); + self.lock_free().push(chunk); + let waker = self.waiters.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).pop(); + if let Some(waker) = waker { + waker.wake(); + } + } + + fn park(&self, cx: &Context<'_>) { + let mut waiters = self.waiters.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if !waiters.iter().any(|waker| waker.will_wake(cx.waker())) { + waiters.push(cx.waker().clone()); + } + } +} + +/// An in-flight RDMA write of a segment: bytes moved and, for a staged write, +/// the chunk to return to the GET's free list. +type SegmentWrite = JoinHandle), CuObjectError>>; + +/// One segment of the body: the erasure decoder writes decoded bytes straight +/// into cuObject staging chunks (no duplex pipe, no consumer copy), full chunks +/// are RDMA-written on their own tasks at the segment's running offset. +struct SegmentState { + current: Option, + /// In-flight RDMA writes in submission order; a staging write returns its + /// chunk, a zero-copy shard write returns none (the shard buffer went back + /// to the arena when the write task dropped it). + writes: VecDeque, + /// Client-buffer offset of the next byte this segment stages. + issued: u64, + /// Bytes confirmed written by reaped writes. + moved: u64, + /// Data shards taken by the emitter and not yet submitted: one + /// scatter-gather RDMA write carries a whole stripe's worth. + pending: Vec, + /// `(arena offset, len)` of each pending shard's bytes, in stream order. + pending_ranges: Vec<(usize, usize)>, +} + +impl SegmentState { + /// Submits the pending shards as one scatter-gather write. + fn submit_pending(&mut self, shared: &Arc) { + if self.pending.is_empty() { + return; + } + let Some(arena) = shared.arena.as_ref() else { + return; + }; + let shards = std::mem::take(&mut self.pending); + let ranges = std::mem::take(&mut self.pending_ranges); + let len: usize = ranges.iter().map(|(_, len)| *len).sum(); + let remote_offset = self.issued; + self.issued += len as u64; + let server = Arc::clone(&shared.server); + let object = shared.object.clone(); + let token = shared.token.clone(); + let source = transport::ArenaRanges { + arena: Arc::clone(arena), + ranges, + }; + self.writes.push_back(tokio::spawn(async move { + let started = std::time::Instant::now(); + let result = server + .write_to_client_sg_owned(&object, &token, remote_offset, source, shards) + .await + .map(|(moved, _shards)| (moved, None)); + record_emit_write_latency(len, started.elapsed(), "write_zero_copy"); + result + })); + } + + fn submit_current(&mut self, shared: &Arc) { + let Some(chunk) = self.current.take() else { + return; + }; + if chunk.is_empty() { + shared.lock_free().push(chunk); + return; + } + let len = chunk.len() as u64; + let offset = self.issued; + self.issued += len; + let server = Arc::clone(&shared.server); + let object = shared.object.clone(); + let token = shared.token.clone(); + self.writes.push_back(tokio::spawn(async move { + let started = std::time::Instant::now(); + let result = server + .write_to_client_owned(&object, &token, offset, chunk) + .await + .map(|(moved, chunk)| (moved, Some(chunk))); + record_emit_write_latency(len as usize, started.elapsed(), "write_staging"); + result + })); + } + + /// Polls the oldest write; on completion its chunk returns to the GET's free list. + fn poll_reap_oldest(&mut self, shared: &SinkShared, cx: &mut Context<'_>) -> Poll> { + let Some(handle) = self.writes.front_mut() else { + return Poll::Ready(Ok(())); + }; + match Pin::new(handle).poll(cx) { + Poll::Pending => Poll::Pending, + Poll::Ready(joined) => { + self.writes.pop_front(); + let (written, chunk) = joined + .map_err(|error| io::Error::other(format!("rdma get write task: {error}")))? + .map_err(|error| io::Error::other(format!("rdma get write: {error}")))?; + self.moved += written; + if let Some(chunk) = chunk { + shared.release(chunk); + } + Poll::Ready(Ok(())) + } + } + } +} + +/// The writer half handed to the storage layer through the GET options (one +/// per segment; the sequential sink is the segment at offset 0). +/// Stage path and buckets for one zero-copy RDMA write (submit to completion), +/// recorded through the GET stage summary so the distribution under load is +/// visible next to the decode-loop stages. +const EMIT_STAGE_PATH: &str = "cuobject_emit"; + +fn record_emit_write_latency(bytes: usize, elapsed: std::time::Duration, path: &'static str) { + let secs = elapsed.as_secs_f64(); + // One stage per emit path, so the summary shows how many writes went out + // straight from the shard arena and how many through the staging copy. + rustfs_io_metrics::record_get_object_stage_duration(EMIT_STAGE_PATH, path, secs); + let bucket = match elapsed.as_millis() { + 0..=1 => "write_le_1ms", + 2..=5 => "write_le_5ms", + 6..=20 => "write_le_20ms", + 21..=50 => "write_le_50ms", + _ => "write_gt_50ms", + }; + rustfs_io_metrics::record_get_object_stage_duration(EMIT_STAGE_PATH, "write_total", secs); + rustfs_io_metrics::record_get_object_stage_duration(EMIT_STAGE_PATH, bucket, secs); + // Bytes per write as a stage whose "duration" is the byte count, so the + // summary shows the average write size next to its latency. + rustfs_io_metrics::record_get_object_stage_duration(EMIT_STAGE_PATH, "write_bytes", bytes as f64); +} + +pub(crate) struct StagingSink { + shared: Arc, + state: Arc>, +} + +/// The handler's half: finishes or aborts the transfer after the producer ends. +pub(crate) struct StagingSinkHandle { + sink: crate::app::storage_api::object_usecase::StorageGetObjectSink, + shared: Arc, + /// Node-wide fan-out permits held for the GET's lifetime (one per extra segment). + _fanout_permits: Option, + /// Counts this GET as active for the fair share until the handle is dropped. + _active: ActiveGetGuard, +} + +/// Decrements the node's active cuObject GET count on drop. +struct ActiveGetGuard(Arc); + +impl Drop for ActiveGetGuard { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::Relaxed); + } +} + +fn lock_segment(state: &std::sync::Mutex) -> std::sync::MutexGuard<'_, SegmentState> { + state.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +impl AsyncWrite for StagingSink { + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { + if buf.is_empty() { + return Poll::Ready(Ok(0)); + } + let shared = Arc::clone(&self.shared); + let mut state = lock_segment(&self.state); + // Shards taken before these bytes go out first so the order is kept. + state.submit_pending(&shared); + if state.current.is_none() { + let mut chunk = shared.lock_free().pop(); + if chunk.is_none() { + // Nothing free for this GET: reap this segment's oldest write, or + // grow from the pool when nothing is in flight. If the pool is + // exhausted too, park until another segment returns a chunk. + match state.poll_reap_oldest(&shared, cx) { + Poll::Ready(Ok(())) => {} + Poll::Ready(Err(error)) => return Poll::Ready(Err(error)), + Poll::Pending => return Poll::Pending, + } + chunk = shared.lock_free().pop().or_else(|| shared.server.try_reserve()); + if chunk.is_none() { + shared.park(cx); + // A chunk may have come back between the pop and the park. + chunk = shared.lock_free().pop(); + if chunk.is_none() { + return Poll::Pending; + } + } + } + state.current = chunk; + } + let chunk = state.current.as_mut().expect("a current chunk was just installed"); + let spare = chunk.spare_mut().map_err(io::Error::other)?; + let n = spare.len().min(buf.len()); + spare[..n].copy_from_slice(&buf[..n]); + chunk.advance(n).map_err(io::Error::other)?; + if chunk.is_full() { + state.submit_current(&shared); + } + Poll::Ready(Ok(n)) + } + + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } +} + +/// Batched zero-copy writes in flight per segment before the emitter applies +/// backpressure (one write per stripe, or per `MAX_SG_RANGES` shards). +const MAX_INFLIGHT_SHARD_WRITES: usize = 4; + +/// The zero-copy half of a segment writer: takes data shards that live in the +/// registered shard arena and RDMA-writes them in place, in stream order with +/// the bytes staged through the segment's [`StagingSink`]. +struct StagingShardEmitter { + shared: Arc, + state: Arc>, + arena: Arc, +} + +impl ShardEmitter for StagingShardEmitter { + fn poll_emit_shard( + &mut self, + cx: &mut Context<'_>, + shard: &mut Option, + range: Range, + ) -> Poll> { + let Some(block) = shard.as_ref().and_then(ShardBuf::arena_block) else { + return Poll::Ready(Ok(false)); + }; + if block.registration_id() != self.arena.id() || range.end > block.len() || range.start > range.end { + return Poll::Ready(Ok(false)); + } + let len = range.end - range.start; + if len == 0 { + shard.take(); + return Poll::Ready(Ok(true)); + } + let local_offset = block.offset() + range.start; + let shared = Arc::clone(&self.shared); + let mut state = lock_segment(&self.state); + if state.pending.len() >= transport::MAX_SG_RANGES { + // The batch is full: submit it (with backpressure) before taking more. + while state.writes.len() >= MAX_INFLIGHT_SHARD_WRITES { + match state.poll_reap_oldest(&shared, cx) { + Poll::Ready(Ok(())) => {} + Poll::Ready(Err(error)) => return Poll::Ready(Err(error)), + Poll::Pending => return Poll::Pending, + } + } + state.submit_pending(&shared); + } + // Bytes staged so far go out first so the stream order is kept. + state.submit_current(&shared); + let taken = shard.take().expect("shard checked above"); + state.pending.push(taken); + state.pending_ranges.push((local_offset, len)); + Poll::Ready(Ok(true)) + } + + fn poll_flush_shards(&mut self, cx: &mut Context<'_>) -> Poll> { + let shared = Arc::clone(&self.shared); + let mut state = lock_segment(&self.state); + if state.pending.is_empty() { + return Poll::Ready(Ok(())); + } + while state.writes.len() >= MAX_INFLIGHT_SHARD_WRITES { + match state.poll_reap_oldest(&shared, cx) { + Poll::Ready(Ok(())) => {} + Poll::Ready(Err(error)) => return Poll::Ready(Err(error)), + Poll::Pending => return Poll::Pending, + } + } + state.submit_pending(&shared); + Poll::Ready(Ok(())) + } +} + +impl StagingSinkHandle { + /// Reserves the staging chunks and builds the sink for one GET. With the + /// fan-out enabled the sink also offers segment writers; each opened + /// segment tops the GET's chunk list up (without waiting) so it can keep + /// its own writes in flight. + pub(crate) async fn new(bucket: &str, key: &str, token: &RdmaToken) -> S3Result { + let service = SERVICE + .get() + .ok_or_else(|| S3Error::with_message(S3ErrorCode::NotImplemented, "rdma get is not enabled"))?; + let server = Arc::clone(service.pick()); + let server_for_arena = Arc::clone(&server); + let mut free = vec![ + server + .reserve(STAGING_RESERVE_TIMEOUT) + .await + .map_err(|error| transfer_error("staging", error))?, + ]; + while free.len() < service.inflight_writes { + match server.reserve(Duration::ZERO).await { + Ok(chunk) => free.push(chunk), + Err(_) => break, + } + } + let shared = Arc::new(SinkShared { + server, + object: format!("{bucket}/{key}"), + token: token.clone(), + inflight_writes: service.inflight_writes, + free: std::sync::Mutex::new(free), + waiters: std::sync::Mutex::new(Vec::new()), + segments: std::sync::Mutex::new(Vec::new()), + arena: service + .shard_arena + .as_ref() + .filter(|arena| Arc::ptr_eq(arena.server(), &server_for_arena)) + .cloned(), + }); + // The fan-out is bounded by what the pool can give this GET right now + // (one segment's worth of chunks each), so under load GETs degrade to + // fewer segments instead of all of them waiting on the same chunks. + // Fair share of the node's producer budget among the GETs open right + // now (this one included): 16 producers give one stream 8 segments, + // four streams 4 each, eight streams 2, sixteen or more 1. Running + // GETs keep their segments; the permits cap the total so a burst can + // never exceed the budget, and nothing waits for a permit. + let active = ActiveGetGuard(Arc::clone(&service.active_gets)); + let streams = active.0.fetch_add(1, Ordering::Relaxed) + 1; + let fair_share = (service.get_fanout_budget / streams).clamp(1, service.get_fanout); + let affordable_segments = 1 + shared.server.available_chunks() / shared.inflight_writes.max(1); + let mut max_segments = fair_share.min(affordable_segments); + let mut fanout_permits = None; + if max_segments >= 2 { + let wanted = u32::try_from(max_segments - 1).unwrap_or(u32::MAX); + let available = u32::try_from(service.get_fanout_permits.available_permits()).unwrap_or(u32::MAX); + let extra = wanted.min(available); + fanout_permits = (extra > 0) + .then(|| Arc::clone(&service.get_fanout_permits).try_acquire_many_owned(extra).ok()) + .flatten(); + max_segments = 1 + fanout_permits.as_ref().map_or(0, |permits| permits.num_permits()); + } + let writer = shared.open_segment_writer(0); + let sink = if max_segments >= 2 { + let factory_shared = Arc::clone(&shared); + let factory: Arc< + dyn Fn(u64, u64) -> crate::app::storage_api::object_usecase::StorageGetObjectSinkWriter + Send + Sync, + > = Arc::new(move |offset, _len| { + factory_shared.top_up(factory_shared.inflight_writes); + factory_shared.open_segment_writer(offset) + }); + crate::app::storage_api::object_usecase::StorageGetObjectSink::with_segments( + writer, + crate::app::storage_api::object_usecase::StorageGetObjectSinkSegments { + factory, + max_segments, + min_segment_bytes: service.get_fanout_min_bytes, + }, + ) + } else { + crate::app::storage_api::object_usecase::StorageGetObjectSink::new(writer) + }; + Ok(Self { + sink, + shared, + _fanout_permits: fanout_permits, + _active: active, + }) + } + + /// The option value to hand to the storage layer. + pub(crate) fn sink(&self) -> crate::app::storage_api::object_usecase::StorageGetObjectSink { + self.sink.clone() + } + + /// Whether the storage layer streamed the body through the sink. + pub(crate) fn was_used(&self) -> bool { + self.sink.is_taken() + } + + fn segments(&self) -> Vec>> { + self.shared.lock_segments().clone() + } + + /// After the producer finished: writes every segment's last partial chunk + /// and waits for every write; returns the bytes moved into the client buffer. + pub(crate) async fn finish(self) -> S3Result { + let segments = self.segments(); + let mut moved = 0; + for state in &segments { + let mut state = lock_segment(state); + state.submit_pending(&self.shared); + state.submit_current(&self.shared); + moved += state.moved; + } + for state in &segments { + loop { + let handle = lock_segment(state).writes.pop_front(); + let Some(handle) = handle else { break }; + let (written, _chunk) = handle + .await + .map_err(|error| S3Error::with_message(S3ErrorCode::InternalError, format!("rdma get write task: {error}")))? + .map_err(|error| transfer_error("write", error))?; + moved += written; + } + } + Ok(moved) + } + + /// After a failed GET: waits for the in-flight writes so their chunks are + /// only released once the DMAs are over. + pub(crate) async fn abort(self) { + for state in self.segments() { + loop { + let handle = lock_segment(&state).writes.pop_front(); + let Some(handle) = handle else { break }; + let _ = handle.await; + } + } + } +} + +/// Request-extension slot carrying the sink handle from request setup to the +/// body build; taken exactly once. +#[derive(Clone)] +pub(crate) struct RdmaSinkSlot(Arc>>); + +impl RdmaSinkSlot { + pub(crate) fn new(handle: StagingSinkHandle) -> Self { + Self(Arc::new(std::sync::Mutex::new(Some(handle)))) + } + + pub(crate) fn take(&self) -> Option { + self.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).take() + } +} + +/// Completes a GET whose body went through the sink: drains the reader (which +/// only yields the producer's completion), then flushes the sink and reports +/// the bytes moved. A producer error aborts the sink first. +pub(crate) async fn finish_get_through_sink( + mut stream: DynReader, + response_content_length: i64, + handle: StagingSinkHandle, +) -> S3Result { + let started = Instant::now(); + let mut scratch = [0u8; 4096]; + loop { + match stream.read(&mut scratch).await { + Ok(0) => break, + Ok(_) => { + // The pipe's write end was dropped unused, so nothing arrives here. + } + Err(error) => { + handle.abort().await; + return Err(transfer_error("read", CuObjectError::Source(error))); + } + } + } + let moved = handle.finish().await?; + let expected = u64::try_from(response_content_length).unwrap_or(0); + if moved != expected { + return Err(S3Error::with_message( + S3ErrorCode::InternalError, + format!("rdma get moved {moved} of {expected} bytes"), + )); + } + rustfs_io_metrics::record_get_object_stage_duration( + super::GET_OBJECT_STAGE_PATH_S3_HANDLER, + "rdma_transfer", + started.elapsed().as_secs_f64(), + ); + Ok(moved) +} diff --git a/rustfs/src/app/object/get.rs b/rustfs/src/app/object/get.rs index 44e178e64e..cad0a53c4a 100644 --- a/rustfs/src/app/object/get.rs +++ b/rustfs/src/app/object/get.rs @@ -255,7 +255,7 @@ const VERY_HIGH_CONCURRENCY_GET_OBJECT_MEMORY_BUFFER_BYTES: i64 = 1024 * 1024; const EVENT_GET_OBJECT_STREAM_BODY: &str = "get_object_stream_body"; -const GET_OBJECT_STAGE_PATH_S3_HANDLER: &str = "s3_handler"; +pub(super) const GET_OBJECT_STAGE_PATH_S3_HANDLER: &str = "s3_handler"; const GET_OBJECT_STAGE_REQUEST_INGRESS_TO_CONTEXT: &str = "request_ingress_to_context"; @@ -3026,7 +3026,13 @@ impl DefaultObjectUsecase { let range = range.clone(); let bucket = bucket.to_owned(); let key = key.to_owned(); - let opts = opts.clone(); + let mut opts = opts.clone(); + // The cold-fill producer materializes the body it reads, so it + // must drain the pipeline itself: a caller sink (cuObject + // S3-over-RDMA) would swallow the bytes and leave the + // materialization short. The RDMA reply is then served from + // the materialized body like any cache hit. + opts.get_object_sink = None; let object_traffic_health = object_traffic_health.as_ref().map(Arc::clone); async move { let producer_deadline = producer.deadline(); @@ -4087,31 +4093,94 @@ impl DefaultObjectUsecase { enable_readahead, } = strategy; let cache_adapter = self.object_data_cache(); - let body_build_start = rustfs_io_metrics::get_stage_metrics_enabled().then(std::time::Instant::now); - let body = Self::build_get_object_body_with_cache( - &cache_adapter, - final_stream, - &info, - response_content_length, - request_id, - content_range.as_deref(), - optimal_buffer_size, - enable_readahead, - concurrent_requests, - part_number, - rs.is_some(), - encryption_applied, - buffered_body, - cache_hook_served, - cache_hook_probed, - cache_fill_allowed, - bucket, - key, - lifecycle, - resume, - ) - .await?; + // Extra response headers beyond what `GetObjectOutput` carries. + #[cfg_attr( + not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")), + allow(unused_mut, reason = "mutated only by the cuObject RDMA branch") + )] + let mut extra_headers: Vec<(&'static str, String)> = Vec::new(); + #[cfg_attr( + not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")), + allow(unused_mut, reason = "mutated only by the cuObject RDMA branch") + )] + let mut http_content_length = response_content_length; + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + let rdma_token = super::cuobject::rdma_token_for_request(&req.headers); + #[cfg(not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")))] + let rdma_token: Option = None; + let body = match rdma_token { + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + Some(token) => { + // S3-over-RDMA: the object bytes go straight into the client's + // registered (GPU or host) memory; the HTTP response carries no body. + let mut lifecycle = lifecycle; + let sink_handle = req + .extensions + .get::() + .and_then(super::cuobject::RdmaSinkSlot::take); + let transfer = match sink_handle { + Some(handle) if handle.was_used() => { + super::cuobject::finish_get_through_sink(final_stream, response_content_length, handle).await + } + _ => { + super::cuobject::serve_get_over_rdma( + final_stream, + buffered_body, + response_content_length, + bucket, + key, + &token, + ) + .await + } + }; + let moved = match transfer { + Ok(moved) => moved, + Err(error) => { + lifecycle.finish_err(); + return Err(error); + } + }; + lifecycle.finish_ok(); + extra_headers.push(( + crate::app::object::cuobject::RDMA_REPLY_HEADER, + if rs.is_some() { "206" } else { "200" }.to_owned(), + )); + if moved > 0 { + extra_headers.push((crate::app::object::cuobject::RDMA_BYTES_TRANSFERRED_HEADER, moved.to_string())); + } + http_content_length = 0; + StreamingBlob::from(crate::app::storage_api::s3::Body::empty()) + } + #[cfg(not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")))] + Some(never) => match never {}, + None => { + Self::build_get_object_body_with_cache( + &cache_adapter, + final_stream, + &info, + response_content_length, + request_id, + content_range.as_deref(), + optimal_buffer_size, + enable_readahead, + concurrent_requests, + part_number, + rs.is_some(), + encryption_applied, + buffered_body, + cache_hook_served, + cache_hook_probed, + cache_fill_allowed, + bucket, + key, + lifecycle, + resume, + ) + .await? + } + }; record_get_object_s3_handler_stage_duration(GET_OBJECT_STAGE_BODY_BUILD, body_build_start); let checksum_headers_start = rustfs_io_metrics::get_stage_metrics_enabled().then(std::time::Instant::now); @@ -4141,7 +4210,7 @@ impl DefaultObjectUsecase { let parts_count = Self::get_object_parts_count(part_number, &info); let output = GetObjectOutput { body: Some(body), - content_length: Some(response_content_length), + content_length: Some(http_content_length), last_modified, content_type, content_encoding: info.content_encoding.clone(), @@ -4179,7 +4248,11 @@ impl DefaultObjectUsecase { event_info, response_content_length, optimal_buffer_size, - extra_checksum_headers: checksums.extra, + extra_checksum_headers: { + let mut extra_checksum_headers = checksums.extra; + extra_checksum_headers.extend(extra_headers); + extra_checksum_headers + }, }) } @@ -4523,6 +4596,20 @@ impl DefaultObjectUsecase { opts, } = request_context; drop(object_metadata_progress); + // cuObject S3-over-RDMA: hand the storage layer a sink that writes decoded + // bytes straight into registered staging (no pipe, no consumer copy). The + // handle rides in the request extensions until the body is built. + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + let opts = match super::cuobject::rdma_token_for_request(&req.headers) { + Some(token) => { + let handle = super::cuobject::StagingSinkHandle::new(&bucket, &key, &token).await?; + let mut opts = opts; + opts.get_object_sink = Some(handle.sink()); + req.extensions.insert(super::cuobject::RdmaSinkSlot::new(handle)); + opts + } + None => opts, + }; let manager = get_concurrency_manager(); diff --git a/rustfs/src/app/object/mod.rs b/rustfs/src/app/object/mod.rs index c7b73032aa..7dfa1b5512 100644 --- a/rustfs/src/app/object/mod.rs +++ b/rustfs/src/app/object/mod.rs @@ -204,6 +204,8 @@ fn remove_source_replication_bookkeeping(user_defined: &mut HashMap { + // Zero-copy only when the body cannot outlive the request in the + // object data cache (fill-on-put keeps it). + let zero_copy = + !i64::try_from(token.buffer_len).is_ok_and(|size| put_body_may_fill_cache(&self.object_data_cache(), size)); + let (body, total) = super::cuobject::rdma_put_body(&bucket, &key, &token, zero_copy)?; + let total = i64::try_from(total).map_err(|_| S3Error::new(S3ErrorCode::EntityTooLarge))?; + (Some(body), Some(total), Some(total)) + } + _ => (body, content_length, None), + }; + #[cfg(not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")))] + let rdma_put: Option = None; let Some(body) = body else { return Err(s3_error!(IncompleteBody)) }; let body = match max_content_length { @@ -1364,7 +1382,22 @@ impl DefaultObjectUsecase { preserve_etag: None, origin: PutObjectOrigin::S3 { req: &req, event_name }, }; - let committed = self.put_object_core(write, body, start_time).await?; + #[cfg_attr( + not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")), + allow(unused_mut, reason = "mutated only by the cuObject RDMA branch") + )] + let mut committed = self.put_object_core(write, body, start_time).await?; + #[cfg(not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")))] + let _ = rdma_put; + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + if let Some(moved) = rdma_put { + committed + .put_extra_checksum_headers + .push((crate::app::object::cuobject::RDMA_REPLY_HEADER, "200".to_owned())); + committed + .put_extra_checksum_headers + .push((crate::app::object::cuobject::RDMA_BYTES_TRANSFERRED_HEADER, moved.to_string())); + } let raw_version = s3_response_version_id(committed.obj_info.version_id); let put_version = if committed.put_versioned { raw_version } else { None }; diff --git a/rustfs/src/app/storage_api.rs b/rustfs/src/app/storage_api.rs index a570b0aa71..2c0f6c6914 100644 --- a/rustfs/src/app/storage_api.rs +++ b/rustfs/src/app/storage_api.rs @@ -52,6 +52,8 @@ pub(crate) mod s3 { PersistedOptionalReplicationStatus, PersistedReplicationConfiguration, PersistedReplicationDestination, PersistedReplicationFilter, PersistedReplicationRule, PersistedReplicationTag, }; + #[cfg(any(test, all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")))] + pub(crate) use s3s::Body; pub(crate) use s3s::S3Response; pub(crate) use s3s::StdError; #[cfg(test)] @@ -84,7 +86,7 @@ pub(crate) mod s3 { #[cfg(test)] pub(crate) use s3s::xml::{Serialize as XmlSerialize, Serializer as XmlSerializer}; #[cfg(test)] - pub(crate) use s3s::{Body, BodySizeLimitExceeded, S3}; + pub(crate) use s3s::{BodySizeLimitExceeded, S3}; pub(crate) use s3s::{S3Error, S3ErrorCode, S3Request, S3Result, TrailingHeaders}; } @@ -1778,6 +1780,18 @@ pub(crate) mod object_usecase { pub(crate) use crate::storage::storage_api::{evaluate_read_preconditions, has_read_preconditions}; } + /// Process-wide runtime facts the object use case reads (cuObject S3-over-RDMA addressing). + /// ECStore surface of the S3-over-RDMA object transport. + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + pub(crate) use crate::storage::storage_api::ecstore_rdma as rdma; + + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + pub(crate) mod runtime { + pub(crate) use super::super::runtime::get_global_endpoints_opt; + #[cfg(not(feature = "nixl"))] + pub(crate) use super::super::runtime::global_rustfs_port; + } + pub(crate) mod contract { #[cfg(test)] pub(crate) mod http { @@ -1809,6 +1823,10 @@ pub(crate) mod object_usecase { validate_object_key, validate_sse_headers_for_read, validate_sse_headers_for_write, validate_ssec_for_read, wrap_response_with_cors, }; + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + pub(crate) use crate::storage::storage_api::{ + StorageGetObjectSink, StorageGetObjectSinkSegments, StorageGetObjectSinkWriter, + }; } pub(crate) mod object_meta_usecase { diff --git a/rustfs/src/startup_server.rs b/rustfs/src/startup_server.rs index ffc9de9108..c8e3eec08b 100644 --- a/rustfs/src/startup_server.rs +++ b/rustfs/src/startup_server.rs @@ -79,6 +79,18 @@ pub(crate) struct StartupHttpServers { pub(crate) console_shutdown_tx: Option, } +/// cuObject S3-over-RDMA servers live for the process lifetime; they stop with it. +#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] +async fn init_cuobject_servers() -> Result<()> { + crate::app::object::cuobject::init_cuobject_service().await?; + Ok(()) +} + +#[cfg(not(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux")))] +async fn init_cuobject_servers() -> Result<()> { + Ok(()) +} + pub(crate) async fn init_startup_listen_context( config: &Config, instance_ctx: &Arc, @@ -290,6 +302,8 @@ pub(crate) async fn init_startup_http_servers( None => None, }; + init_cuobject_servers().await?; + Ok(StartupHttpServers { state_manager, s3_shutdown_tx: Some(s3_shutdown_tx), diff --git a/rustfs/src/storage/rpc/http_service.rs b/rustfs/src/storage/rpc/http_service.rs index 869b753bc4..8cbfb4e739 100644 --- a/rustfs/src/storage/rpc/http_service.rs +++ b/rustfs/src/storage/rpc/http_service.rs @@ -74,6 +74,8 @@ const MIGRATING_META_BUCKET: &str = ".minio.sys"; const EVENT_RPC_BACKGROUND_TASK_FAILED: &str = "rpc_background_task_failed"; const RPC_OPERATION_UNKNOWN: &str = "unknown"; const READ_FILE_STREAM_PATH: &str = "/rustfs/rpc/read_file_stream"; +#[cfg(all(feature = "nixl", target_os = "linux"))] +use crate::storage::storage_api::rpc_consumer::nixl_read::{READ_FILE_NIXL_PATH, WRITE_FILE_NIXL_PATH}; const PUT_FILE_STREAM_PATH: &str = "/rustfs/rpc/put_file_stream"; const PUT_FILE_AUTH_STREAM_PATH: &str = "/rustfs/rpc/put_file_stream_v1"; const PUT_FILE_CAPABILITY_PATH: &str = "/rustfs/rpc/put_file_capability"; @@ -82,8 +84,8 @@ const NS_SCANNER_PATH: &str = "/rustfs/rpc/ns_scanner"; const NS_SCANNER_REQUEST_BODY_TIMEOUT: Duration = Duration::from_secs(15); const NS_SCANNER_STREAM_BUFFER_SIZE: usize = 64 * 1024; static NS_SCANNER_SERVER_EPOCH: LazyLock = LazyLock::new(uuid::Uuid::new_v4); -static PUT_FILE_CAPABILITY_SERVER_EPOCH: LazyLock = LazyLock::new(uuid::Uuid::new_v4); -static PUT_FILE_AUTH_STRICT: LazyLock = LazyLock::new(|| { +pub(super) static PUT_FILE_CAPABILITY_SERVER_EPOCH: LazyLock = LazyLock::new(uuid::Uuid::new_v4); +pub(super) static PUT_FILE_AUTH_STRICT: LazyLock = LazyLock::new(|| { rustfs_utils::get_env_bool( rustfs_config::ENV_INTERNODE_RPC_BODY_DIGEST_STRICT, rustfs_config::DEFAULT_INTERNODE_RPC_BODY_DIGEST_STRICT, @@ -429,15 +431,15 @@ fn validate_walk_dir_completion_request(query: &WalkDirQuery, body: &[u8]) -> Op } #[derive(Clone, Debug, Default, serde::Deserialize)] -struct PutFileQuery { - disk: String, - volume: String, - path: String, - append: bool, - size: i64, - put_file_auth: Option, - put_file_nonce: Option, - put_file_server_epoch: Option, +pub(super) struct PutFileQuery { + pub(super) disk: String, + pub(super) volume: String, + pub(super) path: String, + pub(super) append: bool, + pub(super) size: i64, + pub(super) put_file_auth: Option, + pub(super) put_file_nonce: Option, + pub(super) put_file_server_epoch: Option, } #[derive(Debug, Default, serde::Deserialize)] @@ -470,7 +472,7 @@ fn put_file_server_epoch_matches(query: &PutFileQuery) -> bool { query.put_file_server_epoch == Some(*PUT_FILE_CAPABILITY_SERVER_EPOCH) } -fn put_file_server_epoch_accepted(query: &PutFileQuery, strict: bool) -> bool { +pub(super) fn put_file_server_epoch_accepted(query: &PutFileQuery, strict: bool) -> bool { if put_file_server_epoch_matches(query) { return true; } @@ -565,6 +567,10 @@ async fn handle_internode_rpc( None => response_with_status(StatusCode::NOT_FOUND, "internode rpc route not found"), }, (Method::GET, READ_FILE_STREAM_PATH) | (Method::HEAD, READ_FILE_STREAM_PATH) => handle_read_file(req).await, + #[cfg(all(feature = "nixl", target_os = "linux"))] + (Method::GET, READ_FILE_NIXL_PATH) => super::nixl_read::handle_read_file_nixl(req).await, + #[cfg(all(feature = "nixl", target_os = "linux"))] + (Method::PUT, WRITE_FILE_NIXL_PATH) => super::nixl_read::handle_write_file_nixl(req).await, (Method::GET, WALK_DIR_PATH) | (Method::HEAD, WALK_DIR_PATH) => handle_walk_dir(req).await, (Method::GET, NS_SCANNER_PATH) => match parse_query::(&req) { Ok(query) if query.ns_scanner_protocol == Some(NS_SCANNER_PROTOCOL_VERSION) => match query.ns_scanner_challenge { @@ -636,6 +642,10 @@ fn emit_internode_rpc_telemetry(started_at: Instant, status: StatusCode) { fn internode_http_operation(path: &str) -> Option<&'static str> { match path { READ_FILE_STREAM_PATH => Some(INTERNODE_OPERATION_READ_FILE_STREAM), + #[cfg(all(feature = "nixl", target_os = "linux"))] + READ_FILE_NIXL_PATH => Some(INTERNODE_OPERATION_READ_FILE_STREAM), + #[cfg(all(feature = "nixl", target_os = "linux"))] + WRITE_FILE_NIXL_PATH => Some(INTERNODE_OPERATION_PUT_FILE_STREAM), PUT_FILE_STREAM_PATH | PUT_FILE_AUTH_STREAM_PATH => Some(INTERNODE_OPERATION_PUT_FILE_STREAM), PUT_FILE_CAPABILITY_PATH => Some(INTERNODE_OPERATION_PUT_FILE_CAPABILITY), WALK_DIR_PATH => Some(INTERNODE_OPERATION_WALK_DIR), @@ -1188,7 +1198,7 @@ fn legacy_meta_alias_can_retry(error: &DiskError, volume: &str) -> bool { matches!(error, DiskError::FileNotFound | DiskError::VolumeNotFound) && legacy_meta_bucket_alias(volume).is_some() } -async fn read_file_stream_with_legacy_meta_fallback( +pub(super) async fn read_file_stream_with_legacy_meta_fallback( disk: &DiskStore, volume: &str, path: &str, @@ -1714,7 +1724,7 @@ async fn remove_put_file_staging(disk: &DiskStore, volume: &str, path: &str) -> .map_err(Into::into) } -fn write_authenticated_put_file( +pub(super) fn write_authenticated_put_file( disk: &DiskStore, body: S, query: &PutFileQuery, diff --git a/rustfs/src/storage/rpc/mod.rs b/rustfs/src/storage/rpc/mod.rs index 0ad147860e..64e6435f22 100644 --- a/rustfs/src/storage/rpc/mod.rs +++ b/rustfs/src/storage/rpc/mod.rs @@ -15,6 +15,8 @@ #[cfg(feature = "internode-transport")] pub mod external_transport; pub mod http_service; +#[cfg(all(feature = "nixl", target_os = "linux"))] +pub mod nixl_read; pub mod node_service; pub use http_service::InternodeRpcService; @@ -31,6 +33,33 @@ use serde::Serialize; /// Uses `.with_struct_map()` so structs are serialized with named fields /// (msgpack map) instead of positional arrays. This matches what the /// client-side `Deserializer::new()` expects. +/// Opens a shard file for positional reads (the NIXL serve path) and +/// refuses it unless the opened file lies inside its volume directory: `path` +/// passed the string-level containment check, but a symlink inside the volume +/// could still point elsewhere. The check reads the opened descriptor's real +/// path, so nothing can change between the check and the use. +#[cfg(all(feature = "nixl", target_os = "linux"))] +pub(crate) fn open_shard_contained(path: &std::path::Path, key: &str) -> std::io::Result { + let file = std::fs::File::open(path)?; + #[cfg(target_os = "linux")] + { + use std::os::fd::AsRawFd; + let mut volume = path.to_path_buf(); + for _ in std::path::Path::new(key).components() { + volume.pop(); + } + let volume = std::fs::canonicalize(&volume)?; + let opened = std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd()))?; + if !opened.starts_with(&volume) { + return Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "shard path resolves outside its volume", + )); + } + } + Ok(file) +} + pub(crate) fn encode_msgpack_map(value: &T) -> Result, rmp_serde::encode::Error> { let mut buf = Vec::new(); value.serialize(&mut Serializer::new(&mut buf).with_struct_map())?; @@ -39,6 +68,23 @@ pub(crate) fn encode_msgpack_map(value: &T) -> Result, rmp #[cfg(test)] mod tests { + #[cfg(all(target_os = "linux", feature = "nixl"))] + #[test] + fn shard_opens_stay_inside_their_volume() { + let base = std::env::temp_dir().join(format!("rustfs-shard-open-{}", std::process::id())); + let volume = base.join("disk").join("bucket"); + std::fs::create_dir_all(volume.join("obj")).expect("volume"); + std::fs::write(volume.join("obj").join("part.1"), b"shard").expect("shard"); + std::fs::create_dir_all(base.join("outside")).expect("outside"); + std::fs::write(base.join("outside").join("secret"), b"secret").expect("secret"); + std::os::unix::fs::symlink(base.join("outside"), volume.join("link")).expect("symlink"); + + assert!(super::open_shard_contained(&volume.join("obj").join("part.1"), "obj/part.1").is_ok()); + let escaped = super::open_shard_contained(&volume.join("link").join("secret"), "link/secret"); + assert_eq!(escaped.expect_err("symlink escape").kind(), std::io::ErrorKind::PermissionDenied); + let _ = std::fs::remove_dir_all(&base); + } + use super::encode_msgpack_map; use rmp_serde::{Deserializer, Serializer}; use rustfs_madmin::{BackendDisks, BackendInfo, Disk, ITEM_ONLINE, StorageInfo}; diff --git a/rustfs/src/storage/rpc/nixl_read.rs b/rustfs/src/storage/rpc/nixl_read.rs new file mode 100644 index 0000000000..c75aac535d --- /dev/null +++ b/rustfs/src/storage/rpc/nixl_read.rs @@ -0,0 +1,357 @@ +// 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. + +//! Serving side of internode NIXL chunk reads and shard writes. +//! +//! A peer asks for one range of a shard file on a local disk and names a +//! buffer registered with its NIXL agent (signed query); this node reads the +//! range into its own registered staging memory and writes it into that buffer +//! with a NIXL WRITE before answering with the byte count. The request's +//! signature is checked by the internode dispatcher before it reaches here. + +use crate::storage::storage_api::rpc_consumer::nixl_read::{ + Disk, DiskAPI as _, NIXL_BYTES_HEADER, NIXL_METADATA_HEADER, WRITE_FILE_NIXL_PATH, check_and_record_signed_rpc_nonce, + find_local_disk_by_ref_for_rpc, +}; +use http::{HeaderValue, Request, Response, StatusCode}; +use hyper::body::Incoming; +use rustfs_io_metrics::internode_metrics::{INTERNODE_OPERATION_PUT_FILE_STREAM, INTERNODE_TRANSPORT_BACKEND_RDMA}; +use rustfs_nixl::RdmaToken; +use rustfs_s3_types::Body; +use sha2::{Digest, Sha256}; +use std::sync::{Arc, OnceLock}; +use std::time::Duration; +use tokio::io::{AsyncWrite, AsyncWriteExt}; +use tracing::warn; + +/// This node's NIXL agent, installed by the S3-over-RDMA service once it runs. +/// It lives here, below the app layer, so these handlers can reach it. +static NIXL_SERVER: OnceLock> = OnceLock::new(); + +/// Records this node's NIXL agent; the first installation wins. +pub(crate) fn install_nixl_server(server: Arc) { + let _ = NIXL_SERVER.set(server); +} + +/// This node's NIXL agent, once the transport service is running. +pub(crate) fn nixl_server() -> Option> { + NIXL_SERVER.get().cloned() +} + +/// Finishes one segment's file. A flush is not enough: the direct-I/O disk +/// writer writes its trailing sub-alignment bytes only on shutdown, so a +/// segment closed with a flush loses its tail (as the TCP put-file path, +/// this shuts the writer down). +async fn finish_segment_file(file: &mut W) -> std::io::Result<()> { + file.shutdown().await +} + +const EVENT_NIXL_INTERNODE_READ: &str = "nixl_internode_read"; +const LOG_COMPONENT_INTERNODE_RPC: &str = "internode_rpc"; +const LOG_SUBSYSTEM_NIXL: &str = "nixl"; +/// How long a request waits for a free staging chunk before it is refused. +const STAGING_WAIT: Duration = Duration::from_secs(30); + +#[derive(Debug, serde::Deserialize)] +struct NixlReadQuery { + disk: String, + volume: String, + path: String, + offset: u64, + length: usize, + nixl_agent: String, + nixl_buffer: String, + nixl_md: String, +} + +fn reply(status: StatusCode, message: impl Into) -> Response { + let mut response = Response::new(Body::from(message.into())); + *response.status_mut() = status; + response +} + +fn refuse(status: StatusCode, reason: &'static str, detail: impl std::fmt::Display) -> Response { + warn!( + event = EVENT_NIXL_INTERNODE_READ, + component = LOG_COMPONENT_INTERNODE_RPC, + subsystem = LOG_SUBSYSTEM_NIXL, + result = "refused", + status_code = status.as_u16(), + reason, + detail = %detail, + "nixl internode read refused" + ); + reply(status, reason) +} + +/// Lowercase hex SHA-256 of `bytes`. +pub(crate) fn sha256_hex(bytes: &[u8]) -> String { + hex_simd::encode_to_string(Sha256::digest(bytes), hex_simd::AsciiCase::Lower) +} + +pub(crate) async fn handle_read_file_nixl(req: Request) -> Response { + let query: NixlReadQuery = match serde_urlencoded::from_str(req.uri().query().unwrap_or_default()) { + Ok(query) => query, + Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_query", error), + }; + let Some(server) = nixl_server() else { + return reply(StatusCode::SERVICE_UNAVAILABLE, "nixl transport is not running on this node"); + }; + + // The metadata travels unsigned in a header; it must match the signed digest, + // so a replayed request cannot point the transfer at another endpoint. + let metadata = match req.headers().get(NIXL_METADATA_HEADER).map(HeaderValue::to_str) { + Some(Ok(value)) => Some(value), + Some(Err(_)) => return refuse(StatusCode::BAD_REQUEST, "bad_metadata_header", "not ascii"), + None => None, + }; + if let Some(encoded) = metadata { + let raw = match base64_simd::STANDARD.decode_to_vec(encoded) { + Ok(raw) => raw, + Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_metadata_encoding", error), + }; + if sha256_hex(&raw) != query.nixl_md.to_ascii_lowercase() { + return refuse(StatusCode::FORBIDDEN, "metadata_digest_mismatch", &query.nixl_agent); + } + } + let token = match RdmaToken::from_headers(&query.nixl_agent, metadata, &query.nixl_buffer) { + Ok(token) => token, + Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_nixl_token", error), + }; + if query.length == 0 || query.length as u64 > token.buffer_len || query.length > server.chunk_bytes() { + return refuse(StatusCode::BAD_REQUEST, "bad_length", query.length); + } + + let disk = match find_local_disk_by_ref_for_rpc(&query.disk).await { + Ok(Some(disk)) => disk, + Ok(None) => return refuse(StatusCode::BAD_REQUEST, "disk_not_found", &query.disk), + Err(_) => return reply(StatusCode::SERVICE_UNAVAILABLE, "background storage admission deferred"), + }; + let Disk::Local(local) = disk.as_ref() else { + return refuse(StatusCode::BAD_REQUEST, "disk_not_local", &query.disk); + }; + let path = match local.get_object_path_if_local(&query.volume, &query.path) { + Ok(path) => path, + Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_path", error), + }; + + let chunk = match server.reserve(STAGING_WAIT).await { + Ok(chunk) => chunk, + Err(error) => return refuse(StatusCode::SERVICE_UNAVAILABLE, "staging_exhausted", error), + }; + let (offset, length, key) = (query.offset, query.length, query.path.clone()); + let read = tokio::task::spawn_blocking(move || -> std::io::Result { + use std::os::unix::fs::FileExt; + let mut chunk = chunk; + let file = super::open_shard_contained(&path, &key)?; + let spare = chunk.spare_mut().map_err(std::io::Error::other)?; + let dst = &mut spare[..length]; + let mut filled = 0; + while filled < dst.len() { + let n = file.read_at(&mut dst[filled..], offset + filled as u64)?; + if n == 0 { + break; + } + filled += n; + } + chunk.advance(filled).map_err(std::io::Error::other)?; + Ok(chunk) + }) + .await; + let chunk = match read { + Ok(Ok(chunk)) => chunk, + Ok(Err(error)) if error.kind() == std::io::ErrorKind::NotFound => { + return reply(StatusCode::NOT_FOUND, "file not found"); + } + Ok(Err(error)) if error.kind() == std::io::ErrorKind::PermissionDenied => { + return refuse(StatusCode::FORBIDDEN, "path_outside_volume", error); + } + Ok(Err(error)) => return refuse(StatusCode::INTERNAL_SERVER_ERROR, "read_failed", error), + Err(error) => return refuse(StatusCode::INTERNAL_SERVER_ERROR, "read_task_failed", error), + }; + + let landed = chunk.len(); + if landed > 0 + && let Err(error) = server.write_to_client_owned(&query.path, &token, 0, chunk).await + { + return refuse(StatusCode::BAD_GATEWAY, "nixl_write_failed", error); + } + let mut response = reply(StatusCode::OK, ""); + response + .headers_mut() + .insert(NIXL_BYTES_HEADER, HeaderValue::from(landed as u64)); + response +} + +#[derive(Debug, serde::Deserialize)] +struct NixlWriteQuery { + disk: String, + volume: String, + path: String, + append: bool, + size: i64, + last: bool, + nixl_nonce: uuid::Uuid, + nixl_agent: String, + nixl_buffers: String, + nixl_md: String, +} + +/// A segment of a shard write: pull every named buffer from the writer's +/// agent (NIXL READ) and write it at the end of the file through the same +/// disk writer the TCP path uses. The nonce is recorded so a replayed request +/// is refused; the signature covers the buffers and the metadata digest. +pub(crate) async fn handle_write_file_nixl(req: Request) -> Response { + let query: NixlWriteQuery = match serde_urlencoded::from_str(req.uri().query().unwrap_or_default()) { + Ok(query) => query, + Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_query", error), + }; + if let Err(error) = check_and_record_signed_rpc_nonce( + req.headers(), + query.nixl_nonce, + WRITE_FILE_NIXL_PATH, + INTERNODE_OPERATION_PUT_FILE_STREAM, + INTERNODE_TRANSPORT_BACKEND_RDMA, + ) { + return refuse(StatusCode::FORBIDDEN, "nonce_rejected", error); + } + let Some(server) = nixl_server() else { + return reply(StatusCode::SERVICE_UNAVAILABLE, "nixl transport is not running on this node"); + }; + let metadata = match req.headers().get(NIXL_METADATA_HEADER).map(HeaderValue::to_str) { + Some(Ok(value)) => Some(value), + Some(Err(_)) => return refuse(StatusCode::BAD_REQUEST, "bad_metadata_header", "not ascii"), + None => None, + }; + if let Some(encoded) = metadata { + let raw = match base64_simd::STANDARD.decode_to_vec(encoded) { + Ok(raw) => raw, + Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_metadata_encoding", error), + }; + if sha256_hex(&raw) != query.nixl_md.to_ascii_lowercase() { + return refuse(StatusCode::FORBIDDEN, "metadata_digest_mismatch", &query.nixl_agent); + } + } + let mut tokens = Vec::new(); + for descriptor in query.nixl_buffers.split(',').filter(|descriptor| !descriptor.is_empty()) { + match RdmaToken::from_headers(&query.nixl_agent, metadata, descriptor) { + Ok(token) if token.buffer_len as usize <= server.chunk_bytes() => tokens.push(token), + Ok(token) => return refuse(StatusCode::BAD_REQUEST, "buffer_too_large", token.buffer_len), + Err(error) => return refuse(StatusCode::BAD_REQUEST, "bad_nixl_token", error), + } + } + + let disk = match find_local_disk_by_ref_for_rpc(&query.disk).await { + Ok(Some(disk)) => disk, + Ok(None) => return refuse(StatusCode::BAD_REQUEST, "disk_not_found", &query.disk), + Err(_) => return reply(StatusCode::SERVICE_UNAVAILABLE, "background storage admission deferred"), + }; + let opened = if query.append { + disk.append_file(&query.volume, &query.path).await + } else { + disk.create_file("", &query.volume, &query.path, query.size).await + }; + let mut file = match opened { + Ok(file) => file, + Err(error) => return refuse(StatusCode::INTERNAL_SERVER_ERROR, "open_failed", error), + }; + + let mut written: u64 = 0; + for token in &tokens { + let len = token.buffer_len as usize; + let chunk = match server.reserve(STAGING_WAIT).await { + Ok(chunk) => chunk, + Err(error) => return refuse(StatusCode::SERVICE_UNAVAILABLE, "staging_exhausted", error), + }; + let read_started = rustfs_io_metrics::put_stage_timer(); + let chunk = match server.read_from_client_owned(&query.path, token, 0, len, chunk).await { + Ok(chunk) => chunk, + Err(error) => return refuse(StatusCode::BAD_GATEWAY, "nixl_read_failed", error), + }; + rustfs_io_metrics::record_put_object_stage_duration_from("nixl_write_file_read", read_started); + let staged = match chunk.staged() { + Ok(staged) => staged, + Err(error) => return refuse(StatusCode::INTERNAL_SERVER_ERROR, "staging_view_failed", error), + }; + let write_started = rustfs_io_metrics::put_stage_timer(); + if let Err(error) = file.write_all(staged).await { + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "write_failed", error); + } + rustfs_io_metrics::record_put_object_stage_duration_from("nixl_write_file_write", write_started); + written += len as u64; + } + if !query.append && query.last && query.size > 0 && written != query.size as u64 { + return refuse( + StatusCode::INTERNAL_SERVER_ERROR, + "size_mismatch", + format!("expected {} bytes, received {written}", query.size), + ); + } + let finish_started = rustfs_io_metrics::put_stage_timer(); + if let Err(error) = finish_segment_file(&mut file).await { + return refuse(StatusCode::INTERNAL_SERVER_ERROR, "finish_failed", error); + } + rustfs_io_metrics::record_put_object_stage_duration_from("nixl_write_file_finish", finish_started); + let mut response = reply(StatusCode::OK, ""); + response.headers_mut().insert(NIXL_BYTES_HEADER, HeaderValue::from(written)); + response +} + +#[cfg(test)] +mod tests { + use super::finish_segment_file; + use std::pin::Pin; + use std::task::{Context, Poll}; + use tokio::io::{AsyncWrite, AsyncWriteExt}; + + /// Writes whole 4 KiB blocks as they fill and the remainder only on + /// shutdown, like the direct-I/O disk writer. + #[derive(Default)] + struct TailOnShutdown { + written: Vec, + staged: Vec, + } + + impl AsyncWrite for TailOnShutdown { + fn poll_write(mut self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8]) -> Poll> { + self.staged.extend_from_slice(buf); + let whole = self.staged.len() / 4096 * 4096; + let block: Vec = self.staged.drain(..whole).collect(); + self.written.extend_from_slice(&block); + Poll::Ready(Ok(buf.len())) + } + + fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn poll_shutdown(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll> { + let tail = std::mem::take(&mut self.staged); + self.written.extend_from_slice(&tail); + Poll::Ready(Ok(())) + } + } + + #[tokio::test] + async fn finishing_a_segment_writes_the_sub_alignment_tail() { + let data: Vec = (0..10_000u32).map(|i| i as u8).collect(); + let mut file = TailOnShutdown::default(); + file.write_all(&data).await.expect("write"); + file.flush().await.expect("flush"); + assert_eq!(file.written.len(), 8192, "a flush leaves the tail staged"); + + finish_segment_file(&mut file).await.expect("finish"); + assert_eq!(file.written, data, "finishing the segment must write every byte"); + } +} diff --git a/rustfs/src/storage/storage_api.rs b/rustfs/src/storage/storage_api.rs index 759f1a213b..adf9846bad 100644 --- a/rustfs/src/storage/storage_api.rs +++ b/rustfs/src/storage/storage_api.rs @@ -125,6 +125,12 @@ pub(crate) type StorageGetObjectReader = super::GetObjectReader; pub(crate) type StorageObjectInfo = super::ObjectInfo; pub(crate) type StorageObjectLockDeleteOptions = contract::object::ObjectLockDeleteOptions; pub(crate) type StorageObjectOptions = super::ObjectOptions; +#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] +pub(crate) type StorageGetObjectSink = ecstore_object::GetObjectSink; +#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] +pub(crate) type StorageGetObjectSinkSegments = ecstore_object::GetObjectSinkSegments; +#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] +pub(crate) type StorageGetObjectSinkWriter = ecstore_object::GetObjectSinkWriter; pub(crate) type StoragePrepareSelectObjectSnapshotError = ecstore_object::PrepareSelectObjectSnapshotError; pub(crate) type StorageSelectObjectSnapshot = ecstore_object::SelectObjectSnapshot; pub(crate) type StorageObjectToDelete = contract::object::ObjectToDelete; @@ -328,6 +334,18 @@ pub(crate) mod rpc_consumer { }; } + /// Server side of internode NIXL chunk reads (`nixl` feature). + #[cfg(all(feature = "nixl", target_os = "linux"))] + pub(crate) mod nixl_read { + pub(crate) use super::super::check_and_record_signed_rpc_nonce; + pub(crate) use super::super::ecstore_disk::DiskAPI; + pub(crate) use super::super::find_local_disk_by_ref_for_rpc; + pub(crate) use rustfs_ecstore::api::disk::Disk; + pub(crate) use rustfs_ecstore::api::rpc::nixl::{ + NIXL_BYTES_HEADER, NIXL_METADATA_HEADER, READ_FILE_NIXL_PATH, WRITE_FILE_NIXL_PATH, + }; + } + pub(crate) mod node_service { pub(crate) use super::super::ecstore_rpc::decode_heal_bucket_rpc_options; pub(crate) use super::super::storage_contracts::{ @@ -632,6 +650,14 @@ pub(crate) mod ecstore_rio { }; } +/// ECStore surface of the S3-over-RDMA object transport (`cuobject`/`nixl` features). +#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] +pub(crate) mod ecstore_rdma { + pub(crate) use rustfs_ecstore::api::object::{RegisteredSlabArena, ShardBuf, ShardEmitter, install_shard_arena}; + #[cfg(feature = "nixl")] + pub(crate) use rustfs_ecstore::api::rpc::nixl::{NixlRecvBuffer, NixlRecvPool, install_nixl_recv_pool}; +} + #[cfg(feature = "internode-transport")] pub(crate) mod ecstore_internode { pub use ecstore_rpc::{ @@ -680,6 +706,8 @@ pub(crate) mod ecstore_object { 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, with_get_object_read_condition, }; + #[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))] + pub(crate) use rustfs_ecstore::api::object::{GetObjectSink, GetObjectSinkSegments, GetObjectSinkWriter}; } #[cfg(all(test, feature = "rio-v2"))]