summaryrefslogtreecommitdiff
path: root/java/tools/src/main/java/org/apache/qpid/tools/StressTestClient.java
blob: 5bf1864b4fa5fe29e1396c7a70f5ff20f009ac40 (plain)
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
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.qpid.tools;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import javax.jms.BytesMessage;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;

public class StressTestClient
{
    private static final String QUEUE_NAME_PREFIX = "BURL:direct://amq.direct//stress-test-queue";
    private static final String DURABLE_SUFFIX = "?durable='true'";

    public static final String CONNECTIONS_ARG = "connections";
    public static final String SESSIONS_ARG = "sessions";
    public static final String CONSUME_IMMEDIATELY_ARG = "consumeImmediately";
    public static final String CONSUMERS_ARG = "consumers";
    public static final String CLOSE_CONSUMERS_ARG = "closeconsumers";
    public static final String PRODUCERS_ARG = "producers";
    public static final String MESSAGE_COUNT_ARG = "messagecount";
    public static final String MESSAGE_SIZE_ARG = "size";
    public static final String SUFFIX_ARG = "suffix";
    public static final String REPETITIONS_ARG = "repetitions";
    public static final String PERSISTENT_ARG = "persistent";
    public static final String RANDOM_ARG = "random";
    public static final String TIMEOUT_ARG = "timeout";
    public static final String DELAYCLOSE_ARG = "delayclose";
    public static final String REPORT_MOD_ARG = "reportmod";
    public static final String LOW_PREFETCH_ARG = "lowprefetch";
    public static final String TRANSACTED_ARG = "transacted";
    public static final String TX_BATCH_ARG = "txbatch";

    public static final String CONNECTIONS_DEFAULT = "1";
    public static final String SESSIONS_DEFAULT = "1";
    public static final String CONSUME_IMMEDIATELY_DEFAULT = "true";
    public static final String CLOSE_CONSUMERS_DEFAULT = "true";
    public static final String PRODUCERS_DEFAULT = "1";
    public static final String CONSUMERS_DEFAULT = "1";
    public static final String MESSAGE_COUNT_DEFAULT = "1";
    public static final String MESSAGE_SIZE_DEFAULT = "256";
    public static final String SUFFIX_DEFAULT = "";
    public static final String REPETITIONS_DEFAULT = "1";
    public static final String PERSISTENT_DEFAULT = "false";
    public static final String RANDOM_DEFAULT = "true";
    public static final String TIMEOUT_DEFAULT = "30000";
    public static final String DELAYCLOSE_DEFAULT = "0";
    public static final String REPORT_MOD_DEFAULT = "1";
    public static final String LOW_PREFETCH_DEFAULT = "false";
    public static final String TRANSACTED_DEFAULT = "false";
    public static final String TX_BATCH_DEFAULT = "1";

    private static final String CLASS = "StressTestClient";

    public static void main(String[] args)
    {
        Map<String,String> options = new HashMap<>();
        options.put(CONNECTIONS_ARG, CONNECTIONS_DEFAULT);
        options.put(SESSIONS_ARG, SESSIONS_DEFAULT);
        options.put(CONSUME_IMMEDIATELY_ARG, CONSUME_IMMEDIATELY_DEFAULT);
        options.put(PRODUCERS_ARG, PRODUCERS_DEFAULT);
        options.put(CONSUMERS_ARG, CONSUMERS_DEFAULT);
        options.put(CLOSE_CONSUMERS_ARG, CLOSE_CONSUMERS_DEFAULT);
        options.put(MESSAGE_COUNT_ARG, MESSAGE_COUNT_DEFAULT);
        options.put(MESSAGE_SIZE_ARG, MESSAGE_SIZE_DEFAULT);
        options.put(SUFFIX_ARG, SUFFIX_DEFAULT);
        options.put(REPETITIONS_ARG, REPETITIONS_DEFAULT);
        options.put(PERSISTENT_ARG, PERSISTENT_DEFAULT);
        options.put(RANDOM_ARG, RANDOM_DEFAULT);
        options.put(TIMEOUT_ARG, TIMEOUT_DEFAULT);
        options.put(DELAYCLOSE_ARG, DELAYCLOSE_DEFAULT);
        options.put(REPORT_MOD_ARG, REPORT_MOD_DEFAULT);
        options.put(LOW_PREFETCH_ARG, LOW_PREFETCH_DEFAULT);
        options.put(TRANSACTED_ARG, TRANSACTED_DEFAULT);
        options.put(TX_BATCH_ARG, TX_BATCH_DEFAULT);

        if(args.length == 1 &&
                (args[0].equals("-h") || args[0].equals("--help") || args[0].equals("help")))
        {
            System.out.println("arg=value options: \n" + options.keySet());
            return;
        }

        parseArgumentsIntoConfig(options, args);

        StressTestClient testClient = new StressTestClient();
        testClient.runTest(options);
    }

    public static void parseArgumentsIntoConfig(Map<String, String> initialValues, String[] args)
    {
        for(String arg: args)
        {
            String[] splitArg = arg.split("=");
            if(splitArg.length != 2)
            {
                throw new IllegalArgumentException("arguments must have format <name>=<value>: " + arg);
            }

            if(initialValues.put(splitArg[0], splitArg[1]) == null)
            {
                throw new IllegalArgumentException("not a valid configuration property: " + arg);
            }
        }
    }


    private void runTest(Map<String,String> options)
    {
        int numConnections = Integer.parseInt(options.get(CONNECTIONS_ARG));
        int numSessions = Integer.parseInt(options.get(SESSIONS_ARG));
        int numProducers = Integer.parseInt(options.get(PRODUCERS_ARG));
        int numConsumers = Integer.parseInt(options.get(CONSUMERS_ARG));
        boolean closeConsumers = Boolean.valueOf(options.get(CLOSE_CONSUMERS_ARG));
        boolean consumeImmediately = Boolean.valueOf(options.get(CONSUME_IMMEDIATELY_ARG));
        int numMessage = Integer.parseInt(options.get(MESSAGE_COUNT_ARG));
        int messageSize = Integer.parseInt(options.get(MESSAGE_SIZE_ARG));
        int repetitions = Integer.parseInt(options.get(REPETITIONS_ARG));
        String queueString = QUEUE_NAME_PREFIX + options.get(SUFFIX_ARG) + DURABLE_SUFFIX;
        int deliveryMode = Boolean.valueOf(options.get(PERSISTENT_ARG)) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT;
        boolean random = Boolean.valueOf(options.get(RANDOM_ARG));
        long recieveTimeout = Long.parseLong(options.get(TIMEOUT_ARG));
        long delayClose = Long.parseLong(options.get(DELAYCLOSE_ARG));
        int reportingMod = Integer.parseInt(options.get(REPORT_MOD_ARG));
        boolean lowPrefetch = Boolean.valueOf(options.get(LOW_PREFETCH_ARG));
        boolean transacted = Boolean.valueOf(options.get(TRANSACTED_ARG));
        int txBatch = Integer.parseInt(options.get(TX_BATCH_ARG));

        System.out.println(CLASS + ": Using options: " + options);

        System.out.println(CLASS + ": Creating message payload of " + messageSize + " (bytes)");
        byte[] sentBytes = generateMessage(random, messageSize);

        try
        {
            // Load JNDI properties
            Properties properties = new Properties();
            try(InputStream is = this.getClass().getClassLoader().getResourceAsStream("stress-test-client.properties"))
            {
                properties.load(is);
            }
            Context ctx = new InitialContext(properties);

            ConnectionFactory conFac;
            if(lowPrefetch)
            {
                System.out.println(CLASS + ": Using lowprefetch connection factory");
                conFac = (ConnectionFactory)ctx.lookup("qpidConnectionfactoryLowPrefetch");
            }
            else
            {
                conFac = (ConnectionFactory)ctx.lookup("qpidConnectionfactory");
            }

            //ensure the queue to be used exists and is bound
            System.out.println(CLASS + ": Creating queue: " + queueString);
            Connection startupConn = conFac.createConnection();
            Session startupSess = startupConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination startupDestination = startupSess.createQueue(queueString);
            MessageConsumer startupConsumer = startupSess.createConsumer(startupDestination);
            startupConsumer.close();
            startupSess.close();
            startupConn.close();

            for(int rep = 1 ; rep <= repetitions; rep++)
            {
                ArrayList<Connection> connectionList = new ArrayList<>();

                for (int co= 1; co<= numConnections ; co++)
                {
                    if( co % reportingMod == 0)
                    {
                        System.out.println(CLASS + ": Creating connection " + co);
                    }
                    Connection conn = conFac.createConnection();
                    conn.setExceptionListener(new ExceptionListener()
                    {
                        public void onException(JMSException jmse)
                        {
                            System.err.println(CLASS + ": The sample received an exception through the ExceptionListener");
                            jmse.printStackTrace();
                            System.exit(0);
                        }
                    });

                    connectionList.add(conn);
                    conn.start();
                    for (int se= 1; se<= numSessions ; se++)
                    {
                        if( se % reportingMod == 0)
                        {
                            System.out.println(CLASS + ": Creating Session " + se);
                        }
                        try
                        {
                            Session sess;
                            if(transacted)
                            {
                                sess = conn.createSession(true, Session.SESSION_TRANSACTED);
                            }
                            else
                            {
                                sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
                            }

                            BytesMessage message = sess.createBytesMessage();

                            message.writeBytes(sentBytes);

                            if(!random && numMessage == 1 && numSessions == 1 && numConnections == 1 && repetitions == 1)
                            {
                                //null the array to save memory
                                sentBytes = null;
                            }

                            Destination destination = sess.createQueue(queueString);

                            MessageConsumer consumer = null;
                            for(int cns = 1 ; cns <= numConsumers ; cns++)
                            {
                                if( cns % reportingMod == 0)
                                {
                                    System.out.println(CLASS + ": Creating Consumer " + cns);
                                }
                                consumer = sess.createConsumer(destination);
                            }

                            for(int pr = 1 ; pr <= numProducers ; pr++)
                            {
                                if( pr % reportingMod == 0)
                                {
                                    System.out.println(CLASS + ": Creating Producer " + pr);
                                }
                                MessageProducer prod = sess.createProducer(destination);
                                for(int me = 1; me <= numMessage ; me++)
                                {
                                    if( me % reportingMod == 0)
                                    {
                                        System.out.println(CLASS + ": Sending Message " + me);
                                    }
                                    prod.send(message, deliveryMode,
                                            Message.DEFAULT_PRIORITY,
                                            Message.DEFAULT_TIME_TO_LIVE);
                                    if(transacted && me % txBatch == 0)
                                    {
                                        sess.commit();
                                    }
                                }
                            }

                            if(numConsumers > 0 && consumeImmediately)
                            {
                                for(int cs = 1 ; cs <= numMessage ; cs++)
                                {
                                    if( cs % reportingMod == 0)
                                    {
                                        System.out.println(CLASS + ": Consuming Message " + cs);
                                    }
                                    BytesMessage msg = (BytesMessage) consumer.receive(recieveTimeout);

                                    if(transacted && cs % txBatch == 0)
                                    {
                                        sess.commit();
                                    }

                                    if(msg == null)
                                    {
                                        throw new RuntimeException("Expected message not received in allowed time: " + recieveTimeout);
                                    }

                                    validateReceivedMessageContent(sentBytes, msg, random, messageSize);
                                }

                                if(closeConsumers)
                                {
                                    consumer.close();
                                }
                            }

                        }
                        catch (Exception exp)
                        {
                            System.err.println(CLASS + ": Caught an Exception: " + exp);
                            exp.printStackTrace();
                        }

                    }
                }

                if(numConsumers == -1 && !consumeImmediately)
                {
                    System.out.println(CLASS + ": Consuming left over messages, using recieve timeout:" + recieveTimeout);

                    Connection conn = conFac.createConnection();
                    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    Destination destination = sess.createQueue(queueString);
                    MessageConsumer consumer = sess.createConsumer(destination);
                    conn.start();

                    int count = 0;
                    while(true)
                    {
                        BytesMessage msg = (BytesMessage) consumer.receive(recieveTimeout);

                        if(msg == null)
                        {
                            System.out.println(CLASS + ": Received " + count + " messages");
                            break;
                        }
                        else
                        {
                            count++;
                        }

                        validateReceivedMessageContent(sentBytes, msg, random, messageSize);
                    }

                    consumer.close();
                    sess.close();
                    conn.close();
                }

                if(delayClose > 0)
                {
                    System.out.println(CLASS + ": Delaying closing connections: " + delayClose);
                    Thread.sleep(delayClose);
                }

                // Close the connections to the server
                System.out.println(CLASS + ": Closing connections");

                for(int connection = 0 ; connection < connectionList.size() ; connection++)
                {
                    if( (connection+1) % reportingMod == 0)
                    {
                        System.out.println(CLASS + ": Closing connection " + (connection+1));
                    }
                    Connection c = connectionList.get(connection);
                    c.close();
                }

                // Close the JNDI reference
                System.out.println(CLASS + ": Closing JNDI context");
                ctx.close();
            }
        }
        catch (Exception exp)
        {
            System.err.println(CLASS + ": Caught an Exception: " + exp);
            exp.printStackTrace();
        }
    }


    private byte[] generateMessage(boolean random, int messageSize)
    {
        byte[] sentBytes = new byte[messageSize];
        if(random)
        {
            //fill the array with numbers from 0-9
            Random rand = new Random(System.currentTimeMillis());
            for(int r = 0 ; r < messageSize ; r++)
            {
                sentBytes[r] = (byte) (48 + rand.nextInt(10));
            }
        }
        else
        {
            //use sequential numbers from 0-9
            for(int r = 0 ; r < messageSize ; r++)
            {
                sentBytes[r] = (byte) (48 + (r % 10));
            }
        }
        return sentBytes;
    }


    private void validateReceivedMessageContent(byte[] sentBytes,
            BytesMessage msg, boolean random, int messageSize) throws JMSException
    {
        Long length = msg.getBodyLength();

        if(length != messageSize)
        {
            throw new RuntimeException("Incorrect number of bytes received");
        }

        byte[] recievedBytes = new byte[length.intValue()];
        msg.readBytes(recievedBytes);

        if(random)
        {
            if(!Arrays.equals(sentBytes, recievedBytes))
            {
                throw new RuntimeException("Incorrect value of bytes received");
            }
        }
        else
        {
            for(int r = 0 ; r < messageSize ; r++)
            {
                if(! (recievedBytes[r] == (byte) (48 + (r % 10))))
                {
                    throw new RuntimeException("Incorrect value of bytes received");
                }
            }
        }
    }
}