-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathKeeperHTTPStorageHandler.cpp
More file actions
370 lines (315 loc) · 12.6 KB
/
Copy pathKeeperHTTPStorageHandler.cpp
File metadata and controls
370 lines (315 loc) · 12.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
#include <Server/KeeperHTTPStorageHandler.h>
#if USE_NURAFT
#include <Poco/JSON/Object.h>
#include <Poco/JSON/Stringifier.h>
#include <Poco/Net/HTTPServerResponse.h>
#include <IO/HTTPCommon.h>
#include <IO/LimitReadBuffer.h>
#include <IO/Operators.h>
#include <IO/ReadHelpers.h>
#include <Common/ZooKeeper/ZooKeeperCommon.h>
#include <Coordination/CoordinationSettings.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
}
namespace CoordinationSetting
{
extern const CoordinationSettingsUInt64 max_request_size;
}
namespace
{
Poco::JSON::Object statToJSON(const Coordination::Stat & stat)
{
Poco::JSON::Object result;
result.set("czxid", stat.czxid);
result.set("mzxid", stat.mzxid);
result.set("pzxid", stat.pzxid);
result.set("ctime", stat.ctime);
result.set("mtime", stat.mtime);
result.set("version", stat.version);
result.set("cversion", stat.cversion);
result.set("aversion", stat.aversion);
result.set("ephemeralOwner", stat.ephemeralOwner);
result.set("dataLength", stat.dataLength);
result.set("numChildren", stat.numChildren);
return result;
}
std::optional<int32_t> getVersionFromRequest(const HTTPServerRequest & request)
{
/// we store version argument as a "version" query parameter
Poco::URI uri(request.getURI());
const auto query_params = uri.getQueryParameters();
const auto version_param
= std::ranges::find_if(query_params, [](const auto & param) { return param.first == "version"; });
if (version_param == query_params.end())
return std::nullopt;
try
{
return parse<int32_t>(version_param->second);
}
catch (const std::exception &)
{
return std::nullopt;
}
}
std::string getRawBytesFromRequest(HTTPServerRequest & request, const KeeperContextPtr & keeper_context)
{
std::string request_data;
auto stream = request.getStream();
size_t max_request_size = keeper_context->getCoordinationSettings()[CoordinationSetting::max_request_size];
if (max_request_size > 0)
{
LimitReadBuffer limited_stream(*stream, LimitReadBuffer::Settings{
.read_no_more = max_request_size,
.expect_eof = false,
.excetion_hint = "request body is too large"});
readStringUntilEOF(request_data, limited_stream);
}
else
{
readStringUntilEOF(request_data, *stream);
}
return request_data;
}
bool setErrorResponseForZKCode(const Coordination::Error error, HTTPServerResponse & response)
{
switch (error)
{
case Coordination::Error::ZOK:
return false;
case Coordination::Error::ZNONODE:
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_FOUND, "Node not found.");
*response.send() << "Requested node not found.\n";
return true;
case Coordination::Error::ZNODEEXISTS:
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_CONFLICT, "Node already exists.");
*response.send() << "Node already exists.\n";
return true;
case Coordination::Error::ZBADVERSION:
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_CONFLICT, "Version conflict.");
*response.send() << "Version conflict. Check the current version and try again.\n";
return true;
default:
response.setStatus(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
*response.send() << "Keeper request finished with error: " << errorMessage(error) << ".\n";
return true;
}
}
}
KeeperHTTPStorageHandler::KeeperHTTPStorageHandler(
std::shared_ptr<KeeperHTTPClient> keeper_client_,
KeeperContextPtr keeper_context_)
: log(getLogger("KeeperHTTPStorageHandler"))
, keeper_client(std::move(keeper_client_))
, keeper_context(std::move(keeper_context_))
{
}
void KeeperHTTPStorageHandler::performZooKeeperRequest(
Coordination::OpNum opnum, const std::string & storage_path, HTTPServerRequest & request, HTTPServerResponse & response) const
{
switch (opnum)
{
case Coordination::OpNum::Exists:
performZooKeeperExistsRequest(storage_path, response);
return;
case Coordination::OpNum::List:
performZooKeeperListRequest(storage_path, response);
return;
case Coordination::OpNum::Get:
performZooKeeperGetRequest(storage_path, response);
return;
case Coordination::OpNum::Set:
performZooKeeperSetRequest(storage_path, request, response);
return;
case Coordination::OpNum::Create:
performZooKeeperCreateRequest(storage_path, request, response);
return;
case Coordination::OpNum::Remove:
performZooKeeperRemoveRequest(storage_path, request, response);
return;
default:
throw Exception(ErrorCodes::LOGICAL_ERROR, "Trying to perform ZK request for unsupported OpNum. It's a bug.");
}
}
void KeeperHTTPStorageHandler::performZooKeeperExistsRequest(const std::string & storage_path, HTTPServerResponse & response) const
{
Coordination::Stat stat;
if (!keeper_client->get()->exists(storage_path, &stat))
{
setErrorResponseForZKCode(Coordination::Error::ZNONODE, response);
return;
}
Poco::JSON::Object response_json;
response_json.set("stat", statToJSON(stat));
std::ostringstream oss; // STYLE_CHECK_ALLOW_STD_STRING_STREAM
oss.exceptions(std::ios::failbit);
Poco::JSON::Stringifier::stringify(response_json, oss);
response.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
response.setContentType("application/json");
*response.send() << oss.str();
}
void KeeperHTTPStorageHandler::performZooKeeperListRequest(const std::string & storage_path, HTTPServerResponse & response) const
{
Coordination::Stat stat;
Strings result;
const auto error = keeper_client->get()->tryGetChildren(storage_path, result, &stat);
if (setErrorResponseForZKCode(error, response))
return;
Poco::JSON::Object response_json;
response_json.set("child_node_names", result);
response_json.set("stat", statToJSON(stat));
std::ostringstream oss; // STYLE_CHECK_ALLOW_STD_STRING_STREAM
oss.exceptions(std::ios::failbit);
Poco::JSON::Stringifier::stringify(response_json, oss);
response.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
response.setContentType("application/json");
*response.send() << oss.str();
}
void KeeperHTTPStorageHandler::performZooKeeperGetRequest(const std::string & storage_path, HTTPServerResponse & response) const
{
String result;
if (!keeper_client->get()->tryGet(storage_path, result))
{
setErrorResponseForZKCode(Coordination::Error::ZNONODE, response);
return;
}
response.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
response.setContentType("application/octet-stream");
response.setContentLength(result.size());
auto buffer = response.send();
buffer->write(result.c_str(), result.size());
buffer->next();
}
void KeeperHTTPStorageHandler::performZooKeeperSetRequest(
const std::string & storage_path, HTTPServerRequest & request, HTTPServerResponse & response) const
{
const auto maybe_request_version = getVersionFromRequest(request);
if (!maybe_request_version.has_value())
{
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST, "Version parameter is not set or invalid.");
*response.send() << "Version parameter is not set or invalid for set request.\n";
return;
}
const auto error = keeper_client->get()->trySet(storage_path, getRawBytesFromRequest(request, keeper_context), maybe_request_version.value());
if (setErrorResponseForZKCode(error, response))
return;
response.setStatus(Poco::Net::HTTPResponse::HTTP_OK);
response.setContentType("text/plain");
*response.send() << "OK\n";
}
void KeeperHTTPStorageHandler::performZooKeeperCreateRequest(
const std::string & storage_path, HTTPServerRequest & request, HTTPServerResponse & response) const
{
const auto error = keeper_client->get()->tryCreate(storage_path, getRawBytesFromRequest(request, keeper_context), zkutil::CreateMode::Persistent);
if (setErrorResponseForZKCode(error, response))
return;
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_CREATED, "Created");
response.setContentType("text/plain");
response.set("Location", storage_path);
*response.send() << "Created\n";
}
void KeeperHTTPStorageHandler::performZooKeeperRemoveRequest(
const std::string & storage_path, const HTTPServerRequest & request, HTTPServerResponse & response) const
{
const auto maybe_request_version = getVersionFromRequest(request);
if (!maybe_request_version.has_value())
{
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST, "Version parameter is not set or invalid.");
*response.send() << "Version parameter is not set or invalid for DELETE request.\n";
return;
}
const auto error = keeper_client->get()->tryRemove(storage_path, maybe_request_version.value());
if (setErrorResponseForZKCode(error, response))
return;
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NO_CONTENT, "No Content");
response.send();
}
std::optional<Coordination::OpNum> KeeperHTTPStorageHandler::getOperationFromRequest(
const HTTPServerRequest & request, HTTPServerResponse & response)
{
const auto & method = request.getMethod();
if (method == Poco::Net::HTTPRequest::HTTP_GET)
{
/// Check for ?children=true query parameter
Poco::URI uri(request.getURI());
const auto query_params = uri.getQueryParameters();
const auto children_param = std::ranges::find_if(
query_params, [](const auto & param) { return param.first == "children"; });
if (children_param != query_params.end() && children_param->second == "true")
return Coordination::OpNum::List;
return Coordination::OpNum::Get;
}
if (method == Poco::Net::HTTPRequest::HTTP_HEAD)
return Coordination::OpNum::Exists;
if (method == Poco::Net::HTTPRequest::HTTP_POST)
return Coordination::OpNum::Create;
if (method == Poco::Net::HTTPRequest::HTTP_PUT)
return Coordination::OpNum::Set;
if (method == Poco::Net::HTTPRequest::HTTP_DELETE)
return Coordination::OpNum::Remove;
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_METHOD_NOT_ALLOWED, "Method not allowed.");
*response.send() << "HTTP method '" << method << "' is not supported. "
<< "Use GET, HEAD, POST, PUT, or DELETE.\n";
return std::nullopt;
}
void KeeperHTTPStorageHandler::handleRequest(
HTTPServerRequest & request, HTTPServerResponse & response, const ProfileEvents::Event & /*write_event*/)
try
{
static constexpr auto uri_segments_prefix_length = 3; /// /api/v1/storage
std::vector<std::string> uri_segments;
try
{
Poco::URI 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. Check if special symbols are used.\n";
return;
}
const auto maybe_opnum = getOperationFromRequest(request, response);
if (!maybe_opnum.has_value())
return;
const auto opnum = maybe_opnum.value();
/// Build storage path from URL segments after /api/v1/storage
std::string storage_path;
for (size_t i = uri_segments_prefix_length; i < uri_segments.size(); ++i)
storage_path += "/" + uri_segments[i];
if (storage_path.empty())
storage_path = "/";
setResponseDefaultHeaders(response);
try
{
performZooKeeperRequest(opnum, storage_path, request, response);
}
catch (...)
{
tryLogCurrentException(log, "Error when executing Keeper storage operation");
response.setStatus(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
*response.send() << getCurrentExceptionMessage(false) << '\n';
}
}
catch (...)
{
tryLogCurrentException(log);
try
{
response.setStatus(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");
}
}
}
#endif