Repository navigation
Expand file tree
/
Copy pathStoreAppend.java
More file actions
753 lines (641 loc) · 22.7 KB
/
Copy pathStoreAppend.java
File metadata and controls
753 lines (641 loc) · 22.7 KB
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
/*
* Copyright (c) 2012 Jan Kotek
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mapdb;
import java.io.DataInput;
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Iterator;
import java.util.Random;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.locks.Lock;
/**
* Append only store. Uses different file format than Direct and WAL store
*
*/
public class StoreAppend extends Store{
/** header at beginning of each file */
protected static final long HEADER = 1239900952130003033L;
/** index value has two parts, first is file number, second is offset in file, this is how many bites file offset occupies */
protected static final int FILE_SHIFT = 24;
/** mask used to get file offset from index val*/
protected static final long FILE_MASK = 0xFFFFFF;
protected static final int MAX_FILE_SIZE_SHIFT = CC.VOLUME_SLICE_SHIFT + 6; //TODO shift + 6 !!
/** add to size before writing it to file */
protected static final long SIZEP = 2;
/** add to recid before writing it to file */
protected static final long RECIDP = 3;
/** at place of recid indicates uncommited transaction, an end of append log */
protected static final long END = 1-RECIDP;
/** at place of recid indicates commited transaction, just ignore this value and continue */
protected static final long SKIP = 2-RECIDP;
/** storage file (without number*/
protected final File file;
protected final boolean useRandomAccessFile;
protected final boolean readOnly;
protected final boolean syncOnCommit;
protected final boolean deleteFilesAfterClose;
/** transactions enabled*/
protected final boolean tx;
/** true after file was closed */
protected volatile boolean closed = false;
/** true after file was modified */
protected volatile boolean modified = false;
/** contains opened files, key is file number*/
protected final LongConcurrentHashMap<Volume> volumes = new LongConcurrentHashMap<Volume>();
/** last uses file, currently writing into */
protected Volume currVolume;
/** last used position, currently writing into */
protected long currPos;
/** last file number, currently writing into */
protected long currFileNum;
/** maximal recid */
protected long maxRecid;
/** file position on last commit, used for rollback */
protected long rollbackCurrPos;
/** file number on last commit, used for rollback */
protected long rollbackCurrFileNum;
/** maximial recid on last commit, used for rollback */
protected long rollbackMaxRecid;
/** index table which maps recid into position in index log */
protected Volume index = new Volume.MemoryVol(false,0, MAX_FILE_SIZE_SHIFT); //TODO option to keep index off-heap or in file
/** same as `index`, but stores uncommited modifications made in this transaction*/
protected final LongMap<Long> indexInTx;
public StoreAppend(final File file, final boolean useRandomAccessFile, final boolean readOnly,
final boolean transactionDisabled, final boolean deleteFilesAfterClose, final boolean syncOnCommitDisabled,
boolean checksum, boolean compress, byte[] password, boolean disableLocks) {
super(checksum, compress, password,disableLocks);
this.file = file;
this.useRandomAccessFile = useRandomAccessFile;
this.readOnly = readOnly;
this.deleteFilesAfterClose = deleteFilesAfterClose;
this.syncOnCommit = !syncOnCommitDisabled;
this.tx = !transactionDisabled;
indexInTx = tx?new LongConcurrentHashMap<Long>() : null;
final File parent = file.getAbsoluteFile().getParentFile();
if(!parent.exists() || !parent.isDirectory())
throw new IllegalArgumentException("Parent dir does not exist: "+file);
//list all matching files and sort them by number
final SortedSet<Fun.Tuple2<Long,File>> sortedFiles = new TreeSet<Fun.Tuple2<Long, File>>();
final String prefix = file.getName();
for(File f:parent.listFiles()){
String name= f.getName();
if(!name.startsWith(prefix) || name.length()<=prefix.length()+1) continue;
String number = name.substring(prefix.length()+1, name.length());
if(!number.matches("^[0-9]+$")) continue;
sortedFiles.add(Fun.t2(Long.valueOf(number),f));
}
if(sortedFiles.isEmpty()){
//no files, create empty store
Volume zero = Volume.volumeForFile(getFileFromNum(0),useRandomAccessFile, readOnly,0L,MAX_FILE_SIZE_SHIFT,0);
zero.ensureAvailable(Engine.LAST_RESERVED_RECID*8+8);
zero.putLong(0, HEADER);
long pos = 8;
//put reserved records as empty
for(long recid=1;recid<=LAST_RESERVED_RECID;recid++){
pos+=zero.putPackedLong(pos, recid+RECIDP);
pos+=zero.putPackedLong(pos, 0+SIZEP); //and mark it with zero size (0==tombstone)
}
maxRecid = LAST_RESERVED_RECID;
index.ensureAvailable(LAST_RESERVED_RECID * 8 + 8);
volumes.put(0L, zero);
if(tx){
rollbackCurrPos = pos;
rollbackMaxRecid = maxRecid;
rollbackCurrFileNum = 0;
zero.putUnsignedByte(pos, (int) (END+RECIDP));
pos++;
}
currVolume = zero;
currPos = pos;
}else{
//some files exists, open, check header and replay index
for(Fun.Tuple2<Long,File> t:sortedFiles){
Long num = t.a;
File f = t.b;
Volume vol = Volume.volumeForFile(f,useRandomAccessFile,readOnly, 0L, MAX_FILE_SIZE_SHIFT,0);
if(vol.isEmpty()||vol.getLong(0)!=HEADER){
vol.sync();
vol.close();
Iterator<Volume> vols = volumes.valuesIterator();
while(vols.hasNext()){
Volume next = vols.next();
next.sync();
next.close();
}
throw new IOError(new IOException("File corrupted: "+f));
}
volumes.put(num, vol);
long pos = 8;
while(pos<=FILE_MASK){
long recid = vol.getPackedLong(pos);
pos+=packedLongSize(recid);
recid -= RECIDP;
maxRecid = Math.max(recid,maxRecid);
// System.out.println("replay "+recid+ " - "+pos);
if(recid==END){
//reached end of file
currVolume = vol;
currPos = pos;
currFileNum = num;
rollbackCurrFileNum = num;
rollbackMaxRecid = maxRecid;
rollbackCurrPos = pos-1;
return;
}else if(recid==SKIP){
//commit mark, so skip
continue;
}else if(recid<=0){
Iterator<Volume> vols = volumes.valuesIterator();
while(vols.hasNext()){
Volume next = vols.next();
next.sync();
next.close();
}
throw new IOError(new IOException("File corrupted: "+f));
}
index.ensureAvailable(recid*8+8);
long indexVal = (num<<FILE_SHIFT)|pos;
long size = vol.getPackedLong(pos);
pos+=packedLongSize(size);
size-=SIZEP;
if(size==0){
index.putLong(recid*8,0);
}else if(size>0){
pos+=size;
index.putLong(recid*8,indexVal);
}else{
index.putLong(recid*8, Long.MIN_VALUE); //TODO tombstone
}
}
}
Iterator<Volume> vols = volumes.valuesIterator();
while(vols.hasNext()){
Volume next = vols.next();
next.sync();
next.close();
}
throw new IOError(new IOException("File not sealed, data possibly corrupted"));
}
}
public StoreAppend(File file) {
this(file,false,false,false,false,false,false,false,null,false);
}
protected File getFileFromNum(long fileNumber){
return new File(file.getPath()+"."+fileNumber);
}
protected void rollover(){
if(currVolume.getLong(0)!=HEADER) throw new AssertionError();
if(currPos<=FILE_MASK || readOnly) return;
//beyond usual file size, so create new file
currVolume.sync();
currFileNum++;
currVolume = Volume.volumeForFile(getFileFromNum(currFileNum),useRandomAccessFile, readOnly,0L, MAX_FILE_SIZE_SHIFT,0);
currVolume.ensureAvailable(8);
currVolume.putLong(0,HEADER);
currPos = 8;
volumes.put(currFileNum, currVolume);
}
protected long indexVal(long recid) {
if(tx){
Long val = indexInTx.get(recid);
if(val!=null) return val;
}
return index.getLong(recid*8);
}
protected void setIndexVal(long recid, long indexVal) {
if(tx) indexInTx.put(recid,indexVal);
else{
index.ensureAvailable(recid*8+8);
index.putLong(recid*8,indexVal);
}
}
@Override
public long preallocate() {
final Lock lock;
if(disableLocks) {
lock = null;
}else {
lock = locks[new Random().nextInt(locks.length)].readLock();
lock.lock();
}
try{
if(!disableLocks) {
structuralLock.lock();
}
final long recid;
try{
recid = ++maxRecid;
modified = true;
}finally{
if(!disableLocks) {
structuralLock.unlock();
}
}
assert(recid>0);
return recid;
}finally {
if(!disableLocks) {
lock.unlock();
}
}
}
@Override
public void preallocate(long[] recids) {
final Lock lock;
if(disableLocks) {
lock = null;
}else {
lock = locks[new Random().nextInt(locks.length)].readLock();
lock.lock();
}
try{
if(!disableLocks) {
structuralLock.lock();
}
try{
for(int i = 0;i<recids.length;i++){
recids[i] = ++maxRecid;
assert(recids[i]>0);
}
modified = true;
}finally{
if(!disableLocks) {
structuralLock.unlock();
}
}
}finally {
if(!disableLocks) {
lock.unlock();
}
}
}
@Override
public <A> long put(A value, Serializer<A> serializer) {
assert(value!=null);
DataOutput2 out = serialize(value,serializer);
final Lock lock;
if(disableLocks) {
lock = null;
}else {
lock = locks[new Random().nextInt(locks.length)].readLock();
lock.lock();
}
try{
if(!disableLocks) {
structuralLock.lock();
}
final long oldPos,recid,indexVal;
try{
rollover();
currVolume.ensureAvailable(currPos+6+4+out.pos);
recid = ++maxRecid;
//write recid
currPos+=currVolume.putPackedLong(currPos, recid+RECIDP);
indexVal = (currFileNum<<FILE_SHIFT)|currPos; //TODO file number
//write size
currPos+=currVolume.putPackedLong(currPos, out.pos+SIZEP);
oldPos = currPos;
currPos+=out.pos;
modified = true;
}finally{
if(!disableLocks) {
structuralLock.unlock();
}
}
//write data
currVolume.putData(oldPos,out.buf,0,out.pos);
recycledDataOuts.offer(out);
setIndexVal(recid, indexVal);
assert(recid>0);
return recid;
}finally {
if(!disableLocks) {
lock.unlock();
}
}
}
@Override
public <A> A get(long recid, Serializer<A> serializer) {
assert(recid>0);
final Lock lock;
if(disableLocks) {
lock = null;
}else {
lock = locks[Store.lockPos(recid)].readLock();
lock.lock();
}
try{
return getNoLock(recid, serializer);
}catch(IOException e){
throw new IOError(e);
}finally {
if(!disableLocks) {
lock.unlock();
}
}
}
protected <A> A getNoLock(long recid, Serializer<A> serializer) throws IOException {
long indexVal = indexVal(recid);
if(indexVal==0) return null;
Volume vol = volumes.get(indexVal>>>FILE_SHIFT);
long fileOffset = indexVal&FILE_MASK;
long size = vol.getPackedLong(fileOffset);
fileOffset+= packedLongSize(size);
size-=SIZEP;
if(size<0) return null;
if(size==0) return serializer.deserialize(new DataIO.DataInputByteArray(new byte[0]),0);
DataInput in = vol.getDataInput(fileOffset, (int) size);
return deserialize(serializer, (int) size,in);
}
@Override
public <A> void update(long recid, A value, Serializer<A> serializer) {
assert(value!=null);
assert(recid>0);
DataOutput2 out = serialize(value,serializer);
final Lock lock;
if(disableLocks) {
lock = null;
}else {
lock = locks[Store.lockPos(recid)].writeLock();
lock.lock();
}
try{
updateNoLock(recid, out);
}finally {
if(!disableLocks) {
lock.unlock();
}
}
recycledDataOuts.offer(out);
}
protected void updateNoLock(long recid, DataOutput2 out) {
final long indexVal, oldPos;
if(!disableLocks) {
structuralLock.lock();
}
try{
rollover();
currVolume.ensureAvailable(currPos+6+4+out.pos);
//write recid
currPos+=currVolume.putPackedLong(currPos, recid+RECIDP);
indexVal = (currFileNum<<FILE_SHIFT)|currPos; //TODO file number
//write size
currPos+=currVolume.putPackedLong(currPos, out.pos+SIZEP);
oldPos = currPos;
currPos+=out.pos;
modified = true;
}finally {
if(!disableLocks) {
structuralLock.unlock();
}
}
//write data
currVolume.ensureAvailable(oldPos+out.pos);
currVolume.putData(oldPos,out.buf,0,out.pos);
setIndexVal(recid, indexVal);
}
@Override
public <A> boolean compareAndSwap(long recid, A expectedOldValue, A newValue, Serializer<A> serializer) {
assert(expectedOldValue!=null && newValue!=null);
assert(recid>0);
DataOutput2 out = serialize(newValue,serializer);
final Lock lock;
if(disableLocks) {
lock = null;
}else {
lock = locks[Store.lockPos(recid)].writeLock();
lock.lock();
}
boolean ret;
try{
Object old = getNoLock(recid,serializer);
if(expectedOldValue.equals(old)){
updateNoLock(recid,out);
ret = true;
}else{
ret = false;
}
}catch(IOException e){
throw new IOError(e);
}finally {
if(!disableLocks) {
lock.unlock();
}
}
recycledDataOuts.offer(out);
return ret;
}
@Override
public <A> void delete(long recid, Serializer<A> serializer) {
assert(recid>0);
final Lock lock;
if(disableLocks) {
lock = null;
}else {
lock = locks[Store.lockPos(recid)].writeLock();
lock.lock();
}
try{
if(!disableLocks) {
structuralLock.lock();
}
try{
rollover();
currVolume.ensureAvailable(currPos+6+0);
currPos+=currVolume.putPackedLong(currPos, recid+SIZEP);
setIndexVal(recid, (currFileNum<<FILE_SHIFT) | currPos);
//write tombstone
currPos+=currVolume.putPackedLong(currPos, 1);
modified = true;
}finally{
if(!disableLocks) {
structuralLock.unlock();
}
}
}finally{
if(!disableLocks) {
lock.unlock();
}
}
}
@Override
public void close() {
if(closed) return;
for(Runnable closeListener:closeListeners)
closeListener.run();
if(serializerPojo!=null && serializerPojo.hasUnsavedChanges()){
serializerPojo.save(this);
}
Iterator<Volume> iter=volumes.valuesIterator();
if(!readOnly && modified){ //TODO and modified since last open
rollover();
currVolume.putUnsignedByte(currPos, (int) (END+RECIDP));
}
while(iter.hasNext()){
Volume v = iter.next();
v.sync();
v.close();
if(deleteFilesAfterClose) v.deleteFile();
}
volumes.clear();
closed = true;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public void commit() {
if(!tx){
currVolume.sync();
return;
}
lockAllWrite();
try{
LongMap.LongMapIterator<Long> iter = indexInTx.longMapIterator();
while(iter.moveToNext()){
index.ensureAvailable(iter.key()*8+8);
index.putLong(iter.key()*8, iter.value());
}
Volume rollbackCurrVolume = volumes.get(rollbackCurrFileNum);
rollbackCurrVolume.putUnsignedByte(rollbackCurrPos, (int) (SKIP+RECIDP));
if(syncOnCommit) rollbackCurrVolume.sync();
indexInTx.clear();
rollover();
rollbackCurrPos = currPos;
rollbackMaxRecid = maxRecid;
rollbackCurrFileNum = currFileNum;
currVolume.putUnsignedByte(rollbackCurrPos, (int) (END+RECIDP));
currPos++;
if(serializerPojo!=null && serializerPojo.hasUnsavedChanges()){
serializerPojo.save(this);
}
}finally{
unlockAllWrite();
}
}
@Override
public void rollback() throws UnsupportedOperationException {
if(!tx) throw new UnsupportedOperationException("Transactions are disabled");
lockAllWrite();
try{
indexInTx.clear();
currVolume = volumes.get(rollbackCurrFileNum);
currPos = rollbackCurrPos;
maxRecid = rollbackMaxRecid;
currFileNum = rollbackCurrFileNum;
//TODO rollback serializerPojo?
}finally{
unlockAllWrite();
}
}
@Override
public boolean canRollback(){
return tx;
}
@Override
public boolean isReadOnly() {
return readOnly;
}
@Override
public void clearCache() {
//no cache to clear
}
@Override
public void compact() {
if(readOnly) throw new IllegalAccessError("readonly");
lockAllWrite();
try{
if(!indexInTx.isEmpty()) throw new IllegalAccessError("uncommited changes");
LongHashMap<Boolean> ff = new LongHashMap<Boolean>();
for(long recid=0;recid<=maxRecid;recid++){
long indexVal = index.getLong(recid*8);
if(indexVal ==0)continue;
long fileNum = indexVal>>>FILE_SHIFT;
ff.put(fileNum,true);
}
//now traverse files and delete unused
LongMap.LongMapIterator<Volume> iter = volumes.longMapIterator();
while(iter.moveToNext()){
long fileNum = iter.key();
if(fileNum==currFileNum || ff.get(fileNum)!=null) continue;
Volume v = iter.value();
v.sync();
v.close();
v.deleteFile();
iter.remove();
}
}finally{
unlockAllWrite();
}
}
@Override
public long getMaxRecid() {
return maxRecid;
}
@Override
public ByteBuffer getRaw(long recid) {
//TODO use direct BB
byte[] bb = get(recid, Serializer.BYTE_ARRAY_NOSIZE);
if(bb==null) return null;
return ByteBuffer.wrap(bb);
}
@Override
public Iterator<Long> getFreeRecids() {
return Fun.EMPTY_ITERATOR; //TODO free recid management
}
@Override
public void updateRaw(long recid, ByteBuffer data) {
rollover();
byte[] b = null;
if(data!=null){
data = data.duplicate();
b = new byte[data.remaining()];
data.get(b);
}
//TODO use BB without copying
update(recid, b, Serializer.BYTE_ARRAY_NOSIZE);
modified = true;
}
@Override
public long getSizeLimit() {
return 0;
}
@Override
public long getCurrSize() {
return currFileNum*FILE_MASK;
}
@Override
public long getFreeSize() {
return 0;
}
@Override
public String calculateStatistics() {
return null;
}
/** get number of bytes occupied by packed long */
protected static int packedLongSize(long value) {
int ret = 1;
while ((value & ~0x7FL) != 0) {
ret++;
value >>>= 7;
}
return ret;
}
}