Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,11 @@ zeroize = "1.9"
jsonwebtoken = { version = "9", default-features = false, features = ["use_pem"] } # JWT signing (RS256/384/512, PS256/384/512, ES256/384); use_pem = PEM key loading (adds pem + simple_asn1, no TLS)
pkcs8 = { version = "0.10", features = ["encryption", "pem", "std"] } # PKCS#8 PEM parsing + PBES2 passphrase decryption

# `pthread_sigmask` for kernel-owned runtime threads (`src/util/runtime.rs`).
# Already in the graph through tokio, so no new crate is added.
[target.'cfg(unix)'.dependencies]
libc = "0.2"

[dev-dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util"] }
wiremock = "0.6"
Expand Down
2 changes: 2 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ changes go in their respective binding's NEXT_CHANGELOG.

### Fixed

- The C ABI and shared telemetry runtime threads now block SIGPIPE. A TLS write after a peer reset no longer kills a host that doesn't ignore SIGPIPE, such as a Go program linking the C ABI; the write fails with `EPIPE` and the request reports the connection error instead.

---
*Note: When making changes, please add your change under the appropriate
section with a brief description. At release time, move the entries here
Expand Down
1 change: 1 addition & 0 deletions adbc/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion include/databricks_kernel.h
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,8 @@ KernelStatusCode kernel_init_logging(const char* level, const char* file_path);
* that kernel operation. Hosts that need asynchronous logging can copy the
* record into their own bounded queue and return. Strings are valid only during
* the callback. Calls may be concurrent; copy retained strings and synchronize
* the destination. `user_data` is the pointer supplied at initialization. */
* the destination. `user_data` is the pointer supplied at initialization.
* Kernel threads run with SIGPIPE blocked; callbacks must not unblock it. */
typedef void (*KernelLogCallback)(const char* level, const char* target,
const char* message, void* user_data);

Expand Down
1 change: 1 addition & 0 deletions napi/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyo3/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

79 changes: 77 additions & 2 deletions src/c_abi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ use std::sync::OnceLock;
/// synchronous on the emitting thread, and callbacks may run concurrently on
/// multiple kernel threads. Consumers must return promptly, copy any strings
/// they retain, and synchronize their sink. A consumer that needs asynchronous
/// delivery can enqueue its own owned record before returning.
/// delivery can enqueue its own owned record before returning. Kernel threads
/// run with SIGPIPE blocked, and callbacks must not unblock it.
pub type KernelLogCallback = unsafe extern "C" fn(
level: *const c_char,
target: *const c_char,
Expand All @@ -84,7 +85,9 @@ static RUNTIME: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
// The kernel-owned worker stack floor lives in `crate::util::runtime` as a
// single source of truth shared with the telemetry runtime; see that module
// for the floor-not-cap semantics and the #326 / #328 history.
use crate::util::runtime::{ambient_rust_min_stack, runtime_thread_stack_size};
use crate::util::runtime::{
ambient_rust_min_stack, block_sigpipe_on_current_thread, runtime_thread_stack_size,
};

/// Fetch (initialising on first use) the process-wide C-ABI runtime.
///
Expand All @@ -107,6 +110,7 @@ pub(crate) fn runtime() -> crate::kernel_error::Result<&'static tokio::runtime::
.enable_all()
.thread_name("kernel-c-abi")
.thread_stack_size(runtime_thread_stack_size(ambient_rust_min_stack()))
.on_thread_start(block_sigpipe_on_current_thread)
.build()
.map_err(|e| {
crate::kernel_error::Error::internal()
Expand Down Expand Up @@ -557,4 +561,75 @@ mod tests {
caller thread — see #276",
);
}

#[cfg(target_os = "linux")]
#[test]
fn c_abi_runtime_threads_block_sigpipe() {
let rt = runtime().expect("C-ABI runtime");
crate::util::runtime::assert_runtime_threads_block_sigpipe(rt.handle());
}

#[cfg(target_os = "linux")]
const SIGPIPE_CHILD: &str = "DATABRICKS_KERNEL_SIGPIPE_CHILD";

/// With SIGPIPE at its default action, as in a Go host, a write after a peer
/// reset on a C-ABI worker must fail with EPIPE instead of killing the process.
#[cfg(target_os = "linux")]
#[test]
fn c_abi_write_after_peer_reset_returns_epipe() {
let output = std::process::Command::new(std::env::current_exe().expect("test executable"))
.args([
"--exact",
"c_abi::tests::c_abi_write_after_peer_reset_child",
"--nocapture",
])
.env(SIGPIPE_CHILD, "1")
.output()
.expect("launch SIGPIPE subprocess");

// "1 passed" guards against the filter matching nothing.
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success() && stdout.contains("1 passed"),
"write after peer reset failed (status {}):\nstdout:\n{}\nstderr:\n{}",
output.status,
stdout,
String::from_utf8_lossy(&output.stderr),
);
}

#[cfg(target_os = "linux")]
#[test]
fn c_abi_write_after_peer_reset_child() {
if std::env::var_os(SIGPIPE_CHILD).is_none() {
return;
}
// SAFETY: sets the process-wide default action; no handler is involved.
unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL) };
let kind = block_on_ffi(write_after_peer_reset).expect("C-ABI probe");
assert_eq!(kind, std::io::ErrorKind::BrokenPipe);
}

/// Reads ECONNRESET from a peer that reset the connection, then writes with
/// `write_vectored` (a plain `writev`) and returns the write's error kind.
#[cfg(target_os = "linux")]
#[allow(deprecated)] // `set_linger`: a zero linger resets on close without blocking
async fn write_after_peer_reset() -> crate::kernel_error::Result<std::io::ErrorKind> {
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};

let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let mut client = TcpStream::connect(addr).await.unwrap();
let (peer, _) = listener.accept().await.unwrap();
peer.set_linger(Some(Duration::ZERO)).unwrap();
drop(peer);

let read = client.read(&mut [0u8; 1]).await.unwrap_err();
assert_eq!(read.kind(), std::io::ErrorKind::ConnectionReset);
let bufs = [std::io::IoSlice::new(b"x")];
let write = client.write_vectored(&bufs).await.unwrap_err();
Ok(write.kind())
}
}
12 changes: 11 additions & 1 deletion src/telemetry/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,9 @@ impl TelemetryClient {
// abort the process. The worker stack floor is shared with the C-ABI runtime
// via `crate::util::runtime` (single source of truth); see that module for the
// floor-not-cap semantics and the #326 / #328 history.
use crate::util::runtime::{ambient_rust_min_stack, runtime_thread_stack_size};
use crate::util::runtime::{
ambient_rust_min_stack, block_sigpipe_on_current_thread, runtime_thread_stack_size,
};

fn telemetry_runtime_handle() -> std::io::Result<Handle> {
// A host client can outlive the session that created it. Keep its timer,
Expand All @@ -210,6 +212,7 @@ fn telemetry_runtime_handle() -> std::io::Result<Handle> {
.worker_threads(1)
.thread_name("dbx-sql-telemetry")
.thread_stack_size(runtime_thread_stack_size(ambient_rust_min_stack()))
.on_thread_start(block_sigpipe_on_current_thread)
.enable_all()
.build()?;
let handle = built.handle().clone();
Expand All @@ -227,6 +230,13 @@ mod tests {
// The pure floor-not-cap resolution (#326 / #328) is exercised once over
// the shared helper in `crate::util::runtime`.

#[cfg(target_os = "linux")]
#[test]
fn telemetry_runtime_threads_block_sigpipe() {
let handle = telemetry_runtime_handle().expect("telemetry runtime");
crate::util::runtime::assert_runtime_threads_block_sigpipe(&handle);
}

#[tokio::test]
async fn batch_size_triggers_background_flush() {
let exporter = CapturingTelemetryExporter::default();
Expand Down
43 changes: 43 additions & 0 deletions src/util/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,49 @@ pub(crate) fn ambient_rust_min_stack() -> Option<usize> {
.and_then(|v| v.parse::<usize>().ok())
}

/// `on_thread_start` hook for kernel-owned runtimes. std's `write_vectored` is a plain
/// `writev`, so a write after a peer reset raises SIGPIPE on this thread, and non-Rust hosts
/// that don't ignore it (Go) die. Only kernel threads change; the write still fails with EPIPE.
#[cfg(unix)]
pub(crate) fn block_sigpipe_on_current_thread() {
// SAFETY: initialises a stack-local `sigset_t` and changes only this thread's mask.
unsafe {
let mut set: libc::sigset_t = std::mem::zeroed();
libc::sigemptyset(&mut set);
libc::sigaddset(&mut set, libc::SIGPIPE);
libc::pthread_sigmask(libc::SIG_BLOCK, &set, std::ptr::null_mut());
}
}

/// Windows has no SIGPIPE.
#[cfg(not(unix))]
pub(crate) fn block_sigpipe_on_current_thread() {}

/// Whether SIGPIPE is in the calling thread's `SigBlk` mask.
#[cfg(all(test, target_os = "linux"))]
fn sigpipe_blocked() -> bool {
let path = "/proc/thread-self/status";
let status = std::fs::read_to_string(path).unwrap();
let mask = status
.lines()
.find_map(|l| l.strip_prefix("SigBlk:"))
.unwrap();
let mask = u64::from_str_radix(mask.trim(), 16).unwrap();
(mask & (1u64 << (libc::SIGPIPE - 1))) != 0
}

/// Asserts that a worker and a blocking-pool thread of `handle` block SIGPIPE.
#[cfg(all(test, target_os = "linux"))]
pub(crate) fn assert_runtime_threads_block_sigpipe(handle: &tokio::runtime::Handle) {
assert!(!sigpipe_blocked(), "caller already blocks SIGPIPE");
let worker = handle.spawn(async { sigpipe_blocked() });
let blocking = handle.spawn_blocking(sigpipe_blocked);
let on_worker = futures::executor::block_on(worker).unwrap();
let on_blocking = futures::executor::block_on(blocking).unwrap();
assert!(on_worker, "runtime worker must block SIGPIPE");
assert!(on_blocking, "blocking-pool thread must block SIGPIPE");
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
Loading