forked from eldersantos/community
/
XaLogicalLog.java
1985 lines (1826 loc) · 69.3 KB
/
XaLogicalLog.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) 2002-2011 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.transaction.xaframework;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.transaction.xa.XAException;
import javax.transaction.xa.Xid;
import org.neo4j.helpers.Exceptions;
import org.neo4j.helpers.Pair;
import org.neo4j.kernel.impl.cache.LruCache;
import org.neo4j.kernel.impl.nioneo.store.FileSystemAbstraction;
import org.neo4j.kernel.impl.transaction.xaframework.LogEntry.Commit;
import org.neo4j.kernel.impl.transaction.xaframework.LogEntry.Start;
import org.neo4j.kernel.impl.util.ArrayMap;
import org.neo4j.kernel.impl.util.BufferedFileChannel;
import org.neo4j.kernel.impl.util.FileUtils;
import org.neo4j.kernel.impl.util.StringLogger;
/**
* <CODE>XaLogicalLog</CODE> is a transaction and logical log combined. In
* this log information about the transaction (such as started, prepared and
* committed) will be written. All commands participating in the transaction
* will also be written to the log.
* <p>
* Normally you don't have to do anything with this log except open it after it
* has been instanciated (see {@link XaContainer}). The only method that may be
* of use when implementing a XA compatible resource is the
* {@link #getCurrentTxIdentifier}. Leave everything else be unless you know
* what you're doing.
* <p>
* When the log is opened it will be scaned for uncompleted transactions and
* those transactions will be re-created. When scan of log is complete all
* transactions that hasn't entered prepared state will be marked as done
* (implies rolledback) and dropped. All transactions that have been prepared
* will be held in memory until the transaction manager tells them to commit.
* Transaction that already started commit but didn't get flagged as done will
* be re-committed.
*/
public class XaLogicalLog
{
private final Logger log;
private static final char CLEAN = 'C';
private static final char LOG1 = '1';
private static final char LOG2 = '2';
private FileChannel fileChannel = null;
private final ByteBuffer sharedBuffer;
private LogBuffer writeBuffer = null;
private long previousLogLastCommittedTx = -1;
private long logVersion = 0;
private final ArrayMap<Integer,LogEntry.Start> xidIdentMap =
new ArrayMap<Integer,LogEntry.Start>( 4, false, true );
private final Map<Integer,XaTransaction> recoveredTxMap =
new HashMap<Integer,XaTransaction>();
private int nextIdentifier = 1;
private boolean scanIsComplete = false;
private boolean nonCleanShutdown = false;
private String fileName = null;
private final XaResourceManager xaRm;
private final XaCommandFactory cf;
private final XaTransactionFactory xaTf;
private char currentLog = CLEAN;
private boolean keepLogs = false;
private boolean autoRotate = true;
private long rotateAtSize = 25*1024*1024; // 25MB
private final String storeDir;
private final LogBufferFactory logBufferFactory;
private boolean doingRecovery;
private long lastRecoveredTx = -1;
private long recoveredTxCount;
private final StringLogger msgLog;
private final LruCache<Long, TxPosition> txStartPositionCache =
new LruCache<Long, TxPosition>( "Tx start position cache", 10000, null );
private final LruCache<Long /*log version*/, Long /*last committed tx*/> logHeaderCache =
new LruCache<Long, Long>( "Log header cache", 1000, null );
private final FileSystemAbstraction fileSystem;
XaLogicalLog( String fileName, XaResourceManager xaRm, XaCommandFactory cf,
XaTransactionFactory xaTf, Map<Object, Object> config )
{
this.fileName = fileName;
this.xaRm = xaRm;
this.cf = cf;
this.xaTf = xaTf;
this.logBufferFactory = (LogBufferFactory) config.get( LogBufferFactory.class );
this.fileSystem = (FileSystemAbstraction) config.get( FileSystemAbstraction.class );
log = Logger.getLogger( this.getClass().getName() + File.separator + fileName );
sharedBuffer = ByteBuffer.allocateDirect( 9 + Xid.MAXGTRIDSIZE
+ Xid.MAXBQUALSIZE * 10 );
storeDir = (String) config.get( "store_dir" );
msgLog = (StringLogger) config.get( StringLogger.class );
// We should turn keep-logs on if there are previous logs around,
// this so that e.g. temporary shell sessions or operations don't create
// holes in the log history, because it's just annoying.
keepLogs = hasPreviousLogs();
}
synchronized void open() throws IOException
{
String activeFileName = fileName + ".active";
if ( !fileSystem.fileExists( activeFileName ) )
{
if ( fileSystem.fileExists( fileName ) )
{
// old < b8 xaframework with no log rotation and we need to
// do recovery on it
open( fileName );
}
else
{
open( getLog1FileName() );
setActiveLog( LOG1 );
}
}
else
{
FileChannel fc = fileSystem.open( activeFileName, "rw" );
byte bytes[] = new byte[256];
ByteBuffer buf = ByteBuffer.wrap( bytes );
int read = fc.read( buf );
fc.close();
if ( read != 4 )
{
throw new IllegalStateException( "Read " + read +
" bytes from " + activeFileName + " but expected 4" );
}
buf.flip();
char c = buf.asCharBuffer().get();
if ( c == CLEAN )
{
// clean
String newLog = getLog1FileName();
renameIfExists( newLog );
renameIfExists( getLog2FileName() );
open( newLog );
setActiveLog( LOG1 );
}
else if ( c == LOG1 )
{
String newLog = getLog1FileName();
if ( !fileSystem.fileExists( newLog ) )
{
throw new IllegalStateException(
"Active marked as 1 but no " + newLog + " exist" );
}
if ( fileSystem.fileExists( getLog2FileName() ) )
{
fixDualLogFiles( getLog1FileName(), getLog2FileName() );
}
currentLog = LOG1;
open( newLog );
}
else if ( c == LOG2 )
{
String newLog = getLog2FileName();
if ( !fileSystem.fileExists( newLog ) )
{
throw new IllegalStateException(
"Active marked as 2 but no " + newLog + " exist" );
}
if ( fileSystem.fileExists( getLog1FileName() ) )
{
fixDualLogFiles( getLog2FileName(), getLog1FileName() );
}
currentLog = LOG2;
open( newLog );
}
else
{
throw new IllegalStateException( "Unknown active log: " + c );
}
}
instantiateCorrectWriteBuffer();
}
private void renameIfExists( String fileName ) throws IOException
{
if ( fileSystem.fileExists( fileName ) )
{
renameLogFileToRightVersion( fileName, fileSystem.getFileSize( fileName ) );
}
}
private void instantiateCorrectWriteBuffer() throws IOException
{
writeBuffer = instantiateCorrectWriteBuffer( fileChannel );
}
private LogBuffer instantiateCorrectWriteBuffer( FileChannel channel ) throws IOException
{
return logBufferFactory.create( channel );
}
private void open( String fileToOpen ) throws IOException
{
fileChannel = fileSystem.open( fileToOpen, "rw" );
if ( fileChannel.size() != 0 )
{
nonCleanShutdown = true;
doingRecovery = true;
try
{
doInternalRecovery( fileToOpen );
}
finally
{
doingRecovery = false;
}
}
else
{
logVersion = xaTf.getCurrentVersion();
long lastTxId = xaTf.getLastCommittedTx();
LogIoUtils.writeLogHeader( sharedBuffer, logVersion, lastTxId );
previousLogLastCommittedTx = lastTxId;
logHeaderCache.put( logVersion, previousLogLastCommittedTx );
fileChannel.write( sharedBuffer );
scanIsComplete = true;
msgLog.logMessage( "Opened [" + fileToOpen + "] clean empty log, version=" + logVersion + ", lastTxId=" + lastTxId, true );
}
}
public boolean scanIsComplete()
{
return scanIsComplete;
}
private int getNextIdentifier()
{
nextIdentifier++;
if ( nextIdentifier < 0 )
{
nextIdentifier = 1;
}
return nextIdentifier;
}
// returns identifier for transaction
// [TX_START][xid[gid.length,bid.lengh,gid,bid]][identifier][format id]
public synchronized int start( Xid xid, int masterId, int myId ) throws XAException
{
int xidIdent = getNextIdentifier();
try
{
long position = writeBuffer.getFileChannelPosition();
long timeWritten = System.currentTimeMillis();
LogEntry.Start start = new LogEntry.Start( xid, xidIdent, masterId, myId, position, timeWritten );
LogIoUtils.writeStart( writeBuffer, xidIdent, xid, masterId, myId, timeWritten );
xidIdentMap.put( xidIdent, start );
}
catch ( IOException e )
{
throw Exceptions.withCause( new XAException( "Logical log couldn't start transaction: " + e ), e );
}
return xidIdent;
}
// [TX_PREPARE][identifier]
public synchronized void prepare( int identifier ) throws XAException
{
LogEntry.Start startEntry = xidIdentMap.get( identifier );
assert startEntry != null;
try
{
LogIoUtils.writePrepare( writeBuffer, identifier, System.currentTimeMillis() );
writeBuffer.writeOut();
}
catch ( IOException e )
{
throw Exceptions.withCause( new XAException( "Logical log unable to mark prepare [" + identifier + "] " ),
e );
}
}
// [TX_1P_COMMIT][identifier]
public synchronized void commitOnePhase( int identifier, long txId )
throws XAException
{
LogEntry.Start startEntry = xidIdentMap.get( identifier );
assert startEntry != null;
assert txId != -1;
try
{
LogIoUtils.writeCommit( false, writeBuffer, identifier, txId, System.currentTimeMillis() );
writeBuffer.force();
cacheTxStartPosition( txId, startEntry.getMasterId(), startEntry );
}
catch ( IOException e )
{
throw Exceptions.withCause(
new XAException( "Logical log unable to mark 1P-commit [" + identifier + "] " ), e );
}
}
private synchronized void cacheTxStartPosition( long txId, int masterId,
LogEntry.Start startEntry )
{
cacheTxStartPosition( txId, masterId, startEntry, logVersion );
}
private synchronized TxPosition cacheTxStartPosition( long txId, int masterId,
LogEntry.Start startEntry, long logVersion )
{
if ( startEntry.getStartPosition() == -1 )
{
throw new RuntimeException( "StartEntry.position is " + startEntry.getStartPosition() );
}
TxPosition result = new TxPosition( logVersion, masterId, startEntry.getIdentifier(),
startEntry.getStartPosition(), startEntry.getTimeWritten() );
txStartPositionCache.put( txId, result );
return result;
}
// [DONE][identifier]
public synchronized void done( int identifier ) throws XAException
{
assert xidIdentMap.get( identifier ) != null;
try
{
LogIoUtils.writeDone( writeBuffer, identifier );
xidIdentMap.remove( identifier );
}
catch ( IOException e )
{
throw Exceptions.withCause( new XAException( "Logical log unable to mark as done [" + identifier + "] " ),
e );
}
}
// [DONE][identifier] called from XaResourceManager during internal recovery
synchronized void doneInternal( int identifier ) throws IOException
{
if ( writeBuffer != null )
{ // For 2PC
LogIoUtils.writeDone( writeBuffer, identifier );
}
else
{ // For 1PC
sharedBuffer.clear();
LogIoUtils.writeDone( sharedBuffer, identifier );
sharedBuffer.flip();
fileChannel.write( sharedBuffer );
}
xidIdentMap.remove( identifier );
// force to make sure done record is there if 2PC tx and global log
// marks tx as committed
// fileChannel.force( false );
}
// [TX_2P_COMMIT][identifier]
public synchronized void commitTwoPhase( int identifier, long txId )
throws XAException
{
LogEntry.Start startEntry = xidIdentMap.get( identifier );
assert startEntry != null;
assert txId != -1;
try
{
LogIoUtils.writeCommit( true, writeBuffer, identifier, txId, System.currentTimeMillis() );
writeBuffer.force();
cacheTxStartPosition( txId, startEntry.getMasterId(), startEntry );
}
catch ( IOException e )
{
throw Exceptions.withCause( new XAException( "Logical log unable to mark 2PC [" + identifier + "] " ), e );
}
}
// [COMMAND][identifier][COMMAND_DATA]
public synchronized void writeCommand( XaCommand command, int identifier )
throws IOException
{
checkLogRotation();
assert xidIdentMap.get( identifier ) != null;
LogIoUtils.writeCommand( writeBuffer, identifier, command );
}
private void applyEntry( LogEntry entry ) throws IOException
{
if ( entry instanceof LogEntry.Start )
{
applyStartEntry( (LogEntry.Start) entry );
}
else if ( entry instanceof LogEntry.Prepare )
{
applyPrepareEntry( (LogEntry.Prepare ) entry );
}
else if ( entry instanceof LogEntry.Command )
{
applyCommandEntry( (LogEntry.Command ) entry );
}
else if ( entry instanceof LogEntry.OnePhaseCommit )
{
applyOnePhaseCommitEntry( (LogEntry.OnePhaseCommit ) entry );
}
else if ( entry instanceof LogEntry.TwoPhaseCommit )
{
applyTwoPhaseCommitEntry( (LogEntry.TwoPhaseCommit ) entry );
}
else if ( entry instanceof LogEntry.Done )
{
applyDoneEntry( (LogEntry.Done ) entry );
}
else
{
throw new RuntimeException( "Unrecognized log entry " + entry );
}
}
private void applyStartEntry( LogEntry.Start entry) throws IOException
{
int identifier = entry.getIdentifier();
if ( identifier >= nextIdentifier )
{
nextIdentifier = (identifier + 1);
}
// re-create the transaction
Xid xid = entry.getXid();
xidIdentMap.put( identifier, entry );
XaTransaction xaTx = xaTf.create( identifier );
xaTx.setRecovered();
recoveredTxMap.put( identifier, xaTx );
xaRm.injectStart( xid, xaTx );
// force to make sure done record is there if 2PC tx and global log
// marks tx as committed
// fileChannel.force( false );
}
private void applyPrepareEntry( LogEntry.Prepare prepareEntry ) throws IOException
{
// get the tx identifier
int identifier = prepareEntry.getIdentifier();
LogEntry.Start entry = xidIdentMap.get( identifier );
if ( entry == null )
{
throw new IOException( "Unknown xid for identifier " + identifier );
}
Xid xid = entry.getXid();
if ( xaRm.injectPrepare( xid ) )
{
// read only we can remove
xidIdentMap.remove( identifier );
recoveredTxMap.remove( identifier );
}
}
private void applyOnePhaseCommitEntry( LogEntry.OnePhaseCommit commit )
throws IOException
{
int identifier = commit.getIdentifier();
long txId = commit.getTxId();
LogEntry.Start startEntry = xidIdentMap.get( identifier );
if ( startEntry == null )
{
throw new IOException( "Unknown xid for identifier " + identifier );
}
Xid xid = startEntry.getXid();
try
{
XaTransaction xaTx = xaRm.getXaTransaction( xid );
xaTx.setCommitTxId( txId );
xaRm.injectOnePhaseCommit( xid );
registerRecoveredTransaction( txId );
}
catch ( XAException e )
{
throw new IOException( e );
}
}
private void registerRecoveredTransaction( long txId )
{
if ( doingRecovery )
{
lastRecoveredTx = txId;
recoveredTxCount++;
}
}
private void logRecoveryMessage( String string )
{
if ( doingRecovery )
{
msgLog.logMessage( string, true );
}
}
private void applyDoneEntry( LogEntry.Done done ) throws IOException
{
// get the tx identifier
int identifier = done.getIdentifier();
LogEntry.Start entry = xidIdentMap.get( identifier );
if ( entry == null )
{
throw new IOException( "Unknown xid for identifier " + identifier );
}
Xid xid = entry.getXid();
xaRm.pruneXid( xid );
xidIdentMap.remove( identifier );
recoveredTxMap.remove( identifier );
}
private void applyTwoPhaseCommitEntry( LogEntry.TwoPhaseCommit commit ) throws IOException
{
int identifier = commit.getIdentifier();
long txId = commit.getTxId();
LogEntry.Start startEntry = xidIdentMap.get( identifier );
if ( startEntry == null )
{
throw new IOException( "Unknown xid for identifier " + identifier );
}
Xid xid = startEntry.getXid();
if ( xid == null )
{
throw new IOException( "Xid null for identifier " + identifier );
}
try
{
XaTransaction xaTx = xaRm.getXaTransaction( xid );
xaTx.setCommitTxId( txId );
xaRm.injectTwoPhaseCommit( xid );
registerRecoveredTransaction( txId );
}
catch ( XAException e )
{
throw new IOException( e );
}
}
private void applyCommandEntry( LogEntry.Command entry ) throws IOException
{
int identifier = entry.getIdentifier();
XaCommand command = entry.getXaCommand();
if ( command == null )
{
throw new IOException( "Null command for identifier " + identifier );
}
command.setRecovered();
XaTransaction xaTx = recoveredTxMap.get( identifier );
xaTx.injectCommand( command );
}
private void checkLogRotation() throws IOException
{
if ( autoRotate &&
writeBuffer.getFileChannelPosition() >= rotateAtSize )
{
long currentPos = writeBuffer.getFileChannelPosition();
long firstStartEntry = getFirstStartEntry( currentPos );
// only rotate if no huge tx is running
if ( ( currentPos - firstStartEntry ) < rotateAtSize / 2 )
{
rotate();
}
}
}
private void fixDualLogFiles( String activeLog, String oldLog ) throws IOException
{
FileChannel activeLogChannel = fileSystem.open( activeLog, "r" );
long[] activeLogHeader = LogIoUtils.readLogHeader( ByteBuffer.allocate( 16 ), activeLogChannel, false );
activeLogChannel.close();
FileChannel oldLogChannel = fileSystem.open( oldLog, "r" );
long[] oldLogHeader = LogIoUtils.readLogHeader( ByteBuffer.allocate( 16 ), oldLogChannel, false );
oldLogChannel.close();
if ( oldLogHeader == null )
{
if ( !fileSystem.deleteFile( oldLog ) )
{
throw new IOException( "Unable to delete " + oldLog );
}
}
else if ( activeLogHeader == null || activeLogHeader[0] > oldLogHeader[0] )
{
// we crashed in rotate after setActive but did not move the old log to the right name
// (and we do not know if keepLogs is true or not so play it safe by keeping it)
String newName = getFileName( oldLogHeader[0] );
if ( !fileSystem.renameFile( oldLog, newName ) )
{
throw new IOException( "Unable to rename " + oldLog + " to " + newName );
}
}
else
{
assert activeLogHeader[0] < oldLogHeader[0];
// we crashed in rotate before setActive, do the rotate work again and delete old
if ( !fileSystem.deleteFile( oldLog ) )
{
throw new IOException( "Unable to delete " + oldLog );
}
}
}
private void renameLogFileToRightVersion( String logFileName, long endPosition ) throws IOException
{
if ( !fileSystem.fileExists( logFileName ) )
{
throw new IOException( "Logical log[" + logFileName + "] not found" );
}
FileChannel channel = fileSystem.open( logFileName, "rw" );
long[] header = LogIoUtils.readLogHeader( ByteBuffer.allocate( 16 ), channel, false );
try
{
FileUtils.truncateFile( channel, endPosition );
}
catch ( IOException e )
{
log.log( Level.WARNING, "Failed to truncate log at correct size", e );
}
channel.close();
String newName;
if ( header == null )
{
// header was never written
newName = getFileName( -1 ) + "_empty_header_log_" + System.currentTimeMillis();
}
else
{
newName = getFileName( header[0] );
}
if ( !fileSystem.renameFile( logFileName, newName ) )
{
throw new IOException( "Failed to rename log to: " + newName );
}
}
private void deleteLogFile( String logFileName ) throws IOException
{
if ( !fileSystem.fileExists( logFileName ) )
{
throw new IOException( "Logical log[" + logFileName +
"] not found" );
}
if ( !fileSystem.deleteFile( logFileName ) )
{
log.warning( "Unable to delete clean logical log[" + logFileName + "]" );
}
}
private void releaseCurrentLogFile() throws IOException
{
if ( writeBuffer != null )
{
writeBuffer.force();
}
fileChannel.close();
fileChannel = null;
}
public synchronized void close() throws IOException
{
if ( fileChannel == null || !fileChannel.isOpen() )
{
log.fine( "Logical log: " + fileName + " already closed" );
return;
}
long endPosition = writeBuffer.getFileChannelPosition();
if ( xidIdentMap.size() > 0 )
{
log.info( "Close invoked with " + xidIdentMap.size() +
" running transaction(s). " );
writeBuffer.force();
fileChannel.close();
log.info( "Dirty log: " + fileName + "." + currentLog +
" now closed. Recovery will be started automatically next " +
"time it is opened." );
return;
}
releaseCurrentLogFile();
char logWas = currentLog;
if ( currentLog != CLEAN ) // again special case, see above
{
setActiveLog( CLEAN );
}
if ( !keepLogs )
{
if ( logWas == CLEAN )
{
// special case going from old xa version with no log rotation
// and we started with a recovery
deleteLogFile( fileName );
}
else
{
deleteLogFile( fileName + "." + logWas );
}
}
else
{
renameLogFileToRightVersion( fileName + "." + logWas, endPosition );
xaTf.getAndSetNewVersion();
}
msgLog.logMessage( "Closed log " + fileName, true );
}
private long[] readAndAssertLogHeader( ByteBuffer localBuffer,
ReadableByteChannel channel, long expectedVersion ) throws IOException
{
long[] header = LogIoUtils.readLogHeader( localBuffer, channel, true );
if ( header[0] != expectedVersion )
{
throw new IOException( "Wrong version in log. Expected " + expectedVersion +
", but got " + header[0] );
}
return header;
}
StringLogger getStringLogger()
{
return msgLog;
}
private void doInternalRecovery( String logFileName ) throws IOException
{
log.info( "Non clean shutdown detected on log [" + logFileName +
"]. Recovery started ..." );
msgLog.logMessage( "Non clean shutdown detected on log [" + logFileName +
"]. Recovery started ...", true );
// get log creation time
long[] header = readLogHeader( fileChannel, "Tried to do recovery on log with illegal format version" );
if ( header == null )
{
log.info( "Unable to read header information, "
+ "no records in logical log." );
msgLog.logMessage( "No log version found for " + logFileName, true );
fileChannel.close();
boolean success = fileSystem.renameFile( logFileName,
logFileName + "_unknown_timestamp_" + System.currentTimeMillis() + ".log" );
assert success;
fileChannel.close();
fileChannel = fileSystem.open( logFileName, "rw" );
return;
}
logVersion = header[0];
long lastCommittedTx = header[1];
previousLogLastCommittedTx = lastCommittedTx;
logHeaderCache.put( logVersion, previousLogLastCommittedTx );
log.fine( "Logical log version: " + logVersion + " with committed tx[" +
lastCommittedTx + "]" );
msgLog.logMessage( "[" + logFileName + "] logVersion=" + logVersion +
" with committed tx=" + lastCommittedTx, true );
long logEntriesFound = 0;
long lastEntryPos = fileChannel.position();
fileChannel = new BufferedFileChannel( fileChannel );
LogEntry entry;
while ( (entry = readEntry()) != null )
{
applyEntry( entry );
logEntriesFound++;
lastEntryPos = fileChannel.position();
}
// make sure we overwrite any broken records
fileChannel = ((BufferedFileChannel)fileChannel).getSource();
fileChannel.position( lastEntryPos );
msgLog.logMessage( "[" + logFileName + "] entries found=" + logEntriesFound +
" lastEntryPos=" + lastEntryPos, true );
// zero out the slow way since windows don't support truncate very well
sharedBuffer.clear();
while ( sharedBuffer.hasRemaining() )
{
sharedBuffer.put( (byte)0 );
}
sharedBuffer.flip();
long endPosition = fileChannel.size();
do
{
long bytesLeft = fileChannel.size() - fileChannel.position();
if ( bytesLeft < sharedBuffer.capacity() )
{
sharedBuffer.limit( (int) bytesLeft );
}
fileChannel.write( sharedBuffer );
sharedBuffer.flip();
} while ( fileChannel.position() < endPosition );
fileChannel.position( lastEntryPos );
scanIsComplete = true;
String recoveryCompletedMessage = "Internal recovery completed, scanned " + logEntriesFound
+ " log entries. Recovered " + recoveredTxCount
+ " transactions. Last tx recovered: " + lastRecoveredTx;
log.fine( recoveryCompletedMessage );
msgLog.logMessage( recoveryCompletedMessage );
xaRm.checkXids();
if ( xidIdentMap.size() == 0 )
{
log.fine( "Recovery completed." );
msgLog.logMessage( "Recovery on log [" + logFileName + "] completed." );
}
else
{
log.fine( "[" + logFileName + "] Found " + xidIdentMap.size()
+ " prepared 2PC transactions." );
msgLog.logMessage( "Recovery on log [" + logFileName +
"] completed with " + xidIdentMap + " prepared transactions found." );
for ( LogEntry.Start startEntry : xidIdentMap.values() )
{
log.fine( "[" + logFileName + "] 2PC xid[" +
startEntry.getXid() + "]" );
}
}
recoveredTxMap.clear();
}
// for testing, do not use!
void reset()
{
xidIdentMap.clear();
recoveredTxMap.clear();
}
private LogEntry readEntry() throws IOException
{
long position = fileChannel.position();
LogEntry entry = LogIoUtils.readEntry( sharedBuffer, fileChannel, cf );
if ( entry instanceof LogEntry.Start )
{
((LogEntry.Start) entry).setStartPosition( position );
}
return entry;
}
private final ArrayMap<Thread,Integer> txIdentMap =
new ArrayMap<Thread,Integer>( 5, true, true );
void registerTxIdentifier( int identifier )
{
txIdentMap.put( Thread.currentThread(), identifier );
}
void unregisterTxIdentifier()
{
txIdentMap.remove( Thread.currentThread() );
}
/**
* If the current thread is committing a transaction the identifier of that
* {@link XaTransaction} can be obtained invoking this method.
*
* @return the identifier of the transaction committing or <CODE>-1</CODE>
* if current thread isn't committing any transaction
*/
public int getCurrentTxIdentifier()
{
Integer intValue = txIdentMap.get( Thread.currentThread() );
if ( intValue != null )
{
return intValue;
}
return -1;
}
public ReadableByteChannel getLogicalLog( long version ) throws IOException
{
return getLogicalLog( version, 0 );
}
public ReadableByteChannel getLogicalLog( long version, long position ) throws IOException
{
String name = getFileName( version );
if ( !fileSystem.fileExists( name ) )
{
throw new IOException( "No such log version:" + version );
}
FileChannel channel = fileSystem.open( name, "r" );
channel.position( position );
return new BufferedFileChannel( channel );
}
private void extractPreparedTransactionFromLog( int identifier,
FileChannel logChannel, LogBuffer targetBuffer ) throws IOException
{
LogEntry.Start startEntry = xidIdentMap.get( identifier );
logChannel.position( startEntry.getStartPosition() );
LogEntry entry;
boolean found = false;
while ( (entry = LogIoUtils.readEntry( sharedBuffer, logChannel, cf )) != null )
{
// TODO For now just skip Prepare entries
if ( entry.getIdentifier() != identifier )
{
continue;
}
if ( entry instanceof LogEntry.Prepare )
{
break;
}
if ( entry instanceof LogEntry.Start || entry instanceof LogEntry.Command )
{
LogIoUtils.writeLogEntry( entry, targetBuffer );
found = true;
}
else
{
throw new RuntimeException( "Expected start or command entry but found: " + entry );
}
}
if ( !found )
{
throw new IOException( "Transaction for internal identifier[" + identifier +
"] not found in current log" );
}
}
// private void assertLogCanContainTx( long txId, long prevTxId ) throws IOException
// {
// if ( prevTxId >= txId )
// {
// throw new IOException( "Log says " + txId +
// " can not exist in this log (prev tx id=" + prevTxId + ")" );
// }
// }
public synchronized ReadableByteChannel getPreparedTransaction( int identifier )
throws IOException
{
FileChannel logChannel = (FileChannel) getLogicalLogOrMyselfPrepared( logVersion, 0 );
InMemoryLogBuffer localBuffer = new InMemoryLogBuffer();
extractPreparedTransactionFromLog( identifier, logChannel, localBuffer );
logChannel.close();
return localBuffer;
}
public synchronized void getPreparedTransaction( int identifier, LogBuffer targetBuffer )
throws IOException
{
FileChannel logChannel = (FileChannel) getLogicalLogOrMyselfPrepared( logVersion, 0 );
extractPreparedTransactionFromLog( identifier, logChannel, targetBuffer );
logChannel.close();
}
public class LogExtractor
{
/**
* If tx range is smaller than this threshold ask the position cache for the
* start position furthest back. Otherwise jump to right log and scan.
*/
private static final int CACHE_FIND_THRESHOLD = 100;
private final ByteBuffer localBuffer =
ByteBuffer.allocate( 9 + Xid.MAXGTRIDSIZE + Xid.MAXBQUALSIZE * 10 );
private ReadableByteChannel source;
private final LogEntryCollector collector;
private long version;
private LogEntry.Commit lastCommitEntry;
private LogEntry.Commit previousCommitEntry;
private final long startTxId;
private long nextExpectedTxId;
private int counter;
public LogExtractor( long startTxId, long endTxIdHint ) throws IOException
{
this.startTxId = startTxId;
this.nextExpectedTxId = startTxId;
long diff = endTxIdHint-startTxId + 1/*since they are inclusive*/;