Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement minimal (metrics-only) taskdumps. #5466

Closed
wants to merge 2 commits into from
Closed
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
6 changes: 5 additions & 1 deletion examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ edition = "2018"
# If you copy one of the examples into a new project, you should be using
# [dependencies] instead, and delete the **path**.
[dev-dependencies]
tokio = { version = "1.0.0", path = "../tokio", features = ["full", "tracing"] }
tokio = { version = "1.0.0", path = "../tokio", features = ["full", "taskdump", "tracing"] }
tokio-util = { version = "0.7.0", path = "../tokio-util", features = ["full"] }
tokio-stream = { version = "0.1", path = "../tokio-stream" }

Expand Down Expand Up @@ -90,3 +90,7 @@ path = "named-pipe-ready.rs"
[[example]]
name = "named-pipe-multi-client"
path = "named-pipe-multi-client.rs"

[[example]]
name = "taskdump"
path = "taskdump.rs"
59 changes: 59 additions & 0 deletions examples/taskdump.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//! A service that emits task dumps to stdout upon receipt of a SIGUSR1 signal.

#![warn(rust_2018_idioms)]

use tokio::{
time::{sleep, Duration},
runtime::Handle,
signal::unix::{signal, SignalKind}
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let _ = tokio::spawn(async {
// Listen for SIGUSR1
let mut stream = signal(SignalKind::user_defined1()).unwrap();
loop {
// Wait for receipt of SIGUSR1
stream.recv().await;
// Write a JSON taskdump to stdout.
println!("{}", Handle::current());
}
});

let sleep = sleep(Duration::from_secs(20));

tokio::select! {
_ = tokio::spawn(busy::work()) => {}
_ = tokio::spawn(busy::work()) => {}
_ = sleep => {/* exit the application */}
};

Ok(())
}

mod busy {
use futures::future::{BoxFuture, FutureExt};

#[inline(never)]
pub async fn work() {
loop {
for i in 0..u8::MAX {
recurse(i).await;
}
}
}

#[inline(never)]
pub fn recurse(depth: u8) -> BoxFuture<'static, ()> {
async move {
tokio::task::yield_now().await;
if depth == 0 {
return;
} else {
recurse(depth - 1).await;
}
}
.boxed()
}
}
10 changes: 10 additions & 0 deletions tokio/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ signal = [
"windows-sys/Win32_System_Console",
]
sync = []
taskdump = [
"serde",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even allowing that this would be an opt-in feature, adding serde and serde_json seems like a fairly large addition to tokio's dependencies.

"serde_json",
]
test-util = ["rt", "sync", "time"]
time = []

Expand Down Expand Up @@ -115,6 +119,12 @@ socket2 = { version = "0.4.4", optional = true, features = [ "all" ] }
# Requires `--cfg tokio_unstable` to enable.
[target.'cfg(tokio_unstable)'.dependencies]
tracing = { version = "0.1.25", default-features = false, features = ["std"], optional = true } # Not in full
serde = { version = "1.0", optional = true }
serde_json = { version = "1.0", optional = true }

[target.'cfg(tokio_unstable)'.dev-dependencies]
jsonschema = { version = "0.16.1" }
schemars = { version = "0.8.11" }

[target.'cfg(unix)'.dependencies]
libc = { version = "0.2.42", optional = true }
Expand Down
6 changes: 6 additions & 0 deletions tokio/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,12 @@ compile_error!("Tokio's build script has incorrectly detected wasm.");
))]
compile_error!("Only features sync,macros,io-util,rt,time are supported on wasm.");

#[cfg(all(
not(tokio_unstable),
feature = "taskdump"
))]
compile_error!("Feature taskdump requires tokio_unstable.");

// Includes re-exports used by macros.
//
// This module is not intended to be part of the public API. In general, any
Expand Down
19 changes: 19 additions & 0 deletions tokio/src/macros/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,25 @@ macro_rules! cfg_not_rt_multi_thread {
}
}

macro_rules! cfg_taskdump {
($($item:item)*) => {
$(
#[cfg(all(tokio_unstable, feature = "taskdump"))]
#[cfg_attr(docsrs, doc(cfg(tokio_unstable), feature = "taskdump"))]
$item
)*
}
}

macro_rules! cfg_not_taskdump {
($($item:item)*) => {
$(
#[cfg(not(all(tokio_unstable, feature = "taskdump")))]
$item
)*
}
}

macro_rules! cfg_test_util {
($($item:item)*) => {
$(
Expand Down
16 changes: 16 additions & 0 deletions tokio/src/runtime/handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,22 @@ cfg_metrics! {
}
}

cfg_taskdump! {
/// # Task Dumps
///
/// Display-formatting a `Handle` produces a JSON dump of the runtime's internal state.
///
/// This feature is in very early development, and its API and output is subject to change.
impl fmt::Display for Handle {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was already brought up on the feature proposal issue (#5457), but I'll add it here too.

I feel that performing excessive work inside the Display trait violates the consistency principal (principal of least surprise). My opinion (and so it is just that) is that most users would expect adding a Handle to some println!() call to be "harmless", and I don't think serializing the state of the runtime can be classed as such.

fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use serde_json::to_string_pretty;
let serializable = super::taskdump::Runtime::from(&self);
let json = to_string_pretty(&serializable).map_err(|_| fmt::Error)?;
f.write_str(&json)
}
}
}

/// Error returned by `try_current` when no Runtime has been started
#[derive(Debug)]
pub struct TryCurrentError {
Expand Down
4 changes: 4 additions & 0 deletions tokio/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,3 +261,7 @@ cfg_rt! {
/// After thread starts / before thread stops
type Callback = std::sync::Arc<dyn Fn() + Send + Sync>;
}

cfg_taskdump! {
mod taskdump;
}
121 changes: 121 additions & 0 deletions tokio/src/runtime/taskdump.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
//! Serializable structures for task dumps.

use super::scheduler::{self, current_thread};
use crate::loom::sync::Arc;
use serde::Serialize;

#[cfg(all(feature = "rt-multi-thread", not(tokio_wasi)))]
use scheduler::multi_thread;

#[cfg_attr(test, derive(schemars::JsonSchema))]
#[derive(Serialize)]
#[serde(tag = "flavor")]
/// A taskdump of a Tokio runtime.
pub(super) enum Runtime {
/// A taskdump of a current-thread runtime.
CurrentThread(CurrentThread),
/// A taskdump of a multi-thread runtime.
MultiThread(MultiThread),
}

impl Runtime {
pub(super) fn from(handle: &super::Handle) -> Self {
let metrics = handle.metrics();
match &handle.inner {
scheduler::Handle::CurrentThread(h) => {
Runtime::CurrentThread(CurrentThread::from(h.clone(), metrics))
}
#[cfg(all(feature = "rt-multi-thread", not(tokio_wasi)))]
scheduler::Handle::MultiThread(h) => {
Runtime::MultiThread(MultiThread::from(h.clone(), metrics))
}
}
}
}

/// A taskdump of a current-thread runtime.
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[derive(Serialize)]
pub(super) struct CurrentThread {
/// Runtime metrics.
metrics: CurrentThreadMetrics,
}

impl CurrentThread {
fn from(_handle: Arc<current_thread::Handle>, metrics: super::RuntimeMetrics) -> Self {
Self {
metrics: CurrentThreadMetrics {
remote_schedule_count: metrics.remote_schedule_count(),
#[cfg(feature = "net")]
io_driver: Some(IODriverMetrics {
fd_registered_count: metrics.io_driver_fd_registered_count(),
fd_deregistered_count: metrics.io_driver_fd_deregistered_count(),
}),
#[cfg(not(feature = "net"))]
io_driver: None,
},
}
}
}

#[cfg_attr(test, derive(schemars::JsonSchema))]
#[derive(Serialize)]
pub(super) struct MultiThread {
/// Runtime metrics.
metrics: MultiThreadMetrics,
}

impl MultiThread {
pub(super) fn from(_handle: Arc<multi_thread::Handle>, metrics: super::RuntimeMetrics) -> Self {
Self {
metrics: MultiThreadMetrics {
num_workers: metrics.num_workers(),
num_blocking_threads: metrics.num_blocking_threads(),
num_idle_blocking_threads: metrics.num_idle_blocking_threads(),
remote_schedule_count: metrics.remote_schedule_count(),
#[cfg(feature = "net")]
io_driver: Some(IODriverMetrics {
fd_registered_count: metrics.io_driver_fd_registered_count(),
fd_deregistered_count: metrics.io_driver_fd_deregistered_count(),
}),
#[cfg(not(feature = "net"))]
io_driver: None,
},
}
}
}

/// Metrics for a current-thread runtime.
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[derive(Serialize)]
struct CurrentThreadMetrics {
/// The total number of tasks scheduled from outside of the runtime.
remote_schedule_count: u64,
/// IO driver metrics.
io_driver: Option<IODriverMetrics>,
}

/// Metrics for a multi-thread runtime.
#[cfg_attr(test, derive(schemars::JsonSchema))]
#[derive(serde::Serialize)]
struct MultiThreadMetrics {
/// The number of worker threads used by the runtime.
num_workers: usize,
/// The number of additional threads spawned by the runtime.
num_blocking_threads: usize,
/// The number of idle threads, which have spawned for spawn_blocking calls.
num_idle_blocking_threads: usize,
/// The total number of tasks scheduled from outside of the runtime.
remote_schedule_count: u64,
/// IO driver metrics.
io_driver: Option<IODriverMetrics>,
}

#[cfg_attr(test, derive(schemars::JsonSchema))]
#[derive(Serialize)]
struct IODriverMetrics {
/// The number of file descriptors that have been registered with the runtime’s I/O driver.
fd_registered_count: u64,
/// The number of file descriptors that have been deregistered by the runtime’s I/O driver
fd_deregistered_count: u64,
}
4 changes: 4 additions & 0 deletions tokio/src/runtime/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,8 @@ cfg_not_loom! {

#[cfg(miri)]
mod task;

cfg_taskdump! {
mod taskdump;
}
}
2 changes: 1 addition & 1 deletion tokio/src/runtime/tests/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ fn stress1() {
}

cfg_metrics! {
assert_metrics!(metrics, steal_count == n as _);
assert_metrics!(metrics, steal_count == n as u64);
}

n
Expand Down
Loading