diff --git a/.github/scripts/build-cuobject-client.sh b/.github/scripts/build-cuobject-client.sh new file mode 100755 index 0000000..a7b1cbc --- /dev/null +++ b/.github/scripts/build-cuobject-client.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Build and link the combined client against NVIDIA's x86_64 SDK without a GPU. +set -euo pipefail +: "${NIXL_PREFIX:?NIXL SDK prefix is required}" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +packages="${RUNNER_TEMP:-$work}/cuobject-packages" +mkdir -p "$packages" +repo=https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64 +while read -r digest package; do + archive="$packages/$package" + if ! echo "$digest $archive" | sha256sum --check --status 2>/dev/null; then + curl --fail --silent --show-error --location --retry 3 --retry-all-errors \ + --connect-timeout 20 --max-time 300 "$repo/$package" -o "$archive" + echo "$digest $archive" | sha256sum --check + fi + dpkg-deb -x "$archive" "$work/sdk" +done <<'PACKAGES' +e06a0f89898ec9a7df3124e4d6ad3a1ebf92a0b3ea42c3f81c6fff5ef92a5126 libcuobjclient-13-5_1.4.0.107-1_amd64.deb +ce6188558d94a15593c4ae82cb578828ce7686ea09e2658a201962f56e66fe7c libcuobjclient-dev-13-5_1.4.0.107-1_amd64.deb +d02925a4ab1706b6ba578ff6d7db953c5bcae3291d3abdbd7e4311de8d3d4c11 libcufile-13-5_1.20.0.107-1_amd64.deb +b8e2c20dc796ca09b3ec55ce5fd72f2bdc4c6efea857b907a9cec5b356256072 libcufile-dev-13-5_1.20.0.107-1_amd64.deb +e079c64a1ab86d69a43a7dd8029ddcacb7de8c1953a4c095e485429bd90e8636 cuda-cudart-dev-13-5_13.5.37-1_amd64.deb +PACKAGES +export CUDA_HOME="$work/sdk/usr/local/cuda-13.5" +export CUOBJCLIENT_ROOT="$CUDA_HOME/targets/x86_64-linux" +export LD_LIBRARY_PATH="$CUOBJCLIENT_ROOT/lib:$NIXL_PREFIX/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +export LIBRARY_PATH="$CUOBJCLIENT_ROOT/lib${LIBRARY_PATH:+:$LIBRARY_PATH}" +export NIXL_PLUGIN_DIR="$NIXL_PREFIX/lib/plugins" +./scripts/build-rdma.sh --features cuobject +cargo test --locked --manifest-path nixl/Cargo.toml --features cuobject diff --git a/.github/workflows/nixl.yml b/.github/workflows/nixl.yml index 0ab3fcf..d4f7440 100644 --- a/.github/workflows/nixl.yml +++ b/.github/workflows/nixl.yml @@ -10,6 +10,7 @@ on: - 'Cargo.lock' - 'scripts/build-rdma.sh' - '.github/scripts/build-nixl-runtime.sh' + - '.github/scripts/build-cuobject-client.sh' - '.github/workflows/nixl.yml' permissions: @@ -31,11 +32,13 @@ jobs: - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 with: workspaces: nixl + - name: Check the cuObject crates without the NVIDIA SDK + run: cargo check --locked --manifest-path nixl/Cargo.toml -p rustfs-cuobject-client -p rustfs-cuobject-client-sys - name: Install native build tools run: | echo "NIXL_PREFIX=$RUNNER_TEMP/nixl" >> "$GITHUB_ENV" sudo apt-get update - sudo apt-get install -y --no-install-recommends libclang-dev ninja-build python3-dev python3-venv + sudo apt-get install -y --no-install-recommends libibverbs-dev librdmacm1t64 libclang-dev ninja-build python3-dev python3-venv python3 -m venv "$RUNNER_TEMP/native-tools" "$RUNNER_TEMP/native-tools/bin/pip" install meson==1.12.1 pybind11==3.1.0 echo "$RUNNER_TEMP/native-tools/bin" >> "$GITHUB_PATH" @@ -54,3 +57,5 @@ jobs: export NIXL_PLUGIN_DIR="$NIXL_PREFIX/lib/plugins" ./scripts/build-rdma.sh cargo test --locked --manifest-path nixl/Cargo.toml + - name: Build and test the NVIDIA cuObject client with the real SDK + run: .github/scripts/build-cuobject-client.sh diff --git a/AGENTS.md b/AGENTS.md index ebb78d7..fdb9927 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,9 +103,10 @@ Modifying protected files requires: - Must use `?` or `expect("reason")` - Violation: may cause panic -3. **Using `unsafe` code** - - No exceptions - - Violation: security risk +3. **Using `unsafe` outside the private NVIDIA SDK bridge** + - Only the private bridge in `nixl/cuobject-client-sys/src/sdk.rs`, enabled by the native executable’s `cuobject` feature, may declare the C++ interface and the thread ownership of its opaque window. Keep handwritten Rust operations outside this exception. + - Native host slices require an exclusive window. Once a token is exposed, retain it with its registration until confirmed completion or proof that DMA never started. Quarantine an uncertain exchange or failed token release for the life of the process. + - Keep the lint exception on the bridge. The native executable and the `rustfs-cuobject-client` library must retain `forbid(unsafe_code)`. 4. **Printing credentials in logs/errors** - Includes: access_key, secret_key, Authorization headers diff --git a/crates/cli/src/commands/mod.rs b/crates/cli/src/commands/mod.rs index 982142c..57ca03f 100644 --- a/crates/cli/src/commands/mod.rs +++ b/crates/cli/src/commands/mod.rs @@ -9,8 +9,8 @@ use std::io::{IsTerminal, stderr, stdout}; use clap::{Parser, Subcommand, ValueEnum}; use rc_core::config::Defaults; use rc_core::{ - ConfigManager, DataTransportMode, RequestHeader, set_global_data_transport_mode, - set_global_request_headers, + ConfigManager, DataTransportMode, RdmaBackend, RequestHeader, set_global_data_transport_mode, + set_global_rdma_backend, set_global_request_headers, }; use crate::exit_code::ExitCode; @@ -98,6 +98,10 @@ pub struct Cli { #[arg(long, global = true, env = "RC_DATA_TRANSPORT", default_value = "http")] pub data_transport: DataTransportMode, + /// RDMA backend for auto or rdma mode: nixl or cuobject + #[arg(long, global = true, env = "RC_RDMA_BACKEND", default_value = "nixl")] + pub rdma_backend: RdmaBackend, + /// Maximum multipart parts per object for the destination backend #[arg(long, global = true, env = "RC_MAX_PARTS", default_value_t = 10_000, value_parser = clap::value_parser!(u32).range(1..=10_000))] @@ -371,6 +375,7 @@ pub enum Commands { /// Execute the CLI command and return an exit code pub async fn execute(cli: Cli) -> ExitCode { set_global_data_transport_mode(cli.data_transport); + set_global_rdma_backend(cli.rdma_backend); set_global_request_headers(cli.request_headers.clone()); let cli_output_options = GlobalOutputOptions::from_cli(&cli); if let Err(error) = rc_core::set_global_multipart_max_parts(cli.max_parts as usize) { @@ -592,6 +597,57 @@ mod tests { assert_eq!(cli.data_transport, DataTransportMode::Rdma); assert!(Cli::try_parse_from(["rc", "--data-transport", "udp", "alias", "list"]).is_err()); } + #[test] + fn external_transport_headers_cannot_be_supplied_by_the_caller() { + for name in [ + "X-AmZ-RdMa-ToKeN", + "x-amz-rdma-reply", + "x-amz-rdma-bytes-transferred", + "x-rustfs-nixl-agent", + "x-rustfs-nixl-metadata", + "x-rustfs-nixl-buffer", + ] { + for mode in ["http", "auto", "rdma"] { + assert!( + Cli::try_parse_from([ + "rc", + "--data-transport", + mode, + "-H", + &format!("{name}:opaque"), + "alias", + "list" + ]) + .is_err(), + "{name} in {mode}" + ); + } + } + assert!( + Cli::try_parse_from(["rc", "-H", "x-amz-meta-format:onnx", "alias", "list"]).is_ok() + ); + } + + #[test] + fn rdma_backend_is_independent_of_fallback_policy() { + for policy in ["rdma", "auto"] { + let args = [ + "rc", + "--data-transport", + policy, + "--rdma-backend", + "cuobject", + "alias", + "list", + ]; + let cli = Cli::try_parse_from(args).expect("select NVIDIA cuObject"); + assert_eq!(cli.rdma_backend, RdmaBackend::CuObject); + assert_eq!(cli.data_transport, policy.parse().unwrap()); + } + let default = Cli::try_parse_from(["rc", "alias", "list"]).unwrap(); + assert_eq!(default.rdma_backend, RdmaBackend::Nixl); + assert!(Cli::try_parse_from(["rc", "--rdma-backend", "unknown", "alias", "list"]).is_err()); + } use clap::Parser; #[test] diff --git a/crates/core/src/alias.rs b/crates/core/src/alias.rs index e254a8f..beb80f2 100644 --- a/crates/core/src/alias.rs +++ b/crates/core/src/alias.rs @@ -60,10 +60,23 @@ impl RequestHeader { return Err(Error::Config(format!("Invalid value for header '{name}'"))); } - Ok(Self { + let header = Self { name, value: header_value, - }) + }; + header.validate_transport_name()?; + Ok(header) + } + + /// Transport control headers must come from the owner of the registered memory. + pub fn validate_transport_name(&self) -> Result<()> { + let name = self.name.to_ascii_lowercase(); + if name.starts_with("x-amz-rdma-") || name.starts_with("x-rustfs-nixl-") { + return Err(Error::Config( + "RDMA headers are reserved for the selected transport".into(), + )); + } + Ok(()) } } diff --git a/crates/core/src/data_transport.rs b/crates/core/src/data_transport.rs index 5c6b2b2..2a61da4 100644 --- a/crates/core/src/data_transport.rs +++ b/crates/core/src/data_transport.rs @@ -29,6 +29,40 @@ impl FromStr for DataTransportMode { } } +/// The wire protocol for external object transfers, independent of HTTP fallback. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[repr(u8)] +pub enum RdmaBackend { + #[default] + Nixl, + CuObject, +} + +impl FromStr for RdmaBackend { + type Err = String; + + fn from_str(value: &str) -> Result { + match value { + "nixl" => Ok(Self::Nixl), + "cuobject" => Ok(Self::CuObject), + _ => Err("RDMA backend must be nixl or cuobject".into()), + } + } +} + +static GLOBAL_BACKEND: AtomicU8 = AtomicU8::new(RdmaBackend::Nixl as u8); + +pub fn set_global_rdma_backend(backend: RdmaBackend) { + GLOBAL_BACKEND.store(backend as u8, Ordering::Relaxed); +} + +pub fn global_rdma_backend() -> RdmaBackend { + match GLOBAL_BACKEND.load(Ordering::Relaxed) { + i if i == RdmaBackend::CuObject as u8 => RdmaBackend::CuObject, + _ => RdmaBackend::Nixl, + } +} + /// Business outcome classification. Transport timeouts never imply rejection. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DataTransferState { diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 0ad149b..6a61ad5 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -39,8 +39,8 @@ pub use alias::{ pub use config::{Config, ConfigManager}; pub use cors::{CorsConfiguration, CorsRule}; pub use data_transport::{ - DataTransferState, DataTransportMode, global_data_transport_mode, - set_global_data_transport_mode, + DataTransferState, DataTransportMode, RdmaBackend, global_data_transport_mode, + global_rdma_backend, set_global_data_transport_mode, set_global_rdma_backend, }; pub use encryption::{BucketEncryption, ObjectEncryptionRequest}; pub use error::{Error, MultipartAbortStatus, Result}; diff --git a/crates/s3/src/client.rs b/crates/s3/src/client.rs index 61d6264..ceaa508 100644 --- a/crates/s3/src/client.rs +++ b/crates/s3/src/client.rs @@ -1806,6 +1806,10 @@ impl Intercept for CustomHeaderInterceptor { impl S3Client { /// Create a new S3 client from an alias configuration pub async fn new(alias: Alias) -> Result { + let request_headers = global_request_headers(); + for header in &request_headers { + header.validate_transport_name()?; + } let endpoint = alias.endpoint.clone(); let region = alias.region.clone(); let access_key = alias.access_key.clone(); @@ -1865,7 +1869,6 @@ impl S3Client { let config = config_loader.load().await; // Build S3 client with path-style addressing for compatibility - let request_headers = global_request_headers(); let mut s3_config_builder = aws_sdk_s3::config::Builder::from(&config) .force_path_style(force_path_style_for_alias(&alias)) // Improve compatibility with S3-compatible backends by only sending request @@ -1926,7 +1929,8 @@ impl S3Client { (_, Some(transport)) => Ok(Some(transport)), (DataTransportMode::Rdma, None) => Err(Error::DataTransfer { state: rc_core::DataTransferState::NotAccepted, - message: "This executable has no external object data provider".to_string(), + message: "This executable has no provider for the selected RDMA backend" + .to_string(), source: None, }), } @@ -7697,10 +7701,8 @@ impl ObjectStore for S3Client { } } -/// External control exchanges retain the host client's TLS and signing policy. -#[async_trait] -impl ControlExecutor for S3Client { - async fn execute_headers(&self, request: ControlRequest) -> Result { +impl S3Client { + async fn send_external_control(&self, request: ControlRequest) -> Result { if self.alias.anonymous { return Err(Error::RequestRejected( "External object control requires an authenticated S3 principal".to_string(), @@ -7762,8 +7764,7 @@ impl ControlExecutor for S3Client { // Only response headers travel over HTTPS. Bound the complete wait, // including connection setup, using the same alias policy as S3. let timeout = self.alias.timeout_config(); - let mut response = self - .xml_http_client + self.xml_http_client .request(request.method, url) .headers(signed) .timeout(Duration::from_millis( @@ -7778,7 +7779,42 @@ impl ControlExecutor for S3Client { "External control exchange failed" }; Error::Network(message.to_owned()) - })?; + }) + } +} + +/// External control exchanges retain the host client's TLS and signing policy. +#[async_trait] +impl ControlExecutor for S3Client { + fn endpoint(&self) -> Option<&str> { + Some(&self.alias.endpoint) + } + + async fn execute_registered( + &self, + request: ControlRequest, + ) -> Result { + let method = request.method.clone(); + let conditional = request.headers.contains_key("if-match"); + let mut response = self.send_external_control(request).await?; + let status = response.status(); + let headers = std::mem::take(response.headers_mut()); + if object_error::dma_precondition_response(&method, conditional, status, &headers) + && object_error::has_precondition_error_body(response).await + { + return Ok( + data_transport::RegisteredControlResponse::RejectedBeforeDma(Error::Conflict( + "The S3 endpoint rejected the conditional GET before transferring data".into(), + )), + ); + } + Ok(data_transport::RegisteredControlResponse::Response( + ControlResponse { status, headers }, + )) + } + + async fn execute_headers(&self, request: ControlRequest) -> Result { + let mut response = self.send_external_control(request).await?; Ok(ControlResponse { status: response.status(), headers: std::mem::take(response.headers_mut()), diff --git a/crates/s3/src/client/object_error.rs b/crates/s3/src/client/object_error.rs index c17cd1f..9b2a3a9 100644 --- a/crates/s3/src/client/object_error.rs +++ b/crates/s3/src/client/object_error.rs @@ -137,3 +137,113 @@ impl S3Client { Error::Network(formatted) } } + +/// Only a conditional GET can establish that this particular precondition +/// stopped the read before the server wrote to the advertised memory. +pub(super) fn dma_precondition_response( + method: &http::Method, + conditional: bool, + status: http::StatusCode, + headers: &http::HeaderMap, +) -> bool { + let mut codes = headers.get_all("x-amz-error-code").iter(); + method == http::Method::GET + && conditional + && status == http::StatusCode::PRECONDITION_FAILED + && !headers.keys().any(|name| { + name.as_str().starts_with("x-amz-rdma-") || name.as_str().starts_with("x-rustfs-nixl-") + }) + && codes + .next() + .is_none_or(|value| value == "PreconditionFailed") + && codes.next().is_none() +} + +fn is_s3_precondition_error(body: &[u8]) -> bool { + #[derive(serde::Deserialize)] + enum Document { + Error { + #[serde(rename = "Code")] + code: String, + }, + } + let mut xml = quick_xml::de::Deserializer::from_reader(body.trim_ascii_end()); + matches!(serde::Deserialize::deserialize(&mut xml), Ok(Document::Error {code}) if code == "PreconditionFailed") + && xml.is_empty() +} + +pub(super) async fn has_precondition_error_body(mut response: reqwest::Response) -> bool { + const LIMIT: usize = 16 * 1024; + let mut body = Vec::new(); + loop { + match response.chunk().await { + Ok(Some(chunk)) if chunk.len() <= LIMIT - body.len() => body.extend_from_slice(&chunk), + Ok(None) => return is_s3_precondition_error(&body), + _ => return false, + } + } +} + +#[cfg(test)] +mod dma_tests { + use super::*; + use http::{HeaderMap, Method, StatusCode}; + #[test] + fn requires_a_conditional_get_and_unambiguous_s3_rejection() { + let status = StatusCode::PRECONDITION_FAILED; + let headers = HeaderMap::new(); + let s3 = b"PreconditionFailedetag"; + assert!(dma_precondition_response( + &Method::GET, + true, + status, + &headers + )); + assert!(!dma_precondition_response( + &Method::PUT, + true, + status, + &headers + )); + assert!(!dma_precondition_response( + &Method::GET, + false, + status, + &headers + )); + assert!(!dma_precondition_response( + &Method::GET, + true, + StatusCode::BAD_GATEWAY, + &headers + )); + for name in [ + "x-amz-rdma-reply", + "x-amz-rdma-bytes-transferred", + "x-amz-rdma-extra", + ] { + let mut headers = HeaderMap::new(); + headers.insert(name, "0".parse().unwrap()); + assert!(!dma_precondition_response( + &Method::GET, + true, + status, + &headers + )); + } + assert!(is_s3_precondition_error(s3)); + assert!(is_s3_precondition_error( + b"\nPreconditionFailed\n" + )); + for body in [ + &b""[..], + b"PreconditionFailed", + b"PreconditionFailed", + b"PreconditionFailed", + b"Other", + b"PreconditionFailedOther", + ] { + assert!(!is_s3_precondition_error(body)); + } + } +} diff --git a/crates/s3/src/data_transport.rs b/crates/s3/src/data_transport.rs index 2dd3ff5..3bf39b4 100644 --- a/crates/s3/src/data_transport.rs +++ b/crates/s3/src/data_transport.rs @@ -33,12 +33,34 @@ pub struct ControlResponse { pub headers: HeaderMap, } +/// Outcome of an exchange that advertised client memory. +pub enum RegisteredControlResponse { + Response(ControlResponse), + /// The authenticated peer rejected the request before starting any data transfer. + RejectedBeforeDma(Error), +} + /// Host-owned HTTPS, credentials, signing, custom headers, and TLS configuration. #[async_trait] pub trait ControlExecutor: Send + Sync { + /// Stable endpoint for sharing provider capability discovery across clients. + fn endpoint(&self) -> Option<&str> { + None + } + /// Read only the status and headers. A declined external GET can return an /// ordinary S3 payload of arbitrary size. async fn execute_headers(&self, request: ControlRequest) -> Result; + + /// Executors that cannot establish a pre-transfer rejection return ordinary responses. + async fn execute_registered( + &self, + request: ControlRequest, + ) -> Result { + self.execute_headers(request) + .await + .map(RegisteredControlResponse::Response) + } } /// External transport construction is separate from process-wide policy. @@ -46,19 +68,38 @@ pub trait ObjectDataTransportFactory: Send + Sync { fn create(&self, control: Arc) -> Result>; } -static FACTORY: OnceLock> = OnceLock::new(); +static NIXL_FACTORY: OnceLock> = OnceLock::new(); -/// Install a provider before running the CLI. Replacing a provider is rejected. +static CUOBJECT_FACTORY: OnceLock> = OnceLock::new(); + +fn factory_slot( + backend: rc_core::RdmaBackend, +) -> &'static OnceLock> { + match backend { + rc_core::RdmaBackend::Nixl => &NIXL_FACTORY, + rc_core::RdmaBackend::CuObject => &CUOBJECT_FACTORY, + } +} + +/// Install the default NIXL provider before running the CLI. Replacing a provider is rejected. pub fn install_object_data_transport_factory( factory: Arc, ) -> Result<()> { - FACTORY.set(factory).map_err(|_| { + install_rdma_backend(rc_core::RdmaBackend::Nixl, factory) +} + +/// Register one backend without replacing another provider. +pub fn install_rdma_backend( + backend: rc_core::RdmaBackend, + factory: Arc, +) -> Result<()> { + factory_slot(backend).set(factory).map_err(|_| { Error::Config("An object data transport factory is already installed".to_string()) }) } pub(crate) fn installed_factory() -> Option> { - FACTORY.get().cloned() + factory_slot(rc_core::global_rdma_backend()).get().cloned() } /// A GET's S3 selection and an independent finite receive bound. diff --git a/docs/ADR/0001-object-data-transport.md b/docs/ADR/0001-object-data-transport.md index 6f9955a..8f8480b 100644 --- a/docs/ADR/0001-object-data-transport.md +++ b/docs/ADR/0001-object-data-transport.md @@ -8,13 +8,18 @@ completion, and abort continue to use the established S3 implementation. `rc-core` owns transport selection and business outcome classification. `rc-s3::data_transport` owns the optional provider ports, expressed with existing S3 read/write options, registered file transfers, and borrowed asynchronous IO. -The Linux NIXL executable installs an `ObjectDataTransportFactory` before -calling `rustfs_cli::run()`. +The Linux native executable registers an `ObjectDataTransportFactory` for +each compiled RDMA backend before calling `rustfs_cli::run()`. Backend +selection (`--rdma-backend nixl|cuobject`) and fallback policy are independent. +Both backends use the same multipart publication, version selection, file IO, +checksum verification and receipt handling. The common launcher preserves command dispatch, output, exit codes, and the existing worker-thread configuration. -The provider supplies NIXL agent metadata and a registered buffer description -to a host-owned `ControlExecutor`. The S3 client signs and sends a bodyless +The NIXL backend supplies agent metadata and a registered buffer description. +The NVIDIA backend uses `rustfs-cuobject-client` for registered windows and transfer tokens. Its dependency `rustfs-cuobject-client-sys` builds the C++ bridge and links the NVIDIA client SDK. The window can be reused after +a verified receipt or proof that DMA never started. An uncertain transfer retains both resources +within the process registration budget. Both use the host-owned `ControlExecutor`. The S3 client signs and sends a bodyless HTTPS request on the shared S3 HTTP client using the alias timeout policy. It returns the status and headers directly, including duplicate headers. The provider verifies the RustFS transfer receipt and byte count. Credentials, endpoint addressing, custom headers, and TLS diff --git a/docs/rdma-build.md b/docs/rdma-build.md index c5dc187..0f161b8 100644 --- a/docs/rdma-build.md +++ b/docs/rdma-build.md @@ -1,6 +1,6 @@ # Object data over RDMA -## RustFS native NIXL/UCX +## Build the native client Build on Linux with Rust 1.99 or later, libclang, a C++ compiler and the NIXL libraries, headers and UCX plugin used by the RustFS server. Set @@ -27,18 +27,62 @@ feature and `RUSTFS_NIXL_ENABLE=true`. For a private CA, pass or `rdma` to reuse the selection across commands. The default is `http`. Signed control requests use the alias connection and read timeouts, including the wait for each transfer receipt. +### Choose the RDMA backend + +The native executable uses NIXL/UCX by default. To add NVIDIA cuObject +to the same executable, install the NVIDIA cuObject **client** SDK, +cuFile development libraries, libibverbs development headers and CUDA headers +for the target architecture. +Set `CUOBJCLIENT_ROOT` to the SDK prefix and `CUDA_HOME` to the CUDA toolkit. +The `rustfs-cuobject-client-sys` crate builds the C++17 adapter against `cuobjclient.h` and links the NVIDIA SDK. The CLI accesses registered windows and tokens through `rustfs-cuobject-client`. +The SDK's `libcuobjclient`, `libcufile` and RDMA plugin must be available +at runtime. Set `CUOBJ_ENV_PATH_JSON` to the NVIDIA client configuration +that selects the application RDMA device. + +```sh +./scripts/build-rdma.sh --release --features cuobject +rc --data-transport rdma --rdma-backend cuobject put model.bin lab/models/model.bin +rc --data-transport rdma --rdma-backend cuobject get lab/models/model.bin downloaded.bin +cmp model.bin downloaded.bin +rc --data-transport rdma --rdma-backend nixl get other/models/model.bin from-nixl.bin +``` + +Configure `lab` as a verified HTTPS alias for a RustFS server built with +`--features cuobject` and `RUSTFS_CUOBJECT_ENABLE=true`. Use an alias for a +NIXL-enabled server with the `nixl` backend. `RC_RDMA_BACKEND` sets the +backend for subsequent commands. Request headers in the `x-amz-rdma-*` and +`x-rustfs-nixl-*` namespaces are reserved for the selected provider. The `rdma` policy requires the selected +backend. The `auto` policy allows a safe S3 fallback when that backend is +unavailable. The default `http` policy transfers the payload through S3. + +### Object transfers + File uploads use positional reads directly into two reusable registered windows. Each completed part frees a window for the next part, and S3 receives -the completion list in part-number order. For transfers of up to 1 MiB, the client can register two 1 MiB -windows. Larger transfers use 64 MiB windows, which also serve subsequent -small requests on the same client. File downloads write directly into the temporary -destination file. A range GET for the next window can proceed while the -previous window is being written. All requests keep the caller's version selector. Each GET uses -`If-Match` and checks the version from HEAD before delivering that range. Downloads publish the temporary file -after verifying the transfer count and any applicable object checksum. -A window with an uncertain transfer stays registered until the process exits. +the completion list in part-number order. A new pool sizes each window to the +next power of two that fits the requested part or range, with a 1 MiB minimum +and a 64 MiB maximum. For example, a 4 MiB range registers two 4 MiB windows. +A client can reuse its existing larger pool for subsequent small requests. +For large downloads, NIXL and cuObject issue up to two adjacent range GETs +concurrently. Each request uses the caller's version selector and `If-Match`. +The CLI checks each response against the version observed by HEAD and the requested range, +consumes the results in byte order, and writes directly to the destination +stream or temporary file. File downloads publish the temporary file after +verifying the transfer count and any applicable object checksum. +A verified receipt releases the window. A local rejection before sending or +an authenticated S3 `PreconditionFailed` response to an `If-Match` GET also +releases it. For the latter, the client requires HTTP 412, a bounded S3 +error document and no RDMA response headers. An ambiguous response, a +missing receipt, cancellation or timeout retains the token and window until +the process exits. When both windows are unavailable for this reason, waiting operations use a -fresh pool within the process registration budget. +fresh pool within the process registration budget. Retiring a cuObject pool +releases its idle registrations. Each quarantined window keeps its own +registration and the pool's budget reservation. A native registration also +keeps this reservation if the SDK cannot confirm deregistration. +For the rest of the process, an ordinary HTTP response without an RDMA +receipt disables further probes for the same endpoint, backend and operation +(GET or UploadPart). Concurrent requests share the initial discovery. RustFS can interpret a declined external PUT as an ordinary empty PUT. The client uploads nonempty objects into unpublished multipart parts and @@ -53,6 +97,28 @@ size above 64 MiB use HTTP in `auto` and report an error in `rdma`. To run the real two-agent memory transfer test, use `cargo test --manifest-path nixl/Cargo.toml --locked`. For an S3 command round trip, set `RC` to the native executable and supply disposable buckets -in `NIXL_BUCKET` and `HTTP_BUCKET` on enabled and disabled endpoints. Run -`nixl/tests/interop.sh` with those variables. `UCX_TLS=tcp,self` exercises -the protocol on a machine without an RDMA network adapter. +in `RDMA_BUCKET` and `HTTP_BUCKET` on a native and an HTTP-only endpoint. +Run `RC_RDMA_BACKEND=cuobject nixl/tests/interop.sh` on an NVIDIA client +or `RC_RDMA_BACKEND=nixl nixl/tests/interop.sh` on a NIXL client. The +script accepts `NIXL_BUCKET` as an alias for `RDMA_BUCKET`. For NIXL, +`UCX_TLS=tcp,self` exercises the protocol on a machine without an RDMA adapter. + +On a cuObject client with an active RDMA device, run the buffer lifetime +test with the same SDK and device configuration used by the CLI: + +```sh +cargo test --locked --manifest-path nixl/Cargo.toml --features cuobject \ + cuobject_token_survives_cancellation_and_timeout -- --ignored +``` + +### Test failed cuObject deregistration + +On a Linux RDMA host with the client SDK installed, build the test-only SDK +override and run the registration lifetime test in its own process. + +```sh +c++ -std=c++17 -fPIC -shared -I"$CUOBJCLIENT_ROOT/include" -I"$CUDA_HOME/include" \ + nixl/cuobject-client/tests/failed_deregistration.cc -o /tmp/rc-test-failed-deregistration.so +LD_PRELOAD=/tmp/rc-test-failed-deregistration.so cargo test --manifest-path nixl/Cargo.toml \ + -p rustfs-cuobject-client --features client --test registration_budget -- --ignored +``` diff --git a/nixl/Cargo.lock b/nixl/Cargo.lock index 7e41930..c1cb7a7 100644 --- a/nixl/Cargo.lock +++ b/nixl/Cargo.lock @@ -874,6 +874,17 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -1038,6 +1049,68 @@ dependencies = [ "cmov", ] +[[package]] +name = "cxx" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8a02bfeba9074b2bbb39492c9b0908ec854f455a3cccdcde7a1de55e2315e40" +dependencies = [ + "cc", + "cxx-build", + "cxxbridge-cmd", + "cxxbridge-flags", + "cxxbridge-macro", + "foldhash", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc2ac76997619d2d888b58ad79488f1c835de41ca4dd3dd7082acf4ecb0a50f" +dependencies = [ + "cc", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "scratch", + "syn 3.0.10", +] + +[[package]] +name = "cxxbridge-cmd" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54a486ed16a3f2a053fe7f5b98db4c1a59846a23e8cb9e49f9d1bd48830d51a2" +dependencies = [ + "clap", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c72569be94e2283764d334cd285980b747dbe221e27e315484eb6bcd93fa808a" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "423e795284a7f7b3f843c956a5322c4bc497b60c2dd1a6339da10313cb18d575" +dependencies = [ + "indexmap", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "darling" version = "0.23.0" @@ -1881,6 +1954,15 @@ dependencies = [ "libc", ] +[[package]] +name = "link-cplusplus" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82" +dependencies = [ + "cc", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -2921,10 +3003,26 @@ dependencies = [ "rc-core", "rc-s3", "rustfs-cli", + "rustfs-cuobject-client", "rustfs-nixl", "tokio", ] +[[package]] +name = "rustfs-cuobject-client" +version = "0.1.0" +dependencies = [ + "rustfs-cuobject-client-sys", +] + +[[package]] +name = "rustfs-cuobject-client-sys" +version = "0.1.0" +dependencies = [ + "cxx", + "cxx-build", +] + [[package]] name = "rustfs-nixl" version = "1.0.5" @@ -3038,6 +3136,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scratch" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2" + [[package]] name = "security-framework" version = "3.7.0" @@ -3361,6 +3465,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "thiserror" version = "2.0.21" @@ -3892,6 +4005,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" diff --git a/nixl/Cargo.toml b/nixl/Cargo.toml index 15d6297..5dce38e 100644 --- a/nixl/Cargo.toml +++ b/nixl/Cargo.toml @@ -8,12 +8,18 @@ publish = false [workspace] resolver = "3" +members = ["cuobject-client", "cuobject-client-sys"] +default-members = ["."] [[bin]] name = "rc" path = "src/main.rs" +[features] +cuobject = ["dep:rustfs-cuobject-client"] + [dependencies] +rustfs-cuobject-client = { path = "cuobject-client", features = ["client"], optional = true } rustfs-cli = { path = "../crates/cli" } rc-core = { path = "../crates/core" } rc-s3 = { path = "../crates/s3" } diff --git a/nixl/cuobject-client-sys/Cargo.toml b/nixl/cuobject-client-sys/Cargo.toml new file mode 100644 index 0000000..03d5829 --- /dev/null +++ b/nixl/cuobject-client-sys/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "rustfs-cuobject-client-sys" +version = "0.1.0" +edition = "2024" +rust-version = "1.99.0" +license = "MIT OR Apache-2.0" +publish = false +description = "Native bindings to the NVIDIA cuObject client SDK" +links = "cuobjclient" + +[features] +client = ["dep:cxx", "dep:cxx-build"] + +[dependencies] +cxx = { version = "1", optional = true } + +[build-dependencies] +cxx-build = { version = "1", optional = true } diff --git a/nixl/cuobject-client-sys/build.rs b/nixl/cuobject-client-sys/build.rs new file mode 100644 index 0000000..60d2cdd --- /dev/null +++ b/nixl/cuobject-client-sys/build.rs @@ -0,0 +1,39 @@ +fn main() { + #[cfg(feature = "client")] + build_cuobject(); +} + +#[cfg(feature = "client")] +fn build_cuobject() { + use std::{env, path::PathBuf}; + + for name in ["CUOBJCLIENT_ROOT", "CUDA_HOME"] { + println!("cargo:rerun-if-env-changed={name}"); + } + for file in ["src/sdk.rs", "native/cuobject.h", "native/cuobject.cc"] { + println!("cargo:rerun-if-changed={file}"); + } + let cuda = env::var_os("CUDA_HOME") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("/usr/local/cuda")); + let sdk = env::var_os("CUOBJCLIENT_ROOT") + .map(PathBuf::from) + .unwrap_or_else(|| cuda.clone()); + cxx_build::bridge("src/sdk.rs") + .file("native/cuobject.cc") + .include(".") + .include(sdk.join("include")) + .include(cuda.join("include")) + .std("c++17") + .compile("rc_cuobject"); + for prefix in [&sdk, &cuda] { + for dir in ["lib", "lib64"] { + println!( + "cargo:rustc-link-search=native={}", + prefix.join(dir).display() + ); + } + } + println!("cargo:rustc-link-lib=cuobjclient"); + println!("cargo:rustc-link-lib=cufile"); +} diff --git a/nixl/cuobject-client-sys/native/cuobject.cc b/nixl/cuobject-client-sys/native/cuobject.cc new file mode 100644 index 0000000..b031b40 --- /dev/null +++ b/nixl/cuobject-client-sys/native/cuobject.cc @@ -0,0 +1,131 @@ +#include "rustfs-cuobject-client-sys/src/sdk.rs.h" +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace rc::cuobject { + +class Client final { +public: + // Only the descriptor API is used. The signed S3 control exchange runs in Rust. + CUObjOps_t ops{}; + cuObjClient sdk{ops, CUOBJ_PROTO_RDMA_DC_V1}; + std::mutex mutex; +}; + +std::shared_ptr make_client() { return std::make_shared(); } + +static void check(cuObjErr_t status, const char *operation) { + if (status != CU_OBJ_SUCCESS) { + throw std::runtime_error(std::string(operation) + " failed with cuObject status " + + std::to_string(static_cast(status))); + } +} + +struct NativeWindow::Registration { + rust::Box owner; + std::shared_ptr client; + std::size_t size; + std::uint8_t *data; + char *token = nullptr; + bool release_failed = false; + + Registration(std::shared_ptr sdk_client, std::size_t length, rust::Box guard) + : owner(std::move(guard)), client(std::move(sdk_client)), size(length) { + if (!client) { + throw std::invalid_argument("missing cuObject client"); + } + if (length == 0) { + throw std::invalid_argument("invalid cuObject registration length"); + } + void *mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (mapping == MAP_FAILED) { + throw std::system_error(errno, std::generic_category(), "mmap"); + } + data = static_cast(mapping); + try { + std::lock_guard lock(client->mutex); + check(client->sdk.cuMemObjGetDescriptor(data, size), "register memory"); + } catch (...) { + munmap(data, size); + throw; + } + } + + ~Registration() { munmap(data, size); } +}; + +NativeWindow::NativeWindow(std::shared_ptr client, std::size_t size, rust::Box owner) + : registration_(std::make_unique(std::move(client), size, std::move(owner))) {} + +NativeWindow::~NativeWindow() { + auto &r = *registration_; + // An active token or a failed deregistration must keep the client and mapping alive. + if (!r.token && !r.release_failed) { + try { + std::lock_guard lock(r.client->mutex); + if (r.client->sdk.cuMemObjPutDescriptor(r.data) == CU_OBJ_SUCCESS) { + return; + } + } catch (...) { + // The SDK did not confirm deregistration. + } + } + registration_.release(); +} + +std::unique_ptr register_window(std::shared_ptr client, std::size_t size, rust::Box owner) { + return std::make_unique(std::move(client), size, std::move(owner)); +} + +rust::Slice NativeWindow::writable() { + auto &r = *registration_; + if (r.token || r.release_failed) { + throw std::logic_error("cuObject window still exposed"); + } + return {r.data, r.size}; +} + +void NativeWindow::acquire(std::size_t length, bool for_get) { + auto &r = *registration_; + if (r.token || r.release_failed || length == 0 || length > r.size) { + throw std::invalid_argument("invalid cuObject token request"); + } + std::lock_guard lock(r.client->mutex); + check(r.client->sdk.cuMemObjGetRDMAToken(r.data, length, 0, for_get ? CUOBJ_GET : CUOBJ_PUT, + &r.token), "acquire token"); + if (!r.token || !*r.token) { + throw std::runtime_error("cuObject returned an empty token"); + } +} + +rust::Slice NativeWindow::active_token() const noexcept { + const char *token = registration_->token; + if (!token) { + return {}; + } + return {reinterpret_cast(token), std::strlen(token)}; +} + +void NativeWindow::release_token() { + auto &r = *registration_; + if (r.release_failed) { + throw std::runtime_error("previous cuObject token release failed"); + } + if (r.token) { + std::lock_guard lock(r.client->mutex); + // The SDK may consume the string even when it reports a failure. + r.release_failed = true; + check(r.client->sdk.cuMemObjPutRDMAToken(std::exchange(r.token, nullptr)), "release token"); + r.release_failed = false; + } +} + +} // namespace rc::cuobject diff --git a/nixl/cuobject-client-sys/native/cuobject.h b/nixl/cuobject-client-sys/native/cuobject.h new file mode 100644 index 0000000..bb047cf --- /dev/null +++ b/nixl/cuobject-client-sys/native/cuobject.h @@ -0,0 +1,30 @@ +#pragma once + +#include "rust/cxx.h" +#include +#include +#include + +namespace rc::cuobject { + +struct RegistrationOwner; +class Client; +std::shared_ptr make_client(); + +class NativeWindow final { +public: + NativeWindow(std::shared_ptr client, std::size_t size, rust::Box owner); + ~NativeWindow(); + rust::Slice writable(); + void acquire(std::size_t length, bool for_get); + rust::Slice active_token() const noexcept; + void release_token(); + +private: + struct Registration; + std::unique_ptr registration_; +}; + +std::unique_ptr register_window(std::shared_ptr client, std::size_t size, rust::Box owner); + +} // namespace rc::cuobject diff --git a/nixl/cuobject-client-sys/src/lib.rs b/nixl/cuobject-client-sys/src/lib.rs new file mode 100644 index 0000000..3ad7624 --- /dev/null +++ b/nixl/cuobject-client-sys/src/lib.rs @@ -0,0 +1,14 @@ +//! Native bindings for NVIDIA cuObject client registrations. +#![cfg(feature = "client")] +#![deny(unsafe_code)] + +#[expect( + unsafe_code, + reason = "NVIDIA SDK declarations and native window thread ownership" +)] +mod sdk; + +pub use sdk::RegistrationOwner; +pub use sdk::ffi::{make_client, register_window}; +pub type ClientHandle = cxx::SharedPtr; +pub type WindowHandle = cxx::UniquePtr; diff --git a/nixl/cuobject-client-sys/src/sdk.rs b/nixl/cuobject-client-sys/src/sdk.rs new file mode 100644 index 0000000..e82300a --- /dev/null +++ b/nixl/cuobject-client-sys/src/sdk.rs @@ -0,0 +1,41 @@ +//! Private interface to the NVIDIA client and its registered host windows. + +/// Held by the native registration alongside its mapping and SDK client. +pub struct RegistrationOwner { + _owner: std::sync::Arc, +} +impl RegistrationOwner { + pub fn new(owner: std::sync::Arc) -> Box { + Box::new(Self { _owner: owner }) + } +} + +#[cxx::bridge(namespace = "rc::cuobject")] +pub(super) mod ffi { + extern "Rust" { + type RegistrationOwner; + } + + // SAFETY: every mutable view borrows its pinned window. An outstanding + // token excludes host access until the SDK confirms its release. + unsafe extern "C++" { + include!("native/cuobject.h"); + type Client; + type NativeWindow; + + fn make_client() -> Result>; + fn register_window( + client: SharedPtr, + size: usize, + owner: Box, + ) -> Result>; + fn writable(self: Pin<&mut NativeWindow>) -> Result<&mut [u8]>; + fn acquire(self: Pin<&mut NativeWindow>, length: usize, for_get: bool) -> Result<()>; + fn active_token(self: &NativeWindow) -> &[u8]; + fn release_token(self: Pin<&mut NativeWindow>) -> Result<()>; + } +} + +// SAFETY: transferring ownership between workers neither moves the mapping nor +// exposes it twice. The native client serializes SDK calls shared by windows. +unsafe impl Send for ffi::NativeWindow {} diff --git a/nixl/cuobject-client/Cargo.toml b/nixl/cuobject-client/Cargo.toml new file mode 100644 index 0000000..8fad34f --- /dev/null +++ b/nixl/cuobject-client/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "rustfs-cuobject-client" +version = "0.1.0" +edition = "2024" +rust-version = "1.99.0" +license = "MIT OR Apache-2.0" +publish = false +description = "NVIDIA cuObject client registrations and transfer tokens" + +[features] +client = ["dep:rustfs-cuobject-client-sys"] + +[dependencies] +rustfs-cuobject-client-sys = { path = "../cuobject-client-sys", features = ["client"], optional = true } diff --git a/nixl/cuobject-client/src/lib.rs b/nixl/cuobject-client/src/lib.rs new file mode 100644 index 0000000..8da18ee --- /dev/null +++ b/nixl/cuobject-client/src/lib.rs @@ -0,0 +1,63 @@ +//! Registered host windows for NVIDIA cuObject transfers. +#![cfg(feature = "client")] +#![forbid(unsafe_code)] + +use rustfs_cuobject_client_sys as sys; +use std::io; + +/// A native client shared by the windows it registers. +pub struct Client(sys::ClientHandle); + +impl Client { + pub fn open() -> io::Result { + sys::make_client().map(Self).map_err(io::Error::other) + } + + /// Keeps the client and its accounting owner alive until the SDK confirms + /// deregistration, including when teardown cannot release the mapping. + pub fn register( + &self, + bytes: usize, + owner: std::sync::Arc, + ) -> io::Result { + sys::register_window(self.0.clone(), bytes, sys::RegistrationOwner::new(owner)) + .map(Window) + .map_err(io::Error::other) + } +} + +/// The operation for which a remote endpoint can use a token. +pub enum Operation { + Get, + Put, +} + +/// A registered host buffer. Dropping a window with an active or uncertain +/// token keeps its native mapping and registration alive. +pub struct Window(sys::WindowHandle); + +impl Window { + /// Borrows the registered bytes when the window has no active token. + pub fn writable(&mut self) -> io::Result<&mut [u8]> { + self.0.pin_mut().writable().map_err(io::Error::other) + } + + /// Exposes the first `length` bytes for one transfer and excludes host access. + pub fn acquire_token(&mut self, operation: Operation, length: usize) -> io::Result<&[u8]> { + self.0 + .pin_mut() + .acquire(length, matches!(operation, Operation::Get)) + .map_err(io::Error::other)?; + Ok(self.active_token()) + } + + pub fn active_token(&self) -> &[u8] { + self.0.active_token() + } + + /// Releases the token after confirmed completion or proof that DMA never + /// started. An uncertain exchange must keep the token and window together. + pub fn release_after_completion(&mut self) -> io::Result<()> { + self.0.pin_mut().release_token().map_err(io::Error::other) + } +} diff --git a/nixl/cuobject-client/tests/failed_deregistration.cc b/nixl/cuobject-client/tests/failed_deregistration.cc new file mode 100644 index 0000000..85b768a --- /dev/null +++ b/nixl/cuobject-client/tests/failed_deregistration.cc @@ -0,0 +1,6 @@ +// Test-only replacement for the SDK's deregistration operation. +#include + +cuObjErr_t cuObjClient::cuMemObjPutDescriptor(void *) { + return CU_OBJ_INVALID_VALUE; +} diff --git a/nixl/cuobject-client/tests/registration_budget.rs b/nixl/cuobject-client/tests/registration_budget.rs new file mode 100644 index 0000000..986ce3f --- /dev/null +++ b/nixl/cuobject-client/tests/registration_budget.rs @@ -0,0 +1,15 @@ +#![cfg(feature = "client")] + +use rustfs_cuobject_client::Client; +use std::sync::Arc; + +#[test] +#[ignore = "requires an RDMA device and the failed_deregistration.cc test library in LD_PRELOAD"] +fn failed_descriptor_release_keeps_the_accounting_owner() { + let client = Client::open().unwrap(); + let budget = Arc::new(()); + let retained = Arc::downgrade(&budget); + let window = client.register(1 << 20, budget).unwrap(); + drop(window); + assert_eq!(retained.strong_count(), 1); +} diff --git a/nixl/src/buffer.rs b/nixl/src/buffer.rs new file mode 100644 index 0000000..c7cb1fe --- /dev/null +++ b/nixl/src/buffer.rs @@ -0,0 +1,73 @@ +//! Backend registrations used by the shared object transfer pipeline. + +use base64::{Engine, engine::general_purpose::STANDARD}; +use http::HeaderValue; +use rc_core::{Error, RdmaBackend, Result}; +use rustfs_nixl::{NixlConfig, NixlServer, StagingChunk}; + +pub(super) enum Buffer { + Nixl { + chunk: StagingChunk, + agent: HeaderValue, + metadata: HeaderValue, + }, + #[cfg(feature = "cuobject")] + CuObject(crate::nvidia::HostBuffer), +} + +pub(super) fn register( + backend: RdmaBackend, + size: usize, + count: usize, + _budget: &crate::pool::Budget, +) -> Result> { + if backend == RdmaBackend::CuObject { + #[cfg(feature = "cuobject")] + return crate::nvidia::register(size, count, _budget); + #[cfg(not(feature = "cuobject"))] + return Err(Error::UnsupportedFeature( + "The cuObject backend is not installed".into(), + )); + } + let id = getrandom::u64() + .map_err(|_| Error::General("Could not generate a NIXL agent ID".into()))?; + let name = format!("rc-{}-{id:016x}", std::process::id()); + let agent = NixlServer::new(&NixlConfig { + agent_name: name.clone(), + chunk_bytes: size, + pool_bytes: count * size, + ..NixlConfig::default() + }) + .map_err(nixl_error)?; + let mut metadata = + HeaderValue::from_str(&STANDARD.encode(agent.local_metadata().map_err(nixl_error)?)) + .map_err(|_| Error::General("Invalid NIXL agent metadata".into()))?; + metadata.set_sensitive(true); + let name = HeaderValue::from_str(&name).expect("ASCII agent ID"); + (0..count) + .map(|_| { + let chunk = agent.try_reserve().ok_or_else(|| { + Error::General("NIXL registration has no available window".into()) + })?; + Ok(Buffer::Nixl { + chunk, + agent: name.clone(), + metadata: metadata.clone(), + }) + }) + .collect() +} + +fn nixl_error(error: rustfs_nixl::NixlError) -> Error { + Error::General(format!("NIXL/UCX: {error}")) +} + +impl Buffer { + pub(super) fn writable(&mut self) -> Result<&mut [u8]> { + match self { + Self::Nixl { chunk, .. } => chunk.spare_mut().map_err(nixl_error), + #[cfg(feature = "cuobject")] + Self::CuObject(buffer) => buffer.writable(), + } + } +} diff --git a/nixl/src/main.rs b/nixl/src/main.rs index 521db61..aa80de3 100644 --- a/nixl/src/main.rs +++ b/nixl/src/main.rs @@ -1,16 +1,26 @@ -//! rc with the RustFS native S3-over-NIXL/UCX transport. +//! rc with native S3-over-RDMA providers. #![forbid(unsafe_code)] +mod buffer; +#[cfg(feature = "cuobject")] +mod nvidia; mod pool; mod transport; mod wire; -fn main() { - if let Err(error) = rc_s3::data_transport::install_object_data_transport_factory( - std::sync::Arc::new(transport::Factory), - ) { +use rc_core::RdmaBackend; + +fn register(backend: RdmaBackend) { + let factory = std::sync::Arc::new(transport::Factory::new(backend)); + if let Err(error) = rc_s3::data_transport::install_rdma_backend(backend, factory) { eprintln!("{error}"); std::process::exit(error.exit_code()); } +} + +fn main() { + register(RdmaBackend::Nixl); + #[cfg(feature = "cuobject")] + register(RdmaBackend::CuObject); rustfs_cli::run(); } diff --git a/nixl/src/nvidia.rs b/nixl/src/nvidia.rs new file mode 100644 index 0000000..e1b8be3 --- /dev/null +++ b/nixl/src/nvidia.rs @@ -0,0 +1,78 @@ +//! Direct NVIDIA client registrations for the shared S3 transfer pipeline. + +use crate::buffer::Buffer; +use http::{HeaderMap, HeaderValue, Method}; +use rc_core::{Error, Result}; +use rustfs_cuobject_client::{Client, Operation, Window}; + +pub(super) const TOKEN_HEADER: &str = "x-amz-rdma-token"; + +fn sdk_error(error: std::io::Error) -> Error { + Error::General(format!("NVIDIA cuObject: {error}")) +} + +pub(super) fn register( + size: usize, + count: usize, + budget: &crate::pool::Budget, +) -> Result> { + let client = Client::open().map_err(sdk_error)?; + (0..count) + .map(|_| { + let raw = client.register(size, budget.clone()).map_err(sdk_error)?; + Ok(Buffer::CuObject(HostBuffer { + raw, + #[cfg(test)] + releases: Default::default(), + })) + }) + .collect() +} + +pub(super) struct HostBuffer { + raw: Window, + #[cfg(test)] + pub(super) releases: std::sync::Arc, +} + +impl HostBuffer { + pub(super) fn writable(&mut self) -> Result<&mut [u8]> { + self.raw.writable().map_err(sdk_error) + } + + pub(super) fn describe( + &mut self, + method: &Method, + len: usize, + headers: &mut HeaderMap, + ) -> Result<()> { + let operation = match *method { + Method::GET => Operation::Get, + Method::PUT => Operation::Put, + _ => return Err(Error::General("Unsupported cuObject operation".into())), + }; + let token = self.raw.acquire_token(operation, len).map_err(sdk_error)?; + let mut value = HeaderValue::from_bytes(token) + .map_err(|_| Error::General("Invalid NVIDIA cuObject token".into()))?; + value.set_sensitive(true); + headers.insert(TOKEN_HEADER, value); + Ok(()) + } + + pub(super) fn release_token(&mut self) -> Result<()> { + #[cfg(test)] + let active = !self.raw.active_token().is_empty(); + self.raw.release_after_completion().map_err(sdk_error)?; + #[cfg(test)] + if active { + self.releases + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + Ok(()) + } + + #[cfg(test)] + pub(super) fn holds_token(&self, advertised: &HeaderValue) -> bool { + self.raw.active_token() == advertised.as_bytes() + } +} diff --git a/nixl/src/pool.rs b/nixl/src/pool.rs index e5d0ba0..cf55852 100644 --- a/nixl/src/pool.rs +++ b/nixl/src/pool.rs @@ -1,47 +1,55 @@ -//! Registered host memory and ownership while the server can access it. +//! Bounded registration and exclusive ownership until a transfer completes. -use base64::{Engine, engine::general_purpose::STANDARD}; -use http::{HeaderMap, HeaderValue}; -use rc_core::{Error, Result}; -use rustfs_nixl::{NixlConfig, NixlServer, StagingChunk}; +use crate::buffer::{self, Buffer}; +use http::{HeaderMap, Method}; +use rc_core::{Error, RdmaBackend, Result}; use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::sync::{Mutex as AsyncMutex, Semaphore, SemaphorePermit, watch}; pub(crate) const WINDOW: usize = rc_s3::multipart::DEFAULT_PART_SIZE as usize; -pub(crate) const SMALL_WINDOW: usize = 1024 * 1024; -// Two windows allow the next network read to overlap the previous file write. -static AGENTS: Semaphore = Semaphore::const_new(8); -static QUARANTINE: Mutex> = Mutex::new(Vec::new()); +const SMALL_WINDOW: usize = 1024 * 1024; const WINDOWS_PER_POOL: usize = 2; +static AGENTS: Semaphore = Semaphore::const_new(8); +// Keep the exposed registration and its budget, so the retired pool can free its idle buffers. +pub(super) type Budget = Arc>; +static QUARANTINE: Mutex> = Mutex::new(Vec::new()); + +fn window_size(required: u64) -> usize { + let required = required.clamp(SMALL_WINDOW as u64, WINDOW as u64) as usize; + required.next_power_of_two().min(WINDOW) +} -/// One active registration per S3 client. A larger request upgrades the pool; -/// outstanding windows keep their original registration alive. #[derive(Default)] pub(crate) struct Pools { + backend: RdmaBackend, active: AsyncMutex>>, } impl Pools { + pub(crate) fn new(backend: RdmaBackend) -> Self { + Self { + backend, + active: AsyncMutex::default(), + } + } + pub(crate) async fn reserve(&self, required: u64) -> Result { - let size = if required <= SMALL_WINDOW as u64 { - SMALL_WINDOW - } else { - WINDOW - }; + let size = window_size(required); loop { let pool = { let mut active = self.active.lock().await; if let Some(pool) = active.as_ref() - && pool.agent.chunk_bytes() >= size + && pool.size >= size && *pool.lost.borrow() < WINDOWS_PER_POOL { pool.clone() } else { - let pool = tokio::task::spawn_blocking(move || Pool::open(size)) + let backend = self.backend; + let pool = tokio::task::spawn_blocking(move || Pool::open(backend, size)) .await .map_err(|_| { - Error::General("NIXL agent startup was interrupted".into()) + Error::General("RDMA registration was interrupted".into()) })??; *active = Some(pool.clone()); pool @@ -55,97 +63,135 @@ impl Pools { } struct Pool { + size: usize, + free: Mutex>, + available: Semaphore, lost: watch::Sender, - agent: Arc, - name: HeaderValue, - metadata: HeaderValue, - _budget: SemaphorePermit<'static>, + budget: Budget, } impl Pool { - fn open(window: usize) -> Result> { + fn open(backend: RdmaBackend, size: usize) -> Result> { let budget = AGENTS .try_acquire() - .map_err(|_| Error::General("NIXL registered memory budget exhausted".into()))?; - let id = getrandom::u64() - .map_err(|_| Error::General("Could not generate a NIXL agent ID".into()))?; - let name = format!("rc-{}-{id:016x}", std::process::id()); - let agent = NixlServer::new(&NixlConfig { - agent_name: name.clone(), - chunk_bytes: window, - pool_bytes: WINDOWS_PER_POOL * window, - ..NixlConfig::default() - }) - .map_err(native_error)?; - let mut metadata = - HeaderValue::from_str(&STANDARD.encode(agent.local_metadata().map_err(native_error)?)) - .map_err(|_| Error::General("Invalid NIXL agent metadata".into()))?; - metadata.set_sensitive(true); + .map_err(|_| Error::General("RDMA registered memory budget exhausted".into()))?; + let budget = Arc::new(budget); + let buffers = buffer::register(backend, size, WINDOWS_PER_POOL, &budget)?; Ok(Arc::new(Self { - agent, - name: HeaderValue::from_str(&name).expect("ASCII agent ID"), - metadata, + size, + free: Mutex::new(buffers), + available: Semaphore::new(WINDOWS_PER_POOL), lost: watch::Sender::new(0), - _budget: budget, + budget, })) } - /// A retired registration wakes its waiters so the owner can replace it. async fn reserve(self: &Arc) -> Result> { let mut lost = self.lost.subscribe(); tokio::select! { biased; _ = lost.wait_for(|count| *count == WINDOWS_PER_POOL) => Ok(None), - result = self.agent.reserve(Duration::from_secs(60)) => { - Ok(Some(Window { chunk: result.map_err(native_error)?, pool: self.clone() })) + result = tokio::time::timeout(Duration::from_secs(60), self.available.acquire()) => { + let permit = result + .map_err(|_| Error::General("Timed out waiting for a registered window".into()))? + .expect("registration semaphore remains open"); + let buffer = self.free.lock().unwrap_or_else(|e| e.into_inner()) + .pop().expect("each permit owns a free window"); + permit.forget(); + Ok(Some(Window { buffer: Some(buffer), pool: self.clone(), len: 0 })) } } } } -pub(crate) fn native_error(error: rustfs_nixl::NixlError) -> Error { - Error::General(format!("NIXL/UCX: {error}")) -} - pub(crate) struct Window { - pub(crate) chunk: StagingChunk, + buffer: Option, pool: Arc, + len: usize, } - impl Window { - pub(crate) fn bind(&self, headers: &mut HeaderMap, len: usize) -> Result<()> { - crate::wire::bind( - headers, - &self.pool.name, - &self.pool.metadata, - self.chunk.addr(), - len, - ) + pub(crate) fn writable(&mut self) -> Result<&mut [u8]> { + self.buffer.as_mut().expect("owned window").writable() + } + pub(crate) fn received(&mut self) -> Result<&[u8]> { + let len = self.len; + self.writable()? + .get(..len) + .ok_or_else(|| Error::General("Received length exceeds the registered window".into())) } - pub(crate) fn expose(self) -> Exposed { - Exposed(Some(self)) + pub(crate) fn finish_read(&mut self, len: usize) -> Result<()> { + if len > self.pool.size { + return Err(Error::General( + "Received length exceeds the registered window".into(), + )); + } + self.len = len; + Ok(()) + } + + pub(crate) fn expose( + self, + _method: &Method, + len: usize, + headers: &mut HeaderMap, + ) -> Result { + let mut exposed = Exposed(Some(self)); + let buffer = exposed.window_mut().buffer.as_mut().expect("owned window"); + let result = match buffer { + Buffer::Nixl { + chunk, + agent, + metadata, + } => crate::wire::bind(headers, agent, metadata, chunk.addr(), len), + #[cfg(feature = "cuobject")] + Buffer::CuObject(buffer) => buffer.describe(_method, len, headers), + }; + if let Err(error) = result { + // The token has not left this process. Release it before reuse. + exposed.finished()?; + return Err(error); + } + Ok(exposed) } } -/// Until a receipt proves completion, cancellation must retain the address -/// and its registration. The process registration budget also covers this list. -pub(crate) struct Exposed(Option); +impl Drop for Window { + fn drop(&mut self) { + if let Some(buffer) = self.buffer.take() { + self.pool + .free + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(buffer); + self.pool.available.add_permits(1); + } + } +} +pub(crate) struct Exposed(Option); impl Exposed { - pub(crate) fn finished(mut self) -> Window { - self.0.take().expect("owned NIXL window") + fn window_mut(&mut self) -> &mut Window { + self.0.as_mut().expect("owned transfer") } -} + pub(crate) fn finished(mut self) -> Result { + #[cfg(feature = "cuobject")] + if let Some(Buffer::CuObject(host)) = self.window_mut().buffer.as_mut() { + host.release_token()?; + } + Ok(self.0.take().expect("owned transfer")) + } +} impl Drop for Exposed { fn drop(&mut self) { - if let Some(window) = self.0.take() { + if let Some(mut window) = self.0.take() { + let buffer = window.buffer.take().expect("owned transfer"); window.pool.lost.send_modify(|lost| *lost += 1); QUARANTINE .lock() - .unwrap_or_else(|err| err.into_inner()) - .push(window); + .unwrap_or_else(|e| e.into_inner()) + .push((buffer, Arc::clone(&window.pool.budget))); } } } @@ -154,9 +200,49 @@ impl Drop for Exposed { mod tests { use super::*; + #[test] + fn registrations_use_a_bounded_size_class() { + assert_eq!(window_size(0), SMALL_WINDOW); + assert_eq!(window_size(SMALL_WINDOW as u64), SMALL_WINDOW); + assert_eq!(window_size(3 * SMALL_WINDOW as u64), 4 * SMALL_WINDOW); + assert_eq!(window_size(u64::MAX), WINDOW); + } + #[tokio::test] async fn uncertain_windows_wake_waiters_and_cannot_be_reissued() { - let pools = Pools::default(); + check_window_lifetime(RdmaBackend::Nixl).await; + } + + #[cfg(feature = "cuobject")] + #[tokio::test] + #[ignore = "requires an NVIDIA cuObject client SDK and an active RDMA device"] + async fn cuobject_token_survives_cancellation_and_timeout() { + check_window_lifetime(RdmaBackend::CuObject).await; + } + + fn observe(exposed: Exposed) -> (Exposed, Option>) { + #[cfg(feature = "cuobject")] + { + let mut exposed = exposed; + let release = match exposed.window_mut().buffer.as_mut() { + Some(Buffer::CuObject(host)) => { + assert!(host.writable().is_err()); + assert!( + host.describe(&Method::GET, 1, &mut HeaderMap::new()) + .is_err() + ); + Some(host.releases.clone()) + } + _ => None, + }; + (exposed, release) + } + #[cfg(not(feature = "cuobject"))] + (exposed, None) + } + + async fn check_window_lifetime(backend: RdmaBackend) { + let pools = Pools::new(backend); let first = pools.reserve(32).await.unwrap(); let second = pools.reserve(32).await.unwrap(); let old = first.pool.clone(); @@ -168,17 +254,92 @@ mod tests { _ = &mut waiting => panic!("both windows are checked out"), _ = std::future::ready(()) => {} } - drop(first.expose()); - drop(second.expose()); + let mut headers = HeaderMap::new(); + let (first, first_releases) = + observe(first.expose(&Method::GET, 32, &mut headers).unwrap()); + #[cfg(feature = "cuobject")] + if backend == RdmaBackend::CuObject { + assert!(headers[crate::nvidia::TOKEN_HEADER].is_sensitive()); + } + let exchanging = |exposed: Exposed| async move { + std::future::pending::<()>().await; + exposed.finished() + }; + let (started, ready) = tokio::sync::oneshot::channel(); + let cancelled = tokio::spawn(async move { + started.send(()).unwrap(); + exchanging(first).await + }); + ready.await.unwrap(); + cancelled.abort(); + assert!(matches!(cancelled.await, Err(e) if e.is_cancelled())); + let mut put_headers = HeaderMap::new(); + let second = second.expose(&Method::PUT, 32, &mut put_headers).unwrap(); + let (second, second_releases) = observe(second); + assert!( + tokio::time::timeout(Duration::from_millis(1), exchanging(second)) + .await + .is_err() + ); tokio::select! { biased; result = waiting => assert!(result.unwrap().is_none()), _ = std::future::ready(()) => panic!("retiring a pool must wake its waiters immediately"), } - let replacement = pools.reserve(32).await.unwrap(); + #[cfg(feature = "cuobject")] + if backend == RdmaBackend::CuObject { + let retained = QUARANTINE.lock().unwrap(); + for advertised in [ + &headers[crate::nvidia::TOKEN_HEADER], + &put_headers[crate::nvidia::TOKEN_HEADER], + ] { + assert!(retained.iter().any(|(buffer, budget)| Arc::ptr_eq(budget, &old.budget) + && matches!(buffer, Buffer::CuObject(host) if host.holds_token(advertised)))); + } + } + let replacement = pools.reserve(3 * SMALL_WINDOW as u64).await.unwrap(); + assert_eq!(replacement.pool.size, 4 * SMALL_WINDOW); assert!(!Arc::ptr_eq(&old, &replacement.pool)); - let returned = replacement.expose().finished(); + let fresh_pool = replacement.pool.clone(); + let (completed, completed_releases) = observe( + replacement + .expose(&Method::GET, 32, &mut HeaderMap::new()) + .unwrap(), + ); + let returned = completed.finished().unwrap(); + if let Some(count) = &completed_releases { + assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1); + } drop(returned); - assert!(old.agent.try_reserve().is_none()); + if backend == RdmaBackend::CuObject { + for counter in [first_releases, second_releases] { + assert_eq!( + counter.unwrap().load(std::sync::atomic::Ordering::SeqCst), + 0 + ); + } + assert_eq!( + completed_releases + .unwrap() + .load(std::sync::atomic::Ordering::SeqCst), + 1 + ); + } + assert_eq!(fresh_pool.available.available_permits(), WINDOWS_PER_POOL); + assert_eq!(old.available.available_permits(), 0); + + // Retiring a pool with one uncertain transfer must free its idle sibling. + let window = pools.reserve(32).await.unwrap(); + let pool = Arc::downgrade(&fresh_pool); + let budget = Arc::downgrade(&fresh_pool.budget); + drop( + window + .expose(&Method::GET, 32, &mut HeaderMap::new()) + .unwrap(), + ); + drop(fresh_pool); + drop(pools); + assert!(pool.upgrade().is_none()); + assert!(budget.upgrade().is_some()); } } diff --git a/nixl/src/transport.rs b/nixl/src/transport.rs index 2033f83..8f25893 100644 --- a/nixl/src/transport.rs +++ b/nixl/src/transport.rs @@ -11,16 +11,110 @@ use rustfs_nixl::RDMA_REPLY_HEADER; use std::sync::Arc; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; -use crate::pool::{Exposed, Pools, WINDOW, Window, native_error}; +use crate::pool::{Exposed, Pools, WINDOW, Window}; use crate::wire; +use rc_core::RdmaBackend; -pub(crate) struct Factory; +use std::collections::HashMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU8, Ordering}; +use tokio::sync::{Semaphore, SemaphorePermit}; + +pub(crate) struct Factory { + backend: RdmaBackend, + endpoints: Mutex>>, +} + +impl Factory { + pub(crate) fn new(backend: RdmaBackend) -> Self { + Self { + backend, + endpoints: Mutex::default(), + } + } + + fn support(&self, endpoint: Option<&str>) -> Arc { + match endpoint { + Some(endpoint) => self + .endpoints + .lock() + .unwrap_or_else(|e| e.into_inner()) + .entry(endpoint.to_owned()) + .or_default() + .clone(), + None => Arc::default(), + } + } +} + +#[derive(Default)] +struct EndpointSupport { + get: Capability, + upload_part: Capability, +} + +struct Capability { + state: AtomicU8, + probe: Semaphore, +} + +impl Default for Capability { + fn default() -> Self { + Self { + state: AtomicU8::new(Self::UNKNOWN), + probe: Semaphore::new(1), + } + } +} + +impl Capability { + const UNKNOWN: u8 = 0; + const SUPPORTED: u8 = 1; + const HTTP_ONLY: u8 = 2; + + // Only the first operation probes. Once a response identifies the + // transport, ordinary concurrent transfers need no permit. + async fn enter(&self) -> DataTransportResult>> { + let permit = if self.state.load(Ordering::Acquire) == Self::UNKNOWN { + self.probe.acquire().await.ok() + } else { + None + }; + if self.state.load(Ordering::Acquire) == Self::HTTP_ONLY { + return Err(unavailable(Error::UnsupportedFeature( + "Endpoint served this operation over HTTP".into(), + ))); + } + Ok(permit) + } + + fn supported(&self) { + if self + .state + .compare_exchange( + Self::UNKNOWN, + Self::SUPPORTED, + Ordering::AcqRel, + Ordering::Acquire, + ) + .is_ok() + { + self.probe.close(); + } + } + + fn http_only(&self) { + self.state.store(Self::HTTP_ONLY, Ordering::Release); + self.probe.close(); + } +} impl ObjectDataTransportFactory for Factory { fn create(&self, control: Arc) -> Result> { Ok(Arc::new(Transport { + support: self.support(control.endpoint()), control, - pools: Pools::default(), + pools: Pools::new(self.backend), })) } } @@ -28,12 +122,13 @@ impl ObjectDataTransportFactory for Factory { struct Transport { control: Arc, pools: Pools, + support: Arc, } fn failed(state: DataTransferState, source: Error) -> DataTransportError { DataTransportError { state, - message: "RustFS NIXL object transfer".into(), + message: "RDMA object transfer".into(), source: Some(Box::new(source)), } } @@ -54,11 +149,15 @@ impl Transport { request: ControlRequest, exposed: Exposed, ) -> DataTransportResult<(ControlResponse, Exposed)> { - match self.control.execute_headers(request).await { - Ok(response) => Ok((response, exposed)), + match self.control.execute_registered(request).await { + Ok(RegisteredControlResponse::Response(response)) => Ok((response, exposed)), + Ok(RegisteredControlResponse::RejectedBeforeDma(error)) => { + drop(exposed.finished().map_err(rejected)?); + Err(rejected(error)) + } Err(error @ Error::RequestRejected(_)) => { // ControlExecutor rejected the request locally before sending it. - drop(exposed.finished()); + drop(exposed.finished().map_err(rejected)?); Err(unavailable(error)) } Err(error) => Err(unknown(error)), diff --git a/nixl/src/transport/download.rs b/nixl/src/transport/download.rs index abb1d54..0a378a4 100644 --- a/nixl/src/transport/download.rs +++ b/nixl/src/transport/download.rs @@ -5,6 +5,33 @@ pub(super) enum Sink<'a> { Writer(&'a mut (dyn AsyncWrite + Send + Unpin)), } +impl Sink<'_> { + async fn write_range( + &mut self, + mut window: Window, + offset: u64, + checksum: Option<&mut PayloadChecksumVerifier>, + ) -> Result<()> { + if let Some(checksum) = checksum { + checksum.update(window.received()?); + } + match self { + Self::Writer(writer) => writer.write_all(window.received()?).await?, + Self::File(file) => { + use std::os::unix::fs::FileExt; + let file = file.clone(); + tokio::task::spawn_blocking(move || { + file.write_all_at(window.received()?, offset)?; + Ok::<_, Error>(()) + }) + .await + .map_err(|_| Error::General("RDMA file write was interrupted".into()))??; + } + } + Ok(()) + } +} + struct Selection<'a> { path: &'a RemotePath, requested_version: Option<&'a str>, @@ -26,6 +53,31 @@ fn read_request( wire::request(method, path, query, headers) } +// The caller may retry over HTTP only if both ranges declined before output. +pub(super) fn merged_ranges( + first: DataTransportResult<()>, + second: DataTransportResult, +) -> DataTransportResult { + match (first, second) { + (Ok(()), Ok(value)) => Ok(value), + (Err(first), Err(second)) => { + if second.state == DataTransferState::OutcomeUnknown + || first.state == DataTransferState::NotAccepted + { + Err(second) + } else { + Err(first) + } + } + (Ok(()), Err(mut error)) | (Err(mut error), Ok(_)) => { + if error.state == DataTransferState::NotAccepted { + error.state = DataTransferState::ConfirmedFailure; + } + Err(error) + } + } +} + impl Transport { async fn fetch( &self, @@ -33,6 +85,7 @@ impl Transport { offset: u64, len: usize, ranged: bool, + window: Window, ) -> DataTransportResult { let mut headers = HeaderMap::new(); headers.insert("if-match", selection.etag.clone()); @@ -46,10 +99,10 @@ impl Transport { } else { StatusCode::OK }; - let window = self.pools.reserve(len as u64).await.map_err(unavailable)?; // An empty object still requires a nonempty descriptor. - window.bind(&mut headers, len.max(1)).map_err(unavailable)?; - let exposed = window.expose(); + let exposed = window + .expose(&Method::GET, len.max(1), &mut headers) + .map_err(unavailable)?; let (response, exposed) = self .exchange( read_request( @@ -69,24 +122,26 @@ impl Transport { if !response.headers.contains_key(RDMA_REPLY_HEADER) { // An ordinary successful GET returned the object in its HTTP body. // It is safe to try the ordinary reader before publishing any bytes. - drop(exposed.finished()); + // A missing receipt permits the S3 fallback but does not prove the window is idle. + self.support.get.http_only(); return Err(unavailable(Error::UnsupportedFeature( "The endpoint served GET over HTTP".into(), ))); } if response.status != expected { return Err(rejected(Error::General( - "Unexpected NIXL GET status".into(), + "Unexpected RDMA GET status".into(), ))); } wire::receipt(expected, &response.headers, len as u64).map_err(rejected)?; - let mut window = exposed.finished(); + self.support.get.supported(); + let mut window = exposed.finished().map_err(rejected)?; if wire::field(&response.headers, "content-length") .map_err(rejected)? .is_some_and(|value| value != "0") { return Err(rejected(Error::General( - "NIXL GET returned an HTTP payload".into(), + "RDMA GET returned an HTTP payload".into(), ))); } if wire::field(&response.headers, "x-amz-version-id").map_err(rejected)? @@ -107,15 +162,11 @@ impl Transport { != Some(&expected_range) { return Err(rejected(Error::General( - "NIXL GET returned a different object range".into(), + "RDMA GET returned a different object range".into(), ))); } } - window - .chunk - .advance(len) - .map_err(native_error) - .map_err(rejected)?; + window.finish_read(len).map_err(rejected)?; Ok(window) } @@ -126,9 +177,10 @@ impl Transport { ) -> DataTransportResult { if request.options.customer_key.is_some() { return Err(unavailable(Error::UnsupportedFeature( - "NIXL does not encrypt SSE-C payloads in transit".into(), + "RDMA does not encrypt SSE-C payloads in transit".into(), ))); } + let _probe = self.support.get.enter().await?; let requested_version = request.options.version_id.as_deref(); let mut headers = HeaderMap::new(); if request.options.checksum_mode { @@ -154,7 +206,7 @@ impl Transport { let length = request.max_bytes.unwrap_or(total).min(total); if length > request.max_receive_bytes { return Err(rejected(Error::General( - "NIXL object exceeds the receive bound".into(), + "RDMA object exceeds the receive bound".into(), ))); } let observed_version = wire::field(&head.headers, "x-amz-version-id").map_err(rejected)?; @@ -171,51 +223,60 @@ impl Transport { observed_version, }; let ranged = length > 0 && (request.max_bytes.is_some() || length > WINDOW as u64); - let first = length.min(WINDOW as u64) as usize; - let mut current = self.fetch(&selection, 0, first, ranged).await?; - let mut end = first as u64; let mut checksum = PayloadChecksumVerifier::new(&head.headers).map_err(rejected)?; + let mut offset = 0; loop { - let write = async { - if length == total { - checksum.update(current.chunk.staged().map_err(native_error)?); - } - let offset = end - current.chunk.len() as u64; - match &mut target { - Sink::Writer(writer) => { - writer - .write_all(current.chunk.staged().map_err(native_error)?) - .await? - } - Sink::File(file) => { - use std::os::unix::fs::FileExt; - let file = file.clone(); - tokio::task::spawn_blocking(move || { - file.write_all_at( - current.chunk.staged().map_err(native_error)?, - offset, - )?; - Ok::<_, Error>(()) - }) - .await - .map_err(|_| Error::General("NIXL file write was interrupted".into()))??; - } + let first = (length - offset).min(WINDOW as u64); + let next = offset + first; + let second = (length - next).min(WINDOW as u64); + // Reserve the earlier range first. It can finish and release its window + // even if other downloads or a quarantined window leave only one slot. + let window = self.pools.reserve(first).await.map_err(|e| { + if offset == 0 { + unavailable(e) + } else { + rejected(e) } - (request.on_progress)(end, Some(length)); - Ok::<_, Error>(()) + })?; + let publish_first = async { + let window = self + .fetch(&selection, offset, first as usize, ranged, window) + .await + .map_err(|mut error| { + if offset != 0 && error.state == DataTransferState::NotAccepted { + error.state = DataTransferState::ConfirmedFailure; + } + error + })?; + target + .write_range(window, offset, (length == total).then_some(&mut checksum)) + .await + .map_err(rejected)?; + (request.on_progress)(next, Some(length)); + Ok(()) }; - if end == length { - write.await.map_err(rejected)?; + if second == 0 { + publish_first.await?; + break; + } + let fetch_second = async { + let window = self.pools.reserve(second).await.map_err(unavailable)?; + self.fetch(&selection, next, second as usize, true, window) + .await + }; + // Settle both control exchanges even when one fails. Only the ordered + // consumer updates the checksum, writes bytes and reports progress. + let (first_result, second_result) = tokio::join!(publish_first, fetch_second); + let window = merged_ranges(first_result, second_result)?; + target + .write_range(window, next, (length == total).then_some(&mut checksum)) + .await + .map_err(rejected)?; + offset = next + second; + (request.on_progress)(offset, Some(length)); + if offset == length { break; } - let size = (length - end).min(WINDOW as u64) as usize; - let (written, next) = tokio::join!(write, self.fetch(&selection, end, size, true)); - written.map_err(rejected)?; - current = next.map_err(|mut err| { - err.state = DataTransferState::ConfirmedFailure; - err - })?; - end += size as u64; } if length == total { checksum.verify(&head.headers).map_err(rejected)?; diff --git a/nixl/src/transport/tests.rs b/nixl/src/transport/tests.rs index c561f80..9b42f5b 100644 --- a/nixl/src/transport/tests.rs +++ b/nixl/src/transport/tests.rs @@ -36,7 +36,9 @@ async fn download( queries: Mutex::default(), get_version, }); - let transport = Factory.create(endpoint.clone()).unwrap(); + let transport = Factory::new(RdmaBackend::Nixl) + .create(endpoint.clone()) + .unwrap(); let path = RemotePath::new("test", "bucket", "key"); let options = rc_core::TransferReadOptions { version_id: version_id.map(str::to_owned), @@ -98,7 +100,9 @@ async fn a_delete_marker_keeps_its_version_and_exit_code() { } } - let transport = Factory.create(Arc::new(DeleteMarker)).unwrap(); + let transport = Factory::new(RdmaBackend::Nixl) + .create(Arc::new(DeleteMarker)) + .unwrap(); let path = RemotePath::new("test", "bucket", "key"); let options = rc_core::ObjectReadOptions { version_id: Some("v2".into()), @@ -123,3 +127,419 @@ async fn a_delete_marker_keeps_its_version_and_exit_code() { ); } } + +#[tokio::test] +async fn only_proven_conditional_rejections_reuse_the_registered_window() { + struct Peer(Mutex>); + #[async_trait] + impl ControlExecutor for Peer { + async fn execute_headers(&self, req: ControlRequest) -> Result { + assert_eq!(req.method, Method::HEAD); + let mut headers = HeaderMap::new(); + headers.insert("etag", HeaderValue::from_static("\"etag\"")); + headers.insert("content-length", HeaderValue::from_static("0")); + Ok(ControlResponse { + status: StatusCode::OK, + headers, + }) + } + async fn execute_registered( + &self, + req: ControlRequest, + ) -> Result { + assert_eq!(req.method, Method::GET); + assert!(req.headers.contains_key("if-match")); + let mut seen = self.0.lock().unwrap(); + seen.push(req.headers[rustfs_nixl::NIXL_BUFFER_HEADER].clone()); + Ok(match seen.len() { + 1 => RegisteredControlResponse::Response(ControlResponse { + status: StatusCode::PRECONDITION_FAILED, + headers: HeaderMap::new(), + }), + 2..=19 => RegisteredControlResponse::RejectedBeforeDma(Error::Conflict( + "PreconditionFailed".into(), + )), + _ => { + let mut headers = HeaderMap::new(); + headers.insert(RDMA_REPLY_HEADER, HeaderValue::from_static("200")); + RegisteredControlResponse::Response(ControlResponse { + status: StatusCode::OK, + headers, + }) + } + }) + } + } + let peer = Arc::new(Peer(Mutex::default())); + let transport = Factory::new(RdmaBackend::Nixl) + .create(peer.clone()) + .unwrap(); + let path = RemotePath::new("test", "bucket", "key"); + let opts = rc_core::TransferReadOptions::default(); + for i in 1..=20 { + let r = transport + .download( + DownloadRequest { + path: &path, + options: &opts, + max_bytes: None, + max_receive_bytes: 64, + on_progress: &mut |_, _| {}, + }, + &mut tokio::io::sink(), + ) + .await; + assert_eq!(r.is_ok(), i == 20); + } + let seen = peer.0.lock().unwrap(); + assert_ne!(seen[0], seen[1]); + assert!(seen[1..].iter().all(|v| v == seen[1])); +} + +#[cfg(feature = "cuobject")] +#[tokio::test] +#[ignore = "requires an NVIDIA RDMA device and an authenticated RustFS object"] +async fn rustfs_declines_a_stale_conditional_get_before_dma() { + let env = |key| { + std::env::var(key) + .expect("configure the test endpoint, credentials, CA and existing bucket") + }; + let mut alias = rc_core::Alias::new( + "test", + env("RC_TEST_ENDPOINT"), + env("AWS_ACCESS_KEY_ID"), + env("AWS_SECRET_ACCESS_KEY"), + ); + alias.ca_bundle = Some(env("RC_TEST_CA")); + let client = rc_s3::S3Client::new(alias).await.unwrap(); + let path = RemotePath::new("test", env("RC_TEST_BUCKET"), "known"); + let transport = Transport { + control: Arc::new(client), + pools: Pools::new(RdmaBackend::CuObject), + support: Arc::default(), + }; + for _ in 0..20 { + let mut headers = HeaderMap::new(); + headers.insert("if-match", HeaderValue::from_static("\"stale\"")); + let exposed = transport + .pools + .reserve(4096) + .await + .unwrap() + .expose(&Method::GET, 4096, &mut headers) + .unwrap(); + let req = wire::request(Method::GET, &path, vec![], headers); + match transport.exchange(req, exposed).await { + Err(error) if matches!(error.source.as_deref(), Some(Error::Conflict(_))) => {} + _ => panic!("expected an authenticated pre-transfer rejection"), + } + } +} + +#[tokio::test] +async fn large_get_submits_both_ranges_and_publishes_in_order() { + use rustfs_nixl::{ + NIXL_AGENT_HEADER, NIXL_BUFFER_HEADER, NIXL_METADATA_HEADER, NixlConfig, NixlServer, + RdmaToken, + }; + + struct Ranges { + peer: Arc, + payload: Vec, + second_written: tokio::sync::Notify, + wrong_checksum: bool, + } + + #[async_trait] + impl ControlExecutor for Ranges { + async fn execute_headers(&self, request: ControlRequest) -> Result { + let total = self.payload.len(); + let mut headers = HeaderMap::new(); + headers.insert("etag", HeaderValue::from_static("\"immutable\"")); + if request.method == Method::HEAD { + headers.insert("content-length", HeaderValue::from(total)); + if self.wrong_checksum { + // SHA-256 of the empty payload, while these two ranges are nonempty. + headers.insert( + "x-amz-checksum-sha256", + HeaderValue::from_static("47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="), + ); + } + return Ok(ControlResponse { + status: StatusCode::OK, + headers, + }); + } + assert_eq!(request.headers["if-match"], "\"immutable\""); + let range = request.headers["range"] + .to_str() + .unwrap() + .strip_prefix("bytes=") + .unwrap(); + let (start, end) = range.split_once('-').unwrap(); + let (start, end): (usize, usize) = (start.parse().unwrap(), end.parse().unwrap()); + if start == 0 { + assert_eq!(end, WINDOW - 1); + tokio::time::timeout( + std::time::Duration::from_secs(5), + self.second_written.notified(), + ) + .await + .expect("the second range must finish before the first is written"); + } else { + assert_eq!((start, end), (WINDOW, total - 1)); + } + let token = RdmaToken::from_headers( + request.headers[NIXL_AGENT_HEADER].to_str().unwrap(), + Some(request.headers[NIXL_METADATA_HEADER].to_str().unwrap()), + request.headers[NIXL_BUFFER_HEADER].to_str().unwrap(), + ) + .unwrap(); + let mut staging = self.peer.try_reserve().unwrap(); + staging.append(&self.payload[start..=end]).unwrap(); + let (written, _) = self + .peer + .write_to_client_owned("key", &token, 0, staging) + .await + .unwrap(); + assert_eq!(written, (end - start + 1) as u64); + if start == WINDOW { + self.second_written.notify_one(); + } + headers.insert( + "content-range", + format!("bytes {start}-{end}/{total}").parse().unwrap(), + ); + headers.insert("content-length", HeaderValue::from_static("0")); + headers.insert(RDMA_REPLY_HEADER, HeaderValue::from_static("206")); + headers.insert( + rustfs_nixl::RDMA_BYTES_TRANSFERRED_HEADER, + HeaderValue::from(written), + ); + Ok(ControlResponse { + status: StatusCode::PARTIAL_CONTENT, + headers, + }) + } + } + + let peer = NixlServer::new(&NixlConfig { + agent_name: "rc-ordered-range-peer".into(), + chunk_bytes: WINDOW, + pool_bytes: WINDOW, + ..Default::default() + }) + .unwrap(); + for wrong_checksum in [false, true] { + let ranges = Arc::new(Ranges { + peer: peer.clone(), + payload: (0..=250) + .cycle() + .take(WINDOW) + .chain(*b"second range bytes!") + .collect(), + second_written: tokio::sync::Notify::new(), + wrong_checksum, + }); + let transport = Factory::new(RdmaBackend::Nixl) + .create(ranges.clone()) + .unwrap(); + let mut progress = Vec::new(); + let total = ranges.payload.len() as u64; + let mut output = Vec::with_capacity(ranges.payload.len()); + let result = transport + .download( + DownloadRequest { + path: &RemotePath::new("local", "bucket", "key"), + options: &Default::default(), + max_bytes: None, + max_receive_bytes: total, + on_progress: &mut |written, _| progress.push(written), + }, + &mut output, + ) + .await; + if wrong_checksum { + assert!( + matches!(result, Err(error) if matches!(error.source.as_deref(), Some(Error::General(message)) if message.contains("checksum does not match"))) + ); + } else { + assert_eq!(result.unwrap().bytes_transferred, total); + assert!( + output == ranges.payload, + "downloaded bytes differ from the source object" + ); + } + assert_eq!(progress, [WINDOW as u64, total]); + } +} + +#[tokio::test] +async fn one_declined_range_cannot_hide_an_unconfirmed_sibling() { + use std::sync::atomic::{AtomicUsize, Ordering}; + struct Endpoint(AtomicUsize); + #[async_trait] + impl ControlExecutor for Endpoint { + async fn execute_headers(&self, request: ControlRequest) -> Result { + let mut headers = HeaderMap::new(); + if request.method == Method::HEAD { + headers.insert("etag", HeaderValue::from_static("\"stable\"")); + headers.insert("content-length", HeaderValue::from(WINDOW + 1)); + return Ok(ControlResponse { + status: StatusCode::OK, + headers, + }); + } + self.0.fetch_add(1, Ordering::Relaxed); + if request.headers["range"] + .to_str() + .unwrap() + .starts_with("bytes=0-") + { + Ok(ControlResponse { + status: StatusCode::PARTIAL_CONTENT, + headers, + }) + } else { + Err(Error::Network("control response unavailable".into())) + } + } + } + let endpoint = Arc::new(Endpoint(AtomicUsize::new(0))); + let transport = Factory::new(RdmaBackend::Nixl) + .create(endpoint.clone()) + .unwrap(); + let result = transport + .download( + DownloadRequest { + path: &RemotePath::new("local", "bucket", "key"), + options: &Default::default(), + max_bytes: None, + max_receive_bytes: WINDOW as u64 + 1, + on_progress: &mut |_, _| {}, + }, + &mut tokio::io::sink(), + ) + .await; + assert_eq!(endpoint.0.load(Ordering::Relaxed), 2); + assert_eq!( + result.err().unwrap().state, + DataTransferState::OutcomeUnknown + ); +} + +#[tokio::test] +async fn ordinary_s3_is_probed_once_per_endpoint_backend_and_operation() { + use std::sync::atomic::{AtomicUsize, Ordering}; + struct HttpOnly(AtomicUsize); + #[async_trait] + impl ControlExecutor for HttpOnly { + fn endpoint(&self) -> Option<&str> { + Some("https://ordinary.example") + } + async fn execute_headers(&self, request: ControlRequest) -> Result { + let mut headers = HeaderMap::new(); + if request.method == Method::HEAD { + headers.insert("etag", HeaderValue::from_static("\"tag\"")); + headers.insert("content-length", HeaderValue::from_static("0")); + } else { + self.0.fetch_add(1, Ordering::Relaxed); + } + Ok(ControlResponse { + status: StatusCode::OK, + headers, + }) + } + } + let factory = Factory::new(RdmaBackend::Nixl); + let endpoint = Arc::new(HttpOnly(AtomicUsize::new(0))); + let mut readers = tokio::task::JoinSet::new(); + for _ in 0..20 { + let transport = factory.create(endpoint.clone()).unwrap(); + readers.spawn(async move { + let path = RemotePath::new("lab", "bucket", "key"); + let result = transport + .download( + DownloadRequest { + path: &path, + options: &Default::default(), + max_bytes: None, + max_receive_bytes: 1, + on_progress: &mut |_, _| {}, + }, + &mut tokio::io::sink(), + ) + .await; + assert_eq!( + result.err().expect("ordinary S3 declined RDMA").state, + DataTransferState::NotAccepted + ); + }); + } + while let Some(task) = readers.join_next().await { + task.unwrap(); + } + assert_eq!(endpoint.0.load(Ordering::Relaxed), 1); + let transport = factory.create(endpoint.clone()).unwrap(); + let staged = transport.staged_upload().unwrap(); + let path = RemotePath::new("lab", "bucket", "key"); + assert!(!staged.probe(&path, "upload", 1).await.unwrap()); + assert_eq!( + staged.probe(&path, "upload", 1).await.unwrap_err().state, + DataTransferState::NotAccepted + ); + assert_eq!(endpoint.0.load(Ordering::Relaxed), 2); + for fresh in [ + factory.support(Some("https://other.example")), + Factory::new(RdmaBackend::CuObject).support(endpoint.endpoint()), + ] { + assert!(fresh.get.enter().await.unwrap().is_some()); + } +} + +#[test] +fn range_failure_precedence_preserves_uncertainty_and_output_state() { + use DataTransferState::{ConfirmedFailure, NotAccepted, OutcomeUnknown}; + let cases = [ + (Some(NotAccepted), Some(NotAccepted), NotAccepted), + (Some(NotAccepted), Some(ConfirmedFailure), ConfirmedFailure), + (Some(ConfirmedFailure), Some(NotAccepted), ConfirmedFailure), + (Some(OutcomeUnknown), Some(ConfirmedFailure), OutcomeUnknown), + (Some(ConfirmedFailure), Some(OutcomeUnknown), OutcomeUnknown), + (Some(OutcomeUnknown), None, OutcomeUnknown), + (None, Some(OutcomeUnknown), OutcomeUnknown), + (None, Some(NotAccepted), ConfirmedFailure), + (Some(NotAccepted), None, ConfirmedFailure), + ]; + for (a, b, state) in cases { + let outcome = |s: Option| match s { + Some(s) => Err(failed(s, Error::General("range failure".into()))), + None => Ok(()), + }; + assert_eq!( + download::merged_ranges(outcome(a), outcome(b)) + .unwrap_err() + .state, + state + ); + } +} + +#[cfg(feature = "cuobject")] +#[test] +#[ignore = "requires the NVIDIA cuObject SDK and an RDMA device"] +fn registration_budget_follows_normal_and_retained_native_mappings() { + use rustfs_cuobject_client::{Client, Operation}; + let client = Client::open().unwrap(); + let owner = Arc::new(()); + let available = Arc::downgrade(&owner); + let window = client.register(1 << 20, owner.clone()).unwrap(); + assert!(client.register(0, owner.clone()).is_err()); + drop(window); + assert_eq!(available.strong_count(), 1); + let mut exposed = client.register(1 << 20, owner.clone()).unwrap(); + exposed.acquire_token(Operation::Get, 1).unwrap(); + drop(exposed); + drop(owner); + assert_eq!(available.strong_count(), 1); +} diff --git a/nixl/src/transport/upload.rs b/nixl/src/transport/upload.rs index 9bff30d..99fa7f5 100644 --- a/nixl/src/transport/upload.rs +++ b/nixl/src/transport/upload.rs @@ -7,16 +7,13 @@ impl Transport { source: &mut (dyn AsyncRead + Unpin + Send), ) -> DataTransportResult { let len = part_len(&request)?; + let _probe = self.support.upload_part.enter().await?; let mut window = self .pools .reserve(request.content_length) .await .map_err(unavailable)?; - let dest = window - .chunk - .spare_mut() - .map_err(native_error) - .map_err(unavailable)?; + let dest = window.writable().map_err(unavailable)?; source .read_exact(&mut dest[..len]) .await @@ -30,7 +27,7 @@ impl Transport { != 0 { return Err(rejected(Error::Conflict( - "NIXL part source exceeds its declared length".into(), + "RDMA part source exceeds its declared length".into(), ))); } self.send_part(&request, window) @@ -41,7 +38,7 @@ impl Transport { fn declined_part() -> DataTransportError { rejected(Error::UnsupportedFeature( - "The endpoint did not accept the NIXL part".into(), + "The endpoint did not accept the RDMA part".into(), )) } @@ -51,7 +48,7 @@ fn part_len(request: &UploadRequest<'_>) -> DataTransportResult { .filter(|n| (1..=WINDOW).contains(n)) .ok_or_else(|| { unavailable(Error::UnsupportedFeature( - "Part exceeds the registered NIXL window".into(), + "Part exceeds the registered RDMA window".into(), )) }) } @@ -68,16 +65,13 @@ impl StagedUploadTransport for Transport { upload_id: &str, first_part_bytes: u64, ) -> DataTransportResult { + let _probe = self.support.upload_part.enter().await?; let mut window = self .pools .reserve(first_part_bytes) .await .map_err(unavailable)?; - window - .chunk - .append(&[0]) - .map_err(native_error) - .map_err(unavailable)?; + window.writable().map_err(unavailable)?[0] = 0; let options = rc_core::ObjectWriteOptions::default(); let request = UploadRequest { path, @@ -100,20 +94,18 @@ impl StagedUploadTransport for Transport { ) -> DataTransportResult { use std::os::unix::fs::FileExt; let len = part_len(&request)?; + let _probe = self.support.upload_part.enter().await?; let mut window = self .pools .reserve(request.content_length) .await .map_err(unavailable)?; let window = tokio::task::spawn_blocking(move || { - file.read_exact_at( - &mut window.chunk.spare_mut().map_err(native_error)?[..len], - offset, - )?; + file.read_exact_at(&mut window.writable()?[..len], offset)?; Ok::<_, Error>(window) }) .await - .map_err(|_| rejected(Error::General("NIXL file read was interrupted".into())))? + .map_err(|_| rejected(Error::General("RDMA file read was interrupted".into())))? .map_err(rejected)?; self.send_part(&request, window) .await? @@ -133,17 +125,18 @@ impl Transport { } = request.operation else { return Err(unavailable(Error::UnsupportedFeature( - "NIXL writes require an unpublished multipart part".into(), + "RDMA writes require an unpublished multipart part".into(), ))); }; let len = part_len(request)?; let mut headers = HeaderMap::new(); - window.bind(&mut headers, len).map_err(unavailable)?; + let exposed = window + .expose(&Method::PUT, len, &mut headers) + .map_err(unavailable)?; let query = vec![ ("uploadId".into(), upload_id.into()), ("partNumber".into(), part_number.to_string()), ]; - let exposed = window.expose(); let (response, exposed) = self .exchange( wire::request(Method::PUT, request.path, query, headers), @@ -155,15 +148,17 @@ impl Transport { return Err(rejected(response.object_error(request.path, None))); } if !response.headers.contains_key(RDMA_REPLY_HEADER) { - drop(exposed.finished()); + // A missing receipt permits the S3 fallback but does not prove the window is idle. + self.support.upload_part.http_only(); return Ok(None); } wire::receipt(StatusCode::OK, &response.headers, len as u64).map_err(unknown)?; - drop(exposed.finished()); + self.support.upload_part.supported(); + drop(exposed.finished().map_err(rejected)?); let etag = wire::field(&response.headers, "etag") .map_err(rejected)? .filter(|e| !e.is_empty()) - .ok_or_else(|| rejected(Error::General("NIXL UploadPart returned no ETag".into())))?; + .ok_or_else(|| rejected(Error::General("RDMA UploadPart returned no ETag".into())))?; let mut object = ObjectInfo::file(&request.path.key, len as i64); object.etag = Some(etag.into()); Ok(Some(UploadResult { diff --git a/nixl/src/wire.rs b/nixl/src/wire.rs index c83ae96..44ad99e 100644 --- a/nixl/src/wire.rs +++ b/nixl/src/wire.rs @@ -54,16 +54,16 @@ pub(crate) fn field<'a>(headers: &'a HeaderMap, name: &str) -> Result Result<()> { if field(headers, RDMA_REPLY_HEADER)? != Some(status.as_str()) { return Err(Error::UnsupportedFeature( - "The endpoint did not confirm a RustFS NIXL transfer".into(), + "The endpoint did not confirm an RDMA transfer".into(), )); } let moved = field(headers, RDMA_BYTES_TRANSFERRED_HEADER)? .unwrap_or("0") .parse::() - .map_err(|_| Error::General("Invalid NIXL transfer count".into()))?; + .map_err(|_| Error::General("Invalid RDMA transfer count".into()))?; if moved != bytes { return Err(Error::General(format!( - "NIXL transferred {moved} of {bytes} bytes" + "RDMA transferred {moved} of {bytes} bytes" ))); } Ok(()) diff --git a/nixl/src/wire/native_test.rs b/nixl/src/wire/native_test.rs index acc3c02..b3f5dc6 100644 --- a/nixl/src/wire/native_test.rs +++ b/nixl/src/wire/native_test.rs @@ -13,9 +13,9 @@ async fn rustfs_reads_and_writes_the_advertised_host_window() { }) .unwrap(); let mut source = client.reserve(6).await.unwrap(); - source.chunk.append(b"upload").unwrap(); + source.writable().unwrap()[..6].copy_from_slice(b"upload"); let mut fields = HeaderMap::new(); - source.bind(&mut fields, 6).unwrap(); + let exposed = source.expose(&Method::PUT, 6, &mut fields).unwrap(); let token = RdmaToken::from_headers( fields[NIXL_AGENT_HEADER].to_str().unwrap(), Some(fields[NIXL_METADATA_HEADER].to_str().unwrap()), @@ -36,5 +36,7 @@ async fn rustfs_reads_and_writes_the_advertised_host_window() { .await .unwrap(); assert_eq!(written, 6); - assert_eq!(source.chunk.staged().unwrap(), b"result"); + let mut source = exposed.finished().unwrap(); + source.finish_read(6).unwrap(); + assert_eq!(source.received().unwrap(), b"result"); } diff --git a/nixl/tests/interop.sh b/nixl/tests/interop.sh index c67767a..8230469 100755 --- a/nixl/tests/interop.sh +++ b/nixl/tests/interop.sh @@ -1,9 +1,10 @@ #!/usr/bin/env bash # Run against disposable buckets on two verified HTTPS aliases. The second -# endpoint runs the same RustFS binary with RUSTFS_NIXL_ENABLE=false. +# endpoint serves ordinary S3. RC_RDMA_BACKEND selects the native protocol. set -euo pipefail : "${RC:?path to the native rc executable}" -: "${NIXL_BUCKET:?alias/bucket on the native endpoint}" +RDMA_BUCKET=${RDMA_BUCKET:-${NIXL_BUCKET:-}} +: "${RDMA_BUCKET:?alias/bucket on the native endpoint}" : "${HTTP_BUCKET:?alias/bucket on the HTTP-only endpoint}" tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT @@ -17,22 +18,22 @@ dd if=/dev/urandom of="$tmp/model" bs=1M count=129 status=none printf 'NIXL part receipt\n' > "$tmp/small" : > "$tmp/empty" for name in model small empty; do - object="$NIXL_BUCKET/$prefix/$name" + object="$RDMA_BUCKET/$prefix/$name" nr cp "$tmp/$name" "$object" nr cp "$object" "$tmp/native-$name" plain cp "$object" "$tmp/http-$name" cmp "$tmp/$name" "$tmp/native-$name" cmp "$tmp/$name" "$tmp/http-$name" done -nr object head --bytes 19 "$NIXL_BUCKET/$prefix/model" > "$tmp/range" +nr object head --bytes 19 "$RDMA_BUCKET/$prefix/model" > "$tmp/range" head -c 19 "$tmp/model" | cmp - "$tmp/range" -plain cp "$tmp/small" "$NIXL_BUCKET/$prefix/http-source" -nr cp "$NIXL_BUCKET/$prefix/http-source" "$tmp/from-http" +plain cp "$tmp/small" "$RDMA_BUCKET/$prefix/http-source" +nr cp "$RDMA_BUCKET/$prefix/http-source" "$tmp/from-http" cmp "$tmp/small" "$tmp/from-http" -automatic cp "$tmp/small" "$NIXL_BUCKET/$prefix/auto" -nr cp "$NIXL_BUCKET/$prefix/auto" "$tmp/auto" +automatic cp "$tmp/small" "$RDMA_BUCKET/$prefix/auto" +nr cp "$RDMA_BUCKET/$prefix/auto" "$tmp/auto" cmp "$tmp/small" "$tmp/auto" object="$HTTP_BUCKET/$prefix/declined"