summaryrefslogtreecommitdiff
path: root/qpid/java/broker/src/main/java/org/apache/qpid/server/txn/JDBCTransactionManager.java
blob: 26ddbc881dbc34e5dc1a6631a4567524966c3eb8 (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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/* 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.server.txn;

import org.apache.log4j.Logger;
import org.apache.qpid.server.messageStore.MessageStore;
import org.apache.qpid.server.messageStore.JDBCStore;
import org.apache.qpid.server.exception.*;
import org.apache.commons.configuration.Configuration;

import javax.transaction.xa.Xid;
import java.util.HashMap;
import java.util.Set;


/**
 * Created by Arnaud Simon
 * Date: 16-May-2007
 * Time: 14:05:45
 */
public class JDBCTransactionManager implements TransactionManager
{
    //========================================================================
    // Static Constants
    //========================================================================
    // The logger for this class
    private static final Logger _log = Logger.getLogger(JDBCTransactionManager.class);

    private static final String ENVIRONMENT_TX_TIMEOUT = "environment-tx-timeout";

    //========================================================================
    // Instance Fields
    //========================================================================
    // The underlying jdbc message store
    private JDBCStore _messagStore;

    // A map of XID/x
    private HashMap<Xid, Transaction> _xidMap;

    // A map of in-doubt txs
    private HashMap<Xid, Transaction> _indoubtXidMap;

    // A default tx timeout in sec
    private int _defaultTimeout;   // set to 10s if not specified in the config

    //===================================
    //=== Configuartion
    //===================================

    /**
     * Configure this TM with the Message store implementation
     *
     * @param base         The base element identifier from which all configuration items are relative. For example, if the base
     *                     element is "store", the all elements used by concrete classes will be "store.foo" etc.
     * @param config       The apache commons configuration object
     * @param messageStroe the message store associated with the TM
     */
    public void configure(MessageStore messageStroe, String base, Configuration config)
    {
        _messagStore = (JDBCStore) messageStroe;
        if (config != null)
        {
            _defaultTimeout = config.getInt(base + "." + ENVIRONMENT_TX_TIMEOUT, 120);
        } else
        {
            _defaultTimeout = 120;
        }
        _log.info("Using transaction timeout of " + _defaultTimeout + " s");
        // get the list of in-doubt transactions
        try
        {
            _indoubtXidMap = _messagStore.getAllInddoubt();
            _xidMap = _indoubtXidMap;
        } catch (Exception e)
        {
            _log.fatal("Cannot recover in-doubt transactions", e);
        }
    }

    //===================================
    //=== TransactionManager interface
    //===================================

    /**
     * Begin a transaction branch identified by Xid
     *
     * @param xid The xid of the branch to begin
     * @return <ul>
     *         <li>  <code>XAFlag.ok</code>: Normal execution.
     *         </ul>
     * @throws InternalErrorException In case of internal problem
     * @throws InvalidXidException    The Xid is invalid
     */
    public synchronized XAFlag begin(Xid xid)
            throws
            InternalErrorException,
            InvalidXidException
    {
        if (xid == null)
        {
            throw new InvalidXidException(xid, "null xid");
        }
        if (_xidMap.containsKey(xid))
        {
            throw new InvalidXidException(xid, "Xid already exist");
        }
        Transaction tx = new JDBCTransaction();
        tx.setTimeout(_defaultTimeout);
        _xidMap.put(xid, tx);
        return XAFlag.ok;
    }

    /**
     * Prepare the transaction branch identified by Xid
     *
     * @param xid The xid of the branch to prepare
     * @return <ul>
     *         <li> <code>XAFlag.ok</code>: Normal execution.
     *         <li> <code>XAFlag.rdonly</code>: The transaction branch was read-only and has been committed.
     *         <li> <code>XAFlag.rbrollback</code>: The transaction branch was marked rollback-only for an unspecied reason.
     *         <li> <code>XAFlag.rbtimeout</code>: The work represented by this transaction branch took too long.
     *         </ul>
     * @throws InternalErrorException  In case of internal problem
     * @throws CommandInvalidException Prepare has been call in an improper context
     * @throws UnknownXidException     The Xid is unknown
     */
    public synchronized XAFlag prepare(Xid xid)
            throws
            InternalErrorException,
            CommandInvalidException,
            UnknownXidException
    {
        // get the transaction
        JDBCTransaction tx = getTransaction(xid);
        XAFlag result = XAFlag.ok;
        if (tx.isHeurRollback())
        {
            result = XAFlag.rdonly;
        } else if (tx.hasExpired())
        {
            result = XAFlag.rbtimeout;
            // rollback this tx branch
            rollback(xid);
        } else
        {
            if (tx.isPrepared())
            {
                throw new CommandInvalidException("TransactionImpl is already prepared");
            }
            if (tx.getrecords().size() == 0)
            {
                // the tx was read only (no work has been done)
                _xidMap.remove(xid);
                result = XAFlag.rdonly;
            } else
            {
                try
                {
                    JDBCStore.MyConnection con = _messagStore.getConnection();
                    tx.setConnection(con);
                    // save the xid
                    _messagStore.saveXID(con, tx, xid);
                    for (TransactionRecord record : tx.getrecords())
                    {
                        if (record instanceof JDBCAbstractRecord)
                        {
                            ((JDBCAbstractRecord) record).prepare(_messagStore, xid);
                            _messagStore.saveRecord(con, tx, (JDBCAbstractRecord) record);
                        } else
                        {
                            record.prepare(_messagStore);
                        }
                    }
                    _messagStore.commitConnection(con);
                    tx.setConnection(null);
                } catch (Exception e)
                {
                    _log.error("Cannot prepare tx: " + xid);
                    throw new InternalErrorException("Cannot prepare tx: " + xid, e);
                }
                tx.prepare();
            }
        }
        return result;
    }

    /**
     * Rollback the transaction branch identified by Xid
     *
     * @param xid The xid of the branch to rollback
     * @return <ul>
     *         <li> <code>XAFlag.ok</code>: Normal execution,
     *         <li> <code>NOT SUPPORTED XAFlag.heurhaz</code>: Due to some failure, the work done on behalf of the specified transaction branch may have been heuristically completed.
     *         <li> <code>NOT SUPPORTED XAFlag.heurcom</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was committed.
     *         <li> <code>XAFlag.heurrb</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was rolled back.
     *         <li> <code>NOT SUPPORTED XAFlag.heurmix</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was partially committed and partially rolled back.
     *         <li> <code>NOT SUPPORTED XAFlag.rbrollback</code>: The broker marked the transaction branch rollback-only for an unspeci?ed reason.
     *         <li> <code>XAFlag.rbtimeout</code>: The work represented by this transaction branch took too long.
     *         </ul>
     * @throws InternalErrorException  In case of internal problem
     * @throws CommandInvalidException Rollback has been call in an improper context
     * @throws UnknownXidException     The Xid is unknown
     */
    public synchronized XAFlag rollback(Xid xid)
            throws
            InternalErrorException,
            CommandInvalidException,
            UnknownXidException
    {
        // get the transaction
        JDBCTransaction tx = getTransaction(xid);
        XAFlag flag = XAFlag.ok;
        if (tx.isHeurRollback())
        {
            flag = XAFlag.heurrb;
        } else
        {
            try
            {
                JDBCStore.MyConnection con = _messagStore.getConnection();
                tx.setConnection(con);
                for (TransactionRecord record : tx.getrecords())
                {
                    if (record instanceof JDBCAbstractRecord)
                    {
                        ((JDBCAbstractRecord) record).rollback(_messagStore, xid);
                    } else
                    {
                        record.rollback(_messagStore);
                    }
                }
                if (tx.isPrepared())
                {
                    _messagStore.deleteRecords(con, tx);
                    _messagStore.deleteXID(con, tx);
                    _messagStore.commitConnection(con);
                }
                _messagStore.commitConnection(con);
                tx.setConnection(null);
            }
            catch (Exception e)
            {
                // this should not happen
                _log.error("Error when rolling back distributed transaction: " + xid);
                throw new InternalErrorException("Error when rolling back distributed transaction: " + xid, e);
            }
            removeTransaction(xid);
        }
        if (tx.hasExpired())
        {
            flag = XAFlag.rbtimeout;
        }
        return flag;
    }

    /**
     * Commit the transaction branch identified by Xid
     *
     * @param xid The xid of the branch to commit
     * @return <ul>
     *         <li> <code>XAFlag.ok</code>: Normal execution,
     *         <li> <code>NOT SUPPORTED XAFlag.heurhaz</code>: Due to some failure, the work done on behalf of the specified transaction branch may have been heuristically completed.
     *         <li> <code>NOT SUPPORTED XAFlag.heurcom</code>: Due to a heuristic decision, the work done on behalf of the specied transaction branch was committed.
     *         <li> <code>XAFlag.heurrb</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was rolled back.
     *         <li> <code>XAFlag.heurmix</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was partially committed and partially rolled back.
     *         </ul>
     * @throws InternalErrorException  In case of internal problem
     * @throws CommandInvalidException Commit has been call in an improper context
     * @throws UnknownXidException     The Xid is unknown
     * @throws org.apache.qpid.server.exception.NotPreparedException
     *                                 The branch was not prepared prior to commit
     */
    public synchronized XAFlag commit(Xid xid)
            throws
            InternalErrorException,
            CommandInvalidException,
            UnknownXidException,
            NotPreparedException
    {
        // get the transaction
        JDBCTransaction tx = getTransaction(xid);
        XAFlag flag = XAFlag.ok;
        if (tx.isHeurRollback())
        {
            flag = XAFlag.heurrb;
        } else if (tx.hasExpired())
        {
            flag = XAFlag.rbtimeout;
            // rollback this tx branch
            rollback(xid);
        } else
        {
            if (!tx.isPrepared())
            {
                throw new NotPreparedException("TransactionImpl is not prepared");
            }
            try
            {
                JDBCStore.MyConnection con = _messagStore.getConnection();
                tx.setConnection(con);
                for (TransactionRecord record : tx.getrecords())
                {
                    try
                    {
                        record.commit(_messagStore, xid);
                    } catch (InvalidXidException e)
                    {
                        throw new UnknownXidException(xid, e);
                    } catch (Exception e)
                    {
                        // this should not happen as the queue and the message must exist
                        _log.error("Error when committing distributed transaction heurmix mode returned: " + xid);
                        flag = XAFlag.heurmix;
                    }
                }
                _messagStore.deleteRecords(con, tx);
                _messagStore.deleteXID(con, tx);
                _messagStore.commitConnection(con);
                tx.setConnection(null);
            } catch (Exception e)
            {
                // this should not happen
                _log.error("Error when committing distributed transaction heurrb mode returned: " + xid);
                throw new InternalErrorException("Error when committing distributed transaction: " + xid, e);
            }
            removeTransaction(xid);
        }
        return flag;
    }

    /**
     * One phase commit the transaction branch identified by Xid
     *
     * @param xid The xid of the branch to one phase commit
     * @return <ul>
     *         <li> <code>XAFlag.ok</code>: Normal execution,
     *         <li> <code>NOT SUPPORTED XAFlag.heurhaz</code>: Due to some failure, the work done on behalf of the specified transaction branch may have been heuristically completed.
     *         <li> <code>NOT SUPPORTED XAFlag.heurcom</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was committed.
     *         <li> <code>XAFlag.heurrb</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was rolled back.
     *         <li> <code>NOT SUPPORTED XAFlag.heurmix</code>: Due to a heuristic decision, the work done on behalf of the speci?ed transaction branch was partially committed and partially rolled back.
     *         <li> <code>NOT SUPPORTED XAFlag.rbrollback</code>: The broker marked the transaction branch rollback-only for an unspeci?ed reason.
     *         <li> <code>XAFlag.rbtimeout</code>: The work represented by this transaction branch took too long.
     *         </ul>
     * @throws InternalErrorException  In case of internal problem
     * @throws CommandInvalidException Commit has been call in an improper context
     * @throws UnknownXidException     The Xid is unknown
     */
    public synchronized XAFlag commit_one_phase(Xid xid)
            throws
            InternalErrorException,
            CommandInvalidException,
            UnknownXidException
    {
        XAFlag flag = XAFlag.ok;
        JDBCTransaction tx = getTransaction(xid);
        if (tx.isHeurRollback())
        {
            flag = XAFlag.heurrb;
        } else if (tx.hasExpired())
        {
            flag = XAFlag.rbtimeout;
            // rollback this tx branch
            rollback(xid);
        } else
        {
            try
            {
                // we do not need to prepare the tx
                tx.prepare();
                JDBCStore.MyConnection con = _messagStore.getConnection();
                tx.setConnection(con);
                for (TransactionRecord record : tx.getrecords())
                {
                    try
                    {
                        record.commit(_messagStore, xid);
                    } catch (InvalidXidException e)
                    {
                        throw new UnknownXidException(xid, e);
                    } catch (Exception e)
                    {
                        // this should not happen as the queue and the message must exist
                        _log.error("Error when committing transaction heurmix mode returned: " + xid);
                        flag = XAFlag.heurmix;
                    }
                }
                _messagStore.commitConnection(con);
                tx.setConnection(null);
            } catch (Exception e)
            {
                e.printStackTrace();
                throw new InternalErrorException("cannot commit transaxtion with xid " + xid + " " + e, e);
            }
            finally
            {
                removeTransaction(xid);
            }
        }
        return flag;
    }

    /**
     * Forget about the transaction branch identified by Xid
     *
     * @param xid The xid of the branch to forget
     * @throws InternalErrorException  In case of internal problem
     * @throws CommandInvalidException Forget has been call in an improper context
     * @throws UnknownXidException     The Xid is unknown
     */
    public void forget(Xid xid)
            throws
            InternalErrorException,
            CommandInvalidException,
            UnknownXidException
    {
        synchronized (xid)
        {
            getTransaction(xid);
            removeTransaction(xid);
        }
    }

    /**
     * Set the transaction branch timeout value in seconds
     *
     * @param xid     The xid of the branch to set timeout
     * @param timeout Timeout value in seconds
     * @throws InternalErrorException In case of internal problem
     * @throws UnknownXidException    The Xid is unknown
     */
    public void setTimeout(Xid xid, long timeout)
            throws
            InternalErrorException,
            UnknownXidException
    {
        JDBCTransaction tx = getTransaction(xid);
        tx.setTimeout(timeout);
    }

    /**
     * Get the transaction branch timeout
     *
     * @param xid The xid of the branch to get the timeout from
     * @return The timeout associated with the branch identified with xid
     * @throws InternalErrorException In case of internal problem
     * @throws UnknownXidException    The Xid is unknown
     */
    public long getTimeout(Xid xid)
            throws
            InternalErrorException,
            UnknownXidException
    {
        JDBCTransaction tx = getTransaction(xid);
        return tx.getTimeout();
    }

    /**
     * Get a set of Xids the RM has prepared or heuristically completed
     *
     * @param startscan Indicates that recovery scan should start
     * @param endscan   Indicates that the recovery scan should end after returning the Xids
     * @return Set of Xids the RM has prepared or  heuristically completed
     * @throws InternalErrorException  In case of internal problem
     * @throws CommandInvalidException Recover has been call in an improper context
     */
    public Set<Xid> recover(boolean startscan, boolean endscan)
            throws
            InternalErrorException,
            CommandInvalidException
    {
        return _indoubtXidMap.keySet();
    }

    /**
     * An error happened (for example the channel has been abruptly closed)
     * with this Xid, TM must make a heuristical decision.
     *
     * @param xid The Xid of the transaction branch to be heuristically completed
     * @throws UnknownXidException    The Xid is unknown
     * @throws InternalErrorException In case of internal problem
     */
    public void HeuristicOutcome(Xid xid)
            throws
            UnknownXidException,
            InternalErrorException
    {
        synchronized (xid)
        {
            JDBCTransaction tx = getTransaction(xid);
            if (!tx.isPrepared())
            {
                // heuristically rollback this tx
                for (TransactionRecord record : tx.getrecords())
                {
                    record.rollback(_messagStore);
                }
                tx.heurRollback();
            }
            // add this branch in the list of indoubt tx
            _indoubtXidMap.put(xid, tx);
        }
    }


    public JDBCTransaction getTransaction(Xid xid)
            throws
            UnknownXidException
    {
        Transaction tx = _xidMap.get(xid);
        if (tx == null)
        {
            throw new UnknownXidException(xid, null);
        }
        return (JDBCTransaction) tx;
    }

    //==========================================================================
    //== Methods for Message Store
    //==========================================================================

    /**
     * Get the default tx timeout in seconds
     *
     * @return the default tx timeout in seconds
     */
    public int getDefaultTimeout()
    {
        return _defaultTimeout;
    }
    //==========================================================================
    //== Private Methods
    //==========================================================================

    private void removeTransaction(Xid xid)
    {
        _xidMap.remove(xid);
        _indoubtXidMap.remove(xid);
    }
}