forked from voldemort/voldemort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KeyDistributionGenerator.java
344 lines (300 loc) · 14.6 KB
/
KeyDistributionGenerator.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
/*
* Copyright 2013 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.utils;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import voldemort.cluster.Cluster;
import voldemort.cluster.Node;
import voldemort.routing.RoutingStrategy;
import voldemort.routing.RoutingStrategyFactory;
import voldemort.routing.RoutingStrategyType;
import voldemort.store.StoreDefinition;
import voldemort.xml.ClusterMapper;
import voldemort.xml.StoreDefinitionsMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
public class KeyDistributionGenerator {
private final static DecimalFormat formatter = new DecimalFormat("#.##");
public final static int DEFAULT_NUM_KEYS = 10000;
public static void main(String args[]) throws IOException {
OptionParser parser = new OptionParser();
parser.accepts("help", "print help information");
parser.accepts("cluster-xml", "[REQUIRED] cluster xml file location")
.withRequiredArg()
.describedAs("path");
parser.accepts("stores-xml", "[REQUIRED] stores xml file location")
.withRequiredArg()
.describedAs("path");
parser.accepts("num-keys", "Number of keys to query [Default : " + DEFAULT_NUM_KEYS + "]")
.withRequiredArg()
.describedAs("number")
.ofType(Integer.class);
OptionSet options = parser.parse(args);
if(options.has("help")) {
parser.printHelpOn(System.out);
System.exit(0);
}
Set<String> missing = CmdUtils.missing(options, "cluster-xml", "stores-xml");
if(missing.size() > 0) {
System.err.println("Missing required arguments: " + Joiner.on(", ").join(missing));
parser.printHelpOn(System.err);
System.exit(1);
}
// compulsory params
String clusterXml = (String) options.valueOf("cluster-xml");
String storesXml = (String) options.valueOf("stores-xml");
Integer numKeys = CmdUtils.valueOf(options, "num-keys", DEFAULT_NUM_KEYS);
if(numKeys <= 0) {
System.err.println("Number of keys should be greater than 0");
System.exit(1);
}
Cluster cluster = new ClusterMapper().readCluster(new File(clusterXml));
List<StoreDefinition> storeDefs = new StoreDefinitionsMapper().readStoreList(new File(storesXml));
List<ByteArray> keys = generateKeys(numKeys);
// Print distribution for every store
for(StoreDefinition def: storeDefs) {
HashMap<Integer, Double> storeDistribution = generateDistribution(cluster, def, keys);
System.out.println("For Store " + def.getName());
printDistribution(storeDistribution);
System.out.println("Std dev - " + getStdDeviation(storeDistribution));
System.out.println("=========================");
}
HashMap<Integer, Double> overallDistribution = generateOverallDistribution(cluster,
storeDefs,
keys);
System.out.println("Overall distribution ");
printDistribution(overallDistribution);
System.out.println("Std dev - " + getStdDeviation(overallDistribution));
}
/**
* Given the cluster metadata and list of store definitions, presents a
* string of the store wise distribution
*
* @param cluster The cluster metadata
* @param storeDefs List of store definitions
* @param keys List of byte keys
* @return String representation
*/
public static String printStoreWiseDistribution(Cluster cluster,
List<StoreDefinition> storeDefs,
List<ByteArray> keys) {
StringBuilder builder = new StringBuilder();
// Print distribution for every store
for(StoreDefinition def: storeDefs) {
HashMap<Integer, Double> storeDistribution = generateDistribution(cluster, def, keys);
builder.append("\nFor Store '" + def.getName() + "' \n");
for(int nodeId: storeDistribution.keySet()) {
builder.append("Node " + nodeId + " - "
+ formatter.format(storeDistribution.get(nodeId)) + " \n");
}
builder.append("Std dev - " + getStdDeviation(storeDistribution) + "\n");
}
return builder.toString();
}
/**
* Given the cluster metadata and list of store definitions, presents a
* string of the distribution
*
* @param cluster The cluster metadata
* @param storeDefs List of store definitions
* @param keys List of keys
* @return String representation
*/
public static String printOverallDistribution(Cluster cluster,
List<StoreDefinition> storeDefs,
List<ByteArray> keys) {
StringBuilder builder = new StringBuilder();
HashMap<Integer, Double> distribution = generateOverallDistribution(cluster,
storeDefs,
keys);
builder.append("Cluster('");
builder.append(cluster.getName());
builder.append("', [ ");
for(Node n: cluster.getNodes()) {
builder.append(" Node " + n.getId());
builder.append(" (" + formatter.format(distribution.get(n.getId())) + ")");
builder.append(", ");
}
builder.append("], Std dev - " + getStdDeviation(distribution) + ")");
return builder.toString();
}
public static HashMap<Integer, Double> generateOverallDistribution(Cluster cluster,
List<StoreDefinition> storeDefs,
List<ByteArray> keys) {
return generateOverallDistributionWithUniqueStores(cluster,
getUniqueStoreDefinitionsWithCounts(storeDefs),
keys);
}
public static HashMap<Integer, Double> generateOverallDistributionWithUniqueStores(Cluster cluster,
HashMap<StoreDefinition, Integer> uniqueStoreDefsWithCount,
List<ByteArray> keys) {
HashMap<Integer, Double> overallDistributionCount = Maps.newHashMap();
for(Node node: cluster.getNodes()) {
overallDistributionCount.put(node.getId(), 0.0);
}
int totalStores = 0;
for(Entry<StoreDefinition, Integer> entry: uniqueStoreDefsWithCount.entrySet()) {
HashMap<Integer, Double> nodeDistribution = generateDistribution(cluster,
entry.getKey(),
keys);
for(int nodeId: nodeDistribution.keySet()) {
overallDistributionCount.put(nodeId,
overallDistributionCount.get(nodeId)
+ (nodeDistribution.get(nodeId) * entry.getValue()));
}
totalStores += entry.getValue();
}
// Normalize it
for(int nodeId: overallDistributionCount.keySet()) {
overallDistributionCount.put(nodeId, overallDistributionCount.get(nodeId)
/ (totalStores * 100.0) * 100.0);
}
return overallDistributionCount;
}
/**
* Generates distribution for a specific store definition
*
* @param cluster The cluster metadata
* @param storeDef The store definition metadata
* @param keys The list of keys as bytes
* @return Map of node id to their corresponding %age distribution
*/
public static HashMap<Integer, Double> generateDistribution(Cluster cluster,
StoreDefinition storeDef,
List<ByteArray> keys) {
RoutingStrategyFactory factory = new RoutingStrategyFactory();
RoutingStrategy strategy = factory.updateRoutingStrategy(storeDef, cluster);
HashMap<Integer, Long> requestRouting = Maps.newHashMap();
Long total = new Long(0);
for(ByteArray key: keys) {
List<Node> nodes = strategy.routeRequest(key.get());
for(Node node: nodes) {
Long count = requestRouting.get(node.getId());
if(count == null) {
count = new Long(0);
}
count++;
requestRouting.put(node.getId(), count);
total++;
}
}
HashMap<Integer, Double> finalDistribution = Maps.newHashMap();
for(int nodeId: requestRouting.keySet()) {
finalDistribution.put(nodeId, new Double((requestRouting.get(nodeId) * 100.0) / total));
}
return finalDistribution;
}
// TODO: (refactor) this method should either be part of ClusterInstance or
// of PartitionBalance.
/**
* Given a list of store definitions, find out and return a map of similar
* store definitions + count of them
*
* @param storeDefs All store definitions
* @return Map of a unique store definition + counts
*/
public static HashMap<StoreDefinition, Integer> getUniqueStoreDefinitionsWithCounts(List<StoreDefinition> storeDefs) {
HashMap<StoreDefinition, Integer> uniqueStoreDefs = Maps.newHashMap();
for(StoreDefinition storeDef: storeDefs) {
if(uniqueStoreDefs.isEmpty()) {
uniqueStoreDefs.put(storeDef, 1);
} else {
StoreDefinition sameStore = null;
// Go over all the other stores to find if this is unique
for(StoreDefinition uniqueStoreDef: uniqueStoreDefs.keySet()) {
if(uniqueStoreDef.getReplicationFactor() == storeDef.getReplicationFactor()
&& uniqueStoreDef.getRoutingStrategyType()
.compareTo(storeDef.getRoutingStrategyType()) == 0) {
// Further check for the zone routing case
if(uniqueStoreDef.getRoutingStrategyType()
.compareTo(RoutingStrategyType.ZONE_STRATEGY) == 0) {
boolean zonesSame = true;
for(int zoneId: uniqueStoreDef.getZoneReplicationFactor().keySet()) {
if(storeDef.getZoneReplicationFactor().get(zoneId) == null
|| storeDef.getZoneReplicationFactor().get(zoneId) != uniqueStoreDef.getZoneReplicationFactor()
.get(zoneId)) {
zonesSame = false;
break;
}
}
if(zonesSame) {
sameStore = uniqueStoreDef;
}
} else {
sameStore = uniqueStoreDef;
}
if(sameStore != null) {
// Bump up the count
int currentCount = uniqueStoreDefs.get(sameStore);
uniqueStoreDefs.put(sameStore, currentCount + 1);
break;
}
}
}
if(sameStore == null) {
// New store
uniqueStoreDefs.put(storeDef, 1);
}
}
}
return uniqueStoreDefs;
}
public static List<ByteArray> generateKeys(int numKeys) {
List<ByteArray> keys = Lists.newArrayList();
for(int i = 0; i < numKeys; i++) {
keys.add(new ByteArray(("key" + i).getBytes()));
}
return keys;
}
public static void printDistribution(HashMap<Integer, Double> distribution) {
for(int nodeId: distribution.keySet()) {
System.out.println("Node " + nodeId + " - "
+ formatter.format(distribution.get(nodeId)));
}
}
public static double getStdDeviation(HashMap<Integer, Double> distribution) {
HashMap<Integer, Double> expectedDistribution = Maps.newHashMap();
int numberOfNodes = distribution.keySet().size();
double distributionPerNode = 100.0 / numberOfNodes;
for(int nodeId = 0; nodeId < numberOfNodes; nodeId++) {
expectedDistribution.put(nodeId, distributionPerNode);
}
return getStdDeviation(distribution, expectedDistribution);
}
private static double getStdDeviation(HashMap<Integer, Double> distribution,
HashMap<Integer, Double> expectedDistribution) {
HashMap<Integer, Double> offBy = Maps.newHashMap();
for(Integer nodeId: distribution.keySet()) {
offBy.put(nodeId,
new Double(expectedDistribution.get(nodeId) - distribution.get(nodeId)));
}
double sum = 0, squareSum = 0;
for(double num: offBy.values()) {
squareSum += num * num;
sum += num;
}
double mean = sum / distribution.size();
return Math.sqrt(squareSum / distribution.size() - mean * mean);
}
}