-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathnamespace_fs.js
3081 lines (2796 loc) · 138 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", 4000]*/
/*eslint max-statements: ["error", 80, { "ignoreTopLevelFunctions": true }]*/
'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 native_fs_utils = require('../util/native_fs_utils');
const ChunkFS = require('../util/chunk_fs');
const LRUCache = require('../util/lru_cache');
const nb_native = require('../util/nb_native');
const RpcError = require('../rpc/rpc_error');
const { S3Error } = require('../endpoint/s3/s3_errors');
const NoobaaEvent = require('../manage_nsfs/manage_nsfs_events_utils').NoobaaEvent;
const { PersistentLogger } = require('../util/persistent_logger');
const { GlacierBackend } = require('./nsfs_glacier_backend/backend');
const multi_buffer_pool = new buffer_utils.MultiSizeBuffersPool({
sorted_buf_sizes: [
{
size: config.NSFS_BUF_SIZE_XS,
sem_size: config.NSFS_BUF_POOL_MEM_LIMIT_XS,
}, {
size: config.NSFS_BUF_SIZE_S,
sem_size: config.NSFS_BUF_POOL_MEM_LIMIT_S,
}, {
size: config.NSFS_BUF_SIZE_M,
sem_size: config.NSFS_BUF_POOL_MEM_LIMIT_M,
}, {
size: config.NSFS_BUF_SIZE_L,
sem_size: config.NSFS_BUF_POOL_MEM_LIMIT_L,
},
],
warning_timeout: config.NSFS_BUF_POOL_WARNING_TIMEOUT,
sem_timeout: config.IO_STREAM_SEMAPHORE_TIMEOUT,
sem_timeout_error_code: 'IO_STREAM_ITEM_TIMEOUT',
sem_warning_timeout: config.NSFS_SEM_WARNING_TIMEOUT,
buffer_alloc: size => nb_native().fs.dio_buffer_alloc(size),
});
const XATTR_USER_PREFIX = 'user.';
const XATTR_NOOBAA_INTERNAL_PREFIX = XATTR_USER_PREFIX + 'noobaa.';
const XATTR_NOOBAA_CUSTOM_PREFIX = XATTR_NOOBAA_INTERNAL_PREFIX + 'tag.';
// TODO: In order to verify validity add content_md5_mtime as well
const XATTR_MD5_KEY = XATTR_USER_PREFIX + 'content_md5';
const XATTR_CONTENT_TYPE = XATTR_NOOBAA_INTERNAL_PREFIX + 'content_type';
const XATTR_PART_OFFSET = XATTR_NOOBAA_INTERNAL_PREFIX + 'part_offset';
const XATTR_PART_SIZE = XATTR_NOOBAA_INTERNAL_PREFIX + 'part_size';
const XATTR_PART_ETAG = XATTR_NOOBAA_INTERNAL_PREFIX + 'part_etag';
const XATTR_VERSION_ID = XATTR_NOOBAA_INTERNAL_PREFIX + 'version_id';
const XATTR_PREV_VERSION_ID = XATTR_NOOBAA_INTERNAL_PREFIX + 'prev_version_id';
const XATTR_DELETE_MARKER = XATTR_NOOBAA_INTERNAL_PREFIX + 'delete_marker';
const XATTR_DIR_CONTENT = XATTR_NOOBAA_INTERNAL_PREFIX + 'dir_content';
const HIDDEN_VERSIONS_PATH = '.versions';
const NULL_VERSION_ID = 'null';
const NULL_VERSION_SUFFIX = '_' + NULL_VERSION_ID;
const XATTR_STORAGE_CLASS_KEY = XATTR_USER_PREFIX + 'storage_class';
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 _get_version_id_by_stat({ino, mtimeNsBigint}) {
// TODO: GPFS might require generation number to be added to version_id
return 'mtime-' + mtimeNsBigint.toString(36) + '-ino-' + ino.toString(36);
}
function _is_version_object_including_null_version(filename) {
const is_version_object = _is_version_object(filename);
if (!is_version_object) {
return _is_version_null_version(filename);
}
return is_version_object;
}
function _is_version_null_version(filename) {
return filename.endsWith(NULL_VERSION_SUFFIX);
}
function _is_version_object(filename) {
const mtime_substr_index = filename.indexOf('_mtime-');
if (mtime_substr_index < 0) return false;
const ino_substr_index = filename.indexOf('-ino-');
return ino_substr_index > mtime_substr_index;
}
function _get_mtime_from_filename(filename) {
if (!_is_version_object(filename)) {
// Latest file wont have time suffix which will push the latest
// object last in the list. So to keep the order maintained,
// returning the latest time. Multiplying with 1e6 to provide
// nano second precision
return BigInt(Date.now() * 1e6);
}
const file_parts = filename.split('-');
return size_utils.string_to_bigint(file_parts[file_parts.length - 3], 36);
}
function _get_filename(file_name) {
if (_is_version_object(file_name)) {
return file_name.substring(0, file_name.indexOf('_mtime-'));
} else if (_is_version_null_version(file_name)) {
return file_name.substring(0, file_name.indexOf(NULL_VERSION_SUFFIX));
}
return file_name;
}
/**
* @param {fs.Dirent} first_entry
* @param {fs.Dirent} second_entry
* @returns {Number}
*/
function sort_entries_by_name_and_time(first_entry, second_entry) {
const first_entry_name = _get_filename(first_entry.name);
const second_entry_name = _get_filename(second_entry.name);
if (first_entry_name === second_entry_name) {
const first_entry_mtime = _get_mtime_from_filename(first_entry.name);
const second_entry_mtime = _get_mtime_from_filename(second_entry.name);
// To sort the versions in the latest first order,
// below logic is followed
if (second_entry_mtime < first_entry_mtime) return -1;
if (second_entry_mtime > first_entry_mtime) return 1;
return 0;
} else {
if (first_entry_name < second_entry_name) return -1;
if (first_entry_name > second_entry_name) return 1;
return 0;
}
}
// This is helper function for list object version
// In order to sort the entries by name we would like to change the name of files with suffix of '_null'
// to have the structure of _mtime-...-ino-... as version id.
// This function returns a set that contains all file names that were changed (after change)
// and an array old_versions_after_rename which is old_versions without the versions that stat failed on
async function _rename_null_version(old_versions, fs_context, version_path) {
const renamed_null_versions_set = new Set();
const old_versions_after_rename = [];
for (const old_version of old_versions) {
if (_is_version_null_version(old_version.name)) {
try {
const stat = await nb_native().fs.stat(fs_context, path.join(version_path, old_version.name));
const mtime_ino = _get_version_id_by_stat(stat);
const original_name = _get_filename(old_version.name);
const version_with_mtime_ino = original_name + '_' + mtime_ino;
old_version.name = version_with_mtime_ino;
renamed_null_versions_set.add(version_with_mtime_ino);
} catch (err) {
// to cover an edge case where stat fails
// for example another process deleted an object and we get ENOENT
// just before executing this command but after the starting list object versions
dbg.error(`_rename_null_version of ${old_version.name} got error:`, err);
old_version.name = undefined;
}
}
if (old_version.name) old_versions_after_rename.push(old_version);
}
return { renamed_null_versions_set, old_versions_after_rename };
}
/**
*
* @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 = native_fs_utils.isDirectory(stat);
if (!r && is_symbolic_link(stat)) {
const 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 = native_fs_utils.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`);
}
}
/**
* NOTICE that even files that were written sequentially, can still be identified as sparse:
* 1. After writing, but before all the data is synced, the size is higher than blocks size.
* 2. For files that were moved to an archive tier.
* 3. For files that fetch and cache data from remote storage, which are still not in the cache.
* It's not good enough for avoiding recall storms as needed by _fail_if_archived_or_sparse_file.
* However, using this check is useful for guessing that a reads is going to take more time
* and avoid holding off large buffers from the buffers_pool.
* @param {nb.NativeFSStats} stat
* @returns {boolean}
*/
function is_sparse_file(stat) {
return (stat.blocks * 512 < stat.size);
}
/**
* @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.startsWith(XATTR_NOOBAA_INTERNAL_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: nb.NativeFSStats,
* 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,
});
/**
* @typedef {{
* time: number,
* stat: nb.NativeFSStats,
* ver_dir_stat: nb.NativeFSStats,
* usage: number,
* sorted_entries?: fs.Dirent[],
* }} ReaddirVersionsCacheItem
* @type {LRUCache<object, string, ReaddirVersionsCacheItem>}
*/
const versions_dir_cache = new LRUCache({
name: 'nsfs-versions-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);
const version_path = dir_path + "/" + HIDDEN_VERSIONS_PATH;
let ver_dir_stat_size;
let is_version_path_exists = false;
let ver_dir_stat;
try {
ver_dir_stat = await nb_native().fs.stat(fs_context, version_path);
ver_dir_stat_size = ver_dir_stat.size;
is_version_path_exists = true;
} catch (err) {
if (err.code === 'ENOENT') {
dbg.log0('NamespaceFS: Version dir not found, ', version_path);
} else {
throw err;
}
ver_dir_stat = null;
ver_dir_stat_size = 0;
}
let sorted_entries;
let usage = config.NSFS_DIR_CACHE_MIN_DIR_SIZE;
if (stat.size + ver_dir_stat_size <= config.NSFS_DIR_CACHE_MAX_DIR_SIZE) {
const latest_versions = await nb_native().fs.readdir(fs_context, dir_path);
if (is_version_path_exists) {
const old_versions = await nb_native().fs.readdir(fs_context, version_path);
// In case we have a null version id inside .versions/ directory we will rename it
// Therefore, old_versions_after_rename will not include an entry with 'null' suffix
// (in case stat fails on a version we would remove it from the array)
const {
renamed_null_versions_set,
old_versions_after_rename
} = await _rename_null_version(old_versions, fs_context, version_path);
const entries = latest_versions.concat(old_versions_after_rename);
sorted_entries = entries.sort(sort_entries_by_name_and_time);
// rename back version to include 'null' suffix.
if (renamed_null_versions_set.size > 0) {
for (const ent of sorted_entries) {
if (renamed_null_versions_set.has(ent.name)) {
const file_name = _get_filename(ent.name);
const version_name_with_null = file_name + NULL_VERSION_SUFFIX;
ent.name = version_name_with_null;
}
}
}
} else {
sorted_entries = latest_versions.sort(sort_entries_by_name);
}
/*eslint no-unused-expressions: ["error", { "allowTernary": true }]*/
for (const ent of sorted_entries) {
usage += ent.name.length + 4;
}
}
return { time, stat, ver_dir_stat, sorted_entries, usage };
},
validate: async ({ stat, ver_dir_stat }, { dir_path, fs_context }) => {
const new_stat = await nb_native().fs.stat(fs_context, dir_path);
if (ver_dir_stat) {
const versions_dir_path = path.normalize(path.join(dir_path, '/', HIDDEN_VERSIONS_PATH));
const new_versions_stat = await nb_native().fs.stat(fs_context, versions_dir_path);
return (new_stat.ino === stat.ino &&
new_stat.mtimeNsBigint === stat.mtimeNsBigint &&
new_versions_stat.ino === ver_dir_stat.ino &&
new_versions_stat.mtimeNsBigint === ver_dir_stat.mtimeNsBigint);
} else {
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;
* force_md5_etag: boolean;
* }} params
*/
constructor({
bucket_path,
fs_backend,
bucket_id,
namespace_resource_id,
access_mode,
versioning,
stats,
force_md5_etag,
}) {
dbg.log0('NamespaceFS: buffers_pool ',
multi_buffer_pool.pools);
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;
this.force_md5_etag = force_md5_etag;
this.warmup_buffer = nb_native().fs.dio_buffer_alloc(4096);
}
/**
* @param {nb.ObjectSDK} object_sdk
* @returns {nb.NativeFSContext}
*/
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, other_md, 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'?
params.content_type === other_md.content_type;
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) {
if (!config.NSFS_UPDATE_ISSUES_REPORT_ENABLED) {
dbg.log0('update_issues_report disabled:', this.namespace_resource_id, err);
return;
}
//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) {
return this._list_objects(params, object_sdk, false);
}
/**
* @typedef {{
* bucket: string,
* prefix?: string,
* delimiter?: string,
* key_marker?: string,
* version_id_marker?: string,
* limit?: number,
* }} ListVersionsParams
*/
/**
* @param {ListVersionsParams} params
*/
async list_object_versions(params, object_sdk) {
return this._list_objects(params, object_sdk, true);
}
async _list_objects(params, object_sdk, list_versions) {
try {
const fs_context = this.prepare_fs_context(object_sdk);
await this._load_bucket(params, fs_context);
const {
bucket,
delimiter = '',
prefix = '',
version_id_marker = '',
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?: nb.NativeFSStats,
* }} Result
*/
/** @type {Result[]} */
const results = [];
/**
* @param {string} dir_key
* @returns {Promise<void>}
*/
const process_dir = async dir_key => {
if (this._is_hidden_version_path(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}`);
/**
* @typedef {{
* key: string,
* common_prefix: boolean
* }}
*/
const insert_entry_to_results_arr = async r => {
let pos;
// Since versions are arranged next to latest object in the latest first order,
// no need to find the sorted last index. Push the ".versions/#VERSION_OBJECT" as
// they are in order
if (results.length && r.key < results[results.length - 1].key &&
!this._is_hidden_version_path(r.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;
}
}
};
/**
* @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() ||
ent.name === config.NSFS_FOLDER_OBJECT_NAME) &&
!this._is_hidden_version_path(ent.name)) {
return;
}
const isDir = await is_directory_or_symlink_to_directory(ent, fs_context, path.join(dir_path, ent.name));
let r;
if (list_versions && _is_version_object_including_null_version(ent.name)) {
r = {
key: this._get_version_entry_key(dir_key, ent),
common_prefix: isDir,
};
} else {
r = {
key: this._get_entry_key(dir_key, ent, isDir),
common_prefix: isDir,
};
}
await insert_entry_to_results_arr(r);
};
if (!(await this.check_access(fs_context, dir_path))) return;
try {
if (list_versions) {
cached_dir = await versions_dir_cache.get_with_cache({ dir_path, fs_context });
} else {
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;
}
// insert dir object to objects list if its key is lexicographicly bigger than the key marker &&
// no delimiter OR prefix is the current directory entry
const is_dir_content = cached_dir.stat.xattr && cached_dir.stat.xattr[XATTR_DIR_CONTENT];
if (is_dir_content && dir_key > key_marker && (!delimiter || dir_key === prefix)) {
const r = { key: dir_key, common_prefix: false };
await insert_entry_to_results_arr(r);
}
if (cached_dir.sorted_entries) {
const sorted_entries = cached_dir.sorted_entries;
let marker_index;
// Two ways followed here to find the index.
// 1. When inside marker_dir: Here the entries are sorted based on time. Here
// FindIndex() is called since sortedLastIndexBy() expects sorted order by name
// 2. When marker_dir above dir_path: sortedLastIndexBy() is called since entries are
// sorted by name
// 3. One of the below conditions, marker_curr.includes('/') checks whether
// the call is for the directory that contains marker_curr
if (list_versions && marker_curr && !marker_curr.includes('/')) {
let start_marker = marker_curr;
if (version_id_marker) start_marker = version_id_marker;
marker_index = _.findIndex(
sorted_entries,
{name: start_marker}
) + 1;
} else {
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 = 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];
if (list_versions && marker_curr) {
const ent_name = _get_filename(ent.name);
if (ent_name !== marker_curr) break;
}
// 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,
next_version_id_marker: undefined,
};
for (const r of results) {
let obj_info;
if (r.common_prefix) {
res.common_prefixes.push(r.key);
} else {
obj_info = this._get_object_info(bucket, r.key, r.stat, 'null', false, true);
if (!list_versions && obj_info.delete_marker) {
continue;
}
if (this._is_hidden_version_path(obj_info.key)) {
obj_info.key = path.normalize(obj_info.key.replace(HIDDEN_VERSIONS_PATH + '/', ''));
obj_info.key = _get_filename(obj_info.key);
}
res.objects.push(obj_info);
}
if (res.is_truncated) {
if (list_versions && _is_version_object(r.key)) {
const next_version_id_marker = r.key.substring(r.key.lastIndexOf('/') + 1);
res.next_version_id_marker = next_version_id_marker;
res.next_marker = _get_filename(next_version_id_marker);
} else {
res.next_marker = r.key;
}
}
}
return res;
} catch (err) {
throw this._translate_object_error_codes(err);
}
}
/////////////////
// 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, true);
await this._check_path_in_bucket_boundaries(fs_context, file_path);
await this._load_bucket(params, fs_context);
let stat = await nb_native().fs.stat(fs_context, file_path);
const isDir = native_fs_utils.isDirectory(stat);
if (isDir) {
if (!stat.xattr?.[XATTR_DIR_CONTENT]) {
throw error_utils.new_error_code('ENOENT', 'NoSuchKey');
} else if (stat.xattr?.[XATTR_DIR_CONTENT] === '0') {
stat.size = 0;
} else {
// find dir object content file path and return its stat + xattr of its parent directory
const dir_content_path = await this._find_version_path(fs_context, params);
const dir_content_path_stat = await nb_native().fs.stat(fs_context, dir_content_path);
const xattr = stat.xattr;
stat = { ...dir_content_path_stat, xattr };
}
}
this._throw_if_delete_marker(stat);
return this._get_object_info(params.bucket, params.key, stat, params.version_id || 'null', isDir);
} catch (err) {
this.run_update_issues_report(object_sdk, 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);
// NOTE: don't move this code after the open
// this can lead to ENOENT failures due to file not exists when content size is 0
// if entry is a directory object and its content size = 0 - return empty response
const is_dir_content = this._is_directory_content(file_path, params.key);
if (is_dir_content) {
try {
const md_path = this._get_file_md_path(params);
const dir_stat = await nb_native().fs.stat(fs_context, md_path);
if (dir_stat && dir_stat.xattr[XATTR_DIR_CONTENT] === '0') return null;
} catch (err) {
//failed to get object
new NoobaaEvent(NoobaaEvent.OBJECT_GET_FAILED).create_event(params.key,
{bucket_path: this.bucket_path, object_name: params.key}, err);
dbg.log0('NamespaceFS: read_object_stream couldnt find dir content xattr', err);
}
}
file = await nb_native().fs.open(
fs_context,
file_path,
config.NSFS_OPEN_READ_MODE,
native_fs_utils.get_umasked_mode(config.BASE_MODE_FILE),
);
const stat = await file.stat(fs_context);
this._throw_if_delete_marker(stat);
// await this._fail_if_archived_or_sparse_file(fs_context, file_path, stat);
const start = Number(params.start) || 0;
const end = isNaN(Number(params.end)) ? Infinity : Number(params.end);
let num_bytes = 0;
let num_buffers = 0;
const log2_size_histogram = {};
let drain_promise = null;
dbg.log0('NamespaceFS: read_object_stream', {
file_path, start, end, size: stat.size,
});
let count = 1;
for (let pos = start; pos < end;) {
object_sdk.throw_if_aborted();
// Our buffer pool keeps large buffers and we want to avoid spending
// all our large buffers and then have them waiting for high latency calls
// such as reading from archive/on-demand cache files.
// Instead, we detect the case where a file is "sparse",
// and then use just a small buffer to wait for a tiny read,
// which will recall the file from archive or load from remote into cache,
// and once it returns we can continue to the full fledged read.
if (config.NSFS_BUF_WARMUP_SPARSE_FILE_READS && is_sparse_file(stat)) {
dbg.log0('NamespaceFS: read_object_stream - warmup sparse file', {
file_path, pos, size: stat.size, blocks: stat.blocks,
});
await file.read(fs_context, this.warmup_buffer, 0, 1, pos);
}
const remain_size = Math.min(Math.max(0, end - pos), stat.size);
// 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 multi_buffer_pool.get_buffers_pool(remain_size).get_buffer();
buffer_pool_cleanup = callback; // must be called ***IMMEDIATELY*** after get_buffer
object_sdk.throw_if_aborted();
// read from file
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();
}