-
Notifications
You must be signed in to change notification settings - Fork 386
Expand file tree
/
Copy pathshards_pool.cpp
More file actions
370 lines (275 loc) · 10.1 KB
/
Copy pathshards_pool.cpp
File metadata and controls
370 lines (275 loc) · 10.1 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
/**************************************************************************
Copyright (c) 2017 sewenew
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************/
#include "sw/redis++/shards_pool.h"
#include <unordered_set>
#include "sw/redis++/errors.h"
namespace sw {
namespace redis {
const std::size_t ShardsPool::SHARDS;
ShardsPool::ShardsPool(const ConnectionPoolOptions &pool_opts,
const ConnectionOptions &connection_opts,
Role role) :
_pool_opts(pool_opts),
_connection_opts(connection_opts),
_role(role) {
if (_connection_opts.type != ConnectionType::TCP) {
throw Error("Only support TCP connection for Redis Cluster");
}
Connection connection(_connection_opts);
_shards = _cluster_slots(connection);
_init_pool(_shards);
}
ShardsPool::ShardsPool(ShardsPool &&that) {
std::lock_guard<std::mutex> lock(that._mutex);
_move(std::move(that));
}
ShardsPool& ShardsPool::operator=(ShardsPool &&that) {
if (this != &that) {
std::lock(_mutex, that._mutex);
std::lock_guard<std::mutex> lock_this(_mutex, std::adopt_lock);
std::lock_guard<std::mutex> lock_that(that._mutex, std::adopt_lock);
_move(std::move(that));
}
return *this;
}
ConnectionPoolSPtr ShardsPool::fetch(const StringView &key) {
auto slot = _slot(key);
return _fetch(slot);
}
ConnectionPoolSPtr ShardsPool::fetch() {
auto slot = _slot();
return _fetch(slot);
}
ConnectionPoolSPtr ShardsPool::fetch(const Node &node) {
std::lock_guard<std::mutex> lock(_mutex);
auto iter = _pools.find(node);
if (iter == _pools.end()) {
// Node doesn't exist, and it should be a newly created node.
// So add a new connection pool.
iter = _add_node(node);
}
assert(iter != _pools.end());
return iter->second;
}
void ShardsPool::update() {
// My might send command to a removed node.
// Try at most 3 times from the current shard masters and finally with the user given connection options.
auto retry = shards_update_retry();
for (auto idx = 0; idx < retry + 1; ++idx) {
try {
Shards shards;
if (idx < retry) {
// Randomly pick a connection.
auto pool = fetch();
assert(pool);
SafeConnection safe_connection(*pool);
shards = _cluster_slots(safe_connection.connection());
}
else {
Connection connection(_connection_opts);
shards = _cluster_slots(connection);
}
std::unordered_set<Node, NodeHash> nodes;
for (const auto &shard : shards) {
nodes.insert(shard.second);
}
std::lock_guard<std::mutex> lock(_mutex);
// TODO: If shards is unchanged, no need to update, and return immediately.
_shards = std::move(shards);
// Remove non-existent nodes.
for (auto iter = _pools.begin(); iter != _pools.end(); ) {
if (nodes.find(iter->first) == nodes.end()) {
// Node has been removed.
_pools.erase(iter++);
} else {
++iter;
}
}
// Add connection pool for new nodes.
// In fact, connections will be created lazily.
for (const auto &node : nodes) {
if (_pools.find(node) == _pools.end()) {
_add_node(node);
}
}
// Update successfully.
return;
} catch (const Error &) {
// continue;
}
}
throw Error("Failed to update shards info");
}
ConnectionOptions ShardsPool::connection_options(const StringView &key) {
auto slot = _slot(key);
return _connection_options(slot);
}
ConnectionOptions ShardsPool::connection_options() {
auto slot = _slot();
return _connection_options(slot);
}
Shards ShardsPool::shards() {
std::lock_guard<std::mutex> lock(_mutex);
return _shards;
}
void ShardsPool::_move(ShardsPool &&that) {
_pool_opts = that._pool_opts;
_connection_opts = that._connection_opts;
_shards = std::move(that._shards);
_pools = std::move(that._pools);
_role = that._role;
}
void ShardsPool::_init_pool(const Shards &shards) {
for (const auto &shard : shards) {
_add_node(shard.second);
}
}
Shards ShardsPool::_cluster_slots(Connection &connection) const {
auto reply = _cluster_slots_command(connection);
assert(reply);
return _parse_reply(*reply);
}
ReplyUPtr ShardsPool::_cluster_slots_command(Connection &connection) const {
connection.send("CLUSTER SLOTS");
return connection.recv();
}
Shards ShardsPool::_parse_reply(redisReply &reply) const {
if (!reply::is_array(reply)) {
throw ProtoError("Expect ARRAY reply");
}
if (reply.element == nullptr || reply.elements == 0) {
throw Error("Empty slots");
}
Shards shards;
for (std::size_t idx = 0; idx != reply.elements; ++idx) {
auto *sub_reply = reply.element[idx];
if (sub_reply == nullptr) {
throw ProtoError("Null slot info");
}
shards.emplace(_parse_slot_info(*sub_reply));
}
return shards;
}
Slot ShardsPool::_parse_slot(redisReply *reply) const {
if (reply == nullptr) {
throw ProtoError("null slot id");
}
auto slot = reply::parse<long long>(*reply);
if (slot < 0) {
throw ProtoError("negative slot id");
}
return static_cast<Slot>(slot);
}
Node ShardsPool::_parse_node(redisReply *reply) const {
if (reply == nullptr
|| !reply::is_array(*reply)
|| reply->element == nullptr
|| reply->elements < 2) {
throw ProtoError("invalid node info");
}
auto host = reply::parse<std::string>(*(reply->element[0]));
auto port = static_cast<int>(reply::parse<long long>(*(reply->element[1])));
return {host, port};
}
std::pair<SlotRange, Node> ShardsPool::_parse_slot_info(redisReply &reply) const {
// Slot info is an array reply: min slot, max slot, master node, [slave nodes]
if (reply.elements < 3 || reply.element == nullptr) {
throw ProtoError("Invalid slot info");
}
auto min_slot = _parse_slot(reply.element[0]);
auto max_slot = _parse_slot(reply.element[1]);
if (min_slot > max_slot) {
throw ProtoError("Invalid slot range");
}
auto slot_range = SlotRange{min_slot, max_slot};
switch (_role) {
case Role::MASTER:
// Return master node, i.e. `reply.element[2]`.
return std::make_pair(slot_range, _parse_node(reply.element[2]));
case Role::SLAVE: {
auto size = reply.elements;
if (size <= 3) {
throw Error("no slave node available");
}
// Randomly pick a slave node.
auto *slave_node_reply = reply.element[_random(3, size - 1)];
return std::make_pair(slot_range, _parse_node(slave_node_reply));
}
default:
throw Error("unknown role");
}
}
Slot ShardsPool::_slot(const StringView &key) const {
// The following code is copied from: https://redis.io/topics/cluster-spec
// And I did some minor changes.
const auto *k = key.data();
auto keylen = static_cast<int>(key.size());
// start-end indexes of { and }.
int s = 0;
int e = 0;
// Search the first occurrence of '{'.
for (s = 0; s < keylen; s++)
if (k[s] == '{') break;
// No '{' ? Hash the whole key. This is the base case.
if (s == keylen) return crc16(k, keylen) & SHARDS;
// '{' found? Check if we have the corresponding '}'.
for (e = s + 1; e < keylen; e++)
if (k[e] == '}') break;
// No '}' or nothing between {} ? Hash the whole key.
if (e == keylen || e == s + 1) return crc16(k, keylen) & SHARDS;
// If we are here there is both a { and a } on its right. Hash
// what is in the middle between { and }.
return crc16(k + s + 1, e - s - 1) & SHARDS;
}
Slot ShardsPool::_slot() const {
return _random(0, SHARDS);
}
std::size_t ShardsPool::_random(std::size_t min, std::size_t max) const {
static thread_local std::default_random_engine engine;
std::uniform_int_distribution<std::size_t> uniform_dist(min, max);
return uniform_dist(engine);
}
ConnectionPoolSPtr& ShardsPool::_get_pool(Slot slot) {
auto shards_iter = _shards.lower_bound(SlotRange{slot, slot});
if (shards_iter == _shards.end() || slot < shards_iter->first.min) {
throw Error("Slot is out of range: " + std::to_string(slot));
}
const auto &node = shards_iter->second;
auto node_iter = _pools.find(node);
if (node_iter == _pools.end()) {
throw Error("Slot is NOT covered: " + std::to_string(slot));
}
return node_iter->second;
}
ConnectionPoolSPtr ShardsPool::_fetch(Slot slot) {
std::lock_guard<std::mutex> lock(_mutex);
return _get_pool(slot);
}
ConnectionOptions ShardsPool::_connection_options(Slot slot) {
std::lock_guard<std::mutex> lock(_mutex);
auto &pool = _get_pool(slot);
assert(pool);
return pool->connection_options();
}
auto ShardsPool::_add_node(const Node &node) -> NodeMap::iterator {
auto opts = _connection_opts;
opts.host = node.host;
opts.port = node.port;
// TODO: Better set readonly an attribute of `Node`.
if (_role == Role::SLAVE) {
opts.readonly = true;
}
return _pools.emplace(node, std::make_shared<ConnectionPool>(_pool_opts, opts)).first;
}
}
}