-
Notifications
You must be signed in to change notification settings - Fork 116
/
RedisClusterConnection.java
542 lines (464 loc) · 18.2 KB
/
RedisClusterConnection.java
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
package io.vertx.redis.client.impl;
import io.vertx.codegen.annotations.Nullable;
import io.vertx.core.*;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.impl.logging.Logger;
import io.vertx.core.impl.logging.LoggerFactory;
import io.vertx.redis.client.*;
import io.vertx.redis.client.impl.types.ErrorType;
import java.util.*;
import java.util.function.Function;
import static io.vertx.redis.client.Command.ASKING;
import static io.vertx.redis.client.Command.AUTH;
import static io.vertx.redis.client.Request.cmd;
public class RedisClusterConnection implements RedisConnection {
private static final Logger LOG = LoggerFactory.getLogger(RedisClusterConnection.class);
// we need some randomness, it doesn't need
// to be secure or unpredictable
private static final Random RANDOM = new Random();
// number of attempts/redirects when we get connection errors
// or when we get MOVED/ASK responses
private static final int RETRIES = 16;
// reduce from list fo responses to a single response
private static final Map<Command, Function<List<Response>, Response>> REDUCERS = new HashMap<>();
// List of commands they should run every time only against master nodes
private static final List<Command> MASTER_ONLY_COMMANDS = new ArrayList<>();
public static void addReducer(Command command, Function<List<Response>, Response> fn) {
REDUCERS.put(command, fn);
}
public static void addMasterOnlyCommand(Command command) {
MASTER_ONLY_COMMANDS.add(command);
}
private final VertxInternal vertx;
private final RedisClusterConnectOptions connectOptions;
private final Slots slots;
private final Runnable onMoved;
private final Map<String, PooledRedisConnection> connections;
RedisClusterConnection(Vertx vertx, RedisClusterConnectOptions connectOptions, Slots slots, Runnable onMoved,
Map<String, PooledRedisConnection> connections) {
this.vertx = (VertxInternal) vertx;
this.connectOptions = connectOptions;
this.slots = slots;
this.onMoved = onMoved;
this.connections = connections;
}
@Override
public RedisConnection exceptionHandler(Handler<Throwable> handler) {
for (RedisConnection conn : connections.values()) {
if (conn != null) {
conn.exceptionHandler(handler);
}
}
return this;
}
@Override
public RedisConnection handler(Handler<Response> handler) {
for (RedisConnection conn : connections.values()) {
if (conn != null) {
conn.handler(handler);
}
}
return this;
}
@Override
public RedisConnection pause() {
for (RedisConnection conn : connections.values()) {
if (conn != null) {
conn.pause();
}
}
return this;
}
@Override
public RedisConnection resume() {
for (RedisConnection conn : connections.values()) {
if (conn != null) {
conn.resume();
}
}
return this;
}
@Override
public RedisConnection fetch(long amount) {
for (RedisConnection conn : connections.values()) {
if (conn != null) {
conn.fetch(amount);
}
}
return this;
}
@Override
public RedisConnection endHandler(@Nullable Handler<Void> handler) {
for (RedisConnection conn : connections.values()) {
if (conn != null) {
conn.endHandler(handler);
}
}
return this;
}
@Override
public Future<Response> send(Request request) {
final Promise<Response> promise = vertx.promise();
// process commands for cluster mode
final RequestImpl req = (RequestImpl) request;
final CommandImpl cmd = (CommandImpl) req.command();
final List<byte[]> args = req.getArgs();
if (cmd.needsGetKeys()) {
// it is required to resolve the keys at the server side as we cannot deduct where they are algorithmically
// we shall run this commands on the master node always
send(selectEndpoint(-1, cmd.isReadOnly(args), true), RETRIES, req, promise);
return promise.future();
}
final boolean forceMasterEndpoint = MASTER_ONLY_COMMANDS.contains(cmd);
final List<byte[]> keys = req.keys();
switch (keys.size()) {
case 0:
// can run anywhere
if (REDUCERS.containsKey(cmd)) {
final List<Future<Response>> responses = new ArrayList<>(slots.size());
for (int i = 0; i < slots.size(); i++) {
String[] endpoints = slots.endpointsForSlot(i);
final Promise<Response> p = vertx.promise();
send(selectMasterOrReplicaEndpoint(cmd.isReadOnly(args), endpoints, forceMasterEndpoint), RETRIES, req, p);
responses.add(p.future());
}
Future.all(responses).onComplete(composite -> {
if (composite.failed()) {
// means if one of the operations failed, then we can fail the handler
promise.fail(composite.cause());
} else {
promise.complete(REDUCERS.get(cmd).apply(composite.result().list()));
}
});
} else {
// it doesn't matter which node to use
send(selectEndpoint(-1, cmd.isReadOnly(args), forceMasterEndpoint), RETRIES, req, promise);
}
return promise.future();
case 1:
// trivial option the command is single key
send(selectEndpoint(ZModem.generate(keys.get(0)), cmd.isReadOnly(args), forceMasterEndpoint), RETRIES, req, promise);
return promise.future();
default:
// hashSlot -1 indicates that not all keys of the command targets the same hash slot,
// so Redis would not be able to execute it.
int hashSlot = ZModem.generateMultiRaw(keys);
if (hashSlot == -1) {
// not all keys are in same slot
// we try to perform a reduction if we know how
if (!REDUCERS.containsKey(cmd)) {
// we can't continue as we don't know how to reduce this
promise.fail(buildCrossslotFailureMsg(req));
return promise.future();
}
final Map<Integer, Request> requests = splitRequest(cmd, args);
if (requests.isEmpty()) {
// we can't continue as we don't know how to split this command
promise.fail(buildCrossslotFailureMsg(req));
return promise.future();
}
final List<Future<Response>> responses = new ArrayList<>(requests.size());
for (Map.Entry<Integer, Request> kv : requests.entrySet()) {
final Promise<Response> p = vertx.promise();
send(selectEndpoint(kv.getKey(), cmd.isReadOnly(args), forceMasterEndpoint), RETRIES, kv.getValue(), p);
responses.add(p.future());
}
Future.all(responses).onComplete(composite -> {
if (composite.failed()) {
// means if one of the operations failed, then we can fail the handler
promise.fail(composite.cause());
} else {
promise.complete(REDUCERS.get(cmd).apply(composite.result().list()));
}
});
return promise.future();
} else {
// all keys are in same slot
String[] endpoints = slots.endpointsForKey(hashSlot);
send(selectMasterOrReplicaEndpoint(cmd.isReadOnly(args), endpoints, forceMasterEndpoint), RETRIES, req, promise);
return promise.future();
}
}
}
private Map<Integer, Request> splitRequest(CommandImpl cmd, List<byte[]> args) {
// we will split the request across the slots
final Map<Integer, Request> map = new IdentityHashMap<>();
int lastKey = cmd.iterateKeys(args, (begin, keyIdx, keyStep) -> {
int slot = ZModem.generate(args.get(keyIdx));
// get the client for the slot
Request request = map.get(slot);
if (request == null) {
// we need to create a new one
request = Request.cmd(cmd);
// all params before the key get added
for (int j = 0; j < begin; j++) {
request.arg(args.get(j));
}
// add to the map
map.put(slot, request);
}
// request isn't null anymore
request.arg(args.get(keyIdx));
// all params before the next key get added
for (int j = keyIdx + 1; j < keyIdx + keyStep; j++) {
request.arg(args.get(j));
}
});
// if there are args after the end they must be added to all requests
final Collection<Request> col = map.values();
col.forEach(req -> {
for (int j = lastKey; j < args.size(); j++) {
req.arg(args.get(j));
}
});
return map;
}
private void send(String endpoint, int retries, Request command, Handler<AsyncResult<Response>> handler) {
final PooledRedisConnection connection = connections.get(endpoint);
if (connection == null) {
handler.handle(Future.failedFuture("Missing connection to: " + endpoint));
return;
}
connection
.send(command)
.onComplete(send -> {
if (send.failed() && send.cause() instanceof ErrorType && retries >= 0) {
final ErrorType cause = (ErrorType) send.cause();
if (cause.is("MOVED")) {
this.onMoved.run();
// cluster is unbalanced, need to reconnect
handler.handle(Future.failedFuture(cause));
return;
}
if (cause.is("ASK")) {
connection
.send(cmd(ASKING))
.onFailure(err -> handler.handle(Future.failedFuture(err)))
.onSuccess(asking -> {
// attempt to recover
// REQUERY THE NEW ONE (we've got the correct details)
String addr = cause.slice(' ', cause.is("ERR") ? 3 : 2);
if (addr == null) {
// bad message
handler.handle(Future.failedFuture(cause));
return;
}
// inherit protocol config from the current connection
final RedisURI uri = new RedisURI(endpoint);
// re-run on the new endpoint
send(uri.protocol() + "://" + uri.userinfo() + addr, retries - 1, command, handler);
});
return;
}
if (cause.is("TRYAGAIN") || cause.is("CLUSTERDOWN")) {
// TRYAGAIN response or cluster down, retry with backoff up to 1280ms
long backoff = (long) (Math.pow(2, 16 - Math.max(retries, 9)) * 10);
vertx.setTimer(backoff, t -> send(endpoint, retries - 1, command, handler));
return;
}
if (cause.is("NOAUTH") && connectOptions.getPassword() != null) {
// NOAUTH will try to authenticate
connection
.send(cmd(AUTH).arg(connectOptions.getPassword()))
.onFailure(err -> handler.handle(Future.failedFuture(err)))
.onSuccess(auth -> {
// again
send(endpoint, retries - 1, command, handler);
});
return;
}
}
try {
handler.handle(send);
} catch (RuntimeException e) {
LOG.error("Handler failure", e);
}
});
}
@Override
public Future<List<Response>> batch(List<Request> requests) {
final Promise<List<Response>> promise = vertx.promise();
if (requests.isEmpty()) {
LOG.debug("Empty batch");
promise.complete(Collections.emptyList());
} else {
int currentSlot = -1;
boolean readOnly = false;
boolean forceMasterEndpoint = false;
// look up the base slot for the batch
for (Request request : requests) {
// process commands for cluster mode
final RequestImpl req = (RequestImpl) request;
final CommandImpl cmd = (CommandImpl) req.command();
final List<byte[]> args = req.getArgs();
readOnly |= cmd.isReadOnly(args);
if (cmd.needsGetKeys()) {
// it is required to resolve the keys at the server side as we cannot deduct where they are algorithmically
// we shall run this commands on the master node always
forceMasterEndpoint = true;
continue;
}
final List<byte[]> keys = req.keys();
forceMasterEndpoint |= MASTER_ONLY_COMMANDS.contains(cmd);
int slot;
// process slots, need to verify if we can run this batch
switch (keys.size()) {
case 0:
// this command can run anywhere
break;
case 1:
// command is single key, as long as we're on the same slot, it's OK
slot = ZModem.generate(keys.get(0));
// we are checking the first request key
if (currentSlot == -1) {
currentSlot = slot;
} else if (currentSlot != slot) {
// in cluster mode we currently do not handle batching commands which keys are not on the same slot
promise.fail(buildCrossslotFailureMsg(req));
return promise.future();
}
break;
default:
// multiple keys on the command
for (byte[] key : keys) {
slot = ZModem.generate(key);
if (currentSlot == -1) {
currentSlot = slot;
} else if (currentSlot != slot) {
// in cluster mode we currently do not handle batching commands which keys are not on the same slot
promise.fail(buildCrossslotFailureMsg(req));
return promise.future();
}
break;
}
}
}
// all keys are on the same slot!
batch(selectEndpoint(currentSlot, readOnly, forceMasterEndpoint), RETRIES, requests, promise);
}
return promise.future();
}
private void batch(String endpoint, int retries, List<Request> commands, Handler<AsyncResult<List<Response>>> handler) {
final RedisConnection connection = connections.get(endpoint);
if (connection == null) {
handler.handle(Future.failedFuture("Missing connection to: " + endpoint));
return;
}
connection
.batch(commands)
.onComplete(send -> {
if (send.failed() && send.cause() instanceof ErrorType && retries >= 0) {
final ErrorType cause = (ErrorType) send.cause();
if (cause.is("MOVED")) {
this.onMoved.run();
// cluster is unbalanced, need to reconnect
handler.handle(Future.failedFuture(cause));
return;
}
if (cause.is("ASK")) {
connection
.send(cmd(ASKING))
.onFailure(err -> handler.handle(Future.failedFuture(err)))
.onSuccess(asking -> {
// attempt to recover
// REQUERY THE NEW ONE (we've got the correct details)
String addr = cause.slice(' ', cause.is("ERR") ? 3 : 2);
if (addr == null) {
// bad message
handler.handle(Future.failedFuture(cause));
return;
}
// inherit protocol config from the current connection
final RedisURI uri = new RedisURI(endpoint);
// re-run on the new endpoint
batch(uri.protocol() + "://" + uri.userinfo() + addr, retries - 1, commands, handler);
});
return;
}
if (cause.is("TRYAGAIN") || cause.is("CLUSTERDOWN")) {
// TRYAGAIN response or cluster down, retry with backoff up to 1280ms
long backoff = (long) (Math.pow(2, 16 - Math.max(retries, 9)) * 10);
vertx.setTimer(backoff, t -> batch(endpoint, retries - 1, commands, handler));
return;
}
if (cause.is("NOAUTH") && connectOptions.getPassword() != null) {
// try to authenticate
connection
.send(cmd(AUTH).arg(connectOptions.getPassword()))
.onFailure(err -> handler.handle(Future.failedFuture(err)))
.onSuccess(auth -> {
// again
batch(endpoint, retries - 1, commands, handler);
});
return;
}
}
try {
handler.handle(send);
} catch (RuntimeException e) {
LOG.error("Handler failure", e);
}
});
}
@Override
public Future<Void> close() {
List<Future<Void>> futures = new ArrayList<>();
for (RedisConnection conn : connections.values()) {
if (conn != null) {
futures.add(conn.close());
}
}
return Future.all(futures)
.mapEmpty();
}
@Override
public boolean pendingQueueFull() {
for (RedisConnection conn : connections.values()) {
if (conn != null) {
if (conn.pendingQueueFull()) {
return true;
}
}
}
return false;
}
/**
* Select a Redis client for the given key
*/
private String selectEndpoint(int keySlot, boolean readOnly, boolean forceMasterEndpoint) {
// this command doesn't have keys, return any connection
// NOTE: this means replicas may be used for no key commands regardless of the config
if (keySlot == -1) {
return slots.randomEndPoint(forceMasterEndpoint);
}
String[] endpoints = slots.endpointsForKey(keySlot);
// if we haven't got config for this slot, try any connection
if (endpoints == null || endpoints.length == 0) {
return connectOptions.getEndpoint();
}
return selectMasterOrReplicaEndpoint(readOnly, endpoints, forceMasterEndpoint);
}
private String selectMasterOrReplicaEndpoint(boolean readOnly, String[] endpoints, boolean forceMasterEndpoint) {
if (forceMasterEndpoint) {
return endpoints[0];
}
// always, never, share
RedisReplicas useReplicas = connectOptions.getUseReplicas();
if (readOnly && useReplicas != RedisReplicas.NEVER && endpoints.length > 1) {
switch (useReplicas) {
// always use a replica for read commands
case ALWAYS:
// index must always be more than 1 as 0 denotes master
return endpoints[1 + RANDOM.nextInt(endpoints.length - 1)];
// share read commands across master + replicas
case SHARE:
return endpoints[RANDOM.nextInt(endpoints.length)];
}
}
// fallback to master
return endpoints[0];
}
private String buildCrossslotFailureMsg(RequestImpl req) {
return "Keys of command or batch: \"" + req.toString() + "\" targets not all in the same hash slot (CROSSSLOT) and client side resharding is not supported";
}
}