Repository navigation
Conversation
|
@estcarisimo , could you please take a look at this PR? I would appreciate your feedback. |
| @@ -0,0 +1,49 @@ | |||
| // quiche/src/clock.rs | |||
There was a problem hiding this comment.
| SIM_MODE.store(true, Ordering::Release); | ||
| // Force epoch initialization now, so epoch() is stable from here on. | ||
| let _ = epoch(); | ||
| SIM_OFFSET_US.store(time_us, Ordering::Release); |
There was a problem hiding this comment.
The quiche implementation requires that time moves forward monotonically. I think you should ensure that time_us provided is >= SIM_OFFSET_US via a compare and swap.
| SIM_OFFSET_US.store(time_us, Ordering::Release); | ||
| } | ||
|
|
||
| /// Reverts to the real OS clock (mainly useful for tests). |
There was a problem hiding this comment.
This API seems difficult to implement correctly given the requirement imposed by quiche that time doesn't move backwards. I would consider removing this in favor of comments stating that once you enter simulated clock mode, there is no going back to regular clock. And strongly encourage the first call to enable the simulated clock happen before creation of the quiche connection.
estcarisimo
left a comment
There was a problem hiding this comment.
Thanks, Aalima and team, for opening this, and for the clear write-up in SIMULATED_TIME.md. Simulated time would make quiche much easier to use with ns-3.
Antonio's comments come first, especially recreating the PR from current master. My comments below are meant to fit with his, and they include code you're welcome to reuse. I tried these changes on top of current master: the new unit tests pass, and clippy is clean on macOS and Linux. CI hasn't run on this PR yet, so some of this would only have shown up there.
Happy to take another look once the PR is updated. Please feel free to ask questions here.
| use std::sync::OnceLock; | ||
| use std::time::{Duration, Instant}; | ||
|
|
||
| static EPOCH: OnceLock<Instant> = OnceLock::new(); |
There was a problem hiding this comment.
Building on Antonio's comments on this file, here is one way to put them together:
- Time can't go backward.
fetch_max()does the compare-and-swap Antonio mentioned in one atomic step, so a smaller value is simply ignored. - No way back to the real clock.
use_real_clock()is gone, and the module docs say simulated time stays on and should be enabled before creating any connection. - Tests that don't interfere with each other. The state lives in a small
Clockstruct with one global instance. Unit tests create their ownClock, so they never change the time seen by other tests thatcargo testruns in parallel. - License header. New files in quiche start with the same BSD license header as the other files (for example,
quiche/src/recovery/bytes_in_flight.rs).
Proposed clock.rs (license header omitted)
//! The clock that quiche uses for every time read.
//!
//! By default this is the system's monotonic clock, `Instant::now()`. An
//! application such as a network simulator can drive time instead by calling
//! [`set_simulated_time_us()`]. Simulated time applies to every connection in
//! the process, and once enabled it can't be turned off. Enable it before
//! creating any connection.
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::sync::OnceLock;
use std::time::Duration;
use std::time::Instant;
/// Process-wide clock state.
static CLOCK: Clock = Clock::new();
/// Returns the current time as quiche should see it.
pub(crate) fn now() -> Instant {
CLOCK.now()
}
/// Enables simulated time, and sets it to `time_us` microseconds since the
/// simulated epoch. The epoch is fixed by the first call.
///
/// quiche requires time to move forward, so a value smaller than the current
/// simulated time is ignored.
#[cfg_attr(not(feature = "ffi"), allow(dead_code))]
pub(crate) fn set_simulated_time_us(time_us: u64) {
CLOCK.set_simulated_time_us(time_us);
}
/// Returns `time` as an offset from the simulated epoch, or `None` when
/// simulated time is not enabled.
// Only the FFI uses this, and only on platforms where it converts times.
#[allow(dead_code)]
pub(crate) fn since_simulated_epoch(time: Instant) -> Option<Duration> {
CLOCK
.simulated_epoch()
.map(|epoch| time.saturating_duration_since(epoch))
}
struct Clock {
epoch: OnceLock<Instant>,
offset_us: AtomicU64,
simulated: AtomicBool,
}
impl Clock {
const fn new() -> Self {
Clock {
epoch: OnceLock::new(),
offset_us: AtomicU64::new(0),
simulated: AtomicBool::new(false),
}
}
fn simulated_epoch(&self) -> Option<Instant> {
// `simulated` is set only after `epoch`, so the epoch is always
// initialized here.
if self.simulated.load(Ordering::Acquire) {
self.epoch.get().copied()
} else {
None
}
}
fn now(&self) -> Instant {
match self.simulated_epoch() {
Some(epoch) =>
epoch +
Duration::from_micros(
self.offset_us.load(Ordering::Acquire),
),
None => Instant::now(),
}
}
fn set_simulated_time_us(&self, time_us: u64) {
self.epoch.get_or_init(Instant::now);
// `fetch_max()` is an atomic compare-and-swap that never lowers the
// stored value, so time can't move backward.
self.offset_us.fetch_max(time_us, Ordering::AcqRel);
self.simulated.store(true, Ordering::Release);
}
}
#[cfg(test)]
mod tests {
use super::*;
// Each test uses its own `Clock`, so tests running in parallel never
// see each other's simulated time.
#[test]
fn real_clock_by_default() {
let clock = Clock::new();
let before = Instant::now();
assert!(clock.now() >= before);
assert_eq!(clock.simulated_epoch(), None);
}
#[test]
fn simulated_time_follows_setter() {
let clock = Clock::new();
clock.set_simulated_time_us(1_000);
let t1 = clock.now();
clock.set_simulated_time_us(26_000);
let t2 = clock.now();
assert_eq!(t2 - t1, Duration::from_millis(25));
let epoch = clock.simulated_epoch().unwrap();
assert_eq!(t2 - epoch, Duration::from_micros(26_000));
}
#[test]
fn simulated_time_never_moves_backward() {
let clock = Clock::new();
clock.set_simulated_time_us(5_000);
let t1 = clock.now();
clock.set_simulated_time_us(1_000);
assert_eq!(clock.now(), t1);
}
}since_simulated_epoch() is for the quiche_send_info.at fix in ffi.rs (see my comment there).
| // Best effort to get Instant::now() and SystemTime::now() as closely | ||
| // together as possible. | ||
| let now = Instant::now(); | ||
| let now = crate::clock::now(); |
There was a problem hiding this comment.
quiche's lib.rs sets #![warn(unused_qualifications)], and CI builds with RUSTFLAGS="-D warnings", so crate::clock::now() here will fail the build once CI runs. Since clock is a module of the crate root, this can be:
let now = clock::now();The same applies to the other calls in lib.rs and to crate::clock::set_simulated_time_us() in ffi.rs. In the other modules, crate::clock::now() is fine.
| /// (quiche_conn_recv, quiche_conn_send, quiche_conn_on_timeout, etc.) | ||
| /// whenever the external simulator's clock has advanced. | ||
| #[no_mangle] | ||
| pub extern "C" fn quiche_set_simulated_time_us(time_us: u64) { |
There was a problem hiding this comment.
One thing that affects ns-3 results: quiche_conn_send() reports the pacing time in quiche_send_info.at, and std_time_to_c() converts it using the real system clock. With simulated time on, at ends up in neither the real timeline nor the ns-3 one. If the ns-3 side ignores at, packets go out without pacing, which matters for BBR.
A small change in std_time_to_c() reports at in the same timeline that quiche_set_simulated_time_us() uses:
#[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "windows")))]
fn std_time_to_c(time: &Instant, out: &mut timespec) {
// With simulated time, report times in the simulator's timeline, the
// same one used by quiche_set_simulated_time_us().
if let Some(since_epoch) = clock::since_simulated_epoch(*time) {
out.tv_sec = since_epoch.as_secs() as libc::time_t;
out.tv_nsec = since_epoch.subsec_nanos() as libc::c_long;
return;
}
// ... existing conversion unchanged ...
}ns-3 can then schedule the send at at as simulation time. On macOS and Windows, std_time_to_c() currently always returns zero, so this only helps on Linux. That limitation is worth a line in SIMULATED_TIME.md. This could also be a follow-up PR if you'd rather keep this one small.
| // Drives quiche's internal clock from an external simulator (e.g. ns-3), | ||
| // instead of the real OS clock. |time_us| is microseconds since this | ||
| // process' simulated epoch. Call this before any quiche API that depends | ||
| // on current time (quiche_conn_recv, quiche_conn_send, | ||
| // quiche_conn_on_timeout, etc.) whenever the simulator's clock advances. | ||
| void quiche_set_simulated_time_us(uint64_t time_us); |
There was a problem hiding this comment.
Suggest documenting the rules a caller needs to follow here:
| // Drives quiche's internal clock from an external simulator (e.g. ns-3), | |
| // instead of the real OS clock. |time_us| is microseconds since this | |
| // process' simulated epoch. Call this before any quiche API that depends | |
| // on current time (quiche_conn_recv, quiche_conn_send, | |
| // quiche_conn_on_timeout, etc.) whenever the simulator's clock advances. | |
| void quiche_set_simulated_time_us(uint64_t time_us); | |
| // Switches quiche to simulated time, driven by an external simulator such as | |
| // ns-3, and sets it to |time_us| microseconds since the simulated epoch. The | |
| // first call fixes the epoch. | |
| // | |
| // Simulated time applies to every connection in the process and can't be | |
| // turned off. Make the first call before creating any connection, then call | |
| // it again whenever the simulator's clock advances, before any quiche API | |
| // that depends on the current time (quiche_conn_recv(), quiche_conn_send(), | |
| // quiche_conn_on_timeout(), and so on). Time must not move backward, so a | |
| // value smaller than the current one is ignored. | |
| void quiche_set_simulated_time_us(uint64_t time_us); |
Optional: ns-3 keeps time in nanoseconds, and at 10 Gb/s a 1500-byte packet takes about 1.2 µs to send. Taking nanoseconds (quiche_set_simulated_time_ns()) would avoid rounding pacing times in fast simulations. It's easy to change now, before anyone depends on the name.
Summary
This PR introduces support for a configurable clock abstraction to QUICHE, allowing its internal clock to be synchronized with an external discrete-event simulator.
Motivation
QUICHE currently relies on Rust's
Instant::now()for internal timing operations. When integrated with discrete-event network simulators such as ns-3, these operations need to use the simulator's notion of time rather than the system's real-time clock.Changes
src/clock.rswith support for real-time and simulated-time modes.set_simulated_time_us()to update the externally supplied simulated time.use_real_clock()to restore real-time clock operation.quiche_set_simulated_time_us()through the C FFI and declare it ininclude/quiche.h.Instant::now()calls in the relevant Rust source files with the new clock abstraction.Testing
cargo build --release --features ffi.quiche_set_simulated_time_ussymbol in the compiled shared library.Related Work
See [QUICHE-Timer] for the implementation details.