-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathPrometheusRequestHandler.cpp
More file actions
854 lines (713 loc) · 34.7 KB
/
Copy pathPrometheusRequestHandler.cpp
File metadata and controls
854 lines (713 loc) · 34.7 KB
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
#include <Server/PrometheusRequestHandler.h>
#include <IO/HTTPCommon.h>
#include <IO/ReadBuffer.h>
#include <Server/HTTP/WriteBufferFromHTTPServerResponse.h>
#include <Server/HTTP/sendExceptionToHTTPClient.h>
#include <Server/HTTPHandler.h>
#include <Server/IServer.h>
#include <Server/PrometheusMetricsWriter.h>
#include <base/scope_guard.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/URI.h>
#include <Common/logger_useful.h>
#include <Common/maskSensitiveQueryParameters.h>
#include <Common/setThreadName.h>
#include "config.h"
#include <Access/Credentials.h>
#include <Common/CurrentThread.h>
#include <Common/StringUtils.h>
#include <Common/QueryScope.h>
#include <IO/SnappyBasicReadBuffer.h>
#include <IO/SnappyBasicWriteBuffer.h>
#include <IO/ZstdInflatingReadBuffer.h>
#include <IO/Protobuf/ProtobufZeroCopyInputStreamFromReadBuffer.h>
#include <IO/Protobuf/ProtobufZeroCopyOutputStreamFromWriteBuffer.h>
#include <Interpreters/Context.h>
#include <Interpreters/DatabaseCatalog.h>
#include <Interpreters/Session.h>
#include <Server/HTTP/HTMLForm.h>
#include <Server/HTTP/authenticateUserByHTTP.h>
#include <Server/HTTP/checkHTTPHeader.h>
#include <Server/HTTP/setReadOnlyIfHTTPMethodIdempotent.h>
#include <IO/WriteBufferFromString.h>
#include <IO/WriteHelpers.h>
#include <Core/Settings.h>
#include <Parsers/Prometheus/PrometheusQueryTree.h>
#include <Storages/TimeSeries/PrometheusRemoteReadProtocol.h>
#include <Storages/TimeSeries/PrometheusRemoteWriteProtocol.h>
#include <Storages/TimeSeries/PrometheusHTTPProtocolAPI.h>
namespace DB
{
namespace Setting
{
extern const SettingsUInt64 http_response_buffer_size;
}
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
extern const int CANNOT_WRITE_TO_OSTREAM;
extern const int INCOMPATIBLE_SCHEMA;
extern const int SUPPORT_IS_DISABLED;
extern const int NOT_IMPLEMENTED;
extern const int UNSUPPORTED_MEDIA_TYPE;
}
/// Base implementation of a prometheus protocol.
class PrometheusRequestHandler::Impl
{
public:
explicit Impl(PrometheusRequestHandler & parent) : parent_ref(parent) {}
virtual ~Impl() = default;
virtual void beforeHandlingRequest(HTTPServerRequest & /* request */) {}
virtual bool isSettingLikeParameter(const String & /* name */) { return false; }
virtual void handleRequest(HTTPServerRequest & request, HTTPServerResponse & response) = 0;
virtual void onException() {}
protected:
PrometheusRequestHandler & parent() { return parent_ref; }
IServer & server() { return parent().server; }
const PrometheusRequestHandlerConfig & config() { return parent().config; }
PrometheusMetricsWriter & metrics_writer() { return *parent().metrics_writer; }
LoggerPtr log() { return parent().log; }
WriteBuffer & getOutputStream(HTTPServerResponse & response) { return parent().getOutputStream(response); }
private:
PrometheusRequestHandler & parent_ref;
};
/// Implementation of the exposing metrics protocol.
class PrometheusRequestHandler::MetricsImpl : public Impl
{
public:
explicit MetricsImpl(PrometheusRequestHandler & parent) : Impl(parent) {}
void beforeHandlingRequest(HTTPServerRequest & request) override
{
LOG_INFO(log(), "Handling metrics request from {}", request.get("User-Agent"));
chassert(config().type == PrometheusRequestHandlerConfig::Type::Metrics);
}
void handleRequest(HTTPServerRequest & /* request */, HTTPServerResponse & response) override
{
response.setContentType("text/plain; version=0.0.4; charset=UTF-8");
auto & out = getOutputStream(response);
if (config().expose_info)
metrics_writer().writeInfo(out);
if (config().expose_events)
metrics_writer().writeEvents(out);
if (config().expose_metrics)
metrics_writer().writeMetrics(out);
if (config().expose_asynchronous_metrics)
metrics_writer().writeAsynchronousMetrics(out, parent().async_metrics);
if (config().expose_errors)
metrics_writer().writeErrors(out);
if (config().expose_histograms)
metrics_writer().writeHistogramMetrics(out);
if (config().expose_dimensional_metrics)
metrics_writer().writeDimensionalMetrics(out);
}
};
/// Base implementation of a protocol with Context and authentication.
class PrometheusRequestHandler::ImplWithContext : public Impl
{
public:
explicit ImplWithContext(PrometheusRequestHandler & parent) : Impl(parent), default_settings(server().context()->getSettingsRef()) { }
virtual void handlingRequestWithContext(HTTPServerRequest & request, HTTPServerResponse & response) = 0;
/// When true, `handleRequest` parses `application/x-www-form-urlencoded` (and multipart) bodies for POST/PUT.
/// Must stay false for Write/Read so the raw body stream stays available for protobuf.
virtual bool shouldParseFormFromRequestBody(const HTTPServerRequest & /* request */) const { return false; }
protected:
void handleRequest(HTTPServerRequest & request, HTTPServerResponse & response) override
{
SCOPE_EXIT({
request_credentials.reset();
context.reset();
session.reset();
params.reset();
});
const auto & method = request.getMethod();
if (shouldParseFormFromRequestBody(request)
&& (method == Poco::Net::HTTPRequest::HTTP_POST || method == Poco::Net::HTTPRequest::HTTP_PUT))
params = std::make_unique<HTMLForm>(default_settings, request, *request.getStream());
else
params = std::make_unique<HTMLForm>(default_settings, request);
parent().send_stacktrace = config().is_stacktrace_enabled && params->getParsed<bool>("stacktrace", false);
if (!authenticateUserAndMakeContext(request, response))
return; /// The user is not authenticated yet, and the HTTP_UNAUTHORIZED response is sent with the "WWW-Authenticate" header,
/// and `request_credentials` must be preserved until the next request or until any exception.
/// Apply `http_response_buffer_size` for the output buffer (0 means use the default).
auto buffer_size = context->getSettingsRef()[Setting::http_response_buffer_size].value;
if (buffer_size == 0)
buffer_size = DBMS_DEFAULT_BUFFER_SIZE;
parent().http_response_buffer_size = buffer_size;
/// Initialize query scope.
QueryScope query_scope;
if (context)
query_scope = QueryScope::create(context);
handlingRequestWithContext(request, response);
}
bool authenticateUserAndMakeContext(HTTPServerRequest & request, HTTPServerResponse & response)
{
session = std::make_unique<Session>(server().context(), ClientInfo::Interface::PROMETHEUS, request.isSecure());
if (!authenticateUser(request, response))
return false;
makeContext(request);
return true;
}
bool authenticateUser(HTTPServerRequest & request, HTTPServerResponse & response)
{
return authenticateUserByHTTP(request, *params, response, *session, request_credentials, config().connection_config, server().context(), log());
}
bool isSettingLikeParameter(const String & name) override
{
/// Empty parameter appears when URL like ?&a=b or a=b&&c=d. Just skip them for user's convenience.
if (name.empty())
return false;
/// Some parameters (default_format, everything used in the code above) do not belong to the
/// Settings class.
static const NameSet reserved_param_names{"user", "password", "quota_key", "stacktrace", "role", "query_id", "database", "table"};
return !reserved_param_names.contains(name);
}
void makeContext(HTTPServerRequest & request)
{
context = session->makeQueryContext();
/// Anything else beside HTTP POST should be readonly queries.
setReadOnlyIfHTTPMethodIdempotent(context, request.getMethod());
auto roles = params->getAll("role");
if (!roles.empty())
context->setCurrentRoles(roles);
SettingsChanges settings_changes;
for (const auto & [key, value] : *params)
{
if (isSettingLikeParameter(key))
{
/// This query parameter should be considered as a ClickHouse setting.
settings_changes.push_back({key, value});
}
}
context->checkSettingsConstraints(settings_changes, SettingSource::QUERY);
context->applySettingsChanges(settings_changes);
/// Set the query id supplied by the user, if any, and also update the OpenTelemetry fields.
String query_id = params->get("query_id", request.get("X-ClickHouse-Query-Id", ""));
/// Sanitize query_id: remove ASCII control characters to prevent CRLF injection
/// into HTTP response headers (the query_id is reflected in X-ClickHouse-Query-Id).
std::erase_if(query_id, [](unsigned char c) { return isControlASCII(c) || c == 0x7F; });
context->setCurrentQueryId(query_id);
}
/// Resolves the time series table for the current request. Each of the database and table names comes
/// either from the configuration or from the URL query parameter 'database' and 'table'.
/// A query parameter can't override a value set in the configuration.
/// If the database isn't set, the table name is treated as a possibly-qualified `database.table` name,
/// and if the table name is not a qualified name then the database name falls back to "default".
StorageID getTimeSeriesTableID()
{
QualifiedTableName full_name;
full_name.database = config().time_series_table_name.database;
full_name.table = config().time_series_table_name.table;
if (params->has("database"))
{
if (!full_name.database.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"The database is set in the configuration of this prometheus handler and cannot be overridden by the 'database' query parameter");
full_name.database = params->get("database");
}
if (params->has("table"))
{
if (!full_name.table.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"The table is set in the configuration of this prometheus handler and cannot be overridden by the 'table' query parameter");
full_name.table = params->get("table");
}
if (full_name.table.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"The time series table name is not set; specify it in the configuration or in the 'table' query parameter");
if (full_name.database.empty())
{
full_name = QualifiedTableName::parseFromString(full_name.table);
if (full_name.database.empty())
full_name.database = "default";
}
return StorageID{full_name};
}
void onException() override
{
// So that the next requests on the connection have to always start afresh in case of exceptions.
request_credentials.reset();
}
const Settings & default_settings;
std::unique_ptr<HTMLForm> params;
std::unique_ptr<Session> session;
std::unique_ptr<Credentials> request_credentials;
ContextMutablePtr context;
};
/// Implementation of the remote-write protocol.
class PrometheusRequestHandler::WriteImpl : public ImplWithContext
{
public:
using ImplWithContext::ImplWithContext;
void beforeHandlingRequest(HTTPServerRequest & request) override
{
LOG_INFO(log(), "Handling remote write request from {}", request.get("User-Agent", ""));
chassert(config().type == PrometheusRequestHandlerConfig::Type::Write
|| config().type == PrometheusRequestHandlerConfig::Type::APIv1);
}
void handlingRequestWithContext([[maybe_unused]] HTTPServerRequest & request, [[maybe_unused]] HTTPServerResponse & response) override
{
#if USE_PROMETHEUS_PROTOBUFS
/// Unsupported content types and encodings get 415 Unsupported Media Type.
const String content_type = request.get("Content-Type", "");
if (content_type != "application/x-protobuf")
throw Exception(ErrorCodes::UNSUPPORTED_MEDIA_TYPE,
"HTTP header Content-Type has unsupported value '{}' (must be 'application/x-protobuf')", content_type);
/// The remote-write 1.0 spec mandates snappy, but some senders can also compress with zstd.
const String content_encoding = request.get("Content-Encoding", "");
std::unique_ptr<ReadBuffer> decompressing_buf;
if (content_encoding == "snappy")
decompressing_buf = std::make_unique<SnappyBasicReadBuffer>(wrapReadBufferPointer(request.getStream()));
else if (content_encoding == "zstd")
decompressing_buf = std::make_unique<ZstdInflatingReadBuffer>(wrapReadBufferPointer(request.getStream()));
else
throw Exception(ErrorCodes::UNSUPPORTED_MEDIA_TYPE,
"HTTP header Content-Encoding has unsupported value '{}' (must be 'snappy' or 'zstd')", content_encoding);
auto table = DatabaseCatalog::instance().getTable(getTimeSeriesTableID(), context);
PrometheusRemoteWriteProtocol protocol{table, context};
prometheus::WriteRequest write_request;
{
ProtobufZeroCopyInputStreamFromReadBuffer zero_copy_input_stream{std::move(decompressing_buf)};
if (!write_request.ParsePartialFromZeroCopyStream(&zero_copy_input_stream))
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Cannot parse WriteRequest");
}
protocol.write(write_request.timeseries(), write_request.metadata());
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTPStatus::HTTP_NO_CONTENT, Poco::Net::HTTPResponse::HTTP_REASON_NO_CONTENT);
response.setChunkedTransferEncoding(false);
#else
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Prometheus remote write protocol is disabled");
#endif
}
};
/// Implementation of the remote-read protocol.
class PrometheusRequestHandler::ReadImpl : public ImplWithContext
{
public:
using ImplWithContext::ImplWithContext;
void beforeHandlingRequest(HTTPServerRequest & request) override
{
LOG_INFO(log(), "Handling remote read request from {}", request.get("User-Agent", ""));
chassert(config().type == PrometheusRequestHandlerConfig::Type::Read
|| config().type == PrometheusRequestHandlerConfig::Type::APIv1);
}
void handlingRequestWithContext([[maybe_unused]] HTTPServerRequest & request, [[maybe_unused]] HTTPServerResponse & response) override
{
#if USE_PROMETHEUS_PROTOBUFS
checkHTTPHeader(request, "Content-Type", "application/x-protobuf");
checkHTTPHeader(request, "Content-Encoding", "snappy");
auto table = DatabaseCatalog::instance().getTable(getTimeSeriesTableID(), context);
PrometheusRemoteReadProtocol protocol{table, context};
prometheus::ReadRequest read_request;
{
ProtobufZeroCopyInputStreamFromReadBuffer zero_copy_input_stream{
std::make_unique<SnappyBasicReadBuffer>(wrapReadBufferPointer(request.getStream()))};
if (!read_request.ParseFromZeroCopyStream(&zero_copy_input_stream))
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Cannot parse ReadRequest");
}
/// Prometheus remote-read uses raw snappy block compression (not the snappy framing format
/// used by `SnappyFramedWriteBuffer` for HTTP `Content-Encoding`). Serialize the response
/// straight into the compression buffer, then drop the `prometheus::ReadResponse` object
/// tree before finalizing `SnappyBasicWriteBuffer`, so only the accumulated serialized data
/// (not the object tree) is held while it is compressed into a single raw snappy block.
response.setContentType("application/x-protobuf");
response.set("Content-Encoding", "snappy");
auto & out = getOutputStream(response);
SnappyBasicWriteBuffer snappy_out(&out);
{
prometheus::ReadResponse read_response;
size_t num_queries = read_request.queries_size();
for (size_t i = 0; i != num_queries; ++i)
{
const auto & query = read_request.queries(static_cast<int>(i));
auto & new_query_result = *read_response.add_results();
protocol.readTimeSeries(
*new_query_result.mutable_timeseries(),
query.start_timestamp_ms(),
query.end_timestamp_ms(),
query.matchers(),
query.hints());
}
# if 0
LOG_DEBUG(log, "ReadResponse = {}", read_response.DebugString());
# endif
/// The zero-copy stream is intentionally not finalized here: finalizing it would flush
/// and compress `snappy_out` while the object tree is still alive. Serialization leaves
/// all bytes buffered in `snappy_out`; compression happens in `snappy_out.finalize()`
/// below, after the object tree has been released.
ProtobufZeroCopyOutputStreamFromWriteBuffer zero_copy_output_stream{snappy_out};
if (!read_response.SerializeToZeroCopyStream(&zero_copy_output_stream))
throw Exception(ErrorCodes::CANNOT_WRITE_TO_OSTREAM, "Failed to serialize the Prometheus ReadResponse");
}
snappy_out.finalize();
#else
throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Prometheus remote read protocol is disabled");
#endif
}
};
/// Handles the read-only query and metadata endpoints of the Prometheus HTTP API
/// (/api/v1/query, /api/v1/query_range, /api/v1/series, /api/v1/labels, /api/v1/label/<name>/values, /api/v1/metadata).
class PrometheusRequestHandler::QueryImpl : public ImplWithContext
{
public:
using ImplWithContext::ImplWithContext;
bool shouldParseFormFromRequestBody(const HTTPServerRequest & /* request */) const override { return true; }
void beforeHandlingRequest(HTTPServerRequest & request) override
{
LOG_INFO(log(), "Handling Prometheus HTTP API query request from {}", request.get("User-Agent", ""));
chassert(config().type == PrometheusRequestHandlerConfig::Type::Query
|| config().type == PrometheusRequestHandlerConfig::Type::APIv1);
}
bool isSettingLikeParameter(const String & name) override
{
/// Empty parameter appears when URL like ?&a=b or a=b&&c=d. Just skip them for user's convenience.
if (name.empty())
return false;
/// Some parameters (default_format, everything used in the code above) do not belong to the
/// Settings class. `limit` is defined by Prometheus on these endpoints, so it must not fall through to the ClickHouse setting.
static const NameSet reserved_param_names{"user", "password", "query", "time", "start", "end", "step", "match[]", "limit", "limit_per_metric", "metric", "lookback_delta", "database", "table"};
return !reserved_param_names.contains(name);
}
/// Parses the optional `limit` parameter of the metadata endpoints: the maximum number of returned items,
/// with 0 (the default) meaning no limit.
UInt64 getLimitParam() const
{
String limit_param = params->get("limit", "");
if (limit_param.empty())
return 0;
Int64 parsed_limit = 0;
if (!tryParse(parsed_limit, limit_param.data(), limit_param.size()) || (parsed_limit < 0))
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Invalid value of the 'limit' parameter: '{}', expected a non-negative integer",
limit_param);
return static_cast<UInt64>(parsed_limit);
}
void handlingRequestWithContext(HTTPServerRequest & request, HTTPServerResponse & response) override
{
const String & uri = request.getURI();
/// This endpoint accepts user/password (and other secrets) as query-string parameters via
/// authenticateUserByHTTP, so the URI must be masked before it reaches the logs.
LOG_DEBUG(log(), "Processing Prometheus HTTP API query request: method={}, uri={}", request.getMethod(), maskSensitiveQueryParametersInURI(uri));
response.setContentType("application/json");
try
{
/// Dispatch by the trailing path segment only (e.g. "/query_range", "/query"), so the same
/// endpoint works both bare ("/api/v1/query") and behind a configured prefix ("/prefix/api/v1/query").
/// Use the decoded path without the query string (matching APIv1Impl::getImpl) so a
/// percent-encoded label name in ".../label/<name>/values" is read correctly.
const String uri_path = Poco::URI(uri).getPath();
if (uri_path.ends_with("/format_query"))
{
/// The format_query endpoint only parses and reformats the given PromQL expression,
/// so it doesn't need the TimeSeries table.
formatQuery(getOutputStream(response), params->get("query", ""));
return;
}
auto table = DatabaseCatalog::instance().getTable(getTimeSeriesTableID(), context);
PrometheusHTTPProtocolAPI protocol{table, context};
auto query_finish_callback = [&]()
{
getOutputStream(response).finalize();
};
if (uri_path.ends_with("/query_range"))
{
String query = params->get("query", "");
String start = params->get("start", "");
String end = params->get("end", "");
String step = params->get("step", "");
String lookback_delta = params->get("lookback_delta", "");
/// TODO: Support the following **optional** query parameters:
/// - timeout=<duration>: Evaluation timeout
/// - limit=<number>: Maximum number of returned series
PrometheusHTTPProtocolAPI::Params params
{
.type = PrometheusHTTPProtocolAPI::Type::Range,
.promql_query = query,
.time_param = "",
.start_param = start,
.end_param = end,
.step_param = step,
.lookback_delta_param = lookback_delta,
};
protocol.executePromQLQuery(getOutputStream(response), params, query_finish_callback);
}
else if (uri_path.ends_with("/query"))
{
String query = params->get("query", "");
String time = params->get("time", "");
String lookback_delta = params->get("lookback_delta", "");
/// TODO: Support optional parameters same as for the range query.
PrometheusHTTPProtocolAPI::Params params
{
.type = PrometheusHTTPProtocolAPI::Type::Instant,
.promql_query = query,
.time_param = time,
.start_param = "",
.end_param = "",
.step_param = "",
.lookback_delta_param = lookback_delta,
};
protocol.executePromQLQuery(getOutputStream(response), params, query_finish_callback);
}
else if (uri_path.ends_with("/parse_query"))
{
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "The parse_query endpoint is not implemented");
}
else if (uri_path.ends_with("/series"))
{
Strings match = params->getAll("match[]");
String start = params->get("start", "");
String end = params->get("end", "");
UInt64 limit = getLimitParam();
protocol.getSeries(getOutputStream(response), match, start, end, limit, query_finish_callback);
}
else if (uri_path.ends_with("/metadata"))
{
String metric = params->get("metric", "");
/// Both limit parameters are optional; negative values are accepted and mean "no limit", like in Prometheus.
Int64 limit = getMetadataLimitParam("limit");
Int64 limit_per_metric = getMetadataLimitParam("limit_per_metric");
protocol.getMetadata(getOutputStream(response), metric, limit, limit_per_metric, query_finish_callback);
}
else if (uri_path.ends_with("/labels"))
{
Strings match = params->getAll("match[]");
String start = params->get("start", "");
String end = params->get("end", "");
UInt64 limit = getLimitParam();
protocol.getLabels(getOutputStream(response), match, start, end, limit, query_finish_callback);
}
else if (auto label_name = extractLabelValuesName(uri_path))
{
Strings match = params->getAll("match[]");
String start = params->get("start", "");
String end = params->get("end", "");
UInt64 limit = getLimitParam();
protocol.getLabelValues(getOutputStream(response), *label_name, match, start, end, limit, query_finish_callback);
}
else
{
LOG_ERROR(log(), "No matching endpoint found for URI: {}, method: {}", maskSensitiveQueryParametersInURI(uri), request.getMethod());
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND);
writeString(R"({"status":"error","errorType":"not_found","error":"API endpoint not found"})", getOutputStream(response));
}
}
catch (const Exception & e)
{
/// Once the response header has been sent we can no longer produce
/// a well-formed Prometheus error response. So we let the outer handler
/// abort the chunked stream via cancelWithException() instead.
if (response.sent())
throw;
/// Drop any partial success body still sitting in the output buffer
/// before writing the error response.
getOutputStream(response).rejectBufferedDataSave();
/// A schema-version rejection (see TimeSeriesVersion.h) is a problem with the server or the table,
/// not with the query: report it as an internal error so that clients don't attribute it
/// to the PromQL expression.
bool server_side_error = (e.code() == ErrorCodes::INCOMPATIBLE_SCHEMA);
response.setStatusAndReason(
server_side_error ? Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR : Poco::Net::HTTPResponse::HTTP_BAD_REQUEST);
String error_str;
WriteBufferFromString error_buf(error_str);
writeString(server_side_error ? R"({"status":"error","errorType":"internal","error":)"
: R"({"status":"error","errorType":"bad_data","error":)", error_buf);
writeJSONString(e.message(), error_buf, FormatSettings{});
writeString("}", error_buf);
error_buf.finalize();
writeString(error_str, getOutputStream(response));
LOG_ERROR(log(), "Error executing query: {}", e.displayText());
}
}
private:
/// Handles the format_query endpoint: parses the PromQL expression given in the 'query' parameter
/// and writes it back serialized from the parsed tree, i.e. with the whitespace normalized,
/// the comments removed, and the redundant parentheses dropped.
static void formatQuery(WriteBuffer & out, const String & query)
{
PrometheusQueryTree promql_tree;
promql_tree.parse(query);
writeString(R"({"status":"success","data":)", out);
writeJSONString(promql_tree.toString(), out, FormatSettings{});
writeChar('}', out);
}
/// Parses an optional integer parameter of the metadata endpoint; an absent parameter defaults to -1 (no limit).
Int64 getMetadataLimitParam(const String & name) const
{
String value = params->get(name, "");
if (value.empty())
return -1;
Int64 result = 0;
if (!tryParse(result, value.data(), value.size()))
throw Exception(ErrorCodes::BAD_ARGUMENTS,
"Invalid value of the '{}' parameter: '{}', expected an integer", name, value);
return result;
}
/// Extracts the label name from a label-values endpoint path ".../label/<name>/values".
/// Returns std::nullopt when `uri_path` isn't a valid label-values endpoint.
static std::optional<String> extractLabelValuesName(std::string_view uri_path)
{
static constexpr std::string_view values_suffix = "/values";
static constexpr std::string_view label_segment = "/label";
if (!uri_path.ends_with(values_suffix))
return std::nullopt;
/// Strip the "/values" suffix, leaving "<prefix>/label/<name>".
std::string_view without_values = uri_path.substr(0, uri_path.size() - values_suffix.size());
/// A label name never contains '/', so it is the last path segment.
size_t name_slash = without_values.rfind('/');
if (name_slash == std::string_view::npos)
return std::nullopt;
std::string_view label_name = without_values.substr(name_slash + 1);
if (label_name.empty())
return std::nullopt;
/// The segment before the name must be "/label".
if (!without_values.substr(0, name_slash).ends_with(label_segment))
return std::nullopt;
return String{label_name};
}
};
/// Handles all Prometheus "/api/v1" protocols, dispatching each request to the
/// Write, Read, or Query implementation based on its path.
class PrometheusRequestHandler::APIv1Impl : public Impl
{
public:
explicit APIv1Impl(PrometheusRequestHandler & parent)
: Impl(parent)
, write_impl(parent)
, read_impl(parent)
, query_impl(parent)
{
}
void beforeHandlingRequest(HTTPServerRequest & request) override
{
chassert(config().type == PrometheusRequestHandlerConfig::Type::APIv1);
current_impl = &getImpl(request);
current_impl->beforeHandlingRequest(request);
}
void handleRequest(HTTPServerRequest & request, HTTPServerResponse & response) override
{
/// `current_impl` was selected in beforeHandlingRequest().
/// Forward the whole request to it so its own authentication, context setup,
/// and endpoint dispatch run exactly as for a dedicated single-protocol handler.
current_impl->handleRequest(request, response);
}
void onException() override
{
if (current_impl)
current_impl->onException();
}
private:
/// Selects the implementation for a request based on the trailing segment of its path,
/// so the same endpoint works both bare ("/api/v1/write") and behind a configured prefix
/// ("/prefix/api/v1/write").
Impl & getImpl(const HTTPServerRequest & request)
{
/// Get the decoded URL path (without the query string).
const String path = Poco::URI(request.getURI()).getPath();
if (path.ends_with("/write"))
return write_impl;
if (path.ends_with("/read"))
return read_impl;
/// All other /api/v1/* endpoints (query, query_range, series, labels, label/<name>/values, metadata)
/// are served by the Query implementation, which itself returns 404 for unknown paths.
return query_impl;
}
WriteImpl write_impl;
ReadImpl read_impl;
QueryImpl query_impl;
Impl * current_impl = nullptr;
};
PrometheusRequestHandler::PrometheusRequestHandler(
IServer & server_,
const PrometheusRequestHandlerConfig & config_,
const AsynchronousMetrics & async_metrics_,
std::shared_ptr<PrometheusMetricsWriter> metrics_writer_,
std::unordered_map<String, String> response_headers_)
: server(server_)
, config(config_)
, async_metrics(async_metrics_)
, metrics_writer(metrics_writer_)
, log(getLogger("PrometheusRequestHandler"))
{
response_headers = response_headers_;
createImpl();
}
PrometheusRequestHandler::~PrometheusRequestHandler() = default;
void PrometheusRequestHandler::createImpl()
{
switch (config.type)
{
case PrometheusRequestHandlerConfig::Type::Metrics:
{
impl = std::make_unique<MetricsImpl>(*this);
return;
}
case PrometheusRequestHandlerConfig::Type::Write:
{
impl = std::make_unique<WriteImpl>(*this);
return;
}
case PrometheusRequestHandlerConfig::Type::Read:
{
impl = std::make_unique<ReadImpl>(*this);
return;
}
case PrometheusRequestHandlerConfig::Type::Query:
{
impl = std::make_unique<QueryImpl>(*this);
return;
}
case PrometheusRequestHandlerConfig::Type::APIv1:
{
impl = std::make_unique<APIv1Impl>(*this);
return;
}
}
UNREACHABLE();
}
void PrometheusRequestHandler::handleRequest(HTTPServerRequest & request, HTTPServerResponse & response, const ProfileEvents::Event & write_event_)
{
DB::setThreadName(ThreadName::PROMETHEUS_HANDLER);
applyHTTPResponseHeaders(response, response_headers);
try
{
write_event = write_event_;
http_method = request.getMethod();
chassert(!write_buffer_from_response); /// Nothing is written to the response yet.
/// Make keep-alive works.
if (request.getVersion() == HTTPServerRequest::HTTP_1_1)
response.setChunkedTransferEncoding(true);
setResponseDefaultHeaders(response);
impl->beforeHandlingRequest(request);
impl->handleRequest(request, response);
getOutputStream(response).finalize();
}
catch (...)
{
tryLogCurrentException(log);
ExecutionStatus status = ExecutionStatus::fromCurrentException("", send_stacktrace);
getOutputStream(response).cancelWithException(request, status.code, status.message, nullptr);
tryCallOnException();
}
}
WriteBufferFromHTTPServerResponse & PrometheusRequestHandler::getOutputStream(HTTPServerResponse & response)
{
if (write_buffer_from_response)
return *write_buffer_from_response;
write_buffer_from_response = std::make_unique<WriteBufferFromHTTPServerResponse>(
response, http_method == HTTPRequest::HTTP_HEAD, write_event, http_response_buffer_size);
return *write_buffer_from_response;
}
void PrometheusRequestHandler::tryCallOnException()
{
try
{
if (impl)
impl->onException();
}
catch (...)
{
tryLogCurrentException(log, "onException");
}
}
}