forked from qdrant/qdrant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.rs
438 lines (406 loc) · 14.1 KB
/
metrics.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use prometheus::proto::{Counter, Gauge, LabelPair, Metric, MetricFamily, MetricType};
use prometheus::TextEncoder;
use segment::common::operation_time_statistics::OperationDurationStatistics;
use crate::common::telemetry::TelemetryData;
use crate::common::telemetry_ops::app_telemetry::{AppBuildTelemetry, AppFeaturesTelemetry};
use crate::common::telemetry_ops::cluster_telemetry::{ClusterStatusTelemetry, ClusterTelemetry};
use crate::common::telemetry_ops::collections_telemetry::{
CollectionTelemetryEnum, CollectionsTelemetry,
};
use crate::common::telemetry_ops::requests_telemetry::{
GrpcTelemetry, RequestsTelemetry, WebApiTelemetry,
};
/// Whitelist for REST endpoints in metrics output.
///
/// Contains selection of search, recommend and upsert endpoints.
///
/// This array *must* be sorted.
const REST_ENDPOINT_WHITELIST: &[&str] = &[
"/collections/{name}/index",
"/collections/{name}/points",
"/collections/{name}/points/discover",
"/collections/{name}/points/discover/batch",
"/collections/{name}/points/payload",
"/collections/{name}/points/query",
"/collections/{name}/points/query/batch",
"/collections/{name}/points/recommend",
"/collections/{name}/points/recommend/batch",
"/collections/{name}/points/search",
"/collections/{name}/points/search/batch",
];
/// Whitelist for GRPC endpoints in metrics output.
///
/// Contains selection of search, recommend and upsert endpoints.
///
/// This array *must* be sorted.
const GRPC_ENDPOINT_WHITELIST: &[&str] = &[
"/qdrant.Points/Discover",
"/qdrant.Points/DiscoverBatch",
"/qdrant.Points/OverwritePayload",
"/qdrant.Points/Query",
"/qdrant.Points/QueryBatch",
"/qdrant.Points/Recommend",
"/qdrant.Points/RecommendBatch",
"/qdrant.Points/Search",
"/qdrant.Points/SearchBatch",
"/qdrant.Points/SetPayload",
"/qdrant.Points/Upsert",
];
/// For REST requests, only report timings when having this HTTP response status.
const REST_TIMINGS_FOR_STATUS: u16 = 200;
/// Encapsulates metrics data in Prometheus format.
pub struct MetricsData {
metrics: Vec<MetricFamily>,
}
impl MetricsData {
pub fn format_metrics(&self) -> String {
TextEncoder::new().encode_to_string(&self.metrics).unwrap()
}
}
impl From<TelemetryData> for MetricsData {
fn from(telemetry_data: TelemetryData) -> Self {
let mut metrics = vec![];
telemetry_data.add_metrics(&mut metrics);
Self { metrics }
}
}
trait MetricsProvider {
/// Add metrics definitions for this.
fn add_metrics(&self, metrics: &mut Vec<MetricFamily>);
}
impl MetricsProvider for TelemetryData {
fn add_metrics(&self, metrics: &mut Vec<MetricFamily>) {
self.app.add_metrics(metrics);
self.collections.add_metrics(metrics);
self.cluster.add_metrics(metrics);
self.requests.add_metrics(metrics);
}
}
impl MetricsProvider for AppBuildTelemetry {
fn add_metrics(&self, metrics: &mut Vec<MetricFamily>) {
metrics.push(metric_family(
"app_info",
"information about qdrant server",
MetricType::COUNTER,
vec![counter(
1.0,
&[("name", &self.name), ("version", &self.version)],
)],
));
self.features.iter().for_each(|f| f.add_metrics(metrics));
}
}
impl MetricsProvider for AppFeaturesTelemetry {
fn add_metrics(&self, metrics: &mut Vec<MetricFamily>) {
metrics.push(metric_family(
"app_status_recovery_mode",
"features enabled in qdrant server",
MetricType::COUNTER,
vec![counter(if self.recovery_mode { 1.0 } else { 0.0 }, &[])],
))
}
}
impl MetricsProvider for CollectionsTelemetry {
fn add_metrics(&self, metrics: &mut Vec<MetricFamily>) {
let vector_count = self
.collections
.iter()
.flatten()
.map(|p| match p {
CollectionTelemetryEnum::Aggregated(a) => a.vectors,
CollectionTelemetryEnum::Full(c) => c.count_vectors(),
})
.sum::<usize>();
metrics.push(metric_family(
"collections_total",
"number of collections",
MetricType::GAUGE,
vec![gauge(self.number_of_collections as f64, &[])],
));
metrics.push(metric_family(
"collections_vector_total",
"total number of vectors in all collections",
MetricType::GAUGE,
vec![gauge(vector_count as f64, &[])],
));
}
}
impl MetricsProvider for ClusterTelemetry {
fn add_metrics(&self, metrics: &mut Vec<MetricFamily>) {
let ClusterTelemetry {
enabled,
status,
config: _,
} = self;
metrics.push(metric_family(
"cluster_enabled",
"is cluster support enabled",
MetricType::COUNTER,
vec![counter(if *enabled { 1.0 } else { 0.0 }, &[])],
));
if let Some(ref status) = status {
status.add_metrics(metrics);
}
}
}
impl MetricsProvider for ClusterStatusTelemetry {
fn add_metrics(&self, metrics: &mut Vec<MetricFamily>) {
metrics.push(metric_family(
"cluster_peers_total",
"total number of cluster peers",
MetricType::GAUGE,
vec![gauge(self.number_of_peers as f64, &[])],
));
metrics.push(metric_family(
"cluster_term",
"current cluster term",
MetricType::COUNTER,
vec![counter(self.term as f64, &[])],
));
if let Some(ref peer_id) = self.peer_id.map(|p| p.to_string()) {
metrics.push(metric_family(
"cluster_commit",
"index of last committed (finalized) operation cluster peer is aware of",
MetricType::COUNTER,
vec![counter(self.commit as f64, &[("peer_id", peer_id)])],
));
metrics.push(metric_family(
"cluster_pending_operations_total",
"total number of pending operations for cluster peer",
MetricType::GAUGE,
vec![gauge(self.pending_operations as f64, &[])],
));
metrics.push(metric_family(
"cluster_voter",
"is cluster peer a voter or learner",
MetricType::GAUGE,
vec![gauge(if self.is_voter { 1.0 } else { 0.0 }, &[])],
));
}
}
}
impl MetricsProvider for RequestsTelemetry {
fn add_metrics(&self, metrics: &mut Vec<MetricFamily>) {
self.rest.add_metrics(metrics);
self.grpc.add_metrics(metrics);
}
}
impl MetricsProvider for WebApiTelemetry {
fn add_metrics(&self, metrics: &mut Vec<MetricFamily>) {
let mut builder = OperationDurationMetricsBuilder::default();
for (endpoint, responses) in &self.responses {
let Some((method, endpoint)) = endpoint.split_once(' ') else {
continue;
};
// Endpoint must be whitelisted
if REST_ENDPOINT_WHITELIST.binary_search(&endpoint).is_err() {
continue;
}
for (status, stats) in responses {
builder.add(
stats,
&[
("method", method),
("endpoint", endpoint),
("status", &status.to_string()),
],
*status == REST_TIMINGS_FOR_STATUS,
);
}
}
builder.build("rest", metrics);
}
}
impl MetricsProvider for GrpcTelemetry {
fn add_metrics(&self, metrics: &mut Vec<MetricFamily>) {
let mut builder = OperationDurationMetricsBuilder::default();
for (endpoint, stats) in &self.responses {
// Endpoint must be whitelisted
if GRPC_ENDPOINT_WHITELIST
.binary_search(&endpoint.as_str())
.is_err()
{
continue;
}
builder.add(stats, &[("endpoint", endpoint.as_str())], true);
}
builder.build("grpc", metrics);
}
}
/// A helper struct to build a vector of [`MetricFamily`] out of a collection of
/// [`OperationDurationStatistics`].
#[derive(Default)]
struct OperationDurationMetricsBuilder {
total: Vec<Metric>,
fail_total: Vec<Metric>,
avg_secs: Vec<Metric>,
min_secs: Vec<Metric>,
max_secs: Vec<Metric>,
duration_histogram_secs: Vec<Metric>,
}
impl OperationDurationMetricsBuilder {
/// Add metrics for the provided statistics.
/// If `add_timings` is `false`, only the total and fail_total counters will be added.
pub fn add(
&mut self,
stat: &OperationDurationStatistics,
labels: &[(&str, &str)],
add_timings: bool,
) {
self.total.push(counter(stat.count as f64, labels));
self.fail_total
.push(counter(stat.fail_count as f64, labels));
if !add_timings {
return;
}
self.avg_secs.push(gauge(
stat.avg_duration_micros.unwrap_or(0.0) as f64 / 1_000_000.0,
labels,
));
self.min_secs.push(gauge(
stat.min_duration_micros.unwrap_or(0.0) as f64 / 1_000_000.0,
labels,
));
self.max_secs.push(gauge(
stat.max_duration_micros.unwrap_or(0.0) as f64 / 1_000_000.0,
labels,
));
self.duration_histogram_secs.push(histogram(
stat.count as u64,
stat.total_duration_micros as f64 / 1_000_000.0,
&stat
.duration_micros_histogram
.iter()
.map(|&(b, c)| (b as f64 / 1_000_000.0, c as u64))
.collect::<Vec<_>>(),
labels,
));
}
/// Build metrics and add them to the provided vector.
pub fn build(self, prefix: &str, metrics: &mut Vec<MetricFamily>) {
if !self.total.is_empty() {
metrics.push(metric_family(
&format!("{prefix}_responses_total"),
"total number of responses",
MetricType::COUNTER,
self.total,
));
}
if !self.fail_total.is_empty() {
metrics.push(metric_family(
&format!("{prefix}_responses_fail_total"),
"total number of failed responses",
MetricType::COUNTER,
self.fail_total,
));
}
if !self.avg_secs.is_empty() {
metrics.push(metric_family(
&format!("{prefix}_responses_avg_duration_seconds"),
"average response duration",
MetricType::GAUGE,
self.avg_secs,
));
}
if !self.min_secs.is_empty() {
metrics.push(metric_family(
&format!("{prefix}_responses_min_duration_seconds"),
"minimum response duration",
MetricType::GAUGE,
self.min_secs,
));
}
if !self.max_secs.is_empty() {
metrics.push(metric_family(
&format!("{prefix}_responses_max_duration_seconds"),
"maximum response duration",
MetricType::GAUGE,
self.max_secs,
));
}
if !self.duration_histogram_secs.is_empty() {
metrics.push(metric_family(
&format!("{prefix}_responses_duration_seconds"),
"response duration histogram",
MetricType::HISTOGRAM,
self.duration_histogram_secs,
));
}
}
}
fn metric_family(name: &str, help: &str, r#type: MetricType, metrics: Vec<Metric>) -> MetricFamily {
let mut metric_family = MetricFamily::default();
metric_family.set_name(name.into());
metric_family.set_help(help.into());
metric_family.set_field_type(r#type);
metric_family.set_metric(metrics);
metric_family
}
fn counter(value: f64, labels: &[(&str, &str)]) -> Metric {
let mut metric = Metric::default();
metric.set_label(labels.iter().map(|(n, v)| label_pair(n, v)).collect());
metric.set_counter({
let mut counter = Counter::default();
counter.set_value(value);
counter
});
metric
}
fn gauge(value: f64, labels: &[(&str, &str)]) -> Metric {
let mut metric = Metric::default();
metric.set_label(labels.iter().map(|(n, v)| label_pair(n, v)).collect());
metric.set_gauge({
let mut gauge = Gauge::default();
gauge.set_value(value);
gauge
});
metric
}
fn histogram(
sample_count: u64,
sample_sum: f64,
buckets: &[(f64, u64)],
labels: &[(&str, &str)],
) -> Metric {
let mut metric = Metric::default();
metric.set_label(labels.iter().map(|(n, v)| label_pair(n, v)).collect());
metric.set_histogram({
let mut histogram = prometheus::proto::Histogram::default();
histogram.set_sample_count(sample_count);
histogram.set_sample_sum(sample_sum);
histogram.set_bucket(
buckets
.iter()
.map(|&(upper_bound, cumulative_count)| {
let mut bucket = prometheus::proto::Bucket::default();
bucket.set_cumulative_count(cumulative_count);
bucket.set_upper_bound(upper_bound);
bucket
})
.collect(),
);
histogram
});
metric
}
fn label_pair(name: &str, value: &str) -> LabelPair {
let mut label = LabelPair::default();
label.set_name(name.into());
label.set_value(value.into());
label
}
#[cfg(test)]
mod tests {
#[test]
fn test_endpoint_whitelists_sorted() {
use super::{GRPC_ENDPOINT_WHITELIST, REST_ENDPOINT_WHITELIST};
assert!(
REST_ENDPOINT_WHITELIST.windows(2).all(|n| n[0] <= n[1]),
"REST_ENDPOINT_WHITELIST must be sorted in code to allow binary search"
);
assert!(
GRPC_ENDPOINT_WHITELIST.windows(2).all(|n| n[0] <= n[1]),
"GRPC_ENDPOINT_WHITELIST must be sorted in code to allow binary search"
);
}
}