-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathKeeperJemallocHandler.cpp
More file actions
283 lines (242 loc) · 8.83 KB
/
Copy pathKeeperJemallocHandler.cpp
File metadata and controls
283 lines (242 loc) · 8.83 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
#include <Server/KeeperJemallocHandler.h>
#if USE_NURAFT
#include <IO/HTTPCommon.h>
#include <IO/Operators.h>
#include <Server/HTTP/HTTPResponseHelpers.h>
#include <Server/HTTP/WriteBufferFromHTTPServerResponse.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include <Poco/URI.h>
#if USE_JEMALLOC
#include <Common/Jemalloc.h>
#include <Processors/Sources/JemallocProfileSource.h>
#include <IO/ReadBufferFromFile.h>
#include <IO/ReadHelpers.h>
#include <Poco/JSON/Object.h>
#include <Poco/JSON/Stringifier.h>
#include <base/scope_guard.h>
#include <filesystem>
#include <optional>
#endif
/// Reuse the server's jemalloc HTML — the page auto-adapts via window.JEMALLOC_CONFIG.
constexpr unsigned char resource_jemalloc_html[] =
{
#embed "../../programs/server/jemalloc.html"
};
namespace DB
{
void KeeperJemallocWebUIHandler::handleRequest(
HTTPServerRequest & request, HTTPServerResponse & response, const ProfileEvents::Event &)
{
std::string html(reinterpret_cast<const char *>(resource_jemalloc_html), std::size(resource_jemalloc_html));
constexpr std::string_view head_close = "<head>";
auto pos = html.find(head_close);
if (pos != std::string::npos)
html.insert(pos + head_close.size(), "<script>window.JEMALLOC_CONFIG={mode:'keeper'}</script>");
response.setContentType("text/html; charset=UTF-8");
if (request.getVersion() == HTTPServerRequest::HTTP_1_1)
response.setChunkedTransferEncoding(true);
setResponseDefaultHeaders(response);
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);
auto buf = responseWriteBuffer(request, response);
buf.get()->write(html.data(), html.size());
buf.get()->finalize();
}
void KeeperJemallocRedirectHandler::handleRequest(
HTTPServerRequest &, HTTPServerResponse & response, const ProfileEvents::Event &)
{
setResponseDefaultHeaders(response);
response.redirect("/jemalloc", Poco::Net::HTTPResponse::HTTP_MOVED_PERMANENTLY);
}
#if USE_JEMALLOC
void KeeperJemallocProfileHandler::handleRequest(
HTTPServerRequest & request, HTTPServerResponse & response, const ProfileEvents::Event &)
try
{
Poco::URI uri(request.getURI());
auto params = uri.getQueryParameters();
std::string format = "collapsed";
for (const auto & [key, value] : params)
{
if (key == "format")
format = value;
}
if (format != "collapsed" && format != "raw")
{
setResponseDefaultHeaders(response);
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST);
response.setContentType("text/plain");
*response.send() << "Unknown format: " << format << ". Supported: collapsed, raw\n";
return;
}
Jemalloc::checkProfilingEnabled();
if (request.getMethod() == HTTPRequest::HTTP_HEAD)
{
setResponseDefaultHeaders(response);
response.setContentType("text/plain; charset=UTF-8");
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);
response.send();
return;
}
auto raw_file = std::string(Jemalloc::flushProfile("/tmp/jemalloc_keeper"));
SCOPE_EXIT({
std::error_code ec;
std::filesystem::remove(raw_file, ec);
if (ec)
LOG_WARNING(getLogger("KeeperJemallocProfileHandler"), "Failed to remove temporary heap profile {}: {}", raw_file, ec.message());
});
std::string output;
if (format == "collapsed")
{
output = symbolizeJemallocHeapProfileToString(raw_file, JemallocProfileFormat::Collapsed, /* symbolize_with_inline= */ false);
}
else
{
ReadBufferFromFile in(raw_file);
readStringUntilEOF(output, in);
}
setResponseDefaultHeaders(response);
response.setContentType("text/plain; charset=UTF-8");
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);
auto wb = WriteBufferFromHTTPServerResponse(response, request.getMethod() == HTTPRequest::HTTP_HEAD);
wb.write(output.data(), output.size());
wb.finalize();
}
catch (...)
{
tryLogCurrentException("KeeperJemallocProfileHandler");
try
{
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
if (!response.sent())
*response.send() << getCurrentExceptionMessage(false) << '\n';
}
catch (...)
{
LOG_ERROR(getLogger("KeeperJemallocProfileHandler"), "Cannot send exception to client");
}
}
void KeeperJemallocStatsHandler::handleRequest(
HTTPServerRequest & request, HTTPServerResponse & response, const ProfileEvents::Event &)
try
{
if (request.getMethod() == HTTPRequest::HTTP_HEAD)
{
setResponseDefaultHeaders(response);
response.setContentType("text/plain; charset=UTF-8");
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);
response.send();
return;
}
auto stats = Jemalloc::getStats();
setResponseDefaultHeaders(response);
response.setContentType("text/plain; charset=UTF-8");
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);
auto wb = WriteBufferFromHTTPServerResponse(response, false);
wb.write(stats.data(), stats.size());
wb.finalize();
}
catch (...)
{
tryLogCurrentException("KeeperJemallocStatsHandler");
try
{
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
if (!response.sent())
*response.send() << getCurrentExceptionMessage(false) << '\n';
}
catch (...)
{
LOG_ERROR(getLogger("KeeperJemallocStatsHandler"), "Cannot send exception to client");
}
}
void KeeperJemallocStatusHandler::handleRequest(
HTTPServerRequest & request, HTTPServerResponse & response, const ProfileEvents::Event &)
try
{
Poco::JSON::Object json;
Poco::JSON::Array errors;
auto read_mallctl = [&]<typename T>(const char * name, std::type_identity<T>) -> std::optional<T>
{
T value{};
if (!Jemalloc::tryGetValue(name, value))
{
errors.add(name);
return std::nullopt;
}
return value;
};
auto prof_enabled = read_mallctl("opt.prof", std::type_identity<bool>{});
std::optional<bool> prof_active;
std::optional<bool> thread_active_init;
std::optional<size_t> lg_sample;
if (prof_enabled.value_or(false))
{
prof_active = read_mallctl("prof.active", std::type_identity<bool>{});
lg_sample = read_mallctl("prof.lg_sample", std::type_identity<size_t>{});
/// MibCache::tryGetValue rather than getValue: surface mallctl absence as a JSON `errors`
/// entry instead of asserting in debug builds (jemalloc may be built without prof.*).
if (bool tai = false; Jemalloc::getThreadProfileInitMib().tryGetValue(tai))
thread_active_init = tai;
else
errors.add("prof.thread_active_init");
}
else if (prof_enabled.has_value())
{
prof_active = false;
thread_active_init = false;
lg_sample = size_t(0);
}
auto set_opt_bool = [&json](const char * key, const std::optional<bool> & opt)
{
if (opt.has_value())
json.set(key, *opt);
else
json.set(key, Poco::Dynamic::Var());
};
set_opt_bool("prof_enabled", prof_enabled);
set_opt_bool("prof_active", prof_active);
set_opt_bool("thread_active_init", thread_active_init);
if (lg_sample.has_value())
json.set("lg_sample", static_cast<Poco::UInt64>(*lg_sample));
else
json.set("lg_sample", Poco::Dynamic::Var());
if (errors.size() > 0)
json.set("errors", errors);
std::ostringstream oss; // STYLE_CHECK_ALLOW_STD_STRING_STREAM
oss.exceptions(std::ios::failbit);
Poco::JSON::Stringifier::stringify(json, oss);
setResponseDefaultHeaders(response);
response.setContentType("application/json");
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);
auto wb = WriteBufferFromHTTPServerResponse(response, request.getMethod() == HTTPRequest::HTTP_HEAD);
auto str = oss.str();
wb.write(str.data(), str.size());
wb.finalize();
}
catch (...)
{
tryLogCurrentException("KeeperJemallocStatusHandler");
try
{
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
if (!response.sent())
*response.send() << getCurrentExceptionMessage(false) << '\n';
}
catch (...)
{
LOG_ERROR(getLogger("KeeperJemallocStatusHandler"), "Cannot send exception to client");
}
}
#else
void KeeperJemallocNotAvailableHandler::handleRequest(
HTTPServerRequest &, HTTPServerResponse & response, const ProfileEvents::Event &)
{
setResponseDefaultHeaders(response);
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_NOT_IMPLEMENTED);
response.setContentType("text/plain");
*response.send() << "jemalloc profiling is not available in this build\n";
}
#endif
}
#endif