1
//! Metrics for circuits.
2

            
3
use std::sync::Arc;
4

            
5
use metrics::Counter;
6
use tor_error::HasKind as _;
7

            
8
use crate::util::err::ReactorError;
9

            
10
#[cfg(any(feature = "hs-service", feature = "relay"))]
11
use crate::stream::incoming::IncomingStreamRequest;
12

            
13
/// Length in bytes of a fixed-length cell.
14
///
15
// TODO(relay): Take this from the Channel as it knows the link protocol version. For
16
// now, even the cell codec is hardcoded to this value but it is wrong as the CircID
17
// length is based on the link proto version.
18
const CELL_LEN: u64 = 514;
19

            
20
/// Name of the stream requests counter.
21
const STREAM_REQUESTS_TOTAL: &str = "arti_stream_requests_total";
22

            
23
/// Description of the stream requests counter.
24
const STREAM_REQUESTS_DESCRIPTION: &str =
25
    "Total number of stream requests received (exit, directory and DNS streams)";
26

            
27
/// The metrics counters of the circuits.
28
///
29
/// This is created once and shared between circuit reactors.
30
//
31
// TODO(relay): This is only used for relay circuits. Client circuit (for an actual arti
32
// client) aren't counted nor the relay client's circuits.
33
//
34
// TODO(relay): When clients will use the shared reactors, we need to make it learn the
35
// direction of the cell and use it when updating the read/write counters. Reason is that
36
// the decrypting reactor for the client is actually moving cell backward to the client.
37
pub(crate) struct CircuitMetrics {
38
    /// Number of circuits opened.
39
    circuit_opened: Counter,
40
    /// Number of circuits closed without an error.
41
    circuit_closed_no_error: Counter,
42
    /// Number of cell bytes read in the forward direction.
43
    circuit_read_bytes_forward: Counter,
44
    /// Number of cell bytes read in the backward direction.
45
    circuit_read_bytes_backward: Counter,
46
    /// Number of cell bytes written in the forward direction.
47
    circuit_written_bytes_forward: Counter,
48
    /// Number of cell bytes written in the backward direction.
49
    circuit_written_bytes_backward: Counter,
50
    /// Number of BEGIN stream requests received.
51
    stream_requests_begin: Counter,
52
    /// Number of BEGIN_DIR stream requests received.
53
    stream_requests_begin_dir: Counter,
54
    /// Number of RESOLVE stream requests received.
55
    stream_requests_resolve: Counter,
56
}
57

            
58
impl CircuitMetrics {
59
    /// Create a new instance of [`CircuitMetrics`].
60
67
    pub(crate) fn new() -> Self {
61
67
        Self {
62
67
            circuit_opened: metrics::counter!(
63
67
                description: "Total number of circuits opened",
64
67
                unit: metrics::Unit::Count,
65
67
                "arti_circuits_opened_total",
66
67
            ),
67
67
            circuit_closed_no_error: closed_counter("NoError"),
68
67
            circuit_read_bytes_forward: metrics::counter!(
69
67
                description: "Total number of bytes of circuit cells read",
70
67
                unit: metrics::Unit::Bytes,
71
67
                "arti_circuit_read_bytes_total",
72
67
                "direction" => "forward",
73
67
            ),
74
67
            circuit_read_bytes_backward: metrics::counter!(
75
67
                description: "Total number of bytes of circuit cells read",
76
67
                unit: metrics::Unit::Bytes,
77
67
                "arti_circuit_read_bytes_total",
78
67
                "direction" => "backward",
79
67
            ),
80
67
            circuit_written_bytes_forward: metrics::counter!(
81
67
                description: "Total number of bytes of circuit cells written",
82
67
                unit: metrics::Unit::Bytes,
83
67
                "arti_circuit_written_bytes_total",
84
67
                "direction" => "forward",
85
67
            ),
86
67
            circuit_written_bytes_backward: metrics::counter!(
87
67
                description: "Total number of bytes of circuit cells written",
88
67
                unit: metrics::Unit::Bytes,
89
67
                "arti_circuit_written_bytes_total",
90
67
                "direction" => "backward",
91
67
            ),
92
67
            stream_requests_begin: metrics::counter!(
93
67
                description: STREAM_REQUESTS_DESCRIPTION,
94
67
                unit: metrics::Unit::Count,
95
67
                STREAM_REQUESTS_TOTAL,
96
67
                "type" => "begin",
97
67
            ),
98
67
            stream_requests_begin_dir: metrics::counter!(
99
67
                description: STREAM_REQUESTS_DESCRIPTION,
100
67
                unit: metrics::Unit::Count,
101
67
                STREAM_REQUESTS_TOTAL,
102
67
                "type" => "begin_dir",
103
67
            ),
104
67
            stream_requests_resolve: metrics::counter!(
105
67
                description: STREAM_REQUESTS_DESCRIPTION,
106
67
                unit: metrics::Unit::Count,
107
67
                STREAM_REQUESTS_TOTAL,
108
67
                "type" => "resolve",
109
67
            ),
110
67
        }
111
67
    }
112

            
113
    /// Count a circuit that opened.
114
    ///
115
    /// Returns a guard that, when dropped, will count that the circuit closed.
116
    /// You can provide the reason for the closure to [`CircuitCloseGuard::circuit_closed()`].
117
    //
118
    // This awkwardly requires `Arc<Self>` because how we use it in `Reactor::run_inner()` won't let
119
    // us just borrow `Self`, since borrowing `Self` means that `Reactor` cannot call any of its
120
    // methods that take `&mut Reactor`.
121
32
    pub(crate) fn circuit_opened(self: &Arc<Self>) -> CircuitCloseGuard {
122
32
        self.circuit_opened.increment(1);
123
32
        CircuitCloseGuard::new(Arc::clone(self))
124
32
    }
125

            
126
    /// Count the bytes of a cell read in the forward direction.
127
39
    pub(crate) fn forward_cell_read(&self) {
128
39
        self.circuit_read_bytes_forward.increment(CELL_LEN);
129
39
    }
130

            
131
    /// Count the bytes of a cell read in the backward direction.
132
2
    pub(crate) fn backward_cell_read(&self) {
133
2
        self.circuit_read_bytes_backward.increment(CELL_LEN);
134
2
    }
135

            
136
    /// Count the bytes of a cell written in the forward direction.
137
4
    pub(crate) fn forward_cell_written(&self) {
138
4
        self.circuit_written_bytes_forward.increment(CELL_LEN);
139
4
    }
140

            
141
    /// Count the bytes of a cell written in the backward direction.
142
12
    pub(crate) fn backward_cell_written(&self) {
143
12
        self.circuit_written_bytes_backward.increment(CELL_LEN);
144
12
    }
145

            
146
    /// Count a stream request by its type.
147
    #[cfg(any(feature = "hs-service", feature = "relay"))]
148
8
    pub(crate) fn increment_stream_requests(&self, req: &IncomingStreamRequest) {
149
8
        match req {
150
4
            IncomingStreamRequest::Begin(_) => self.stream_requests_begin.increment(1),
151
2
            IncomingStreamRequest::BeginDir(_) => self.stream_requests_begin_dir.increment(1),
152
2
            IncomingStreamRequest::Resolve(_) => self.stream_requests_resolve.increment(1),
153
        }
154
8
    }
155
}
156

            
157
/// Helper: Return the closed circuits counter for the given `reason`.
158
82
fn closed_counter(reason: &'static str) -> Counter {
159
82
    metrics::counter!(
160
        description: "Total number of circuits closed",
161
        unit: metrics::Unit::Count,
162
82
        "arti_circuits_closed_total",
163
82
        "reason" => reason,
164
    )
165
82
}
166

            
167
/// A guard returned by [`CircuitMetrics::circuit_opened()`] which ensures that
168
/// we always increase the "circuit closed" counter
169
/// (except if used with `std::mem::forget()`).
170
//
171
// It would be much less code if we removed this and just used `DropGuard` at the callsite
172
// (once it's available in our MSRV).
173
// This might be worthwhile, depending on how the rest of `CircuitMetrics` evolves.
174
pub(crate) struct CircuitCloseGuard(Option<Arc<CircuitMetrics>>);
175

            
176
impl CircuitCloseGuard {
177
    /// Create a new [`CircuitCloseGuard`].
178
32
    fn new(metrics: Arc<CircuitMetrics>) -> Self {
179
32
        Self(Some(metrics))
180
32
    }
181

            
182
    /// Record that the circuit has closed.
183
    ///
184
    /// This allows you to pass in the `result` that will be recorded,
185
    /// as opposed to the `Drop` impl which will use "Unknown".
186
27
    pub(crate) fn circuit_closed(mut self, result: &Result<(), ReactorError>) {
187
27
        let metrics = self
188
27
            .0
189
27
            .take()
190
27
            .expect("we always construct this guard with Some value");
191

            
192
27
        match result {
193
17
            Ok(()) | Err(ReactorError::Shutdown) => metrics.circuit_closed_no_error.increment(1),
194
            Err(ReactorError::Err(e)) => {
195
                // Notice here that we lookup the metrics' registry with counter!() macro
196
                // instead of keeping a local copy per-error kind. This is a bit more
197
                // expensive as there is a lookup but it allows us to not keep in sync
198
                // the ErrorKind with the equivalent amount of counters on our side.
199
                //
200
                // The variant name is used as it is a standard CamelCase that has proper
201
                // semantic and maps nicely to ErrorKind name in the code.
202
10
                closed_counter(e.kind().into()).increment(1);
203
            }
204
        }
205
27
    }
206
}
207

            
208
impl std::ops::Drop for CircuitCloseGuard {
209
32
    fn drop(&mut self) {
210
32
        if let Some(_metrics) = self.0.take() {
211
5
            closed_counter("Unknown").increment(1);
212
27
        }
213
32
    }
214
}