relay_server/services/
stats.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use std::sync::Arc;

use relay_config::{Config, RelayMode};
#[cfg(feature = "processing")]
use relay_redis::{AsyncRedisClient, RedisPool, RedisPools, Stats};
use relay_statsd::metric;
use relay_system::{Addr, Handle, RuntimeMetrics, Service};
use relay_threading::AsyncPool;
use tokio::time::interval;

use crate::services::processor::EnvelopeProcessorServicePool;
#[cfg(feature = "processing")]
use crate::services::store::StoreServicePool;
use crate::services::upstream::{IsNetworkOutage, UpstreamRelay};
use crate::statsd::{RelayCounters, RelayGauges, RuntimeCounters, RuntimeGauges};

/// Relay Stats Service.
///
/// Service which collects stats periodically and emits them via statsd.
pub struct RelayStats {
    config: Arc<Config>,
    runtime: Handle,
    rt_metrics: RuntimeMetrics,
    upstream_relay: Addr<UpstreamRelay>,
    #[cfg(feature = "processing")]
    redis_pools: Option<RedisPools>,
    processor_pool: EnvelopeProcessorServicePool,
    #[cfg(feature = "processing")]
    store_pool: StoreServicePool,
}

impl RelayStats {
    pub fn new(
        config: Arc<Config>,
        runtime: Handle,
        upstream_relay: Addr<UpstreamRelay>,
        #[cfg(feature = "processing")] redis_pools: Option<RedisPools>,
        processor_pool: EnvelopeProcessorServicePool,
        #[cfg(feature = "processing")] store_pool: StoreServicePool,
    ) -> Self {
        Self {
            config,
            upstream_relay,
            rt_metrics: runtime.metrics(),
            runtime,
            #[cfg(feature = "processing")]
            redis_pools,
            processor_pool,
            #[cfg(feature = "processing")]
            store_pool,
        }
    }

    async fn service_metrics(&self) {
        for (service, metrics) in self.runtime.current_services_metrics().iter() {
            metric!(
                gauge(RelayGauges::ServiceUtilization) = metrics.utilization as u64,
                service = service.name(),
                instance_id = &service.instance_id().to_string(),
            );
        }
    }

    async fn tokio_metrics(&self) {
        metric!(gauge(RuntimeGauges::NumIdleThreads) = self.rt_metrics.num_idle_threads() as u64);
        metric!(gauge(RuntimeGauges::NumAliveTasks) = self.rt_metrics.num_alive_tasks() as u64);
        metric!(
            gauge(RuntimeGauges::BlockingQueueDepth) =
                self.rt_metrics.blocking_queue_depth() as u64
        );
        metric!(
            gauge(RuntimeGauges::NumBlockingThreads) =
                self.rt_metrics.num_blocking_threads() as u64
        );
        metric!(
            gauge(RuntimeGauges::NumIdleBlockingThreads) =
                self.rt_metrics.num_idle_blocking_threads() as u64
        );

        metric!(
            counter(RuntimeCounters::BudgetForcedYieldCount) +=
                self.rt_metrics.budget_forced_yield_count()
        );

        metric!(gauge(RuntimeGauges::NumWorkers) = self.rt_metrics.num_workers() as u64);
        for worker in 0..self.rt_metrics.num_workers() {
            let worker_name = worker.to_string();

            metric!(
                gauge(RuntimeGauges::WorkerLocalQueueDepth) =
                    self.rt_metrics.worker_local_queue_depth(worker) as u64,
                worker = &worker_name,
            );
            metric!(
                gauge(RuntimeGauges::WorkerMeanPollTime) =
                    self.rt_metrics.worker_mean_poll_time(worker).as_secs_f64(),
                worker = &worker_name,
            );

            metric!(
                counter(RuntimeCounters::WorkerLocalScheduleCount) +=
                    self.rt_metrics.worker_local_schedule_count(worker),
                worker = &worker_name,
            );
            metric!(
                counter(RuntimeCounters::WorkerNoopCount) +=
                    self.rt_metrics.worker_noop_count(worker),
                worker = &worker_name,
            );
            metric!(
                counter(RuntimeCounters::WorkerOverflowCount) +=
                    self.rt_metrics.worker_overflow_count(worker),
                worker = &worker_name,
            );
            metric!(
                counter(RuntimeCounters::WorkerParkCount) +=
                    self.rt_metrics.worker_park_count(worker),
                worker = &worker_name,
            );
            metric!(
                counter(RuntimeCounters::WorkerPollCount) +=
                    self.rt_metrics.worker_poll_count(worker),
                worker = &worker_name,
            );
            metric!(
                counter(RuntimeCounters::WorkerStealCount) +=
                    self.rt_metrics.worker_steal_count(worker),
                worker = &worker_name,
            );
            metric!(
                counter(RuntimeCounters::WorkerStealOperations) +=
                    self.rt_metrics.worker_steal_operations(worker),
                worker = &worker_name,
            );
            metric!(
                counter(RuntimeCounters::WorkerTotalBusyDuration) +=
                    self.rt_metrics
                        .worker_total_busy_duration(worker)
                        .as_millis() as u64,
                worker = &worker_name,
            );
        }
    }

    async fn upstream_status(&self) {
        if self.config.relay_mode() == RelayMode::Managed {
            if let Ok(is_outage) = self.upstream_relay.send(IsNetworkOutage).await {
                metric!(gauge(RelayGauges::NetworkOutage) = u64::from(is_outage));
            }
        }
    }

    #[cfg(feature = "processing")]
    fn redis_pool(redis_pool: &RedisPool, name: &str) {
        Self::stats_metrics(redis_pool.stats(), name);
    }

    #[cfg(feature = "processing")]
    fn async_redis_connection(client: &AsyncRedisClient, name: &str) {
        Self::stats_metrics(client.stats(), name);
    }

    #[cfg(feature = "processing")]
    fn stats_metrics(stats: Stats, name: &str) {
        metric!(
            gauge(RelayGauges::RedisPoolConnections) = u64::from(stats.connections),
            pool = name
        );
        metric!(
            gauge(RelayGauges::RedisPoolIdleConnections) = u64::from(stats.idle_connections),
            pool = name
        );
    }

    #[cfg(not(feature = "processing"))]
    async fn redis_pools(&self) {}

    #[cfg(feature = "processing")]
    async fn redis_pools(&self) {
        if let Some(RedisPools {
            project_configs,
            cardinality,
            quotas,
        }) = self.redis_pools.as_ref()
        {
            Self::async_redis_connection(project_configs, "project_configs");
            Self::redis_pool(cardinality, "cardinality");
            Self::redis_pool(quotas, "quotas");
        }
    }

    fn emit_async_pool_metrics<T>(async_pool: &AsyncPool<T>) {
        let metrics = async_pool.metrics();

        metric!(
            gauge(RelayGauges::AsyncPoolQueueSize) = metrics.queue_size(),
            pool = async_pool.name()
        );
        metric!(
            gauge(RelayGauges::AsyncPoolUtilization) = metrics.utilization() as f64,
            pool = async_pool.name()
        );
        metric!(
            counter(RelayCounters::AsyncPoolFinishedTasks) += metrics.finished_tasks(),
            pool = async_pool.name()
        );
    }

    async fn async_pools_metrics(&self) {
        Self::emit_async_pool_metrics(&self.processor_pool);
        #[cfg(feature = "processing")]
        Self::emit_async_pool_metrics(&self.store_pool);
    }
}

impl Service for RelayStats {
    type Interface = ();

    async fn run(self, _rx: relay_system::Receiver<Self::Interface>) {
        let Some(mut ticker) = self.config.metrics_periodic_interval().map(interval) else {
            return;
        };

        loop {
            let _ = tokio::join!(
                self.upstream_status(),
                self.service_metrics(),
                self.tokio_metrics(),
                self.redis_pools(),
                self.async_pools_metrics()
            );
            ticker.tick().await;
        }
    }
}