-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
ClusterManager.java
1249 lines (1118 loc) · 44 KB
/
ClusterManager.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) 2002-2015 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.ha;
import org.w3c.dom.Document;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.IntFunction;
import java.util.function.Predicate;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.neo4j.backup.OnlineBackupSettings;
import org.neo4j.cluster.ClusterSettings;
import org.neo4j.cluster.InstanceId;
import org.neo4j.cluster.client.ClusterClient;
import org.neo4j.cluster.client.ClusterClientModule;
import org.neo4j.cluster.client.Clusters;
import org.neo4j.cluster.client.ClustersXMLSerializer;
import org.neo4j.cluster.com.NetworkReceiver;
import org.neo4j.cluster.com.NetworkSender;
import org.neo4j.cluster.member.ClusterMemberEvents;
import org.neo4j.cluster.member.ClusterMemberListener;
import org.neo4j.cluster.protocol.election.NotElectableElectionCredentialsProvider;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.TransactionFailureException;
import org.neo4j.graphdb.config.Setting;
import org.neo4j.graphdb.factory.GraphDatabaseBuilder;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.graphdb.factory.HighlyAvailableGraphDatabaseFactory;
import org.neo4j.kernel.configuration.Settings;
import org.neo4j.helpers.collection.Iterables;
import org.neo4j.helpers.collection.MapUtil;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.ha.HaSettings;
import org.neo4j.kernel.ha.HighlyAvailableGraphDatabase;
import org.neo4j.kernel.ha.UpdatePuller;
import org.neo4j.kernel.ha.cluster.HighAvailabilityMemberState;
import org.neo4j.kernel.ha.cluster.member.ClusterMember;
import org.neo4j.kernel.ha.cluster.member.ClusterMembers;
import org.neo4j.kernel.ha.cluster.member.ObservedClusterMembers;
import org.neo4j.kernel.ha.cluster.modeswitch.HighAvailabilityModeSwitcher;
import org.neo4j.kernel.ha.com.master.Slaves;
import org.neo4j.kernel.impl.factory.GraphDatabaseFacadeFactory;
import org.neo4j.kernel.impl.logging.LogService;
import org.neo4j.kernel.impl.logging.NullLogService;
import org.neo4j.kernel.impl.transaction.log.rotation.StoreFlusher;
import org.neo4j.kernel.impl.util.Dependencies;
import org.neo4j.kernel.lifecycle.LifeSupport;
import org.neo4j.kernel.lifecycle.Lifecycle;
import org.neo4j.kernel.lifecycle.LifecycleAdapter;
import org.neo4j.kernel.monitoring.Monitors;
import org.neo4j.logging.Log;
import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableMap;
import static org.neo4j.helpers.ArrayUtil.contains;
import static org.neo4j.helpers.collection.Iterables.count;
import static org.neo4j.helpers.collection.MapUtil.stringMap;
import static org.neo4j.io.fs.FileUtils.copyRecursively;
/**
* Utility for spinning up an HA cluster inside the same JVM. Only intended for being used in tests
* as well as other tools that may need a cluster conveniently within the same JVM.
*/
public class ClusterManager
extends LifecycleAdapter
{
/**
* Network Flags for passing into {@link ManagedCluster#fail(HighlyAvailableGraphDatabase, NetworkFlag...)}
*/
public enum NetworkFlag
{
/**
* Fail outgoing cluster network traffic.
*/
OUT,
/**
* Fail incoming cluster network traffic.
*/
IN;
}
public static final Map<String,String> CONFIG_FOR_SINGLE_JVM_CLUSTER = unmodifiableMap( stringMap(
GraphDatabaseSettings.pagecache_memory.name(), "8m" ) );
public interface StoreDirInitializer
{
void initializeStoreDir( int serverId, File storeDir ) throws IOException;
}
/**
* Provides a specification of which clusters to start in {@link ClusterManager#start()}.
*/
public interface Provider
{
Clusters clusters() throws Throwable;
}
public interface RepairKit
{
HighlyAvailableGraphDatabase repair() throws Throwable;
}
public static IntFunction<String> constant( final String value )
{
return ignored -> value;
}
private final File root;
private final Map<String,IntFunction<String>> commonConfig;
private final Map<String,ManagedCluster> clusterMap = new HashMap<>();
private final Provider clustersProvider;
private final HighlyAvailableGraphDatabaseFactory dbFactory;
private final StoreDirInitializer storeDirInitializer;
LifeSupport life;
private ClusterManager( Builder builder )
{
this.clustersProvider = builder.provider;
this.root = builder.root;
this.commonConfig = withDefaults( builder.commonConfig );
this.dbFactory = builder.factory;
this.storeDirInitializer = builder.initializer;
}
private Map<String,IntFunction<String>> withDefaults( Map<String,IntFunction<String>> commonConfig )
{
Map<String,IntFunction<String>> result = new HashMap<>();
for ( Map.Entry<String,String> conf : CONFIG_FOR_SINGLE_JVM_CLUSTER.entrySet() )
{
result.put( conf.getKey(), constant( conf.getValue() ) );
}
result.putAll( commonConfig );
return result;
}
/**
* Provider pointing out an XML file to read.
*
* @param clustersXml the XML file containing the cluster specifications.
*/
public static Provider fromXml( final URI clustersXml )
{
return () -> {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document clustersXmlDoc = documentBuilder.parse( clustersXml.toURL().openStream() );
return new ClustersXMLSerializer( documentBuilder ).read( clustersXmlDoc );
};
}
/**
* Provides a cluster specification with default values
*
* @param memberCount the total number of members in the cluster to start.
*/
public static Provider clusterOfSize( int memberCount )
{
Clusters.Cluster cluster = new Clusters.Cluster( "neo4j.ha" );
for ( int i = 0; i < memberCount; i++ )
{
cluster.getMembers().add( new Clusters.Member( 5001 + i, true ) );
}
final Clusters clusters = new Clusters();
clusters.getClusters().add( cluster );
return provided( clusters );
}
/**
* Provides a cluster specification with default values
*
* @param haMemberCount the total number of members in the cluster to start.
*/
public static Provider clusterWithAdditionalClients( int haMemberCount, int additionalClientCount )
{
Clusters.Cluster cluster = new Clusters.Cluster( "neo4j.ha" );
int counter = 0;
for ( int i = 0; i < haMemberCount; i++, counter++ )
{
cluster.getMembers().add( new Clusters.Member( 5001 + counter, true ) );
}
for ( int i = 0; i < additionalClientCount; i++, counter++ )
{
cluster.getMembers().add( new Clusters.Member( 5001 + counter, false ) );
}
final Clusters clusters = new Clusters();
clusters.getClusters().add( cluster );
return provided( clusters );
}
/**
* Provides a cluster specification with default values
*
* @param haMemberCount the total number of members in the cluster to start.
*/
public static Provider clusterWithAdditionalArbiters( int haMemberCount, int arbiterCount )
{
Clusters.Cluster cluster = new Clusters.Cluster( "neo4j.ha" );
int counter = 0;
for ( int i = 0; i < arbiterCount; i++, counter++ )
{
cluster.getMembers().add( new Clusters.Member( 5001 + counter, false ) );
}
for ( int i = 0; i < haMemberCount; i++, counter++ )
{
cluster.getMembers().add( new Clusters.Member( 5001 + counter, true ) );
}
final Clusters clusters = new Clusters();
clusters.getClusters().add( cluster );
return provided( clusters );
}
public static Provider provided( final Clusters clusters )
{
return () -> clusters;
}
/**
* The current master sees this many slaves as available.
*
* @param count number of slaves to see as available.
*/
public static Predicate<ManagedCluster> masterSeesSlavesAsAvailable( final int count )
{
return new Predicate<ClusterManager.ManagedCluster>()
{
@Override
public boolean test( ManagedCluster cluster )
{
return count( cluster.getMaster().getDependencyResolver().resolveDependency( Slaves.class )
.getSlaves() ) >= count;
}
@Override
public String toString()
{
return "Master should see " + count + " slaves as available";
}
};
}
/**
* The current master sees all slaves in the cluster as available.
* Based on the total number of members in the cluster.
*/
public static Predicate<ManagedCluster> masterSeesAllSlavesAsAvailable()
{
return new Predicate<ClusterManager.ManagedCluster>()
{
@Override
public boolean test( ManagedCluster cluster )
{
return count( cluster.getMaster().getDependencyResolver().resolveDependency( Slaves.class )
.getSlaves() ) >= cluster.size() - 1;
}
@Override
public String toString()
{
return "Master should see all slaves as available";
}
};
}
/**
* There must be a master available. Optionally exceptions, useful for when awaiting a
* re-election of a different master.
*/
public static Predicate<ManagedCluster> masterAvailable( final HighlyAvailableGraphDatabase... except )
{
final Collection<HighlyAvailableGraphDatabase> excludedNodes = asList( except );
return new Predicate<ClusterManager.ManagedCluster>()
{
@Override
public boolean test( ManagedCluster cluster )
{
Predicate<HighlyAvailableGraphDatabase> filterMasterPredicate =
node -> !excludedNodes.contains( node ) &&
node.isAvailable( 0 ) &&
node.isMaster();
return Iterables.filter( filterMasterPredicate, cluster.getAllMembers() ).iterator().hasNext();
}
@Override
public String toString()
{
return "There's an available master";
}
};
}
/**
* The current master sees this many members (including itself).
*
* @param count number of members to see.
*/
public static Predicate<ManagedCluster> masterSeesMembers( final int count )
{
return new Predicate<ClusterManager.ManagedCluster>()
{
@Override
public boolean test( ManagedCluster cluster )
{
ClusterMembers members =
cluster.getMaster().getDependencyResolver().resolveDependency( ClusterMembers.class );
return count( members.getMembers() ) == count;
}
@Override
public String toString()
{
return "Master should see " + count + " members";
}
};
}
public static Predicate<ManagedCluster> allSeesAllAsAvailable()
{
return new Predicate<ManagedCluster>()
{
@Override
public boolean test( ManagedCluster cluster )
{
if ( !allSeesAllAsJoined().test( cluster ) )
{
return false;
}
for ( HighlyAvailableGraphDatabase database : cluster.getAllMembers() )
{
ClusterMembers members = database.getDependencyResolver().resolveDependency( ClusterMembers.class );
for ( ClusterMember clusterMember : members.getMembers() )
{
if ( clusterMember.getHARole().equals( HighAvailabilityModeSwitcher.UNKNOWN ) )
{
return false;
}
}
}
// Everyone sees everyone else as available!
for( HighlyAvailableGraphDatabase database : cluster.getAllMembers() )
{
Log log = database.getDependencyResolver().resolveDependency( LogService.class ).getInternalLog( getClass() );
log.debug( this.toString() );
}
return true;
}
@Override
public String toString()
{
return "All instances should see all others as available";
}
};
}
public static Predicate<ManagedCluster> allSeesAllAsJoined()
{
return new Predicate<ManagedCluster>()
{
@Override
public boolean test( ManagedCluster cluster )
{
int clusterSize = cluster.size();
for ( HighlyAvailableGraphDatabase database : cluster.getAllMembers() )
{
ClusterMembers members = database.getDependencyResolver().resolveDependency( ClusterMembers.class );
if ( count( members.getMembers() ) < clusterSize )
{
return false;
}
}
for ( ObservedClusterMembers arbiter : cluster.getArbiters() )
{
if ( count( arbiter.getMembers() ) < clusterSize )
{
return false;
}
}
// Everyone sees everyone else as joined!
return true;
}
@Override
public String toString()
{
return "All instances should see all others as joined";
}
};
}
public static Predicate<ManagedCluster> allAvailabilityGuardsReleased()
{
return item -> {
for ( HighlyAvailableGraphDatabase member : item.getAllMembers())
{
try
{
member.beginTx().close();
}
catch ( TransactionFailureException e )
{
return false;
}
}
return true;
};
}
public static Predicate<ManagedCluster> memberSeesOtherMemberAsFailed(
final HighlyAvailableGraphDatabase observer, final HighlyAvailableGraphDatabase observed )
{
return cluster -> {
InstanceId observedServerId = observed.getDependencyResolver().resolveDependency( Config.class )
.get( ClusterSettings.server_id );
for ( ClusterMember member : observer.getDependencyResolver().resolveDependency(
ClusterMembers.class ).getMembers() )
{
if ( member.getInstanceId().equals( observedServerId ) )
{
return !member.isAlive();
}
}
throw new IllegalStateException( observed + " not a member according to " + observer );
};
}
public static Predicate<ManagedCluster> memberThinksItIsRole(
final HighlyAvailableGraphDatabase member, final String role )
{
return cluster -> role.equals( member.role() );
}
public static String stateToString( ManagedCluster cluster )
{
StringBuilder buf = new StringBuilder( "\n" );
for ( HighlyAvailableGraphDatabase database : cluster.getAllMembers() )
{
ClusterClient client = database.getDependencyResolver().resolveDependency( ClusterClient.class );
buf.append( "Instance " ).append( client.getServerId() )
.append( ":State " ).append( database.getInstanceState() )
.append( " (" ).append( client.getClusterServer() ).append( "):" ).append( "\n" );
ClusterMembers members = database.getDependencyResolver().resolveDependency( ClusterMembers.class );
buf.append( members );
}
return buf.toString();
}
@Override
public void start() throws Throwable
{
Clusters clusters = clustersProvider.clusters();
life = new LifeSupport();
// Started so instances added here will be started immediately, and in case of exceptions they can be
// shutdown() or stop()ped properly
life.start();
for ( Clusters.Cluster cluster : clusters.getClusters())
{
ManagedCluster managedCluster = new ManagedCluster( cluster );
clusterMap.put( cluster.getName(), managedCluster );
life.add( managedCluster );
}
}
@Override
public void stop() throws Throwable
{
life.stop();
}
@Override
public void shutdown() throws Throwable
{
life.shutdown();
}
@SuppressWarnings( "unchecked" )
private <T> T instance( Class<T> classToFind, Iterable<?> from )
{
for ( Object item : from )
{
if ( classToFind.isAssignableFrom( item.getClass() ) )
{
return (T) item;
}
}
throw new AssertionError( "Couldn't find the network instance to fail. "
+ "Internal field, so fragile sensitive to changes though" );
}
private Field accessible( Field field )
{
field.setAccessible( true );
return field;
}
public ManagedCluster getCluster( String name )
{
if ( !clusterMap.containsKey( name ) )
{
throw new IllegalArgumentException( name );
}
return clusterMap.get( name );
}
public ManagedCluster getDefaultCluster()
{
return getCluster( "neo4j.ha" );
}
protected void config( GraphDatabaseBuilder builder, String clusterName, InstanceId serverId )
{
}
protected void insertInitialData( GraphDatabaseService db, String name, InstanceId serverId )
{
}
public interface ClusterBuilder<SELF>
{
SELF withRootDirectory( File root );
SELF withSeedDir( File seedDir );
SELF withStoreDirInitializer( StoreDirInitializer initializer );
SELF withDbFactory( HighlyAvailableGraphDatabaseFactory dbFactory );
SELF withProvider( Provider provider );
/**
* Supplies configuration where config values, as opposed to {@link #withSharedConfig(Map)},
* are a function of (one-based) server id. The function may return {@code null} which means
* that the particular member doesn't have that config value, or at least not specifically
* set, such that any default value would be used.
*/
SELF withInstanceConfig( Map<String,IntFunction<String>> commonConfig );
/**
* Like {@link #withInstanceConfig(Map)}, but for individual settings, conveniently using
* {@link Setting} instance as key as well.
*/
SELF withInstanceSetting( Setting<?> setting, IntFunction<String> valueFunction );
/**
* Supplies configuration where config values are shared with all instances in the cluster.
*/
SELF withSharedConfig( Map<String,String> commonConfig );
/**
* Like {@link #withInstanceSetting(Setting, IntFunction)}, but for individual settings, conveniently using
* {@link Setting} instance as key as well.
*/
SELF withSharedSetting( Setting<?> setting, String value );
}
public static class Builder implements ClusterBuilder<Builder>
{
private File root;
private Provider provider = clusterOfSize( 3 );
private final Map<String,IntFunction<String>> commonConfig = new HashMap<>();
private HighlyAvailableGraphDatabaseFactory factory = new HighlyAvailableGraphDatabaseFactory();
private StoreDirInitializer initializer;
public Builder( File root )
{
this.root = root;
}
public Builder()
{
// We want this, at least in the ClusterRule case where we fill this Builder instances
// with all our behavior, but we don't know about the root directory until we evaluate the rule.
}
@Override
public Builder withRootDirectory( File root )
{
this.root = root;
return this;
}
@Override
public Builder withSeedDir( final File seedDir )
{
return withStoreDirInitializer( ( serverId, storeDir ) -> copyRecursively( seedDir, storeDir ) );
}
@Override
public Builder withStoreDirInitializer( StoreDirInitializer initializer )
{
this.initializer = initializer;
return this;
}
@Override
public Builder withDbFactory( HighlyAvailableGraphDatabaseFactory dbFactory )
{
this.factory = dbFactory;
return this;
}
@Override
public Builder withProvider( Provider provider )
{
this.provider = provider;
return this;
}
@Override
public Builder withInstanceConfig( Map<String,IntFunction<String>> commonConfig )
{
this.commonConfig.putAll( commonConfig );
return this;
}
@Override
public Builder withInstanceSetting( Setting<?> setting, IntFunction<String> valueFunction )
{
this.commonConfig.put( setting.name(), valueFunction );
return this;
}
@Override
public Builder withSharedConfig( Map<String,String> commonConfig )
{
Map<String,IntFunction<String>> dynamic = new HashMap<>();
for ( Map.Entry<String,String> entry : commonConfig.entrySet() )
{
dynamic.put( entry.getKey(), constant( entry.getValue() ) );
}
return withInstanceConfig( dynamic );
}
@Override
public Builder withSharedSetting( Setting<?> setting, String value )
{
return withInstanceSetting( setting, constant( value ) );
}
public ClusterManager build()
{
return new ClusterManager( this );
}
}
private static final class HighlyAvailableGraphDatabaseProxy
{
private final ExecutorService executor;
private GraphDatabaseService result;
private Future<GraphDatabaseService> untilThen;
public HighlyAvailableGraphDatabaseProxy( final GraphDatabaseBuilder graphDatabaseBuilder )
{
Callable<GraphDatabaseService> starter = graphDatabaseBuilder::newGraphDatabase;
executor = Executors.newFixedThreadPool( 1 );
untilThen = executor.submit( starter );
}
public HighlyAvailableGraphDatabase get()
{
if ( result == null )
{
try
{
result = untilThen.get();
}
catch ( InterruptedException | ExecutionException e )
{
throw new RuntimeException( e );
}
finally
{
executor.shutdownNow();
}
}
return (HighlyAvailableGraphDatabase) result;
}
}
private static final class FutureLifecycleAdapter<T extends Lifecycle> extends LifecycleAdapter
{
private final T wrapped;
private final ExecutorService starter;
private Future<Void> currentFuture;
public FutureLifecycleAdapter( T toWrap )
{
wrapped = toWrap;
starter = Executors.newFixedThreadPool( 1 );
}
@Override
public void init() throws Throwable
{
currentFuture = starter.submit( (Callable<Void>) () -> {
try
{
wrapped.init();
}
catch ( Throwable throwable )
{
throw new RuntimeException( throwable );
}
return null;
} );
}
@Override
public void start() throws Throwable
{
currentFuture.get();
currentFuture = starter.submit( (Callable<Void>) () -> {
try
{
wrapped.start();
}
catch ( Throwable throwable )
{
throw new RuntimeException( throwable );
}
return null;
} );
}
@Override
public void stop() throws Throwable
{
currentFuture.get();
currentFuture = starter.submit( (Callable<Void>) () -> {
try
{
wrapped.stop();
}
catch ( Throwable throwable )
{
throw new RuntimeException( throwable );
}
return null;
} );
}
@Override
public void shutdown() throws Throwable
{
currentFuture = starter.submit( (Callable<Void>) () -> {
try
{
wrapped.shutdown();
}
catch ( Throwable throwable )
{
throw new RuntimeException( throwable );
}
return null;
} );
currentFuture.get();
starter.shutdownNow();
}
}
/**
* Represent one cluster. It can retrieve the current master, random slave
* or all members. It can also temporarily fail an instance or shut it down.
*/
public class ManagedCluster extends LifecycleAdapter
{
private final Clusters.Cluster spec;
private final String name;
private final Map<InstanceId,HighlyAvailableGraphDatabaseProxy> members = new ConcurrentHashMap<>();
private final List<ObservedClusterMembers> arbiters = new ArrayList<>();
ManagedCluster( Clusters.Cluster spec ) throws URISyntaxException, IOException
{
this.spec = spec;
this.name = spec.getName();
for ( int i = 0; i < spec.getMembers().size(); i++ )
{
startMember( new InstanceId( i + 1 ) );
}
for ( HighlyAvailableGraphDatabaseProxy member : members.values() )
{
HighlyAvailableGraphDatabase graphDatabase = member.get();
Config config = graphDatabase.getDependencyResolver().resolveDependency( Config.class );
insertInitialData( graphDatabase, name, config.get( ClusterSettings.server_id ) );
}
}
public String getInitialHostsConfigString()
{
StringBuilder result = new StringBuilder();
for ( HighlyAvailableGraphDatabase member : getAllMembers() )
{
result.append( result.length() > 0 ? "," : "" ).append( ":" )
.append( member.getDependencyResolver().resolveDependency(
ClusterClient.class ).getClusterServer().getPort() );
}
return result.toString();
}
@Override
public void stop() throws Throwable
{
for ( HighlyAvailableGraphDatabaseProxy member : members.values() )
{
member.get().shutdown();
}
}
/**
* @return all started members in this cluster.
*/
public Iterable<HighlyAvailableGraphDatabase> getAllMembers()
{
return Iterables.map( from -> {
return from.get();
}, members.values() );
}
public Iterable<ObservedClusterMembers> getArbiters()
{
return arbiters;
}
/**
* @return the current master in the cluster.
* @throws IllegalStateException if there's no current master.
*/
public HighlyAvailableGraphDatabase getMaster()
{
for ( HighlyAvailableGraphDatabase graphDatabaseService : getAllMembers() )
{
if ( graphDatabaseService.isAvailable( 0 ) && graphDatabaseService.isMaster() )
{
return graphDatabaseService;
}
}
throw new IllegalStateException( "No master found in cluster " + name + stateToString( this ) );
}
/**
* @param except do not return any of the dbs found in this array
* @return a slave in this cluster.
* @throws IllegalStateException if no slave was found in this cluster.
*/
public HighlyAvailableGraphDatabase getAnySlave( HighlyAvailableGraphDatabase... except )
{
Set<HighlyAvailableGraphDatabase> exceptSet = new HashSet<>( asList( except ) );
for ( HighlyAvailableGraphDatabase graphDatabaseService : getAllMembers() )
{
if ( graphDatabaseService.getInstanceState() == HighAvailabilityMemberState.SLAVE
&& !exceptSet.contains( graphDatabaseService ) )
{
return graphDatabaseService;
}
}
throw new IllegalStateException( "No slave found in cluster " + name + stateToString( this ) );
}
/**
* @param serverId the server id to return the db for.
* @return the {@link HighlyAvailableGraphDatabase} with the given server id.
* @throws IllegalStateException if that db isn't started or no such
* db exists in the cluster.
*/
public HighlyAvailableGraphDatabase getMemberByServerId( InstanceId serverId )
{
HighlyAvailableGraphDatabase db = members.get( serverId ).get();
if ( db == null )
{
throw new IllegalStateException( "Db " + serverId + " not found at the moment in " + name +
stateToString( this ) );
}
return db;
}
/**
* Shuts down a member of this cluster. A {@link RepairKit} is returned
* which is able to restore the instance (i.e. start it again).
*
* @param db the {@link HighlyAvailableGraphDatabase} to shut down.
* @return a {@link RepairKit} which can start it again.
* @throws IllegalArgumentException if the given db isn't a member of this cluster.
*/
public RepairKit shutdown( HighlyAvailableGraphDatabase db )
{
assertMember( db );
InstanceId serverId =
db.getDependencyResolver().resolveDependency( Config.class ).get( ClusterSettings.server_id );
members.remove( serverId );
life.remove( db );
db.shutdown();
return new StartDatabaseAgainKit( this, serverId );
}
private void assertMember( HighlyAvailableGraphDatabase db )
{
for ( HighlyAvailableGraphDatabaseProxy highlyAvailableGraphDatabaseProxy : members.values() )
{
if ( highlyAvailableGraphDatabaseProxy.get().equals( db ) )
{
return;
}
}
throw new IllegalArgumentException( "Db " + db + " not a member of this cluster " + name +
stateToString( this ) );
}
public RepairKit fail( HighlyAvailableGraphDatabase db ) throws Throwable
{
return fail( db, NetworkFlag.values() );
}
/**
* WARNING: beware of hacks.
* <p>
* Fails a member of this cluster by making it not respond to heart beats.
* A {@link RepairKit} is returned which is able to repair the instance
* (i.e start the network) again.
*
* @param db the {@link HighlyAvailableGraphDatabase} to fail.
* @return a {@link RepairKit} which can repair the failure.
* @throws IllegalArgumentException if the given db isn't a member of this cluster.
*/
public RepairKit fail( HighlyAvailableGraphDatabase db, NetworkFlag... flags ) throws Throwable
{
assertMember( db );
NetworkReceiver networkReceiver = db.getDependencyResolver().resolveDependency( NetworkReceiver.class );
NetworkSender networkSender = db.getDependencyResolver().resolveDependency( NetworkSender.class );
if ( contains( flags, NetworkFlag.IN ) )
{
networkReceiver.setPaused( true );
}
if ( contains( flags, NetworkFlag.OUT ) )
{
networkSender.setPaused( true );
}
return new StartNetworkAgainKit( db, networkReceiver, networkSender, flags );
}
private void startMember( InstanceId serverId ) throws URISyntaxException, IOException
{
Clusters.Member member = spec.getMembers().get( serverId.toIntegerIndex() - 1 );
StringBuilder initialHosts = new StringBuilder( spec.getMembers().get( 0 ).getHost() );
for ( int i = 1; i < spec.getMembers().size(); i++ )
{