Repository navigation
Expand file tree
/
Copy pathStoreAppend.java
More file actions
671 lines (565 loc) · 21.1 KB
/
Copy pathStoreAppend.java
File metadata and controls
671 lines (565 loc) · 21.1 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
package org.mapdb;
import java.io.DataInput;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.logging.Level;
/**
* append only store
*/
public class StoreAppend extends Store {
/** 2 byte store version*/
protected static final int STORE_VERSION = 100;
/** 4 byte file header */
protected static final int HEADER = (0xAB3D<<16) | STORE_VERSION;
protected static final int I_UPDATE = 1;
protected static final int I_INSERT = 3;
protected static final int I_DELETE = 2;
protected static final int I_PREALLOC = 4;
protected static final int I_SKIP_SINGLE_BYTE = 6;
protected static final int I_SKIP_MULTI_BYTE = 7;
protected static final int I_TX_VALID = 8;
protected static final int I_TX_ROLLBACK = 9;
protected static final long headerSize = 16;
protected static final StoreAppend[] STORE_APPENDS_ZERO_ARRAY = new StoreAppend[0];
protected Volume vol;
/**
* In memory table which maps recids into their offsets. Positive values are offsets.
* Zero value indicates on-used records
* Negative values are:
* <pre>
* -1 - records was deleted, return null
* -2 - record has zero size
* -3 - null record, return null
* </pre>
*
*
*/
//TODO this is in-memory, move to temporary file or something
protected Volume indexTable;
//guarded by StructuralLock
protected long eof = 0;
protected final AtomicLong highestRecid = new AtomicLong(0);
protected final boolean tx;
protected final LongLongMap[] modified;
protected final ScheduledExecutorService compactionExecutor;
protected final Set<StoreAppend> snapshots;
protected final boolean isSnapshot;
protected final long startSize;
protected final long sizeIncrement;
protected final int sliceShift;
protected StoreAppend(String fileName,
Volume.VolumeFactory volumeFactory,
Cache cache,
int lockScale,
int lockingStrategy,
boolean checksum,
boolean compress,
byte[] password,
boolean readonly,
boolean snapshotEnable,
boolean fileLockDisable,
DataIO.HeartbeatFileLock fileLockHeartbeat,
boolean txDisabled,
ScheduledExecutorService compactionExecutor,
long startSize,
long sizeIncrement
) {
super(fileName, volumeFactory, cache, lockScale,lockingStrategy, checksum, compress, password, readonly,
snapshotEnable,fileLockDisable, fileLockHeartbeat);
this.tx = !txDisabled;
if(tx){
modified = new LongLongMap[this.lockScale];
for(int i=0;i<modified.length;i++){
modified[i] = new LongLongMap();
}
}else{
modified = null;
}
this.compactionExecutor = compactionExecutor;
this.snapshots = Collections.synchronizedSet(new HashSet<StoreAppend>());
this.isSnapshot = false;
this.sizeIncrement = Math.max(1L<<CC.VOLUME_PAGE_SHIFT, DataIO.nextPowTwo(sizeIncrement));
this.startSize = Fun.roundUp(Math.max(1L<<CC.VOLUME_PAGE_SHIFT,startSize), this.sizeIncrement);
this.sliceShift = Volume.sliceShiftFromSize(this.sizeIncrement);
}
public StoreAppend(String fileName) {
this(fileName,
fileName==null? CC.DEFAULT_MEMORY_VOLUME_FACTORY : CC.DEFAULT_FILE_VOLUME_FACTORY,
null,
CC.DEFAULT_LOCK_SCALE,
0,
false,
false,
null,
false,
false,
false,
null,
false,
null,
0,
0
);
}
/** protected constructor used to take snapshots*/
protected StoreAppend(StoreAppend host, LongLongMap[] uncommitedData){
super(null, null,null,
host.lockScale,
Store.LOCKING_STRATEGY_NOLOCK,
host.checksum,
host.compress,
null, //TODO password on snapshot
true, //snapshot is readonly
false,
false,
null);
indexTable = host.indexTable;
vol = host.vol;
//replace locks, so reads on snapshots are not performed while host is updated
for(int i=0;i<locks.length;i++){
locks[i] = host.locks[i];
}
tx = true;
modified = new LongLongMap[this.lockScale];
if(uncommitedData==null){
for(int i=0;i<modified.length;i++) {
modified[i] = new LongLongMap();
}
}else{
for(int i=0;i<modified.length;i++) {
Lock lock = locks[i].writeLock();
lock.lock();
try {
modified[i] = uncommitedData[i].clone();
}finally {
lock.unlock();
}
}
}
this.compactionExecutor = null;
this.snapshots = host.snapshots;
this.isSnapshot = true;
host.snapshots.add(StoreAppend.this);
this.startSize = host.startSize;
this.sizeIncrement = host.sizeIncrement;
this.sliceShift = host.sliceShift;
}
@Override
public void init() {
super.init();
structuralLock.lock();
try {
boolean empty = Volume.isEmptyFile(fileName);
vol = volumeFactory.makeVolume(fileName, readonly,fileLockDisable,sliceShift, startSize, false);
indexTable = new Volume.ByteArrayVol(CC.VOLUME_PAGE_SHIFT,0L);
indexTable.ensureAvailable(RECID_LAST_RESERVED*8);
eof = headerSize;
for (int i = 0; i <= RECID_LAST_RESERVED; i++) {
indexTable.ensureAvailable(i * 8);
indexTable.putLong(i * 8, -3);
}
if (empty) {
initCreate();
} else {
initOpen();
}
}finally {
structuralLock.unlock();
}
}
protected void initCreate() {
vol.ensureAvailable(headerSize);
highestRecid.set(RECID_LAST_RESERVED);
vol.putInt(0,HEADER);
long feat = makeFeaturesBitmap();
vol.putLong(HEAD_FEATURES, feat);
vol.sync();
}
protected void initOpen() {
if (!readonly)
vol.ensureAvailable(headerSize);
checkFeaturesBitmap(vol.getLong(HEAD_FEATURES));
//replay log
long pos = headerSize;
final long volumeSize = vol.length();
long lastValidPos= pos;
long lastValidCommitOffset = 0;
long highestRecid2 = RECID_LAST_RESERVED;
LongLongMap commitData = tx?new LongLongMap():null;
try{
while(true) {
lastValidPos = pos;
if(pos>=volumeSize)
break;
final long instPos = pos;
final int inst = vol.getUnsignedByte(pos++);
if (inst == I_INSERT || inst == I_UPDATE) {
long recid = vol.getPackedLong(pos);
pos += recid>>>60;
recid = longParityGet(recid & DataIO.PACK_LONG_RESULT_MASK);
highestRecid2 = Math.max(highestRecid2, recid);
commitData.put(recid, instPos);
//skip rest of the record
long size = vol.getPackedLong(pos);
long dataLen = longParityGet(size & DataIO.PACK_LONG_RESULT_MASK) - 1;
dataLen = Math.max(0,dataLen);
pos = pos + (size>>>60) + dataLen;
} else if (inst == I_DELETE) {
long recid = vol.getPackedLong(pos);
pos += recid>>>60;
recid = longParityGet(recid & DataIO.PACK_LONG_RESULT_MASK);
highestRecid2 = Math.max(highestRecid2, recid);
commitData.put(recid, -1);
} else if (inst == I_DELETE) {
long recid = vol.getPackedLong(pos);
pos += recid>>>60;
recid = longParityGet(recid & DataIO.PACK_LONG_RESULT_MASK);
highestRecid2 = Math.max(highestRecid2, recid);
commitData.put(recid,-2);
} else if (inst == I_SKIP_SINGLE_BYTE) {
//do nothing, just skip single byte
} else if (inst == I_SKIP_MULTI_BYTE) {
//read size and skip it
//skip rest of the record
long size = vol.getPackedLong(pos);
pos += (size>>>60) + longParityGet(size & DataIO.PACK_LONG_RESULT_MASK);
} else if (inst == I_TX_VALID) {
if (tx){
lastValidCommitOffset = pos;
//apply changes from commitData to indexTable
for(int i=0;i<commitData.table.length;i+=2){
long recidOffset = commitData.table[i]*8;
if(recidOffset==0)
continue;
indexTable.ensureAvailable(recidOffset + 8);
indexTable.putLong(recidOffset, commitData.table[i+1]);
}
commitData.clear();
}
} else if (inst == I_TX_ROLLBACK) {
if (tx) {
commitData.clear();
}
} else if (inst == 0) {
//rollback last changes if that is necessary
if (tx) {
//rollback changes in index table since last valid tx
commitData.clear();
}
break;
} else {
//TODO log here?
LOG.warning("Unknown instruction " + inst);
break;
}
}
}catch (RuntimeException e){
//log replay failed for some reason
if(tx) {
LOG.log(Level.WARNING, "Log corrupted, most likely last TX was not committed. " +
"Rolling back to last valid commit at offset: "+lastValidCommitOffset,e);
//rollback changes in index table since last valid tx
commitData.clear();
}else{
LOG.warning("AppendStore has transactions disabled, which means no crash protection. Data corruption at offset: "+pos);
//TODO data recovery possible, but needs documentation and tooling. For now just hard fail.
throw e;
}
}
eof = lastValidPos;
highestRecid.set(highestRecid2);
}
protected long alloc(int headSize, int totalSize){
structuralLock.lock();
try{
while(eof/StoreDirect.PAGE_SIZE != (eof+headSize)/StoreDirect.PAGE_SIZE){
//add skip instructions
vol.ensureAvailable(eof+1);
vol.putUnsignedByte(eof++, I_SKIP_SINGLE_BYTE);
}
long ret = eof;
eof+=totalSize;
return ret;
}finally {
structuralLock.unlock();
}
}
@Override
protected <A> A get2(long recid, Serializer<A> serializer) {
if(CC.ASSERT)
assertReadLocked(recid);
long offset = tx?
modified[lockPos(recid)].get(recid):
0;
if(offset==0) {
try {
offset = indexTable.getLong(recid * 8);
} catch (ArrayIndexOutOfBoundsException e) {
//TODO this code should be aware if indexTable internals?
throw new DBException.EngineGetVoid();
}
}
if(offset==-3||offset==-1) //null, preallocated or deleted
return null;
if(offset == 0){ //non existent
throw new DBException.EngineGetVoid();
}
if(offset == -2){
//zero size record
return deserialize(serializer,0,new DataIO.DataInputByteArray(new byte[0]));
}
final long packedRecidSize = DataIO.packLongSize(longParitySet(recid));
if(CC.ASSERT){
int instruction = vol.getUnsignedByte(offset);
if(instruction!= I_UPDATE && instruction!= I_INSERT)
throw new DBException.DataCorruption("wrong instruction "+instruction);
long recid2 = vol.getPackedLong(offset+1);
if(packedRecidSize!=recid2>>>60)
throw new DBException.DataCorruption("inconsistent recid len");
recid2 = longParityGet(recid2&DataIO.PACK_LONG_RESULT_MASK);
if(recid!=recid2)
throw new DBException.DataCorruption("recid does not match");
}
offset += 1 + //instruction size
packedRecidSize; // recid size
//read size
long size = vol.getPackedLong(offset);
offset+=size>>>60;
size = longParityGet(size & DataIO.PACK_LONG_RESULT_MASK);
size -= 1; //normalize size
if(CC.ASSERT && size<=0)
throw new DBException.DataCorruption("wrong size");
DataInput input = vol.getDataInputOverlap(offset, (int) size);
return deserialize(serializer, (int) size, input);
}
@Override
protected void update2(long recid, DataIO.DataOutputByteArray out) {
insertOrUpdate(recid, out, false);
}
private void insertOrUpdate(long recid, DataIO.DataOutputByteArray out, boolean isInsert) {
if(CC.ASSERT)
assertWriteLocked(lockPos(recid));
//TODO assert indexTable state, record should already exist/not exist
final int realSize = out==null ? 0: out.pos;
final int shiftedSize = out==null ?0 : realSize+1; //one additional state to indicate null
final int headSize = 1 + //instruction
DataIO.packLongSize(longParitySet(recid)) + //recid
DataIO.packLongSize(longParitySet(shiftedSize)); //length
long offset = alloc(headSize, headSize+realSize);
final long origOffset = offset;
//ensure available worst case scenario
vol.ensureAvailable(offset+headSize+realSize);
//instruction
vol.putUnsignedByte(offset, isInsert ? I_INSERT : I_UPDATE);
offset++;
//recid
offset+=vol.putPackedLong(offset,longParitySet(recid));
//size
offset+=vol.putPackedLong(offset,longParitySet(shiftedSize));
if(realSize!=0)
vol.putDataOverlap(offset, out.buf,0,out.pos);
// -3 is null record
// -2 is zero size record
indexTablePut(recid, out==null? -3 : (realSize==0) ? -2:origOffset);
}
@Override
protected <A> void delete2(long recid, Serializer<A> serializer) {
if(CC.ASSERT)
assertWriteLocked(lockPos(recid));
final int headSize = 1 + DataIO.packLongSize(longParitySet(recid));
long offset = alloc(headSize,headSize);
vol.ensureAvailable(offset + headSize);
vol.putUnsignedByte(offset, I_DELETE); //delete instruction
offset++;
vol.putPackedLong(offset,longParitySet(recid));
indexTablePut(recid, -1); // -1 is deleted record
}
@Override
public long getCurrSize() {
return 0;
}
@Override
public long getFreeSize() {
return 0;
}
@Override
public long preallocate() {
long recid = highestRecid.incrementAndGet();
Lock lock = locks[lockPos(recid)].writeLock();
lock.lock();
try{
final int headSize = 1 + DataIO.packLongSize(longParitySet(recid));
long offset = alloc(headSize,headSize);
vol.ensureAvailable(offset + headSize);
vol.putUnsignedByte(offset, I_PREALLOC);
offset++;
vol.putPackedLong(offset, longParitySet(recid));
indexTablePut(recid,-3);
}finally {
lock.unlock();
}
return recid;
}
protected void indexTablePut(long recid, long offset) {
if(tx){
modified[lockPos(recid)].put(recid,offset);
}else {
indexTable.ensureAvailable(recid*8+8);
indexTable.putLong(recid * 8, offset);
}
}
@Override
public <A> long put(A value, Serializer<A> serializer) {
DataIO.DataOutputByteArray out = serialize(value,serializer);
long recid = highestRecid.incrementAndGet();
int lockPos = lockPos(recid);
Cache cache = caches==null ? null : caches[lockPos] ;
Lock lock = locks[lockPos].writeLock();
lock.lock();
try{
if(cache!=null) {
cache.put(recid, value);
}
insertOrUpdate(recid,out,true);
}finally {
lock.unlock();
}
return recid;
}
@Override
public void close() {
if(closed)
return;
commitLock.lock();
try {
if(closed)
return;
if(isSnapshot){
snapshots.remove(this);
return;
}
vol.sync();
vol.close();
indexTable.close();
if(caches!=null){
for(Cache c:caches){
c.close();
}
Arrays.fill(caches,null);
}
if(fileLockHeartbeat !=null) {
fileLockHeartbeat.unlock();
fileLockHeartbeat = null;
}
closed = true;
}finally{
commitLock.unlock();
}
}
@Override
public void commit() {
if(isSnapshot)
return;
if(!tx){
vol.sync();
return;
}
commitLock.lock();
try{
StoreAppend[] snaps = snapshots==null ?
STORE_APPENDS_ZERO_ARRAY :
snapshots.toArray(STORE_APPENDS_ZERO_ARRAY);
for(int i=0;i<locks.length;i++) {
Lock lock = locks[i].writeLock();
lock.lock();
try {
long[] m = modified[i].table;
for(int j=0;j<m.length;j+=2){
long recid = m[j];
long recidOffset = recid*8;
if(recidOffset==0)
continue;
indexTable.ensureAvailable(recidOffset + 8);
long oldVal = indexTable.getLong(recidOffset);
indexTable.putLong(recidOffset,m[j+1]);
for(StoreAppend snap:snaps){
LongLongMap m2 = snap.modified[i];
if(m2.get(recid)==0) {
m2.put(recid, oldVal);
}
}
}
modified[i].clear();
}finally {
lock.unlock();
}
}
long offset = alloc(1,1);
vol.putUnsignedByte(offset,I_TX_VALID);
vol.sync();
}finally {
commitLock.unlock();
}
}
@Override
public void rollback() throws UnsupportedOperationException {
if(!tx || readonly || isSnapshot)
throw new UnsupportedOperationException();
commitLock.lock();
try{
for(int i=0;i<locks.length;i++) {
Lock lock = locks[i].writeLock();
lock.lock();
try {
modified[i].clear();
}finally {
lock.unlock();
}
}
long offset = alloc(1,1);
vol.putUnsignedByte(offset,I_TX_ROLLBACK);
vol.sync();
}finally {
commitLock.unlock();
}
}
@Override
public boolean canRollback() {
return tx;
}
@Override
public boolean canSnapshot() {
return true;
}
@Override
public Engine snapshot() throws UnsupportedOperationException {
commitLock.lock();
try {
return new StoreAppend(this, modified);
}finally {
commitLock.unlock();
}
}
@Override
public void compact() {
if(isSnapshot)
return;
}
@Override
public void backup(OutputStream out, boolean incremental) {
//TODO full backup
throw new UnsupportedOperationException("not yet implemented");
}
@Override
public void backupRestore(InputStream[] in) {
//TODO full backup
throw new UnsupportedOperationException("not yet implemented");
}
}