| 1 | /* |
| 2 | * Copyright (C) 2012-2015 DataStax Inc. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | package com.datastax.driver.stress; |
| 17 | |
| 18 | import com.datastax.driver.core.*; |
| 19 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 20 | import joptsimple.*; |
| 21 | import org.apache.log4j.PropertyConfigurator; |
| 22 | |
| 23 | import java.io.IOException; |
| 24 | import java.util.HashMap; |
| 25 | import java.util.List; |
| 26 | import java.util.Map; |
| 27 | |
| 28 | /** |
| 29 | * A simple stress tool to demonstrate the use of the driver. |
| 30 | * <p/> |
| 31 | * Sample usage: |
| 32 | * stress insert -n 100000 |
| 33 | * stress read -n 10000 |
| 34 | */ |
| 35 | public class Stress { |
| 36 | |
| 37 | private static final Map<String, QueryGenerator.Builder> generators = new HashMap<String, QueryGenerator.Builder>(); |
| 38 | |
| 39 | static { |
| 40 | PropertyConfigurator.configure(System.getProperty("log4j.configuration", "./conf/log4j.properties")); |
| 41 | |
| 42 | QueryGenerator.Builder[] gs = new QueryGenerator.Builder[]{ |
| 43 | Generators.INSERTER, |
| 44 | Generators.READER |
| 45 | }; |
| 46 | |
| 47 | for (QueryGenerator.Builder b : gs) |
| 48 | register(b.name(), b); |
| 49 | } |
| 50 | |
| 51 | private static OptionParser defaultParser() { |
| 52 | OptionParser parser = new OptionParser() {{ |
| 53 | accepts("h", "Show this help message"); |
| 54 | accepts("n", "Number of requests to perform (default: unlimited)").withRequiredArg().ofType(Integer.class); |
| 55 | accepts("t", "Level of concurrency to use").withRequiredArg().ofType(Integer.class).defaultsTo(50); |
| 56 | accepts("async", "Make asynchronous requests instead of blocking ones"); |
| 57 | accepts("ip", "The hosts ip to connect to").withRequiredArg().ofType(String.class).defaultsTo("127.0.0.1"); |
| 58 | accepts("report-file", "The name of csv file to use for reporting results").withRequiredArg().ofType(String.class).defaultsTo("last.csv"); |
| 59 | accepts("print-delay", "The delay in seconds at which to report on the console").withRequiredArg().ofType(Integer.class).defaultsTo(5); |
| 60 | accepts("compression", "Use compression (SNAPPY)"); |
| 61 | accepts("connections-per-host", "The number of connections per hosts (default: based on the number of threads)").withRequiredArg().ofType(Integer.class); |
| 62 | accepts("consistency-level", "Consistency level").withRequiredArg().withValuesConvertedBy(new ConsistencyLevelConverter()) |
| 63 | .ofType(ConsistencyLevel.class).defaultsTo(ConsistencyLevel.LOCAL_ONE); |
| 64 | }}; |
| 65 | String msg = "Where <generator> can be one of " + generators.keySet() + '\n' |
| 66 | + "You can get more help on a particular generator with: stress <generator> -h"; |
| 67 | parser.formatHelpWith(Help.formatFor("<generator>", msg)); |
| 68 | return parser; |
| 69 | } |
| 70 | |
| 71 | public static void register(String name, QueryGenerator.Builder generator) { |
| 72 | if (generators.containsKey(name)) |
| 73 | throw new IllegalStateException("There is already a generator registered with the name " + name); |
| 74 | |
| 75 | generators.put(name, generator); |
| 76 | } |
| 77 | |
| 78 | private static class Stresser { |
| 79 | private final QueryGenerator.Builder genBuilder; |
| 80 | private final OptionParser parser; |
| 81 | private final OptionSet options; |
| 82 | |
| 83 | private Stresser(QueryGenerator.Builder genBuilder, OptionParser parser, OptionSet options) { |
| 84 | this.genBuilder = genBuilder; |
| 85 | this.parser = parser; |
| 86 | this.options = options; |
| 87 | } |
| 88 | |
| 89 | public static Stresser forCommandLineArguments(String[] args) { |
| 90 | OptionParser parser = defaultParser(); |
| 91 | |
| 92 | String generatorName = findPotentialGenerator(args); |
| 93 | if (generatorName == null) { |
| 94 | // Still parse the options to handle -h |
| 95 | OptionSet options = parseOptions(parser, args); |
| 96 | System.err.println("Missing generator, you need to provide a generator."); |
| 97 | printHelp(parser); |
| 98 | System.exit(1); |
| 99 | } |
| 100 | |
| 101 | if (!generators.containsKey(generatorName)) { |
| 102 | System.err.println(String.format("Unknown generator '%s'", generatorName)); |
| 103 | printHelp(parser); |
| 104 | System.exit(1); |
| 105 | } |
| 106 | |
| 107 | QueryGenerator.Builder genBuilder = generators.get(generatorName); |
| 108 | parser = genBuilder.addOptions(parser); |
| 109 | OptionSet options = parseOptions(parser, args); |
| 110 | |
| 111 | List<?> nonOpts = options.nonOptionArguments(); |
| 112 | if (nonOpts.size() > 1) { |
| 113 | System.err.println("Too many generators provided. Got " + nonOpts + " but only one generator supported."); |
| 114 | printHelp(parser); |
| 115 | System.exit(1); |
| 116 | } |
| 117 | |
| 118 | return new Stresser(genBuilder, parser, options); |
| 119 | } |
| 120 | |
| 121 | private static String findPotentialGenerator(String[] args) { |
| 122 | for (String arg : args) |
| 123 | if (!arg.startsWith("-")) |
| 124 | return arg; |
| 125 | |
| 126 | return null; |
| 127 | } |
| 128 | |
| 129 | private static OptionSet parseOptions(OptionParser parser, String[] args) { |
| 130 | try { |
| 131 | OptionSet options = parser.parse(args); |
| 132 | if (options.has("h")) { |
| 133 | printHelp(parser); |
| 134 | System.exit(0); |
| 135 | } |
| 136 | return options; |
| 137 | } catch (Exception e) { |
| 138 | System.err.println("Error parsing options: " + e.getMessage()); |
| 139 | printHelp(parser); |
| 140 | System.exit(1); |
| 141 | throw new AssertionError(); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | private static void printHelp(OptionParser parser) { |
| 146 | try { |
| 147 | parser.printHelpOn(System.out); |
| 148 | } catch (IOException e) { |
| 149 | throw new AssertionError(e); |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | public OptionSet getOptions() { |
| 154 | return options; |
| 155 | } |
| 156 | |
| 157 | public void prepare(Session session) { |
| 158 | genBuilder.prepare(options, session); |
| 159 | } |
| 160 | |
| 161 | public QueryGenerator newGenerator(int id, Session session, int iterations) { |
| 162 | return genBuilder.create(id, iterations, options, session); |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | public static class Help implements HelpFormatter { |
| 167 | |
| 168 | private final HelpFormatter defaultFormatter; |
| 169 | private final String generator; |
| 170 | private final String header; |
| 171 | |
| 172 | private Help(HelpFormatter defaultFormatter, String generator, String header) { |
| 173 | this.defaultFormatter = defaultFormatter; |
| 174 | this.generator = generator; |
| 175 | this.header = header; |
| 176 | } |
| 177 | |
| 178 | public static Help formatFor(String generator, String header) { |
| 179 | // It's a pain in the ass to get the real console width in JAVA so hardcode it. But it's the 21th |
| 180 | // century, we're not stuck at 80 characters anymore. |
| 181 | int width = 120; |
| 182 | return new Help(new BuiltinHelpFormatter(width, 4), generator, header); |
| 183 | } |
| 184 | |
| 185 | @Override |
| 186 | public String format(Map<String, ? extends OptionDescriptor> options) { |
| 187 | StringBuilder sb = new StringBuilder(); |
| 188 | |
| 189 | sb.append("Usage: stress ").append(generator).append(" [<option>]*").append("\n\n"); |
| 190 | sb.append(header).append("\n\n"); |
| 191 | sb.append(defaultFormatter.format(options)); |
| 192 | return sb.toString(); |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | public static void main(String[] args) throws Exception { |
| 197 | |
| 198 | Stresser stresser = Stresser.forCommandLineArguments(args); |
| 199 | OptionSet options = stresser.getOptions(); |
| 200 | |
| 201 | int requests = options.has("n") ? (Integer) options.valueOf("n") : -1; |
| 202 | int concurrency = (Integer) options.valueOf("t"); |
| 203 | ConsistencyLevel consistencyLevel = (ConsistencyLevel) options.valueOf("consistency-level"); |
| 204 | |
| 205 | String reportFileName = (String) options.valueOf("report-file"); |
| 206 | |
| 207 | boolean async = options.has("async"); |
| 208 | |
| 209 | int iterations = (requests == -1 ? -1 : requests / concurrency); |
| 210 | |
| 211 | final int maxRequestsPerConnection = 128; |
| 212 | int maxConnections = options.has("connections-per-host") |
| 213 | ? (Integer) options.valueOf("connections-per-host") |
| 214 | : concurrency / maxRequestsPerConnection + 1; |
| 215 | |
| 216 | PoolingOptions pools = new PoolingOptions(); |
| 217 | pools.setNewConnectionThreshold(HostDistance.LOCAL, concurrency); |
| 218 | pools.setCoreConnectionsPerHost(HostDistance.LOCAL, maxConnections); |
| 219 | pools.setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections); |
| 220 | pools.setCoreConnectionsPerHost(HostDistance.REMOTE, maxConnections); |
| 221 | pools.setMaxConnectionsPerHost(HostDistance.REMOTE, maxConnections); |
| 222 | |
| 223 | System.out.println("Initializing stress test:"); |
| 224 | System.out.println(" request count: " + (requests == -1 ? "unlimited" : requests)); |
| 225 | System.out.println(" concurrency: " + concurrency + " (" + iterations + " requests/thread)"); |
| 226 | System.out.println(" mode: " + (async ? "asynchronous" : "blocking")); |
| 227 | System.out.println(" per-host connections: " + maxConnections); |
| 228 | System.out.println(" compression: " + options.has("compression")); |
| 229 | System.out.println(" consistency-level: " + consistencyLevel.name()); |
| 230 | |
| 231 | try { |
| 232 | // Create session to hosts |
| 233 | Cluster cluster = new Cluster.Builder() |
| 234 | .addContactPoints(String.valueOf(options.valueOf("ip"))) |
| 235 | .withPoolingOptions(pools) |
| 236 | .withSocketOptions(new SocketOptions().setTcpNoDelay(true)) |
| 237 | .withQueryOptions(new QueryOptions().setConsistencyLevel(consistencyLevel)) |
| 238 | .build(); |
| 239 | |
| 240 | if (options.has("compression")) |
| 241 | cluster.getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.SNAPPY); |
| 242 | |
| 243 | Session session = cluster.connect(); |
| 244 | |
| 245 | Metadata metadata = cluster.getMetadata(); |
| 246 | System.out.println(String.format("Connected to cluster '%s' on %s.", metadata.getClusterName(), metadata.getAllHosts())); |
| 247 | |
| 248 | System.out.println("Preparing test..."); |
| 249 | stresser.prepare(session); |
| 250 | |
| 251 | Reporter reporter = new Reporter((Integer) options.valueOf("print-delay"), reportFileName, args, requests); |
| 252 | |
| 253 | Consumer[] consumers = new Consumer[concurrency]; |
| 254 | for (int i = 0; i < concurrency; i++) { |
| 255 | QueryGenerator generator = stresser.newGenerator(i, session, iterations); |
| 256 | consumers[i] = async ? new AsynchronousConsumer(session, generator, reporter) : |
| 257 | new BlockingConsumer(session, generator, reporter); |
| 258 | } |
| 259 | |
| 260 | System.out.println("Starting to stress test..."); |
| 261 | System.out.println(); |
| 262 | |
| 263 | reporter.start(); |
| 264 | |
| 265 | for (Consumer consumer : consumers) |
| 266 | consumer.start(); |
| 267 | |
| 268 | for (Consumer consumer : consumers) |
| 269 | consumer.join(); |
| 270 | |
| 271 | reporter.stop(); |
| 272 | |
| 273 | System.out.println("Stress test successful."); |
| 274 | System.exit(0); |
| 275 | |
| 276 | } catch (NoHostAvailableException e) { |
| 277 | System.err.println("No alive hosts to use: " + e.getMessage()); |
| 278 | System.exit(1); |
| 279 | } catch (Exception e) { |
| 280 | System.err.println("Unexpected error: " + e.getMessage()); |
| 281 | e.printStackTrace(); |
| 282 | System.exit(1); |
| 283 | } |
| 284 | } |
| 285 | } |