summaryrefslogtreecommitdiff
path: root/java/systests/src/main/java/org/apache/qpid/test/unit/publish/DirtyTransactedPublishTest.java
blob: 3ec793781234d0a50387bb50dfbe109c6da4d09f (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
/*
 *
 * 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.test.unit.publish;

import org.apache.qpid.client.AMQConnection;
import org.apache.qpid.client.AMQDestination;
import org.apache.qpid.client.AMQSession;
import org.apache.qpid.jms.ConnectionListener;
import org.apache.qpid.test.utils.FailoverBaseCase;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TransactionRolledBackException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * QPID-1816 : Whilst testing Acknoledgement after failover this completes testing
 * of the client after failover. When we have a dirty session we should receive
 * an error if we attempt to publish. This test ensures that both in the synchronous
 * and asynchronous message delivery paths we receive the expected exceptions at
 * the expected time.
 */
public class DirtyTransactedPublishTest extends FailoverBaseCase implements ConnectionListener
{
    protected CountDownLatch _failoverCompleted = new CountDownLatch(1);

    protected int NUM_MESSAGES;
    protected Connection _connection;
    protected Queue _queue;
    protected Session _consumerSession;
    protected MessageConsumer _consumer;
    protected MessageProducer _producer;

    private static final String MSG = "MSG";
    private static final String SEND_FROM_ON_MESSAGE_TEXT = "sendFromOnMessage";
    protected CountDownLatch _receviedAll;
    protected AtomicReference<Exception> _causeOfFailure = new AtomicReference<Exception>(null);

    @Override
    protected void setUp() throws Exception
    {
        super.setUp();
        NUM_MESSAGES = 10;

        _queue = getTestQueue();

        //Create Producer put some messages on the queue
        _connection = getConnection();
    }

    /**
     * Initialise the test variables
     * @param transacted is this a transacted test
     * @param mode if not trasacted then what ack mode to use
     * @throws Exception if there is a setup issue.
     */
    protected void init(boolean transacted, int mode) throws Exception
    {
        _consumerSession = _connection.createSession(transacted, mode);
        _consumer = _consumerSession.createConsumer(_queue);
        _producer = _consumerSession.createProducer(_queue);

        // These should all end up being prefetched by session
        sendMessage(_consumerSession, _queue, 1);

        assertEquals("Wrong number of messages on queue", 1,
                     ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue));
    }

    /**
     * If a transacted session has failed over whilst it has uncommitted sent
     * data then we need to throw a TransactedRolledbackException on commit()
     *
     * The alternative would be to maintain a replay buffer so that the message
     * could be resent. This is not currently implemented
     *
     * @throws Exception if something goes wrong.
     */
    public void testDirtySendingSynchronousTransacted() throws Exception
    {
        Session producerSession = _connection.createSession(true, Session.SESSION_TRANSACTED);

        // Ensure we get failover notifications
        ((AMQConnection) _connection).setConnectionListener(this);

        MessageProducer producer = producerSession.createProducer(_queue);

        // Create and send message 0
        Message msg = producerSession.createMessage();
        msg.setIntProperty(INDEX, 0);
        producer.send(msg);

        // DON'T commit message .. fail connection

        failBroker(getFailingPort());

        // Ensure destination exists for sending
        producerSession.createConsumer(_queue).close();

        // Send the next message
        msg.setIntProperty(INDEX, 1);
        try
        {
            producer.send(msg);
            fail("Should fail with Qpid as we provide early warning of the dirty session via a JMSException.");
        }
        catch (JMSException jmse)
        {
            assertEquals("Early warning of dirty session not correct",
                         "Failover has occurred and session is dirty so unable to send.", jmse.getMessage());
        }

        // Ignore that the session is dirty and attempt to commit to validate the
        // exception is thrown. AND that the above failure notification did NOT
        // clean up the session.

        try
        {
            producerSession.commit();
            fail("Session is dirty we should get an TransactionRolledBackException");
        }
        catch (TransactionRolledBackException trbe)
        {
            // Normal path.
        }

        // Resending of messages should now work ok as the commit was forcilbly rolledback
        msg.setIntProperty(INDEX, 0);
        producer.send(msg);
        msg.setIntProperty(INDEX, 1);
        producer.send(msg);

        producerSession.commit();

        assertEquals("Wrong number of messages on queue", 2,
                     ((AMQSession) producerSession).getQueueDepth((AMQDestination) _queue));
    }

    /**
     * If a transacted session has failed over whilst it has uncommitted sent
     * data then we need to throw a TransactedRolledbackException on commit()
     *
     * The alternative would be to maintain a replay buffer so that the message
     * could be resent. This is not currently implemented
     *
     * @throws Exception if something goes wrong.
     */
    public void testDirtySendingOnMessageTransacted() throws Exception
    {
        NUM_MESSAGES = 1;
        _receviedAll = new CountDownLatch(NUM_MESSAGES);
        ((AMQConnection) _connection).setConnectionListener(this);

        init(true, Session.SESSION_TRANSACTED);

        _consumer.setMessageListener(new MessageListener()
        {

            public void onMessage(Message message)
            {
                try
                {
                    // Create and send message 0
                    Message msg = _consumerSession.createMessage();
                    msg.setIntProperty(INDEX, 0);
                    _producer.send(msg);

                    // DON'T commit message .. fail connection

                    failBroker(getFailingPort());

                    // rep
                    repopulateBroker();

                    // Destination will exist as this failBroker will populate
                    // the queue with 1 message

                    // Send the next message
                    msg.setIntProperty(INDEX, 1);
                    try
                    {
                        _producer.send(msg);
                        fail("Should fail with Qpid as we provide early warning of the dirty session via a JMSException.");
                    }
                    catch (JMSException jmse)
                    {
                        assertEquals("Early warning of dirty session not correct",
                                     "Failover has occurred and session is dirty so unable to send.", jmse.getMessage());
                    }

                    // Ignore that the session is dirty and attempt to commit to validate the
                    // exception is thrown. AND that the above failure notification did NOT
                    // clean up the session.

                    try
                    {
                        _consumerSession.commit();
                        fail("Session is dirty we should get an TransactionRolledBackException");
                    }
                    catch (TransactionRolledBackException trbe)
                    {
                        // Normal path.
                    }

                    // Resend messages
                    msg.setIntProperty(INDEX, 0);
                    msg.setStringProperty(MSG, SEND_FROM_ON_MESSAGE_TEXT);
                    _producer.send(msg);
                    msg.setIntProperty(INDEX, 1);
                    msg.setStringProperty(MSG, SEND_FROM_ON_MESSAGE_TEXT);
                    _producer.send(msg);

                    _consumerSession.commit();

                    // Stop this consumer .. can't do _consumer.stop == DEADLOCK
                    // this doesn't seem to stop dispatcher running
                    _connection.stop();

                    // Signal that the onMessage send part of test is complete
                    // main thread can validate that messages are correct
                    _receviedAll.countDown();

                }
                catch (Exception e)
                {
                    fail(e);
                }

            }

        });

        _connection.start();

        if (!_receviedAll.await(10000L, TimeUnit.MILLISECONDS))
        {
            // Check to see if we ended due to an exception in the onMessage handler
            Exception cause = _causeOfFailure.get();
            if (cause != null)
            {
                cause.printStackTrace();
                fail(cause.getMessage());
            }
            else
            {
                fail("All messages not received:" + _receviedAll.getCount() + "/" + NUM_MESSAGES);
            }
        }

        // Check to see if we ended due to an exception in the onMessage handler
        Exception cause = _causeOfFailure.get();
        if (cause != null)
        {
            cause.printStackTrace();
            fail(cause.getMessage());
        }

        _consumer.close();
        _consumerSession.close();

        _consumerSession = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        _connection.start();

        // Validate that we could send the messages as expected.
        assertEquals("Wrong number of messages on queue", 3,
                     ((AMQSession) _consumerSession).getQueueDepth((AMQDestination) _queue));

        MessageConsumer consumer = _consumerSession.createConsumer(_queue);

        //Validate the message sent to setup the failed over broker.
        Message message = consumer.receive(1000);
        assertNotNull("Message " + 0 + " not received.", message);
        assertEquals("Incorrect message received", 0, message.getIntProperty(INDEX));

        // Validate the two messages sent from within the onMessage
        for (int index = 0; index <= 1; index++)
        {
            message = consumer.receive(1000);
            assertNotNull("Message " + index + " not received.", message);
            assertEquals("Incorrect message received", index, message.getIntProperty(INDEX));
            assertEquals("Incorrect message text for message:" + index, SEND_FROM_ON_MESSAGE_TEXT, message.getStringProperty(MSG));
        }

        assertNull("Extra message received.", consumer.receiveNoWait());

        _consumerSession.close();

        assertEquals("Wrong number of messages on queue", 0,
                     ((AMQSession) getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE)).getQueueDepth((AMQDestination) _queue));
    }

    private void repopulateBroker() throws Exception
    {
        // Repopulate this new broker so we can test what happends after failover

        //Get the connection to the first (main port) broker.
        Connection connection = getConnection();
        // Use a transaction to send messages so we can be sure they arrive.
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        // ensure destination is created.
        session.createConsumer(_queue).close();

        sendMessage(session, _queue, NUM_MESSAGES);

        assertEquals("Wrong number of messages on queue", NUM_MESSAGES,
                     ((AMQSession) session).getQueueDepth((AMQDestination) _queue));

        connection.close();
    }

    // AMQConnectionListener Interface.. used so we can validate that we
    // actually failed over.

    public void bytesSent(long count)
    {
    }

    public void bytesReceived(long count)
    {
    }

    public boolean preFailover(boolean redirect)
    {
        //Allow failover
        return true;
    }

    public boolean preResubscribe()
    {
        //Allow failover
        return true;
    }

    public void failoverComplete()
    {
        _failoverCompleted.countDown();
    }

    /**
     * Override so we can block until failover has completd
     *
     * @param port int the port of the broker to fail.
     */
    @Override
    public void failBroker(int port)
    {
        super.failBroker(port);

        try
        {
            if (!_failoverCompleted.await(DEFAULT_FAILOVER_TIME, TimeUnit.MILLISECONDS))
            {
                fail("Failover did not occur in specified time:" + DEFAULT_FAILOVER_TIME);
            }
        }
        catch (InterruptedException e)
        {
            fail("Failover was interuppted");
        }
    }

    /**
     * Pass the given exception back to the waiting thread to fail the test run.
     *
     * @param e The exception that is causing the test to fail.
     */
    protected void fail(Exception e)
    {
        _causeOfFailure.set(e);
        // End the test.
        while (_receviedAll.getCount() != 0)
        {
            _receviedAll.countDown();
        }
    }
}