use of voldemort.routing.RoutingStrategyFactory in project voldemort by voldemort.
the class ReadOnlyStorageEngineTestInstance method create.
public static ReadOnlyStorageEngineTestInstance create(SearchStrategy strategy, File baseDir, int testSize, int numNodes, int repFactor, SerializerDefinition keySerDef, SerializerDefinition valueSerDef, ReadOnlyStorageFormat type, int[][] partitionMap) throws Exception {
// create some test data
Map<String, String> data = createTestData(testSize);
JsonReader reader = makeTestDataReader(data, baseDir);
// set up definitions for cluster and store
List<Node> nodes = new ArrayList<Node>();
for (int i = 0; i < numNodes; i++) {
List<Integer> partitions = new ArrayList<Integer>(partitionMap[i].length);
for (int p : partitionMap[i]) {
partitions.add(p);
}
nodes.add(new Node(i, "localhost", 8080 + i, 6666 + i, 7000 + i, partitions));
}
Cluster cluster = new Cluster("test", nodes);
StoreDefinition storeDef = new StoreDefinitionBuilder().setName("test").setType(ReadOnlyStorageConfiguration.TYPE_NAME).setKeySerializer(keySerDef).setValueSerializer(valueSerDef).setRoutingPolicy(RoutingTier.CLIENT).setRoutingStrategyType(RoutingStrategyType.CONSISTENT_STRATEGY).setReplicationFactor(repFactor).setPreferredReads(1).setRequiredReads(1).setPreferredWrites(1).setRequiredWrites(1).build();
RoutingStrategy router = new RoutingStrategyFactory().updateRoutingStrategy(storeDef, cluster);
// build store files in outputDir
File outputDir = TestUtils.createTempDir(baseDir);
JsonStoreBuilder storeBuilder = new JsonStoreBuilder(reader, cluster, storeDef, router, outputDir, null, testSize / 5, 1, 2, 10000, false);
storeBuilder.build(type);
File nodeDir = TestUtils.createTempDir(baseDir);
@SuppressWarnings("unchecked") Serializer<String> keySerializer = (Serializer<String>) new DefaultSerializerFactory().getSerializer(keySerDef);
@SuppressWarnings("unchecked") Serializer<String> valueSerializer = (Serializer<String>) new DefaultSerializerFactory().getSerializer(valueSerDef);
Serializer<String> transSerializer = new StringSerializer();
Map<Integer, Store<String, String, String>> nodeStores = Maps.newHashMap();
Map<Integer, ReadOnlyStorageEngine> readOnlyStores = Maps.newHashMap();
for (int i = 0; i < numNodes; i++) {
File currNode = new File(nodeDir, Integer.toString(i));
currNode.mkdirs();
currNode.deleteOnExit();
Utils.move(new File(outputDir, "node-" + Integer.toString(i)), new File(currNode, "version-0"));
CompressionStrategyFactory compressionStrategyFactory = new CompressionStrategyFactory();
CompressionStrategy keyCompressionStrat = compressionStrategyFactory.get(keySerDef.getCompression());
CompressionStrategy valueCompressionStrat = compressionStrategyFactory.get(valueSerDef.getCompression());
ReadOnlyStorageEngine readOnlyStorageEngine = new ReadOnlyStorageEngine("test", strategy, router, i, currNode, 1);
readOnlyStores.put(i, readOnlyStorageEngine);
Store<ByteArray, byte[], byte[]> innerStore = new CompressingStore(readOnlyStorageEngine, keyCompressionStrat, valueCompressionStrat);
nodeStores.put(i, SerializingStore.wrap(innerStore, keySerializer, valueSerializer, transSerializer));
}
return new ReadOnlyStorageEngineTestInstance(data, baseDir, readOnlyStores, nodeStores, router, keySerializer);
}
use of voldemort.routing.RoutingStrategyFactory in project voldemort by voldemort.
the class BaseStreamingClient method addStoreToSession.
/**
* Add another store destination to an existing streaming session
*
*
* @param store the name of the store to stream to
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void addStoreToSession(String store) {
Exception initializationException = null;
storeNames.add(store);
for (Node node : nodesToStream) {
SocketDestination destination = null;
SocketAndStreams sands = null;
try {
destination = new SocketDestination(node.getHost(), node.getAdminPort(), RequestFormatType.ADMIN_PROTOCOL_BUFFERS);
sands = streamingSocketPool.checkout(destination);
DataOutputStream outputStream = sands.getOutputStream();
DataInputStream inputStream = sands.getInputStream();
nodeIdStoreToSocketRequest.put(new Pair(store, node.getId()), destination);
nodeIdStoreToOutputStreamRequest.put(new Pair(store, node.getId()), outputStream);
nodeIdStoreToInputStreamRequest.put(new Pair(store, node.getId()), inputStream);
nodeIdStoreToSocketAndStreams.put(new Pair(store, node.getId()), sands);
nodeIdStoreInitialized.put(new Pair(store, node.getId()), false);
remoteStoreDefs = adminClient.metadataMgmtOps.getRemoteStoreDefList(node.getId()).getValue();
} catch (Exception e) {
logger.error(e);
try {
close(sands.getSocket());
streamingSocketPool.checkin(destination, sands);
} catch (Exception ioE) {
logger.error(ioE);
}
if (!faultyNodes.contains(node.getId()))
faultyNodes.add(node.getId());
initializationException = e;
}
}
if (initializationException != null)
throw new VoldemortException(initializationException);
if (store.equals("slop"))
return;
boolean foundStore = false;
for (StoreDefinition remoteStoreDef : remoteStoreDefs) {
if (remoteStoreDef.getName().equals(store)) {
RoutingStrategyFactory factory = new RoutingStrategyFactory();
RoutingStrategy storeRoutingStrategy = factory.updateRoutingStrategy(remoteStoreDef, adminClient.getAdminClientCluster());
storeToRoutingStrategy.put(store, storeRoutingStrategy);
validateSufficientNodesAvailable(blackListedNodes, remoteStoreDef);
foundStore = true;
break;
}
}
if (!foundStore) {
logger.error("Store Name not found on the cluster");
throw new VoldemortException("Store Name not found on the cluster");
}
}
use of voldemort.routing.RoutingStrategyFactory in project voldemort by voldemort.
the class ImportTextDumpToBDB method main.
public static void main(String[] argv) throws Exception {
OptionParser parser = getParser();
OptionSet options = parser.parse(argv);
validateOptions(options);
String inputPath = (String) options.valueOf("input");
String storeBdbFolderPath = (String) options.valueOf("bdb");
String clusterXmlPath = (String) options.valueOf("cluster-xml");
String storesXmlPath = (String) options.valueOf("stores-xml");
Integer nodeId = (Integer) options.valueOf("node-id");
File input = new File(inputPath);
List<File> dataFiles = new ArrayList<File>();
if (input.isDirectory()) {
File[] files = input.listFiles();
if (files != null)
Collections.addAll(dataFiles, files);
} else if (input.isFile()) {
dataFiles.add(input);
} else {
System.err.println(inputPath + "is not file or directory");
}
File storeBdbFolder = new File(storeBdbFolderPath);
final String storeName = storeBdbFolder.getName();
Cluster cluster = new ClusterMapper().readCluster(new File(clusterXmlPath));
List<StoreDefinition> storeDefs = new StoreDefinitionsMapper().readStoreList(new File(storesXmlPath));
StoreDefinition storeDef = null;
for (StoreDefinition sd : storeDefs) {
if (sd.getName() != null && sd.getName().equals(storeName)) {
storeDef = sd;
}
}
if (storeDef == null) {
throw new VoldemortException("StoreNotfound: " + storeName);
}
RoutingStrategy routingStrategy = new RoutingStrategyFactory().updateRoutingStrategy(storeDef, cluster);
Properties properties = new Properties();
properties.put("node.id", "0");
properties.put("voldemort.home", storeBdbFolder.getParent());
VoldemortConfig voldemortConfig = new VoldemortConfig(properties);
voldemortConfig.setBdbDataDirectory(storeBdbFolder.getParent());
voldemortConfig.setEnableJmx(false);
voldemortConfig.setBdbOneEnvPerStore(true);
BdbStorageConfiguration bdbConfiguration = new BdbStorageConfiguration(voldemortConfig);
class MockStoreDefinition extends StoreDefinition {
public MockStoreDefinition() {
super(storeName, null, null, null, null, null, null, null, 0, null, 0, null, 0, null, null, null, null, null, null, null, null, null, null, null, null, 0);
}
@Override
public boolean hasMemoryFootprint() {
return false;
}
}
StoreDefinition mockStoreDef = new MockStoreDefinition();
StorageEngine<ByteArray, byte[], byte[]> engine = bdbConfiguration.getStore(mockStoreDef, routingStrategy);
long reportIntervalMs = 10000L;
long lastCount = 0;
long lastInserted = 0;
Reporter<Boolean> rp = new Reporter<Boolean>(reportIntervalMs);
long count = 0;
long inserted = 0;
for (File f : dataFiles) {
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(f), READER_BUFFER_SIZE);
engine.beginBatchModifications();
while (true) {
String line = bufferedReader.readLine();
if (line == null) {
break;
}
Pair<ByteArray, Versioned<byte[]>> entry;
try {
entry = lineToEntry(line);
} catch (Exception e) {
System.err.println("Skipping line: " + line);
e.printStackTrace();
continue;
}
ByteArray key = entry.getFirst();
List<Node> nodeList = routingStrategy.routeRequest(key.get());
for (Node node : nodeList) {
if (nodeId == node.getId()) {
try {
engine.put(key, entry.getSecond(), null);
inserted++;
} catch (ObsoleteVersionException e) {
e.printStackTrace();
}
break;
}
}
count++;
final Long countObject = count;
final Long insertedObject = inserted;
Boolean reported = rp.tryReport(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
System.out.print(String.format("Imported %15d entries; Inserted %15d entries", countObject, insertedObject));
return true;
}
});
if (reported != null) {
long importSpeed = (count - lastCount) / (reportIntervalMs / 1000);
long insertSpeed = (inserted - lastInserted) / (reportIntervalMs / 1000);
System.out.println(String.format("; ImportSpeed: %8d/s; InsertSpeed: %8d/s ", importSpeed, insertSpeed));
lastCount = count;
lastInserted = inserted;
}
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
engine.endBatchModifications();
}
}
engine.close();
System.out.println(String.format("Finished importing %d entries (%d inserted, rest discarded)", count, inserted));
}
use of voldemort.routing.RoutingStrategyFactory in project voldemort by voldemort.
the class RoutedStoreTest method testPutDeleteZoneRouting.
@Test
public void testPutDeleteZoneRouting() throws Exception {
cluster = VoldemortTestConstants.getEightNodeClusterWithZones();
HashMap<Integer, Integer> zoneReplicationFactor = Maps.newHashMap();
zoneReplicationFactor.put(0, 2);
zoneReplicationFactor.put(1, 2);
Versioned<byte[]> versioned = new Versioned<byte[]>(new byte[] { 1 });
Map<Integer, Store<ByteArray, byte[], byte[]>> subStores = Maps.newHashMap();
Set<Integer> sleepy = Sets.newHashSet(4, 5, 6, 7);
for (Node n : cluster.getNodes()) {
Store<ByteArray, byte[], byte[]> subStore = null;
if (sleepy != null && sleepy.contains(n.getId()))
subStore = new SleepyStore<ByteArray, byte[], byte[]>(SLEEPY_TIME, new InMemoryStorageEngine<ByteArray, byte[], byte[]>("test"));
else
subStore = new InMemoryStorageEngine<ByteArray, byte[], byte[]>("test");
subStores.put(n.getId(), subStore);
}
setFailureDetector(subStores);
StoreDefinition storeDef = ServerTestUtils.getStoreDef("test", 1, 1, 1, 1, 0, 0, zoneReplicationFactor, HintedHandoffStrategyType.PROXIMITY_STRATEGY, RoutingStrategyType.ZONE_STRATEGY);
routedStoreThreadPool = Executors.newFixedThreadPool(8);
RoutedStoreFactory routedStoreFactory = createFactory();
Store<ByteArray, byte[], byte[]> s1 = routedStoreFactory.create(cluster, storeDef, subStores, failureDetector, createConfig(OPERATION_TIMEOUT));
RoutingStrategy routingStrategy = new RoutingStrategyFactory().updateRoutingStrategy(storeDef, cluster);
List<Node> nodesRoutedTo = routingStrategy.routeRequest("test".getBytes());
long start = System.nanoTime(), elapsed;
try {
s1.put(new ByteArray("test".getBytes()), versioned, null);
} finally {
elapsed = (System.nanoTime() - start) / Time.NS_PER_MS;
assertTrue(elapsed + " < " + SLEEPY_TIME, elapsed < SLEEPY_TIME);
}
Thread.sleep(SLEEPY_TIME - elapsed);
for (Node node : nodesRoutedTo) {
assertEquals(subStores.get(node.getId()).get(new ByteArray("test".getBytes()), null).get(0), versioned);
}
// make sure the failure detector adds back any previously failed nodes
Thread.sleep(BANNAGE_PERIOD + 100);
start = System.nanoTime();
try {
s1.delete(new ByteArray("test".getBytes()), versioned.getVersion());
} finally {
elapsed = (System.nanoTime() - start) / Time.NS_PER_MS;
assertTrue(elapsed + " < " + SLEEPY_TIME, elapsed < SLEEPY_TIME);
}
Thread.sleep(SLEEPY_TIME - elapsed);
for (Node node : nodesRoutedTo) {
assertEquals(subStores.get(node.getId()).get(new ByteArray("test".getBytes()), null).size(), 0);
}
}
use of voldemort.routing.RoutingStrategyFactory in project voldemort by voldemort.
the class RedirectingStoreTest method setUp.
@Before
public void setUp() throws IOException, InterruptedException {
currentCluster = ServerTestUtils.getLocalCluster(3, new int[][] { { 0, 1 }, { 2, 3 }, {} });
targetCluster = UpdateClusterUtils.createUpdatedCluster(currentCluster, 2, Arrays.asList(0));
this.primaryPartitionsMoved = Lists.newArrayList(0);
this.secondaryPartitionsMoved = Lists.newArrayList(2, 3);
this.storeDef = new StoreDefinitionBuilder().setName("test").setType(BdbStorageConfiguration.TYPE_NAME).setKeySerializer(new SerializerDefinition("string")).setValueSerializer(new SerializerDefinition("string")).setRoutingPolicy(RoutingTier.CLIENT).setRoutingStrategyType(RoutingStrategyType.CONSISTENT_STRATEGY).setReplicationFactor(2).setPreferredReads(1).setRequiredReads(1).setPreferredWrites(1).setRequiredWrites(1).build();
File tempStoreXml = new File(TestUtils.createTempDir(), "stores.xml");
FileUtils.writeStringToFile(tempStoreXml, new StoreDefinitionsMapper().writeStoreList(Lists.newArrayList(storeDef)));
this.servers = new VoldemortServer[3];
for (int nodeId = 0; nodeId < 3; nodeId++) {
this.servers[nodeId] = startServer(nodeId, tempStoreXml.getAbsolutePath(), currentCluster);
}
// Start another node for only this unit test
HashMap<ByteArray, byte[]> entrySet = ServerTestUtils.createRandomKeyValuePairs(100);
SocketStoreClientFactory factory = new SocketStoreClientFactory(new ClientConfig().setBootstrapUrls(Lists.newArrayList("tcp://" + currentCluster.getNodeById(0).getHost() + ":" + currentCluster.getNodeById(0).getSocketPort())));
StoreClient<Object, Object> storeClient = factory.getStoreClient("test");
this.primaryEntriesMoved = Maps.newHashMap();
this.secondaryEntriesMoved = Maps.newHashMap();
this.proxyPutTestPrimaryEntries = Maps.newHashMap();
this.proxyPutTestSecondaryEntries = Maps.newHashMap();
RoutingStrategy strategy = new RoutingStrategyFactory().updateRoutingStrategy(storeDef, currentCluster);
for (Entry<ByteArray, byte[]> entry : entrySet.entrySet()) {
storeClient.put(new String(entry.getKey().get()), new String(entry.getValue()));
List<Integer> pList = strategy.getPartitionList(entry.getKey().get());
if (primaryPartitionsMoved.contains(pList.get(0))) {
primaryEntriesMoved.put(entry.getKey(), entry.getValue());
} else if (secondaryPartitionsMoved.contains(pList.get(0))) {
secondaryEntriesMoved.put(entry.getKey(), entry.getValue());
}
}
// Sleep a while for the queries to go through...
// Hope the 'God of perfect timing' is on our side
Thread.sleep(500);
// steal a few primary key-value pairs for testing proxy put logic
int cnt = 0;
for (Entry<ByteArray, byte[]> entry : primaryEntriesMoved.entrySet()) {
if (cnt > 3)
break;
this.proxyPutTestPrimaryEntries.put(entry.getKey(), entry.getValue());
cnt++;
}
for (ByteArray key : this.proxyPutTestPrimaryEntries.keySet()) {
this.primaryEntriesMoved.remove(key);
}
assertTrue("Not enough primary entries", primaryEntriesMoved.size() > 1);
// steal a few secondary key-value pairs for testing proxy put logic
cnt = 0;
for (Entry<ByteArray, byte[]> entry : secondaryEntriesMoved.entrySet()) {
if (cnt > 3)
break;
this.proxyPutTestSecondaryEntries.put(entry.getKey(), entry.getValue());
cnt++;
}
for (ByteArray key : this.proxyPutTestSecondaryEntries.keySet()) {
this.secondaryEntriesMoved.remove(key);
}
assertTrue("Not enough secondary entries", primaryEntriesMoved.size() > 1);
RebalanceBatchPlan RebalanceBatchPlan = new RebalanceBatchPlan(currentCluster, targetCluster, Lists.newArrayList(storeDef));
List<RebalanceTaskInfo> plans = Lists.newArrayList(RebalanceBatchPlan.getBatchPlan());
// Set into rebalancing state
for (RebalanceTaskInfo partitionPlan : plans) {
servers[partitionPlan.getStealerId()].getMetadataStore().put(MetadataStore.SERVER_STATE_KEY, MetadataStore.VoldemortState.REBALANCING_MASTER_SERVER);
servers[partitionPlan.getStealerId()].getMetadataStore().put(MetadataStore.REBALANCING_STEAL_INFO, new RebalancerState(Lists.newArrayList(partitionPlan)));
servers[partitionPlan.getStealerId()].getMetadataStore().put(MetadataStore.REBALANCING_SOURCE_CLUSTER_XML, currentCluster);
// update original storedefs
servers[partitionPlan.getStealerId()].getMetadataStore().put(MetadataStore.REBALANCING_SOURCE_STORES_XML, Lists.newArrayList(storeDef));
}
// Update the cluster metadata on all three nodes
for (VoldemortServer server : servers) {
server.getMetadataStore().put(MetadataStore.CLUSTER_KEY, targetCluster);
}
}
Aggregations