-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathMemcachedConnection.java
More file actions
1819 lines (1658 loc) · 61.7 KB
/
MemcachedConnection.java
File metadata and controls
1819 lines (1658 loc) · 61.7 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
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* arcus-java-client : Arcus Java client
* Copyright 2010-2014 NAVER Corp.
* Copyright 2014-2022 JaM2in Co., Ltd.
*
* 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.
*/
// Copyright (c) 2006 Dustin Sallings <dustin@spy.net>
package net.spy.memcached;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import net.spy.memcached.compat.SpyObject;
import net.spy.memcached.compat.log.LoggerFactory;
import net.spy.memcached.internal.ReconnDelay;
import net.spy.memcached.metrics.OpLatencyMonitor;
import net.spy.memcached.metrics.OpThroughputMonitor;
import net.spy.memcached.ops.KeyedOperation;
import net.spy.memcached.ops.MultiOperationCallback;
import net.spy.memcached.ops.Operation;
import net.spy.memcached.ops.OperationCallback;
import net.spy.memcached.ops.OperationException;
import net.spy.memcached.ops.OperationState;
import net.spy.memcached.ops.OperationStatus;
/**
* Connection to a cluster of memcached servers.
*/
public final class MemcachedConnection extends SpyObject {
private int emptySelects = 0;
// The number of empty selects we'll allow before assuming we may have
// missed one and should check the current selectors. This generally
// indicates a bug, but we'll check it nonetheless.
private static final int DOUBLE_CHECK_EMPTY = 256;
// The number of empty selects we'll allow before blowing up. It's too
// easy to write a bug that causes it to loop uncontrollably. This helps
// find those bugs and often works around them.
private static final int EXCESSIVE_EMPTY = 0x1000000;
private final int timeoutExceptionThreshold;
private final int timeoutRatioThreshold;
private final int timeoutDurationThreshold;
private final String connName;
private Selector selector = null;
private final NodeLocator locator;
private final FailureMode failureMode;
// If true, optimization will collapse multiple sequential get ops
private final boolean optimizeGetOp;
// AddedQueue is used to track the QueueAttachments for which operations
// have recently been queued.
private final ConcurrentLinkedQueue<MemcachedNode> addedQueue;
// reconnectQueue contains the attachments that need to be reconnected
private final ReconnectQueue reconnectQueue;
private final AtomicReference<List<InetSocketAddress>> cacheNodesChange
= new AtomicReference<>(null);
/* ENABLE_MIGRATION if */
private final AtomicReference<List<InetSocketAddress>> alterNodesChange
= new AtomicReference<>(null);
private final AtomicReference<List<InetSocketAddress>> delayedAlterNodesChange
= new AtomicReference<>(null);
/* ENABLE_MIGRATION end */
private final OperationFactory opFactory;
private final ConnectionFactory connFactory;
private final Collection<ConnectionObserver> connObservers =
new ConcurrentLinkedQueue<>();
private final Set<MemcachedNode> nodesNeedVersionOp = new HashSet<>();
/* ENABLE_MIGRATION if */
private boolean arcusMigrEnabled = false;
private MigrationType mgType = MigrationType.UNKNOWN;
private MigrationState mgState = MigrationState.UNKNOWN;
private boolean mgInProgress = false;
/* ENABLE_MIGRATION end */
/* ENABLE_REPLICATION if */
private static final long DELAYED_SWITCHOVER_TIMEOUT_MILLISECONDS = 50;
private boolean arcusReplEnabled;
private final DelayedSwitchoverGroups delayedSwitchoverGroups =
new DelayedSwitchoverGroups(DELAYED_SWITCHOVER_TIMEOUT_MILLISECONDS);
/* ENABLE_REPLICATION end */
/**
* Construct a memcached connection.
*
* @param name the name of memcached connection
* @param f the factory that will provide an operation queue
* @param a the addresses of the servers to connect to
* @param obs the observers that see the first connection established.
* @param fm the failure mode for the underlying connection :
* Cancel(default), Redistribute, Retry.
* @param opfactory the operation factory.
* @throws IOException if a connection attempt fails early
*/
public MemcachedConnection(String name, ConnectionFactory f,
List<InetSocketAddress> a, Collection<ConnectionObserver> obs,
FailureMode fm, OperationFactory opfactory)
throws IOException {
this.connFactory = f;
connName = name;
connObservers.addAll(obs);
addedQueue = new ConcurrentLinkedQueue<>();
failureMode = fm;
optimizeGetOp = f.shouldOptimize();
opFactory = opfactory;
timeoutExceptionThreshold = f.getTimeoutExceptionThreshold();
timeoutRatioThreshold = f.getTimeoutRatioThreshold();
timeoutDurationThreshold = f.getTimeoutDurationThreshold();
selector = Selector.open();
List<MemcachedNode> connections = new ArrayList<>(a.size());
for (SocketAddress sa : a) {
connections.add(makeMemcachedNode(connName, sa));
}
locator = f.createLocator(connections);
reconnectQueue = new ReconnectQueue(f.getMaxReconnectDelay());
}
/* ENABLE_REPLICATION if */
// handleNodesChangeQueue and updateConnections behave slightly differently
// depending on the Arcus version. We could have created a subclass and overload
// those methods. But, MemcachedConnection is a final class.
void setArcusReplEnabled(boolean b) {
arcusReplEnabled = b;
}
boolean getArcusReplEnabled() {
return arcusReplEnabled;
}
/* ENABLE_REPLICATION end */
/* ENABLE_MIGRATION if */
void setArcusMigrEnabled(boolean b) {
arcusMigrEnabled = b;
}
void setMigrationTypeAndState(MigrationType type, MigrationState state) {
if (state != this.mgState && state == MigrationState.PREPARED) {
this.mgInProgress = false;
}
this.mgType = type;
this.mgState = state;
}
/* ENABLE_MIGRATION end */
private boolean selectorsMakeSense() {
for (MemcachedNode qa : locator.getAll()) {
if (qa.getSk() != null && qa.getSk().isValid()) {
if (qa.getChannel().isConnected()) {
int sops = qa.getSk().interestOps();
int expected = 0;
if (qa.hasReadOp()) {
expected |= SelectionKey.OP_READ;
}
if (qa.hasWriteOp()) {
expected |= SelectionKey.OP_WRITE;
}
if (qa.getBytesRemainingToWrite() > 0) {
expected |= SelectionKey.OP_WRITE;
}
assert sops == expected : "Invalid ops: "
+ qa + ", expected " + expected + ", got " + sops;
} else {
int sops = qa.getSk().interestOps();
assert sops == SelectionKey.OP_CONNECT
: "Not connected, and not watching for connect: " + sops;
}
}
}
getLogger().debug("Checked the selectors.");
return true;
}
private void addVersionOpToVersionAbsentNodes() {
Iterator<MemcachedNode> it = nodesNeedVersionOp.iterator();
while (it.hasNext()) {
MemcachedNode qa = it.next();
try {
prepareVersionInfo(qa);
} catch (IllegalStateException e) {
// queue overflow occurs. retry later
continue;
}
it.remove();
}
}
/**
* MemcachedClient calls this method to handle IO over the connections.
*/
public void handleIO() throws IOException {
// add versionOp to the node that need it.
addVersionOpToVersionAbsentNodes();
// Deal with all of the stuff that's been added, but may not be marked writable.
handleInputQueue();
getLogger().debug("Done dealing with queue.");
long delay = 0;
if (cacheNodesChange.get() != null) {
delay = 1;
} else if (!reconnectQueue.isEmpty()) {
delay = reconnectQueue.getMinDelayMillis();
}
/* ENABLE_REPLICATION if */
if (arcusReplEnabled && !delayedSwitchoverGroups.isEmpty()) {
long minSwitchoverDelay = delayedSwitchoverGroups.getMinDelayMillis();
delay = (delay > 0) ? Math.min(minSwitchoverDelay, delay) : minSwitchoverDelay;
}
/* ENABLE_REPLICATION end */
getLogger().debug("Selecting with delay of %sms", delay);
assert selectorsMakeSense() : "Selectors don't make sense.";
int selected = selector.select(delay);
Set<SelectionKey> selectedKeys = selector.selectedKeys();
if (selectedKeys.isEmpty()) {
getLogger().debug("No selectors ready, interrupted: " + Thread.interrupted());
if (++emptySelects > DOUBLE_CHECK_EMPTY) {
getLogger().info(
"Reached to the double check of emptySelect. Selected with delay of %dms", delay);
for (SelectionKey sk : selector.keys()) {
getLogger().info("%s has %s, interested in %s",
sk, sk.readyOps(), sk.interestOps());
if (sk.readyOps() != 0) {
getLogger().info("%s has a ready op, handling IO", sk);
handleIO(sk);
} else {
lostConnection((MemcachedNode) sk.attachment(),
ReconnDelay.DEFAULT, "too many empty selects");
}
}
assert emptySelects < EXCESSIVE_EMPTY : "Too many empty selects";
}
} else {
getLogger().debug("Selected %d, selected %d keys", selected, selectedKeys.size());
emptySelects = 0;
for (SelectionKey sk : selectedKeys) {
handleIO(sk);
}
selectedKeys.clear();
}
// see if any connections blew up with large number of timeouts
for (SelectionKey sk : selector.keys()) {
Object attachment = sk.attachment();
// attachment might be null, because some node has already closed the channel to reconnect.
if (attachment == null) {
continue;
}
MemcachedNode mn = (MemcachedNode) attachment;
if (mn.getContinuousTimeout() > timeoutExceptionThreshold &&
(timeoutDurationThreshold == 0 || mn.getTimeoutDuration() > timeoutDurationThreshold)) {
getLogger().warn(
"%s exceeded continuous timeout threshold. >%s(count), >%s(duration) (%s)",
mn.getNodeName(),
timeoutExceptionThreshold, timeoutDurationThreshold, mn.getOpQueueStatus());
lostConnection(mn, ReconnDelay.DEFAULT, "continuous timeout");
} else if (timeoutRatioThreshold > 0 && mn.getTimeoutRatioNow() > timeoutRatioThreshold) {
getLogger().warn("%s exceeded timeout ratio threshold. >%s (%s)",
mn.getNodeName(), timeoutRatioThreshold, mn.getOpQueueStatus());
lostConnection(mn, ReconnDelay.DEFAULT, "high timeout ratio");
}
}
/* ENABLE_REPLICATION if */
if (arcusReplEnabled) {
// Deal with the memcached server group that need delayed switchover.
handleDelayedSwitchover();
}
/* ENABLE_REPLICATION end */
// Deal with the memcached server group that's been added by CacheManager.
handleCacheNodesChange();
if (!reconnectQueue.isEmpty()) {
attemptReconnects();
}
}
private void handleNodesToRemove(final List<MemcachedNode> nodesToRemove) {
for (MemcachedNode node : nodesToRemove) {
getLogger().info("old memcached node removed %s", node);
reconnectQueue.remove(node);
/* ENABLE_MIGRATION if */
if (mgType == MigrationType.LEAVE) {
if (node.hasReadOp()) {
redistributeOperationsForMigration(node.destroyReadQueue(false));
}
if (node.hasWriteOp()) {
redistributeOperationsForMigration(node.destroyWriteQueue(false));
}
redistributeOperationsForMigration(node.destroyInputQueue());
continue;
}
/* ENABLE_MIGRATION end */
// removing node is not related to failure mode.
// so, cancel operations regardless of failure mode.
String cause = "node removed.";
cancelOperations(node.destroyReadQueue(false), cause);
cancelOperations(node.destroyWriteQueue(false), cause);
cancelOperations(node.destroyInputQueue(), cause);
}
}
private void updateConnections(List<InetSocketAddress> addrs) throws IOException {
List<MemcachedNode> attachNodes = new ArrayList<>();
List<MemcachedNode> removeNodes = new ArrayList<>();
for (MemcachedNode node : locator.getAll()) {
if (addrs.contains(node.getSocketAddress())) {
addrs.remove(node.getSocketAddress());
} else {
removeNodes.add(node);
}
}
// Make connections to the newly added nodes.
for (SocketAddress sa : addrs) {
attachNodes.add(attachMemcachedNode(sa));
}
// Update the hash.
locator.update(attachNodes, removeNodes);
// Remove the unavailable nodes.
handleNodesToRemove(removeNodes);
}
/* ENABLE_REPLICATION if */
private Set<String> findChangedGroups(List<InetSocketAddress> addrs,
Collection<MemcachedNode> nodes) {
Map<String, InetSocketAddress> addrMap = new HashMap<>();
for (InetSocketAddress each : addrs) {
addrMap.put(each.toString(), each);
}
Set<String> changedGroupSet = new HashSet<>();
for (MemcachedNode node : nodes) {
String nodeAddr = ((InetSocketAddress) node.getSocketAddress()).toString();
if (addrMap.remove(nodeAddr) == null) { // removed node
changedGroupSet.add(node.getReplicaGroup().getGroupName());
}
}
for (String addr : addrMap.keySet()) { // newly added node
ArcusReplNodeAddress a = (ArcusReplNodeAddress) addrMap.get(addr);
changedGroupSet.add(a.getGroupName());
}
return changedGroupSet;
}
private List<InetSocketAddress> findAddrsOfChangedGroups(List<InetSocketAddress> addrs,
Set<String> changedGroups) {
List<InetSocketAddress> changedGroupAddrs = new ArrayList<>();
for (InetSocketAddress addr : addrs) {
if (changedGroups.contains(((ArcusReplNodeAddress) addr).getGroupName())) {
changedGroupAddrs.add(addr);
}
}
return changedGroupAddrs;
}
private void updateReplConnections(List<InetSocketAddress> addrs) throws IOException {
List<MemcachedNode> attachNodes = new ArrayList<>();
List<MemcachedNode> removeNodes = new ArrayList<>();
List<MemcachedReplicaGroup> changeRoleGroups = new ArrayList<>();
List<Task> taskList = new ArrayList<>(); // tasks executed after locator update
/* In replication, after SWITCHOVER or REPL_SLAVE is received from a group
* and switchover is performed, but before the group's znode is changed,
* another group's znode can be changed.
*
* In this case, there is a problem that the switchover is restored
* because the state of the switchover group and the znode state are different.
*
* In order to remove the abnormal phenomenon,
* we find out the changed groups with the comparison of previous and current znode list,
* and update the state of groups based on them.
*/
Set<String> changedGroups = findChangedGroups(addrs, locator.getAll());
Map<String, List<ArcusReplNodeAddress>> newAllGroups =
ArcusReplNodeAddress.makeGroupAddrsList(findAddrsOfChangedGroups(addrs, changedGroups));
// remove invalidated groups in changedGroups
for (Map.Entry<String, List<ArcusReplNodeAddress>> entry : newAllGroups.entrySet()) {
if (!ArcusReplNodeAddress.validateGroup(entry)) {
changedGroups.remove(entry.getKey());
}
}
Map<String, MemcachedReplicaGroup> oldAllGroups =
((ArcusReplKetamaNodeLocator) locator).getAllGroups();
for (String changedGroupName : changedGroups) {
MemcachedReplicaGroup oldGroup = oldAllGroups.get(changedGroupName);
List<ArcusReplNodeAddress> newGroupAddrs = newAllGroups.get(changedGroupName);
if (oldGroup == null) {
// Newly added group
for (ArcusReplNodeAddress newAddr : newGroupAddrs) {
attachNodes.add(attachMemcachedNode(newAddr));
}
continue;
}
if (newGroupAddrs == null) {
// Old group nodes have disappeared. Remove the old group nodes.
removeNodes.add(oldGroup.getMasterNode());
removeNodes.addAll(oldGroup.getSlaveNodes());
delayedSwitchoverGroups.remove(oldGroup);
continue;
}
if (oldGroup.isDelayedSwitchover()) {
delayedSwitchoverGroups.remove(oldGroup);
switchoverMemcachedReplGroup(oldGroup.getMasterNode(), true);
}
MemcachedNode oldMasterNode = oldGroup.getMasterNode();
List<MemcachedNode> oldSlaveNodes = oldGroup.getSlaveNodes();
getLogger().debug("New group nodes : " + newGroupAddrs);
getLogger().debug("Old group nodes : [" + oldGroup + "]");
ArcusReplNodeAddress oldMasterAddr = (ArcusReplNodeAddress) oldMasterNode.getSocketAddress();
ArcusReplNodeAddress newMasterAddr = newGroupAddrs.get(0);
assert oldMasterAddr != null : "invalid old rgroup";
assert newMasterAddr != null : "invalid new rgroup";
Set<ArcusReplNodeAddress> oldSlaveAddrs = getAddrsFromNodes(oldSlaveNodes);
Set<ArcusReplNodeAddress> newSlaveAddrs = getSlaveAddrsFromGroupAddrs(newGroupAddrs);
if (oldMasterAddr.isSameAddress(newMasterAddr)) {
// add newly added slave node
for (ArcusReplNodeAddress newSlaveAddr : newSlaveAddrs) {
if (!oldSlaveAddrs.contains(newSlaveAddr)) {
attachNodes.add(attachMemcachedNode(newSlaveAddr));
}
}
// remove not exist old slave node
for (MemcachedNode oldSlaveNode : oldSlaveNodes) {
if (!newSlaveAddrs.contains((ArcusReplNodeAddress) oldSlaveNode.getSocketAddress())) {
removeNodes.add(oldSlaveNode);
// move operation slave -> master.
taskList.add(new MoveOperationTask(
oldSlaveNode, oldMasterNode, false));
}
}
} else if (oldSlaveAddrs.contains(newMasterAddr)) {
oldGroup.setMasterCandidateByAddr(newMasterAddr);
if (newSlaveAddrs.contains(oldMasterAddr)) {
// Switchover
if (oldMasterNode.hasNonIdempotentOperationInReadQ()) {
// delay to change role and move operations
// by the time switchover timeout occurs or
// "SWITCHOVER", "REPL_SLAVE" response received.
delayedSwitchoverGroups.put(oldGroup);
} else {
changeRoleGroups.add(oldGroup);
taskList.add(new MoveOperationTask(
oldMasterNode, oldGroup.getMasterCandidate(), false));
taskList.add(new QueueReconnectTask(
oldMasterNode, ReconnDelay.IMMEDIATE,
"Discarded all pending reading state operation to move operations."));
}
} else {
changeRoleGroups.add(oldGroup);
// Failover
removeNodes.add(oldMasterNode);
// move operation: master -> slave.
taskList.add(new MoveOperationTask(
oldMasterNode, oldGroup.getMasterCandidate(), true));
}
// add newly added slave node
for (ArcusReplNodeAddress newSlaveAddr : newSlaveAddrs) {
if (!oldSlaveAddrs.contains(newSlaveAddr) && !oldMasterAddr.isSameAddress(newSlaveAddr)) {
attachNodes.add(attachMemcachedNode(newSlaveAddr));
}
}
// remove not exist old slave node
for (MemcachedNode oldSlaveNode : oldSlaveNodes) {
ArcusReplNodeAddress oldSlaveAddr
= (ArcusReplNodeAddress) oldSlaveNode.getSocketAddress();
if (!newSlaveAddrs.contains(oldSlaveAddr) && !newMasterAddr.isSameAddress(oldSlaveAddr)) {
removeNodes.add(oldSlaveNode);
// move operation slave -> master.
taskList.add(new MoveOperationTask(
oldSlaveNode, oldGroup.getMasterCandidate(), false));
}
}
} else {
// Old master has gone away. And, new group has appeared.
MemcachedNode newMasterNode = attachMemcachedNode(newMasterAddr);
attachNodes.add(newMasterNode);
for (ArcusReplNodeAddress newSlaveAddr : newSlaveAddrs) {
attachNodes.add(attachMemcachedNode(newSlaveAddr));
}
removeNodes.add(oldMasterNode);
// move operation: master -> master.
taskList.add(new MoveOperationTask(
oldMasterNode, newMasterNode, true));
for (MemcachedNode oldSlaveNode : oldSlaveNodes) {
removeNodes.add(oldSlaveNode);
// move operation slave -> master.
taskList.add(new MoveOperationTask(
oldSlaveNode, newMasterNode, false));
}
}
}
// Update the hash.
((ArcusReplKetamaNodeLocator) locator).update(attachNodes, removeNodes, changeRoleGroups);
// do task after locator update
for (Task task : taskList) {
task.doTask();
}
// Remove the unavailable nodes.
handleNodesToRemove(removeNodes);
}
private Set<ArcusReplNodeAddress> getAddrsFromNodes(List<MemcachedNode> nodes) {
Set<ArcusReplNodeAddress> addrs = Collections.emptySet();
if (!nodes.isEmpty()) {
addrs = new HashSet<>((int) (nodes.size() / .75f) + 1);
for (MemcachedNode node : nodes) {
addrs.add((ArcusReplNodeAddress) node.getSocketAddress());
}
}
return addrs;
}
private Set<ArcusReplNodeAddress> getSlaveAddrsFromGroupAddrs(
List<ArcusReplNodeAddress> groupAddrs) {
Set<ArcusReplNodeAddress> slaveAddrs = Collections.emptySet();
int groupSize = groupAddrs.size();
if (groupSize > 1) {
slaveAddrs = new HashSet<>((int) ((groupSize - 1) / .75f) + 1);
for (int i = 1; i < groupSize; i++) {
slaveAddrs.add(groupAddrs.get(i));
}
}
return slaveAddrs;
}
/* ENABLE_REPLICATION end */
/* ENABLE_REPLICATION if */
private void switchoverMemcachedReplGroup(MemcachedNode node, boolean cancelNonIdempotent) {
MemcachedReplicaGroup group = node.getReplicaGroup();
/* must keep the following execution order when switchover
* - first moveOperations
* - second, queueReconnect
*
* because moves all operations
*/
if (group.getMasterNode() != null && group.getMasterCandidate() != null) {
if (((ArcusReplNodeAddress) node.getSocketAddress()).isMaster()) {
((ArcusReplKetamaNodeLocator) locator).switchoverReplGroup(group);
}
node.moveOperations(group.getMasterNode(), cancelNonIdempotent);
addedQueue.offer(group.getMasterNode());
queueReconnect(node, ReconnDelay.IMMEDIATE,
"Discarded all pending reading state operation to move operations.");
} else {
getLogger().warn("Delay switchover because invalid group state : " + group);
}
}
/* ENABLE_REPLICATION end */
private MemcachedNode attachMemcachedNode(SocketAddress sa) throws IOException {
/* ENABLE_MIGRATION if */
if (mgType == MigrationType.JOIN) {
/* Only joining nodes can be attached */
MemcachedNode node = locator.getAlterNode(sa);
if (node != null) {
return node;
}
}
/* ENABLE_MIGRATION end */
return makeMemcachedNode(connName, sa);
}
private MemcachedNode makeMemcachedNode(String name,
SocketAddress sa) throws IOException {
MemcachedNode qa = connFactory.createMemcachedNode(name, sa, connFactory.getReadBufSize());
if (timeoutRatioThreshold > 0) {
qa.enableTimeoutRatio();
}
SocketChannel ch = SocketChannel.open();
ch.configureBlocking(false);
ch.socket().setTcpNoDelay(!connFactory.useNagleAlgorithm());
ch.socket().setKeepAlive(connFactory.getKeepAlive());
ch.socket().setReuseAddress(true);
/* The codes above can be replaced by the codes below since java 1.7 */
// ch.setOption(StandardSocketOptions.TCP_NODELAY, !f.useNagleAlgorithm());
// ch.setOption(StandardSocketOptions.SO_REUSEADDR, true);
qa.setChannel(ch);
int ops = 0;
// Initially I had attempted to skirt this by queueing every
// connect, but it considerably slowed down start time.
try {
if (ch.connect(sa)) {
getLogger().info("new memcached node connected to %s immediately", qa);
connected(qa);
} else {
getLogger().info("new memcached node added %s to connect queue", qa);
ops = SelectionKey.OP_CONNECT;
}
qa.setSk(ch.register(selector, ops, qa));
assert ch.isConnected()
|| qa.getSk().interestOps() == SelectionKey.OP_CONNECT
: "Not connected, and not wanting to connect";
} catch (SocketException e) {
getLogger().warn("new memcached socket error on initial connect");
queueReconnect(qa, ReconnDelay.DEFAULT, "initial connection error");
}
prepareVersionInfo(qa);
return qa;
}
private void prepareVersionInfo(final MemcachedNode node) {
Operation op = opFactory.version(new OperationCallback() {
@Override
public void receivedStatus(OperationStatus status) {
if (status.isSuccess()) {
node.setVersion(status.getMessage());
} else {
getLogger().warn("VersionOp failed : " + status.getMessage());
}
}
@Override
public void complete() {
if (node.getVersion() == null) {
nodesNeedVersionOp.add(node);
}
}
});
addOperation(node, op);
}
// Handle the memcached server group that's been added by CacheManager.
void handleCacheNodesChange() throws IOException {
/* ENABLE_MIGRATION if */
/*
* handleCacheNodesChange() and handleAlterNodesChange() have been integrated
* to fix bug that occurs when Context Switching from Java Client IO Thread to ZK IO Thread
* is executed after handleCacheNodesChange() and before handleAlterNodesChange().
* If change of cache_list and alter_list are received when after handleCacheNodesChange()
* and before handleAlterNodesChange(), there MUST be bug because alter_list change
* will be applied without application of dependent cache_list change.
*/
List<InetSocketAddress> alterList = alterNodesChange.getAndSet(null);
/* ENABLE_MIGRATION end */
List<InetSocketAddress> cacheList = cacheNodesChange.getAndSet(null);
if (cacheList != null) {
// Update the memcached server group.
/* ENABLE_REPLICATION if */
if (arcusReplEnabled) {
updateReplConnections(cacheList);
return;
}
/* ENABLE_REPLICATION end */
updateConnections(cacheList);
}
/* ENABLE_MIGRATION if */
if (arcusMigrEnabled && alterList != null) {
if (mgState == MigrationState.PREPARED) {
if (!mgInProgress) {
// prepare connections of alter nodes
prepareAlterConnections(alterList);
} else {
// check joining node down
updateAlterConnections(alterList);
}
}
if (alterList.isEmpty()) { // end of migration
mgState = MigrationState.DONE;
mgInProgress = false;
}
}
/* ENABLE_MIGRATION end */
}
// Called by CacheManger to add the memcached server group.
public void setCacheNodesChange(List<InetSocketAddress> addrs) {
List<InetSocketAddress> old = cacheNodesChange.getAndSet(addrs);
if (old != null) {
getLogger().info("Ignored previous cache nodes change.");
}
/* ENABLE_MIGRATION if */
old = delayedAlterNodesChange.getAndSet(null);
if (old != null) {
alterNodesChange.set(old);
}
/* ENABLE_MIGRATION end */
selector.wakeup();
}
/* ENABLE_MIGRATION if */
/* Called by CacheManger to add the alter memcached server group. */
public void setAlterNodesChange(List<InetSocketAddress> addrs, boolean readingCacheList) {
if (readingCacheList) {
List<InetSocketAddress> old = delayedAlterNodesChange.getAndSet(addrs);
if (old != null) {
getLogger().info("Ignored previous delayed alter nodes change.");
}
} else {
List<InetSocketAddress> old = alterNodesChange.getAndSet(addrs);
if (old != null) {
getLogger().info("Ignored previous alter nodes change.");
}
delayedAlterNodesChange.set(null);
selector.wakeup();
}
}
public void prepareAlterConnections(List<InetSocketAddress> addrs) throws IOException {
getLogger().info("Prepare connection of alter nodes. addrs=" + addrs);
List<MemcachedNode> alterNodes = new ArrayList<>();
if (mgType == MigrationType.JOIN) {
for (SocketAddress sa : addrs) {
alterNodes.add(makeMemcachedNode(connName, sa));
}
} else { // MigrationType.LEAVE
for (MemcachedNode node : locator.getAll()) {
if (addrs.contains(node.getSocketAddress())) {
alterNodes.add(node);
}
}
}
locator.prepareMigration(alterNodes, mgType);
mgInProgress = true;
}
private void updateAlterConnections(List<InetSocketAddress> addrs) throws IOException {
List<MemcachedNode> attachNodes = new ArrayList<>();
List<MemcachedNode> removeNodes = new ArrayList<>();
for (MemcachedNode node : locator.getAlterAll()) {
if (addrs.contains(node.getSocketAddress())) {
addrs.remove(node.getSocketAddress());
} else {
if (mgType == MigrationType.JOIN) {
removeNodes.add(node);
}
}
}
if (mgType == MigrationType.JOIN) {
for (MemcachedNode node : locator.getAll()) {
if (addrs.contains(node.getSocketAddress())) {
addrs.remove(node.getSocketAddress());
}
}
}
/* ENABLE_REPLICATION if */
if (arcusReplEnabled) {
// Make connections to the newly added alter nodes with slave role.
for (SocketAddress sa : addrs) {
attachNodes.add(makeMemcachedNode(connName, sa));
getLogger().info("Address of new alter node to attach: %s.", sa.toString());
}
}
/* ENABLE_REPLICATION end */
// Update the hash.
locator.updateAlter(attachNodes, removeNodes);
// Remove the unavailable nodes.
handleNodesToRemove(removeNodes);
}
/* ENABLE_MIGRATION end */
// Handle the memcached server group that need delayed switchover.
private void handleDelayedSwitchover() {
if (!delayedSwitchoverGroups.isEmpty()) {
delayedSwitchoverGroups.switchover();
}
}
// Handle any requests that have been made against the client.
private void handleInputQueue() {
if (!addedQueue.isEmpty()) {
getLogger().debug("Handling queue");
// If there's stuff in the added queue. Try to process it.
Collection<MemcachedNode> toAdd = new HashSet<>();
// Transfer the queue into a hashset. There are very likely more
// additions than there are nodes.
Collection<MemcachedNode> todo = new HashSet<>();
MemcachedNode node;
while ((node = addedQueue.poll()) != null) {
todo.add(node);
}
// Now process the queue.
for (MemcachedNode qa : todo) {
boolean readyForIO = false;
if (qa.isActive()) {
if (qa.getCurrentWriteOp() != null) {
readyForIO = true;
getLogger().debug("Handling queued write %s", qa);
}
} else {
toAdd.add(qa);
}
qa.copyInputQueue();
if (readyForIO) {
try {
if (qa.getWbuf().hasRemaining()) {
handleWrites(qa);
}
} catch (IOException e) {
getLogger().warn("Exception handling write", e);
lostConnection(qa, ReconnDelay.DEFAULT, "exception handling write");
}
}
qa.fixupOps();
}
addedQueue.addAll(toAdd);
}
}
/**
* Add a connection observer.
*
* @return whether the observer was successfully added
*/
public boolean addObserver(ConnectionObserver obs) {
return connObservers.add(obs);
}
/**
* Remove a connection observer.
*
* @return true if the observer existed and now doesn't
*/
public boolean removeObserver(ConnectionObserver obs) {
return connObservers.remove(obs);
}
private void connected(MemcachedNode qa) {
assert qa.getChannel().isConnected() : "Not connected.";
int rt = qa.getReconnectCount();
qa.connected();
for (ConnectionObserver observer : connObservers) {
observer.connectionEstablished(qa.getSocketAddress(), rt);
}
}
private void lostConnection(MemcachedNode qa, ReconnDelay type, String cause) {
queueReconnect(qa, type, cause);
for (ConnectionObserver observer : connObservers) {
observer.connectionLost(qa.getSocketAddress());
}
}
// Handle IO for a specific selector. Any IOException will cause a
// reconnect
private void handleIO(SelectionKey sk) {
MemcachedNode qa = (MemcachedNode) sk.attachment();
try {
getLogger().debug(
"Handling IO for: %s (r=%s, w=%s, c=%s, op=%s)",
sk, sk.isReadable(), sk.isWritable(),
sk.isConnectable(), sk.attachment());
if (sk.isConnectable()) {
getLogger().info("Connection state changed for %s", qa);
final SocketChannel channel = qa.getChannel();
if (channel.finishConnect()) {
connected(qa);
addedQueue.offer(qa);
if (qa.getWbuf().hasRemaining()) {
handleWrites(qa);
}
} else {
assert !channel.isConnected() : "connected";
}
} else {
if (sk.isValid() && sk.isReadable()) {
handleReads(qa);
}
if (sk.isValid() && sk.isWritable()) {
handleWrites(qa);
}
}
} catch (ClosedChannelException e) {
// Note, not all channel closes end up here
getLogger().warn("Closed channel. "
+ "Queueing reconnect on %s", qa, e);
lostConnection(qa, ReconnDelay.DEFAULT, "closed channel");
} catch (ConnectException e) {
// Failures to establish a connection should attempt a reconnect
// without signaling the observers.
getLogger().warn("Reconnecting due to failure to connect to %s", qa, e);
queueReconnect(qa, ReconnDelay.DEFAULT, "failure to connect");
} catch (OperationException e) {
qa.setupForAuth("operation exception"); // noop if !shouldAuth
getLogger().warn("Reconnection due to exception " +
"handling a memcached exception on %s.", qa, e);
lostConnection(qa, ReconnDelay.IMMEDIATE, "operation exception");
} catch (Exception e) {
// Any particular error processing an item should simply
// cause us to reconnect to the server.
//
// One cause is just network oddness or servers
// restarting, which lead here with IOException
qa.setupForAuth("due to exception"); // noop if !shouldAuth
getLogger().warn("Reconnecting due to exception on %s", qa, e);
lostConnection(qa, ReconnDelay.DEFAULT, e.getMessage());
}
qa.fixupOps();
}
private void handleWrites(MemcachedNode qa)
throws IOException {
/* ENABLE_REPLICATION if */
if (arcusReplEnabled) {
if (qa.getReplicaGroup().isDelayedSwitchover()) {
return;
}
}
/* ENABLE_REPLICATION end */
qa.fillWriteBuffer(optimizeGetOp);
boolean canWriteMore = qa.getBytesRemainingToWrite() > 0;
while (canWriteMore) {
int wrote = qa.writeSome();
qa.fillWriteBuffer(optimizeGetOp);
canWriteMore = wrote > 0 && qa.getBytesRemainingToWrite() > 0;
}
}
private void handleReads(MemcachedNode qa)
throws IOException {
Operation currentOp = qa.getCurrentReadOp();
ByteBuffer rbuf = qa.getRbuf();
final SocketChannel channel = qa.getChannel();
int read = channel.read(rbuf);
while (read > 0) {
getLogger().debug("Read %d bytes", read);
((Buffer) rbuf).flip();
while (rbuf.remaining() > 0) {
if (currentOp == null) {
throw new IllegalStateException("No read operation.");
}
currentOp.readFromBuffer(rbuf);
OpLatencyMonitor.getInstance().recordLatency(currentOp.getStartTime());
if (currentOp.getState() == OperationState.COMPLETE) {
getLogger().debug("Completed read op: %s and giving the next %d bytes",
currentOp, rbuf.remaining());
Operation op = qa.removeCurrentReadOp();
assert op == currentOp : "Expected to pop " + currentOp + " got " + op;