-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
CommonAbstractStore.java
1300 lines (1196 loc) · 43.9 KB
/
CommonAbstractStore.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-2017 "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.store;
import java.io.File;
import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.nio.file.OpenOption;
import java.nio.file.StandardOpenOption;
import java.util.Collection;
import org.neo4j.graphdb.config.Setting;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.helpers.collection.Visitor;
import org.neo4j.io.pagecache.PageCache;
import org.neo4j.io.pagecache.PageCursor;
import org.neo4j.io.pagecache.PagedFile;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.store.format.RecordFormat;
import org.neo4j.kernel.impl.store.id.IdGenerator;
import org.neo4j.kernel.impl.store.id.IdGeneratorFactory;
import org.neo4j.kernel.impl.store.id.IdType;
import org.neo4j.kernel.impl.store.id.validation.IdValidator;
import org.neo4j.kernel.impl.store.record.AbstractBaseRecord;
import org.neo4j.kernel.impl.store.record.Record;
import org.neo4j.kernel.impl.store.record.RecordLoad;
import org.neo4j.logging.Log;
import org.neo4j.logging.LogProvider;
import org.neo4j.logging.Logger;
import org.neo4j.string.UTF8;
import static java.nio.file.StandardOpenOption.DELETE_ON_CLOSE;
import static org.neo4j.helpers.ArrayUtil.contains;
import static org.neo4j.helpers.Exceptions.launderedException;
import static org.neo4j.io.pagecache.PageCacheOpenOptions.ANY_PAGE_SIZE;
import static org.neo4j.io.pagecache.PagedFile.PF_READ_AHEAD;
import static org.neo4j.io.pagecache.PagedFile.PF_SHARED_READ_LOCK;
import static org.neo4j.io.pagecache.PagedFile.PF_SHARED_WRITE_LOCK;
import static org.neo4j.kernel.impl.store.record.Record.NULL_REFERENCE;
import static org.neo4j.kernel.impl.store.record.RecordLoad.CHECK;
import static org.neo4j.kernel.impl.store.record.RecordLoad.NORMAL;
/**
* Contains common implementation of {@link RecordStore}.
*/
public abstract class CommonAbstractStore<RECORD extends AbstractBaseRecord,HEADER extends StoreHeader>
implements RecordStore<RECORD>, AutoCloseable
{
public static final String UNKNOWN_VERSION = "Unknown";
protected final Config configuration;
protected final PageCache pageCache;
protected final File storageFileName;
protected final IdType idType;
protected final IdGeneratorFactory idGeneratorFactory;
protected final Log log;
protected PagedFile storeFile;
protected final String storeVersion;
protected final RecordFormat<RECORD> recordFormat;
private IdGenerator idGenerator;
private boolean storeOk = true;
private Throwable causeOfStoreNotOk;
private final String typeDescriptor;
protected int recordSize;
private final StoreHeaderFormat<HEADER> storeHeaderFormat;
private HEADER storeHeader;
private final OpenOption[] openOptions;
/**
* Opens and validates the store contained in <CODE>fileName</CODE>
* loading any configuration defined in <CODE>config</CODE>. After
* validation the <CODE>initStorage</CODE> method is called.
* <p>
* If the store had a clean shutdown it will be marked as <CODE>ok</CODE>
* and the {@link #getStoreOk()} method will return true.
* If a problem was found when opening the store the {@link #makeStoreOk()}
* must be invoked.
* <p>
* throws IOException if the unable to open the storage or if the
* <CODE>initStorage</CODE> method fails
*
* @param idType The Id used to index into this store
*/
public CommonAbstractStore(
File fileName,
Config configuration,
IdType idType,
IdGeneratorFactory idGeneratorFactory,
PageCache pageCache,
LogProvider logProvider,
String typeDescriptor,
RecordFormat<RECORD> recordFormat,
StoreHeaderFormat<HEADER> storeHeaderFormat,
String storeVersion,
OpenOption... openOptions )
{
this.storageFileName = fileName;
this.configuration = configuration;
this.idGeneratorFactory = idGeneratorFactory;
this.pageCache = pageCache;
this.idType = idType;
this.typeDescriptor = typeDescriptor;
this.recordFormat = recordFormat;
this.storeHeaderFormat = storeHeaderFormat;
this.storeVersion = storeVersion;
this.openOptions = openOptions;
this.log = logProvider.getLog( getClass() );
}
void initialise( boolean createIfNotExists )
{
try
{
checkAndLoadStorage( createIfNotExists );
}
catch ( Exception e )
{
closeAndThrow( e );
}
}
private void closeAndThrow( Exception e )
{
if ( storeFile != null )
{
try
{
closeStoreFile();
}
catch ( IOException failureToClose )
{
// Not really a suppressed exception, but we still want to throw the real exception, e,
// but perhaps also throw this in there or convenience.
e.addSuppressed( failureToClose );
}
}
throw launderedException( e );
}
/**
* Returns the type and version that identifies this store.
*
* @return This store's implementation type and version identifier
*/
public String getTypeDescriptor()
{
return typeDescriptor;
}
/**
* This method is called by constructors. Checks the header record and loads the store.
* <p>
* Note: This method will map the file with the page cache. The store file must not
* be accessed directly until it has been unmapped - the store file must only be
* accessed through the page cache.
* @param createIfNotExists If true, creates and initialises the store file if it does not exist already. If false,
* this method will instead throw an exception in that situation.
*/
protected void checkAndLoadStorage( boolean createIfNotExists )
{
int pageSize = pageCache.pageSize();
int filePageSize;
try ( PagedFile pagedFile = pageCache.map( storageFileName, pageSize, ANY_PAGE_SIZE ) )
{
extractHeaderRecord( pagedFile );
filePageSize = pageCache.pageSize() - pageCache.pageSize() % getRecordSize();
}
catch ( NoSuchFileException | StoreNotFoundException e )
{
if ( createIfNotExists )
{
try
{
createStore( pageSize );
return;
}
catch ( IOException e1 )
{
e.addSuppressed( e1 );
}
}
if ( e instanceof StoreNotFoundException )
{
throw (StoreNotFoundException) e;
}
throw new StoreNotFoundException( "Store file not found: " + storageFileName, e );
}
catch ( IOException e )
{
throw new UnderlyingStorageException( "Unable to open store file: " + storageFileName, e );
}
loadStorage( filePageSize );
}
private void createStore( int pageSize ) throws IOException
{
try ( PagedFile file = pageCache.map( storageFileName, pageSize, StandardOpenOption.CREATE ) )
{
initialiseNewStoreFile( file );
}
checkAndLoadStorage( false );
}
private void loadStorage( int filePageSize )
{
try
{
storeFile = pageCache.map( getStorageFileName(), filePageSize, openOptions );
loadIdGenerator();
}
catch ( IOException e )
{
throw new UnderlyingStorageException( "Unable to open store file: " + storageFileName, e );
}
}
protected void initialiseNewStoreFile( PagedFile file ) throws IOException
{
if ( getNumberOfReservedLowIds() > 0 )
{
try ( PageCursor pageCursor = file.io( 0, PF_SHARED_WRITE_LOCK ) )
{
if ( pageCursor.next() )
{
pageCursor.setOffset( 0 );
createHeaderRecord( pageCursor );
if ( pageCursor.checkAndClearBoundsFlag() )
{
throw new UnderlyingStorageException(
"Out of page bounds when writing header; page size too small: " +
pageCache.pageSize() + " bytes.");
}
}
}
}
// Determine record size right after writing the header since some stores
// use it when initializing their stores to write some records.
recordSize = determineRecordSize();
File idFileName = new File( storageFileName.getPath() + ".id" );
idGeneratorFactory.create( idFileName, getNumberOfReservedLowIds(), false );
}
protected void createHeaderRecord( PageCursor cursor ) throws IOException
{
int offset = cursor.getOffset();
storeHeaderFormat.writeHeader( cursor );
cursor.setOffset( offset );
readHeaderAndInitializeRecordFormat( cursor );
}
private void extractHeaderRecord( PagedFile pagedFile ) throws IOException
{
if ( getNumberOfReservedLowIds() > 0 )
{
try ( PageCursor pageCursor = pagedFile.io( 0, PF_SHARED_READ_LOCK ) )
{
if ( pageCursor.next() )
{
do
{
pageCursor.setOffset( 0 );
readHeaderAndInitializeRecordFormat( pageCursor );
}
while ( pageCursor.shouldRetry() );
if ( pageCursor.checkAndClearBoundsFlag() )
{
throw new UnderlyingStorageException(
"Out of page bounds when reading header; page size too small: " +
pageCache.pageSize() + " bytes." );
}
}
else
{
throw new StoreNotFoundException( "Fail to read header record of store file: " +
storageFileName );
}
}
}
else
{
readHeaderAndInitializeRecordFormat( null );
}
recordSize = determineRecordSize();
}
protected long pageIdForRecord( long id )
{
return RecordPageLocationCalculator.pageIdForRecord( id, storeFile.pageSize(), recordSize );
}
protected int offsetForId( long id )
{
return RecordPageLocationCalculator.offsetForId( id, storeFile.pageSize(), recordSize );
}
@Override
public int getRecordsPerPage()
{
return storeFile.pageSize() / recordSize;
}
public byte[] getRawRecordData( long id ) throws IOException
{
byte[] data = new byte[recordSize];
long pageId = pageIdForRecord( id );
int offset = offsetForId( id );
try ( PageCursor cursor = storeFile.io( pageId, PagedFile.PF_SHARED_READ_LOCK ) )
{
if ( cursor.next() )
{
do
{
cursor.setOffset( offset );
cursor.getBytes( data );
}
while ( cursor.shouldRetry() );
checkForDecodingErrors( cursor, id, CHECK );
}
}
return data;
}
/**
* This method is called when opening the store to extract header data and determine things like
* record size of the specific record format for this store. Some formats rely on information
* in the store header, that's why it happens at this stage.
*
* @param cursor {@link PageCursor} initialized at the start of the store header where header information
* can be read if need be. This can be {@code null} if this store has no store header. The initialization
* of the record format still happens in here.
* @throws IOException if there were problems reading header information.
*/
private void readHeaderAndInitializeRecordFormat( PageCursor cursor ) throws IOException
{
storeHeader = storeHeaderFormat.readHeader( cursor );
}
private void loadIdGenerator()
{
try
{
if ( storeOk )
{
openIdGenerator();
}
// else we will rebuild the id generator after recovery, and we don't want to have the id generator
// picking up calls to freeId during recovery.
}
catch ( InvalidIdGeneratorException e )
{
setStoreNotOk( e );
}
finally
{
if ( !getStoreOk() )
{
log.debug( getStorageFileName() + " non clean shutdown detected" );
}
}
}
public boolean isInUse( long id )
{
long pageId = pageIdForRecord( id );
int offset = offsetForId( id );
try ( PageCursor cursor = storeFile.io( pageId, PF_SHARED_READ_LOCK ) )
{
boolean recordIsInUse = false;
if ( cursor.next() )
{
do
{
cursor.setOffset( offset );
recordIsInUse = isInUse( cursor );
}
while ( cursor.shouldRetry() );
checkForDecodingErrors( cursor, id, NORMAL );
}
return recordIsInUse;
}
catch ( IOException e )
{
throw new UnderlyingStorageException( e );
}
}
/**
* Should rebuild the id generator from scratch.
* <p>
* Note: This method may be called both while the store has the store file mapped in the
* page cache, and while the store file is not mapped. Implementers must therefore
* map their own temporary PagedFile for the store file, and do their file IO through that,
* if they need to access the data in the store file.
*/
final void rebuildIdGenerator()
{
int blockSize = getRecordSize();
if ( blockSize <= 0 )
{
throw new InvalidRecordException( "Illegal blockSize: " + blockSize );
}
log.info( "Rebuilding id generator for[" + getStorageFileName() + "] ..." );
closeIdGenerator();
createIdGenerator( getIdFileName() );
openIdGenerator();
long defraggedCount = 0;
boolean fastRebuild = isOnlyFastIdGeneratorRebuildEnabled( configuration );
try
{
long foundHighId = scanForHighId();
setHighId( foundHighId );
if ( !fastRebuild )
{
try ( PageCursor cursor = storeFile.io( 0, PF_SHARED_WRITE_LOCK | PF_READ_AHEAD ) )
{
defraggedCount = rebuildIdGeneratorSlow( cursor, getRecordsPerPage(), blockSize, foundHighId );
}
}
}
catch ( IOException e )
{
throw new UnderlyingStorageException( "Unable to rebuild id generator " + getStorageFileName(), e );
}
log.info( "[" + getStorageFileName() + "] high id=" + getHighId() + " (defragged=" + defraggedCount + ")" );
log.info( getStorageFileName() + " rebuild id generator, highId=" + getHighId() +
" defragged count=" + defraggedCount );
if ( !fastRebuild )
{
closeIdGenerator();
openIdGenerator();
}
}
protected boolean isOnlyFastIdGeneratorRebuildEnabled( Config config )
{
return config.get( Configuration.rebuild_idgenerators_fast );
}
private long rebuildIdGeneratorSlow( PageCursor cursor, int recordsPerPage, int blockSize,
long foundHighId ) throws IOException
{
if ( !cursor.isWriteLocked() )
{
throw new IllegalArgumentException(
"The store scanning id generator rebuild process requires a page cursor that is write-locked" );
}
long defragCount = 0;
long[] freedBatch = new long[recordsPerPage]; // we process in batches of one page worth of records
int startingId = getNumberOfReservedLowIds();
int defragged;
boolean done = false;
while ( !done && cursor.next() )
{
long idPageOffset = (cursor.getCurrentPageId() * recordsPerPage);
defragged = 0;
for ( int i = startingId; i < recordsPerPage; i++ )
{
int offset = i * blockSize;
cursor.setOffset( offset );
long recordId = idPageOffset + i;
if ( recordId >= foundHighId )
{ // We don't have to go further than the high id we found earlier
done = true;
break;
}
if ( !isInUse( cursor ) )
{
freedBatch[defragged++] = recordId;
}
else if ( isRecordReserved( cursor ) )
{
cursor.setOffset( offset );
cursor.putByte( Record.NOT_IN_USE.byteValue() );
cursor.putInt( 0 );
freedBatch[defragged++] = recordId;
}
}
checkIdScanCursorBounds( cursor );
for ( int i = 0; i < defragged; i++ )
{
freeId( freedBatch[i] );
}
defragCount += defragged;
startingId = 0;
}
return defragCount;
}
private void checkIdScanCursorBounds( PageCursor cursor )
{
if ( cursor.checkAndClearBoundsFlag() )
{
throw new UnderlyingStorageException(
"Out of bounds access on page " + cursor.getCurrentPageId() + " detected while scanning the " +
storageFileName + " file for deleted records" );
}
}
/**
* Marks this store as "not ok".
*/
protected void setStoreNotOk( Throwable cause )
{
storeOk = false;
causeOfStoreNotOk = cause;
idGenerator = null; // since we will rebuild it later
}
/**
* If store is "not ok" <CODE>false</CODE> is returned.
*
* @return True if this store is ok
*/
protected boolean getStoreOk()
{
return storeOk;
}
/**
* Throws cause of not being OK if {@link #getStoreOk()} returns {@code false}.
*/
protected void checkStoreOk()
{
if ( !storeOk )
{
throw launderedException( causeOfStoreNotOk );
}
}
/**
* Returns the next id for this store's {@link IdGenerator}.
*
* @return The next free id
*/
@Override
public long nextId()
{
if ( idGenerator == null )
{
throw new IllegalStateException( "IdGenerator is not initialized" );
}
return idGenerator.nextId();
}
/**
* Frees an id for this store's {@link IdGenerator}.
*
* @param id The id to free
*/
public void freeId( long id )
{
IdGenerator generator = this.idGenerator;
if ( generator != null )
{
generator.freeId( id );
}
// else we're deleting records as part of applying transactions during recovery, and that's fine
}
/**
* Return the highest id in use. If this store is not OK yet, the high id is calculated from the highest
* in use record on the store, using {@link #scanForHighId()}.
*
* @return The high id, i.e. highest id in use + 1.
*/
@Override
public long getHighId()
{
return idGenerator != null ? idGenerator.getHighId() : scanForHighId();
}
/**
* Sets the high id, i.e. highest id in use + 1 (use this when rebuilding id generator).
*
* @param highId The high id to set.
*/
public void setHighId( long highId )
{
// This method might get called during recovery, where we don't have a reliable id generator yet,
// so ignore these calls and let rebuildIdGenerators() figure out the high id after recovery.
IdGenerator generator = this.idGenerator;
if ( generator != null )
{
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized ( generator )
{
if ( highId > generator.getHighId() )
{
generator.setHighId( highId );
}
}
}
}
/**
* If store is not ok a call to this method will rebuild the {@link
* IdGenerator} used by this store and if successful mark it as OK.
*
* WARNING: this method must NOT be called if recovery is required, but hasn't performed.
* To remove all negations from the above statement: Only call this method if store is in need of
* recovery and recovery has been performed.
*/
public void makeStoreOk()
{
if ( !storeOk )
{
rebuildIdGenerator();
storeOk = true;
causeOfStoreNotOk = null;
}
}
/**
* Returns the name of this store.
*
* @return The name of this store
*/
@Override
public File getStorageFileName()
{
return storageFileName;
}
private File getIdFileName()
{
return new File( getStorageFileName().getPath() + ".id" );
}
/**
* Opens the {@link IdGenerator} used by this store.
* <p>
* Note: This method may be called both while the store has the store file mapped in the
* page cache, and while the store file is not mapped. Implementers must therefore
* map their own temporary PagedFile for the store file, and do their file IO through that,
* if they need to access the data in the store file.
*/
protected void openIdGenerator()
{
idGenerator = idGeneratorFactory.open( getIdFileName(), getIdType(), scanForHighId(), recordFormat.getMaxId() );
}
/**
* Starts from the end of the file and scans backwards to find the highest in use record.
* Can be used even if {@link #makeStoreOk()} hasn't been called. Basically this method should be used
* over {@link #getHighestPossibleIdInUse()} and {@link #getHighId()} in cases where a store has been opened
* but is in a scenario where recovery isn't possible, like some tooling or migration.
*
* @return the id of the highest in use record + 1, i.e. highId.
*/
protected long scanForHighId()
{
try ( PageCursor cursor = storeFile.io( 0, PF_SHARED_READ_LOCK ) )
{
byte[] expectedLegacyVersionBytes = UTF8.encode( typeDescriptor + " " + storeVersion );
long nextPageId = storeFile.getLastPageId();
int recordsPerPage = getRecordsPerPage();
int recordSize = getRecordSize();
long highestId = getNumberOfReservedLowIds();
while ( nextPageId >= 0 && cursor.next( nextPageId ) )
{
nextPageId--;
boolean found;
do
{
found = false;
int currentRecord = recordsPerPage;
while ( currentRecord-- > 0 )
{
int offset = currentRecord * recordSize;
cursor.setOffset( offset );
long recordId = (cursor.getCurrentPageId() * recordsPerPage) + currentRecord;
if ( isInUse( cursor ) )
{
boolean justLegacyStoreTrailer = isJustLegacyStoreTrailer( cursor, offset,
expectedLegacyVersionBytes, recordSize );
if ( !justLegacyStoreTrailer )
{
// We've found the highest id in use
highestId = recordId + 1 /*+1 since we return the high id*/;
found = true;
break;
}
}
}
}
while ( cursor.shouldRetry() );
checkIdScanCursorBounds( cursor );
if ( found )
{
return highestId;
}
}
return getNumberOfReservedLowIds();
}
catch ( IOException e )
{
throw new UnderlyingStorageException(
"Unable to find high id by scanning backwards " + getStorageFileName(), e );
}
}
/**
* {@link CommonAbstractStore} doesn't use version trailers in the end of the stores after a clean shutdown
* anymore. Although {@link RecordFormat} is now pluggable and so a {@link CommonAbstractStore} may be used
* to open an older version of the store, one which might have version trailers. This method is used
* during opening a store to figure out the highest id by scanning from the end. It's very convenient
* if we were aware of the existence of version trailers as to support opening older versions without
* problems in this regard. A version trailer may span multiple records in a store which has record size
* smaller than the trailer length and so the matching takes that into account in that it can figure
* out all possible subsets of the trailer to compare with. Without this method the scan which figures
* out highest in use id may mistake version trailer "records" for inUse records, if the inUse bit
* happened to be set and so would report too high highest id and reading those higher/trailer records,
* trying to interpret them as normal records would fail in random and interesting ways.
*
* @param cursor {@link PageCursor} to read and compare trailer bytes with.
* @param offset offset to start reading the record bytes from the cursor.
* @param expectedVersionBytes the whole version trailer as a {@code byte[]}.
* @param recordSize record size of records in this store.
* @return {@code true} if the record at the offset was just a version trailer "record", otherwise
* {@code false} where the id of this record will be set as the highest inUse record in this store.
*/
private boolean isJustLegacyStoreTrailer( PageCursor cursor, int offset, byte[] expectedVersionBytes,
int recordSize )
{
try
{
for ( int i = 0; i < expectedVersionBytes.length; )
{
// If the version bytes are bigger than record size then we must also compare with subsets
// of those bytes in recordSize chunks
boolean mismatch = false;
for ( int j = 0; i < expectedVersionBytes.length && j < recordSize; i++, j++ )
{
byte b = cursor.getByte( offset + j );
if ( b != expectedVersionBytes[i] )
{
mismatch = true;
}
}
if ( !mismatch )
{
return true;
}
}
return false;
}
catch ( IndexOutOfBoundsException e )
{
return false;
}
}
protected int determineRecordSize()
{
return recordFormat.getRecordSize( storeHeader );
}
@Override
public final int getRecordSize()
{
return recordSize;
}
@Override
public int getRecordDataSize()
{
return recordSize - recordFormat.getRecordHeaderSize();
}
private boolean isInUse( PageCursor cursor )
{
return recordFormat.isInUse( cursor );
}
protected boolean isRecordReserved( PageCursor cursor )
{
return false;
}
protected void createIdGenerator( File fileName )
{
idGeneratorFactory.create( fileName, 0, false );
}
/** Closed the {@link IdGenerator} used by this store */
protected void closeIdGenerator()
{
if ( idGenerator != null )
{
idGenerator.close();
}
}
@Override
public void flush()
{
try
{
storeFile.flushAndForce();
}
catch ( IOException e )
{
throw new UnderlyingStorageException( "Failed to flush", e );
}
}
/**
* Checks if this store is closed and throws exception if it is.
*
* @throws IllegalStateException if the store is closed
*/
protected void assertNotClosed()
{
if ( storeFile == null )
{
throw new IllegalStateException( this + " for file '" + storageFileName + "' is closed" );
}
}
/**
* Closes this store. This will cause all buffers and channels to be closed.
* Requesting an operation from after this method has been invoked is
* illegal and an exception will be thrown.
* <p>
* This method will start by invoking the {@link #closeStoreFile()} method
* giving the implementing store way to do anything that it needs to do
* before the pagedFile is closed.
*/
@Override
public void close()
{
try
{
closeStoreFile();
}
catch ( IOException | IllegalStateException e )
{
throw new UnderlyingStorageException( "Failed to close store file: " + getStorageFileName(), e );
}
}
private void closeStoreFile() throws IOException
{
try
{
/*
* Note: the closing ordering here is important!
* It is the case since we wand to mark the id generator as closed cleanly ONLY IF
* also the store file is cleanly shutdown.
*/
if ( storeFile != null )
{
storeFile.close();
}
if ( idGenerator != null )
{
if ( contains( openOptions, DELETE_ON_CLOSE ) )
{
idGenerator.delete();
}
else
{
idGenerator.close();
}
}
}
finally
{
storeFile = null;
}
}
/** @return The highest possible id in use, -1 if no id in use. */
@Override
public long getHighestPossibleIdInUse()
{
return idGenerator != null ? idGenerator.getHighestPossibleIdInUse() : scanForHighId() - 1;
}
/**
* Sets the highest id in use. After this call highId will be this given id + 1.
*
* @param highId The highest id in use to set.
*/
@Override
public void setHighestPossibleIdInUse( long highId )
{
setHighId( highId + 1 );
}
/** @return The total number of ids in use. */
public long getNumberOfIdsInUse()
{
if ( idGenerator == null )
{
throw new IllegalStateException( "IdGenerator is not initialized" );
}
return idGenerator.getNumberOfIdsInUse();
}
/**
* @return the number of records at the beginning of the store file that are reserved for other things
* than actual records. Stuff like permanent configuration data.
*/
@Override
public int getNumberOfReservedLowIds()
{
return storeHeaderFormat.numberOfReservedRecords();
}
public IdType getIdType()
{
return idType;
}
public void logVersions( Logger logger )
{
logger.log( " " + getTypeDescriptor() + " " + storeVersion );
}
public void logIdUsage( Logger logger )
{
logger.log( String.format( " %s: used=%s high=%s",
getTypeDescriptor(), getNumberOfIdsInUse(), getHighestPossibleIdInUse() ) );
}
/**
* Visits this store, and any other store managed by this store.
* TODO this could, and probably should, replace all override-and-do-the-same-thing-to-all-my-managed-stores
* methods like:
* {@link #makeStoreOk()},
* {@link #close()} (where that method could be deleted all together and do a visit in {@link #close()}),
* {@link #logIdUsage(Logger)},
* {@link #logVersions(Logger)}
* For a good samaritan to pick up later.
*/
public void visitStore( Visitor<CommonAbstractStore<RECORD,HEADER>,RuntimeException> visitor )
{
visitor.visit( this );
}
/**
* Called from the part of the code that starts the {@link MetaDataStore} and friends, together with any
* existing transaction log, seeing that there are transactions to recover. Now, this shouldn't be
* needed because the state of the id generator _should_ reflect this fact, but turns out that,
* given HA and the nature of the .id files being like orphans to the rest of the store, we just
* can't trust that to be true. If we happen to have id generators open during recovery we delegate
* {@link #freeId(long)} calls to {@link IdGenerator#freeId(long)} and since the id generator is most likely
* out of date w/ regards to high id, it may very well blow up.
*
* This also marks the store as not OK. A call to {@link #makeStoreOk()} is needed once recovery is complete.
*/
final void deleteIdGenerator()
{
if ( idGenerator != null )
{
idGenerator.delete();
idGenerator = null;
setStoreNotOk( new IllegalStateException( "IdGenerator is not initialized" ) );
}
}
@Override
public long getNextRecordReference( RECORD record )
{
return recordFormat.getNextRecordReference( record );
}