-
Notifications
You must be signed in to change notification settings - Fork 0
/
CarbonRouterInstanceBase.cpp
225 lines (194 loc) · 7.07 KB
/
CarbonRouterInstanceBase.cpp
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
/*
* 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.
*/
#include "CarbonRouterInstanceBase.h"
#include <memory>
#include <boost/filesystem/operations.hpp>
#include <folly/Singleton.h>
#include <folly/system/ThreadName.h>
#include "mcrouter/AsyncWriter.h"
#include "mcrouter/ProxyBase.h"
#include "mcrouter/lib/CompressionCodecManager.h"
#include "mcrouter/lib/fbi/cpp/util.h"
#include "mcrouter/stats.h"
namespace facebook {
namespace memcache {
namespace mcrouter {
namespace {
struct CarbonRouterInstanceBaseFunctionSchedulerTag {};
folly::Singleton<
folly::FunctionScheduler,
CarbonRouterInstanceBaseFunctionSchedulerTag>
globalFunctionScheduler([]() {
auto scheduler = std::make_unique<folly::FunctionScheduler>();
scheduler->start();
scheduler->setThreadName("carbon-global-scheduler");
return scheduler.release();
});
struct CarbonRouterLoggingAsyncWriter {};
folly::Singleton<AsyncWriter, CarbonRouterLoggingAsyncWriter>
sharedLoggingAsyncWriter([]() {
// Queue size starts at 1, we'll make it unlimited if requested.
auto writer = std::make_unique<AsyncWriter>(1);
if (!writer->start("mcrtr-statsw")) {
throw std::runtime_error("Failed to spawn async stats logging thread");
}
return writer.release();
});
struct CarbonRouterAsyncWriter {};
folly::Singleton<AsyncWriter, CarbonRouterAsyncWriter> sharedAsyncWriter([]() {
auto writer = std::make_unique<AsyncWriter>();
if (!writer->start("mcrtr-awriter")) {
throw std::runtime_error("Failed to spawn mcrouter awriter thread");
}
return writer.release();
});
std::string statsUpdateFunctionName(folly::StringPiece routerName) {
static std::atomic<uint64_t> uniqueId(0);
return folly::to<std::string>(
"carbon-stats-update-fn-", routerName, "-", uniqueId.fetch_add(1));
}
McrouterOptions finalizeOpts(McrouterOptions&& opts) {
facebook::memcache::mcrouter::finalizeOptions(opts);
return std::move(opts);
}
} // anonymous namespace
CarbonRouterInstanceBase::CarbonRouterInstanceBase(McrouterOptions inputOptions)
: opts_(finalizeOpts(std::move(inputOptions))),
pid_(getpid()),
configApi_(createConfigApi(opts_)),
rtVarsData_(std::make_shared<ObservableRuntimeVars>()),
leaseTokenMap_(globalFunctionScheduler.try_get()),
statsUpdateFunctionHandle_(statsUpdateFunctionName(opts_.router_name)) {
if (auto statsLogger = statsLogWriter()) {
if (opts_.stats_async_queue_length) {
statsLogger->increaseMaxQueueSize(opts_.stats_async_queue_length);
} else {
statsLogger->makeQueueSizeUnlimited();
}
}
if (!opts_.pool_stats_config_file.empty()) {
try {
folly::dynamic poolStatJson =
readStaticJsonFile(opts_.pool_stats_config_file);
if (poolStatJson != nullptr) {
auto jStatsEnabledPools = poolStatJson.get_ptr("stats_enabled_pools");
if (jStatsEnabledPools && jStatsEnabledPools->isArray()) {
for (const auto& it : *jStatsEnabledPools) {
if (it.isString()) {
statsEnabledPools_.push_back(it.asString());
} else {
LOG(ERROR) << "Pool Name is not a string";
}
}
}
}
} catch (const std::exception& e) {
LOG(ERROR) << "Invalid pool-stats-config-file : " << e.what();
}
}
}
void CarbonRouterInstanceBase::setUpCompressionDictionaries(
std::unordered_map<uint32_t, CodecConfigPtr>&& codecConfigs) noexcept {
if (codecConfigs.empty() || compressionCodecManager_ != nullptr) {
return;
}
compressionCodecManager_ = std::make_unique<const CompressionCodecManager>(
std::move(codecConfigs));
}
void CarbonRouterInstanceBase::addStartupOpts(
std::unordered_map<std::string, std::string> additionalOpts) {
additionalStartupOpts_.insert(additionalOpts.begin(), additionalOpts.end());
}
std::unordered_map<std::string, std::string>
CarbonRouterInstanceBase::getStartupOpts() const {
constexpr size_t kMaxOptionValueLength = 256;
auto result = opts_.toDict();
result.insert(additionalStartupOpts_.begin(), additionalStartupOpts_.end());
result.emplace("version", MCROUTER_PACKAGE_STRING);
for (auto& it : result) {
it.second = shorten(it.second, kMaxOptionValueLength);
}
return result;
}
size_t CarbonRouterInstanceBase::nextProxyIndex() {
std::lock_guard<std::mutex> guard(nextProxyMutex_);
assert(nextProxy_ < opts().num_proxies);
size_t res = nextProxy_;
nextProxy_ = (nextProxy_ + 1) % opts().num_proxies;
return res;
}
void CarbonRouterInstanceBase::registerForStatsUpdates() {
if (!opts_.num_proxies) {
return;
}
if (auto scheduler = functionScheduler()) {
scheduler->addFunction(
[this]() { updateStats(); },
/*interval=*/std::chrono::seconds(MOVING_AVERAGE_BIN_SIZE_IN_SECOND),
statsUpdateFunctionHandle_,
/*startDelay=*/std::chrono::seconds(MOVING_AVERAGE_BIN_SIZE_IN_SECOND));
}
}
void CarbonRouterInstanceBase::deregisterForStatsUpdates() {
if (auto scheduler = functionScheduler()) {
scheduler->cancelFunctionAndWait(statsUpdateFunctionHandle_);
}
}
void CarbonRouterInstanceBase::updateStats() {
const int BIN_NUM =
(MOVING_AVERAGE_WINDOW_SIZE_IN_SECOND /
MOVING_AVERAGE_BIN_SIZE_IN_SECOND);
// To avoid inconsistence among proxies, we lock all mutexes together
std::vector<std::unique_lock<std::mutex>> statsLocks;
statsLocks.reserve(opts_.num_proxies);
for (size_t i = 0; i < opts_.num_proxies; ++i) {
statsLocks.push_back(getProxyBase(i)->stats().lock());
}
const auto idx = statsIndex();
for (size_t i = 0; i < opts_.num_proxies; ++i) {
auto* const proxy = getProxyBase(i);
proxy->stats().aggregate(idx);
proxy->advanceRequestStatsBin();
}
statsIndex((idx + 1) % BIN_NUM);
}
folly::ReadMostlySharedPtr<AsyncWriter>
CarbonRouterInstanceBase::statsLogWriter() {
return sharedLoggingAsyncWriter.try_get_fast();
}
folly::ReadMostlySharedPtr<AsyncWriter>
CarbonRouterInstanceBase::asyncWriter() {
return sharedAsyncWriter.try_get_fast();
}
std::shared_ptr<folly::FunctionScheduler>
CarbonRouterInstanceBase::functionScheduler() {
return globalFunctionScheduler.try_get();
}
int32_t CarbonRouterInstanceBase::getStatsEnabledPoolIndex(
const folly::StringPiece poolName) const {
if (statsEnabledPools_.size() == 0) {
return -1;
}
int longestPrefixMatchIndex = -1;
// Do sequential search for longest matching name. Since this is done
// only once during the initialization and the size of the array is
// expected to be small, linear search should be OK.
for (size_t i = 0; i < statsEnabledPools_.size(); i++) {
if (poolName.subpiece(0, statsEnabledPools_[i].length())
.compare(statsEnabledPools_[i]) == 0) {
if ((longestPrefixMatchIndex == -1) ||
(statsEnabledPools_[longestPrefixMatchIndex].length() <
statsEnabledPools_[i].length())) {
longestPrefixMatchIndex = i;
}
}
}
return longestPrefixMatchIndex;
}
} // mcrouter
} // memcache
} // facebook