mirror of
https://github.com/rustfs/rustfs.git
synced 2026-11-29 03:51:55 +08:00
feat: S3-over-RDMA with NIXL and cuObject transports
A signed S3 request with an empty body names a registered client buffer; the server moves the object bytes with one-sided RDMA (NIXL/UCX, or NVIDIA cuObject through the cuobject crate) instead of the HTTP body. Internode shard reads and writes can also move over NIXL. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a679d7d110
commit
0f3c19a0f8
33 files changed
+5992
-67
No files matched your search
Generated
+252
-4
@@ -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",
|
||||
@@ -1621,6 +1621,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"
|
||||
@@ -1636,7 +1665,7 @@ dependencies = [
|
||||
"quote",
|
||||
"regex",
|
||||
"rustc-hash",
|
||||
"shlex",
|
||||
"shlex 2.0.1",
|
||||
"syn 3.0.9",
|
||||
]
|
||||
|
||||
@@ -1769,6 +1798,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"
|
||||
@@ -2090,7 +2128,7 @@ dependencies = [
|
||||
"find-msvc-tools",
|
||||
"jobserver",
|
||||
"libc",
|
||||
"shlex",
|
||||
"shlex 2.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2774,6 +2812,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"
|
||||
@@ -6949,6 +7008,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"
|
||||
@@ -7180,6 +7256,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"
|
||||
@@ -7191,6 +7288,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"
|
||||
@@ -7204,7 +7346,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]]
|
||||
@@ -7217,6 +7362,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"
|
||||
@@ -7228,6 +7384,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"
|
||||
@@ -7237,6 +7405,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"
|
||||
@@ -7492,6 +7691,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"
|
||||
@@ -9605,6 +9820,7 @@ dependencies = [
|
||||
"rustfs-config",
|
||||
"rustfs-credentials",
|
||||
"rustfs-crypto",
|
||||
"rustfs-cuobject",
|
||||
"rustfs-data-usage",
|
||||
"rustfs-ecstore",
|
||||
"rustfs-extension-schema",
|
||||
@@ -9623,6 +9839,7 @@ dependencies = [
|
||||
"rustfs-madmin",
|
||||
"rustfs-mimalloc",
|
||||
"rustfs-mimalloc-sys",
|
||||
"rustfs-nixl",
|
||||
"rustfs-notify",
|
||||
"rustfs-object-capacity",
|
||||
"rustfs-object-data-cache",
|
||||
@@ -9811,6 +10028,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"
|
||||
@@ -10404,6 +10632,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"
|
||||
@@ -11963,6 +12205,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"
|
||||
@@ -14366,7 +14614,7 @@ version = "2.1.2+zstd.1.5.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"bindgen 0.73.2",
|
||||
"cc",
|
||||
"pkg-config",
|
||||
]
|
||||
@@ -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" }
|
||||
@@ -298,6 +302,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"
|
||||
|
||||
@@ -323,8 +323,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-<first local endpoint host>`.
|
||||
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 {
|
||||
@@ -455,6 +577,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"]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[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 }
|
||||
cuobject = { workspace = true }
|
||||
parking_lot = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true, features = ["net", "rt-multi-thread", "sync", "time"] }
|
||||
@@ -0,0 +1,768 @@
|
||||
// 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.
|
||||
|
||||
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<cuobject::Error> 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<Self, CuObjectError> {
|
||||
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<Arc<Server>>,
|
||||
free: parking_lot::Mutex<VecDeque<usize>>,
|
||||
permits: Semaphore,
|
||||
chunk_bytes: usize,
|
||||
}
|
||||
|
||||
/// One cuObject server bound to the RDMA device that owns an IP address.
|
||||
pub struct CuObjectServer {
|
||||
server: Arc<Server>,
|
||||
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<Semaphore>,
|
||||
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<RegisteredArena>,
|
||||
/// `(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<RegisteredArena>,
|
||||
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<Arc<Server>>,
|
||||
server: Arc<CuObjectServer>,
|
||||
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<CuObjectServer> {
|
||||
&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<CuObjectServer>,
|
||||
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<RegisteredArena>,
|
||||
offset: usize,
|
||||
len: usize,
|
||||
},
|
||||
/// Several ranges of a caller-owned arena, sent as one operation.
|
||||
ArenaList {
|
||||
arena: Arc<RegisteredArena>,
|
||||
entries: Vec<SgEntry>,
|
||||
},
|
||||
}
|
||||
|
||||
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<cuobject::Error> 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<Arc<Self>, 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<Self>, timeout: Duration) -> Result<StagingChunk, CuObjectError> {
|
||||
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<Self>) -> Option<StagingChunk> {
|
||||
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<Self>, len: usize) -> Result<Arc<RegisteredArena>, 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<Self>,
|
||||
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<T: Send + 'static>(
|
||||
self: &Arc<Self>,
|
||||
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<T: Send + 'static>(
|
||||
self: &Arc<Self>,
|
||||
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<Self>,
|
||||
key: &str,
|
||||
token: &RdmaToken,
|
||||
remote_offset: u64,
|
||||
len: usize,
|
||||
mut chunk: StagingChunk,
|
||||
) -> Result<StagingChunk, CuObjectError> {
|
||||
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<tokio::sync::OwnedSemaphorePermit, CuObjectError> {
|
||||
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<T: Send + 'static>(
|
||||
self: &Arc<Self>,
|
||||
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.
|
||||
#[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<SgBuffer<'a, Arc<Server>>>,
|
||||
) -> Result<Source<'l, Arc<Server>>, 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<u64, CuObjectError> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -654,6 +654,15 @@ pub mod rio {
|
||||
|
||||
pub mod rpc {
|
||||
pub use crate::cluster::rpc::http_auth::with_rpc_background_request;
|
||||
/// 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,
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -30,8 +30,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,
|
||||
@@ -63,7 +63,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";
|
||||
@@ -89,7 +89,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 },
|
||||
}
|
||||
@@ -118,8 +118,8 @@ struct PutFileCapabilityFlight {
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct PutFileCapabilityCacheState {
|
||||
cached: Option<PutFileCapabilityState>,
|
||||
pub(super) struct PutFileCapabilityCacheState {
|
||||
pub(super) cached: Option<PutFileCapabilityState>,
|
||||
generation: u64,
|
||||
in_flight: Option<PutFileCapabilityFlight>,
|
||||
rejected_server_epoch: Option<Uuid>,
|
||||
@@ -128,12 +128,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<parking_lot::RwLock<PutFileCapabilityCacheState>>;
|
||||
pub(super) type PutFileCapabilityCacheEntry = Arc<parking_lot::RwLock<PutFileCapabilityCacheState>>;
|
||||
|
||||
static PUT_FILE_CAPABILITY_CACHE: LazyLock<parking_lot::RwLock<HashMap<String, PutFileCapabilityCacheEntry>>> =
|
||||
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;
|
||||
}
|
||||
@@ -155,7 +155,7 @@ fn fresh_put_file_capability(state: Option<PutFileCapabilityState>, 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();
|
||||
@@ -525,7 +525,7 @@ impl TcpHttpInternodeDataTransport {
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn put_file_auth_capability(&self, endpoint: &str) -> Result<Option<Uuid>> {
|
||||
pub(super) async fn put_file_auth_capability(&self, endpoint: &str) -> Result<Option<Uuid>> {
|
||||
resolve_put_file_auth_capability(endpoint, || async {
|
||||
tokio::time::timeout(PUT_FILE_CAPABILITY_PROBE_TIMEOUT, self.probe_put_file_auth(endpoint))
|
||||
.await
|
||||
@@ -655,7 +655,7 @@ fn verify_put_file_capability_response(challenge: Uuid, body: &[u8]) -> Result<U
|
||||
Ok(response.server_epoch)
|
||||
}
|
||||
|
||||
fn build_read_file_stream_url(request: &ReadStreamRequest) -> String {
|
||||
pub(super) fn build_read_file_stream_url(request: &ReadStreamRequest) -> String {
|
||||
format!(
|
||||
"{}{}?disk={}&volume={}&path={}&offset={}&length={}",
|
||||
request.endpoint,
|
||||
@@ -705,7 +705,7 @@ fn build_put_file_capability_url(endpoint: &str, challenge: Uuid) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
struct PutFileAuthWriter<W> {
|
||||
pub(super) struct PutFileAuthWriter<W> {
|
||||
inner: W,
|
||||
url: String,
|
||||
nonce: Uuid,
|
||||
@@ -718,7 +718,7 @@ struct PutFileAuthWriter<W> {
|
||||
}
|
||||
|
||||
impl<W> PutFileAuthWriter<W> {
|
||||
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,
|
||||
@@ -910,7 +910,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
|
||||
@@ -933,6 +933,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)),
|
||||
}
|
||||
}
|
||||
@@ -2238,14 +2241,22 @@ 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 {
|
||||
for configured in [DEFAULT_INTERNODE_DATA_TRANSPORT, INTERNODE_DATA_TRANSPORT_TCP] {
|
||||
let transport = build_internode_data_transport(Some(configured)).unwrap();
|
||||
|
||||
assert_eq!(transport.name(), DEFAULT_INTERNODE_DATA_TRANSPORT);
|
||||
}
|
||||
// NIXL builds everywhere and serves reads over TCP/HTTP until a node
|
||||
// installs its receive pool.
|
||||
let transport = build_internode_data_transport(Some(INTERNODE_DATA_TRANSPORT_NIXL)).unwrap();
|
||||
assert_eq!(transport.name(), INTERNODE_DATA_TRANSPORT_NIXL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,771 @@
|
||||
// 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<Box<dyn NixlRecvBuffer>>>;
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// `<dram|vram>:<device>:<address>:<length>` 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<Self>, len: usize) -> io::Result<Bytes>;
|
||||
}
|
||||
|
||||
static RECV_POOL: OnceLock<Arc<dyn NixlRecvPool>> = OnceLock::new();
|
||||
|
||||
/// Installs this node's receive pool; only the first installation wins.
|
||||
pub fn install_nixl_recv_pool(pool: Arc<dyn NixlRecvPool>) -> bool {
|
||||
RECV_POOL.set(pool).is_ok()
|
||||
}
|
||||
|
||||
fn recv_pool() -> Option<Arc<dyn NixlRecvPool>> {
|
||||
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<NixlChunkReader> {
|
||||
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<FileReader> {
|
||||
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<FileReader> {
|
||||
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<Option<ChunkReaderBox>> {
|
||||
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<Option<ChunkReaderBox>> {
|
||||
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<FileWriter> {
|
||||
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<FileReader> {
|
||||
self.tcp.open_walk_dir(request).await
|
||||
}
|
||||
|
||||
async fn open_ns_scanner(&self, request: NsScannerStreamRequest) -> Result<FileReader> {
|
||||
self.tcp.open_ns_scanner(request).await
|
||||
}
|
||||
|
||||
async fn probe_ns_scanner(&self, request: NsScannerCapabilityRequest) -> Result<Uuid> {
|
||||
self.tcp.probe_ns_scanner(request).await
|
||||
}
|
||||
|
||||
async fn probe_ns_scanner_capability(&self, request: NsScannerCapabilityRequest) -> Result<NsScannerCapabilityResponse> {
|
||||
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<Box<dyn NixlRecvBuffer>>,
|
||||
}
|
||||
|
||||
impl LentBuffer {
|
||||
fn complete(mut self, len: usize) -> io::Result<Bytes> {
|
||||
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<dyn NixlRecvPool>, 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() {
|
||||
return Err(io::Error::other(format!("nixl internode read returned {status}")));
|
||||
}
|
||||
let landed = response_headers
|
||||
.get(NIXL_BYTES_HEADER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.parse::<usize>().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<dyn NixlRecvPool>,
|
||||
base: ReadStreamRequest,
|
||||
next: usize,
|
||||
end: usize,
|
||||
chunk: usize,
|
||||
depth: usize,
|
||||
timeout: Duration,
|
||||
inflight: FuturesOrdered<ChunkFuture>,
|
||||
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<io::Result<Option<Bytes>>> {
|
||||
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<ReaderState>,
|
||||
}
|
||||
|
||||
impl NixlChunkReader {
|
||||
fn new(pool: Arc<dyn NixlRecvPool>, 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<io::Result<Option<Bytes>>> {
|
||||
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<io::Result<()>> {
|
||||
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<dyn NixlRecvPool>,
|
||||
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::<Vec<_>>()
|
||||
.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() {
|
||||
return Err(io::Error::other(format!(
|
||||
"nixl internode write returned {status}: {}",
|
||||
String::from_utf8_lossy(&body)
|
||||
)));
|
||||
}
|
||||
let written = response_headers
|
||||
.get(NIXL_BYTES_HEADER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.parse::<usize>().ok());
|
||||
if written != Some(total) {
|
||||
return Err(io::Error::other(format!("nixl internode write stored {written:?} of {total} bytes")));
|
||||
}
|
||||
for (buffer, _) in buffers {
|
||||
buffer.release();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
type SegmentFuture = BoxFuture<'static, io::Result<()>>;
|
||||
type ReserveFuture = BoxFuture<'static, io::Result<Box<dyn NixlRecvBuffer>>>;
|
||||
|
||||
struct WriterState {
|
||||
pool: Arc<dyn NixlRecvPool>,
|
||||
base: WriteStreamRequest,
|
||||
timeout: Duration,
|
||||
current: Option<(LentBuffer, usize)>,
|
||||
filled: Vec<(LentBuffer, usize)>,
|
||||
reserving: Option<ReserveFuture>,
|
||||
sending: Option<SegmentFuture>,
|
||||
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<io::Result<()>> {
|
||||
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<io::Result<usize>> {
|
||||
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));
|
||||
}
|
||||
if self.current.is_none() {
|
||||
let pool = Arc::clone(&self.pool);
|
||||
let reserving = self.reserving.get_or_insert_with(|| pool.reserve());
|
||||
let buffer = futures::ready!(reserving.as_mut().poll(cx));
|
||||
self.reserving = None;
|
||||
self.current = Some((LentBuffer { buffer: Some(buffer?) }, 0));
|
||||
}
|
||||
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<io::Result<()>> {
|
||||
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<WriterState>,
|
||||
}
|
||||
|
||||
impl NixlFileWriter {
|
||||
fn new(pool: Arc<dyn NixlRecvPool>, 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<io::Result<usize>> {
|
||||
self.get_mut().state_mut().poll_write(cx, data)
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
// 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<io::Result<()>> {
|
||||
self.get_mut().state_mut().poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct CountingBuffer {
|
||||
released: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
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<Self>, len: usize) -> io::Result<Bytes> {
|
||||
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<u8>);
|
||||
|
||||
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<Self>, len: usize) -> io::Result<Bytes> {
|
||||
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<dyn NixlRecvBuffer>>> {
|
||||
Box::pin(async { Ok(Box::new(VecBuffer(vec![0; 8])) as Box<dyn NixlRecvBuffer>) })
|
||||
}
|
||||
}
|
||||
|
||||
#[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<u8> = (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<u8> = 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));
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
[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
|
||||
|
||||
[dependencies]
|
||||
base64-simd = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
memmap2 = { workspace = true }
|
||||
nixl-sys = { git = "https://github.com/ai-dynamo/nixl", tag = "v1.5.2" }
|
||||
parking_lot = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "sync", "time"] }
|
||||
tracing = { workspace = true }
|
||||
@@ -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/<dev>/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<String>,
|
||||
pub excluded: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct PortState {
|
||||
active: bool,
|
||||
link_up: bool,
|
||||
rate_gbps: u64,
|
||||
link_layer: String,
|
||||
link_downed: Option<u64>,
|
||||
}
|
||||
|
||||
fn read_trimmed(path: &Path) -> Option<String> {
|
||||
std::fs::read_to_string(path).ok().map(|value| value.trim().to_owned())
|
||||
}
|
||||
|
||||
fn read_port(root: &Path, device: &str) -> Option<PortState> {
|
||||
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::<f64>().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<String> {
|
||||
let mut devices: Vec<String> = 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<String, u64> = 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<String, u64> = 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<String> = ["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<String> = ["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);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,109 @@
|
||||
//! 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.
|
||||
|
||||
#![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<Self, NixlError> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -692,6 +692,33 @@ fn should_disable_proxy_for_url(url: &str, tuning: InternodeHttpClientTuning) ->
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<Duration>,
|
||||
) -> 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<Client> {
|
||||
let tuning = internode_http_client_tuning();
|
||||
// Reuse HTTP connection pools while honoring the configured internode proxy
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -56,6 +56,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)
|
||||
|
||||
|
||||
@@ -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:<gpu>:<addr>:<len>` 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.
|
||||
@@ -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: <addr>:<size>:<rkey>:<lid>:<dctn>:<gidpresent>:<gid>`.
|
||||
|
||||
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=<roce ip>` 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-<cuda>.pc` on `PKG_CONFIG_PATH`, then run with
|
||||
`PYTHONPATH=<prefix>/lib/python3/dist-packages` and
|
||||
`NIXL_PLUGIN_DIR=<prefix>/lib/<triplet>/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.
|
||||
@@ -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-<first local endpoint host>` | 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://<host>/rustfs/admin/v3/bucket-etag/<bucket>" -d '{"algorithm":"xxh3"}' # md5 | xxh3
|
||||
|
||||
# Read it back ("algorithm": null means no setting: MD5 ETags)
|
||||
curl "http://<host>/rustfs/admin/v3/bucket-etag/<bucket>"
|
||||
|
||||
# Clear it (MD5 ETags again)
|
||||
curl -X DELETE "http://<host>/rustfs/admin/v3/bucket-etag/<bucket>"
|
||||
```
|
||||
|
||||
- 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` | `<dram|vram>:<device>:<address>:<length>`: 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/<dev>/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.
|
||||
@@ -75,6 +75,10 @@ connect-e2e-short-credentials = []
|
||||
# Builds the dedicated rustfs-cli-e2e target with a build-time public enrollment root.
|
||||
offline-enrollment-e2e-root = []
|
||||
rio-v2 = ["rustfs-ecstore/rio-v2"]
|
||||
# Linux-only cuObject S3-over-RDMA GET into client (GPU) memory; needs libcuobjserver.
|
||||
cuobject = ["dep:rustfs-cuobject"]
|
||||
# NIXL/UCX transport for S3-over-RDMA; replaces cuobject when both are enabled.
|
||||
nixl = ["dep:rustfs-nixl"]
|
||||
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"]
|
||||
@@ -243,6 +247,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 }
|
||||
|
||||
@@ -1313,6 +1313,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<i64> = None;
|
||||
let size = resolve_upload_part_size(content_length, body.as_ref())?;
|
||||
if let Some(size) = size {
|
||||
reject_oversize_single_upload(size)?;
|
||||
@@ -1589,7 +1603,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,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+115
-28
@@ -247,7 +247,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";
|
||||
|
||||
@@ -3022,7 +3022,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();
|
||||
@@ -4083,31 +4089,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<std::convert::Infallible> = 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::<super::cuobject::RdmaSinkSlot>()
|
||||
.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(s3s::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);
|
||||
@@ -4137,7 +4206,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(),
|
||||
@@ -4175,7 +4244,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
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4519,6 +4592,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();
|
||||
|
||||
|
||||
@@ -216,6 +216,8 @@ fn remove_source_replication_bookkeeping(user_defined: &mut HashMap<String, Stri
|
||||
#[cfg(test)]
|
||||
mod conditional_read_bench;
|
||||
mod copy;
|
||||
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
|
||||
pub(crate) mod cuobject;
|
||||
mod delete;
|
||||
mod extract;
|
||||
mod get;
|
||||
|
||||
@@ -1288,6 +1288,24 @@ impl DefaultObjectUsecase {
|
||||
)?;
|
||||
rustfs_io_metrics::record_put_object_stage_duration_from("app_request_shape", request_shape_stage_start);
|
||||
|
||||
// cuObject S3-over-RDMA PUT: an empty HTTP body plus `x-amz-rdma-token`
|
||||
// means the bytes are read from the client's registered buffer; the
|
||||
// token's buffer length is the object length.
|
||||
#[cfg(all(any(feature = "cuobject", feature = "nixl"), target_os = "linux"))]
|
||||
let (body, content_length, rdma_put) = match super::cuobject::rdma_token_for_request(&req.headers) {
|
||||
Some(token) if content_length.unwrap_or(0) == 0 => {
|
||||
// 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<i64> = None;
|
||||
let Some(body) = body else { return Err(s3_error!(IncompleteBody)) };
|
||||
|
||||
let body = match max_content_length {
|
||||
@@ -1355,7 +1373,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 };
|
||||
|
||||
@@ -1747,6 +1747,14 @@ 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).
|
||||
#[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 {
|
||||
@@ -1778,6 +1786,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 multipart_usecase {
|
||||
|
||||
@@ -78,6 +78,18 @@ pub(crate) struct StartupHttpServers {
|
||||
pub(crate) console_shutdown_tx: Option<ShutdownHandle>,
|
||||
}
|
||||
|
||||
/// 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<InstanceContext>,
|
||||
@@ -279,6 +291,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),
|
||||
|
||||
@@ -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(feature = "nixl")]
|
||||
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<uuid::Uuid> = LazyLock::new(uuid::Uuid::new_v4);
|
||||
static PUT_FILE_CAPABILITY_SERVER_EPOCH: LazyLock<uuid::Uuid> = LazyLock::new(uuid::Uuid::new_v4);
|
||||
static PUT_FILE_AUTH_STRICT: LazyLock<bool> = LazyLock::new(|| {
|
||||
pub(super) static PUT_FILE_CAPABILITY_SERVER_EPOCH: LazyLock<uuid::Uuid> = LazyLock::new(uuid::Uuid::new_v4);
|
||||
pub(super) static PUT_FILE_AUTH_STRICT: LazyLock<bool> = LazyLock::new(|| {
|
||||
rustfs_utils::get_env_bool(
|
||||
rustfs_config::ENV_INTERNODE_RPC_BODY_DIGEST_STRICT,
|
||||
rustfs_config::DEFAULT_INTERNODE_RPC_BODY_DIGEST_STRICT,
|
||||
@@ -412,15 +414,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<String>,
|
||||
put_file_nonce: Option<uuid::Uuid>,
|
||||
put_file_server_epoch: Option<uuid::Uuid>,
|
||||
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<String>,
|
||||
pub(super) put_file_nonce: Option<uuid::Uuid>,
|
||||
pub(super) put_file_server_epoch: Option<uuid::Uuid>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, serde::Deserialize)]
|
||||
@@ -453,7 +455,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;
|
||||
}
|
||||
@@ -524,6 +526,10 @@ async fn handle_internode_rpc(req: Request<Incoming>) -> Response<Body> {
|
||||
let path = req.uri().path();
|
||||
let response = match (method, path) {
|
||||
(Method::GET, READ_FILE_STREAM_PATH) | (Method::HEAD, READ_FILE_STREAM_PATH) => handle_read_file(req).await,
|
||||
#[cfg(feature = "nixl")]
|
||||
(Method::GET, READ_FILE_NIXL_PATH) => super::nixl_read::handle_read_file_nixl(req).await,
|
||||
#[cfg(feature = "nixl")]
|
||||
(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::<NsScannerCapabilityQuery>(&req) {
|
||||
Ok(query) if query.ns_scanner_protocol == Some(NS_SCANNER_PROTOCOL_VERSION) => match query.ns_scanner_challenge {
|
||||
@@ -592,6 +598,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(feature = "nixl")]
|
||||
READ_FILE_NIXL_PATH => Some(INTERNODE_OPERATION_READ_FILE_STREAM),
|
||||
#[cfg(feature = "nixl")]
|
||||
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),
|
||||
@@ -1029,7 +1039,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,
|
||||
@@ -1555,7 +1565,7 @@ async fn remove_put_file_staging(disk: &DiskStore, volume: &str, path: &str) ->
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
async fn write_authenticated_put_file<S, E>(
|
||||
pub(super) async fn write_authenticated_put_file<S, E>(
|
||||
disk: &DiskStore,
|
||||
body: S,
|
||||
query: &PutFileQuery,
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
// limitations under the License.
|
||||
|
||||
pub mod http_service;
|
||||
#[cfg(feature = "nixl")]
|
||||
pub mod nixl_read;
|
||||
pub mod node_service;
|
||||
|
||||
pub use http_service::InternodeRpcService;
|
||||
@@ -29,6 +31,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(feature = "nixl")]
|
||||
pub(crate) fn open_shard_contained(path: &std::path::Path, key: &str) -> std::io::Result<std::fs::File> {
|
||||
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<T: Serialize>(value: &T) -> Result<Vec<u8>, rmp_serde::encode::Error> {
|
||||
let mut buf = Vec::new();
|
||||
value.serialize(&mut Serializer::new(&mut buf).with_struct_map())?;
|
||||
@@ -37,6 +66,23 @@ pub(crate) fn encode_msgpack_map<T: Serialize>(value: &T) -> Result<Vec<u8>, 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};
|
||||
|
||||
@@ -0,0 +1,343 @@
|
||||
// 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::app::object::cuobject::nixl_server;
|
||||
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 s3s::Body;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncWrite, AsyncWriteExt};
|
||||
use tracing::warn;
|
||||
|
||||
/// 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<W: AsyncWrite + Unpin>(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<String>) -> Response<Body> {
|
||||
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<Body> {
|
||||
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<Incoming>) -> Response<Body> {
|
||||
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<rustfs_nixl::StagingChunk> {
|
||||
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<Incoming>) -> Response<Body> {
|
||||
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<u8>,
|
||||
staged: Vec<u8>,
|
||||
}
|
||||
|
||||
impl AsyncWrite for TailOnShutdown {
|
||||
fn poll_write(mut self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
|
||||
self.staged.extend_from_slice(buf);
|
||||
let whole = self.staged.len() / 4096 * 4096;
|
||||
let block: Vec<u8> = 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<std::io::Result<()>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
|
||||
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<u8> = (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");
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -295,6 +301,18 @@ pub(crate) mod rpc_consumer {
|
||||
};
|
||||
}
|
||||
|
||||
/// Server side of internode NIXL chunk reads (`nixl` feature).
|
||||
#[cfg(feature = "nixl")]
|
||||
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::{
|
||||
@@ -648,6 +666,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"))]
|
||||
|
||||
Reference in new issue
Block a user