-
Notifications
You must be signed in to change notification settings - Fork 76
/
namespace_fs.js
2040 lines (1845 loc) · 86.4 KB
/
namespace_fs.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) 2020 NooBaa */
/*eslint max-lines: ["error", 2500]*/
'use strict';
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const util = require('util');
const mime = require('mime');
const { v4: uuidv4 } = require('uuid');
const P = require('../util/promise');
const dbg = require('../util/debug_module')(__filename);
const config = require('../../config');
const s3_utils = require('../endpoint/s3/s3_utils');
const error_utils = require('../util/error_utils');
const stream_utils = require('../util/stream_utils');
const buffer_utils = require('../util/buffer_utils');
const size_utils = require('../util/size_utils');
const ChunkFS = require('../util/chunk_fs');
const LRUCache = require('../util/lru_cache');
const Semaphore = require('../util/semaphore');
const nb_native = require('../util/nb_native');
const RpcError = require('../rpc/rpc_error');
const buffers_pool_sem = new Semaphore(config.NSFS_BUF_POOL_MEM_LIMIT, {
timeout: config.IO_STREAM_SEMAPHORE_TIMEOUT,
timeout_error_code: 'IO_STREAM_ITEM_TIMEOUT',
warning_timeout: config.NSFS_SEM_WARNING_TIMEOUT,
});
const buffers_pool = new buffer_utils.BuffersPool({
buf_size: config.NSFS_BUF_SIZE,
sem: buffers_pool_sem,
warning_timeout: config.NSFS_BUF_POOL_WARNING_TIMEOUT
});
const XATTR_USER_PREFIX = 'user.';
// TODO: In order to verify validity add content_md5_mtime as well
const XATTR_MD5_KEY = XATTR_USER_PREFIX + 'content_md5';
const XATTR_VERSION_ID = XATTR_USER_PREFIX + 'version_id';
const XATTR_PREV_VERSION_ID = XATTR_USER_PREFIX + 'prev_version_id';
const XATTR_DELETE_MARKER = XATTR_USER_PREFIX + 'delete_marker';
const HIDDEN_VERSIONS_PATH = '.versions';
const versioning_status_enum = {
VER_ENABLED: 'ENABLED',
VER_SUSPENDED: 'SUSPENDED',
VER_DISABLED: 'DISABLED'
};
const version_format = /^[a-z0-9]+$/;
// describes the status of the copy that was done, default is fallback
// LINKED = the file was linked on the server side
// IS_SAME_INODE = source and target are the same inode, nothing to copy
// FALLBACK = will be reported when link on server side copy failed
// or on non server side copy
const copy_status_enum = {
LINKED: 'LINKED',
SAME_INODE: 'SAME_INODE',
FALLBACK: 'FALLBACK'
};
/**
* @param {fs.Dirent} a
* @param {fs.Dirent} b
* @returns {1|-1|0}
*/
function sort_entries_by_name(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
function isDirectory(ent) {
if (!ent) throw new Error('isDirectory: ent is empty');
if (ent.mode) {
// eslint-disable-next-line no-bitwise
return (((ent.mode) & nb_native().fs.S_IFMT) === nb_native().fs.S_IFDIR);
} else if (ent.type) {
return ent.type === nb_native().fs.DT_DIR;
} else {
throw new Error(`isDirectory: ent ${ent} is not supported`);
}
}
/**
*
* @param {*} stat - entity stat yo check
* @param {*} fs_context - account config using to check symbolic links
* @param {*} entry_path - path of symbolic link
* @returns
*/
async function is_directory_or_symlink_to_directory(stat, fs_context, entry_path) {
try {
let r = isDirectory(stat);
if (!r && is_symbolic_link(stat)) {
let targetStat = await nb_native().fs.stat(fs_context, entry_path);
if (!targetStat) throw new Error('is_directory_or_symlink_to_directory: targetStat is empty');
r = isDirectory(targetStat);
}
return r;
} catch (err) {
if (err.code !== 'ENOENT') {
throw err;
}
}
}
function is_symbolic_link(stat) {
if (!stat) throw new Error('isSymbolicLink: stat is empty');
if (stat.mode) {
// eslint-disable-next-line no-bitwise
return (((stat.mode) & nb_native().fs.S_IFMT) === nb_native().fs.S_IFLNK);
} else if (stat.type) {
return stat.type === nb_native().fs.DT_LNK;
} else {
throw new Error(`isSymbolicLink: stat ${stat} is not supported`);
}
}
function get_umasked_mode(mode) {
// eslint-disable-next-line no-bitwise
return mode & ~config.NSFS_UMASK;
}
/**
* @param {fs.Dirent} e
* @returns {string}
*/
function get_entry_name(e) {
return e.name;
}
/**
* @param {string} name
* @returns {fs.Dirent}
*/
function make_named_dirent(name) {
const entry = new fs.Dirent();
entry.name = name;
return entry;
}
function to_xattr(fs_xattr) {
const xattr = _.mapKeys(fs_xattr, (val, key) =>
(key.startsWith(XATTR_USER_PREFIX) ? key.slice(XATTR_USER_PREFIX.length) : '')
);
// keys which do not start with prefix will all map to the empty string key, so we remove it once
delete xattr[''];
// @ts-ignore
xattr[s3_utils.XATTR_SORT_SYMBOL] = true;
return xattr;
}
function to_fs_xattr(xattr) {
if (_.isEmpty(xattr)) return undefined;
return _.mapKeys(xattr, (val, key) => XATTR_USER_PREFIX + key);
}
/**
* @typedef {{
* time: number,
* stat: fs.Stats,
* usage: number,
* sorted_entries?: fs.Dirent[],
* }} ReaddirCacheItem
* @type {LRUCache<object, string, ReaddirCacheItem>}
*/
const dir_cache = new LRUCache({
name: 'nsfs-dir-cache',
make_key: ({ dir_path }) => dir_path,
load: async ({ dir_path, fs_context }) => {
const time = Date.now();
const stat = await nb_native().fs.stat(fs_context, dir_path);
let sorted_entries;
let usage = config.NSFS_DIR_CACHE_MIN_DIR_SIZE;
if (stat.size <= config.NSFS_DIR_CACHE_MAX_DIR_SIZE) {
sorted_entries = await nb_native().fs.readdir(fs_context, dir_path);
sorted_entries.sort(sort_entries_by_name);
for (const ent of sorted_entries) {
usage += ent.name.length + 4;
}
}
return { time, stat, sorted_entries, usage };
},
validate: async ({ stat }, { dir_path, fs_context }) => {
const new_stat = await nb_native().fs.stat(fs_context, dir_path);
return (new_stat.ino === stat.ino && new_stat.mtimeNsBigint === stat.mtimeNsBigint);
},
item_usage: ({ usage }, dir_path) => usage,
max_usage: config.NSFS_DIR_CACHE_MAX_TOTAL_SIZE,
});
/**
* NamespaceFS map objets to files in a filesystem.
* @implements {nb.Namespace}
*/
class NamespaceFS {
/**
* @param {{
* bucket_path: string;
* fs_backend?: string;
* bucket_id: string;
* namespace_resource_id?: string;
* access_mode: string;
* versioning: 'DISABLED' | 'SUSPENDED' | 'ENABLED';
* stats: import('./endpoint_stats_collector').EndpointStatsCollector;
* }} params
*/
constructor({
bucket_path,
fs_backend,
bucket_id,
namespace_resource_id,
access_mode,
versioning,
stats,
}) {
dbg.log1('NamespaceFS: buffers_pool length',
buffers_pool.buffers.length, buffers_pool.sem);
this.bucket_path = path.resolve(bucket_path);
this.fs_backend = fs_backend;
this.bucket_id = bucket_id;
this.namespace_resource_id = namespace_resource_id;
this.access_mode = access_mode;
this.versioning = (config.NSFS_VERSIONING_ENABLED && versioning) || versioning_status_enum.VER_DISABLED;
this.stats = stats;
}
prepare_fs_context(object_sdk) {
const fs_context = object_sdk?.requesting_account?.nsfs_account_config;
if (!fs_context) throw new RpcError('UNAUTHORIZED', 'nsfs_account_config is missing');
fs_context.backend = this.fs_backend || '';
fs_context.warn_threshold_ms = config.NSFS_WARN_THRESHOLD_MS;
if (this.stats) fs_context.report_fs_stats = this.stats.update_fs_stats;
return fs_context;
}
get_bucket_tmpdir() {
return config.NSFS_TEMP_DIR_NAME + '_' + this.bucket_id;
}
get_write_resource() {
return this;
}
get_bucket(bucket) {
return bucket;
}
is_server_side_copy(other, params) {
const is_server_side_copy = other instanceof NamespaceFS &&
other.bucket_path === this.bucket_path &&
other.fs_backend === this.fs_backend && //Check that the same backend type
params.xattr_copy; // TODO, DO we need to hard link at MetadataDirective 'REPLACE'?
dbg.log2('NamespaceFS: is_server_side_copy:', is_server_side_copy);
dbg.log2('NamespaceFS: other instanceof NamespaceFS:', other instanceof NamespaceFS,
'other.bucket_path:', other.bucket_path, 'this.bucket_path:', this.bucket_path,
'other.fs_backend', other.fs_backend, 'this.fs_backend', this.fs_backend,
'params.xattr_copy', params.xattr_copy);
return is_server_side_copy;
}
run_update_issues_report(object_sdk, err) {
//We want to avoid the report when we have no error code.
if (!err.code) return;
//In standalone, we want to avoid the report.
if (!this.namespace_resource_id) return;
try {
object_sdk.rpc_client.pool.update_issues_report({
namespace_resource_id: this.namespace_resource_id,
error_code: err.code,
time: Date.now(),
});
} catch (e) {
console.log('update_issues_report on error:', e, 'ignoring.');
}
}
is_readonly_namespace() {
return this.access_mode === 'READ_ONLY';
}
/////////////////
// OBJECT LIST //
/////////////////
/**
* @typedef {{
* bucket: string,
* prefix?: string,
* delimiter?: string,
* key_marker?: string,
* limit?: number,
* }} ListParams
*/
/**
* @param {ListParams} params
*/
async list_objects(params, object_sdk) {
try {
const fs_context = this.prepare_fs_context(object_sdk);
await this._load_bucket(params, fs_context);
const {
bucket,
delimiter = '',
prefix = '',
key_marker = '',
} = params;
if (delimiter && delimiter !== '/') {
throw new Error('NamespaceFS: Invalid delimiter ' + delimiter);
}
const limit = Math.min(1000, _.isUndefined(params.limit) ? 1000 : params.limit);
if (limit < 0) throw new Error('Limit must be a positive Integer');
// In case that we've received max-keys 0, we should return an empty reply without is_truncated
// This is used in order to follow aws spec and behaviour
if (!limit) return { is_truncated: false, objects: [], common_prefixes: [] };
let is_truncated = false;
/**
* @typedef {{
* key: string,
* common_prefix: boolean,
* stat?: fs.Stats,
* }} Result
*/
/** @type {Result[]} */
const results = [];
/**
* @param {string} dir_key
* @returns {Promise<void>}
*/
const process_dir = async dir_key => {
if (this._skip_version_dir(dir_key)) {
return;
}
// /** @type {fs.Dir} */
let dir_handle;
/** @type {ReaddirCacheItem} */
let cached_dir;
const dir_path = path.join(this.bucket_path, dir_key);
const prefix_dir = prefix.slice(0, dir_key.length);
const prefix_ent = prefix.slice(dir_key.length);
if (!dir_key.startsWith(prefix_dir)) {
// dbg.log0(`prefix dir does not match so no keys in this dir can apply: dir_key=${dir_key} prefix_dir=${prefix_dir}`);
return;
}
const marker_dir = key_marker.slice(0, dir_key.length);
const marker_ent = key_marker.slice(dir_key.length);
// marker is after dir so no keys in this dir can apply
if (dir_key < marker_dir) {
// dbg.log0(`marker is after dir so no keys in this dir can apply: dir_key=${dir_key} marker_dir=${marker_dir}`);
return;
}
// when the dir portion of the marker is completely below the current dir
// then every key in this dir satisfies the marker and marker_ent should not be used.
const marker_curr = (marker_dir < dir_key) ? '' : marker_ent;
// dbg.log0(`process_dir: dir_key=${dir_key} prefix_ent=${prefix_ent} marker_curr=${marker_curr}`);
/**
* @param {fs.Dirent} ent
*/
const process_entry = async ent => {
// dbg.log0('process_entry', dir_key, ent.name);
if (!ent.name.startsWith(prefix_ent) ||
ent.name < marker_curr ||
ent.name === this.get_bucket_tmpdir()) {
return;
}
const isDir = await is_directory_or_symlink_to_directory(ent, fs_context, path.join(dir_path, ent.name));
const r = {
key: this._get_entry_key(dir_key, ent, isDir),
common_prefix: isDir,
};
let pos;
if (results.length && r.key < results[results.length - 1].key) {
pos = _.sortedLastIndexBy(results, r, a => a.key);
} else {
pos = results.length;
}
if (pos >= limit) {
is_truncated = true;
return; // not added
}
if (!delimiter && r.common_prefix) {
await process_dir(r.key);
} else {
if (pos < results.length) {
results.splice(pos, 0, r);
} else {
results.push(r);
}
if (results.length > limit) {
results.length = limit;
is_truncated = true;
}
}
};
if (!(await this.check_access(fs_context, dir_path))) return;
try {
cached_dir = await dir_cache.get_with_cache({ dir_path, fs_context });
} catch (err) {
if (err.code === 'ENOENT') {
dbg.log0('NamespaceFS: no keys for non existing dir', dir_path);
return;
}
throw err;
}
if (cached_dir.sorted_entries) {
const sorted_entries = cached_dir.sorted_entries;
const marker_index = _.sortedLastIndexBy(
sorted_entries,
make_named_dirent(marker_curr),
get_entry_name
);
// handling a scenario in which key_marker points to an object inside a directory
// since there can be entries inside the directory that will need to be pushed
// to results array
if (marker_index) {
const prev_dir = sorted_entries[marker_index - 1];
const prev_dir_name = path.join(prev_dir.name, '/');
if (marker_curr.startsWith(prev_dir_name) && dir_key !== prev_dir.name) {
if (!delimiter) {
const isDir = await is_directory_or_symlink_to_directory(
prev_dir, fs_context, path.join(dir_path, prev_dir_name));
if (isDir) {
await process_dir(path.join(dir_key, prev_dir_name));
}
}
}
}
for (let i = marker_index; i < sorted_entries.length; ++i) {
const ent = sorted_entries[i];
// when entry is NSFS_FOLDER_OBJECT_NAME=.folder file,
// and the dir key marker is the name of the curr directory - skip on adding it
if (ent.name === config.NSFS_FOLDER_OBJECT_NAME && dir_key === marker_dir) {
continue;
}
await process_entry(ent);
// since we traverse entries in sorted order,
// we can break as soon as enough keys are collected.
if (is_truncated) break;
}
return;
}
// for large dirs we cannot keep all entries in memory
// so we have to stream the entries one by one while filtering only the needed ones.
try {
dbg.warn('NamespaceFS: open dir streaming', dir_path, 'size', cached_dir.stat.size);
dir_handle = await nb_native().fs.opendir(fs_context, dir_path); //, { bufferSize: 128 });
for (;;) {
const dir_entry = await dir_handle.read(fs_context);
if (!dir_entry) break;
await process_entry(dir_entry);
// since we dir entries streaming order is not sorted,
// we have to keep scanning all the keys before we can stop.
}
await dir_handle.close(fs_context);
dir_handle = null;
} finally {
if (dir_handle) {
try {
dbg.warn('NamespaceFS: close dir streaming', dir_path, 'size', cached_dir.stat.size);
await dir_handle.close(fs_context);
} catch (err) {
dbg.error('NamespaceFS: close dir failed', err);
}
dir_handle = null;
}
}
};
const prefix_dir_key = prefix.slice(0, prefix.lastIndexOf('/') + 1);
await process_dir(prefix_dir_key);
await Promise.all(results.map(async r => {
if (r.common_prefix) return;
const entry_path = path.join(this.bucket_path, r.key);
//If entry is outside of bucket, returns stat of symbolic link
const use_lstat = !(await this._is_path_in_bucket_boundaries(fs_context, entry_path));
r.stat = await nb_native().fs.stat(fs_context, entry_path, { use_lstat });
}));
const res = {
objects: [],
common_prefixes: [],
is_truncated,
next_marker: undefined,
};
for (const r of results) {
if (r.common_prefix) {
res.common_prefixes.push(r.key);
} else {
res.objects.push(this._get_object_info(bucket, r.key, r.stat, 'null'));
}
if (res.is_truncated) {
res.next_marker = r.key;
}
}
return res;
} catch (err) {
throw this._translate_object_error_codes(err);
}
}
async list_object_versions(params, object_sdk) {
// for now we do not support versioning, so returning the same as list objects
return this.list_objects(params, object_sdk);
}
/////////////////
// OBJECT READ //
/////////////////
async read_object_md(params, object_sdk) {
const fs_context = this.prepare_fs_context(object_sdk);
try {
const file_path = await this._find_version_path(fs_context, params);
await this._check_path_in_bucket_boundaries(fs_context, file_path);
await this._load_bucket(params, fs_context);
const stat = await nb_native().fs.stat(fs_context, file_path);
if (isDirectory(stat)) throw error_utils.new_error_code('ENOENT', 'NoSuchKey');
this._throw_if_delete_marker(stat);
return this._get_object_info(params.bucket, params.key, stat, params.version_id || 'null');
} catch (err) {
this.run_update_issues_report(object_sdk, err);
throw this._translate_object_error_codes(err);
}
}
/*
async read_object_stream_SLOW(params, object_sdk, res) {
try {
const fs_context = this.prepare_fs_context(object_sdk);
await this._load_bucket(params, fs_context);
const file_path = await this._find_version_path(fs_context, params);
return fs.createReadStream(file_path, {
highWaterMark: config.NSFS_BUF_SIZE,
start: Number.isInteger(params.start) ? params.start : undefined,
// end offset for files is inclusive, so need to adjust our exclusive end
end: Number.isInteger(params.end) ? params.end - 1 : undefined,
});
} catch (err) {
throw this._translate_object_error_codes(err);
}
}
*/
// eslint-disable-next-line max-statements
async read_object_stream(params, object_sdk, res) {
let file;
let buffer_pool_cleanup = null;
const fs_context = this.prepare_fs_context(object_sdk);
let file_path;
try {
await this._load_bucket(params, fs_context);
file_path = await this._find_version_path(fs_context, params);
await this._check_path_in_bucket_boundaries(fs_context, file_path);
await this._fail_if_archived_or_sparse_file(fs_context, file_path);
const stat = await nb_native().fs.stat(fs_context, file_path);
this._throw_if_delete_marker(stat);
file = await nb_native().fs.open(fs_context, file_path, undefined, get_umasked_mode(config.BASE_MODE_FILE));
const start = Number(params.start) || 0;
const end = isNaN(Number(params.end)) ? Infinity : Number(params.end);
let num_bytes = 0;
let num_buffers = 0;
let log2_size_histogram = {};
let drain_promise = null;
dbg.log0('NamespaceFS: read_object_stream', { file_path, start, end });
let count = 1;
for (let pos = start; pos < end;) {
object_sdk.throw_if_aborted();
// allocate or reuse buffer
// TODO buffers_pool and the underlying semaphore should support abort signal
// to avoid sleeping inside the semaphore until the timeout while the request is already aborted.
const { buffer, callback } = await buffers_pool.get_buffer();
buffer_pool_cleanup = callback; // must be called ***IMMEDIATELY*** after get_buffer
object_sdk.throw_if_aborted();
// read from file
const remain_size = Math.max(0, end - pos);
const read_size = Math.min(buffer.length, remain_size);
const bytesRead = await file.read(fs_context, buffer, 0, read_size, pos);
if (!bytesRead) {
buffer_pool_cleanup = null;
callback();
break;
}
object_sdk.throw_if_aborted();
const data = buffer.slice(0, bytesRead);
// update stats
pos += bytesRead;
num_bytes += bytesRead;
num_buffers += 1;
const log2_size = Math.ceil(Math.log2(bytesRead));
log2_size_histogram[log2_size] = (log2_size_histogram[log2_size] || 0) + 1;
// collect read stats
this.stats?.update_nsfs_read_stats({
namespace_resource_id: this.namespace_resource_id,
bucket_name: params.bucket,
size: bytesRead,
count
});
// clear count for next updates
count = 0;
// wait for response buffer to drain before adding more data if needed -
// this occurs when the output network is slower than the input file
if (drain_promise) {
await drain_promise;
drain_promise = null;
object_sdk.throw_if_aborted();
}
// write the data out to response
buffer_pool_cleanup = null; // cleanup is now in the socket responsibility
const write_ok = res.write(data, null, callback);
if (!write_ok) {
drain_promise = stream_utils.wait_drain(res, { signal: object_sdk.abort_controller.signal });
drain_promise.catch(() => undefined); // this avoids UnhandledPromiseRejection
}
}
await file.close(fs_context);
file = null;
object_sdk.throw_if_aborted();
// wait for the last drain if pending.
if (drain_promise) {
await drain_promise;
drain_promise = null;
object_sdk.throw_if_aborted();
}
// end the stream
res.end();
await stream_utils.wait_finished(res, { signal: object_sdk.abort_controller.signal });
object_sdk.throw_if_aborted();
dbg.log0('NamespaceFS: read_object_stream completed file', file_path, {
num_bytes,
num_buffers,
avg_buffer: num_bytes / num_buffers,
log2_size_histogram,
});
// return null to signal the caller that we already handled the response
return null;
} catch (err) {
dbg.log0('NamespaceFS: read_object_stream error file', file_path, err);
throw this._translate_object_error_codes(err);
} finally {
try {
if (file) {
dbg.log0('NamespaceFS: read_object_stream finally closing file', file_path);
await file.close(fs_context);
}
} catch (err) {
dbg.warn('NamespaceFS: read_object_stream file close error', err);
}
try {
// release buffer back to pool if needed
if (buffer_pool_cleanup) {
dbg.log0('NamespaceFS: read_object_stream finally buffer_pool_cleanup', file_path);
buffer_pool_cleanup();
}
} catch (err) {
dbg.warn('NamespaceFS: read_object_stream buffer pool cleanup error', err);
}
}
}
///////////////////
// OBJECT UPLOAD //
///////////////////
async upload_object(params, object_sdk) {
const fs_context = this.prepare_fs_context(object_sdk);
await this._load_bucket(params, fs_context);
const open_mode = this._is_gpfs(fs_context) ? 'wt' : 'w';
const file_path = this._get_file_path(params);
let upload_params;
try {
await this._check_path_in_bucket_boundaries(fs_context, file_path);
upload_params = await this._start_upload(fs_context, object_sdk, file_path, params, open_mode);
if (!params.copy_source || upload_params.copy_res === copy_status_enum.FALLBACK) {
// TODO: Take up only as much as we need (requires fine-tune of the semaphore inside the _upload_stream)
// Currently we are taking config.NSFS_BUF_SIZE for any sized upload (1KB upload will take a full buffer from semaphore)
upload_params.digest = await buffers_pool_sem.surround_count(
config.NSFS_BUF_SIZE, async () => this._upload_stream(upload_params));
}
const upload_info = await this._finish_upload(upload_params);
return upload_info;
} catch (err) {
this.run_update_issues_report(object_sdk, err);
throw this._translate_object_error_codes(err);
} finally {
try {
if (upload_params && upload_params.target_file) await upload_params.target_file.close(fs_context);
} catch (err) {
dbg.warn('NamespaceFS: upload_object file close error', err);
}
}
}
// creates upload_path if needed
// on copy will call try_copy_file() or fallback
// and opens upload_path (if exists) or file_path
// returns upload params - params that are passed to the called functions in upload_object
async _start_upload(fs_context, object_sdk, file_path, params, open_mode) {
let upload_path;
// upload path is needed only when open_mode is w / for copy
if (open_mode === 'w' || params.copy_source) {
const upload_id = uuidv4();
upload_path = path.join(this.bucket_path, this.get_bucket_tmpdir(), 'uploads', upload_id);
await this._make_path_dirs(upload_path, fs_context);
}
let open_path = upload_path || file_path;
let copy_res = params.copy_source && (await this._try_copy_file(fs_context, params, file_path, upload_path));
if (copy_res) {
if (copy_res === copy_status_enum.FALLBACK) {
params.copy_source.nsfs_copy_fallback();
} else {
// open file after copy link/same inode should use read open mode
open_mode = 'r';
if (copy_res === copy_status_enum.SAME_INODE) open_path = file_path;
}
}
const target_file = await this._open_file(fs_context, open_path, open_mode);
return { fs_context, params, object_sdk, open_mode, file_path, upload_path, target_file, copy_res };
}
// opens open_path on POSIX, and on GPFS it will open open_path parent folder
async _open_file(fs_context, open_path, open_mode) {
const dir_path = path.dirname(open_path);
if ((open_mode === 'wt' || open_mode === 'w') && dir_path !== this.bucket_path) {
dbg.log1(`NamespaceFS._open_file: mode=${open_mode} creating dirs`, open_path, this.bucket_path);
await this._make_path_dirs(open_path, fs_context);
}
dbg.log0(`NamespaceFS._open_file: mode=${open_mode || 'r'}`, open_path);
const actual_open_path = open_mode === 'wt' ? dir_path : open_path;
return nb_native().fs.open(fs_context, actual_open_path, open_mode, get_umasked_mode(config.BASE_MODE_FILE));
}
// on server side copy -
// 1. check if source and target is same inode and return if do nothing if true, status is SAME_INODE
// 2. else we try link - on link success, status is LINKED
// 3. if link failed - status is fallback - read the stream from the source and upload it as regular upload
// on non server side copy - we will immediatly do the fallback
async _try_copy_file(fs_context, params, file_path, upload_path) {
const source_file_path = await this._find_version_path(fs_context, params.copy_source);
await this._check_path_in_bucket_boundaries(fs_context, source_file_path);
await this._fail_if_archived_or_sparse_file(fs_context, source_file_path);
let res = copy_status_enum.FALLBACK;
if (this._is_versioning_disabled()) {
try {
// indicates a retry situation in which the source and target point to the same inode
const same_inode = await this._is_same_inode(fs_context, source_file_path, file_path);
if (same_inode) return copy_status_enum.SAME_INODE;
// Doing a hard link.
await nb_native().fs.link(fs_context, source_file_path, upload_path);
res = copy_status_enum.LINKED;
} catch (e) {
dbg.warn('NamespaceFS: COPY using link failed with:', e);
}
}
return res;
}
// on put part - file path is equal to upload path
// put part upload should NOT contain - versioning & move to dest steps
// if copy status is SAME_INODE - NO xattr replace/move_to_dest
// if copy status is LINKED - NO xattr replace
// xattr_copy = false implies on non server side copy fallback copy (copy status = FALLBACK)
async _finish_upload({ fs_context, params, open_mode, target_file, upload_path, file_path, digest = undefined, copy_res = undefined }) {
const part_upload = file_path === upload_path;
const same_inode = params.copy_source && copy_res === copy_status_enum.SAME_INODE;
let stat = await target_file.stat(fs_context);
this._verify_encryption(params.encryption, this._get_encryption_info(stat));
let fs_xattr;
// handle xattr
if (!params.copy_source || !params.xattr_copy) {
fs_xattr = to_fs_xattr(params.xattr);
if (digest) {
const { md5_b64, key, bucket, upload_id } = params;
if (md5_b64) {
const md5_hex = Buffer.from(md5_b64, 'base64').toString('hex');
if (md5_hex !== digest) throw new Error('_upload_stream mismatch etag: ' + util.inspect({ key, bucket, upload_id, md5_hex, digest }));
}
fs_xattr = this._assign_md5_to_fs_xattr(digest, fs_xattr);
}
if (!part_upload && this._is_versioning_enabled()) {
const cur_ver_info = await this._get_version_info(fs_context, file_path);
fs_xattr = await this._assign_versions_to_fs_xattr(fs_context, cur_ver_info, stat, params.key, fs_xattr);
}
if (fs_xattr) await target_file.replacexattr(fs_context, fs_xattr);
}
// fsync
if (config.NSFS_TRIGGER_FSYNC) await target_file.fsync(fs_context);
dbg.log1('NamespaceFS._finish_upload:', open_mode, file_path, upload_path, fs_xattr);
if (!same_inode && !part_upload) {
await this._move_to_dest(fs_context, upload_path, file_path, target_file, open_mode, { key: params.key });
if (config.NSFS_TRIGGER_FSYNC) await nb_native().fs.fsync(fs_context, path.dirname(file_path));
}
// calc response
// file path is empty in put part, upload path is empty in wt regular upload
stat = await nb_native().fs.stat(fs_context, file_path);
const upload_info = this._get_upload_info(stat, fs_xattr && fs_xattr[XATTR_VERSION_ID]);
return upload_info;
}
// this function handles best effort of files move in posix file systems
// 1. safe_link
// 2. create tmp file
// 2. safe_unlink
async safe_move_posix(fs_context, from_path, to_path, version_info) {
// retry safe linking a file in case of parallel put/delete of the source path
await this._wrap_safe_op_with_retries(
fs_context,
async ({ mtimeNsBigint, ino }) => nb_native().fs.safe_link(fs_context, from_path, to_path, mtimeNsBigint, ino),
Object.assign(version_info || {}, { from_path, to_path }),
'FS::SafeLink ERROR link target doesn\'t match expected inode and mtime'
);
// retry safe unlinking a file in case of parallel put/delete of the source path
await this._wrap_safe_op_with_retries(
fs_context,
async ({ mtimeNsBigint, ino }) => {
const unique_temp_path = await this._generate_unique_path(fs_context);
await nb_native().fs.safe_unlink(fs_context, from_path, unique_temp_path, mtimeNsBigint, ino);
},
Object.assign(version_info || {}, { from_path }),
'FS::SafeUnlink ERROR unlink target doesn\'t match expected inode and mtime'
);
}
async _wrap_safe_op_with_retries(fs_context, handler, params, retry_err_msg, success_err_codes) {
let retries = config.NSFS_RENAME_RETRIES;
let { from_path, to_path = undefined, mtimeNsBigint, ino } = params;
for (;;) {
try {
dbg.log1('Namespace_fs.wrap_safe_with_retries: ', handler, fs_context, from_path, to_path, mtimeNsBigint, ino);
await handler(params);
break;
} catch (err) {
retries -= 1;
if (retries <= 0) throw err;
if (err.message !== retry_err_msg) throw err;
if (success_err_codes && success_err_codes.includes(err.code)) return;
// stat and extract mtimeNsBigint & ino again
const stat = (await nb_native().fs.stat(fs_context, from_path));
params.mtimeNsBigint = stat.mtimeNsBigint;
params.ino = stat.ino;
dbg.warn(`NamespaceFS: Retrying safe posix ${retry_err_msg.split(' ')[0]} retries=${retries}` +
` from_path=${from_path} to_path=${to_path}`, err);
}
}
}
// 1. get old version_id if exists
// 2. if old version exists -
// 2.1 create .versions/ if it doesnt exist
// 2.2 move old version (existing latest) to .versions/
// 3. move new version to dest (key path)
async _move_to_dest_ver_enabled(fs_context, source_path, dest_path, { key }) {
const cur_ver_info = await this._get_version_info(fs_context, dest_path);
if (cur_ver_info) {
const versioned_path = this._get_version_path(key, cur_ver_info.version_id_str);
await this._make_path_dirs(versioned_path, fs_context);
await this.safe_move_posix(fs_context, dest_path, versioned_path, cur_ver_info);
} else {
dbg.log1('NamespaceFS._move_to_dest_ver_enabled old version doesnt exist - creating first version of object');
}
const new_ver_info = await this._get_version_info(fs_context, source_path);
if (!new_ver_info) throw new Error('NamespaceFS._move_to_dest_ver_enabled - upload file doesnt exist');
await this.safe_move_posix(fs_context, source_path, dest_path, new_ver_info);
}
async _move_to_dest_ver_enabled_gpfs() {
throw new Error('TODO');
}
async _move_to_dest_ver_suspended() {
throw new Error('TODO');
}
async _move_to_dest_ver_suspended_gpfs() {
throw new Error('TODO');
}
// move to dest GPFS (wt) / POSIX (w / undefined) - non part upload
async _move_to_dest(fs_context, source_path, dest_path, target_file, open_mode, versioning_options) {
let retries = config.NSFS_RENAME_RETRIES;
// will retry renaming a file in case of parallel deleting of the destination path
for (;;) {
try {
await this._make_path_dirs(dest_path, fs_context);
if (this._is_versioning_disabled()) {
if (open_mode === 'wt') {
await target_file.linkfileat(fs_context, dest_path);
} else {
await nb_native().fs.rename(fs_context, source_path, dest_path);
}
} else if (this._is_versioning_enabled()) {
if (open_mode === 'wt') {
await this._move_to_dest_ver_enabled_gpfs();
} else {
await this._move_to_dest_ver_enabled(fs_context, source_path, dest_path, versioning_options);
}
} else if (open_mode === 'wt') {
await this._move_to_dest_ver_suspended_gpfs();
} else {
await this._move_to_dest_ver_suspended();
}
break;
} catch (err) {
retries -= 1;
if (retries <= 0) throw err;
if (err.code !== 'ENOENT') throw err;
// checking that the source_path still exists
if (!await this.check_access(fs_context, source_path)) throw err;
dbg.warn(`NamespaceFS: Retrying failed move to dest retries=${retries}` +
` source_path=${source_path} dest_path=${dest_path}`, err);
}
}
}
// Comparing both device and inode number (st_dev and st_ino returned by stat)
// will tell you whether two different file names refer to the same thing.
// If so, we will return the etag and encryption info of the file_path
async _is_same_inode(fs_context, source_file_path, file_path) {
try {
dbg.log2('NamespaceFS: checking _is_same_inode');
const file_path_stat = await nb_native().fs.stat(fs_context, file_path);
const file_path_inode = file_path_stat.ino.toString();
const file_path_device = file_path_stat.dev.toString();
const source_file_stat = await nb_native().fs.stat(fs_context, source_file_path, { skip_user_xattr: true });
const source_file_inode = source_file_stat.ino.toString();
const source_file_device = source_file_stat.dev.toString();
dbg.log2('NamespaceFS: file_path_inode:', file_path_inode, 'source_file_inode:', source_file_inode,
'file_path_device:', file_path_device, 'source_file_device:', source_file_device);
if (file_path_inode === source_file_inode && file_path_device === source_file_device) {
return file_path_stat;
}
} catch (e) {
dbg.log2('NamespaceFS: _is_same_inode got an error', e);
// If we fail for any reason, we want to return undefined. so doing nothing in this catch.
}
}
// Allocated config.NSFS_BUF_SIZE in Semaphore but in fact we can take up more inside
// This is due to MD5 calculation and data buffers
// Can be finetuned further on if needed and inserting the Semaphore logic inside
// Instead of wrapping the whole _upload_stream function (q_buffers lives outside of the data scope of the stream)
async _upload_stream({ fs_context, params, target_file, object_sdk }) {
const { source_stream } = params;
try {
// Not using async iterators with ReadableStreams due to unsettled promises issues on abort/destroy