Lines
100 %
Functions
50 %
Branches
//! Metrics for circuits.
use std::sync::Arc;
use metrics::Counter;
use tor_error::HasKind as _;
use crate::util::err::ReactorError;
#[cfg(any(feature = "hs-service", feature = "relay"))]
use crate::stream::incoming::IncomingStreamRequest;
/// Length in bytes of a fixed-length cell.
///
// TODO(relay): Take this from the Channel as it knows the link protocol version. For
// now, even the cell codec is hardcoded to this value but it is wrong as the CircID
// length is based on the link proto version.
const CELL_LEN: u64 = 514;
/// Name of the stream requests counter.
const STREAM_REQUESTS_TOTAL: &str = "arti_stream_requests_total";
/// Description of the stream requests counter.
const STREAM_REQUESTS_DESCRIPTION: &str =
"Total number of stream requests received (exit, directory and DNS streams)";
/// The metrics counters of the circuits.
/// This is created once and shared between circuit reactors.
//
// TODO(relay): This is only used for relay circuits. Client circuit (for an actual arti
// client) aren't counted nor the relay client's circuits.
// TODO(relay): When clients will use the shared reactors, we need to make it learn the
// direction of the cell and use it when updating the read/write counters. Reason is that
// the decrypting reactor for the client is actually moving cell backward to the client.
pub(crate) struct CircuitMetrics {
/// Number of circuits opened.
circuit_opened: Counter,
/// Number of circuits closed without an error.
circuit_closed_no_error: Counter,
/// Number of cell bytes read in the forward direction.
circuit_read_bytes_forward: Counter,
/// Number of cell bytes read in the backward direction.
circuit_read_bytes_backward: Counter,
/// Number of cell bytes written in the forward direction.
circuit_written_bytes_forward: Counter,
/// Number of cell bytes written in the backward direction.
circuit_written_bytes_backward: Counter,
/// Number of BEGIN stream requests received.
stream_requests_begin: Counter,
/// Number of BEGIN_DIR stream requests received.
stream_requests_begin_dir: Counter,
/// Number of RESOLVE stream requests received.
stream_requests_resolve: Counter,
}
impl CircuitMetrics {
/// Create a new instance of [`CircuitMetrics`].
pub(crate) fn new() -> Self {
Self {
circuit_opened: metrics::counter!(
description: "Total number of circuits opened",
unit: metrics::Unit::Count,
"arti_circuits_opened_total",
),
circuit_closed_no_error: closed_counter("NoError"),
circuit_read_bytes_forward: metrics::counter!(
description: "Total number of bytes of circuit cells read",
unit: metrics::Unit::Bytes,
"arti_circuit_read_bytes_total",
"direction" => "forward",
circuit_read_bytes_backward: metrics::counter!(
"direction" => "backward",
circuit_written_bytes_forward: metrics::counter!(
description: "Total number of bytes of circuit cells written",
"arti_circuit_written_bytes_total",
circuit_written_bytes_backward: metrics::counter!(
stream_requests_begin: metrics::counter!(
description: STREAM_REQUESTS_DESCRIPTION,
STREAM_REQUESTS_TOTAL,
"type" => "begin",
stream_requests_begin_dir: metrics::counter!(
"type" => "begin_dir",
stream_requests_resolve: metrics::counter!(
"type" => "resolve",
/// Count a circuit that opened.
/// Returns a guard that, when dropped, will count that the circuit closed.
/// You can provide the reason for the closure to [`CircuitCloseGuard::circuit_closed()`].
// This awkwardly requires `Arc<Self>` because how we use it in `Reactor::run_inner()` won't let
// us just borrow `Self`, since borrowing `Self` means that `Reactor` cannot call any of its
// methods that take `&mut Reactor`.
pub(crate) fn circuit_opened(self: &Arc<Self>) -> CircuitCloseGuard {
self.circuit_opened.increment(1);
CircuitCloseGuard::new(Arc::clone(self))
/// Count the bytes of a cell read in the forward direction.
pub(crate) fn forward_cell_read(&self) {
self.circuit_read_bytes_forward.increment(CELL_LEN);
/// Count the bytes of a cell read in the backward direction.
pub(crate) fn backward_cell_read(&self) {
self.circuit_read_bytes_backward.increment(CELL_LEN);
/// Count the bytes of a cell written in the forward direction.
pub(crate) fn forward_cell_written(&self) {
self.circuit_written_bytes_forward.increment(CELL_LEN);
/// Count the bytes of a cell written in the backward direction.
pub(crate) fn backward_cell_written(&self) {
self.circuit_written_bytes_backward.increment(CELL_LEN);
/// Count a stream request by its type.
pub(crate) fn increment_stream_requests(&self, req: &IncomingStreamRequest) {
match req {
IncomingStreamRequest::Begin(_) => self.stream_requests_begin.increment(1),
IncomingStreamRequest::BeginDir(_) => self.stream_requests_begin_dir.increment(1),
IncomingStreamRequest::Resolve(_) => self.stream_requests_resolve.increment(1),
/// Helper: Return the closed circuits counter for the given `reason`.
fn closed_counter(reason: &'static str) -> Counter {
metrics::counter!(
description: "Total number of circuits closed",
"arti_circuits_closed_total",
"reason" => reason,
)
/// A guard returned by [`CircuitMetrics::circuit_opened()`] which ensures that
/// we always increase the "circuit closed" counter
/// (except if used with `std::mem::forget()`).
// It would be much less code if we removed this and just used `DropGuard` at the callsite
// (once it's available in our MSRV).
// This might be worthwhile, depending on how the rest of `CircuitMetrics` evolves.
pub(crate) struct CircuitCloseGuard(Option<Arc<CircuitMetrics>>);
impl CircuitCloseGuard {
/// Create a new [`CircuitCloseGuard`].
fn new(metrics: Arc<CircuitMetrics>) -> Self {
Self(Some(metrics))
/// Record that the circuit has closed.
/// This allows you to pass in the `result` that will be recorded,
/// as opposed to the `Drop` impl which will use "Unknown".
pub(crate) fn circuit_closed(mut self, result: &Result<(), ReactorError>) {
let metrics = self
.0
.take()
.expect("we always construct this guard with Some value");
match result {
Ok(()) | Err(ReactorError::Shutdown) => metrics.circuit_closed_no_error.increment(1),
Err(ReactorError::Err(e)) => {
// Notice here that we lookup the metrics' registry with counter!() macro
// instead of keeping a local copy per-error kind. This is a bit more
// expensive as there is a lookup but it allows us to not keep in sync
// the ErrorKind with the equivalent amount of counters on our side.
// The variant name is used as it is a standard CamelCase that has proper
// semantic and maps nicely to ErrorKind name in the code.
closed_counter(e.kind().into()).increment(1);
impl std::ops::Drop for CircuitCloseGuard {
fn drop(&mut self) {
if let Some(_metrics) = self.0.take() {
closed_counter("Unknown").increment(1);