-
Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathFSExtentStore.ts
677 lines (607 loc) · 20 KB
/
FSExtentStore.ts
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
import {
close,
createReadStream,
createWriteStream,
fdatasync,
truncate,
mkdir,
open,
stat,
unlink
} from "fs";
import multistream = require("multistream");
import { join } from "path";
import { Writable } from "stream";
import { promisify } from "util";
import uuid = require("uuid");
import { ZERO_EXTENT_ID } from "../../blob/persistence/IBlobMetadataStore";
import ILogger from "../ILogger";
import BufferStream from "../utils/BufferStream";
import {
DEFAULT_MAX_EXTENT_SIZE,
DEFAULT_READ_CONCURRENCY
} from "../utils/constants";
import { rimrafAsync } from "../utils/utils";
import ZeroBytesStream from "../ZeroBytesStream";
import IExtentMetadataStore, { IExtentModel } from "./IExtentMetadataStore";
import IExtentStore, {
IExtentChunk,
StoreDestinationArray
} from "./IExtentStore";
import IOperationQueue from "./IOperationQueue";
import OperationQueue from "./OperationQueue";
const statAsync = promisify(stat);
const mkdirAsync = promisify(mkdir);
const unlinkAsync = promisify(unlink);
const truncateAsync = promisify(truncate);
// The max size of an extent.
const MAX_EXTENT_SIZE = DEFAULT_MAX_EXTENT_SIZE;
enum AppendStatusCode {
Idle,
Appending
}
interface IAppendExtent {
id: string;
offset: number;
appendStatus: AppendStatusCode; // 0 for idle, 1 for appending
locationId: string;
fd?: number;
}
const openAsync = promisify(open);
const closeAsync = promisify(close);
/**
* Persistency layer data store source implementation interacting with the storage media.
* It provides the methods to read and write data with the storage.
*
* @export
* @class FSExtentStore
* @implements {IExtentStore}
*/
export default class FSExtentStore implements IExtentStore {
private readonly metadataStore: IExtentMetadataStore;
private readonly appendQueue: IOperationQueue;
private readonly readQueue: IOperationQueue;
private initialized: boolean = false;
private closed: boolean = true;
// The active extents to be appended data.
private activeWriteExtents: IAppendExtent[];
private activeWriteExtentsNumber: number;
private persistencyPath: Map<string, string>;
public constructor(
metadata: IExtentMetadataStore,
private readonly persistencyConfiguration: StoreDestinationArray,
private readonly logger: ILogger
) {
this.activeWriteExtents = [];
this.persistencyPath = new Map<string, string>();
for (const storeDestination of persistencyConfiguration) {
this.persistencyPath.set(
storeDestination.locationId,
storeDestination.locationPath
);
for (let i = 0; i < storeDestination.maxConcurrency; i++) {
const appendExtent = this.createAppendExtent(
storeDestination.locationId
);
this.activeWriteExtents.push(appendExtent);
}
}
this.activeWriteExtentsNumber = this.activeWriteExtents.length;
this.metadataStore = metadata;
this.appendQueue = new OperationQueue(
this.activeWriteExtentsNumber,
logger
);
this.readQueue = new OperationQueue(DEFAULT_READ_CONCURRENCY, logger);
}
public isInitialized(): boolean {
return this.initialized;
}
public isClosed(): boolean {
return this.closed;
}
public async init(): Promise<void> {
for (const storeDestination of this.persistencyConfiguration) {
try {
await statAsync(storeDestination.locationPath);
} catch {
await mkdirAsync(storeDestination.locationPath);
}
}
if (!this.metadataStore.isInitialized()) {
await this.metadataStore.init();
}
this.initialized = true;
this.closed = false;
}
public async close(): Promise<void> {
if (!this.metadataStore.isClosed()) {
await this.metadataStore.close();
}
this.closed = true;
}
public async clean(): Promise<void> {
if (this.isClosed()) {
for (const path of this.persistencyConfiguration) {
try {
await rimrafAsync(path.locationPath);
} catch {
// TODO: Find out why sometimes it throws no permission error
/* NOOP */
}
}
return;
}
throw new Error(`Cannot clean FSExtentStore, it's not closed.`);
}
/**
* This method may create a new extent or append data to an existing extent.
* Return the extent chunk information including the extentId, offset and count.
*
* @param {(NodeJS.ReadableStream | Buffer)} data
* @param {string} [contextId]
* @returns {Promise<IExtentChunk>}
* @memberof FSExtentStore
*/
public async appendExtent(
data: NodeJS.ReadableStream | Buffer,
contextId?: string
): Promise<IExtentChunk> {
const op = () =>
new Promise<IExtentChunk>((resolve, reject) => {
(async (): Promise<IExtentChunk> => {
let appendExtentIdx = 0;
for (let i = 1; i < this.activeWriteExtentsNumber; i++) {
if (
this.activeWriteExtents[i].appendStatus === AppendStatusCode.Idle
) {
appendExtentIdx = i;
break;
}
}
this.activeWriteExtents[appendExtentIdx].appendStatus =
AppendStatusCode.Appending;
this.logger.info(
`FSExtentStore:appendExtent() Select extent from idle location for extent append operation. LocationId:${appendExtentIdx} extentId:${this.activeWriteExtents[appendExtentIdx].id} offset:${this.activeWriteExtents[appendExtentIdx].offset} MAX_EXTENT_SIZE:${MAX_EXTENT_SIZE} `,
contextId
);
if (
this.activeWriteExtents[appendExtentIdx].offset >= MAX_EXTENT_SIZE
) {
this.logger.info(
`FSExtentStore:appendExtent() Size of selected extent offset is larger than maximum extent size ${MAX_EXTENT_SIZE} bytes, try appending to new extent.`,
contextId
);
const selectedFd = this.activeWriteExtents[appendExtentIdx].fd;
if (selectedFd) {
this.logger.info(
`FSExtentStore:appendExtent() Close unused fd:${selectedFd}.`,
contextId
);
try {
await closeAsync(selectedFd);
} catch (err) {
this.logger.error(
`FSExtentStore:appendExtent() Close unused fd:${selectedFd} error:${JSON.stringify(
err
)}.`,
contextId
);
}
}
await this.getNewExtent(this.activeWriteExtents[appendExtentIdx]);
this.logger.info(
`FSExtentStore:appendExtent() Allocated new extent LocationID:${appendExtentIdx} extentId:${this.activeWriteExtents[appendExtentIdx].id} offset:${this.activeWriteExtents[appendExtentIdx].offset} MAX_EXTENT_SIZE:${MAX_EXTENT_SIZE} `,
contextId
);
}
let rs: NodeJS.ReadableStream;
if (data instanceof Buffer) {
rs = new BufferStream(data);
} else {
rs = data;
}
const appendExtent = this.activeWriteExtents[appendExtentIdx];
const id = appendExtent.id;
const path = this.generateExtentPath(appendExtent.locationId, id);
let fd = appendExtent.fd;
this.logger.debug(
`FSExtentStore:appendExtent() Get fd:${fd} for extent:${id} from cache.`,
contextId
);
if (fd === undefined) {
fd = await openAsync(path, "a");
appendExtent.fd = fd;
this.logger.debug(
`FSExtentStore:appendExtent() Open file:${path} for extent:${id}, get new fd:${fd}`,
contextId
);
}
const ws = createWriteStream(path, {
fd,
autoClose: false
});
this.logger.debug(
`FSExtentStore:appendExtent() Created write stream for fd:${fd}`,
contextId
);
let count = 0;
this.logger.debug(
`FSExtentStore:appendExtent() Start writing to extent ${id}`,
contextId
);
try {
count = await this.streamPipe(rs, ws, fd, contextId);
const offset = appendExtent.offset;
appendExtent.offset += count;
const extent: IExtentModel = {
id,
locationId: appendExtent.locationId,
path: id,
size: count + offset,
lastModifiedInMS: Date.now()
};
this.logger.debug(
`FSExtentStore:appendExtent() Write finish, start updating extent metadata. extent:${JSON.stringify(
extent
)}`,
contextId
);
await this.metadataStore.updateExtent(extent);
this.logger.debug(
`FSExtentStore:appendExtent() Update extent metadata done. Resolve()`,
contextId
);
appendExtent.appendStatus = AppendStatusCode.Idle;
return {
id,
offset,
count
};
} catch (err) {
// Reset cursor position to the current offset. On Windows, truncating a file open in append mode doesn't
// work, so we need to close the file descriptor first.
try {
appendExtent.fd = undefined;
await closeAsync(fd);
await truncateAsync(path, appendExtent.offset);
// Indicate that the extent is ready for the next append operation.
appendExtent.appendStatus = AppendStatusCode.Idle;
} catch (truncate_err) {
this.logger.error(
`FSExtentStore:appendExtent() Truncate path:${path} len: ${appendExtent.offset} error:${JSON.stringify(
truncate_err
)}.`,
contextId
);
}
throw err;
}
})()
.then(resolve)
.catch(reject);
});
return this.appendQueue.operate(op, contextId);
}
/**
* Read data from persistency layer according to the given IExtentChunk.
*
* @param {IExtentChunk} [extentChunk]
* @returns {Promise<NodeJS.ReadableStream>}
* @memberof FSExtentStore
*/
public async readExtent(
extentChunk?: IExtentChunk,
contextId?: string
): Promise<NodeJS.ReadableStream> {
if (extentChunk === undefined || extentChunk.count === 0) {
return new ZeroBytesStream(0);
}
if (extentChunk.id === ZERO_EXTENT_ID) {
const subRangeCount = Math.min(extentChunk.count);
return new ZeroBytesStream(subRangeCount);
}
const persistencyId = await this.metadataStore.getExtentLocationId(
extentChunk.id
);
const path = this.generateExtentPath(persistencyId, extentChunk.id);
const op = () =>
new Promise<NodeJS.ReadableStream>((resolve, reject) => {
this.logger.verbose(
`FSExtentStore:readExtent() Creating read stream. LocationId:${persistencyId} extentId:${
extentChunk.id
} path:${path} offset:${extentChunk.offset} count:${
extentChunk.count
} end:${extentChunk.offset + extentChunk.count - 1}`,
contextId
);
const stream = createReadStream(path, {
start: extentChunk.offset,
end: extentChunk.offset + extentChunk.count - 1
}).on("close", () => {
this.logger.verbose(
`FSExtentStore:readExtent() Read stream closed. LocationId:${persistencyId} extentId:${
extentChunk.id
} path:${path} offset:${extentChunk.offset} count:${
extentChunk.count
} end:${extentChunk.offset + extentChunk.count - 1}`,
contextId
);
});
resolve(stream);
});
return this.readQueue.operate(op, contextId);
}
/**
* Merge several extent chunks to a ReadableStream according to the offset and count.
*
* @param {(IExtentChunk)[]} extentChunkArray
* @param {number} [offset=0]
* @param {number} [count=Infinity]
* @param {string} [contextId]
* @returns {Promise<NodeJS.ReadableStream>}
* @memberof FSExtentStore
*/
public async readExtents(
extentChunkArray: (IExtentChunk)[],
offset: number = 0,
count: number = Infinity,
contextId?: string
): Promise<NodeJS.ReadableStream> {
this.logger.verbose(
`FSExtentStore:readExtents() Start read from multi extents...`,
contextId
);
if (count === 0) {
return new ZeroBytesStream(0);
}
const start = offset; // Start inclusive position in the merged stream
const end = offset + count; // End exclusive position in the merged stream
const streams: NodeJS.ReadableStream[] = [];
let accumulatedOffset = 0; // Current payload offset in the merged stream
for (const chunk of extentChunkArray) {
const nextOffset = accumulatedOffset + chunk.count;
if (nextOffset <= start) {
accumulatedOffset = nextOffset;
continue;
} else if (end <= accumulatedOffset) {
break;
} else {
let chunkStart = chunk.offset;
let chunkEnd = chunk.offset + chunk.count;
if (start > accumulatedOffset) {
chunkStart = chunkStart + start - accumulatedOffset; // Inclusive
}
if (end <= nextOffset) {
chunkEnd = chunkEnd - (nextOffset - end); // Exclusive
}
streams.push(
await this.readExtent(
{
id: chunk.id,
offset: chunkStart,
count: chunkEnd - chunkStart
},
contextId
)
);
accumulatedOffset = nextOffset;
}
}
// TODO: What happens when count exceeds merged payload length?
// throw an error of just return as much data as we can?
if (end !== Infinity && accumulatedOffset < end) {
throw new RangeError(
// tslint:disable-next-line:max-line-length
`Not enough payload data error. Total length of payloads is ${accumulatedOffset}, while required data offset is ${offset}, count is ${count}.`
);
}
return multistream(streams);
}
/**
* Delete the extents from persistency layer.
*
* @param {Iterable<string>} persistency
* @returns {Promise<number>} Number of extents deleted
* @memberof IExtentStore
*/
public async deleteExtents(extents: Iterable<string>): Promise<number> {
let count = 0;
for (const id of extents) {
// Should not delete active write extents
// Will not throw error because GC doesn't know extent is active, and will call this method to
// delete active extents
if (this.isActiveExtent(id)) {
this.logger.debug(
`FSExtentStore:deleteExtents() Skip deleting active extent:${id}`
);
continue;
}
const locationId = await this.metadataStore.getExtentLocationId(id);
const path = this.generateExtentPath(locationId, id);
this.logger.debug(
`FSExtentStore:deleteExtents() Delete extent:${id} location:${locationId} path:${path}`
);
try {
await unlinkAsync(path);
await this.metadataStore.deleteExtent(id);
} catch (err) {
if (err.code === "ENOENT") {
await this.metadataStore.deleteExtent(id);
}
}
count++;
}
return count;
}
/**
* Return its metadata store.
*
* @returns {IExtentMetadataStore}
* @memberof IExtentStore
*/
public getMetadataStore(): IExtentMetadataStore {
return this.metadataStore;
}
private async streamPipe(
rs: NodeJS.ReadableStream,
ws: Writable,
fd?: number,
contextId?: string
): Promise<number> {
return new Promise<number>((resolve, reject) => {
this.logger.debug(
`FSExtentStore:streamPipe() Start piping data to write stream`,
contextId
);
let count: number = 0;
let wsEnd = false;
rs.on("data", data => {
count += data.length;
if (!ws.write(data)) {
rs.pause();
}
})
.on("end", () => {
this.logger.debug(
`FSExtentStore:streamPipe() Readable stream triggers close event, ${count} bytes piped`,
contextId
);
if (!wsEnd) {
this.logger.debug(
`FSExtentStore:streamPipe() Invoke write stream end()`,
contextId
);
ws.end();
wsEnd = true;
}
})
.on("close", () => {
this.logger.debug(
`FSExtentStore:streamPipe() Readable stream triggers close event, ${count} bytes piped`,
contextId
);
if (!wsEnd) {
this.logger.debug(
`FSExtentStore:streamPipe() Invoke write stream end()`,
contextId
);
ws.end();
wsEnd = true;
}
})
.on("error", err => {
this.logger.debug(
`FSExtentStore:streamPipe() Readable stream triggers error event, error:${JSON.stringify(
err
)}, after ${count} bytes piped. Reject streamPipe().`,
contextId
);
reject(err);
});
ws.on("drain", () => {
rs.resume();
})
.on("finish", () => {
if (typeof fd === "number") {
this.logger.debug(
`FSExtentStore:streamPipe() Writable stream triggers finish event, after ${count} bytes piped. Flush data to fd:${fd}.`,
contextId
);
fdatasync(fd, err => {
if (err) {
this.logger.debug(
`FSExtentStore:streamPipe() Flush data to fd:${fd} failed with error:${JSON.stringify(
err
)}. Reject streamPipe().`,
contextId
);
reject(err);
} else {
this.logger.debug(
`FSExtentStore:streamPipe() Flush data to fd:${fd} successfully. Resolve streamPipe().`,
contextId
);
resolve(count);
}
});
} else {
this.logger.debug(
`FSExtentStore:streamPipe() Resolve streamPipe() without flushing data.`,
contextId
);
resolve(count);
}
})
.on("error", err => {
this.logger.debug(
`FSExtentStore:streamPipe() Writable stream triggers error event, error:${JSON.stringify(
err
)}, after ${count} bytes piped. Reject streamPipe().`,
contextId
);
reject(err);
});
});
}
/**
* Check an extent is one of active extents or not.
*
* @private
* @param {string} id
* @returns {boolean}
* @memberof FSExtentStore
*/
private isActiveExtent(id: string): boolean {
// TODO: Use map instead of array to quick check
for (const extent of this.activeWriteExtents) {
if (extent.id === id) {
return true;
}
}
return false;
}
/**
* Create a new append extent model for a new write directory.
*
* @private
* @param {string} persistencyPath
* @returns {IAppendExtent}
* @memberof FSExtentStore
*/
private createAppendExtent(persistencyId: string): IAppendExtent {
return {
id: uuid(),
offset: 0,
appendStatus: AppendStatusCode.Idle,
locationId: persistencyId
};
}
/**
* Select a new extent to append for an exist write directory.
*
* @private
* @param {IAppendExtent} appendExtent
* @memberof FSExtentStore
*/
private getNewExtent(appendExtent: IAppendExtent) {
appendExtent.id = uuid();
appendExtent.offset = 0;
appendExtent.fd = undefined;
}
/**
* Generate the file path for a new extent.
*
* @private
* @param {string} extentId
* @returns {string}
* @memberof FSExtentStore
*/
private generateExtentPath(persistencyId: string, extentId: string): string {
const directoryPath = this.persistencyPath.get(persistencyId);
if (!directoryPath) {
// To be completed
}
return join(directoryPath!, extentId);
}
}