summaryrefslogtreecommitdiff
path: root/qpid/java/systests/src/main/java/org/apache/qpid/test/unit/ack/AcknowledgeAfterFailoverOnMessageTest.java
blob: f22a405fc3d106996fddc2f9cb91ba9bb7829bf0 (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
/*
 *
 * 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.ack;

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 javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TransactionRolledBackException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class AcknowledgeAfterFailoverOnMessageTest extends AcknowledgeOnMessageTest implements ConnectionListener
{

    protected CountDownLatch _failoverCompleted = new CountDownLatch(1);
    private MessageListener _listener = null;

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

    /**
     * Override default init to add connectionListener so we can verify that
     * failover took place
     *
     * @param transacted create a transacted session for this test
     * @param mode       if not transacted what ack mode to use for this test
     *
     * @throws Exception if a problem occured during test setup.
     */
    @Override
    public void init(boolean transacted, int mode) throws Exception
    {
        super.init(transacted, mode);
        ((AMQConnection) _connection).setConnectionListener(this);
        // Override the listener for the dirtyAck testing.
        if (_listener != null)
        {
            _consumer.setMessageListener(_listener);
        }
    }

    protected void prepBroker(int count) throws Exception
    {
        //Stop the connection whilst we repopulate the broker, or the no_ack
        // test will drain the msgs before we can check we put the right number
        // back on again.
//        _connection.stop();

        Connection connection = getConnection();
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        // ensure destination is created.
        session.createConsumer(_queue).close();

        sendMessage(session, _queue, count, NUM_MESSAGES - count, 0);

        if (_consumerSession.getAcknowledgeMode() != AMQSession.NO_ACKNOWLEDGE)
        {
            assertEquals("Wrong number of messages on queue", count,
                         ((AMQSession) session).getQueueDepth((AMQDestination) _queue));
        }

        connection.close();

//        _connection.start();
    }

    @Override
    public void doAcknowlegement(Message msg) throws JMSException
    {
        //Acknowledge current message
        super.doAcknowlegement(msg);

        int msgCount = msg.getIntProperty(INDEX);

        if (msgCount % 2 == 0)
        {
            failBroker(getFailingPort());
        }
        else
        {
            failBroker(getPort());
        }

        try
        {
            prepBroker(NUM_MESSAGES - msgCount - 1);
        }
        catch (Exception e)
        {
            fail("Unable to prep new broker," + e.getMessage());
        }

        try
        {

            if (msgCount % 2 == 0)
            {
                startBroker(getFailingPort());
            }
            else
            {
                startBroker(getPort());
            }
        }
        catch (Exception e)
        {
            fail("Unable to start failover broker," + e.getMessage());
        }

    }

    int msgCount = 0;
    boolean cleaned = false;

    class DirtyAckingHandler implements MessageListener
    {
        /**
         * Validate first message but do nothing with it.
         *
         * Failover
         *
         * The receive the message again
         *
         * @param message
         */
        public void onMessage(Message message)
        {
            // Stop processing if we have an error and had to stop running.
            if (_receviedAll.getCount() == 0)
            {
                _logger.debug("Dumping msgs due to error(" + _causeOfFailure.get().getMessage() + "):" + message);
                return;
            }

            try
            {
                // Check we have the next message as expected
                assertNotNull("Message " + msgCount + " not correctly received.", message);
                assertEquals("Incorrect message received", msgCount, message.getIntProperty(INDEX));

                if (msgCount == 0 && _failoverCompleted.getCount() != 0)
                {
                    // This is the first message we've received so lets fail the broker

                    failBroker(getFailingPort());

                    repopulateBroker();

                    _logger.error("Received first msg so failing over");

                    return;
                }

                msgCount++;

                // Don't acknowlege the first message after failover so we can commit
                // them together
                if (msgCount == 1)
                {
                    _logger.error("Received first msg after failover ignoring:" + msgCount);

                    // Acknowledge the first message if we are now on the cleaned pass
                    if (cleaned)
                    {
                        _receviedAll.countDown();
                    }

                    return;
                }

                if (_consumerSession.getTransacted())
                {
                    try
                    {
                        _consumerSession.commit();
                        if (!cleaned)
                        {
                            fail("Session is dirty we should get an TransactionRolledBackException");
                        }
                    }
                    catch (TransactionRolledBackException trbe)
                    {
                        //expected path
                    }
                }
                else
                {
                    try
                    {
                        message.acknowledge();
                        if (!cleaned)
                        {
                            fail("Session is dirty we should get an IllegalStateException");
                        }
                    }
                    catch (javax.jms.IllegalStateException ise)
                    {
                        assertEquals("Incorrect Exception thrown", "has failed over", ise.getMessage());
                        // Recover the sesion and try again.
                        _consumerSession.recover();
                    }
                }

                // Acknowledge the last message if we are in a clean state
                // this will then trigger test teardown.
                if (cleaned)
                {
                    _receviedAll.countDown();
                }

                //Reset message count so we can try again.
                msgCount = 0;
                cleaned = true;
            }
            catch (Exception e)
            {
                // If something goes wrong stop and notifiy main thread.
                fail(e);
            }
        }
    }

    /**
     * Test that Acking/Committing a message received before failover causes
     * an exception at commit/ack time.
     *
     * Expected behaviour is that in:
     * * tx mode commit() throws a transacted RolledBackException
     * * client ack mode throws an IllegalStateException
     *
     * @param transacted is this session trasacted
     * @param mode       What ack mode should be used if not trasacted
     *
     * @throws Exception if something goes wrong.
     */
    protected void testDirtyAcking(boolean transacted, int mode) throws Exception
    {
        NUM_MESSAGES = 2;
        _listener = new DirtyAckingHandler();

        super.testAcking(transacted, mode);
    }

    public void testDirtyClientAck() throws Exception
    {
        testDirtyAcking(false, Session.CLIENT_ACKNOWLEDGE);
    }

    public void testDirtyAckingTransacted() throws Exception
    {
        testDirtyAcking(true, Session.SESSION_TRANSACTED);
    }

    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
     */
    @Override
    public void failBroker(int port)
    {
        super.failBroker(port);

        try
        {
            if (!_failoverCompleted.await(DEFAULT_FAILOVER_TIME, TimeUnit.MILLISECONDS))
            {
                // Use an exception so that we use our local fail() that notifies the main thread of failure
                throw new Exception("Failover did not occur in specified time:" + DEFAULT_FAILOVER_TIME);
            }

        }
        catch (Exception e)
        {
            // Use an exception so that we use our local fail() that notifies the main thread of failure
            fail(e);
        }
    }

}