-
Notifications
You must be signed in to change notification settings - Fork 33
/
TransactionHandler.java
2826 lines (2558 loc) · 130 KB
/
TransactionHandler.java
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000, 2017 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2022 Contributors to the Eclipse Foundation
* Copyright (c) 2020 Payara Services Ltd.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.messaging.jmq.jmsserver.data.handlers;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import java.util.Properties;
import javax.transaction.xa.XAResource;
import com.sun.messaging.jmq.io.JMQByteBufferInputStream;
import com.sun.messaging.jmq.io.Packet;
import com.sun.messaging.jmq.io.PacketType;
import com.sun.messaging.jmq.io.Status;
import com.sun.messaging.jmq.io.SysMessageID;
import com.sun.messaging.jmq.jmsserver.BrokerStateHandler;
import com.sun.messaging.jmq.jmsserver.FaultInjection;
import com.sun.messaging.jmq.jmsserver.GlobalProperties;
import com.sun.messaging.jmq.jmsserver.Globals;
import com.sun.messaging.jmq.jmsserver.persist.api.PartitionedStore;
import com.sun.messaging.jmq.jmsserver.persist.api.TxnLoggingStore;
import com.sun.messaging.jmq.jmsserver.core.BrokerAddress;
import com.sun.messaging.jmq.jmsserver.cluster.api.ClusterBroadcast;
import com.sun.messaging.jmq.jmsserver.core.Consumer;
import com.sun.messaging.jmq.jmsserver.core.ConsumerUID;
import com.sun.messaging.jmq.jmsserver.core.Destination;
import com.sun.messaging.jmq.jmsserver.core.DestinationList;
import com.sun.messaging.jmq.jmsserver.core.DestinationUID;
import com.sun.messaging.jmq.jmsserver.core.PacketReference;
import com.sun.messaging.jmq.jmsserver.core.Session;
import com.sun.messaging.jmq.jmsserver.core.MessageDeliveryTimeInfo;
import com.sun.messaging.jmq.jmsserver.data.AutoRollbackType;
import com.sun.messaging.jmq.jmsserver.data.BaseTransaction;
import com.sun.messaging.jmq.jmsserver.data.ClusterTransaction;
import com.sun.messaging.jmq.jmsserver.data.LocalTransaction;
import com.sun.messaging.jmq.jmsserver.data.PacketHandler;
import com.sun.messaging.jmq.jmsserver.data.RollbackReason;
import com.sun.messaging.jmq.jmsserver.data.TransactionBroker;
import com.sun.messaging.jmq.jmsserver.data.TransactionList;
import com.sun.messaging.jmq.jmsserver.data.TransactionAcknowledgement;
import com.sun.messaging.jmq.jmsserver.data.TransactionState;
import com.sun.messaging.jmq.jmsserver.data.TransactionUID;
import com.sun.messaging.jmq.jmsserver.data.TransactionWork;
import com.sun.messaging.jmq.jmsserver.data.TransactionWorkMessage;
import com.sun.messaging.jmq.jmsserver.data.TransactionWorkMessageAck;
import com.sun.messaging.jmq.jmsserver.management.agent.Agent;
import com.sun.messaging.jmq.jmsserver.resources.BrokerResources;
import com.sun.messaging.jmq.jmsserver.service.imq.IMQBasicConnection;
import com.sun.messaging.jmq.jmsserver.service.imq.IMQConnection;
import com.sun.messaging.jmq.jmsserver.util.AckEntryNotFoundException;
import com.sun.messaging.jmq.jmsserver.util.BrokerDownException;
import com.sun.messaging.jmq.jmsserver.util.BrokerException;
import com.sun.messaging.jmq.jmsserver.util.MaxConsecutiveRollbackException;
import com.sun.messaging.jmq.jmsserver.util.lists.RemoveReason;
import com.sun.messaging.jmq.jmsserver.data.handlers.admin.DebugHandler;
import com.sun.messaging.jmq.util.CacheHashMap;
import com.sun.messaging.jmq.util.GoodbyeReason;
import com.sun.messaging.jmq.util.JMQXid;
import com.sun.messaging.jmq.util.UID;
import com.sun.messaging.jmq.util.log.Logger;
import com.sun.messaging.jmq.util.selector.SelectorFormatException;
import com.sun.messaging.jmq.io.txnlog.TransactionLogType;
/**
* Handler class for transaction packets.
*/
public class TransactionHandler extends PacketHandler {
private static boolean DEBUG = false;
private static boolean DEBUG_CLUSTER_TXN = Globals.getConfig().getBooleanProperty(Globals.IMQ + ".cluster.debug.txn") || DEBUG;
private DestinationList DL = Globals.getDestinationList();
FaultInjection fi = null;
public TransactionHandler() {
fi = FaultInjection.getInjection();
}
public void sendReply(IMQConnection con, Packet msg, int type, int status, long tid, String reason) {
sendReply(con, msg, type, status, tid, reason, null, null, 0L);
}
public void sendReply(IMQConnection con, Packet msg, int type, int status, long tid, String reason, BrokerException bex) {
sendReply(con, msg, type, status, tid, reason, bex, null, 0L);
}
public void sendReply(IMQConnection con, Packet msg, int type, int status, long tid, String reason, BrokerException bex, Map props, long nextTid) {
if (fi.FAULT_INJECTION) {
checkFIAfterProcess(msg.getPacketType());
}
Packet pkt = new Packet(con.useDirectBuffers());
pkt.setPacketType(type);
pkt.setConsumerID(msg.getConsumerID());
Hashtable hash = new Hashtable();
hash.put("JMQStatus", Integer.valueOf(status));
if (reason != null) {
hash.put("JMQReason", reason);
}
if (tid != 0) {
hash.put("JMQTransactionID", Long.valueOf(tid));
}
if (bex != null && bex.isRemote()) {
hash.put("JMQRemote", Boolean.TRUE);
if (bex.getRemoteConsumerUIDs() != null) {
hash.put("JMQRemoteConsumerIDs", bex.getRemoteConsumerUIDs());
}
}
if (props != null) {
Iterator<Map.Entry> itr = props.entrySet().iterator();
Map.Entry pair = null;
Object key = null;
while (itr.hasNext()) {
pair = itr.next();
key = pair.getKey();
hash.put(key, pair.getValue());
}
}
if (nextTid != 0) {
hash.put("JMQNextTransactionID", Long.valueOf(nextTid));
}
pkt.setProperties(hash);
con.sendControlMessage(pkt);
if (fi.FAULT_INJECTION) {
checkFIAfterReply(msg.getPacketType());
}
}
/**
* Send a reply packet with a body and properties
*/
public void sendReplyBody(IMQConnection con, Packet msg, int type, int status, Hashtable hash, byte[] body) {
Packet pkt = new Packet(con.useDirectBuffers());
pkt.setPacketType(type);
pkt.setConsumerID(msg.getConsumerID());
if (hash == null) {
hash = new Hashtable();
}
hash.put("JMQStatus", Integer.valueOf(status));
if (((IMQBasicConnection) con).getDumpPacket() || ((IMQBasicConnection) con).getDumpOutPacket()) {
hash.put("JMQReqID", msg.getSysMessageID().toString());
}
pkt.setProperties(hash);
if (body != null) {
pkt.setMessageBody(body);
}
con.sendControlMessage(pkt);
}
/**
* Get the value of the JMQTransactionID property. For 2.0 clients the property is an Integer. For Falcon it is a Long
*/
public long getJMQTransactionID(Hashtable props) {
if (props != null) {
Object obj = props.get("JMQTransactionID");
if (obj instanceof Integer) {
// old protocol
return ((Integer) obj).intValue();
} else if (obj != null) {
// new protocol
return ((Long) obj).longValue();
}
}
return 0;
}
/**
* Convert the transaction ID on an iMQ 2.0 packet to the new style.
*/
public static void convertPacketTid(IMQConnection con, Packet p) {
long messagetid = p.getTransactionID();
HashMap tidMap = (HashMap) con.getClientData(IMQConnection.TRANSACTION_IDMAP);
if (tidMap == null) {
// No transactions have been started yet. Can't convert ID
return;
}
// Lookup old style ID in table
TransactionUID id = (TransactionUID) tidMap.get(Long.valueOf(messagetid));
if (id == null) {
return;
}
// Convert the old ID to the corresponding new ID
p.setTransactionID(id.longValue());
}
/**
* Method to handle Transaction Messages
*/
@Override
public boolean handle(IMQConnection con, Packet msg) throws BrokerException {
long messagetid = 0;
TransactionUID id = null;
TransactionState ts = null;
JMQXid xid = null;
Integer xaFlags = null;
boolean redeliverMsgs = false;
boolean startNextTransaction = false;
boolean setRedeliverFlag = true;
boolean isIndemp = msg.getIndempotent();
boolean replay = false;
boolean jmqonephase = false;
Boolean jmqonephaseFlag = null;
Hashtable props = null;
String reason = null;
TransactionList[] tls = Globals.getDestinationList().getTransactionList(con.getPartitionedStore());
TransactionList translist = tls[0];
try {
props = msg.getProperties();
if (props == null) {
props = new Hashtable();
}
} catch (Exception ex) {
logger.logStack(Logger.WARNING, "Unable to retrieve " + " properties from transaction message " + msg, ex);
props = new Hashtable();
}
// performance optimisation:
// start a new transaction immediately after commit or rollback and return
// transactionID in message ack.
// The client then does not need to make a separate call to startTransaction.
Boolean startNextTransactionBool = (Boolean) props.get("JMQStartNextTransaction");
startNextTransaction = startNextTransactionBool != null && startNextTransactionBool.booleanValue();
Boolean redeliverMsgBool = (Boolean) props.get("JMQRedeliver");
redeliverMsgs = redeliverMsgBool != null && redeliverMsgBool.booleanValue();
Boolean b = (Boolean) props.get("JMQUpdateConsumed");
boolean updateConsumed = b != null && b.booleanValue();
Boolean redeliverFlag = (Boolean) props.get("JMQSetRedelivered");
setRedeliverFlag = redeliverFlag == null || redeliverFlag.booleanValue();
Integer maxRollbackFlag = (Integer) props.get("JMQMaxRollbacks");
int maxRollbacks = (maxRollbackFlag == null ? -1 : maxRollbackFlag.intValue());
/**
* if dmqOnMaxRollbacks false, and max rollbacks reached, return error to client without rollback and without redelivery
* any consumed messages
*/
Boolean dmqOnMaxRollbacksFlag = (Boolean) props.get("JMQDMQOnMaxRollbacks");
boolean dmqOnMaxRollbacks = dmqOnMaxRollbacksFlag != null && dmqOnMaxRollbacksFlag.booleanValue();
if (maxRollbacks <= 0) {
dmqOnMaxRollbacks = Consumer.MSG_MAX_CONSECUTIVE_ROLLBACKS > 0;
}
jmqonephaseFlag = (Boolean) props.get("JMQXAOnePhase");
jmqonephase = jmqonephaseFlag != null && jmqonephaseFlag.booleanValue();
if (DEBUG) {
logger.log(Logger.DEBUG, PacketType.getString(msg.getPacketType()) + ": " + "TUID=" + id + ", JMQRedeliver=" + redeliverMsgBool
+ (jmqonephaseFlag == null ? "" : ", JMQXAOnePhase=" + jmqonephase));
}
List conlist = (List) con.getClientData(IMQConnection.TRANSACTION_LIST);
if (conlist == null) {
conlist = new ArrayList();
con.addClientData(IMQConnection.TRANSACTION_LIST, conlist);
}
// If there is a message body, then it should contain an Xid.
ByteBuffer body = msg.getMessageBodyByteBuffer();
if (body != null) {
JMQByteBufferInputStream bbis = new JMQByteBufferInputStream(body);
try {
xid = JMQXid.read(new DataInputStream(bbis));
startNextTransaction = false;
} catch (IOException e) {
logger.log(Logger.ERROR, BrokerResources.E_INTERNAL_BROKER_ERROR,
"Could not decode xid from packet: " + e + " Ignoring " + PacketType.getString(msg.getPacketType()));
reason = e.getMessage();
sendReply(con, msg, msg.getPacketType() + 1, Status.BAD_REQUEST, 0, reason);
return true;
}
}
// Get XAFlags. Note, not all packets will have this -- that's OK.
xaFlags = (Integer) props.get("JMQXAFlags");
// tidMap maps an old style transaction identifier to a TransactionUID.
// In iMQ2.0 the transaction identifier in the packet was an int
// generated by the client and only unique on the connection.
// In Falcon it is a long that is unique accross the cluster.
// So for 2.0 clients we allocate a TransactionUID and map the old
// style identifier to it.
//
// Get tidMap
HashMap tidMap = null;
synchronized (con) {
tidMap = (HashMap) con.getClientData(IMQConnection.TRANSACTION_IDMAP);
if (tidMap == null) {
tidMap = new HashMap();
con.addClientData(IMQConnection.TRANSACTION_IDMAP, tidMap);
}
}
// Go ahead and get the value of "JMQTransactionID" from the packet.
// may not be used in all cases.
messagetid = getJMQTransactionID(props);
// handle initial fault injections
if (fi.FAULT_INJECTION) {
checkFIBeforeProcess(msg.getPacketType());
}
boolean translistResolved = false;
// If it is a new transaction then create a new transaction id.
// else wrap the one specified in the packet
if (msg.getPacketType() == PacketType.START_TRANSACTION && (xaFlags == null || TransactionState.isFlagSet(XAResource.TMNOFLAGS, xaFlags))) {
// It's a START_TRANSACTION that is not a Join, or Resume.
// Allocate a new TransactionUID
if (isIndemp) { // deal with indemp flag
Object[] rets = TransactionList.getTransactionByCreator(msg.getSysMessageID().toString());
if (rets == null) {
id = new TransactionUID();
} else {
translist = (TransactionList) rets[0];
id = (TransactionUID) rets[1];
replay = true;
}
} else {
id = new TransactionUID();
}
translistResolved = true;
} else if (msg.getPacketType() == PacketType.RECOVER_TRANSACTION) {
if (messagetid != 0) {
// Recovering a specific transaction.
id = new TransactionUID(messagetid);
}
xid = null;
} else {
// Operation on an existing transaction
// Get TransactionUID out of packet
// If only Xid was specified need to lookup TransactionUID
if (messagetid == 0 && xid != null) {
Object[] rets = TransactionList.mapXidToTid(xid, con);
if (rets != null) {
translist = (TransactionList) rets[0];
id = (TransactionUID) rets[1];
messagetid = id.longValue();
translistResolved = true;
} else {
// Hmmm...haven't seen this Xid before.
// XXX I18N
logger.log(Logger.WARNING, PacketType.getString(msg.getPacketType()) + ": Ignoring unknown XID=" + xid + " broker will "
+ (msg.getSendAcknowledge() ? "notify the client" : " not notify the client"));
if (msg.getSendAcknowledge()) {
reason = "Uknown XID " + xid;
sendReply(con, msg, msg.getPacketType() + 1, Status.NOT_FOUND, 0, reason);
}
return true;
}
} else if (messagetid != 0) {
if (con.getClientProtocolVersion() == PacketType.VERSION1) {
// Map old style to new
synchronized (tidMap) {
id = (TransactionUID) tidMap.get(Long.valueOf(messagetid));
}
} else {
// Wrap new style
id = new TransactionUID(messagetid);
}
}
// Get the state of the transaction
if (id == null) {
logger.log(Logger.INFO,
"InternalError: " + "Transaction ID was not passed by " + "the jms api on a method that reqires an " + "existing transaction ");
sendReply(con, msg, msg.getPacketType() + 1, Status.ERROR, 0, "Internal Error: bad MQ protocol," + " missing TransactionID");
return true;
}
if (translistResolved) {
if (translist == null) {
String emsg = "XXXNo transaction list found to process " + PacketType.getString(msg.getPacketType()) + " for transaction " + id + "[" + xid
+ "]";
logger.log(Logger.WARNING, emsg);
if (msg.getSendAcknowledge()) {
reason = emsg;
sendReply(con, msg, msg.getPacketType() + 1, Status.GONE, 0, reason);
}
return true;
}
ts = translist.retrieveState(id);
} else {
Object[] oo = TransactionList.getTransListAndState(id, con, false, false);
if (oo != null) {
translist = (TransactionList) oo[0];
ts = (TransactionState) oo[1];
}
}
if (ts == null) {
// Check if we've recently operated on this transaction
if (isIndemp && (msg.getPacketType() == PacketType.ROLLBACK_TRANSACTION || msg.getPacketType() == PacketType.COMMIT_TRANSACTION)) {
if (msg.getSendAcknowledge()) {
sendReply(con, msg, msg.getPacketType() + 1, Status.OK, id.longValue(), reason);
return true;
}
if (fi.FAULT_INJECTION) {
checkFIAfterProcess(msg.getPacketType());
checkFIAfterReply(msg.getPacketType());
}
} else {
ts = cacheGetState(id, con);
if (ts != null) {
// XXX l10n
logger.log(Logger.ERROR,
"Transaction ID " + id + " has already been resolved. Ignoring request: " + PacketType.getString(msg.getPacketType())
+ ". Last state of this transaction: " + ts.toString() + " broker will "
+ (msg.getSendAcknowledge() ? "notify the client" : " not notify the client"));
} else {
logger.log((BrokerStateHandler.isShuttingDown() ? Logger.DEBUG : Logger.WARNING),
Globals.getBrokerResources().getKString(
(msg.getSendAcknowledge() ? BrokerResources.W_UNKNOWN_TRANSACTIONID_NOTIFY_CLIENT
: BrokerResources.W_UNKNOWN_TRANSACTIONID_NONOTIFY_CLIENT),
"" + id + "(" + messagetid + ")" + (xid == null ? "" : "XID=" + xid), PacketType.getString(msg.getPacketType())) + "\n"
+ com.sun.messaging.jmq.io.PacketUtil.dumpPacket(msg));
}
// Only send reply if A bit is set
if (msg.getSendAcknowledge()) {
reason = "Unknown transaction " + id;
sendReply(con, msg, msg.getPacketType() + 1, Status.NOT_FOUND, id.longValue(), reason);
}
return true;
}
}
}
if (DEBUG) {
logger.log(Logger.INFO,
this.getClass().getName() + ": " + PacketType.getString(msg.getPacketType()) + ": " + "TUID=" + id + " XAFLAGS="
+ TransactionState.xaFlagToString(xaFlags) + (jmqonephaseFlag == null ? "" : " JMQXAOnePhase=" + jmqonephase) + " State=" + ts
+ " Xid=" + xid);
}
// If a packet came with an Xid, make sure it matches what
// we have in the transaction table.
if (xid != null && ts != null) {
if (ts.getXid() == null || !xid.equals(ts.getXid())) {
// This should never happen
logger.log(Logger.ERROR, BrokerResources.E_INTERNAL_BROKER_ERROR,
"Transaction Xid mismatch. " + PacketType.getString(msg.getPacketType()) + " Packet has tuid=" + id + " xid=" + xid
+ ", transaction table has tuid=" + id + " xid=" + ts.getXid() + ". Using values from table.");
xid = ts.getXid();
}
}
if (xid == null && ts != null && ts.getXid() != null && msg.getPacketType() != PacketType.RECOVER_TRANSACTION) {
// Client forgot to put Xid in packet.
xid = ts.getXid();
logger.log(Logger.WARNING, BrokerResources.E_INTERNAL_BROKER_ERROR,
"Transaction Xid " + xid + " not found in " + PacketType.getString(msg.getPacketType()) + " packet for tuid " + id + ". Will use " + xid);
}
int status = Status.OK;
// retrieve new 4.0 properties
AutoRollbackType type = null;
long lifetime = 0;
boolean sessionLess = false;
Integer typeValue = (Integer) props.get("JMQAutoRollback");
Long lifetimeValue = (Long) props.get("JMQLifetime");
Boolean sessionLessValue = (Boolean) props.get("JMQSessionLess");
if (typeValue != null) {
type = AutoRollbackType.getType(typeValue.intValue());
}
if (lifetimeValue != null) {
lifetime = lifetimeValue.longValue();
}
if (sessionLessValue != null) {
sessionLess = sessionLessValue.booleanValue();
} else {
sessionLess = xid != null;
}
switch (msg.getPacketType()) {
case PacketType.START_TRANSACTION: {
try {
doStart(translist, id, conlist, con, type, xid, sessionLess, lifetime, messagetid, xaFlags, msg.getPacketType(), replay,
msg.getSysMessageID().toString());
} catch (Exception ex) {
status = Status.ERROR;
logger.logStack(Logger.ERROR, ex.toString() + ": TUID=" + id + " Xid=" + xid, ex);
reason = ex.getMessage();
if (ex instanceof BrokerException) {
status = ((BrokerException) ex).getStatusCode();
}
}
sendReply(con, msg, PacketType.START_TRANSACTION_REPLY, status, id.longValue(), reason);
break;
}
case PacketType.END_TRANSACTION:
try {
// if the noop flag is set the we don't want to actually
// process the XA_END. See bug 12364646 and XAResourceImpl.end()
Boolean jmqnoop = (Boolean) props.get("JMQNoOp");
if (jmqnoop == null || jmqnoop == false) {
doEnd(translist, msg.getPacketType(), xid, xaFlags, ts, id);
}
} catch (Exception ex) {
status = Status.ERROR;
reason = ex.getMessage();
if (ex instanceof BrokerException) {
status = ((BrokerException) ex).getStatusCode();
}
}
sendReply(con, msg, msg.getPacketType() + 1, status, id.longValue(), reason);
break;
case PacketType.PREPARE_TRANSACTION:
BrokerException bex = null;
HashMap tmpp = null;
try {
doPrepare(translist, id, xaFlags, ts, msg.getPacketType(), jmqonephase, null, con);
} catch (Exception ex) {
status = Status.ERROR;
if ((!(ex instanceof BrokerDownException) && !(ex instanceof AckEntryNotFoundException)) || DEBUG_CLUSTER_TXN) {
logger.logStack(Logger.ERROR, ex.toString() + ": TUID=" + id + " Xid=" + xid, ex);
} else {
logger.log(((ex instanceof AckEntryNotFoundException) ? Logger.WARNING : Logger.ERROR), ex.toString() + ": TUID=" + id + " Xid=" + xid);
}
reason = ex.getMessage();
if (ex instanceof BrokerException) {
status = ((BrokerException) ex).getStatusCode();
bex = (BrokerException) ex;
}
if (ts.getState() == TransactionState.FAILED) {
tmpp = new HashMap();
tmpp.put("JMQPrepareStateFAILED", Boolean.TRUE);
}
}
sendReply(con, msg, msg.getPacketType() + 1, status, id.longValue(), reason, bex, tmpp, 0L);
break;
case PacketType.RECOVER_TRANSACTION:
Vector v = null;
if (id != null) {
// Check if specified transaction is in PREPARED state
v = new Vector();
ts = translist.retrieveState(id);
if (ts.getState() == TransactionState.PREPARED) {
v.add(id);
}
} else {
// XA Transaction only. We return all Xids on a STARTRSCAN
// and nothing on ENDRSCAN or NOFLAGS
if (xaFlags == null || !TransactionState.isFlagSet(XAResource.TMSTARTRSCAN, xaFlags)) {
Hashtable hash = new Hashtable();
hash.put("JMQQuantity", Integer.valueOf(0));
sendReplyBody(con, msg, PacketType.RECOVER_TRANSACTION_REPLY, Status.OK, hash, null);
break;
}
// Get list of transactions in PENDING state and marshal
// the Xid's to a byte array.
v = translist.getTransactions(TransactionState.PREPARED);
}
int nIDs = v.size();
int nWritten = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream(nIDs * JMQXid.size());
DataOutputStream dos = new DataOutputStream(bos);
for (int n = 0; n < nIDs; n++) {
TransactionUID tuid = (TransactionUID) v.get(n);
TransactionState _ts = translist.retrieveState(tuid);
if (_ts == null) {
// Should never happen
logger.log(Logger.ERROR, BrokerResources.E_INTERNAL_BROKER_ERROR, "Could not find state for TUID " + tuid);
continue;
}
JMQXid _xid = _ts.getXid();
if (_xid != null) {
try {
_xid.write(dos);
nWritten++;
} catch (Exception e) {
logger.log(Logger.ERROR, BrokerResources.E_INTERNAL_BROKER_ERROR, "Could not write Xid " + _xid + " to message body: " + e.toString());
}
}
}
Hashtable hash = new Hashtable();
hash.put("JMQQuantity", Integer.valueOf(nWritten));
if (id != null) {
hash.put("JMQTransactionID", Long.valueOf(id.longValue()));
}
// Send reply with serialized Xids as the body
sendReplyBody(con, msg, PacketType.RECOVER_TRANSACTION_REPLY, Status.OK, hash, bos.toByteArray());
break;
case PacketType.COMMIT_TRANSACTION:
// XXX-LKS clean up any destination locks ???
try {
// doCommit will send reply if successful
if (xaFlags != null && jmqonephase) {
Integer newxaFlags = Integer.valueOf(xaFlags.intValue() & ~XAResource.TMONEPHASE);
doCommit(translist, id, xid, newxaFlags, ts, conlist, true, con, msg);
} else {
doCommit(translist, id, xid, xaFlags, ts, conlist, true, con, msg, startNextTransaction);
}
} catch (BrokerException ex) {
// doCommit has already logged error
status = ex.getStatusCode();
reason = ex.getMessage();
if (msg.getSendAcknowledge()) {
HashMap tmppp = null;
if (!jmqonephase && TransactionState.isFlagSet(XAResource.TMONEPHASE, xaFlags)) {
if (ts.getState() == TransactionState.FAILED) {
tmppp = new HashMap();
tmppp.put("JMQPrepareStateFAILED", Boolean.TRUE);
}
}
sendReply(con, msg, msg.getPacketType() + 1, status, id.longValue(), reason, ex, tmppp, 0L);
} else {
if (fi.FAULT_INJECTION) {
checkFIAfterProcess(msg.getPacketType());
checkFIAfterReply(msg.getPacketType());
}
}
}
break;
case PacketType.ROLLBACK_TRANSACTION: {
BrokerException maxrbex = null;
try {
preRollback(translist, id, xid, xaFlags, ts);
try {
// if redeliverMsgs is true, we want to redeliver
// to both active and inactive consumers
boolean processActiveConsumers = redeliverMsgs;
redeliverUnacked(translist, id, processActiveConsumers, setRedeliverFlag, updateConsumed, maxRollbacks, dmqOnMaxRollbacks);
} catch (BrokerException ex) {
if (ex instanceof MaxConsecutiveRollbackException) {
maxrbex = ex;
} else {
logger.logStack(Logger.ERROR, "REDELIVER: " + ex.toString() + ": TUID=" + id + " Xid=" + xid, ex);
}
reason = ex.getMessage();
status = ex.getStatusCode();
}
if (!(maxrbex != null && !dmqOnMaxRollbacks)) {
try {
if (fi.checkFault(fi.FAULT_TXN_ROLLBACK_1_5_EXCEPTION, null)) {
// fi.unsetFault(fi.FAULT_TXN_ROLLBACK_1_5_EXCEPTION);
throw new BrokerException(fi.FAULT_TXN_ROLLBACK_1_5_EXCEPTION);
}
doRollback(translist, id, xid, xaFlags, ts, conlist, con, RollbackReason.APPLICATION);
} catch (BrokerException ex) {
if (!ex.isStackLogged()) {
logger.logStack(logger.WARNING, ex.getMessage(), ex);
} else {
logger.log(logger.WARNING, br.getKString(br.X_ROLLBACK_TXN, id, ex.getMessage()));
}
// doRollback has already logged error
if (maxrbex == null) {
reason = ex.getMessage();
status = ex.getStatusCode();
}
}
}
} catch (BrokerException ex) {
reason = ex.getMessage();
status = ex.getStatusCode();
}
// performance optimisation
// start next transaction and return transaction id
long nextTxnID = 0;
if (startNextTransaction) {
try {
TransactionUID nextid = new TransactionUID();
doStart(translist, nextid, conlist, con, type, xid, sessionLess, lifetime, 0, xaFlags, PacketType.START_TRANSACTION, replay,
msg.getSysMessageID().toString());
nextTxnID = nextid.longValue();
} catch (Exception ex) {
logger.logStack(Logger.ERROR, ex.toString() + ": TUID=" + id + " Xid=" + xid, ex);
if (maxrbex == null) {
status = Status.ERROR;
reason = ex.getMessage();
if (ex instanceof BrokerException) {
status = ((BrokerException) ex).getStatusCode();
}
}
}
}
if (msg.getSendAcknowledge()) {
sendReply(con, msg, msg.getPacketType() + 1, status, id.longValue(), reason, null, null, nextTxnID);
} else {
if (fi.FAULT_INJECTION) {
checkFIAfterProcess(msg.getPacketType());
checkFIAfterReply(msg.getPacketType());
}
}
break;
}
}
return true;
}
public void checkFIBeforeProcess(int type) throws BrokerException {
switch (type) {
case PacketType.START_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_START_1, null, 2, false);
break;
case PacketType.END_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_END_1, null, 2, false);
break;
case PacketType.PREPARE_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_PREPARE_1, null, 2, false);
break;
case PacketType.ROLLBACK_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_ROLLBACK_1, null, 2, false);
break;
case PacketType.COMMIT_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_COMMIT_1, null, 2, false);
break;
default:
}
}
public void checkFIAfterProcess(int type) {
switch (type) {
case PacketType.START_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_START_2, null, 2, false);
break;
case PacketType.END_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_END_2, null, 2, false);
break;
case PacketType.PREPARE_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_PREPARE_2, null, 2, false);
break;
case PacketType.ROLLBACK_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_ROLLBACK_2, null, 2, false);
break;
case PacketType.COMMIT_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_COMMIT_2, null, 2, false);
break;
default:
}
}
public void checkFIAfterDB(int type) {
switch (type) {
case PacketType.ROLLBACK_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_ROLLBACK_4, null, 2, false);
break;
case PacketType.COMMIT_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_COMMIT_4, null, 2, false);
break;
default:
}
}
public void checkFIAfterReply(int type) {
switch (type) {
case PacketType.START_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_START_3, null, 2, false);
break;
case PacketType.END_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_END_3, null, 2, false);
break;
case PacketType.PREPARE_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_PREPARE_3, null, 2, false);
break;
case PacketType.ROLLBACK_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_ROLLBACK_3, null, 2, false);
break;
case PacketType.COMMIT_TRANSACTION:
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_COMMIT_3, null, 2, false);
break;
default:
}
}
/**
* We cache the last N transactions to be committed or rolledback. This is simply to let us more easily debug problems
* when the client sends a bogus transaction ID.
*
* To improve performance, this feature should be disabled by setting the "imq.transaction.debug" property to false. For
* now, it will be disabled by default to improve direct mode benchmark performance.
*/
private void cacheSetState(TransactionUID id, TransactionState ts, IMQConnection con) {
// Do this only if transaction debug is enabled!
if (GlobalProperties.getGlobalProperties().TRANSACTION_DEBUG) {
if (con == null) {
return;
}
CacheHashMap cache = (CacheHashMap) con.getClientData(IMQConnection.TRANSACTION_CACHE);
if (cache == null) {
cache = new CacheHashMap(4);
con.addClientData(IMQConnection.TRANSACTION_CACHE, cache);
}
cache.put(id, ts);
}
}
private TransactionState cacheGetState(TransactionUID id, IMQConnection con) {
TransactionState ts = null;
// Do this only if transaction debug is enabled!
if (GlobalProperties.getGlobalProperties().TRANSACTION_DEBUG) {
CacheHashMap cache = (CacheHashMap) con.getClientData(IMQConnection.TRANSACTION_CACHE);
if (cache != null) {
ts = (TransactionState) cache.get(id);
}
}
return ts;
}
public void doCommit(TransactionList translist, TransactionUID id, JMQXid xid, Integer xaFlags, TransactionState ts, List conlist, boolean sendReply,
IMQConnection con, Packet msg) throws BrokerException {
doCommit(translist, id, xid, xaFlags, ts, conlist, sendReply, con, msg, false);
}
/**
* Commit a transaction. This method is invoked from two places: 1) From TransactionHandler.handle() when handling a
* client COMMIT packet. This is the common case. 2) From the admin handler when an admin commit request has been issued
* on a PREPARED XA transaction.
*
* @param id The TransactionUID to commit
* @param xid The Xid of the transaction to commit. Required if transaction is an XA transaction. Must be null if it is
* not an XA transaction.
* @param xaFlags xaFlags passed on COMMIT operation. Used only if an XA transaction.
* @param ts Current TransactionState of this transaction.
* @param conlist List of transactions on this connection. Will be null if commit is trigger by an admin request.
* @param sendReply True to have method send a Status.OK reply while processing transaction. This should be "true" for
* client initiated commits, "false" for admin initiated commits.
* @param con Connection client commit packet came in on or, for admin, the connection the admin request came in on.
* @param msg Client commit packet. Should be "null" for admin initiated commits.
*
* @throws BrokerException on an error. The method will have logged a message to the broker log.
*/
public void doCommit(TransactionList translist, TransactionUID id, JMQXid xid, Integer xaFlags, TransactionState ts, List conlist, boolean sendReply,
IMQConnection con, Packet msg, boolean startNextTransaction) throws BrokerException {
int status = Status.OK;
HashMap cmap = null;
HashMap sToCmap = null;
List plist = null;
PartitionedStore pstore = translist.getPartitionedStore();
int transactionType = BaseTransaction.UNDEFINED_TRANSACTION_TYPE; // local, or cluster
if (fi.checkFault(FaultInjection.FAULT_TXN_COMMIT_1_EXCEPTION, null)) {
fi.unsetFault(FaultInjection.FAULT_TXN_COMMIT_1_EXCEPTION);
throw new BrokerException(FaultInjection.FAULT_TXN_COMMIT_1_EXCEPTION);
}
// let acks get handled at a lower level since the
// lower level methods assumes only 1 ack per message
plist = translist.retrieveSentMessages(id);
cmap = translist.retrieveConsumedMessages(id);
sToCmap = translist.retrieveStoredConsumerUIDs(id);
cacheSetState(id, ts, con);
// remove from our active connection list
if (conlist != null) {
conlist.remove(id);
}
// new performance enhancement
// log transactions before we store transaction work in message store
// and before remote commit
try {
Globals.getStore().txnLogSharedLock.lock();
TransactionWork txnWork = null;
if (Globals.isNewTxnLogEnabled()) {
txnWork = getTransactionWork2(translist.getPartitionedStore(), plist, cmap, sToCmap);
}
// Update transaction state
try {
int s;
if (xid == null) {
// Plain JMS transaction.
s = TransactionState.COMMITTED;
} else {
// XA Transaction.
s = ts.nextState(PacketType.COMMIT_TRANSACTION, xaFlags);
}
// After this call, returned base transaction will either be:
// a) null (for single phase LOCAL transaction)
// b) a prepared XA LOCAL transaction
// c) a prepared (XA or not) CLUSTER transaction
// currently, all cluster transactions are 2 phase
BaseTransaction baseTransaction = doRemoteCommit(translist, id, xaFlags, ts, s, msg, txnWork, con);
if (Globals.isNewTxnLogEnabled()) {
if (ts.getState() == TransactionState.PREPARED) {
// commit called (from client) on 2-phase transaction
transactionType = BaseTransaction.LOCAL_TRANSACTION_TYPE;
if (translist.isClusterTransaction(id)) {
transactionType = BaseTransaction.CLUSTER_TRANSACTION_TYPE;
}
logTxnCompletion(translist.getPartitionedStore(), id, TransactionState.COMMITTED, transactionType);
} else if ((baseTransaction != null && baseTransaction.getState() == TransactionState.PREPARED)) {
transactionType = baseTransaction.getType();
logTxnCompletion(translist.getPartitionedStore(), id, TransactionState.COMMITTED, transactionType);
} else {
// one phase commit, log all work here
transactionType = BaseTransaction.LOCAL_TRANSACTION_TYPE;
LocalTransaction localTxn = new LocalTransaction(id, TransactionState.COMMITTED, xid, txnWork);
logTxn(translist.getPartitionedStore(), localTxn);
}
} else {
// System.out.println("isFastLogTransactions=false ");
}
if (fi.FAULT_INJECTION) {
fi.checkFaultAndThrowBrokerException(FaultInjection.FAULT_TXN_COMMIT_1_1, null);
}
if (ts.getState() == TransactionState.PREPARED || (baseTransaction != null && baseTransaction.getState() == TransactionState.PREPARED)) {
translist.updateState(id, s, true);
} else { // 1-phase commit
if (ts.getType() != AutoRollbackType.NEVER && Globals.isMinimumPersistLevel2()) {
translist.updateStateCommitWithWork(id, s, true);
} else {
translist.updateState(id, s, true);
}
}
if (fi.FAULT_INJECTION) {
checkFIAfterDB(PacketType.COMMIT_TRANSACTION);
fi.checkFaultAndExit(FaultInjection.FAULT_TXN_COMMIT_1_5, null, 2, false);
}
startTxnAndSendReply(translist, con, msg, status, startNextTransaction, conlist, xid, id, xaFlags, sendReply);
} catch (BrokerException ex) {