forked from voldemort/voldemort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServerTestUtils.java
811 lines (718 loc) · 37 KB
/
ServerTestUtils.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
/*
* Copyright 2008-2012 LinkedIn, Inc
*
* 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 voldemort;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.net.BindException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.apache.http.client.HttpClient;
import org.apache.log4j.Logger;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
import voldemort.client.RoutingTier;
import voldemort.client.protocol.RequestFormatFactory;
import voldemort.client.protocol.RequestFormatType;
import voldemort.client.protocol.admin.AdminClient;
import voldemort.client.protocol.admin.AdminClientConfig;
import voldemort.cluster.Cluster;
import voldemort.cluster.Node;
import voldemort.cluster.Zone;
import voldemort.routing.RoutingStrategyType;
import voldemort.serialization.SerializerDefinition;
import voldemort.server.AbstractSocketService;
import voldemort.server.RequestRoutingType;
import voldemort.server.StoreRepository;
import voldemort.server.VoldemortConfig;
import voldemort.server.VoldemortServer;
import voldemort.server.http.StoreServlet;
import voldemort.server.niosocket.NioSocketService;
import voldemort.server.protocol.RequestHandler;
import voldemort.server.protocol.RequestHandlerFactory;
import voldemort.server.protocol.SocketRequestHandlerFactory;
import voldemort.server.socket.SocketService;
import voldemort.store.Store;
import voldemort.store.StoreDefinition;
import voldemort.store.StoreDefinitionBuilder;
import voldemort.store.UnreachableStoreException;
import voldemort.store.http.HttpStore;
import voldemort.store.memory.InMemoryStorageConfiguration;
import voldemort.store.memory.InMemoryStorageEngine;
import voldemort.store.metadata.MetadataStore;
import voldemort.store.slop.Slop;
import voldemort.store.slop.strategy.HintedHandoffStrategyType;
import voldemort.store.socket.SocketStoreFactory;
import voldemort.utils.ByteArray;
import voldemort.utils.ByteUtils;
import voldemort.utils.Props;
import voldemort.versioning.Versioned;
import voldemort.xml.ClusterMapper;
import voldemort.xml.StoreDefinitionsMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
/**
* Helper functions for testing with real server implementations
*
*
*/
public class ServerTestUtils {
private static final Logger logger = Logger.getLogger(ServerTestUtils.class.getName());
public static StoreRepository getStores(String storeName, String clusterXml, String storesXml) {
StoreRepository repository = new StoreRepository();
Store<ByteArray, byte[], byte[]> store = new InMemoryStorageEngine<ByteArray, byte[], byte[]>(storeName);
repository.addLocalStore(store);
repository.addRoutedStore(store);
// create new metadata store.
MetadataStore metadata = createMetadataStore(new ClusterMapper().readCluster(new StringReader(clusterXml)),
new StoreDefinitionsMapper().readStoreList(new StringReader(storesXml)));
repository.addLocalStore(metadata);
return repository;
}
public static VoldemortConfig getVoldemortConfig() {
File temp = TestUtils.createTempDir();
VoldemortConfig config = new VoldemortConfig(0, temp.getAbsolutePath());
new File(config.getMetadataDirectory()).mkdir();
return config;
}
public static AbstractSocketService getSocketService(boolean useNio,
String clusterXml,
String storesXml,
String storeName,
int port) {
RequestHandlerFactory factory = getSocketRequestHandlerFactory(clusterXml,
storesXml,
getStores(storeName,
clusterXml,
storesXml));
return getSocketService(useNio, factory, port, 5, 10, 10000);
}
public static RequestHandlerFactory getSocketRequestHandlerFactory(String clusterXml,
String storesXml,
StoreRepository storeRepository) {
return new SocketRequestHandlerFactory(null,
storeRepository,
createMetadataStore(new ClusterMapper().readCluster(new StringReader(clusterXml)),
new StoreDefinitionsMapper().readStoreList(new StringReader(storesXml))),
null,
null,
null);
}
public static AbstractSocketService getSocketService(boolean useNio,
RequestHandlerFactory requestHandlerFactory,
int port,
int coreConnections,
int maxConnections,
int bufferSize) {
AbstractSocketService socketService = null;
if(useNio) {
socketService = new NioSocketService(requestHandlerFactory,
port,
bufferSize,
coreConnections,
"client-request-service",
false,
-1);
} else {
socketService = new SocketService(requestHandlerFactory,
port,
coreConnections,
maxConnections,
bufferSize,
"client-request-service",
false);
}
return socketService;
}
public static Store<ByteArray, byte[], byte[]> getSocketStore(SocketStoreFactory storeFactory,
String storeName,
int port) {
return getSocketStore(storeFactory, storeName, port, RequestFormatType.VOLDEMORT_V1);
}
public static Store<ByteArray, byte[], byte[]> getSocketStore(SocketStoreFactory storeFactory,
String storeName,
int port,
RequestFormatType type) {
return getSocketStore(storeFactory, storeName, "localhost", port, type);
}
public static Store<ByteArray, byte[], byte[]> getSocketStore(SocketStoreFactory storeFactory,
String storeName,
String host,
int port,
RequestFormatType type) {
return getSocketStore(storeFactory, storeName, host, port, type, false);
}
public static Store<ByteArray, byte[], byte[]> getSocketStore(SocketStoreFactory storeFactory,
String storeName,
String host,
int port,
RequestFormatType type,
boolean isRouted) {
RequestRoutingType requestRoutingType = RequestRoutingType.getRequestRoutingType(isRouted,
false);
return storeFactory.create(storeName, host, port, type, requestRoutingType);
}
public static Context getJettyServer(String clusterXml,
String storesXml,
String storeName,
RequestFormatType requestFormat,
int port) throws Exception {
StoreRepository repository = getStores(storeName, clusterXml, storesXml);
// initialize servlet
Server server = new Server(port);
server.setSendServerVersion(false);
Context context = new Context(server, "/", Context.NO_SESSIONS);
RequestHandler handler = getSocketRequestHandlerFactory(clusterXml, storesXml, repository).getRequestHandler(requestFormat);
context.addServlet(new ServletHolder(new StoreServlet(handler)), "/stores");
server.start();
return context;
}
public static HttpStore getHttpStore(String storeName,
RequestFormatType format,
int port,
final HttpClient httpClient) {
return new HttpStore(storeName,
"localhost",
port,
httpClient,
new RequestFormatFactory().getRequestFormat(format),
false);
}
/**
* Return a free port as chosen by new ServerSocket(0).
*
* There is no guarantee that the port returned will be free when the caller
* attempts to bind to the port. This is a time-of-check-to-time-of-use
* (TOCTOU) issue that cannot be avoided.
*/
public static int findFreePort() {
return findFreePorts(1)[0];
}
/**
* Return an array of free ports as chosen by new ServerSocket(0)
*
* There is no guarantee that the ports returned will be free when the
* caller attempts to bind to some returned port. This is a
* time-of-check-to-time-of-use (TOCTOU) issue that cannot be avoided.
*/
public static int[] findFreePorts(int n) {
logger.info("findFreePorts cannot guarantee that ports identified as free will still be free when used. This is effectively a TOCTOU issue. Expect intermittent BindException when \"free\" ports are used.");
int[] ports = new int[n];
ServerSocket[] sockets = new ServerSocket[n];
try {
for(int i = 0; i < n; i++) {
sockets[i] = new ServerSocket(0);
ports[i] = sockets[i].getLocalPort();
}
return ports;
} catch(IOException e) {
throw new RuntimeException(e);
} finally {
for(int i = 0; i < n; i++) {
try {
if(sockets[i] != null)
sockets[i].close();
} catch(IOException e) {}
}
}
}
public static Cluster getLocalCluster(int numberOfNodes) {
return getLocalCluster(numberOfNodes, findFreePorts(3 * numberOfNodes), null);
}
public static Cluster getLocalCluster(int numberOfNodes, int[][] partitionMap) {
return getLocalCluster(numberOfNodes, findFreePorts(3 * numberOfNodes), partitionMap);
}
public static Cluster getLocalCluster(int numberOfNodes, int[] ports, int[][] partitionMap) {
if(3 * numberOfNodes != ports.length)
throw new IllegalArgumentException(3 * numberOfNodes + " ports required but only "
+ ports.length + " given.");
List<Node> nodes = new ArrayList<Node>();
for(int i = 0; i < numberOfNodes; i++) {
List<Integer> partitions = ImmutableList.of(i);
if(null != partitionMap) {
partitions = new ArrayList<Integer>(partitionMap[i].length);
for(int p: partitionMap[i]) {
partitions.add(p);
}
}
nodes.add(new Node(i,
"localhost",
ports[3 * i],
ports[3 * i + 1],
ports[3 * i + 2],
partitions));
}
return new Cluster("test-cluster", nodes);
}
/**
* Update a cluster by replacing the specified server with a new host, i.e.
* new ports since they are all localhost
*
* @param original The original cluster to be updated
* @param serverIds The ids of the server to be replaced with new hosts
* @return updated cluster
*/
public static Cluster updateClusterWithNewHost(Cluster original, int... serverIds) {
int highestPortInuse = 0;
for(Node node: original.getNodes()) {
int nodeMaxPort = 0;
nodeMaxPort = Math.max(nodeMaxPort, node.getAdminPort());
nodeMaxPort = Math.max(nodeMaxPort, node.getHttpPort());
nodeMaxPort = Math.max(nodeMaxPort, node.getSocketPort());
highestPortInuse = Math.max(highestPortInuse, nodeMaxPort);
}
Set<Integer> newNodesSet = new HashSet<Integer>(serverIds.length);
for(int id: serverIds) {
newNodesSet.add(id);
}
List<Node> newNodeList = new ArrayList<Node>(serverIds.length);
for(Node node: original.getNodes()) {
if(newNodesSet.contains(node.getId())) {
node = new Node(node.getId(),
"localhost",
++highestPortInuse,
++highestPortInuse,
++highestPortInuse,
node.getPartitionIds());
}
newNodeList.add(node);
}
return new Cluster(original.getName(), newNodeList);
}
/**
* Returns a list of zones with their proximity list being in increasing
* order
*
* @param numberOfZones The number of zones to return
* @return List of zones
*/
public static List<Zone> getZones(int numberOfZones) {
List<Zone> zones = Lists.newArrayList();
for(int i = 0; i < numberOfZones; i++) {
LinkedList<Integer> proximityList = Lists.newLinkedList();
int zoneId = i + 1;
for(int j = 0; j < numberOfZones; j++) {
if(zoneId % numberOfZones == i)
break;
proximityList.add(zoneId % numberOfZones);
zoneId++;
}
zones.add(new Zone(i, proximityList));
}
return zones;
}
/**
* Returns a cluster with <b>numberOfNodes</b> nodes in <b>numberOfZones</b>
* zones. It is important that <b>numberOfNodes</b> be divisible by
* <b>numberOfZones</b>
*
* @param numberOfNodes Number of nodes in the cluster
* @param partitionsPerNode Number of partitions in one node
* @param numberOfZones Number of zones
* @return Cluster
*/
public static Cluster getLocalCluster(int numberOfNodes,
int partitionsPerNode,
int numberOfZones) {
if(numberOfZones > 0 && numberOfNodes > 0 && numberOfNodes % numberOfZones != 0) {
throw new VoldemortException("The number of nodes (" + numberOfNodes
+ ") is not divisible by number of zones ("
+ numberOfZones + ")");
}
int[] ports = findFreePorts(3 * numberOfNodes);
List<Integer> partitions = Lists.newArrayList();
for(int i = 0; i < partitionsPerNode * numberOfNodes; i++)
partitions.add(i);
Collections.shuffle(partitions);
// Generate nodes
int numberOfNodesPerZone = numberOfNodes / numberOfZones;
List<Node> nodes = new ArrayList<Node>();
for(int i = 0; i < numberOfNodes; i++) {
nodes.add(new Node(i,
"localhost",
ports[3 * i],
ports[3 * i + 1],
ports[3 * i + 2],
i / numberOfNodesPerZone,
partitions.subList(partitionsPerNode * i, partitionsPerNode * i
+ partitionsPerNode)));
}
// Generate zones
if(numberOfZones > 1) {
List<Zone> zones = Lists.newArrayList();
for(int i = 0; i < numberOfZones; i++) {
LinkedList<Integer> proximityList = Lists.newLinkedList();
int zoneId = i + 1;
for(int j = 0; j < numberOfZones; j++) {
proximityList.add(zoneId % numberOfZones);
zoneId++;
}
zones.add(new Zone(i, proximityList));
}
return new Cluster("cluster", nodes, zones);
} else {
return new Cluster("cluster", nodes);
}
}
public static Node getLocalNode(int nodeId, List<Integer> partitions) {
int[] ports = findFreePorts(3);
return new Node(nodeId, "localhost", ports[0], ports[1], ports[2], partitions);
}
public static MetadataStore createMetadataStore(Cluster cluster, List<StoreDefinition> storeDefs) {
Store<String, String, String> innerStore = new InMemoryStorageEngine<String, String, String>("inner-store");
innerStore.put(MetadataStore.CLUSTER_KEY,
new Versioned<String>(new ClusterMapper().writeCluster(cluster)),
null);
innerStore.put(MetadataStore.STORES_KEY,
new Versioned<String>(new StoreDefinitionsMapper().writeStoreList(storeDefs)),
null);
return new MetadataStore(innerStore, 0);
}
public static List<StoreDefinition> getStoreDefs(int numStores) {
List<StoreDefinition> defs = new ArrayList<StoreDefinition>();
SerializerDefinition serDef = new SerializerDefinition("string");
for(int i = 0; i < numStores; i++)
defs.add(new StoreDefinitionBuilder().setName("test" + i)
.setType(InMemoryStorageConfiguration.TYPE_NAME)
.setKeySerializer(serDef)
.setValueSerializer(serDef)
.setRoutingPolicy(RoutingTier.SERVER)
.setRoutingStrategyType(RoutingStrategyType.CONSISTENT_STRATEGY)
.setReplicationFactor(2)
.setPreferredReads(1)
.setRequiredReads(1)
.setPreferredWrites(1)
.setRequiredWrites(1)
.build());
return defs;
}
public static StoreDefinition getStoreDef(String storeName,
int replicationFactor,
int preads,
int rreads,
int pwrites,
int rwrites,
String strategyType) {
SerializerDefinition serDef = new SerializerDefinition("string");
return new StoreDefinitionBuilder().setName(storeName)
.setType(InMemoryStorageConfiguration.TYPE_NAME)
.setKeySerializer(serDef)
.setValueSerializer(serDef)
.setRoutingPolicy(RoutingTier.SERVER)
.setRoutingStrategyType(strategyType)
.setReplicationFactor(replicationFactor)
.setPreferredReads(preads)
.setRequiredReads(rreads)
.setPreferredWrites(pwrites)
.setRequiredWrites(rwrites)
.build();
}
public static StoreDefinition getStoreDef(String storeName,
int preads,
int rreads,
int pwrites,
int rwrites,
int zonereads,
int zonewrites,
HashMap<Integer, Integer> zoneReplicationFactor,
HintedHandoffStrategyType hhType,
String strategyType) {
SerializerDefinition serDef = new SerializerDefinition("string");
int replicationFactor = 0;
for(Integer repFac: zoneReplicationFactor.values()) {
replicationFactor += repFac;
}
return new StoreDefinitionBuilder().setName(storeName)
.setType(InMemoryStorageConfiguration.TYPE_NAME)
.setKeySerializer(serDef)
.setValueSerializer(serDef)
.setRoutingPolicy(RoutingTier.SERVER)
.setRoutingStrategyType(strategyType)
.setPreferredReads(preads)
.setRequiredReads(rreads)
.setHintedHandoffStrategy(hhType)
.setZoneCountReads(zonereads)
.setZoneCountWrites(zonewrites)
.setReplicationFactor(replicationFactor)
.setZoneReplicationFactor(zoneReplicationFactor)
.setPreferredWrites(pwrites)
.setRequiredWrites(rwrites)
.build();
}
public static HashMap<ByteArray, byte[]> createRandomKeyValuePairs(int numKeys) {
HashMap<ByteArray, byte[]> map = new HashMap<ByteArray, byte[]>();
for(int cnt = 0; cnt <= numKeys; cnt++) {
int keyInt = (int) (Math.random() * 100000);
ByteArray key = new ByteArray(ByteUtils.getBytes("" + keyInt, "UTF-8"));
byte[] value = ByteUtils.getBytes("value-" + keyInt, "UTF-8");
map.put(key, value);
}
return map;
}
public static List<Versioned<Slop>> createRandomSlops(int nodeId,
int numKeys,
String... storeNames) {
List<Versioned<Slop>> slops = new ArrayList<Versioned<Slop>>();
for(int cnt = 0; cnt < numKeys; cnt++) {
int storeId = (int) Math.round(Math.random() * (storeNames.length - 1));
int operation = (int) Math.round(Math.random() + 1);
Slop.Operation operationType;
if(operation == 1)
operationType = Slop.Operation.PUT;
else
operationType = Slop.Operation.DELETE;
long keyInt = (long) (Math.random() * 1000000000L);
ByteArray key = new ByteArray(ByteUtils.getBytes("" + keyInt, "UTF-8"));
byte[] value = ByteUtils.getBytes("value-" + keyInt, "UTF-8");
Versioned<Slop> versioned = Versioned.value(new Slop(storeNames[storeId],
operationType,
key,
value,
null,
nodeId,
new Date()));
slops.add(versioned);
// Adding twice so as check if ObsoleteVersionExceptions are
// swallowed correctly
slops.add(versioned);
}
return slops;
}
public static HashMap<String, String> createRandomKeyValueString(int numKeys) {
HashMap<String, String> map = new HashMap<String, String>();
for(int cnt = 0; cnt <= numKeys; cnt++) {
int keyInt = (int) (Math.random() * 100000);
map.put("" + keyInt, "value-" + keyInt);
}
return map;
}
public static VoldemortConfig createServerConfigWithDefs(boolean useNio,
int nodeId,
String baseDir,
Cluster cluster,
List<StoreDefinition> stores,
Properties properties)
throws IOException {
File clusterXml = new File(TestUtils.createTempDir(), "cluster.xml");
File storesXml = new File(TestUtils.createTempDir(), "stores.xml");
ClusterMapper clusterMapper = new ClusterMapper();
StoreDefinitionsMapper storeDefMapper = new StoreDefinitionsMapper();
FileWriter writer = new FileWriter(clusterXml);
writer.write(clusterMapper.writeCluster(cluster));
writer.close();
writer = new FileWriter(storesXml);
writer.write(storeDefMapper.writeStoreList(stores));
writer.close();
return createServerConfig(useNio,
nodeId,
baseDir,
clusterXml.getAbsolutePath(),
storesXml.getAbsolutePath(),
properties);
}
public static VoldemortConfig createServerConfig(boolean useNio,
int nodeId,
String baseDir,
String clusterFile,
String storeFile,
Properties properties) throws IOException {
Props props = new Props();
props.put("node.id", nodeId);
props.put("voldemort.home", baseDir + "/node-" + nodeId);
props.put("bdb.cache.size", 1 * 1024 * 1024);
props.put("bdb.write.transactions", "true");
props.put("bdb.flush.transactions", "true");
props.put("jmx.enable", "false");
props.put("enable.mysql.engine", "true");
props.loadProperties(properties);
VoldemortConfig config = new VoldemortConfig(props);
config.setMysqlDatabaseName("voldemort");
config.setMysqlUsername("voldemort");
config.setMysqlPassword("voldemort");
config.setStreamMaxReadBytesPerSec(10 * 1000 * 1000);
config.setStreamMaxWriteBytesPerSec(10 * 1000 * 1000);
config.setUseNioConnector(useNio);
// clean and reinit metadata dir.
File tempDir = new File(config.getMetadataDirectory());
tempDir.mkdirs();
tempDir.deleteOnExit();
File tempDir2 = new File(config.getDataDirectory());
tempDir2.mkdirs();
tempDir2.deleteOnExit();
// copy cluster.xml / stores.xml to temp metadata dir.
if(null != clusterFile)
FileUtils.copyFile(new File(clusterFile),
new File(tempDir.getAbsolutePath() + File.separatorChar
+ "cluster.xml"));
if(null != storeFile)
FileUtils.copyFile(new File(storeFile), new File(tempDir.getAbsolutePath()
+ File.separatorChar + "stores.xml"));
return config;
}
public static AdminClient getAdminClient(Cluster cluster) {
AdminClientConfig config = new AdminClientConfig();
return new AdminClient(cluster, config);
}
public static AdminClient getAdminClient(String bootstrapURL) {
AdminClientConfig config = new AdminClientConfig();
return new AdminClient(bootstrapURL, config);
}
public static RequestHandlerFactory getSocketRequestHandlerFactory(StoreRepository repository) {
return new SocketRequestHandlerFactory(null, repository, null, null, null, null);
}
public static void stopVoldemortServer(VoldemortServer server) throws IOException {
try {
server.stop();
} finally {
FileUtils.deleteDirectory(new File(server.getVoldemortConfig().getVoldemortHome()));
}
}
public static VoldemortServer startVoldemortServer(SocketStoreFactory socketStoreFactory,
VoldemortConfig config,
Cluster cluster) {
// TODO: Some tests that use this method fail intermittently with the
// following output:
//
// A successor version version() to this version() exists for key
// cluster.xml
// voldemort.versioning.ObsoleteVersionException: A successor version
// version() to this version() exists for key cluster.xml"
//
// Need to trace through the constructor VoldemortServer(VoldemortConfig
// config, Cluster cluster) to understand how this error is possible,
// and why it only happens intermittently.
VoldemortServer server = new VoldemortServer(config, cluster);
server.start();
ServerTestUtils.waitForServerStart(socketStoreFactory, server.getIdentityNode());
// wait till server start or throw exception
return server;
}
public static VoldemortServer startVoldemortServer(SocketStoreFactory socketStoreFactory,
VoldemortConfig config) {
VoldemortServer server = new VoldemortServer(config);
server.start();
ServerTestUtils.waitForServerStart(socketStoreFactory, server.getIdentityNode());
// wait till server start or throw exception
return server;
}
public static void waitForServerStart(SocketStoreFactory socketStoreFactory, Node node) {
boolean success = false;
int retries = 10;
Store<ByteArray, ?, ?> store = null;
while(retries-- > 0) {
store = ServerTestUtils.getSocketStore(socketStoreFactory,
MetadataStore.METADATA_STORE_NAME,
node.getSocketPort());
try {
store.get(new ByteArray(MetadataStore.CLUSTER_KEY.getBytes()), null);
success = true;
} catch(UnreachableStoreException e) {
store.close();
store = null;
System.out.println("UnreachableSocketStore sleeping will try again " + retries
+ " times.");
try {
Thread.sleep(1000);
} catch(InterruptedException e1) {
// ignore
}
}
}
store.close();
if(!success)
throw new RuntimeException("Failed to connect with server:" + node);
}
protected static Cluster internalStartVoldemortCluster(int numServers,
VoldemortServer[] voldemortServers,
int[][] partitionMap,
SocketStoreFactory socketStoreFactory,
boolean useNio,
String clusterFile,
String storeFile,
Properties properties)
throws IOException {
Cluster cluster = ServerTestUtils.getLocalCluster(numServers, partitionMap);
for(int i = 0; i < numServers; i++) {
voldemortServers[i] = ServerTestUtils.startVoldemortServer(socketStoreFactory,
ServerTestUtils.createServerConfig(useNio,
i,
TestUtils.createTempDir()
.getAbsolutePath(),
clusterFile,
storeFile,
properties),
cluster);
}
return cluster;
}
/**
* This method wraps up work that is done in many different tests to set up
* some number of Voldemort servers in a cluster. This method masks an
* intermittent TOCTOU problem with the ports identified by
* {@link #findFreePorts(int)} not actually being free when a server needs
* to bind to them.
*
* @param numServers
* @param voldemortServers
* @param partitionMap
* @param socketStoreFactory
* @param useNio
* @param clusterFile
* @param storeFile
* @param properties
* @return Cluster object that was used to successfully start all of the
* servers.
* @throws IOException
*/
public static Cluster startVoldemortCluster(int numServers,
VoldemortServer[] voldemortServers,
int[][] partitionMap,
SocketStoreFactory socketStoreFactory,
boolean useNio,
String clusterFile,
String storeFile,
Properties properties) throws IOException {
boolean started = false;
Cluster cluster = null;
while(!started) {
try {
cluster = internalStartVoldemortCluster(numServers,
voldemortServers,
partitionMap,
socketStoreFactory,
useNio,
clusterFile,
storeFile,
properties);
started = true;
} catch(BindException be) {
logger.debug("Caught BindException when starting cluster. Will retry.");
}
}
return cluster;
}
}