forked from cmu-db/benchbase
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathDBWorkload.java
1084 lines (926 loc) · 52.4 KB
/
DBWorkload.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 2020 by OLTPBenchmark Project
*
* 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.oltpbenchmark;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hubspot.jinjava.Jinjava;
import com.hubspot.jinjava.JinjavaConfig;
import com.hubspot.jinjava.interpret.RenderResult;
import com.oltpbenchmark.api.BenchmarkModule;
import com.oltpbenchmark.api.TransactionType;
import com.oltpbenchmark.api.TransactionTypes;
import com.oltpbenchmark.api.Worker;
import com.oltpbenchmark.types.DatabaseType;
import com.oltpbenchmark.util.*;
import org.apache.commons.cli.*;
import org.apache.commons.collections4.map.ListOrderedMap;
import org.apache.commons.configuration2.HierarchicalConfiguration;
import org.apache.commons.configuration2.XMLConfiguration;
import org.apache.commons.configuration2.YAMLConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.convert.DisabledListDelimiterHandler;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.configuration2.tree.ImmutableNode;
import org.apache.commons.configuration2.tree.xpath.XPathExpressionEngine;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class DBWorkload {
private static final Logger LOG = LoggerFactory.getLogger(DBWorkload.class);
private static final String SINGLE_LINE = StringUtil.repeat("=", 70);
private static final String RATE_DISABLED = "disabled";
private static final String RATE_UNLIMITED = "unlimited";
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// create the command line parser
CommandLineParser parser = new DefaultParser();
XMLConfiguration pluginConfig = buildConfiguration("config/plugin.xml");
Options options = buildOptions(pluginConfig);
CommandLine argsLine = parser.parse(options, args);
if (argsLine.hasOption("h")) {
printUsage(options);
return;
} else if (!argsLine.hasOption("c")) {
LOG.error("Missing Configuration file");
printUsage(options);
return;
} else if (!argsLine.hasOption("b")) {
LOG.error("Missing Benchmark Class to load");
printUsage(options);
return;
}
// Seconds
int intervalMonitor = 0;
if (argsLine.hasOption("im")) {
intervalMonitor = Integer.parseInt(argsLine.getOptionValue("im"));
}
// -------------------------------------------------------------------
// GET PLUGIN LIST
// -------------------------------------------------------------------
String targetBenchmarks = argsLine.getOptionValue("b");
String[] targetList = targetBenchmarks.split(",");
List<BenchmarkModule> benchList = new ArrayList<>();
List<BenchmarkModule> copyBenchList = new ArrayList<>();
// Use this list for filtering of the output
List<TransactionType> activeTXTypes = new ArrayList<>();
String configFile = argsLine.getOptionValue("c");
XMLConfiguration xmlConfig = null;
// Load the configuration for each benchmark
int lastTxnId = 0;
for (String plugin : targetList) {
String pluginTest = "[@bench='" + plugin + "']";
if (plugin.equalsIgnoreCase("featurebench"))
{
String[] params=null;
if (argsLine.hasOption("params")) {
params = argsLine.getOptionValues("params");
LOG.info("Creating modified temporary input yaml with passed parameters from : "+ configFile);
configFile = replaceParametersInYaml(params,configFile);
}
xmlConfig = buildConfigurationFromYaml(configFile);
}
else
xmlConfig = buildConfiguration(configFile);
// ----------------------------------------------------------------
// BEGIN LOADING WORKLOAD CONFIGURATION
// ----------------------------------------------------------------
WorkloadConfiguration wrkld = new WorkloadConfiguration();
wrkld.setBenchmarkName(plugin);
wrkld.setXmlConfig(xmlConfig);
// Pull in database configuration
wrkld.setDatabaseType(DatabaseType.get(xmlConfig.getString("type")));
wrkld.setDriverClass(xmlConfig.getString("driver"));
wrkld.setUrl(xmlConfig.getString("url"));
wrkld.setUsername(xmlConfig.getString("username"));
wrkld.setPassword(xmlConfig.getString("password"));
wrkld.setRandomSeed(xmlConfig.getInt("randomSeed", -1));
wrkld.setBatchSize(xmlConfig.getInt("batchsize", 128));
wrkld.setMaxRetries(xmlConfig.getInt("retries", 3));
wrkld.setNewConnectionPerTxn(xmlConfig.getBoolean("newConnectionPerTxn", false));
int terminals = xmlConfig.getInt("terminals[not(@bench)]", 0);
terminals = xmlConfig.getInt("terminals" + pluginTest, terminals);
wrkld.setTerminals(terminals);
if (xmlConfig.containsKey("loaderThreads")) {
int loaderThreads = xmlConfig.getInt("loaderThreads");
wrkld.setLoaderThreads(loaderThreads);
}
String isolationMode = xmlConfig.getString("isolation[not(@bench)]", "TRANSACTION_SERIALIZABLE");
wrkld.setIsolationMode(xmlConfig.getString("isolation" + pluginTest, isolationMode));
wrkld.setScaleFactor(xmlConfig.getDouble("scalefactor", 1.0));
wrkld.setDataDir(xmlConfig.getString("datadir", "."));
wrkld.setDDLPath(xmlConfig.getString("ddlpath", null));
double selectivity = -1;
try {
selectivity = xmlConfig.getDouble("selectivity");
wrkld.setSelectivity(selectivity);
} catch (NoSuchElementException nse) {
// Nothing to do here !
}
// ----------------------------------------------------------------
// CREATE BENCHMARK MODULE
// ----------------------------------------------------------------
String classname = pluginConfig.getString("/plugin[@name='" + plugin + "']");
if (classname == null) {
throw new ParseException("Plugin " + plugin + " is undefined in config/plugin.xml");
}
BenchmarkModule bench = ClassUtil.newInstance(classname, new Object[]{wrkld}, new Class<?>[]{WorkloadConfiguration.class});
Map<String, Object> initDebug = new ListOrderedMap<>();
initDebug.put("Benchmark", String.format("%s {%s}", plugin.toUpperCase(), classname));
initDebug.put("Configuration", configFile);
initDebug.put("Type", wrkld.getDatabaseType());
initDebug.put("Driver", wrkld.getDriverClass());
initDebug.put("URL", wrkld.getUrl());
initDebug.put("Isolation", wrkld.getIsolationString());
initDebug.put("Batch Size", wrkld.getBatchSize());
initDebug.put("Scale Factor", wrkld.getScaleFactor());
initDebug.put("Terminals", wrkld.getTerminals());
initDebug.put("New Connection Per Txn", wrkld.getNewConnectionPerTxn());
if (selectivity != -1) {
initDebug.put("Selectivity", selectivity);
}
LOG.info("{}\n\n{}", SINGLE_LINE, StringUtil.formatMaps(initDebug));
LOG.info(SINGLE_LINE);
// ----------------------------------------------------------------
// LOAD TRANSACTION DESCRIPTIONS
// ----------------------------------------------------------------
int numTxnTypes = xmlConfig.configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size();
if (numTxnTypes == 0 && targetList.length == 1) {
//if it is a single workload run, <transactiontypes /> w/o attribute is used
pluginTest = "[not(@bench)]";
numTxnTypes = xmlConfig.configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size();
}
List<HierarchicalConfiguration<ImmutableNode>> workloads =
xmlConfig.configurationsAt("microbenchmark/properties/executeRules");
int totalWorkloadCount =
plugin.equalsIgnoreCase("featurebench") ?
(workloads == null ? 1 : (workloads.size() == 0 ? 1 : workloads.size())) : 1;
boolean createDone = false;
boolean loadDone = false;
Set<String> uniqueRunWorkloads = new HashSet<>();
List<String> workloadsFromExecuteRules = new ArrayList<>();
String fileForAllWorkloadList = "allWorkloads" + ".txt";
if (workloads != null && workloads.size() != 0) {
for (int workCount = 1; workCount <= totalWorkloadCount; workCount++) {
workloadsFromExecuteRules.add(workloads.get(workCount - 1)
.containsKey("workload") ? workloads.get(workCount - 1)
.getString("workload") : String.valueOf(workCount));
}
try (PrintStream ps = new PrintStream(FileUtil.joinPath(fileForAllWorkloadList))) {
System.out.println("All Workloads:");
for (int workCount = 1; workCount <= totalWorkloadCount; workCount++) {
ps.println((workloads.get(workCount - 1)
.containsKey("workload") ? workloads.get(workCount - 1).getString("workload") : workCount));
System.out.println((workloads.get(workCount - 1)
.containsKey("workload") ? workloads.get(workCount - 1).getString("workload") : workCount));
}
}
} else {
try (PrintStream ps = new PrintStream(FileUtil.joinPath(fileForAllWorkloadList))) {
ps.println("DEFAULT_WORKLOAD");
}
}
if (isBooleanOptionSet(argsLine, "execute")) {
if ((argsLine.hasOption("workloads")) && !argsLine.getOptionValue("workloads").isEmpty()) {
List<String> runWorkloads = List.of(argsLine.getOptionValue("workloads").trim().split("\\s*,\\s*"));
uniqueRunWorkloads.addAll(runWorkloads);
uniqueRunWorkloads.forEach(uniqueWorkload -> {
if (workloadsFromExecuteRules.contains(uniqueWorkload)) {
LOG.info("Workload: " + uniqueWorkload + " will be scheduled to run");
} else if (workloadsFromExecuteRules.size() == 0 &&
uniqueWorkload.equalsIgnoreCase("DEFAULT_WORKLOAD")) {
LOG.info("Running workload specified through code implementation");
} else {
throw new RuntimeException("Wrong workload name provided in --workloads args: " + uniqueWorkload);
}
});
} else {
workloadsFromExecuteRules
.forEach(workloadFromExecuteRule -> LOG.info("Workload: "
+ workloadFromExecuteRule + " will be scheduled to run"));
uniqueRunWorkloads.addAll(workloadsFromExecuteRules);
}
}
for (int workCount = 1; workCount <= totalWorkloadCount; workCount++) {
List<HierarchicalConfiguration<ImmutableNode>> executeRules =
(workloads == null || workloads.size() == 0) ? null : workloads.get(workCount - 1)
.configurationsAt("run");
boolean isExecutePresent = xmlConfig.containsKey("microbenchmark/properties/execute");
boolean isExecuteTrue = false;
if (isExecutePresent) {
isExecuteTrue = xmlConfig.getBoolean("microbenchmark/properties/execute");
}
if (plugin.equalsIgnoreCase("featurebench")) {
if (executeRules == null) {
numTxnTypes = 1;
} else if (executeRules.size() == 0) {
executeRules = null;
numTxnTypes = 1;
} else {
if (!executeRules.get(0).containsKey("name")) {
executeRules = null;
numTxnTypes = 1;
} else {
numTxnTypes = executeRules.size();
}
}
}
List<TransactionType> ttypes = new ArrayList<>();
ttypes.add(TransactionType.INVALID);
int txnIdOffset = lastTxnId;
if (plugin.equalsIgnoreCase("featurebench")) {
txnIdOffset = 0;
}
for (int i = 1; i <= numTxnTypes; i++) {
String key = "transactiontypes" + pluginTest + "/transactiontype[" + i + "]";
String txnName = xmlConfig.getString(key + "/name");
// Get ID if specified; else increment from last one.
int txnId = i;
if (xmlConfig.containsKey(key + "/id")) {
txnId = xmlConfig.getInt(key + "/id");
}
long preExecutionWait = 0;
if (xmlConfig.containsKey(key + "/preExecutionWait")) {
preExecutionWait = xmlConfig.getLong(key + "/preExecutionWait");
}
long postExecutionWait = 0;
if (xmlConfig.containsKey(key + "/postExecutionWait")) {
postExecutionWait = xmlConfig.getLong(key + "/postExecutionWait");
}
TransactionType tmpType;
if (plugin.equalsIgnoreCase("featurebench")) {
if (isExecuteTrue) {
tmpType = bench.initTransactionType("FeatureBench", txnId + txnIdOffset, preExecutionWait,
postExecutionWait, "execute");
} else if (executeRules != null) {
tmpType = bench.initTransactionType("FeatureBench", txnId + txnIdOffset, preExecutionWait,
postExecutionWait, executeRules.get(i - 1).getString("name"));
} else {
tmpType = bench.initTransactionType("FeatureBench", txnId + txnIdOffset, preExecutionWait,
postExecutionWait, "executeOnce");
}
} else {
tmpType = bench.initTransactionType(txnName, txnId + txnIdOffset, preExecutionWait, postExecutionWait);
}
// Keep a reference for filtering
activeTXTypes.add(tmpType);
// Add a ref for the active TTypes in this benchmark
ttypes.add(tmpType);
lastTxnId = i;
}
// Wrap the list of transactions and save them
TransactionTypes tt = new TransactionTypes(ttypes);
wrkld.setTransTypes(tt);
LOG.debug("Using the following transaction types: {}", tt);
// Read in the groupings of transactions (if any) defined for this
// benchmark
int numGroupings = xmlConfig.configurationsAt("transactiontypes" + pluginTest + "/groupings/grouping").size();
LOG.debug("Num groupings: {}", numGroupings);
for (int i = 1; i < numGroupings + 1; i++) {
String key = "transactiontypes" + pluginTest + "/groupings/grouping[" + i + "]";
// Get the name for the grouping and make sure it's valid.
String groupingName = xmlConfig.getString(key + "/name").toLowerCase();
if (!groupingName.matches("^[a-z]\\w*$")) {
LOG.error(String.format("Grouping name \"%s\" is invalid." + " Must begin with a letter and contain only" + " alphanumeric characters.", groupingName));
System.exit(-1);
} else if (groupingName.equals("all")) {
LOG.error("Grouping name \"all\" is reserved." + " Please pick a different name.");
System.exit(-1);
}
// Get the weights for this grouping and make sure that there
// is an appropriate number of them.
List<String> groupingWeights = Arrays.asList(xmlConfig.getString(key + "/weights").split("\\s*,\\s*"));
if (groupingWeights.size() != numTxnTypes) {
LOG.error(String.format("Grouping \"%s\" has %d weights," + " but there are %d transactions in this" + " benchmark.", groupingName, groupingWeights.size(), numTxnTypes));
System.exit(-1);
}
LOG.debug("Creating grouping with name, weights: {}, {}", groupingName, groupingWeights);
}
benchList.add(bench);
if (workCount == 1) {
copyBenchList.add(bench);
}
// ----------------------------------------------------------------
// WORKLOAD CONFIGURATION
// ----------------------------------------------------------------
int size = xmlConfig.configurationsAt("/works/work").size();
for (int i = 1; i < size + 1; i++) {
final HierarchicalConfiguration<ImmutableNode> work = xmlConfig.configurationAt("works/work[" + i + "]");
List<String> weight_strings;
// use a workaround if there are multiple workloads or single
// attributed workload
int time = work.getInt("/time", 0);
int warmup = work.getInt("/warmup", 0);
if (targetList.length > 1 || work.containsKey("weights[@bench]")) {
weight_strings = Arrays.asList(work.getString("weights" + pluginTest).split("\\s*,\\s*"));
} else if (plugin.equalsIgnoreCase("featurebench")) {
weight_strings = List.of();
time = work.getInt("/time_secs", 0);
} else {
weight_strings = Arrays.asList(work.getString("weights[not(@bench)]").split("\\s*,\\s*"));
}
int rate = 1;
boolean rateLimited = true;
boolean disabled = false;
boolean timed;
// can be "disabled", "unlimited" or a number
String rate_string;
rate_string = work.getString("rate[not(@bench)]", "");
rate_string = work.getString("rate" + pluginTest, rate_string);
if (rate_string.equals(RATE_DISABLED)) {
disabled = true;
} else if (rate_string.equals(RATE_UNLIMITED)) {
rateLimited = false;
} else if (rate_string.isEmpty()) {
LOG.error(String.format("Please specify the rate for phase %d and workload %s", i, plugin));
System.exit(-1);
} else {
try {
rate = Integer.parseInt(rate_string);
if (rate < 1) {
LOG.error("Rate limit must be at least 1. Use unlimited or disabled values instead.");
System.exit(-1);
}
} catch (NumberFormatException e) {
LOG.error(String.format("Rate string must be '%s', '%s' or a number", RATE_DISABLED, RATE_UNLIMITED));
System.exit(-1);
}
}
Phase.Arrival arrival = Phase.Arrival.REGULAR;
String arrive = work.getString("@arrival", "regular");
if (arrive.equalsIgnoreCase("POISSON")) {
arrival = Phase.Arrival.POISSON;
}
// We now have the option to run all queries exactly once in
// a serial (rather than random) order.
boolean serial = Boolean.parseBoolean(work.getString("serial", Boolean.FALSE.toString()));
int activeTerminals;
activeTerminals = work.getInt("active_terminals[not(@bench)]", terminals);
activeTerminals = work.getInt("active_terminals" + pluginTest, activeTerminals);
// If using serial, we should have only one terminal
if (serial && activeTerminals != 1) {
LOG.warn("Serial ordering is enabled, so # of active terminals is clamped to 1.");
activeTerminals = 1;
}
if (activeTerminals > terminals) {
LOG.error(String.format("Configuration error in work %d: " + "Number of active terminals is bigger than the total number of terminals", i));
System.exit(-1);
}
//----------->
if (plugin.equalsIgnoreCase("featurebench") && executeRules == null && !isExecuteTrue) {
serial = true;
time = 0;
}
timed = (time > 0);
if (!timed) {
if (serial) {
LOG.info("Timer disabled for serial run; will execute" + " all queries exactly once.");
} else {
LOG.error("Must provide positive time bound for" + " non-serial executions. Either provide" + " a valid time or enable serial mode.");
System.exit(-1);
}
} else if (serial) {
LOG.info("Timer enabled for serial run; will run queries" + " serially in a loop until the timer expires.");
}
if (warmup < 0) {
LOG.error("Must provide non-negative time bound for" + " warmup.");
System.exit(-1);
}
ArrayList<Double> weights = new ArrayList<>();
double totalWeight = 0;
if (plugin.equalsIgnoreCase("featurebench")) {
if (executeRules == null) {
totalWeight = 100;
weights.add(100.0);
} else {
double defaultweight = 100.0 / executeRules.size();
boolean containWeight = executeRules.get(0).containsKey("weight");
for (HierarchicalConfiguration<ImmutableNode> rule : executeRules) {
double weight;
if (containWeight) {
if (!rule.containsKey("weight")) {
throw new RuntimeException("Please Provide weight or not to all queries");
}
weight = rule.getDouble("weight");
} else {
if (rule.containsKey("weight")) {
throw new RuntimeException("Please Provide weight or not to all queries");
}
weight = defaultweight;
}
totalWeight += weight;
weights.add(weight);
}
}
} else {
for (String weightString : weight_strings) {
double weight = Double.parseDouble(weightString);
totalWeight += weight;
weights.add(weight);
}
}
long roundedWeight = Math.round(totalWeight);
if (roundedWeight != 100) {
LOG.warn("rounded weight [{}] does not equal 100. Original weight is [{}]", roundedWeight, totalWeight);
}
wrkld.addPhase(i, time, warmup, rate, weights, rateLimited, disabled, serial, timed, activeTerminals, arrival);
}
// CHECKING INPUT PHASES
int j = 0;
for (Phase p : wrkld.getPhases()) {
j++;
if (p.getWeightCount() != numTxnTypes) {
LOG.error(String.format("Configuration files is inconsistent, phase %d contains %d weights but you defined %d transaction types", j, p.getWeightCount(), numTxnTypes));
if (p.isSerial()) {
LOG.error("However, note that since this a serial phase, the weights are irrelevant (but still must be included---sorry).");
}
System.exit(-1);
}
}
// Generate the dialect map
wrkld.init();
// Export StatementDialects
if (isBooleanOptionSet(argsLine, "dialects-export")) {
BenchmarkModule benchtemp = benchList.get(0);
if (benchtemp.getStatementDialects() != null) {
LOG.info("Exporting StatementDialects for {}", benchtemp);
String xml = benchtemp.getStatementDialects().export(benchtemp.getWorkloadConfiguration().getDatabaseType(), benchtemp.getProcedures().values());
LOG.debug(xml);
System.exit(0);
}
throw new RuntimeException("No StatementDialects is available for " + benchtemp);
}
// Create the Benchmark's Database
if (isBooleanOptionSet(argsLine, "create") && !createDone) {
try {
for (BenchmarkModule benchmark : benchList) {
LOG.info("Creating new {} database...", benchmark.getBenchmarkName().toUpperCase());
if (benchmark.getBenchmarkName().equalsIgnoreCase("featurebench") && benchmark.getWorkloadConfiguration().getXmlConfig().containsKey("createdb")) {
String newUrl = runCreatorDB(benchmark, benchmark.getWorkloadConfiguration().getXmlConfig().getString("createdb"));
LOG.info("New JDBC URL : " + newUrl);
benchmark.getWorkloadConfiguration().setUrl(newUrl);
benchmark.getWorkloadConfiguration().getXmlConfig().setProperty("url", newUrl);
}
runCreator(benchmark);
LOG.info("Finished creating new {} database...", benchmark.getBenchmarkName().toUpperCase());
}
} catch (Throwable ex) {
LOG.error("Unexpected error when creating benchmark database tables.", ex);
System.exit(1);
}
createDone = true;
} else {
LOG.debug("Skipping creating benchmark database tables");
}
if (!isBooleanOptionSet(argsLine, "create") && !createDone) {
for (BenchmarkModule benchmark : benchList) {
if (benchmark.getBenchmarkName().equalsIgnoreCase("featurebench") && benchmark.getWorkloadConfiguration().getXmlConfig().containsKey("createdb")) {
String newUrl = getNewUrl(benchmark, benchmark.getWorkloadConfiguration().getXmlConfig().getString("createdb"));
LOG.info("New JDBC URL : " + newUrl);
benchmark.getWorkloadConfiguration().setUrl(newUrl);
benchmark.getWorkloadConfiguration().getXmlConfig().setProperty("url", newUrl);
}
}
createDone = true;
}
// Refresh the catalog.
for (BenchmarkModule benchmark : benchList) {
benchmark.refreshCatalog();
}
// Clear the Benchmark's Database
if (isBooleanOptionSet(argsLine, "clear")) {
try {
for (BenchmarkModule benchmark : benchList) {
LOG.info("Clearing {} database...", benchmark.getBenchmarkName().toUpperCase());
benchmark.refreshCatalog();
benchmark.clearDatabase();
benchmark.refreshCatalog();
LOG.info("Finished clearing {} database...", benchmark.getBenchmarkName().toUpperCase());
}
} catch (Throwable ex) {
LOG.error("Unexpected error when clearing benchmark database tables.", ex);
System.exit(1);
}
} else {
LOG.debug("Skipping clearing benchmark database tables");
}
// Execute Loader
if (isBooleanOptionSet(argsLine, "load") && !loadDone) {
try {
for (BenchmarkModule benchmark : benchList) {
LOG.info("Loading data into {} database...", benchmark.getBenchmarkName().toUpperCase());
runLoader(benchmark);
LOG.info("Finished loading data into {} database...", benchmark.getBenchmarkName().toUpperCase());
}
} catch (Throwable ex) {
LOG.error("Unexpected error when loading benchmark database records.", ex);
System.exit(1);
}
loadDone = true;
} else {
LOG.debug("Skipping loading benchmark database records");
}
if (isBooleanOptionSet(argsLine, "execute") && (argsLine.hasOption("workloads")) && executeRules != null) {
String val = workloads.get(workCount - 1).getString("workload");
if (uniqueRunWorkloads.contains(val) || uniqueRunWorkloads.contains("DEFAULT_WORKLOAD")) {
LOG.info("Starting Workload " + (workloads.get(workCount - 1).containsKey("workload") ? workloads.get(workCount - 1).getString("workload") : workCount));
try {
Results r = runWorkload(benchList, intervalMonitor, workCount);
writeOutputs(r, activeTXTypes, argsLine, xmlConfig, executeRules == null ? null : workloads.get(workCount - 1).getString("workload"));
writeHistograms(r);
if (argsLine.hasOption("json-histograms")) {
String histogram_json = writeJSONHistograms(r);
String fileName = argsLine.getOptionValue("json-histograms");
FileUtil.writeStringToFile(new File(fileName), histogram_json);
LOG.info("Histograms JSON Data: " + fileName);
}
} catch (Throwable ex) {
LOG.error("Unexpected error when executing benchmarks.", ex);
System.exit(1);
}
}
}
// Execute Workload
else if (isBooleanOptionSet(argsLine, "execute")) {
if (executeRules == null) {
LOG.info("Starting Workload " + workCount);
} else {
LOG.info("Starting Workload " + (workloads.get(workCount - 1).containsKey("workload") ? workloads.get(workCount - 1).getString("workload") : workCount));
}
// Bombs away!
try {
Results r = runWorkload(benchList, intervalMonitor, workCount);
// if block currently only valid for bulkload experiments
if(xmlConfig.containsKey("microbenchmark/properties/workload")) {
writeOutputs(r, activeTXTypes, argsLine, xmlConfig, xmlConfig.getString("microbenchmark/properties/workload"));
}
else {
writeOutputs(r, activeTXTypes, argsLine, xmlConfig, executeRules == null ? null : workloads.get(workCount - 1).getString("workload"));
}
writeHistograms(r);
if (argsLine.hasOption("json-histograms")) {
String histogram_json = writeJSONHistograms(r);
String fileName = argsLine.getOptionValue("json-histograms");
FileUtil.writeStringToFile(new File(fileName), histogram_json);
LOG.info("Histograms JSON Data: " + fileName);
}
} catch (Throwable ex) {
LOG.error("Unexpected error when executing benchmarks.", ex);
System.exit(1);
}
} else {
LOG.info("Skipping benchmark workload execution");
}
benchList.clear();
wrkld.clearPhase();
activeTXTypes.clear();
}
if (argsLine.hasOption("cleanup") && isBooleanOptionSet(argsLine, "cleanup")) {
for (BenchmarkModule benchmarkModule : copyBenchList) {
if (xmlConfig.containsKey("microbenchmark/properties/cleanup")) {
List<String> ddls = xmlConfig.getList(String.class, "microbenchmark/properties/cleanup");
try {
Statement stmtObj = benchmarkModule.makeConnection().createStatement();
for (String ddl : ddls) {
stmtObj.execute(ddl);
}
LOG.info("\n=================Cleanup Phase taking from Yaml=========\n");
stmtObj.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
else {
LOG.info("No cleanup phase mentioned in YAML, but flag provided in run! ");
}
}
}
}
}
private static Options buildOptions(XMLConfiguration pluginConfig) {
Options options = new Options();
options.addOption("b", "bench", true, "[required] Benchmark class. Currently supported: " + pluginConfig.getList("/plugin//@name"));
options.addOption("c", "config", true, "[required] Workload configuration file");
options.addOption(null, "create", true, "Initialize the database for this benchmark");
options.addOption(null, "clear", true, "Clear all records in the database for this benchmark");
options.addOption(null, "load", true, "Load data using the benchmark's data loader");
options.addOption(null, "execute", true, "Execute the benchmark workload");
options.addOption("h", "help", false, "Print this help");
options.addOption("s", "sample", true, "Sampling window");
options.addOption("im", "interval-monitor", true, "Throughput Monitoring Interval in milliseconds");
options.addOption("d", "directory", true, "Base directory for the result files, default is current directory");
options.addOption(null, "dialects-export", true, "Export benchmark SQL to a dialects file");
options.addOption("jh", "json-histograms", true, "Export histograms to JSON file");
options.addOption("workloads", "workloads", true, "Run some specific workloads");
options.addOption("p", "params", true, "Use varibles through CLI for YAML");
options.addOption(null, "cleanup", true, "Clean up the database");
return options;
}
private static XMLConfiguration buildConfiguration(String filename) throws ConfigurationException {
Parameters params = new Parameters();
FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>(XMLConfiguration.class).configure(params.xml().setFileName(filename).setListDelimiterHandler(new DisabledListDelimiterHandler()).setExpressionEngine(new XPathExpressionEngine()));
return builder.getConfiguration();
}
private static XMLConfiguration buildConfigurationFromYaml(String filename) throws ConfigurationException {
Parameters params = new Parameters();
FileBasedConfigurationBuilder<YAMLConfiguration> builder = new FileBasedConfigurationBuilder<>(YAMLConfiguration.class).configure(params.hierarchical().setFileName(filename).setListDelimiterHandler(new DisabledListDelimiterHandler()).setExpressionEngine(new XPathExpressionEngine()));
XMLConfiguration conf = new XMLConfiguration(builder.getConfiguration());
conf.setListDelimiterHandler(new DisabledListDelimiterHandler());
conf.setExpressionEngine(new XPathExpressionEngine());
return conf;
}
private static void writeHistograms(Results r) {
StringBuilder sb = new StringBuilder();
sb.append("\n");
sb.append(StringUtil.bold("Completed Transactions:")).append("\n").append(r.getSuccess()).append("\n\n");
sb.append(StringUtil.bold("Aborted Transactions:")).append("\n").append(r.getAbort()).append("\n\n");
sb.append(StringUtil.bold("Rejected Transactions (Server Retry):")).append("\n").append(r.getRetry()).append("\n\n");
sb.append(StringUtil.bold("Rejected Transactions (Retry Different):")).append("\n").append(r.getRetryDifferent()).append("\n\n");
sb.append(StringUtil.bold("Unexpected SQL Errors:")).append("\n").append(r.getError()).append("\n\n");
sb.append(StringUtil.bold("Unknown Status Transactions:")).append("\n").append(r.getUnknown()).append("\n\n");
sb.append(StringUtil.bold("Zero Rows Transactions:")).append("\n").append(r.getZeroRows()).append("\n\n");
if (!r.getAbortMessages().isEmpty()) {
sb.append("\n\n").append(StringUtil.bold("User Aborts:")).append("\n").append(r.getAbortMessages());
}
LOG.info(SINGLE_LINE);
LOG.info("Workload Histograms:\n{}", sb);
LOG.info(SINGLE_LINE);
}
private static String writeJSONHistograms(Results r) {
Map<String, JSONSerializable> map = new HashMap<>();
map.put("completed", r.getSuccess());
map.put("aborted", r.getAbort());
map.put("rejected", r.getRetry());
map.put("unexpected", r.getError());
return JSONUtil.toJSONString(map);
}
/**
* Write out the results for a benchmark run to a bunch of files
*
* @param r
* @param activeTXTypes
* @param argsLine
* @param xmlConfig
* @throws Exception
*/
private static void writeOutputs(Results r, List<TransactionType> activeTXTypes, CommandLine argsLine, XMLConfiguration xmlConfig, String workload_name) throws Exception {
// If an output directory is used, store the information
String outputDirectory = "results";
String filePathForOutputJson = "results/output.json";
Map<String, Map<String, Object>> workloadToSummaryMap = new TreeMap<>();
if (argsLine.hasOption("d")) {
outputDirectory = argsLine.getOptionValue("d");
}
if (activeTXTypes.get(0).getName().equalsIgnoreCase("featurebench")) {
outputDirectory = outputDirectory + "/" + (workload_name == null ? TimeUtil.getCurrentTimeString() : (workload_name + "/" + TimeUtil.getCurrentTimeString()));
}
FileUtil.makeDirIfNotExists(outputDirectory);
ResultWriter rw = new ResultWriter(r, xmlConfig, argsLine);
String name = StringUtils.join(StringUtils.split(argsLine.getOptionValue("b"), ','), '-');
String baseFileName = name;
int windowSize = Integer.parseInt(argsLine.getOptionValue("s", "5"));
String rawFileName = baseFileName + ".raw.csv";
try (PrintStream ps = new PrintStream(FileUtil.joinPath(outputDirectory, rawFileName))) {
LOG.info("Output Raw data into file: {}", rawFileName);
rw.writeRaw(activeTXTypes, ps);
}
String sampleFileName = baseFileName + ".samples.csv";
try (PrintStream ps = new PrintStream(FileUtil.joinPath(outputDirectory, sampleFileName))) {
LOG.info("Output samples into file: {}", sampleFileName);
rw.writeSamples(ps);
}
String summaryFileName = baseFileName + ".summary.json";
try (PrintStream ps = new PrintStream(FileUtil.joinPath(outputDirectory, summaryFileName))) {
LOG.info("Output summary data into file: {}", summaryFileName);
rw.writeSummary(ps);
}
String paramsFileName = baseFileName + ".params.json";
try (PrintStream ps = new PrintStream(FileUtil.joinPath(outputDirectory, paramsFileName))) {
LOG.info("Output DBMS parameters into file: {}", paramsFileName);
rw.writeParams(ps);
}
if (rw.hasMetrics()) {
String metricsFileName = baseFileName + ".metrics.json";
try (PrintStream ps = new PrintStream(FileUtil.joinPath(outputDirectory, metricsFileName))) {
LOG.info("Output DBMS metrics into file: {}", metricsFileName);
rw.writeMetrics(ps);
}
}
if (name.equalsIgnoreCase("featurebench")) {
String configFileName = baseFileName + ".config.yaml";
try (PrintStream ps = new PrintStream(FileUtil.joinPath(outputDirectory, configFileName))) {
LOG.info("Output benchmark config into file: {}", configFileName);
rw.writeYamlConfig(ps);
}
String fbDetailedFileName = baseFileName + ".detailed.json";
try (PrintStream ps = new PrintStream(FileUtil.joinPath(outputDirectory, fbDetailedFileName))) {
LOG.info("Output detailed summary into file: {}", fbDetailedFileName);
File file = new File(filePathForOutputJson);
if (file.exists()) {
ObjectMapper mapper = new ObjectMapper(new JsonFactory());
workloadToSummaryMap.putAll(mapper.readValue(file, TreeMap.class));
}
if(workload_name == null || workload_name.isEmpty())
workload_name = baseFileName;
workloadToSummaryMap.put(workload_name, rw.writeDetailedSummary(ps));
try {
FileWriter writer = new FileWriter(filePathForOutputJson);
writer.write(JSONUtil.format(JSONUtil.toJSONString(workloadToSummaryMap)));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
String configFileName = baseFileName + ".config.xml";
try (PrintStream ps = new PrintStream(FileUtil.joinPath(outputDirectory, configFileName))) {
LOG.info("Output benchmark config into file: {}", configFileName);
rw.writeConfig(ps);
}
}
String resultsFileName = baseFileName + ".results.csv";
try (PrintStream ps = new PrintStream(FileUtil.joinPath(outputDirectory, resultsFileName))) {
LOG.info("Output results into file: {} with window size {}", resultsFileName, windowSize);
rw.writeResults(windowSize, ps);
}
if (name.equalsIgnoreCase("featurebench")) {
for (TransactionType t : activeTXTypes) {
String fileName = baseFileName + ".results." + t.getTransactionName() + ".csv";
try (PrintStream ps = new PrintStream(FileUtil.joinPath(outputDirectory, fileName))) {
rw.writeResults(windowSize, ps, t);
}
}
} else {
for (TransactionType t : activeTXTypes) {
String fileName = baseFileName + ".results." + t.getName() + ".csv";
try (PrintStream ps = new PrintStream(FileUtil.joinPath(outputDirectory, fileName))) {
rw.writeResults(windowSize, ps, t);
}
}
}
}
private static void runCreator(BenchmarkModule bench) throws SQLException, IOException {
LOG.debug(String.format("Creating %s Database", bench));
bench.createDatabase();
}
private static String runCreatorDB(BenchmarkModule benchmark, String totalDDL) throws SQLException {
Statement stmtObj = benchmark.makeConnection().createStatement();
stmtObj.execute(totalDDL);
Pattern patternCreateDB = Pattern.compile("create database (.+?) ", Pattern.CASE_INSENSITIVE);
Matcher matcherCreateDB = patternCreateDB.matcher(totalDDL);
boolean matchFoundforcreate = matcherCreateDB.find();
String createDDL = matcherCreateDB.group(0);
String pattern = "database\\s(\\w+)\\s";
Pattern db = Pattern.compile(pattern);
Matcher m = db.matcher(createDDL);
String dbName = "";
if (m.find()) {
dbName = m.group(1);
} else {
LOG.warn("Incorrect DDL for create database");
}
String url = benchmark.getWorkloadConfiguration().getUrl();
String[] pieces = url.split("\\?", 10);
Pattern p = Pattern.compile("[a-zA-Z_]+$", Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(pieces[0]);
boolean matchFound = matcher.find();
if (matchFound) {
LOG.info(matcher.group(0));
} else {
LOG.info("No match!");
}
int index = url.indexOf(matcher.group(0), url.indexOf(matcher.group(0)) + 1);
String newUrl = url.substring(0, index) + dbName + url.substring(index + matcher.group(0).length());
stmtObj.close();
return newUrl;
}
private static String getNewUrl(BenchmarkModule benchmark, String totalDDL) throws SQLException {
Pattern patternCreateDB = Pattern.compile("create database (.+?) ", Pattern.CASE_INSENSITIVE);
Matcher matcherCreateDB = patternCreateDB.matcher(totalDDL);
boolean matchFoundforcreate = matcherCreateDB.find();
String createDDL = matcherCreateDB.group(0);
String pattern = "database\\s(\\w+)\\s";
Pattern db = Pattern.compile(pattern);
Matcher m = db.matcher(createDDL);
String dbName = "";
if (m.find()) {
dbName = m.group(1);
} else {
LOG.warn("Incorrect DDL for create database");
}
String url = benchmark.getWorkloadConfiguration().getUrl();
String[] pieces = url.split("\\?", 10);
Pattern p = Pattern.compile("[a-zA-Z_]+$", Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(pieces[0]);
boolean matchFound = matcher.find();
if (matchFound) {
LOG.info(matcher.group(0));
} else {
LOG.info("No match!");
}
int index = url.indexOf(matcher.group(0), url.indexOf(matcher.group(0)) + 1);
return url.substring(0, index) + dbName + url.substring(index + matcher.group(0).length());
}
private static void runLoader(BenchmarkModule bench) throws SQLException, InterruptedException {
LOG.debug(String.format("Loading %s Database", bench));
bench.loadDatabase();
}
private static Results runWorkload(List<BenchmarkModule> benchList, int intervalMonitor, int workcount) throws IOException {
List<Worker<?>> workers = new ArrayList<>();
List<WorkloadConfiguration> workConfs = new ArrayList<>();