-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServiceInfo-inl.h
441 lines (393 loc) · 14.1 KB
/
ServiceInfo-inl.h
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
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <folly/Format.h>
#include <folly/Range.h>
#include <folly/json.h>
#include "mcrouter/CarbonRouterInstance.h"
#include "mcrouter/McrouterFiberContext.h"
#include "mcrouter/Proxy.h"
#include "mcrouter/ProxyConfigBuilder.h"
#include "mcrouter/ProxyRequestContextTyped.h"
#include "mcrouter/config-impl.h"
#include "mcrouter/config.h"
#include "mcrouter/lib/RouteHandleTraverser.h"
#include "mcrouter/lib/carbon/CarbonMessageConversionUtils.h"
#include "mcrouter/lib/fbi/cpp/globals.h"
#include "mcrouter/lib/fbi/cpp/util.h"
#include "mcrouter/lib/network/CarbonMessageList.h"
#include "mcrouter/lib/network/TypedMsg.h"
#include "mcrouter/lib/network/gen/MemcacheRouterInfo.h"
#include "mcrouter/options.h"
#include "mcrouter/routes/ProxyRoute.h"
#include "mcrouter/standalone_options.h"
namespace facebook {
namespace memcache {
namespace mcrouter {
namespace detail {
template <class RouterInfo>
class RouteHandlesCommandDispatcher {
public:
bool dispatch(
size_t typeId,
folly::StringPiece key,
const ProxyRoute<RouterInfo>& proxyRoute,
std::string& outStr) {
return dispatcher_.dispatch(typeId, *this, key, proxyRoute, outStr);
}
template <class Request>
static void processMsg(
RouteHandlesCommandDispatcher<RouterInfo>& me,
folly::StringPiece key,
const ProxyRoute<RouterInfo>& proxyRoute,
std::string& outStr) {
outStr = me.processMsgInternal<Request>(key, proxyRoute);
}
private:
CallDispatcher<
// Request List
typename RouterInfo::RoutableRequests,
// Dispatcher class
detail::RouteHandlesCommandDispatcher<RouterInfo>,
// List of types of args to Dispatcher::processMsg()
folly::StringPiece,
const ProxyRoute<RouterInfo>&,
std::string&>
dispatcher_;
template <class Request>
std::string processMsgInternal(
folly::StringPiece key,
const ProxyRoute<RouterInfo>& proxyRoute) {
std::string tree;
int level = 0;
Request request;
RouteHandleTraverser<typename RouterInfo::RouteHandleIf> t(
[&tree, &level](const typename RouterInfo::RouteHandleIf& rh) {
tree.append(std::string(level, ' ') + rh.routeName() + '\n');
++level;
},
[&level]() { --level; });
if (!key.empty() && key[0] == '{' && key[key.size() - 1] == '}') {
carbon::convertFromFollyDynamic(folly::parseJson(key), request);
} else {
request.key() = key;
}
proxyRoute.traverse(request, t);
return tree;
}
};
template <class RouterInfo>
class RouteCommandDispatcher {
public:
bool dispatch(
size_t typeId,
const std::shared_ptr<
ProxyRequestContextTyped<RouterInfo, ServiceInfoRequest>>& ctx,
folly::StringPiece keyStr,
Proxy<RouterInfo>& proxy,
const ProxyRoute<RouterInfo>& proxyRoute) {
return dispatcher_.dispatch(typeId, *this, ctx, keyStr, proxy, proxyRoute);
}
template <class Request>
static void processMsg(
RouteCommandDispatcher<RouterInfo>& /* me */,
const std::shared_ptr<
ProxyRequestContextTyped<RouterInfo, ServiceInfoRequest>>& ctx,
folly::StringPiece keyStr,
Proxy<RouterInfo>& proxy,
const ProxyRoute<RouterInfo>& proxyRoute) {
proxy.fiberManager().addTaskFinally(
[keyStr, &proxy, &proxyRoute]() {
auto destinations = std::make_unique<std::vector<std::string>>();
folly::fibers::Baton baton;
auto rctx =
ProxyRequestContextWithInfo<RouterInfo>::createRecordingNotify(
proxy,
baton,
[&destinations](const PoolContext&, const AccessPoint& dest) {
destinations->push_back(dest.toHostPortString());
});
Request recordingReq;
if (!keyStr.empty() && keyStr[0] == '{' &&
keyStr[keyStr.size() - 1] == '}') {
carbon::convertFromFollyDynamic(
folly::parseJson(keyStr), recordingReq);
} else {
recordingReq.key() = keyStr;
}
fiber_local<RouterInfo>::runWithLocals(
[ctx = std::move(rctx), &recordingReq, &proxyRoute]() mutable {
fiber_local<RouterInfo>::setSharedCtx(std::move(ctx));
/* ignore the reply */
proxyRoute.route(recordingReq);
});
baton.wait();
return destinations;
},
[ctx](folly::Try<std::unique_ptr<std::vector<std::string>>>&& data) {
std::string str;
const auto& destinations = *data;
for (const auto& d : *destinations) {
if (!str.empty()) {
str.push_back('\r');
str.push_back('\n');
}
str.append(d);
}
ReplyT<ServiceInfoRequest> reply(carbon::Result::FOUND);
reply.value() = folly::IOBuf(folly::IOBuf::COPY_BUFFER, str);
ctx->sendReply(std::move(reply));
});
}
private:
CallDispatcher<
// Request List
typename RouterInfo::RoutableRequests,
// Dispatcher class
detail::RouteCommandDispatcher<RouterInfo>,
// List of types of args to Dispatcher::processMsg()
const std::shared_ptr<
ProxyRequestContextTyped<RouterInfo, ServiceInfoRequest>>&,
folly::StringPiece,
Proxy<RouterInfo>&,
const ProxyRoute<RouterInfo>&>
dispatcher_;
};
} // detail
template <class RouterInfo>
struct ServiceInfo<RouterInfo>::ServiceInfoImpl {
Proxy<RouterInfo>& proxy_;
ProxyRoute<RouterInfo>& proxyRoute_;
std::unordered_map<
std::string,
std::function<std::string(const std::vector<folly::StringPiece>& args)>>
commands_;
detail::RouteHandlesCommandDispatcher<RouterInfo>
routeHandlesCommandDispatcher_;
mutable detail::RouteCommandDispatcher<RouterInfo> routeCommandDispatcher_;
ServiceInfoImpl(
Proxy<RouterInfo>& proxy,
const ProxyConfig<RouterInfo>& config);
void handleRequest(
folly::StringPiece req,
const std::shared_ptr<
ProxyRequestContextTyped<RouterInfo, ServiceInfoRequest>>& ctx) const;
void handleRouteCommand(
const std::shared_ptr<
ProxyRequestContextTyped<RouterInfo, ServiceInfoRequest>>& ctx,
const std::vector<folly::StringPiece>& args) const;
};
/* Must be here since unique_ptr destructor needs to know complete
ServiceInfoImpl type */
template <class RouterInfo>
ServiceInfo<RouterInfo>::~ServiceInfo() {}
template <class RouterInfo>
ServiceInfo<RouterInfo>::ServiceInfo(
Proxy<RouterInfo>& proxy,
const ProxyConfig<RouterInfo>& config)
: impl_(std::make_unique<ServiceInfoImpl>(proxy, config)) {}
template <class RouterInfo>
ServiceInfo<RouterInfo>::ServiceInfoImpl::ServiceInfoImpl(
Proxy<RouterInfo>& proxy,
const ProxyConfig<RouterInfo>& config)
: proxy_(proxy), proxyRoute_(config.proxyRoute()) {
commands_.emplace(
"version", [](const std::vector<folly::StringPiece>& /* args */) {
return MCROUTER_PACKAGE_STRING;
});
commands_.emplace(
"config_age",
[&proxy](const std::vector<folly::StringPiece>& /* args */) {
/* capturing this and accessing proxy_ crashes gcc-4.7 */
return std::to_string(proxy.stats().getConfigAge(time(nullptr)));
});
commands_.emplace(
"config_file", [this](const std::vector<folly::StringPiece>& /* args */) {
folly::StringPiece configStr = proxy_.router().opts().config;
if (configStr.startsWith(ConfigApi::kFilePrefix)) {
configStr.removePrefix(ConfigApi::kFilePrefix);
return configStr.str();
}
if (proxy_.router().opts().config_file.empty()) {
throw std::runtime_error("no config file found!");
}
return proxy_.router().opts().config_file;
});
commands_.emplace(
"options", [this](const std::vector<folly::StringPiece>& args) {
if (args.size() > 1) {
throw std::runtime_error("options: 0 or 1 args expected");
}
auto optDict = proxy_.router().getStartupOpts();
if (args.size() == 1) {
auto it = optDict.find(args[0].str());
if (it == optDict.end()) {
throw std::runtime_error(
"options: option " + args[0].str() + " not found");
}
return it->second;
}
// Print all options in order listed in the file
auto optData = McrouterOptions::getOptionData();
auto startupOpts = McrouterStandaloneOptions::getOptionData();
optData.insert(optData.end(), startupOpts.begin(), startupOpts.end());
std::string str;
for (auto& opt : optData) {
if (optDict.find(opt.name) != optDict.end()) {
str.append(opt.name + " " + optDict[opt.name] + "\n");
}
}
return str;
});
/*
This is a special case and handled separately below
{"route", ...
},
*/
commands_.emplace(
"route_handles", [this](const std::vector<folly::StringPiece>& args) {
if (args.size() != 2) {
throw std::runtime_error("route_handles: 2 args expected");
}
auto requestName = args[0];
auto key = args[1];
auto typeId = carbon::getTypeIdByName(
requestName, typename RouterInfo::RoutableRequests());
std::string res;
if (!routeHandlesCommandDispatcher_.dispatch(
typeId, key, proxyRoute_, res)) {
throw std::runtime_error(
folly::sformat("route: unknown request {}", requestName));
}
return res;
});
commands_.emplace(
"config_md5_digest",
[&config](const std::vector<folly::StringPiece>& /* args */) {
if (config.getConfigMd5Digest().empty()) {
throw std::runtime_error("no config md5 digest found!");
}
return config.getConfigMd5Digest();
});
commands_.emplace(
"config_sources_info",
[this](const std::vector<folly::StringPiece>& /* args */) {
auto configInfo = proxy_.router().configApi().getConfigSourcesInfo();
return toPrettySortedJson(configInfo);
});
commands_.emplace(
"preprocessed_config",
[this](const std::vector<folly::StringPiece>& /* args */) {
std::string confFile;
std::string path;
if (!proxy_.router().configApi().getConfigFile(confFile, path)) {
throw std::runtime_error("Can not load config from " + path);
}
ProxyConfigBuilder builder(
proxy_.router().opts(), proxy_.router().configApi(), confFile);
return toPrettySortedJson(builder.preprocessedConfig());
});
commands_.emplace(
"hostid", [](const std::vector<folly::StringPiece>& /* args */) {
return folly::to<std::string>(globals::hostid());
});
commands_.emplace(
"verbosity", [](const std::vector<folly::StringPiece>& args) {
if (args.size() == 1) {
auto before = FLAGS_v;
FLAGS_v = folly::to<int>(args[0]);
return folly::sformat("{} -> {}", before, FLAGS_v);
} else if (args.empty()) {
return folly::to<std::string>(FLAGS_v);
}
throw std::runtime_error(
"expected at most 1 argument, got " +
folly::to<std::string>(args.size()));
});
}
template <class RouterInfo>
void ServiceInfo<RouterInfo>::ServiceInfoImpl::handleRequest(
folly::StringPiece key,
const std::shared_ptr<
ProxyRequestContextTyped<RouterInfo, ServiceInfoRequest>>& ctx) const {
auto p = key.find('(');
auto cmd = key;
folly::StringPiece argsStr(key.end(), key.end());
if (p != folly::StringPiece::npos && key.back() == ')') {
assert(key.size() - p >= 2);
cmd = folly::StringPiece(key.begin(), key.begin() + p);
argsStr =
folly::StringPiece(key.begin() + p + 1, key.begin() + key.size() - 1);
}
std::vector<folly::StringPiece> args;
if (!argsStr.empty()) {
// Handle keys with commas correctly for route and route_handles subcommands
if (cmd.startsWith("route")) {
const auto pos = argsStr.find(',');
if (pos != std::string::npos) {
args.emplace_back(argsStr.data(), pos);
args.emplace_back(argsStr.data() + pos + 1, argsStr.size() - pos - 1);
}
} else {
folly::split(',', argsStr, args);
}
}
std::string replyStr;
try {
if (cmd == "route") {
/* Route is a special case since it involves background requests */
handleRouteCommand(ctx, args);
return;
}
auto it = commands_.find(cmd.str());
if (it == commands_.end()) {
throw std::runtime_error("unknown command: " + cmd.str());
}
replyStr = it->second(args);
if (!replyStr.empty() && replyStr.back() == '\n') {
replyStr = replyStr.substr(0, replyStr.size() - 1);
}
} catch (const std::exception& e) {
replyStr = std::string("ERROR: ") + e.what();
}
ReplyT<ServiceInfoRequest> reply(carbon::Result::FOUND);
reply.value() = folly::IOBuf(folly::IOBuf::COPY_BUFFER, replyStr);
ctx->sendReply(std::move(reply));
}
template <class RouterInfo>
void ServiceInfo<RouterInfo>::ServiceInfoImpl::handleRouteCommand(
const std::shared_ptr<
ProxyRequestContextTyped<RouterInfo, ServiceInfoRequest>>& ctx,
const std::vector<folly::StringPiece>& args) const {
if (args.size() != 2) {
throw std::runtime_error("route: 2 args expected");
}
auto requestName = args[0];
auto key = args[1];
auto typeId = carbon::getTypeIdByName(
requestName, typename RouterInfo::RoutableRequests());
if (!routeCommandDispatcher_.dispatch(
typeId, ctx, key, proxy_, proxyRoute_)) {
throw std::runtime_error(
folly::sformat("route: unknown request {}", requestName));
}
}
template <class RouterInfo>
void ServiceInfo<RouterInfo>::handleRequest(
folly::StringPiece key,
const std::shared_ptr<
ProxyRequestContextTyped<RouterInfo, ServiceInfoRequest>>& ctx) const {
impl_->handleRequest(key, ctx);
}
} // mcrouter
} // memcache
} // facebook