/
InternalPartitionServiceImpl.java
1660 lines (1442 loc) · 66.7 KB
/
InternalPartitionServiceImpl.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
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
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* 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.
*/
package com.hazelcast.internal.partition.impl;
import com.hazelcast.cluster.ClusterState;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.HazelcastInstanceNotActiveException;
import com.hazelcast.core.ICompletableFuture;
import com.hazelcast.core.Member;
import com.hazelcast.core.MemberLeftException;
import com.hazelcast.core.MigrationListener;
import com.hazelcast.instance.Node;
import com.hazelcast.internal.cluster.ClusterStateListener;
import com.hazelcast.internal.cluster.ClusterVersionListener;
import com.hazelcast.internal.cluster.Versions;
import com.hazelcast.internal.cluster.impl.ClusterServiceImpl;
import com.hazelcast.internal.cluster.impl.operations.TriggerMemberListPublishOp;
import com.hazelcast.internal.metrics.MetricsRegistry;
import com.hazelcast.internal.metrics.Probe;
import com.hazelcast.internal.partition.InternalPartition;
import com.hazelcast.internal.partition.InternalPartitionService;
import com.hazelcast.internal.partition.MigrationInfo;
import com.hazelcast.internal.partition.MigrationInfo.MigrationStatus;
import com.hazelcast.internal.partition.PartitionListener;
import com.hazelcast.internal.partition.PartitionReplica;
import com.hazelcast.internal.partition.PartitionReplicaVersionManager;
import com.hazelcast.internal.partition.PartitionRuntimeState;
import com.hazelcast.internal.partition.PartitionServiceProxy;
import com.hazelcast.internal.partition.PartitionTableView;
import com.hazelcast.internal.partition.operation.AssignPartitions;
import com.hazelcast.internal.partition.operation.FetchPartitionStateOperation;
import com.hazelcast.internal.partition.operation.PartitionStateOperation;
import com.hazelcast.internal.partition.operation.PartitionStateVersionCheckOperation;
import com.hazelcast.internal.partition.operation.ShutdownRequestOperation;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.partition.NoDataMemberInClusterException;
import com.hazelcast.partition.PartitionEvent;
import com.hazelcast.partition.PartitionEventListener;
import com.hazelcast.partition.PartitionLostListener;
import com.hazelcast.spi.EventPublishingService;
import com.hazelcast.spi.ExecutionService;
import com.hazelcast.spi.InternalCompletableFuture;
import com.hazelcast.spi.NodeEngine;
import com.hazelcast.spi.Operation;
import com.hazelcast.spi.OperationService;
import com.hazelcast.spi.PartitionAwareService;
import com.hazelcast.spi.UrgentSystemOperation;
import com.hazelcast.spi.exception.TargetNotMemberException;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.impl.operationexecutor.OperationExecutor;
import com.hazelcast.spi.impl.operationservice.InternalOperationService;
import com.hazelcast.spi.impl.operationservice.impl.OperationServiceImpl;
import com.hazelcast.spi.partition.IPartition;
import com.hazelcast.spi.partition.IPartitionLostEvent;
import com.hazelcast.spi.properties.GroupProperty;
import com.hazelcast.spi.properties.HazelcastProperties;
import com.hazelcast.util.ExceptionUtil;
import com.hazelcast.util.FutureUtil.ExceptionHandler;
import com.hazelcast.util.HashUtil;
import com.hazelcast.util.scheduler.CoalescingDelayedTrigger;
import com.hazelcast.util.scheduler.ScheduledEntry;
import com.hazelcast.version.Version;
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.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import static com.hazelcast.cluster.memberselector.MemberSelectors.DATA_MEMBER_SELECTOR;
import static com.hazelcast.cluster.memberselector.MemberSelectors.NON_LOCAL_MEMBER_SELECTOR;
import static com.hazelcast.internal.partition.impl.MigrationManager.applyMigration;
import static com.hazelcast.util.FutureUtil.logAllExceptions;
import static com.hazelcast.util.FutureUtil.returnWithDeadline;
import static com.hazelcast.util.MapUtil.createHashMap;
import static java.lang.Math.ceil;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Thread.currentThread;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* The {@link InternalPartitionService} implementation.
*/
@SuppressWarnings({"checkstyle:methodcount", "checkstyle:classfanoutcomplexity", "checkstyle:classdataabstractioncoupling"})
public class InternalPartitionServiceImpl implements InternalPartitionService,
EventPublishingService<PartitionEvent, PartitionEventListener<PartitionEvent>>,
PartitionAwareService, ClusterStateListener, ClusterVersionListener {
private static final int PARTITION_OWNERSHIP_WAIT_MILLIS = 10;
private static final String EXCEPTION_MSG_PARTITION_STATE_SYNC_TIMEOUT = "Partition state sync invocation timed out";
private static final int PTABLE_SYNC_TIMEOUT_SECONDS = 10;
private static final int SAFE_SHUTDOWN_MAX_AWAIT_STEP_MILLIS = 1000;
private static final long FETCH_PARTITION_STATE_SECONDS = 5;
private static final long TRIGGER_MASTER_DELAY_MILLIS = 1000;
private final Node node;
private final NodeEngineImpl nodeEngine;
private final ILogger logger;
private final int partitionCount;
private final long partitionMigrationTimeout;
private final PartitionServiceProxy proxy;
private final Lock lock = new ReentrantLock();
private final InternalPartitionListener partitionListener;
private final PartitionStateManager partitionStateManager;
private final MigrationManager migrationManager;
private final PartitionReplicaManager replicaManager;
private final PartitionReplicaStateChecker partitionReplicaStateChecker;
private final PartitionEventManager partitionEventManager;
private final ExceptionHandler partitionStateSyncTimeoutHandler;
/** Determines if a {@link AssignPartitions} is being sent to the master, used to limit partition assignment requests. */
private final AtomicBoolean masterTriggered = new AtomicBoolean(false);
private final CoalescingDelayedTrigger masterTrigger;
private final AtomicReference<CountDownLatch> shutdownLatchRef = new AtomicReference<CountDownLatch>();
private volatile Address latestMaster;
/** Whether the master should fetch the partition tables from other nodes, can happen when node becomes new master. */
private volatile boolean shouldFetchPartitionTables;
public InternalPartitionServiceImpl(Node node) {
HazelcastProperties properties = node.getProperties();
this.partitionCount = properties.getInteger(GroupProperty.PARTITION_COUNT);
this.node = node;
this.nodeEngine = node.nodeEngine;
this.logger = node.getLogger(InternalPartitionService.class);
partitionListener = new InternalPartitionListener(node, this);
partitionStateManager = new PartitionStateManager(node, this, partitionListener);
migrationManager = new MigrationManager(node, this, lock);
replicaManager = new PartitionReplicaManager(node, this);
partitionReplicaStateChecker = new PartitionReplicaStateChecker(node, this);
partitionEventManager = new PartitionEventManager(node);
masterTrigger = new CoalescingDelayedTrigger(nodeEngine.getExecutionService(), TRIGGER_MASTER_DELAY_MILLIS,
2 * TRIGGER_MASTER_DELAY_MILLIS, new Runnable() {
@Override
public void run() {
resetMasterTriggeredFlag();
}
});
partitionStateSyncTimeoutHandler =
logAllExceptions(logger, EXCEPTION_MSG_PARTITION_STATE_SYNC_TIMEOUT, Level.FINEST);
partitionMigrationTimeout = properties.getMillis(GroupProperty.PARTITION_MIGRATION_TIMEOUT);
proxy = new PartitionServiceProxy(nodeEngine, this);
MetricsRegistry metricsRegistry = nodeEngine.getMetricsRegistry();
metricsRegistry.scanAndRegister(this, "partitions");
metricsRegistry.scanAndRegister(partitionStateManager, "partitions");
metricsRegistry.scanAndRegister(migrationManager, "partitions");
metricsRegistry.scanAndRegister(replicaManager, "partitions");
}
@Override
public void init(NodeEngine nodeEngine, Properties properties) {
int partitionTableSendInterval = node.getProperties().getSeconds(GroupProperty.PARTITION_TABLE_SEND_INTERVAL);
if (partitionTableSendInterval <= 0) {
partitionTableSendInterval = 1;
}
ExecutionService executionService = nodeEngine.getExecutionService();
executionService.scheduleWithRepetition(new PublishPartitionRuntimeStateTask(node, this),
partitionTableSendInterval, partitionTableSendInterval, SECONDS);
migrationManager.start();
replicaManager.scheduleReplicaVersionSync(executionService);
}
@Override
public Address getPartitionOwner(int partitionId) {
if (!partitionStateManager.isInitialized()) {
firstArrangement();
}
final InternalPartition partition = partitionStateManager.getPartitionImpl(partitionId);
if (partition.getOwnerReplicaOrNull() == null && !node.isMaster()) {
if (!isClusterFormedByOnlyLiteMembers()) {
triggerMasterToAssignPartitions();
}
}
return partition.getOwnerOrNull();
}
@Override
public Address getPartitionOwnerOrWait(int partitionId) {
Address owner;
while ((owner = getPartitionOwner(partitionId)) == null) {
if (!nodeEngine.isRunning()) {
throw new HazelcastInstanceNotActiveException();
}
ClusterState clusterState = node.getClusterService().getClusterState();
if (!clusterState.isMigrationAllowed()) {
throw new IllegalStateException("Partitions can't be assigned since cluster-state: " + clusterState);
}
if (isClusterFormedByOnlyLiteMembers()) {
throw new NoDataMemberInClusterException(
"Partitions can't be assigned since all nodes in the cluster are lite members");
}
try {
Thread.sleep(PARTITION_OWNERSHIP_WAIT_MILLIS);
} catch (InterruptedException e) {
currentThread().interrupt();
throw ExceptionUtil.rethrow(e);
}
}
return owner;
}
@Override
public PartitionRuntimeState firstArrangement() {
if (!isLocalMemberMaster()) {
triggerMasterToAssignPartitions();
return null;
}
lock.lock();
try {
if (!partitionStateManager.isInitialized()) {
Set<Member> excludedMembers = migrationManager.getShutdownRequestedMembers();
if (partitionStateManager.initializePartitionAssignments(excludedMembers)) {
publishPartitionRuntimeState();
}
}
return createPartitionStateInternal();
} finally {
lock.unlock();
}
}
/** Sends a {@link AssignPartitions} to the master to assign partitions. */
private void triggerMasterToAssignPartitions() {
if (!shouldTriggerMasterToAssignPartitions()) {
return;
}
ClusterServiceImpl clusterService = node.getClusterService();
ClusterState clusterState = clusterService.getClusterState();
if (!clusterState.isMigrationAllowed()) {
logger.warning("Partitions can't be assigned since cluster-state=" + clusterState);
return;
}
final Address masterAddress = latestMaster;
if (masterAddress == null || masterAddress.equals(node.getThisAddress())) {
return;
}
if (masterTriggered.compareAndSet(false, true)) {
InternalOperationService operationService = nodeEngine.getOperationService();
ICompletableFuture<PartitionRuntimeState> future =
operationService.invokeOnTarget(SERVICE_NAME, new AssignPartitions(), masterAddress);
future.andThen(new ExecutionCallback<PartitionRuntimeState>() {
@Override
public void onResponse(PartitionRuntimeState partitionState) {
resetMasterTriggeredFlag();
if (partitionState != null) {
partitionState.setMaster(masterAddress);
processPartitionRuntimeState(partitionState);
}
}
@Override
public void onFailure(Throwable t) {
resetMasterTriggeredFlag();
logger.severe(t);
}
});
masterTrigger.executeWithDelay();
}
}
private boolean shouldTriggerMasterToAssignPartitions() {
ClusterServiceImpl clusterService = node.getClusterService();
return !partitionStateManager.isInitialized() && clusterService.isJoined() && node.getNodeExtension().isStartCompleted();
}
private void resetMasterTriggeredFlag() {
masterTriggered.set(false);
}
private boolean isClusterFormedByOnlyLiteMembers() {
final ClusterServiceImpl clusterService = node.getClusterService();
return clusterService.getMembers(DATA_MEMBER_SELECTOR).isEmpty();
}
/**
* Sets the initial partition table and state version. If any partition has a replica, the partition state manager is
* set to initialized, otherwise {@link #partitionStateManager#isInitialized()} stays uninitialized but the current state
* will be updated nevertheless.
* This method acquires the partition service lock.
*
* @param partitionTable the initial partition table
* @throws IllegalStateException if the partition manager has already been initialized
*/
public void setInitialState(PartitionTableView partitionTable) {
lock.lock();
try {
partitionStateManager.setInitialState(partitionTable);
} finally {
lock.unlock();
}
}
@Override
public int getMemberGroupsSize() {
return partitionStateManager.getMemberGroupsSize();
}
@Probe(name = "maxBackupCount")
@Override
public int getMaxAllowedBackupCount() {
return max(min(getMemberGroupsSize() - 1, InternalPartition.MAX_BACKUP_COUNT), 0);
}
public void updateMemberGroupSize() {
partitionStateManager.updateMemberGroupsSize();
}
@Override
public void memberAdded(Member member) {
logger.fine("Adding " + member);
lock.lock();
try {
latestMaster = node.getClusterService().getMasterAddress();
if (!member.localMember()) {
partitionStateManager.updateMemberGroupsSize();
}
if (isLocalMemberMaster()) {
if (partitionStateManager.isInitialized()) {
migrationManager.triggerControlTask();
}
}
} finally {
lock.unlock();
}
}
@Override
public void memberRemoved(Member member) {
logger.fine("Removing " + member);
lock.lock();
try {
migrationManager.onMemberRemove(member);
replicaManager.cancelReplicaSyncRequestsTo(member);
Address formerMaster = latestMaster;
latestMaster = node.getClusterService().getMasterAddress();
ClusterState clusterState = node.getClusterService().getClusterState();
if (clusterState.isMigrationAllowed() || clusterState.isPartitionPromotionAllowed()) {
partitionStateManager.updateMemberGroupsSize();
boolean isMaster = node.isMaster();
boolean isThisNodeNewMaster = isMaster && !node.getThisAddress().equals(formerMaster);
if (isThisNodeNewMaster) {
assert !shouldFetchPartitionTables;
shouldFetchPartitionTables = true;
}
if (isMaster) {
migrationManager.triggerControlTask();
}
}
} finally {
lock.unlock();
}
}
@Override
public void onClusterStateChange(ClusterState newState) {
if (!newState.isMigrationAllowed()) {
return;
}
if (!partitionStateManager.isInitialized()) {
return;
}
if (!isLocalMemberMaster()) {
return;
}
lock.lock();
try {
if (partitionStateManager.isInitialized()
&& migrationManager.shouldTriggerRepartitioningWhenClusterStateAllowsMigration()) {
migrationManager.triggerControlTask();
}
} finally {
lock.unlock();
}
}
@Override
public void onClusterVersionChange(Version newVersion) {
// RU_COMPAT_3_11
if (newVersion.isEqualTo(Versions.V3_12)) {
lock.lock();
try {
if (!partitionStateManager.isInitialized()) {
return;
}
for (int pid = 0; pid < getPartitionCount(); pid++) {
InternalPartitionImpl partition = partitionStateManager.getPartitionImpl(pid);
PartitionReplica[] replicaMembers = partition.getReplicas();
for (PartitionReplica member : replicaMembers) {
if (member == null) {
continue;
}
if (PartitionReplica.UNKNOWN_UID.equals(member.uuid())) {
throw new IllegalStateException("Unknown uuid: " + member);
}
}
}
migrationManager.onClusterVersionChange(newVersion);
} finally {
lock.unlock();
}
}
}
@Override
public PartitionRuntimeState createPartitionState() {
if (!isFetchMostRecentPartitionTableTaskRequired()) {
return createPartitionStateInternal();
}
return null;
}
/**
* Returns a copy of the partition table or {@code null} if not initialized. This method will acquire the partition service
* lock.
*/
public PartitionRuntimeState createPartitionStateInternal() {
lock.lock();
try {
if (!partitionStateManager.isInitialized()) {
return null;
}
List<MigrationInfo> completedMigrations = migrationManager.getCompletedMigrationsCopy();
InternalPartition[] partitions = partitionStateManager.getPartitions();
PartitionRuntimeState state = new PartitionRuntimeState(partitions, completedMigrations, getPartitionStateVersion());
state.setActiveMigration(migrationManager.getActiveMigration());
return state;
} finally {
lock.unlock();
}
}
/**
* Creates a transient PartitionRuntimeState to commit given migration.
* Result migration is applied to partition table and migration is added to completed-migrations set.
* Version of created partition table is incremented by 1.
*/
PartitionRuntimeState createMigrationCommitPartitionState(MigrationInfo migrationInfo) {
lock.lock();
try {
if (!partitionStateManager.isInitialized()) {
return null;
}
List<MigrationInfo> completedMigrations = migrationManager.getCompletedMigrationsCopy();
InternalPartition[] partitions = partitionStateManager.getPartitionsCopy();
int partitionId = migrationInfo.getPartitionId();
InternalPartitionImpl partition = (InternalPartitionImpl) partitions[partitionId];
applyMigration(partition, migrationInfo);
migrationInfo.setStatus(MigrationStatus.SUCCESS);
completedMigrations.add(migrationInfo);
int committedVersion = getPartitionStateVersion() + 1;
return new PartitionRuntimeState(partitions, completedMigrations, committedVersion);
} finally {
lock.unlock();
}
}
/**
* Creates a transient {@link PartitionRuntimeState} to commit promotions by applying the {@code migrationInfos}.
* The partition table version is incremented by number of promotions.
* This method will acquire the partition service lock.
*
* @param migrationInfos the promotions to be executed on the destination
* @return the partition table with the executed migrations or {@code null} if the partitions are not initialized (assigned)
*/
PartitionRuntimeState createPromotionCommitPartitionState(Collection<MigrationInfo> migrationInfos) {
lock.lock();
try {
if (!partitionStateManager.isInitialized()) {
return null;
}
List<MigrationInfo> completedMigrations = migrationManager.getCompletedMigrationsCopy();
InternalPartition[] partitions = partitionStateManager.getPartitionsCopy();
for (MigrationInfo migrationInfo : migrationInfos) {
int partitionId = migrationInfo.getPartitionId();
InternalPartitionImpl partition = (InternalPartitionImpl) partitions[partitionId];
applyMigration(partition, migrationInfo);
migrationInfo.setStatus(MigrationStatus.SUCCESS);
}
// each promotion increments version by 2
int committedVersion = getPartitionStateVersion() + migrationInfos.size() * 2;
return new PartitionRuntimeState(partitions, completedMigrations, committedVersion);
} finally {
lock.unlock();
}
}
/**
* Called on the master node to publish the current partition state to all cluster nodes. It will not publish the partition
* state if the partitions have not yet been initialized, there is ongoing repartitioning or a node is joining the cluster.
*/
@SuppressWarnings("checkstyle:npathcomplexity")
void publishPartitionRuntimeState() {
if (!partitionStateManager.isInitialized()) {
// do not send partition state until initialized!
return;
}
if (!isLocalMemberMaster()) {
return;
}
if (!areMigrationTasksAllowed()) {
// migration is disabled because of a member leave, wait till enabled!
return;
}
PartitionRuntimeState partitionState = createPartitionStateInternal();
if (partitionState == null) {
return;
}
if (logger.isFineEnabled()) {
logger.fine("Publishing partition state, version: " + partitionState.getVersion());
}
PartitionStateOperation op = new PartitionStateOperation(partitionState, false);
OperationService operationService = nodeEngine.getOperationService();
Collection<Member> members = node.clusterService.getMembers();
for (Member member : members) {
if (!member.localMember()) {
try {
operationService.send(op, member.getAddress());
} catch (Exception e) {
logger.finest(e);
}
}
}
}
void sendPartitionRuntimeState(Address target) {
if (!isLocalMemberMaster()) {
return;
}
assert partitionStateManager.isInitialized();
assert areMigrationTasksAllowed();
PartitionRuntimeState partitionState = createPartitionStateInternal();
assert partitionState != null;
if (logger.isFineEnabled()) {
logger.fine("Sending partition state, version: " + partitionState.getVersion() + ", to " + target);
}
OperationService operationService = nodeEngine.getOperationService();
PartitionStateOperation op = new PartitionStateOperation(partitionState, true);
operationService.invokeOnTarget(SERVICE_NAME, op, target);
}
void checkClusterPartitionRuntimeStates() {
if (!partitionStateManager.isInitialized()) {
return;
}
if (!isLocalMemberMaster()) {
return;
}
if (!areMigrationTasksAllowed()) {
// migration is disabled because of a member leave, wait till enabled!
return;
}
int partitionStateVersion = getPartitionStateVersion();
if (logger.isFineEnabled()) {
logger.fine("Checking partition state, version: " + partitionStateVersion);
}
OperationService operationService = nodeEngine.getOperationService();
Collection<Member> members = node.clusterService.getMembers();
for (final Member member : members) {
if (!member.localMember()) {
Operation op = new PartitionStateVersionCheckOperation(partitionStateVersion);
ICompletableFuture<Boolean> future = operationService.invokeOnTarget(SERVICE_NAME, op, member.getAddress());
future.andThen(new ExecutionCallback<Boolean>() {
@Override
public void onResponse(Boolean response) {
if (!Boolean.TRUE.equals(response)) {
logger.fine(member + " has a stale partition state. Will send the most recent partition state now.");
sendPartitionRuntimeState(member.getAddress());
}
}
@Override
public void onFailure(Throwable t) {
logger.fine("Failure while checking partition state on " + member, t);
sendPartitionRuntimeState(member.getAddress());
}
});
}
}
}
/**
* Called on the master node to send the partition tables to other cluster members. It will not publish the partition
* state if the partitions have not yet been initialized.
* Waits for {@value PTABLE_SYNC_TIMEOUT_SECONDS} for the members to respond to the partition state operation.
*
* @return {@code true} if all cluster members have synced their partition tables, {@code false} otherwise.
*/
// RU_COMPAT_3_11
@SuppressWarnings("checkstyle:npathcomplexity")
boolean syncPartitionRuntimeState() {
assert !((ReentrantLock) lock).isHeldByCurrentThread();
assert partitionStateManager.isInitialized();
assert node.isMaster();
PartitionRuntimeState partitionState = createPartitionStateInternal();
assert partitionState != null;
if (logger.isFineEnabled()) {
logger.fine("Sync'ing partition state, version: " + partitionState.getVersion());
}
OperationService operationService = nodeEngine.getOperationService();
Collection<Member> members = node.clusterService.getMembers();
Collection<Future<Boolean>> futures = new ArrayList<Future<Boolean>>(members.size());
for (Member member : members) {
if (!member.localMember()) {
PartitionStateOperation op = new PartitionStateOperation(partitionState, true);
InternalCompletableFuture<Boolean> future =
operationService.invokeOnTarget(SERVICE_NAME, op, member.getAddress());
futures.add(future);
}
}
Collection<Boolean> results = returnWithDeadline(futures, PTABLE_SYNC_TIMEOUT_SECONDS,
SECONDS, partitionStateSyncTimeoutHandler);
if (futures.size() != results.size()) {
return false;
}
for (Boolean result : results) {
if (!result) {
return false;
}
}
return true;
}
/**
* Sets the {@code partitionState} if the node is started and the state is sent by the master known by this node.
*
* @param partitionState the new partition state
* @return {@code true} if the partition state was applied
*/
public boolean processPartitionRuntimeState(final PartitionRuntimeState partitionState) {
Address sender = partitionState.getMaster();
if (!node.getNodeExtension().isStartCompleted()) {
logger.warning("Ignoring received partition table, startup is not completed yet. Sender: " + sender);
return false;
}
if (!validateSenderIsMaster(sender, "partition table update")) {
return false;
}
return applyNewPartitionTable(partitionState.getPartitionTable(), partitionState.getVersion(),
partitionState.getCompletedMigrations(), sender);
}
private boolean validateSenderIsMaster(Address sender, String messageType) {
Address thisAddress = node.getThisAddress();
if (thisAddress.equals(latestMaster) && !thisAddress.equals(sender)) {
logger.warning("This is the master node and received " + messageType + " from " + sender
+ ". Ignoring incoming state! ");
return false;
} else {
if (!isMemberMaster(sender)) {
if (node.clusterService.getMember(sender) == null) {
logger.severe("Received " + messageType + " from an unknown member!"
+ " => Sender: " + sender + "! ");
} else {
logger.warning("Received " + messageType + ", but its sender doesn't seem to be master!"
+ " => Sender: " + sender + "! (Ignore if master node has changed recently.)");
}
return false;
}
}
return true;
}
/**
* Applies the {@code partitionState} sent by the {@code sender} if the new state is newer than the current one
* and finalizes the migrations.
* This method does not validate the sender. It is caller method's responsibility.
* This method will acquire the partition service lock.
*
* @param partitionTable the new partition table
* @param newVersion new partition state version
* @param completedMigrations latest completed migrations
* @param sender the sender of the new partition state
* @return {@code true} if the partition state version is higher than the current one and was applied or
* if the partition state version is same as the current one
*/
private boolean applyNewPartitionTable(PartitionReplica[][] partitionTable,
int newVersion, Collection<MigrationInfo> completedMigrations, Address sender) {
try {
if (!lock.tryLock(PTABLE_SYNC_TIMEOUT_SECONDS, SECONDS)) {
return false;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
try {
int currentVersion = partitionStateManager.getVersion();
if (newVersion < currentVersion) {
if (logger.isFineEnabled()) {
logger.fine("Already applied partition state change. Local version: " + currentVersion
+ ", Master version: " + newVersion + " Master: " + sender);
}
return false;
} else if (newVersion == currentVersion) {
if (logger.isFineEnabled()) {
logger.fine("Already applied partition state change. Version: " + currentVersion + ", Master: " + sender);
}
return true;
}
// RU_COMPAT_3_11
updatePartitionTableReplicasForCompatibility(partitionTable);
requestMemberListUpdateIfUnknownMembersFound(sender, partitionTable);
updatePartitionsAndFinalizeMigrations(partitionTable, newVersion, completedMigrations);
return true;
} finally {
lock.unlock();
}
}
// RU_COMPAT_3_11
private void updatePartitionTableReplicasForCompatibility(PartitionReplica[][] partitionTable) {
ClusterServiceImpl clusterService = node.getClusterService();
Version version = clusterService.getClusterVersion();
boolean compatibilityMode = version.isLessThan(Versions.V3_12);
for (int partitionId = 0; partitionId < partitionCount; partitionId++) {
PartitionReplica[] replicas = partitionTable[partitionId];
if (compatibilityMode) {
for (int ix = 0; ix < replicas.length; ix++) {
if (replicas[ix] == null) {
continue;
}
if (PartitionReplica.UNKNOWN_UID.equals(replicas[ix].uuid())) {
Address address = replicas[ix].address();
Member member = clusterService.getMember(address);
if (member == null) {
// We don't know this member yet. But it's guaranteed we will learn it
// before cluster version is upgraded, since version upgrade transaction
// will fail until we get the latest member list.
continue;
}
replicas[ix] = PartitionReplica.from(member);
}
}
} else {
for (PartitionReplica replica : replicas) {
assert replica == null || !PartitionReplica.UNKNOWN_UID.equals(replica.uuid())
: "Invalid replica: " + replica;
}
}
}
}
private void requestMemberListUpdateIfUnknownMembersFound(Address sender, PartitionReplica[][] partitionTable) {
ClusterServiceImpl clusterService = node.clusterService;
ClusterState clusterState = clusterService.getClusterState();
Set<PartitionReplica> unknownReplicas = new HashSet<PartitionReplica>();
for (PartitionReplica[] replicas : partitionTable) {
for (int index = 0; index < InternalPartition.MAX_REPLICA_COUNT; index++) {
PartitionReplica replica = replicas[index];
if (replica == null) {
continue;
}
if (node.clusterService.getMember(replica.address(), replica.uuid()) == null
&& (clusterState.isJoinAllowed()
|| !clusterService.isMissingMember(replica.address(), replica.uuid()))) {
unknownReplicas.add(replica);
}
}
}
if (!unknownReplicas.isEmpty()) {
if (logger.isWarningEnabled()) {
StringBuilder s = new StringBuilder("Following unknown addresses are found in partition table")
.append(" sent from master[").append(sender).append("].")
.append(" (Probably they have recently joined or left the cluster.)")
.append(" {");
for (PartitionReplica replica : unknownReplicas) {
s.append("\n\t").append(replica);
}
s.append("\n}");
logger.warning(s.toString());
}
Address masterAddress = node.getClusterService().getMasterAddress();
// If node is shutting down, master can be null.
if (masterAddress != null && !masterAddress.equals(node.getThisAddress())) {
// unknown addresses found in partition table, request a new member-list from master
nodeEngine.getOperationService().send(new TriggerMemberListPublishOp(), masterAddress);
}
}
}
/**
* Updates all partitions and version, updates (adds and retains) the completed migrations and finalizes the active
* migration if it is equal to any completed.
*
* @see MigrationManager#scheduleActiveMigrationFinalization(MigrationInfo)
* @param partitionTable new partition table
* @param version partition state version
* @param completedMigrations completed migrations
*/
private void updatePartitionsAndFinalizeMigrations(PartitionReplica[][] partitionTable,
int version, Collection<MigrationInfo> completedMigrations) {
for (int partitionId = 0; partitionId < partitionCount; partitionId++) {
PartitionReplica[] replicas = partitionTable[partitionId];
partitionStateManager.updateReplicas(partitionId, replicas);
}
partitionStateManager.setVersion(version);
for (MigrationInfo migration : completedMigrations) {
boolean added = migrationManager.addCompletedMigration(migration);
if (added) {
migrationManager.scheduleActiveMigrationFinalization(migration);
}
}
if (logger.isFineEnabled()) {
logger.fine("Applied partition state update with version: " + version);
}
migrationManager.retainCompletedMigrations(completedMigrations);
if (!partitionStateManager.setInitialized()) {
node.getNodeExtension().onPartitionStateChange();
}
}
@SuppressWarnings({"checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity"})
public boolean applyCompletedMigrations(Collection<MigrationInfo> migrations, Address sender) {
if (!validateSenderIsMaster(sender, "completed migrations")) {
return false;
}
lock.lock();
try {
if (!partitionStateManager.isInitialized()) {
if (logger.isFineEnabled()) {
logger.fine("Cannot apply completed migrations until partition table is initialized. "
+ "Completed migrations: " + migrations);
}
return false;
}
boolean appliedAllMigrations = true;
for (MigrationInfo migration : migrations) {
int currentVersion = partitionStateManager.getVersion();
if (migration.getFinalPartitionVersion() <= currentVersion) {
if (logger.isFinestEnabled()) {
logger.finest("Already applied migration commit. Local version: " + currentVersion
+ ", Commit version: " + migration.getFinalPartitionVersion() + " Master: " + sender);
}
continue;
}
if (migration.getInitialPartitionVersion() != currentVersion) {
logger.fine("Cannot apply migration commit! Expected version: " + migration.getInitialPartitionVersion()
+ ", current version: " + currentVersion + ", final version: " + migration.getFinalPartitionVersion()
+ ", Master: " + sender);
appliedAllMigrations = false;
break;
}
boolean added = migrationManager.addCompletedMigration(migration);
assert added : "Migration: " + migration;
partitionStateManager.incrementVersion(migration.getPartitionVersionIncrement());
if (migration.getStatus() == MigrationStatus.SUCCESS) {
if (logger.isFineEnabled()) {
logger.fine("Applying completed migration " + migration);
}
InternalPartitionImpl partition = partitionStateManager.getPartitionImpl(migration.getPartitionId());
applyMigration(partition, migration);
}
migrationManager.scheduleActiveMigrationFinalization(migration);
}
if (logger.isFineEnabled()) {
logger.fine("Applied completed migrations with partition state version: " + partitionStateManager.getVersion());
}
migrationManager.retainCompletedMigrations(migrations);
node.getNodeExtension().onPartitionStateChange();
return appliedAllMigrations;
} finally {
lock.unlock();
}
}
@Override
public IPartition[] getPartitions() {
IPartition[] result = new IPartition[partitionCount];
System.arraycopy(partitionStateManager.getPartitions(), 0, result, 0, partitionCount);
return result;
}
@Override
public InternalPartition[] getInternalPartitions() {
return partitionStateManager.getPartitions();
}
@Override
public InternalPartition getPartition(int partitionId) {
return getPartition(partitionId, true);
}
@Override
public InternalPartition getPartition(int partitionId, boolean triggerOwnerAssignment) {
InternalPartitionImpl p = partitionStateManager.getPartitionImpl(partitionId);
if (triggerOwnerAssignment && p.getOwnerReplicaOrNull() == null) {
// probably ownerships are not set yet.
// force it.
getPartitionOwner(partitionId);
}