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