-
Notifications
You must be signed in to change notification settings - Fork 143
/
RecoveryManager.java
1881 lines (1611 loc) · 67 KB
/
RecoveryManager.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) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1995-1997 IBM Corp. All rights reserved.
* Copyright (c) 2021 Contributors to the Eclipse Foundation
*
* 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
*/
//----------------------------------------------------------------------------
//
// Module: RecoveryManager.java
//
// Description: Process transaction management.
//
// Product: com.sun.jts.CosTransactions
//
// Author: Simon Holdsworth
//
// Date: March, 1997
//----------------------------------------------------------------------------
package com.sun.jts.CosTransactions;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.omg.CORBA.COMM_FAILURE;
import org.omg.CORBA.SystemException;
import org.omg.CORBA.TRANSIENT;
import org.omg.CosTransactions.Status;
import com.sun.enterprise.transaction.jts.api.TransactionRecoveryFence;
import com.sun.jts.codegen.jtsxa.OTSResource;
import com.sun.jts.jtsxa.OTSResourceImpl;
import com.sun.jts.utils.LogFormatter;
import com.sun.logging.LogDomains;
/**
* This class manages information required for recovery, and also general
* state regarding transactions in a process.
*
* @version 0.01
*
* @author Simon Holdsworth, IBM Corporation
*
* @see
*/
//----------------------------------------------------------------------------
// CHANGE HISTORY
//
// Version By Change Description
// 0.01 SAJH Initial implementation.
//-----------------------------------------------------------------------------
public class RecoveryManager {
/**
* list of XA Resources to be recovered.
*/
private static Enumeration uniqueRMSet = null;
/**
* This attribute indicates whether initialisation has been started.
*/
private static boolean initialised = false;
/**
* This attribute indicates the number of Coordinator objects which require
* resync. This is set to the number of in-doubt transactions recovered
* from the log, then decreased as transactions are resolved.
*/
private static int resyncCoords = 0;
/**
* This attribute records the thread which is used to perform resync during
* restart
*/
private static ResyncThread resyncThread = null;
/**
* This attribute is used to block new requests while there are
* Coordinators which still require resync.
*/
private static volatile EventSemaphore resyncInProgress = new EventSemaphore();
/**
* This attribute is used to block requests against RecoveryCoordinators or
* CoordinatorResources before recovery has completed.
*/
private static volatile EventSemaphore recoveryInProgress = new EventSemaphore();
/**
* This attribute is used by the Recovery Thread to know if the
* xaResource list is ready in case manual recovery is attempted.
*/
private static volatile EventSemaphore uniqueRMSetReady = new EventSemaphore();
private static Hashtable coordsByGlobalTID = new Hashtable();
private static Hashtable coordsByLocalTID = new Hashtable();
/**
* Mapping between transactionIds and threads. This is used to ensure
* there is at most one thread doing work in a transaction.
*/
private static Hashtable transactionIds = new Hashtable();
/**
* Mapping between incompleteTxIds and their commit decisions.
*/
private static Hashtable inCompleteTxMap = new Hashtable();
// This will start TransactionRecoveryFence service as soon as all resources are available.
private static TransactionRecoveryFence txRecoveryFence = new TransactionRecoveryFenceSimple();
/**
* This is intented to be used as a lock object.
*/
private static java.lang.Object lockObject = new java.lang.Object();
/**
* Logger to log transaction messages
*/
static Logger _logger = LogDomains.getLogger(RecoveryManager.class, LogDomains.TRANSACTION_LOGGER);
/**
* Initialises the static state of the RecoveryManager class.
*
* @param
*
* @return
*
* @see
*/
static void initialise() {
// If already initialised, return immediately.
if (initialised) {
return;
}
initialised = true;
// Perform recovery/resync if necessary.
if (Configuration.isRecoverable()) {
resyncThread = new ResyncThread();
if(_logger.isLoggable(Level.FINE))
{
_logger.logp(Level.FINE,"RecoveryManager","initialise()",
"Before starting ResyncThread ");
}
//resyncThread.start();
} else {
// If the process is non-recoverable, but there is a valid server
// name,then check for a log file and issue a warning message
// if one exists. Also ensure that restart required is set to no.
if (!Configuration.isAppClientContainer()) {
String serverName = Configuration.getServerName();
if (serverName != null && Log.checkFileExists(serverName)) {
_logger.log(Level.INFO,"jts.log_file_transient_server",serverName);
}
}
// Modify the restart requirement in the repository, and
// post the event semaphore as there will be no Coordinators
// requiring resync.
try {
recoveryInProgress.post(); // BUGFIX (Ram Jeyaraman)
resyncComplete(false, false);
} catch (Throwable exc) {exc.printStackTrace();}
}
}
/**
* Sets up the local and global identifier to Coordinator mapping as given.
* <p>
* If the global identifier has already got associated information,
* the operation returns false.
* <p>
* The timeout value, if non-zero, is used to establish a time-out for the
* transaction; if the local identifier to Coordinator association
* exists after the time-out period, then the TimeoutManager will
* attempt to roll the transaction back.
*
* @param globalTID The global identifier for the transaction.
* @param localTID The local identifier for the transaction.
* @param coord The Coordinator for the transaction.
* @param timeout The timeout for the transaction.
* @param log The log object for the transaction.
*
* @return Indicates success of the operation.
*
* @see
*/
static boolean addCoordinator(GlobalTID globalTID,
Long localTID, CoordinatorImpl coord, int timeout) {
boolean result = true;
// Attempt to add the global and local indentifier to
// Coordinator associations to the maps.
coordsByGlobalTID.put(globalTID,coord);
coordsByLocalTID.put(localTID,coord);
// Set up the timeout for the transaction. When active, the
// timeout thread will periodically examine the map and abort
// any active transactions on it that have gone beyond their
// allocated time.
if (timeout != 0) {
TimeoutManager.setTimeout(localTID, TimeoutManager.ACTIVE_TIMEOUT, timeout);
}
return result;
}
/**
* Removes the Coordinator associations for the given identifiers.
* <p>
* If there was no association the operation returns false.
* <p>
* Any timeout that was established for the Coordinator is cancelled,
* and any active thread associations for the transaction are removed
* and the corresponding Control objects destroyed.
*
* @param globalTID The global identifier for the transaction.
* @param localTID The local identifier for the transaction.
* @param aborted The transaction aborted indicator.
*
* @return Indicates success of the operation.
*
* @see
*/
static boolean removeCoordinator(GlobalTID globalTID, Long localTID, boolean aborted) {
boolean result = false;
// Remove the global identifier to Coordinator mapping if possible.
CoordinatorImpl coord = null;
result = (coordsByGlobalTID.remove(globalTID) != null);
// Remove the InternalTid to Coordinator mapping if possible.
if (result) {
coord = (CoordinatorImpl) coordsByLocalTID.remove(localTID);
result = (coord != null);
}
// If that succeeded, forget the CoordinatorLog object, if the
// transaction is not a subtransaction. The following may return
// FALSE if there are no log records available
// (i.e. non-recoverable OTS).
if (coord != null) {
try {
if (coord.is_top_level_transaction()) {
if (inCompleteTxMap.get(coord) == null) {
if (Configuration.isDBLoggingEnabled())
LogDBHelper.getInstance().deleteRecord(localTID.longValue());
else
CoordinatorLog.removeLog(localTID);
} else {
if(_logger.isLoggable(Level.FINE)) {
_logger.logp(Level.FINE,"RecoveryManager","removeCoordinator()",
"Transaction hasn't completed, let it stay in active logs");
}
}
}
} catch(SystemException exc) {
result = false;
}
}
// Clear the timeout for the transaction, if any.
// Perform the removal under the timer mutex.
TimeoutManager.setTimeout(localTID, TimeoutManager.CANCEL_TIMEOUT, 0);
// Modify any thread associations there may be for the transaction, to
// indicate that the transaction has ended.
// COMMENT(Ram J) 09/19/2001 This below line is commented out since in
// the J2EE controlled environment, all threads are associated and
// dissociated in an orderly fashion, as well as there is no possibility
// of concurrent threads active in a given transaction.
//CurrentTransaction.endAll(globalTID, aborted);
// If the count of resyncing Coordinators is greater than zero,
// this means we are still in resync. Decrease the count.
if (resyncCoords > 0) {
resyncCoords--;
// If the number of resyncing Coordinators is now zero,
// we may allow new work.
if (resyncCoords == 0) {
try {
resyncComplete(true, true);
} catch (Throwable exc) {}
}
}
return result;
}
/**
* Returns a reference to the Coordinator object that corresponds to the
* global identifier passed as a parameter.
*
* @param globalTID The global identifier for the transaction.
*
* @return The Coordinator for the transaction.
*
* @see
*/
static CoordinatorImpl getCoordinator(GlobalTID globalTID) {
CoordinatorImpl result = (CoordinatorImpl) coordsByGlobalTID.get(globalTID);
return result;
}
/**
* Read and update the transaction ID map atomically with the current
* thread, if and only if there is no concurrent activity for the
* specified transaction id.
*
* @param tid transaction id.
*
* @return true if there is no concurrent activity and the map has been
* updated.
*/
static boolean readAndUpdateTxMap(GlobalTID tid) {
synchronized (transactionIds) {
Thread thread = (Thread) transactionIds.get(tid);
if (thread != null) { // concurrent activity
return false;
}
// register the thread for the transaction id
transactionIds.put(tid, Thread.currentThread());
return true;
}
}
/**
* Get the value (thread) for the specified transaction id from the
* transaction ID map.
*
* @return the value for the transaction id key from the
* transaction ID map.
*/
static Thread getThreadFromTxMap(GlobalTID tid) {
return (Thread) transactionIds.get(tid);
}
/**
* Remove the specified transaction id from the transaction ID map.
*
* @return the value for the transaction id key from the
* transaction ID map.
*/
static Thread removeFromTxMap(GlobalTID tid) {
return (Thread) transactionIds.remove(tid);
}
/**
* Requests that the RecoveryManager proceed with recovery.
* <p>
* The log is read and a list of TopCoordinators is reconstructed that
* corresponds to those transactions that were in-doubt at the time of the
* previous failure.
* <p>
* The method returns true if any transactions require resync.
*
* @param
*
* @return Indicates that there are Coordinators requiring resync.
*
* @see
*/
static boolean recover() {
boolean result = false;
if (skipRecoveryOnStartup()) {
_logger.fine("========== no recovery ==========");
// Quickly release all locks
// Post the recovery in progress event so that requests
// waiting for recovery to complete may proceed.
recoveryInProgress.post();
// And finish resync
try {
resyncComplete(false, false);
} catch (Throwable ex) { }
return result;
}
// Check the log for transactions. If there are any outstanding
// transactions, recover the Coordinator objects and set up the
// OMGtid to Coordinator map.
boolean keypointRequired = false;
Enumeration logRecords = CoordinatorLog.getLogged();
while (logRecords.hasMoreElements()) {
keypointRequired = true;
try {
new TopCoordinator().
reconstruct((CoordinatorLog) logRecords.nextElement());
} catch(Exception exc) {
_logger.log(Level.SEVERE,"jts.recovery_in_doubt_exception",exc);
_logger.log(Level.SEVERE,"jts.recovery_in_doubt",exc.toString());
String msg = LogFormatter.getLocalizedMessage(_logger,
"jts.recovery_in_doubt",
new java.lang.Object[] {exc.toString()});
throw new org.omg.CORBA.INTERNAL(msg);
}
}
// Perform recovery of XA resources.
//recoverXA();
if (_logger.isLoggable(Level.FINE)) {
_logger.logp(Level.FINE,"RecoveryManager","recover()",
"Before invoking proceedWithXARecovery()");
}
proceedWithXARecovery();
// Post the recovery in progress event so that requests
// waiting for recovery to complete may proceed.
recoveryInProgress.post();
// If resync is not needed, then perform after-resync
// tasks immediately.
result = coordsByGlobalTID.size() > 0;
if (!result) {
try {
resyncComplete(false,keypointRequired);
} catch(Throwable exc) {}
}
return result;
}
/**
* Performs resync processing.
* <p>
* The RecoveryManager gets recovery information from each TopCoordinator
* (while holding the transaction lock) and proceeds with resync.
* <p>
* Once resync is complete, a keypoint is taken to indicate that the log
* information is no longer required.
*
* @param
*
* @return
*
* @see
*/
static void resync() {
// If there are any transactions, proceed with resync. The map of
// coordinators by global identifier is created during the
// TopCoordinator reconstruct method when the coordinators are added
// via addCoordinator. We copy the contents to another map as
// Coordinators will remove themselves from the map during resync.
// Now that the Coordinators have been reconstructed, record
// the number of transactions requiring resync,
// and make an event trace point. We must clone the Hashtable
// here so that the Enumeration does not get
// changed when any subsequent transaction is created (this can happen
// when the last Coordinator is removed).
resyncCoords = coordsByGlobalTID.size();
Enumeration resyncList = ((Hashtable) coordsByGlobalTID.clone()).elements();
boolean isRoot[] = new boolean[1];
// Go through and resync each transaction. The transaction lock
// for each transaction is obtained to avoid deadlocks during recovery.
while (resyncList.hasMoreElements()) {
TopCoordinator coord = (TopCoordinator)resyncList.nextElement();
try {
// Before performing recovery, lock the coordinator.
synchronized (coord) {
Status state = coord.recover(isRoot);
if (state == Status.StatusUnknown) {
// If the coordinator can be locked, then perform
// recovery on it. If the outcome is not currently
// known, we do nothing with the transaction,
// as we expect to eventually get an outcome
// from the parent. In this case an in-doubt timeout
// is established for the
// transaction so that it will continue to retry.
// For subordinates, the Coordinator will compl-ete the
// transaction itself as it will have no
// Synchronization objects.
TimeoutManager.setTimeout(
coord.getLocalTID(),
TimeoutManager.IN_DOUBT_TIMEOUT,
60);
} else if (state == Status.StatusCommitted) {
// For committed or rolled back, proceed with
// completion of the transaction, regardless of
// whether it is the root or a subordinate.
// If the transaction represents a root, it would
// normally wait for the CoordinatorTerm object to
// call before completing the transaction. As there is
// no CoordinatorTerm in recovery, we must do it here.
if(_logger.isLoggable(Level.FINE))
{
_logger.logp(Level.FINE,"RecoveryManager","resync()",
"Before invoking commit on the reconstructed coordinator, "+
"GTID is: "+
coord.superInfo.globalTID.toString());
}
try {
coord.commit();
} catch (Throwable exc) {
_logger.log(Level.WARNING,"jts.exception_during_resync",
new java.lang.Object[] {exc.toString(),"commit"});
}
if (isRoot[0]) {
try {
coord.afterCompletion(state);
} catch (Throwable exc) {
_logger.log(Level.WARNING,"jts.exception_during_resync",
new java.lang.Object[] {exc.toString(),
"after_completion"});
}
}
} else {
// By default, roll the transaction back.
try {
if(_logger.isLoggable(Level.FINE))
{
_logger.logp(Level.FINE,"RecoveryManager","resync()",
"Before invoking rollback on the"+
"reconstructed coordinator :"+
"GTID is : "+
coord.superInfo.globalTID.toString());
}
coord.rollback(true);
} catch (Throwable exc) {
_logger.log(Level.WARNING,"jts.resync_failed",
new java.lang.Object [] {exc.toString(),"rollback"});
}
if (isRoot[0]) {
try {
coord.afterCompletion(Status.StatusRolledBack);
} catch (Throwable exc) {
_logger.log(Level.WARNING,"jts.resync_failed",
new java.lang.Object[]
{ exc.toString(), "after_completion"});
}
}
}
}
} catch (Throwable exc) {}
}
// Note that resyncComplete will be called by the
// last TopCoordinator to complete resync (in removeCoordinator)
// so we do not need to do it here.
}
/**
* Called to indicate that resync is complete.
* <p>
* Indicates that all in-doubt Coordinators recovered from the log have
* obtained global outcomes are corresponding transactions are complete.
* <p>
* The parameters indicate whether there were Coordinators
* requiring resync, and whether a keypoint is required.
*
* @param resynced Indicates whether any resync was done.
* @param keypointRequired Indicates whether the log needs keypointing.
*
* @return
*
* @exception LogicErrorException An internal logic error occurred.
*
* @see
*/
static void resyncComplete(boolean resynced, boolean keypointRequired) throws LogicErrorException {
// Inform JTSXA that resync is complete, and trace the fact
// that resync has completed.
// COMMENT(Ram J) not needed anymore
//JTSXA.resyncComplete();
// Perform a keypoint of the log if required.
if (keypointRequired) {
CoordinatorLog.keypoint();
}
// Post the resync in progress event semaphore.
if (resyncInProgress != null) {
resyncInProgress.post();
resyncInProgress = null;
}
}
/**
* Returns a reference to the Coordinator object that corresponds to the
* local identifier passed as a parameter.
*
* @param localTID The local identifier for the transaction.
*
* @return The Coordinator object.
*
* @see
*/
static CoordinatorImpl getLocalCoordinator(Long localTID) {
return (CoordinatorImpl) coordsByLocalTID.get(localTID);
}
/**
* Determines whether the local transaction identifier represents a valid
* transaction.
*
* @param localTID The local transaction identifier to check.
*
* @return Indicates the local transaction identifier is valid.
*
* @see
*/
static boolean validLocalTID(Long localTID) {
return coordsByLocalTID.containsKey(localTID);
}
/**
* Informs the RecoveryManager that the transaction service is being shut
* down.
*
* For immediate shutdown,
*
* For quiesce,
*
* @param immediate Indicates whether to stop immediately.
*
* @return
*
* @see
*/
static void shutdown(boolean immediate) {
/**
if (immediate) {
// If immediate, stop the resync thread if any.
if (resyncThread != null) {
resyncThread.stop();
}
} else {
**/
// Otherwise ensure that resync has completed.
if (resyncInProgress != null) {
try {
resyncInProgress.waitEvent();
if (resyncThread != null) {
resyncThread.join();
}
} catch (InterruptedException exc) {}
}
/**
}
**/
// COMMENT(Ram J) not needed anymore.
//JTSXA.shutdown(immediate);
// If not immediate shutdown, keypoint and close the log.
// Only do this if the process is recoverable!
if (!immediate && Configuration.isRecoverable()) {
CoordinatorLog.keypoint();
CoordinatorLog.finalizeAll();
}
//$Continue with shutdown/quiesce.
}
/**
* Reduce the set of XAResource objects into a unique set such that there
* is at most one XAResource object per RM.
*/
private static Enumeration getUniqueRMSet(Enumeration xaResourceList){
Vector uniqueRMList = new Vector();
while (xaResourceList.hasMoreElements()) {
XAResource xaRes = (XAResource) xaResourceList.nextElement();
int size = uniqueRMList.size();
boolean match = false;
for (int i = 0; i < size; i++) { // compare and eliminate duplicates
XAResource uniqueXaRes = (XAResource) uniqueRMList.elementAt(i);
try {
if (xaRes.isSameRM(uniqueXaRes)) {
match = true;
break;
}
} catch (XAException xe) {}
}
if (!match) {
uniqueRMList.add(xaRes);
}
}
return uniqueRMList.elements();
}
/**
* Recovers the in doubt transactions from the provided list of
* XAResource objects. This method is never called by the recovery
* thread, and its the application threads which wants to pass in
* the XA resources that call this.
*
* @param xaResources enumerated list of XA Resources to be recovered
*
*/
public static void recoverXAResources(Enumeration xaResources) {
/* This method has been newly added - Ram Jeyaraman */
String manualRecovery = Configuration.getPropertyValue(Configuration.MANUAL_RECOVERY);
// if ManualRecovery property is not set, do not attempt XA recovery.
if (manualRecovery == null ||
!(manualRecovery.equalsIgnoreCase("true"/*#Frozen*/))) {
return;
}
synchronized (lockObject) {
if (uniqueRMSetReady.isPosted() == false) {
RecoveryManager.uniqueRMSet = getUniqueRMSet(xaResources);
uniqueRMSetReady.post();
waitForResync();
return;
} else {
RecoveryManager.waitForResync();
RecoveryManager.uniqueRMSet = getUniqueRMSet(xaResources);
// the following call is meant to induce recovery. But
// currently it will not work as intended, if it is called
// during regular TP processing. Currently, this call deals
// only with XA recovery. There needs to be some support
// from the coordinator to be able to support recovery
// during TP processing.
proceedWithXARecovery();
}
}
}
/**
* This method returns InDoubt Xids for a given XAResource
*/
static Xid[] getInDoubtXids(XAResource xaResource) {
if(_logger.isLoggable(Level.FINE))
{
_logger.logp(Level.FINE,"RecoveryManager", "getInDoubtXids()",
"Before receiving inDoubtXids from xaresource = " +
xaResource);
}
Xid[] inDoubtXids = null;
ArrayList<Xid> inDoubtXidList = null;
int flags;
String recoveryScanFlags = System.getProperty("RECOVERSCANFLAGS");
if (recoveryScanFlags != null && recoveryScanFlags.equals("TMNOFLAGS"))
flags = XAResource.TMSTARTRSCAN;
else
flags = XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN;
boolean continueLoop = true;
while (continueLoop) {
try {
inDoubtXids = xaResource.recover(flags);
if (inDoubtXids == null || inDoubtXids.length == 0)
break;
if (flags == XAResource.TMSTARTRSCAN || flags == XAResource.TMNOFLAGS) {
flags = XAResource.TMNOFLAGS;
if (inDoubtXidList == null) {
inDoubtXidList = new ArrayList<Xid>();
}
for (int i = 0; i < inDoubtXids.length; i++)
inDoubtXidList.add(inDoubtXids[i]);
}
else {
break;
}
} catch (XAException e) {
_logger.log(Level.WARNING,"jts.xaexception_in_recovery", e.errorCode);
_logger.log(Level.WARNING, com.sun.jts.trace.TraceUtil.getXAExceptionInfo(e, _logger), e);
break;
}
}
if (inDoubtXidList != null) {
inDoubtXids = inDoubtXidList.toArray(new Xid[]{});
}
if (_logger.isLoggable(Level.FINE) && (inDoubtXids != null)) {
String xidList = LogFormatter.convertXidArrayToString(inDoubtXids);
_logger.logp(Level.FINE,"RecoveryManager",
"getInDoubtXid()",
"InDoubtXids returned from xaresource = "+
xaResource + "are: " +xidList);
}
return inDoubtXids;
}
/**
* This method is used to recontruct and register the Resource objects
* corresponding to in-doubt transactions in the RMs. It is assumed
* that the XAResource list has already been provided to the
* Recovery Manager. This method can be called by Recovery Thread as
* well as any other thread driving recovery of XA Resources.
*/
private static void proceedWithXARecovery() {
/* This method has been newly added - Ram Jeyaraman */
Enumeration xaResources = RecoveryManager.uniqueRMSet;
/**
if (xaResources == null) {
// TODO - check that automatic recovery works in a clustered instance
return;
}
**/
String manualRecovery = Configuration.getPropertyValue(Configuration.MANUAL_RECOVERY);
// if ManualRecovery property is not set, do not attempt XA recovery.
if (manualRecovery == null ||
!(manualRecovery.equalsIgnoreCase("true"/*#Frozen*/))) {
return;
}
if (Thread.currentThread().getName().equals("JTS Resync Thread"/*#Frozen*/)) {
if (uniqueRMSetReady != null) {
try {
uniqueRMSetReady.waitEvent();
txRecoveryFence.raiseFence();
xaResources = RecoveryManager.uniqueRMSet;
} catch (InterruptedException exc) {
_logger.log(Level.SEVERE,"jts.wait_for_resync_complete_interrupted");
String msg = LogFormatter.getLocalizedMessage(_logger,
"jts.wait_for_resync_complete_interrupted");
throw new org.omg.CORBA.INTERNAL(msg);
}
}
}
// sanity check
if (xaResources == null) {
return;
}
Vector otsResources = new Vector();
// Map uniqueXids = new Hashtable();
Set uniqueXids = new HashSet();
while (xaResources.hasMoreElements()) {
XAResource xaResource = (XAResource) xaResources.nextElement();
// Get the list of XIDs which represent in-doubt transactions
// for the database.
Xid[] inDoubtXids = getInDoubtXids(xaResource);
// uniqueXids.clear();
if (inDoubtXids == null || inDoubtXids.length == 0) {
continue; // No in-doubt xids for this resource.
}
for (int i = 0; i < inDoubtXids.length; i++) {
// check to see if the xid belongs to this server.
String branchQualifier = new String(inDoubtXids[i].getBranchQualifier());
String serverName = Configuration.getServerName();
if (branchQualifier.startsWith(serverName)) {
// check if the xid is a duplicate. i.e., Xids
// which have same globalId and branchId are
// considered duplicates. Note that the
// branchId format is (serverId, rmId). This is
// to make sure that at most one OTSResource object
// is registered with the coordinator per transaction
// per RM.
if (!uniqueXids.contains(inDoubtXids[i])) { // unique xid
if(_logger.isLoggable(Level.FINE))
{
_logger.logp(Level.FINE,"RecoveryManager",
"proceedWithXARecovery",
" This xid is UNIQUE " +
inDoubtXids[i]);
}
uniqueXids.add(inDoubtXids[i]);// add to uniqueList
// Create an OTSResource for the in-doubt
// transaction and add it to the list. Each
// OTSResource represents a RM per transaction.
otsResources.addElement(
new OTSResourceImpl(inDoubtXids[i], xaResource, null).getCORBAObjReference());
} else {
if(_logger.isLoggable(Level.FINE))
{
_logger.logp(Level.FINE,"RecoveryManager",
"proceedWithXARecovery",
" This xid is NOTUNIQUE " +
inDoubtXids[i]);
}
}
} else {
if(_logger.isLoggable(Level.FINE))
{
_logger.logp(Level.FINE,"RecoveryManager",
"proceedWithXARecovery",
" This xid doesn't belong to me " +
inDoubtXids[i]);
}
}
}
}
// For each OTSResource, determine whether the transaction is known,