-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathKeeperHTTPHandlerFactory.cpp
More file actions
451 lines (384 loc) · 16.6 KB
/
Copy pathKeeperHTTPHandlerFactory.cpp
File metadata and controls
451 lines (384 loc) · 16.6 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
#include <Server/KeeperHTTPHandlerFactory.h>
#if USE_NURAFT
#include <memory>
#include <Coordination/FourLetterCommand.h>
#include <Coordination/KeeperDispatcher.h>
#include <IO/HTTPCommon.h>
#include <IO/Operators.h>
#include <Server/HTTP/WriteBufferFromHTTPServerResponse.h>
#include <Server/HTTPHandlerFactory.h>
#include <Server/IServer.h>
#include <Poco/JSON/JSON.h>
#include <Poco/JSON/Object.h>
#include <Poco/JSON/Stringifier.h>
#include <Poco/Net/HTTPRequestHandlerFactory.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include <Poco/Util/LayeredConfiguration.h>
#include <Server/KeeperDashboardRequestHandler.h>
#include <Server/KeeperHTTPStorageHandler.h>
#include <Server/KeeperJemallocHandler.h>
#include <Server/KeeperNotFoundHandler.h>
#include <Common/ZooKeeper/ZooKeeperConstants.h>
#include <Common/ZooKeeper/KeeperClientCLI/KeeperClient.h>
#include <Common/ZooKeeper/KeeperOverDispatcher.h>
namespace DB
{
namespace ErrorCodes
{
extern const int INVALID_CONFIG_PARAMETER;
extern const int UNKNOWN_ELEMENT_IN_CONFIG;
}
KeeperHTTPRequestHandlerFactory::KeeperHTTPRequestHandlerFactory(const std::string & name_) : log(getLogger(name_)), name(name_)
{
}
std::unique_ptr<HTTPRequestHandler> KeeperHTTPRequestHandlerFactory::createRequestHandler(const HTTPServerRequest & request)
{
LOG_TRACE(log, "HTTP Request for {}. {}", name, request.toStringForLogging());
for (auto & handler_factory : child_factories)
{
if (auto handler = handler_factory->createRequestHandler(request))
return handler;
}
if (request.getMethod() == Poco::Net::HTTPRequest::HTTP_GET || request.getMethod() == Poco::Net::HTTPRequest::HTTP_HEAD
|| request.getMethod() == Poco::Net::HTTPRequest::HTTP_POST)
{
return std::make_unique<KeeperNotFoundHandler>(hints.getHints(request.getURI()));
}
return nullptr;
}
static void addDashboardHandlersToFactory(
KeeperHTTPRequestHandlerFactory & factory, std::shared_ptr<KeeperDispatcher> keeper_dispatcher)
{
auto dashboard_ui_creator = []() -> std::unique_ptr<KeeperDashboardWebUIRequestHandler>
{ return std::make_unique<KeeperDashboardWebUIRequestHandler>(); };
auto dashboard_path_filter = [](const String & path)
{
return [path](const auto & request)
{
const auto & uri = request.getURI();
return uri == path
|| (uri.size() > path.size() && uri.starts_with(path) && uri[path.size()] == '?');
};
};
auto dashboard_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<KeeperDashboardWebUIRequestHandler>>(dashboard_ui_creator);
dashboard_handler->addFilter(dashboard_path_filter("/dashboard"));
dashboard_handler->allowGetAndHeadRequest();
factory.addPathToHints("/dashboard");
factory.addHandler(dashboard_handler);
auto dashboard_content_creator = [keeper_dispatcher]() -> std::unique_ptr<KeeperDashboardContentRequestHandler>
{ return std::make_unique<KeeperDashboardContentRequestHandler>(keeper_dispatcher); };
auto dashboard_content_handler
= std::make_shared<HandlingRuleHTTPHandlerFactory<KeeperDashboardContentRequestHandler>>(dashboard_content_creator);
dashboard_content_handler->addFilter(dashboard_path_filter("/dashboard/content"));
dashboard_content_handler->allowGetAndHeadRequest();
factory.addHandler(dashboard_content_handler);
}
static void addReadinessHandlerToFactory(
KeeperHTTPRequestHandlerFactory & factory,
std::shared_ptr<KeeperDispatcher> keeper_dispatcher,
const Poco::Util::AbstractConfiguration & config)
{
auto creator = [keeper_dispatcher]() -> std::unique_ptr<KeeperHTTPReadinessHandler>
{ return std::make_unique<KeeperHTTPReadinessHandler>(keeper_dispatcher); };
auto readiness_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<KeeperHTTPReadinessHandler>>(std::move(creator));
readiness_handler->attachStrictPath(config.getString("keeper_server.http_control.readiness.endpoint", "/ready"));
readiness_handler->allowGetAndHeadRequest();
factory.addPathToHints("/ready");
factory.addHandler(readiness_handler);
}
static void addCommandsHandlersToFactory(
KeeperHTTPRequestHandlerFactory & factory,
std::shared_ptr<KeeperDispatcher> keeper_dispatcher,
std::shared_ptr<KeeperHTTPClient> keeper_client)
{
auto creator = [keeper_dispatcher, keeper_client]() -> std::unique_ptr<KeeperHTTPCommandsHandler>
{ return std::make_unique<KeeperHTTPCommandsHandler>(keeper_dispatcher, keeper_client); };
auto commands_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<KeeperHTTPCommandsHandler>>(std::move(creator));
commands_handler->attachNonStrictPath("/api/v1/commands");
commands_handler->allowRESTMethods();
factory.addPathToHints("/api/v1/commands");
factory.addHandler(commands_handler);
}
template <typename H>
static void addStrictHandler(KeeperHTTPRequestHandlerFactory & factory, const std::string & path)
{
auto handler = std::make_shared<HandlingRuleHTTPHandlerFactory<H>>(
[] { return std::make_unique<H>(); });
handler->addFilter([path](const auto & request)
{
const auto & uri = request.getURI();
return uri == path
|| (uri.size() > path.size() && uri.starts_with(path) && uri[path.size()] == '?');
});
handler->allowGetAndHeadRequest();
factory.addHandler(handler);
}
static void addJemallocHandlersToFactory(KeeperHTTPRequestHandlerFactory & factory)
{
addStrictHandler<KeeperJemallocWebUIHandler>(factory, "/jemalloc");
factory.addPathToHints("/jemalloc");
addStrictHandler<KeeperJemallocRedirectHandler>(factory, "/jemalloc/");
#if USE_JEMALLOC
addStrictHandler<KeeperJemallocProfileHandler>(factory, "/jemalloc/profile");
addStrictHandler<KeeperJemallocStatsHandler>(factory, "/jemalloc/stats");
addStrictHandler<KeeperJemallocStatusHandler>(factory, "/jemalloc/status");
#else
addStrictHandler<KeeperJemallocNotAvailableHandler>(factory, "/jemalloc/profile");
addStrictHandler<KeeperJemallocNotAvailableHandler>(factory, "/jemalloc/stats");
addStrictHandler<KeeperJemallocNotAvailableHandler>(factory, "/jemalloc/status");
#endif
}
static void addStorageHandlersToFactory(
KeeperHTTPRequestHandlerFactory & factory,
std::shared_ptr<KeeperDispatcher> keeper_dispatcher,
std::shared_ptr<KeeperHTTPClient> keeper_client)
{
auto creator = [keeper_client, keeper_context = keeper_dispatcher->getKeeperContext()]() -> std::unique_ptr<KeeperHTTPStorageHandler>
{ return std::make_unique<KeeperHTTPStorageHandler>(keeper_client, keeper_context); };
auto storage_handler = std::make_shared<HandlingRuleHTTPHandlerFactory<KeeperHTTPStorageHandler>>(std::move(creator));
storage_handler->attachNonStrictPath("/api/v1/storage");
storage_handler->allowRESTMethods();
factory.addPathToHints("/api/v1/storage");
factory.addHandler(storage_handler);
}
static std::shared_ptr<KeeperHTTPClient> createKeeperClient(
const IServer & server,
std::shared_ptr<KeeperDispatcher> keeper_dispatcher)
{
auto session_timeout = Poco::Timespan(
server.config().getUInt("keeper_server.http_control.storage.session_timeout_ms", Coordination::DEFAULT_SESSION_TIMEOUT_MS)
* Poco::Timespan::MILLISECONDS);
/// Client is created lazily on first use to avoid blocking server startup
/// with synchronous Keeper session creation, which requires Raft consensus
/// and can time out if the leader is not yet fully available.
auto client_factory = [keeper_dispatcher, session_timeout]() -> std::shared_ptr<zkutil::ZooKeeper>
{
return zkutil::ZooKeeper::createFromImpl(
[keeper_dispatcher, session_timeout]()
{
return std::make_unique<Coordination::KeeperOverDispatcher>(keeper_dispatcher, session_timeout);
});
};
return std::make_shared<KeeperHTTPClient>(std::move(client_factory));
}
static void addDefaultHandlersToFactory(
KeeperHTTPRequestHandlerFactory & factory,
const IServer & server,
std::shared_ptr<KeeperDispatcher> keeper_dispatcher,
const Poco::Util::AbstractConfiguration & config)
{
auto keeper_client = createKeeperClient(server, keeper_dispatcher);
addReadinessHandlerToFactory(factory, keeper_dispatcher, config);
addDashboardHandlersToFactory(factory, keeper_dispatcher);
addCommandsHandlersToFactory(factory, keeper_dispatcher, keeper_client);
addStorageHandlersToFactory(factory, keeper_dispatcher, keeper_client);
addJemallocHandlersToFactory(factory);
}
static auto createHandlersFactoryFromConfig(
const IServer & server,
std::shared_ptr<KeeperDispatcher> keeper_dispatcher,
const Poco::Util::AbstractConfiguration & config,
const std::string & name,
const String & prefix)
{
auto main_handler_factory = std::make_shared<KeeperHTTPRequestHandlerFactory>(name);
auto keeper_client = createKeeperClient(server, keeper_dispatcher);
Poco::Util::AbstractConfiguration::Keys keys;
config.keys(prefix, keys);
for (const auto & key : keys)
{
if (key == "defaults")
{
addDefaultHandlersToFactory(*main_handler_factory, server, keeper_dispatcher, config);
}
else if (startsWith(key, "rule"))
{
const auto & handler_type = config.getString(prefix + "." + key + ".handler.type", "");
if (handler_type.empty())
throw Exception(
ErrorCodes::INVALID_CONFIG_PARAMETER,
"Handler type in config is not specified here: "
"{}.{}.handler.type",
prefix,
key);
if (handler_type == "ready")
addReadinessHandlerToFactory(*main_handler_factory, keeper_dispatcher, config);
else if (handler_type == "dashboard")
addDashboardHandlersToFactory(*main_handler_factory, keeper_dispatcher);
else if (handler_type == "commands")
addCommandsHandlersToFactory(*main_handler_factory, keeper_dispatcher, keeper_client);
else if (handler_type == "storage")
addStorageHandlersToFactory(*main_handler_factory, keeper_dispatcher, keeper_client);
else if (handler_type == "jemalloc")
addJemallocHandlersToFactory(*main_handler_factory);
else
throw Exception(
ErrorCodes::INVALID_CONFIG_PARAMETER,
"Unknown handler type '{}' in config here: {}.{}.handler.type",
handler_type,
prefix,
key);
}
else
throw Exception(
ErrorCodes::UNKNOWN_ELEMENT_IN_CONFIG,
"Unknown element in config: "
"{}.{}, must be 'rule' or 'defaults'",
prefix,
key);
}
return main_handler_factory;
}
KeeperHTTPReadinessHandler::KeeperHTTPReadinessHandler(std::shared_ptr<KeeperDispatcher> keeper_dispatcher_)
: log(getLogger("KeeperHTTPReadinessHandler")), keeper_dispatcher(keeper_dispatcher_)
{
}
void KeeperHTTPReadinessHandler::handleRequest(
HTTPServerRequest & /*request*/, HTTPServerResponse & response, const ProfileEvents::Event & /*write_event*/)
{
try
{
auto is_leader = keeper_dispatcher->isLeader();
auto is_follower = keeper_dispatcher->isFollower() && keeper_dispatcher->hasLeader();
auto is_observer = keeper_dispatcher->isObserver() && keeper_dispatcher->hasLeader();
auto data = keeper_dispatcher->getKeeper4LWInfo();
auto status = is_leader || is_follower || is_observer;
Poco::JSON::Object json;
Poco::JSON::Object details;
details.set("role", data.getRole());
details.set("hasLeader", keeper_dispatcher->hasLeader());
json.set("details", details);
json.set("status", status ? "ok" : "fail");
std::ostringstream oss; // STYLE_CHECK_ALLOW_STD_STRING_STREAM
oss.exceptions(std::ios::failbit);
Poco::JSON::Stringifier::stringify(json, oss);
if (!status)
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_SERVICE_UNAVAILABLE);
*response.send() << oss.str();
}
catch (...)
{
tryLogCurrentException(log);
try
{
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
if (!response.sent())
{
/// We have not sent anything yet and we don't even know if we need to compress response.
*response.send() << getCurrentExceptionMessage(false) << '\n';
}
}
catch (...)
{
LOG_ERROR(log, "Cannot send exception to client");
}
}
}
KeeperHTTPCommandsHandler::KeeperHTTPCommandsHandler(
std::shared_ptr<KeeperDispatcher> keeper_dispatcher_,
std::shared_ptr<KeeperHTTPClient> keeper_client_)
: log(getLogger("KeeperHTTPCommandsHandler"))
, keeper_dispatcher(std::move(keeper_dispatcher_))
, keeper_client(std::move(keeper_client_))
{
}
void KeeperHTTPCommandsHandler::handleRequest(
HTTPServerRequest & request, HTTPServerResponse & response, const ProfileEvents::Event & /*write_event*/)
try
{
std::vector<std::string> uri_segments;
Poco::URI uri;
try
{
uri = Poco::URI(request.getURI());
uri.getPathSegments(uri_segments);
}
catch (const std::exception &)
{
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST, "Could not parse request path.");
*response.send() << "Could not parse request path.\n";
return;
}
String command;
String cwd = "/";
const auto params = uri.getQueryParameters();
for (const auto & [key, value]: params)
{
if (key == "command")
command = value;
else if (key == "cwd")
cwd = value;
}
if (command.empty())
{
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST, "Invalid command");
*response.send() << "Invalid command\n";
return;
}
setResponseDefaultHeaders(response);
Poco::JSON::Object response_json;
response.setContentType("application/json");
if (FourLetterCommandFactory::instance().isKnown(DB::IFourLetterCommand::toCode(command)))
{
auto command_ptr = FourLetterCommandFactory::instance().get(DB::IFourLetterCommand::toCode(command));
LOG_DEBUG(log, "Received four letter command {}", command_ptr->name());
try
{
String res = command_ptr->run();
response_json.set("result", res);
response.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
}
catch (...)
{
tryLogCurrentException(log, "Error when executing four letter command " + command_ptr->name());
response_json.set("message", "Internal server error.");
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
}
}
else
{
std::ostringstream stream; // STYLE_CHECK_ALLOW_STD_STRING_STREAM
KeeperClientBase client(stream, stream);
client.zookeeper = keeper_client->get();
client.cwd = cwd;
client.ask_confirmation = false; // Confirmations are not supported in UI
client.processQueryText(command);
response_json.set("result", stream.str());
}
std::ostringstream oss; // STYLE_CHECK_ALLOW_STD_STRING_STREAM
oss.exceptions(std::ios::failbit);
Poco::JSON::Stringifier::stringify(response_json, oss);
*response.send() << oss.str();
}
catch (...)
{
tryLogCurrentException(log);
try
{
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
if (!response.sent())
{
/// We have not sent anything yet and we don't even know if we need to compress response.
*response.send() << getCurrentExceptionMessage(false) << '\n';
}
}
catch (...)
{
LOG_ERROR(log, "Cannot send exception to client");
}
}
HTTPRequestHandlerFactoryPtr createKeeperHTTPHandlerFactory(
const IServer & server,
const Poco::Util::AbstractConfiguration & config,
std::shared_ptr<KeeperDispatcher> keeper_dispatcher,
const std::string & name)
{
if (config.has("keeper_server.http_control.handlers"))
return createHandlersFactoryFromConfig(server, keeper_dispatcher, config, name, "keeper_server.http_control.handlers");
auto factory = std::make_shared<KeeperHTTPRequestHandlerFactory>(name);
addDefaultHandlersToFactory(*factory, server, keeper_dispatcher, config);
return factory;
}
}
#endif