forked from royaltm/node-zmq-raft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilelog.js
1487 lines (1318 loc) · 53.5 KB
/
filelog.js
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) 2016-2017 Rafał Michalski <[email protected]>
*/
"use strict";
const assert = require('assert')
, path = require('path')
, { watch, constants: { R_OK, W_OK } } = require('fs')
const isArray = Array.isArray
, isBuffer = Buffer.isBuffer
, isEncoding = Buffer.isEncoding
, now = Date.now
, min = Math.min
, max = Math.max
, push = Array.prototype.push
, MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER
const { DEFAULT_REQUEST_ID_TTL, MIN_REQUEST_ID_TTL, MAX_REQUEST_ID_TTL } = require('../common/constants');
const { access, readdir, openDir, closeDir, mkdirp, renameSyncDir} = require('../utils/fsutil');
const { assertConstantsDefined, defineConst, delay, regexpEscape
, validateIntegerOption, createOptionsFactory
, isPowerOfTwo32, nextPowerOfTwo32 } = require('../utils/helpers');
const { writeBufUIntLE, readBufUIntLE } = require('../utils/bufconv');
const { createRotateName } = require('../utils/filerotate');
const synchronize = require('../utils/synchronize');
const { exclusive: lockExclusive, shared: lockShared } = require('../utils/lock');
const { createTempName, cleanupTempFiles } = require('../utils/tempfiles');
const ReadyEmitter = require('../common/readyemitter');
const StateMachineWriter = require('../common/state_machine_writer');
const IndexFile = require('../common/indexfile');
const SnapshotFile = require('../common/snapshotfile');
const LogStream = require('../server/logstream');
const LogWriter = require('../server/logwriter');
const { logPathComponents, logBaseName, logPath
, INDEX_FILENAME_LENGTH
, INDEX_FILE_EXT
, INDEX_PATH_PREFIX_LENGTH
, MIN_CAPACITY
, MAX_CAPACITY
, DEFAULT_CAPACITY
} = IndexFile;
const INDEX_BASENAME_LENGTH = INDEX_FILENAME_LENGTH - INDEX_FILE_EXT.length
, ENTRY_CHECKPOINT_DATA = [0xc0]
const FEED_STATE_NUM_ENTRIES_TRESHOLD = 2;
const REQUESTDB_CLEANUP_INTERVAL = 10000;
const INSTALL_SNAPSHOT_WATCHER_COOLDOWN_INTERVAL = 10000;
const MIN_REQUEST_ID_CACHE_HW = 1;
const { REQUEST_LOG_ENTRY_OFFSET
, REQUEST_LOG_ENTRY_LENGTH
, REQUEST_LOG_ENTRY_BASE64_LENGTH
, TYPE_LOG_ENTRY_OFFSET
, TERM_LOG_ENTRY_OFFSET
, LOG_ENTRY_HEADER_SIZE
, LOG_ENTRY_TYPE_STATE
, LOG_ENTRY_TYPE_CONFIG
, LOG_ENTRY_TYPE_CHECKPOINT
, makeHasRequestExpired
, readers: { readTypeOf }
, mixinReaders
, LogEntry } = require('../common/log_entry');
const REQUEST_LOG_ENTRY_END = REQUEST_LOG_ENTRY_OFFSET + REQUEST_LOG_ENTRY_LENGTH;
assertConstantsDefined({
INDEX_FILE_EXT
}, 'string');
assertConstantsDefined({
INDEX_FILENAME_LENGTH
, INDEX_PATH_PREFIX_LENGTH
, REQUEST_LOG_ENTRY_OFFSET
, REQUEST_LOG_ENTRY_LENGTH
, REQUEST_LOG_ENTRY_BASE64_LENGTH
, REQUEST_LOG_ENTRY_END
, TYPE_LOG_ENTRY_OFFSET
, TERM_LOG_ENTRY_OFFSET
, LOG_ENTRY_HEADER_SIZE
, LOG_ENTRY_TYPE_STATE
, LOG_ENTRY_TYPE_CONFIG
, LOG_ENTRY_TYPE_CHECKPOINT
, DEFAULT_CAPACITY
, MIN_CAPACITY
, MAX_CAPACITY
, DEFAULT_REQUEST_ID_TTL
, MIN_REQUEST_ID_TTL
, MAX_REQUEST_ID_TTL
, MIN_REQUEST_ID_CACHE_HW
}, 'number');
const zeroRequestBuf = Buffer.alloc(REQUEST_LOG_ENTRY_LENGTH, 0)
, entryCheckpointDataBuf = Buffer.from(ENTRY_CHECKPOINT_DATA)
, logEntryTypeBuffers = {
[LOG_ENTRY_TYPE_STATE]: Buffer.from([LOG_ENTRY_TYPE_STATE])
, [LOG_ENTRY_TYPE_CONFIG]: Buffer.from([LOG_ENTRY_TYPE_CONFIG])
, [LOG_ENTRY_TYPE_CHECKPOINT]: Buffer.from([LOG_ENTRY_TYPE_CHECKPOINT])
};
const CACHE_INDEX_FILES_LIMIT_CAPACITY_LO = 50
, CACHE_INDEX_FILES_LIMIT_CAPACITY_HI = 75
assert(CACHE_INDEX_FILES_LIMIT_CAPACITY_HI > CACHE_INDEX_FILES_LIMIT_CAPACITY_LO);
const debug = require('debug')('zmq-raft:filelog');
const indexFileCache$ = Symbol("indexFileCache")
, indexFileNames$ = Symbol("indexFileNames")
, lastIndexFile$ = Symbol("lastIndexFile")
, requestDb$ = Symbol("requestDb")
, rdbCleanInterval$ = Symbol("rdbCleanInterval");
const isUInt = (v) => ('number' === typeof v && v % 1 === 0 && v >= 0 && v <= MAX_SAFE_INTEGER)
, isValidTerm = isUInt
, isValidIndex = isUInt;
const createFileLogOptions = createOptionsFactory({
readOnly: false
, indexFileCapacity: DEFAULT_CAPACITY
, requestIdTtl: DEFAULT_REQUEST_ID_TTL
, requestIdCacheMax: null
});
/*
TODO: long lived request ids
FileLog
=======
only one process/thread can update the log
type: 0 state
type: 1 cluster config
type: 2 checkpoint
log entry format
offs. content
0 | 12-bytes request id
12 | 1 byte entry type
13 | 7-byte LSB unsigned long term
20 | data
snapshoting log:
1. determine offset
2. create snapshot
3. replace current snapshot with a new snapshot
4. delete log before last snapshot offset + 1
4a. find first file
4b. if the whole file < first index delete file, next file, repeat
dirs:
log/8765/43/21/87654321000000-87654321003FFF
log/8765/43/21/87654321FF0000-87654321FFFFFF
rolling criteria:
- N index entries boundary (N & 65536)
- max data size (<2^31)
*/
class FileLog extends ReadyEmitter {
/**
* Creates an instance of a new FileLog.
*
* @param {string} logdir - a path to the directory where the root of the log file structure
* will be created.
* @param {string} snapshot - a path to the snapshot file (existing or to be created).
* @param {Object|boolean} [options|readOnly] - pass `true` to open in read only mode.
*
* options:
* - readOnly {boolean}: if the FileLog should be opened in a read only mode.
* - indexFileCapacity {number}: the IndexFile capacity when creating a new file log.
* - requestIdTtl {number|null}: an updating request IDs' Time-To-Live in milliseconds,
* null disables all time based checks, default: 8 hours.
* - requestIdCacheMax {number|null}: sets high water mark for capacity of updating
* request IDs' cache, default: null.
*
* At least one of the options: requestIdTtl or requestIdCacheMax should be non-null.
* Otherwise an error will be thrown.
*
* @return {FileLog}
**/
constructor(logdir, snapshot, options) {
super();
if (!logdir || 'string' !== typeof logdir) throw new TypeError("FileLog: first argument must be a directory name");
defineConst(this, 'logdir', logdir);
if (!snapshot || 'string' !== typeof snapshot) throw new TypeError("FileLog: second argument must be a path to the snapshot file");
if (path.resolve(snapshot).startsWith(path.resolve(logdir))) {
throw new TypeError("FileLog: snapshot must not be placed in the log sub-directory");
}
if (options === true || options === false) {
options = {readOnly: options};
}
options = createFileLogOptions(options);
var readOnly = !!options.readOnly;
var indexFileCapacity = validateIntegerOption(options, 'indexFileCapacity', MIN_CAPACITY, MAX_CAPACITY);
if (!isPowerOfTwo32(indexFileCapacity)) {
throw new Error("FileLog: indexFileCapacity should be a power of 2");
}
defineConst(this, 'requestIdTtl', (options.requestIdTtl === null)
? null
: validateIntegerOption(options, 'requestIdTtl', MIN_REQUEST_ID_TTL, MAX_REQUEST_ID_TTL));
defineConst(this, 'requestIdCacheMax', (options.requestIdCacheMax === null)
? null
: validateIntegerOption(options, 'requestIdCacheMax', MIN_REQUEST_ID_CACHE_HW));
if (this.requestIdTtl == null && this.requestIdCacheMax == null) {
throw new Error("FileLog: options requestIdTtl and requestIdCacheMax must not be null at the same time");
}
defineConst(this, 'hasRequestExpired', makeHasRequestExpired(this.requestIdTtl));
this[indexFileCache$] = new IndexFileCache(this);
this[indexFileNames$] = new Map();
this[requestDb$] = new Map();
this[rdbCleanInterval$] = null;
this._appendQueue = [];
this._termBufferLastTerm = Symbol();
this._termBuffer = null;
initializeLogFile.call(this, logdir, snapshot, readOnly, indexFileCapacity)
.then(() => {
debug('first index: %s, last index: %s, last term: %s', this.firstIndex, this.lastIndex, this.lastTerm);
this[Symbol.for('setReady')]();
})
.catch(err => this.error(err));
}
/**
* closes FileLog instance
*
* @return {Promise}
**/
close() {
var snapshot = this.snapshot;
return synchronize(this, () => {
if (!snapshot) return;
debug('closing');
if (this.installSnapshotWatcher) {
this.installSnapshotWatcher.close();
this.installSnapshotWatcher = null;
}
clearInterval(this[rdbCleanInterval$]);
this[rdbCleanInterval$] = null;
this[lastIndexFile$] = null;
var promises = [this[indexFileCache$].close(), snapshot.close()];
this[indexFileNames$].clear();
this[indexFileCache$] = null;
this[indexFileNames$] = null;
this.snapshot = null;
return Promise.all(promises);
});
}
/**
* returns log entry index for the first (the oldest) update request id
* that is still remembered (and probably still fresh)
*
* this can be helpfull to determine up to which index it's safe to prune log entry files
* after installing log compaction snapshot
*
* @return {number|undefined}
**/
getFirstFreshIndex() {
for(var index of this[requestDb$].values()) break;
return index;
}
/**
* returns log entry index for a given update request id
*
* requestId must be fresh enough to be remembered
*
* @param {string|Buffer} requestId
* @return {number|undefined}
**/
getRid(requestId) {
if ('string' === typeof requestId && requestId.length === REQUEST_LOG_ENTRY_BASE64_LENGTH) {
return this[requestDb$].get(requestId);
}
else if (isBuffer(requestId) && requestId.length === REQUEST_LOG_ENTRY_LENGTH) {
return this[requestDb$].get(requestId.toString('base64'));
}
throw new TypeError("FileLog.getRid: requestId must be a 16 characters base64 string or a 12 byte buffer");
}
/**
* appends a checkpoint type entry to the log with the given term
*
* resolves to new entry's index
*
* @param {number} term
* @return {Promise}
**/
appendCheckpoint(term) {
return this.appendEntry(zeroRequestBuf, LOG_ENTRY_TYPE_CHECKPOINT, term, entryCheckpointDataBuf);
}
/**
* appends a state type entry to the log with the given term
*
* resolves to new entry's index
*
* @param {string|Buffer} requestId
* @param {number} term
* @param {Buffer} data
* @return {Promise}
**/
appendState(requestId, term, data) {
return this.appendEntry(requestId, LOG_ENTRY_TYPE_STATE, term, data);
}
/**
* appends a config type entry to the log with the given term
*
* resolves to new entry's index
*
* @param {string|Buffer} requestId
* @param {number} term
* @param {Buffer} data
* @return {Promise}
**/
appendConfig(requestId, term, data) {
return this.appendEntry(requestId, LOG_ENTRY_TYPE_CONFIG, term, data);
}
/**
* appends an entry to the log with the given term
*
* resolves to new entry's index
*
* @param {string|Buffer} requestId
* @param {number} type
* @param {number} term
* @param {Buffer} data
* @return {Promise}
**/
appendEntry(requestId, type, term, data) {
return new Promise((resolve, reject) => {
var logEntryTypeBuf = logEntryTypeBuffers[type];
if (logEntryTypeBuf === undefined) return reject(new TypeError("FileLog.appendEntry: type is invalid"));
if (!isValidTerm(term)) return reject(new Error("FileLog.appendEntry: term is invalid"));
var termBuf = this._getTermBufferCached(term);
if ('string' === typeof requestId && requestId.length === REQUEST_LOG_ENTRY_BASE64_LENGTH) {
requestId = Buffer.from(requestId, 'base64');
} else if (!isBuffer(requestId) || requestId.length !== REQUEST_LOG_ENTRY_LENGTH) {
return reject(new TypeError("FileLog.appendEntry: requestId must be a 16 characters base64 string or a 12 byte buffer"));
}
var appendQueue = this._appendQueue;
debug('appending type: %s entry: (%s) with term: %s pending: %d', type, data.length, term,
appendQueue.push({resolve, reject, entry: [requestId, logEntryTypeBuf, termBuf, data]})
);
synchronize(this, () => {
if (appendQueue.length === 0) return;
var queue = appendQueue.splice(0)
, entries = queue.map(({entry}) => entry);
return this._writeEntries(entries)
.then(() => {
var firstIndex = this.lastIndex - queue.length + 1;
queue.forEach(({resolve}, index) => resolve(firstIndex + index));
});
})
.catch(err => {
queue.forEach(({reject}) => reject(err));
});
});
}
_getTermBufferCached(term) {
if (this._termBufferLastTerm === term) {
return this._termBuffer;
}
var termBuffer = this._termBuffer = Buffer.allocUnsafe(7);
this._termBufferLastTerm = term;
writeBufUIntLE(term, termBuffer, 0, 7);
return termBuffer;
}
/**
* appends log entries to the log optionally truncating it first to the given index
*
* entries must consist of buffers representing properly encoded entry data
*
* provided entries array may be empty
*
* @param {Array} entries
* @param {number} [index]
* @return {Promise}
**/
appendEntries(entries, index) {
if (!isArray(entries) || !entries.every(b => isBuffer(b) && b.length > LOG_ENTRY_HEADER_SIZE)) {
return Promise.reject(new Error("FileLog.appendEntries: entries are invalid"));
}
return synchronize(this, () => this._writeEntries(entries, index));
}
_writeEntries(entries, index) {
if (index === undefined) index = this.lastIndex + 1;
else if (!isValidIndex(index)) throw new Error("FileLog.appendEntries: index is invalid");
const hasRequestExpired = this.hasRequestExpired;
return this._truncate(index).then(() => {
const firstIndex = index
, numEntries = entries.length;
if (numEntries === 0) return; /* already truncated, no-op */
const rdb = this[requestDb$];
const write = (indexFile, index, entries) => indexFile.writev(entries, index)
.then(([numUnwritten, nextEntry]) => {
var lastWritten = nextEntry - index - 1
, entry, requestKey, requestId
, i;
this[lastIndexFile$] = indexFile;
if (lastWritten >= 0) {
for(i = 0; i <= lastWritten; ++i) {
entry = entries[i];
if (entry.length === 4) { // entry is an array of buffers from appendEntry
requestId = entry[0];
if (!zeroRequestBuf.equals(requestId)
&& !hasRequestExpired(requestId, 0)) {
requestKey = requestId.toString('base64');
rdb.set(requestKey, index + i);
}
}
else { // entry is a buffer
if (zeroRequestBuf.compare(entry, REQUEST_LOG_ENTRY_OFFSET, REQUEST_LOG_ENTRY_END) !== 0
&& !hasRequestExpired(entry, REQUEST_LOG_ENTRY_OFFSET)) {
requestKey = entry.toString('base64', REQUEST_LOG_ENTRY_OFFSET, REQUEST_LOG_ENTRY_END);
rdb.set(requestKey, index + i);
}
}
}
this.lastIndex = nextEntry - 1;
entry = entries[lastWritten];
if (entry.length === 4) {
this.lastTerm = readBufUIntLE(entry[2], 0, 7);
}
else {
this.lastTerm = readBufUIntLE(entry, TERM_LOG_ENTRY_OFFSET, LOG_ENTRY_HEADER_SIZE);
}
}
if (numUnwritten !== 0) {
return this._createNewIndexFile(indexFile, indexFile => write(indexFile, nextEntry, entries.slice(-numUnwritten)));
}
else {
debug('appended log (%s) indexes: %s - %s last term: %s', numEntries, firstIndex, this.lastIndex, this.lastTerm);
}
});
return this._lastIndexFile(indexFile => write(indexFile, index, entries));
});
}
_truncate(index) {
var nextIndex = this.lastIndex + 1;
if (index < this.firstIndex || index > nextIndex) return Promise.reject(new Error("FileLog.truncate: index out of index range"));
if (index === nextIndex) return Promise.resolve(); /* no-op */
var lastIndex = index - 1;
const rdb = this[requestDb$], rdbsize = rdb.size;
for(let [key, idx] of rdb) {
if (idx >= index) rdb.delete(key);
}
debug('truncating log before: %s last: %s rdb: -%s', index, this.lastIndex, rdbsize - rdb.size);
var truncate = (lastIndexFile) => {
if (lastIndexFile.allowed(lastIndex)) {
return lockExclusive(lastIndexFile, () => readTermAt(lastIndexFile, lastIndex).then(term => {
this.lastIndex = lastIndex;
this.lastTerm = term;
return lastIndexFile.truncate(index);
}));
}
else if (index === this.firstIndex && index === lastIndexFile.firstAllowedIndex) {
return lockExclusive(lastIndexFile, () => {
this.lastIndex = lastIndex;
this.lastTerm = this.snapshot.logTerm;
return lastIndexFile.truncate(index);
});
}
else {
return this._indexFileOf(lastIndexFile.firstAllowedIndex - 1,
prevIndexFile => readTermAt(prevIndexFile, prevIndexFile.lastAllowedIndex)
.then(term => {
this.lastIndex = prevIndexFile.lastAllowedIndex;
this.lastTerm = term;
this[lastIndexFile$] = prevIndexFile;
this[indexFileCache$].delete(lastIndexFile.basename);
debug('deleting log file: %s', lastIndexFile);
return lockExclusive(lastIndexFile, () => lastIndexFile.destroy().then(() => {
this._pruneFileNamesCache(lastIndexFile.basename);
return prevIndexFile;
}));
})
).then(truncate);
}
};
return this._lastIndexFile().then(truncate);
}
/**
* Create a LogWriter instance
*
* example:
*
* var client = new ZmqRaftClient(url);
* var logwriter = log.createLogEntryWriteStream();
* client.requestEntriesStream(0).pipe(logwriter).on('finish', () => logwriter.commit())
*
* @return {LogWriter}
**/
createLogEntryWriteStream() {
return new LogWriter(this);
}
_writeEntryUncommitted(entry, index) {
var nextIndex = this.lastIndex + 1;
return this._truncate(index > nextIndex ? nextIndex
: index).then(() => {
const write = (indexFile) => indexFile.write(entry, index, true)
.then(([numUnwritten]) => {
this[lastIndexFile$] = indexFile;
if (numUnwritten === 0) {
if (zeroRequestBuf.compare(entry, REQUEST_LOG_ENTRY_OFFSET, REQUEST_LOG_ENTRY_END) !== 0
&& !this.hasRequestExpired(entry, REQUEST_LOG_ENTRY_OFFSET)) {
this[requestDb$].set(entry.toString('base64', REQUEST_LOG_ENTRY_OFFSET, REQUEST_LOG_ENTRY_END), index);
}
}
else {
return this._commitIndexFile(indexFile)
.then(() => this._createNewIndexFile(indexFile, indexFile => write(indexFile)));
}
});
return this._lastIndexFile(indexFile => write(indexFile));
});
}
_commitIndexFile(indexFile) {
return indexFile.commit()
.then(nextIndex => {
var lastIndex = nextIndex - 1;
if (this.lastIndex !== lastIndex) {
return readTermAt(indexFile, lastIndex).then(lastTerm => {
this.lastIndex = lastIndex;
this.lastTerm = lastTerm;
});
}
});
}
_commitLastIndexFile() {
return this._lastIndexFile(indexFile => this._commitIndexFile(indexFile));
}
/**
* read log entry at the given index into the buffer
*
* resolves to a buffer or a buffer slice containing the whole entry data
*
* if buffer is not provided or is too small a new buffer will be created
*
* @param {number} index
* @param {Buffer} [buffer]
* @return {Promise}
**/
getEntry(index, buffer) {
return this._indexFileOf(index, indexFile => {
if (isBuffer(buffer) && buffer.length >= indexFile.getByteSize(index, 1)) {
return indexFile.readb(index, 1, buffer, 0).then(length => buffer.slice(0, length));
}
else return indexFile.read(index, 1);
});
}
/**
* read log entries from the given first index up to the last index
*
* resolves to an array of buffers, each buffer representing an entry
*
* @param {number} firstIndex
* @param {number} lastIndex
* @return {Promise}
**/
getEntries(firstIndex, lastIndex) {
if (lastIndex > this.lastIndex) return Promise.reject(new Error("FileLog.getEntries: lastIndex too large"));
const result = [];
if (lastIndex < firstIndex) return Promise.resolve(result);
const next = (index) => this._indexFileOf(index, indexFile => {
const maxIndex = min(indexFile.lastAllowedIndex, lastIndex);
return indexFile.readv(index, maxIndex - index + 1);
})
.then(entries => {
push.apply(result, entries);
const nextIndex = index + entries.length;
return (nextIndex <= lastIndex) ? next(nextIndex) : result;
});
return next(firstIndex);
}
/**
* read log entries from the given first index up to the last index
*
* reads as many entries as fits into the given buffer
* if the provided buffer is too small a new buffer will be created
* of the same size as the first entry
*
* resolves to an array of buffer views, each buffer representing an entry
*
* @param {number} firstIndex
* @param {number} lastIndex
* @param {Buffer} buffer
* @return {Promise}
**/
readEntries(firstIndex, lastIndex, buffer) {
const buflen = buffer.length;
if (lastIndex > this.lastIndex) return Promise.reject(new Error("FileLog.readEntries: lastIndex too large"));
const result = [];
if (lastIndex < firstIndex) return Promise.resolve(result);
var offset = 0;
const next = (index) => this._indexFileOf(index, indexFile => {
const maxIndex = min(indexFile.lastAllowedIndex, lastIndex)
, count = indexFile.countEntriesFitSize(index, maxIndex - index + 1, buflen - offset);
if (count !== 0) return indexFile.readb(index, count, buffer, offset)
.then(size => {
assert(size > 0);
const entries = indexFile.splitb(index, count, buffer, offset);
push.apply(result, entries);
offset += size;
return index + count;
});
else return lastIndex + 1;
})
.then(nextIndex => {
if (nextIndex <= lastIndex) {
return next(nextIndex);
}
else if (result.length === 0) {
/* nothing fit into the buffer */
debug('won\'t fit index: %s in %s', firstIndex, buflen);
return this.getEntry(firstIndex).then(entry => [entry]);
}
else return result;
});
return next(firstIndex);
}
/**
* Create a LogStream instance that streams file log entries
*
* @param {number} firstIndex - first index to read
* @param {number} lastIndex - last index to read
* @param {Object} [options] - LogStream options
* @return {LogStream}
**/
createEntriesReadStream(firstIndex, lastIndex, options) {
if (!isValidIndex(firstIndex) || firstIndex < this.firstIndex || firstIndex > this.lastIndex) {
throw new TypeError("FileLog.streamEntries: firstIndex must be a valid index");
}
if (!isValidIndex(lastIndex) || lastIndex < this.firstIndex || lastIndex > this.lastIndex) {
throw new TypeError("FileLog.streamEntries: lastIndex must be a valid index");
}
return new LogStream(this, firstIndex, lastIndex, options);
}
/**
* read a term at the given index
*
* resolves to {number}
*
* @param {number} index
* @return {Promise}
**/
termAt(index) {
/* hot paths */
if (index === this.lastIndex) return Promise.resolve(this.lastTerm);
else if (index === this.snapshot.logIndex) return Promise.resolve(this.snapshot.logTerm);
else if (index < this.firstIndex || index > this.lastIndex) return Promise.resolve();
/* slow path */
return this._indexFileOf(index, indexFile => readTermAt(indexFile, index));
}
/**
* creates a temporary snapshot file in the same directory as the current snapshot
*
* when the snapshot is complete one can install it with installSnapshot method
*
* @param {number} index - snapshot index
* @param {number} term - snapshot term
* @param {number|stream.Reader} dataSize - snapshot data size or a stream.Reader instance
* @return {Promise}
**/
createTmpSnapshot(index, term, dataSize) {
return new SnapshotFile(createTempName(this.snapshot.filename), index, term, dataSize);
}
/**
* install snapshot file instance replacing current snapshot
*
* @param {SnapshotFile} snapshot - snapshot file instance to install
* @param {boolean} [compactOnly] - allow only compacting snapshot
* @return {Promise}
**/
installSnapshot(snapshot, compactOnly) {
if (snapshot instanceof SnapshotFile) {
if (this.readOnly) Promise.reject(new Error("FileLog is in read-only mode"));
return snapshot.ready().then(() => synchronize(this, () => lockExclusive(this.snapshot, () => {
var currentSnapshot = this.snapshot;
if (snapshot === currentSnapshot) return;
return this.termAt(snapshot.logIndex).then(term => {
if (snapshot.logTerm === term) {
/* compaction snapshot */
debug('installing compaction snapshot index: %s term: %s dataSize: %s', snapshot.logIndex, snapshot.logTerm, snapshot.dataSize);
debug('replacing snapshot index: %s term: %s dataSize: %s', currentSnapshot.logIndex, currentSnapshot.logTerm, currentSnapshot.dataSize);
this.snapshot = snapshot;
this.firstIndex = snapshot.logIndex + 1;
/* TODO: wipe out obsolete log files in the background, this requires synchronization with
any current pending reads that began before this.firstIndex modification */
let retries = 0;
const replace = () => snapshot.replace(currentSnapshot.filename)
.catch(err => {
if (++retries > 10) {
throw err;
}
debug('error while installing snapshot file, retrying: %s', retries);
return delay(250).then(replace);
});
return currentSnapshot.close().then(replace);
}
else if (!compactOnly) {
/* discard the entire log (rename logdir, create new log dir, new index file, new caches etc) */
/* during this operation any attempt to read log files will end up with error */
return currentSnapshot.close().then(() => snapshot.replace(currentSnapshot.filename))
.then(() => createNewLogDirectory.call(this, snapshot));
}
else throw new TypeError("FileLog.installSnapshot: the snapshot is not a compaction of the log");
});
})));
}
else throw new TypeError("FileLog.installSnapshot: the snapshot must be an instance of the SnapshotFile");
}
/**
* watch install snapshot directory for compacting snapshot and install it automatically
*
* emits "snapshot" event on FileLog instance every time new snapshot has been installed
*
* @param {string} filename - install snapshot filename
* @return {Promise}
**/
watchInstallSnapshot(filename) {
const dirname = path.dirname(filename)
, basename = path.basename(filename);
debug('watching install snapshot file: %s', filename);
return synchronize(this, () => mkdirp(dirname)
.then(created => {
var watcher = this.installSnapshotWatcher;
if (created) debug('created install snapshot directory: %s', dirname);
if (watcher) {
watcher.close();
debug('install snapshot watcher closed');
this.installSnapshotWatcher = null;
}
const checkWatcher = () => (watcher && this.installSnapshotWatcher === watcher);
const installer = () => {
if (checkWatcher()) {
new SnapshotFile(filename).ready()
.then(snapshot => {
if (checkWatcher()) {
return this.installSnapshot(snapshot, true)
.then(() => this.emit('snapshot')
, (err) => {
console.error('FileLog: snapshot failed to be installed: %s', err);
if (checkWatcher()) {
debug('closing install snapshot watcher');
watcher.close();
this.installSnapshotWatcher = null;
}
});
}
else return snapshot.close();
})
.then(() => checkWatcher() && setTimeout(startWatching, INSTALL_SNAPSHOT_WATCHER_COOLDOWN_INTERVAL).unref())
.catch(err => {
console.error('FileLog: install snapshot failed to open: %s', err);
checkWatcher() && setTimeout(startWatching, INSTALL_SNAPSHOT_WATCHER_COOLDOWN_INTERVAL).unref();
});
}
};
const handler = (type, name) => {
if (type === 'rename' && name === basename) {
watcher.removeListener('change', handler);
installer();
}
};
const startWatching = () => {
if (checkWatcher()) {
access(filename, R_OK | W_OK).then(installer, err => {
if (checkWatcher()) {
watcher.on('change', handler);
debug('install snapshot watching for changes in: %s', filename);
}
});
}
};
this.installSnapshotWatcher = watcher = watch(dirname)
.on('error', err => {
console.error('FileLog: install snapshot watcher error: %s', err);
if (watcher) {
if (this.installSnapshotWatcher === watcher) this.installSnapshotWatcher = null;
watcher.close();
watcher = null;
debug('install snapshot watcher closed');
}
});
startWatching();
}));
}
/**
* feed stateMachine with content of this log
*
* resolves to stateMachine.lastApplied
*
* @param {StateMachineBase} state
* @param {number} [lastIndex]
* @param {number} [currentTerm]
* @return {Promise}
**/
feedStateMachine(stateMachine, lastIndex, currentTerm) {
var snapshot
, firstIndex = this.firstIndex
, lastApplied = stateMachine.lastApplied;
if (lastIndex === undefined) lastIndex = this.lastIndex;
if (currentTerm === undefined) currentTerm = this.lastTerm;
if (lastIndex > this.lastIndex || lastIndex < firstIndex - 1) return Promise.reject(new Error("last index not in the file log range"));
if (lastIndex <= lastApplied) return Promise.resolve(lastApplied);
if (lastApplied < this.snapshot.logIndex) {
snapshot = this.snapshot;
}
else firstIndex = lastApplied + 1;
if (lastIndex - firstIndex < FEED_STATE_NUM_ENTRIES_TRESHOLD) {
return this.getEntries(firstIndex, lastIndex)
.then(entries => stateMachine.applyEntries(entries, firstIndex, currentTerm, snapshot));
}
else return new Promise((resolve, reject) => {
this.createEntriesReadStream(firstIndex, lastIndex)
.on('error', reject)
.pipe(new StateMachineWriter(stateMachine, firstIndex, currentTerm, snapshot))
.on('error', reject)
.on('finish', () => resolve(stateMachine.lastApplied));
});
}
/**
* find the index file path by index
*
* resolves to index file path string
*
* @param {number} index
* @return {Promise}
**/
findIndexFilePathOf(index) {
return this._indexBaseNameOf(index).then(basename => basename && logPath(this.logdir, basename));
}
// firstIndexOfTerm(term) {
// }
/* PRIVATE API */
_createNewIndexFile(lastIndexFile, callback) {
if (this.readOnly) Promise.reject(new Error("FileLog is in read-only mode"));
var index = lastIndexFile.lastAllowedIndex + 1;
var basename = logBaseName(index);
lastIndexFile = this[indexFileCache$].get(basename);
if (!lastIndexFile) {
debug('creating new index file: %s', index);
lastIndexFile = new IndexFile(this.logdir, index, this.indexFileCapacity);
this[indexFileCache$].add(lastIndexFile);
this._pruneFileNamesCache(basename);
}
return lockShared(lastIndexFile, () => lastIndexFile.ready().then(callback));
}
_lastIndexFile(callback) {
if (this.readOnly) Promise.reject(new Error("FileLog is in read-only mode"));
const lastIndexFile = this[lastIndexFile$];
if (callback) return lockShared(lastIndexFile, () => lastIndexFile.ready().then(callback));
return lastIndexFile.ready();
}
_indexFileOf(index, callback) {
const lastIndexFile = this[lastIndexFile$];
if (lastIndexFile && lastIndexFile.isReady && lastIndexFile.includes(index)) {
/* hot path */
return lockShared(lastIndexFile, () => {
if (callback) return lastIndexFile.ready().then(callback);
else return lastIndexFile.ready();
});
}
const found = (basename) => {
if (basename !== undefined && index <= this.lastIndex) {
var indexFile = this[indexFileCache$].get(basename);
if (indexFile === undefined) {
debug('opening index file: %s', basename);
indexFile = new IndexFile(logPath(this.logdir, basename));
this[indexFileCache$].add(indexFile);
}
return lockShared(indexFile, ()=> indexFile.ready().then(indexFile => {
if (!indexFile.includes(index)) {
throw new Error("FileLog: could not find index file for: " + index.toString(16));
}
if (callback) return callback(indexFile);
return indexFile;
}));
}
throw new Error("FileLog: could not find index file for: " + index.toString(16));
};
return this._indexBaseNameOf(index).then(found);
}
/* refresh indexFileNames when files destroyed/new created */
_pruneFileNamesCache(index) {
var basename = logBaseName(index);
var prefix = basename.substr(0, INDEX_PATH_PREFIX_LENGTH);
this[indexFileNames$].delete(prefix);
}
_indexBaseNameOf(index) {
if (index < 1 || index > this.lastIndex) return Promise.resolve();
var basename = logBaseName(index);
var prefix = basename.substr(0, INDEX_PATH_PREFIX_LENGTH);
var indexFileNames = this[indexFileNames$];
var proment = indexFileNames.get(prefix);
if (proment === undefined) {
debug('no cached names for prefix: %s, reading directory', prefix);
proment = readdir(path.dirname(logPath(this.logdir, basename)))
.then(entries => entries.filter(file => file.length === INDEX_FILENAME_LENGTH && file.endsWith(INDEX_FILE_EXT))
.map(file => file.substr(0, INDEX_BASENAME_LENGTH))
.sort());
indexFileNames.set(prefix, proment);
}
return proment.then(entries => bSearch(entries, basename));
}
_findRealLastIndexFile(firstIndexFile, lastIndexFile, readOnly) {