-
Notifications
You must be signed in to change notification settings - Fork 1
/
hdrfs.py
executable file
·3742 lines (3253 loc) · 170 KB
/
hdrfs.py
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
#!/usr/bin/python3
#
# HDRFS: High Data Retention Filesystem.
# Copyright (C) 2017 J Taylor
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import logging, os, glob, sys, sqlite3, struct, time, stat, hashlib, errno, shutil, zlib, pickle, uuid, datetime, copy
from optparse import OptionParser
from functools import reduce
from fusepy import LoggingMixIn, FuseOSError, Operations, FUSE, fuse_get_context
# Set up logging.
hdrfslog = logging.getLogger('hdrfs')
hdrfslog.setLevel(logging.INFO)
fh = logging.StreamHandler()
formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
fh.setFormatter(formatter)
hdrfslog.addHandler(fh)
#fuselog = logging.getLogger('fuse.log-mixin')
#fuselog.addHandler(fh)
#fuselog.setLevel(logging.DEBUG)
MAX_TIMEPOINT = 9223372036854775807
HDRFS_VERSION = "0.1.0"
class LogParserException(Exception):
"""Represents a generic error that may occur when parsing a log.
volpos and logpos define the START of the block in which the error
occurred. This is critical in the operation of the nuclear-fsck option as
it defines the point from which the Log will be truncated.
"""
def __init__(self, message, volpos=None, logpos=None):
self.message = message
self.volpos = volpos
self.logpos = logpos
def __repr__(self):
return self.message + " (volume {}, offset {})".format(self.volpos, self.logpos)
class NonContiguityError(Exception):
"""Represents an error that may be encountered when rebuilding the Index from the Log.
"""
def __init__(self, missing_vol_number):
self.missing_vol_number = missing_vol_number
class BlockHeader(object):
"""Represents the header of a Log"""
magic_id = b"\xD3HDRFS\x0D\x0A\x1A\x0A\x00HDRFS\x00"
version = b"\x00"
crc_algo = b"\x00"
hash_algo = b"\x00"
def __init__(self, fs_id, prev_vol_hash, vol_seq_no):
self.fs_id = fs_id
self.prev_vol_hash = prev_vol_hash
self.vol_seq_no = vol_seq_no
def __bytes__(self):
header = self.magic_id
header += self.version
header += self.fs_id
header += self.crc_algo
header += self.hash_algo
header += struct.pack("<Q", self.vol_seq_no)
header += self.prev_vol_hash
crc = struct.pack("<L", zlib.crc32(header))
return header + crc
def __repr__(self):
return ("BlockHeader(length={}, magic_id={}, version={}, fs_id={}, "
"crc_algo={}, hash_algo={}, vol_seq_no={}, prev_vol_hash={})"
).format(len(bytes(self)), self.magic_id, self.version,
self.fs_id, self.crc_algo, self.hash_algo,
self.vol_seq_no, self.prev_vol_hash)
class BlockNull(object):
"""Represent a run of zeroes. A zero-length run represents the absence of a block."""
block_id = b'\x00'
def __init__(self, length=0):
self.length = length
def __repr__(self):
return "BlockNull(length={})".format(self.length)
class BlockInode(object):
"""Represent an inode.
All supplied arguments must be ints, except extent_list which may be None
or a list, and linktarget, which must be a string.
"""
block_id = b'\x01'
def __init__(self, inode_number, log_timestamp, st_mode, st_uid, st_gid, st_atime, st_mtime, st_ctime,
st_btime, extent_list=[], linktarget="", st_size=None, st_nlink=1, refcount=0):
self.inode_number = inode_number
self.log_timestamp = log_timestamp
self.st_mode = st_mode
self.st_uid = st_uid
self.st_gid = st_gid
self.st_atime = st_atime
self.st_mtime = st_mtime
self.st_ctime = st_ctime
self.st_btime = st_btime
self.extent_list = extent_list
self.linktarget = linktarget
self.st_nlink = st_nlink # Note this is not serialized - it's a derived item.
self.refcount = refcount # Note this is not serialized - it's only used when an inode is open
self.dirty = False # Set to true if a change must be persisted upon fsync
if st_size is not None:
self.st_size = st_size
else:
if stat.S_ISREG(self.st_mode):
if len(extent_list) > 0:
self.st_size = extent_list[-1].logical_end_offset
else:
self.st_size = 0
elif stat.S_ISLNK(self.st_mode):
self.st_size = len(self.linktarget.encode())
else:
self.st_size = 75
def __bytes__(self):
linktarget_binary = self.linktarget.encode()
s = self.block_id
s += struct.pack("<Q", self.inode_number) # little-endian unsigned long long (8 bytes)
s += struct.pack("<Q", self.log_timestamp) # little-endian unsigned long long (8 bytes)
s += struct.pack("<H", self.st_mode) # little-endian unsigned short (2 bytes)
s += struct.pack("<H", self.st_uid) # little-endian unsigned short (2 bytes)
s += struct.pack("<H", self.st_gid) # little-endian unsigned short (2 bytes)
s += struct.pack("<Q", self.st_atime) # little-endian unsigned long long (8 bytes)
s += struct.pack("<Q", self.st_mtime) # little-endian unsigned long long (8 bytes)
s += struct.pack("<Q", self.st_ctime) # little-endian unsigned long long (8 bytes)
s += struct.pack("<Q", self.st_btime) # little-endian unsigned long long (8 bytes)
s += struct.pack("<Q", self.st_size) # little-endian unsigned long long (8 bytes)
if stat.S_ISREG(self.st_mode):
t = b''
for m in self.extent_list:
t += struct.pack("<Q", m.volume)
t += struct.pack("<Q", m.physical_start_offset)
t += struct.pack("<Q", m.block_size)
t += m.block_multiplicity
t += struct.pack("<Q", m.block_count)
t += struct.pack("<Q", m.pre_truncate)
t += struct.pack("<Q", m.post_truncate)
t += struct.pack("<Q", m.logical_start_offset)
s += struct.pack("<Q", len(t))
s += t
elif stat.S_ISLNK(self.st_mode):
s += struct.pack("<Q", len(linktarget_binary))
s += linktarget_binary
else:
s += struct.pack("<Q", 0)
crc = struct.pack("<L", zlib.crc32(s))
return s + crc
def __repr__(self):
return ("BlockInode(length={}, inode_number={}, log_timestamp={}, st_mode={}, st_uid={}, st_gid={}, "
"st_atime={}, st_mtime={}, st_ctime={}, st_btime={}, st_size={}, extent_list={}, linktarget={}, "
"st_nlink={}, refcount={}").format(len(bytes(self)),
self.inode_number,
self.log_timestamp,
self.st_mode,
self.st_uid,
self.st_gid,
self.st_atime,
self.st_mtime,
self.st_ctime,
self.st_btime,
self.st_size,
self.extent_list,
self.linktarget,
self.st_nlink,
self.refcount)
class BlockLink(object):
block_id = b'\x02'
def __init__(self, log_timestamp, child_inode, parent_inode, objname):
self.log_timestamp = log_timestamp
self.child_inode = child_inode
self.parent_inode = parent_inode
self.objname = objname
def __bytes__(self):
objname_binary = self.objname.encode()
s = self.block_id
s += struct.pack("<Q", self.log_timestamp)
s += struct.pack("<Q", self.child_inode)
s += struct.pack("<Q", self.parent_inode)
s += struct.pack("<H", len(objname_binary)) # Kernel enforces a max path length of 4095
s += objname_binary
crc = struct.pack("<L", zlib.crc32(s))
return s + crc
def __repr__(self):
return "BlockLink(length={}, log_timestamp={}, child_inode={}, parent_inode={}, objname={})".format(
len(bytes(self)), self.log_timestamp, self.child_inode, self.parent_inode, self.objname)
class BlockUnlink(object):
block_id = b'\x03'
def __init__(self, log_timestamp, child_inode, parent_inode, name):
self.log_timestamp = log_timestamp
self.child_inode = child_inode
self.parent_inode = parent_inode
self.objname = name
def __bytes__(self):
objname_binary = self.objname.encode()
s = self.block_id
s += struct.pack("<Q", self.log_timestamp)
s += struct.pack("<Q", self.child_inode)
s += struct.pack("<Q", self.parent_inode)
s += struct.pack("<H", len(objname_binary))
s += objname_binary
crc = struct.pack("<L", zlib.crc32(s))
return s + crc
def __repr__(self):
return "BlockUnlink(length={}, log_timestamp={}, child_inode={}, parent_inode={}, objname={})".format(
len(bytes(self)), self.log_timestamp, self.child_inode, self.parent_inode, self.objname)
class BlockXattr(object):
block_id = b'\x04'
def __init__(self, log_timestamp, inode_number, name, value):
"""For some reason fusepy gives us a str for a name and bytes for value."""
assert type(log_timestamp) == int
assert type(inode_number) == int
assert type(name) == str
assert type(value) == bytes
self.log_timestamp = log_timestamp
self.inode_number = inode_number
self.name = name
self.value = value
def __bytes__(self):
name_binary = self.name.encode("utf-8")
s = self.block_id
s += struct.pack("<Q", self.log_timestamp)
s += struct.pack("<Q", self.inode_number)
s += struct.pack("<B", len(name_binary)) # Max length 2^8 = 255 imposed by the kernel
s += struct.pack("<H", len(self.value)) # Max length 2^16 = 65536 imposed by the kernel
s += name_binary
s += self.value
crc = struct.pack("<L", zlib.crc32(s))
return s + crc
def __repr__(self):
return "BlockXattr(length={}, log_timestamp={}, inode_number={}, name={}, value={})".format(
len(bytes(self)), self.log_timestamp, self.inode_number, self.name, self.value)
class BlockRemovedXattr(object):
block_id = b'\x05'
def __init__(self, log_timestamp, inode_number, name):
assert type(log_timestamp) == int
assert type(inode_number) == int
assert type(name) == str
self.log_timestamp = log_timestamp
self.inode_number = inode_number
self.name = name
def __bytes__(self):
name_binary = self.name.encode("utf-8")
s = self.block_id
s += struct.pack("<Q", self.log_timestamp)
s += struct.pack("<Q", self.inode_number)
s += struct.pack("<B", len(name_binary))
s += name_binary
crc = struct.pack("<L", zlib.crc32(s))
return s + crc
def __repr__(self):
return "BlockRemovedXattr(length={}, inode_number={}, log_timestamp={}, name={})".format(
len(bytes(self)), self.log_timestamp, self.inode_number, self.name)
class BlockData(object):
block_id = b'\x06'
def __init__(self, log_timestamp, payload):
"""A log_timestamp should be the same for all blocks created by a single write() call"""
self.log_timestamp = log_timestamp
self.payload = payload
def __bytes__(self):
s = self.block_id
s += struct.pack("<Q", self.log_timestamp)
s += struct.pack("<Q", len(self.payload)) # In typical usage this length will be <=131072. Future kernels may allow higher.
s += self.payload # and nothing prevents an HDRFS Log file containing larger extents.
crc = struct.pack("<L", zlib.crc32(s))
return s + crc
def __repr__(self):
return "BlockData(length={}, log_timestamp={}, payload_length={})".format(
len(bytes(self)), self.log_timestamp, len(self.payload))
class BlockRename(object):
block_id = b'\x07'
def __init__(self, log_timestamp, oldpath, newpath):
self.log_timestamp = log_timestamp
self.oldpath = oldpath
self.newpath = newpath
def __bytes__(self):
oldpath_binary = self.oldpath.encode('UTF-8')
newpath_binary = self.newpath.encode('UTF-8')
s = self.block_id
s += struct.pack("<Q", self.log_timestamp)
s += struct.pack("<H", len(oldpath_binary)) # Kernel enforces a max path length of 4095
s += struct.pack("<H", len(newpath_binary)) # Kernel enforces a max path length of 4095
s += oldpath_binary
s += newpath_binary
crc = struct.pack("<L", zlib.crc32(s))
return s + crc
def __repr__(self):
return "BlockRename(length={}, log_timestamp={}, oldpath={}, newpath={})".format(
len(bytes(self)), self.log_timestamp, self.oldpath, self.newpath)
class BlockLinkTable(object):
"""TODO: Wise to store all links in memory? Potential for huge memory use on large filesystems?
This block holds no timestamp as it is always written as the first block in a new volume and
not at the request of any POSIX operation."""
block_id = b'\x08'
def __init__(self, links):
self.links = links
def __bytes__(self):
s = self.block_id
s += struct.pack("<Q", len(self.links))
for a in self.links:
child, parent, name = a
name_binary = name.encode('UTF-8')
s += struct.pack("<Q", child)
s += struct.pack("<Q", parent)
s += struct.pack("<H", len(name_binary))
s += name_binary
crc = struct.pack("<L", zlib.crc32(s))
return s + crc
def __repr__(self):
return "BlockLinkTable(length={}, entries)".format(
len(bytes(self)), len(self.links))
class Extent(object):
"""
pre_truncate and post_truncate may both be any integer up to and including block_size*block_count
This lets us easily trim extents without doing too much arithmetic
Note the ugliness of calculate_properties(). Users of this class have to call this function after every modification of
an Extent object. In return, we get a ~10% speed boost over using dynamically calculated @properties. We mitigate the risk
of an un-re-calculated attribute with extensive tests.
"""
__slots__ = ('volume', 'physical_start_offset', 'block_size', 'block_multiplicity', 'block_count', 'pre_truncate', 'post_truncate',
'logical_start_offset', 'length', 'logical_end_offset')
def __init__(self, volume, physical_start_offset, block_size, block_multiplicity, block_count, pre_truncate, post_truncate,
logical_start_offset):
assert type(volume) == int
assert volume >= 0
assert type(physical_start_offset) == int
assert physical_start_offset >= 0
assert type(block_size) == int
assert block_size >= 0
assert block_multiplicity in (b'C', b'R') # C = Count. R = Repeat.
assert type(block_count) == int
assert block_count >= 0
assert type(pre_truncate) == int
assert pre_truncate >= 0
assert type(post_truncate) == int
assert post_truncate >= 0
assert type(logical_start_offset) == int
assert logical_start_offset >= 0
self.volume = volume
self.physical_start_offset = physical_start_offset
self.block_size = block_size
self.block_multiplicity = block_multiplicity
self.block_count = block_count # Used to reference a sequence of blocks
self.pre_truncate = pre_truncate
self.post_truncate = post_truncate
self.logical_start_offset = logical_start_offset
self.calculate_properties()
def calculate_properties(self):
self.length = (self.block_size * self.block_count) - self.pre_truncate - self.post_truncate
self.logical_end_offset = self.logical_start_offset + self.length
def __eq__(self, other):
"""http://stackoverflow.com/questions/9843569/if-duck-typing-in-python-should-you-test-isinstance"""
if isinstance(other, self.__class__):
if (self.volume == other.volume
and self.physical_start_offset == other.physical_start_offset
and self.block_size == other.block_size
and self.block_multiplicity == other.block_multiplicity
and self.block_count == other.block_count
and self.pre_truncate == other.pre_truncate
and self.post_truncate == other.post_truncate
and self.logical_start_offset == other.logical_start_offset):
return True
else:
return NotImplemented
def __ne__(self, other):
return not self == other
def __repr__(self):
return "Extent({})".format(", ".join([str(getattr(self, s)) for s in self.__slots__]))
@staticmethod # Rationale for a staticmethod rather than a top-level function - grouping utility functions
def truncate(extent_list, length):
newmapping = []
for e in extent_list:
if e.logical_end_offset <= length:
newmapping.append(e)
elif e.logical_start_offset < length < e.logical_end_offset:
e.post_truncate += e.logical_end_offset - length
e.calculate_properties()
newmapping.append(e)
elif length <= e.logical_start_offset:
pass # In this case, drop the extent from the new mapping
return newmapping
@staticmethod
def is_extent_list_ordered(extent_list):
"""Returns True if the extents in the list are in logical order. Note the use
of <= less than or equal - a list may not have two extents claiming to start at the same
logical position."""
logical_position = -1
for e in extent_list:
if e.logical_start_offset <= logical_position:
return False
logical_position = e.logical_start_offset
return True
# The problem is now how to implement splicing of an Extent into a list of other extents.
# A volume with many blocks:
#
# |---------|------------------|--|--|--|--|--|------------|
# (---------------------------------)
# An extent runs from here... to here
#
# The list must be ordered by logical_start_offset
#
# A new extent will have a logical start offset. Need to iterate over the extent list looking for where it should start.
@staticmethod
def splice(cur, new):
"Given an ordered list of Extents, and a new Extent, splice the latter into the former"
assert Extent.is_extent_list_ordered(cur)
assert type(new) == Extent
# Simplest case: a new file with no current extents
if len(cur) == 0:
return [new]
# Block repeat detection
last_extent = cur[-1]
if (last_extent.logical_end_offset == new.logical_start_offset and
last_extent.physical_start_offset == new.physical_start_offset and
last_extent.volume == new.volume and
last_extent.block_size == new.block_size):
last_extent.block_multiplicity = b'R'
last_extent.block_count += 1
last_extent.calculate_properties()
assert Extent.is_extent_list_ordered(cur)
return cur
# First check for the special case of new extending exactly from the last element of cur
# The block size must match, and they must be on the same volume.
# ISSUE: This case is not reached if writing a new sequence of blocks into the middle of the file.
# When might that be the case? Probably rare? Need some real-world usage to determine.
if (last_extent.logical_end_offset == new.logical_start_offset and
last_extent.block_size == new.block_size and
last_extent.volume == new.volume and
last_extent.physical_start_offset+(17+last_extent.block_size+4)*last_extent.block_count == new.physical_start_offset): # This condition checks that the new block really does follow on from the last
last_extent.block_count += new.block_count
last_extent.calculate_properties()
assert Extent.is_extent_list_ordered(cur)
return cur
# Otherwise, continue with a general extent splicing algorithm
for i, e in enumerate(cur):
logical_start = e.logical_start_offset
logical_end = logical_start + e.length
# New may either be strictly before the current element, overlap it, or be strictly after it.
# If it's strictly before, insert it into the list before the current element - and we're done.
# If it's strictly after, continue iterating
# Otherwise, splice
# Case 1: new is strictly before. We already know if must be strictly after the previous e to have
# gotten here.
if new.logical_end_offset < e.logical_start_offset:
cur.insert(i, new)
assert Extent.is_extent_list_ordered(cur)
return cur
# Case 2: strictly after
elif new.logical_start_offset > e.logical_end_offset:
continue
# Case 3: It must overlap
else:
# In general, when new overlaps e, there will be a portion of an existing e before it (possibly zero!)
# then new, then a portion of an existing e after it. Need to start a new loop through cur to find the
# end of new.
# First work out how much of the current e needs to be retained
post_truncation_amount = e.logical_end_offset - new.logical_start_offset
assert post_truncation_amount >= 0
# Now loop through the remainder of cur, looking for the end of new, and index that location as j
# [a,b,c,d,e]
# i
# 0 1 2 3 4
# len() = 5
# 5-2 = 3
# range(3) = [0,1,2]
# In case there are no other elements, j = i.
for j in range(i, len(cur)):
f = cur[j]
if f.logical_end_offset >= new.logical_end_offset:
break
# There are another two cases now. Either j>i, in which case we
# pre-truncate f, or j=i in which case we MAY need to create a new
# Extent representing the trailing portion of e, which logically
# starts where new ends
if j>i:
pre_truncation_amount = new.logical_end_offset - f.logical_start_offset
assert pre_truncation_amount >= 0
f.pre_truncate += pre_truncation_amount
f.logical_start_offset = new.logical_end_offset
f.calculate_properties()
trailer = False
else:
if e.logical_end_offset > new.logical_end_offset:
trailer = True
trailer_pretruncation_amount = e.pre_truncate + (new.logical_end_offset - e.logical_start_offset)
trailer_extent = Extent(e.volume, e.physical_start_offset, e.block_size, e.block_multiplicity, e.block_count,
trailer_pretruncation_amount, e.post_truncate, new.logical_end_offset)
else:
trailer = False
# Now that we've done the main length logic, we can apply the post-truncation.
e.post_truncate += post_truncation_amount
e.calculate_properties()
# We now know the first (e, at index i) and last (f, at index j) extents which overlap new. They may be the same!
# We need to remove all elements within this range, and optionally the endpoints too,
# if their lengths have dropped to zero due to truncation.
# There are 4 cases: i=j with trailer, i=j with no trailer, j=i+1, j>i+1
# The correct order for each of these is:
# i=j with trailer:
# [..., e, new, trailer, ...]
# i=j with no trailer:
# [..., e, new, ...]
# j=i+1:
# [..., e, new, f, ...]
# j>i+1:
# [..., e, new, f, ...] <--- Difference is that for i < x < j all x have been removed
#
# In each of these cases, e and f may need deleting if they are zero-length.
#
# Work from the right hand end of the list first to keep indices stable.
if i==j:
if trailer:
cur.insert(i+1, trailer_extent)
cur.insert(i+1, new)
elif j==i+1:
if f.length <= 0:
del cur[j]
cur.insert(j, new)
elif j > i+1:
if f.length <= 0:
del cur[j]
del cur[i+1:j]
cur.insert(i+1, new)
else:
hdrfslog.error("Impossible?!")
raise FuseOSError(errno.EIO)
if e.length <= 0:
del cur[i]
assert Extent.is_extent_list_ordered(cur)
return cur
# If we've got this far without returning, then the current extent must
# never exceed new, and therefore it just gets appended.
cur.append(new)
assert Extent.is_extent_list_ordered(cur)
return cur
class HDRFS(Operations):
def __init__(self, options):
"""
This class controls all HDRFS-related functionality. It does not handle
startup, shutdown, user interface or FUSE operations.
11-case startup
"""
self.options = options
self.readonly = False
# Short-circuiting or sometimes considered an anti-pattern.
# But option values are always a string so we will not be surprised by falsy other types.
self.indexdir = options["indexdir"] or options["datadir"]
self.logdir = options["logdir"] or options["datadir"]
self.dedupdir = options["dedupdir"] or options["datadir"]
self.dedup_file = os.path.join(self.dedupdir, 'dedup.hdrfs')
if os.path.exists(self.dedup_file):
with open(self.dedup_file, 'rb') as f:
self.dedup = pickle.loads(f.read())
else:
self.dedup = {}
db_file = os.path.join(self.indexdir, "index.hdrfs")
db_file_already_exists = os.path.exists(db_file)
matches = glob.glob(os.path.join(self.logdir, "L????????????????.hdrfs"))
if len(matches) == 0 and not db_file_already_exists:
# Case 11
self.I = HDRFSIndex(db_file, create_new=True)
self.L = HDRFSLog(self.logdir, options, create_new=True, I=self.I)
self._initialise_root_dir()
elif len(matches) == 0 and db_file_already_exists:
# Case 10 - read-only with access to metadata only.
self.readonly = True
self.I = HDRFSIndex(db_file)
self.L = HDRFSLog(self.logdir, options)
else:
# Log files exist, so start up a Log instance and use it to determine exact startup case.
self.L = HDRFSLog(self.logdir, options)
log_head = self.L.get_head_pointer()
if self.L.degraded:
if db_file_already_exists:
self.I = HDRFSIndex(db_file)
index_head = self.I.get_head_pointer()
if log_head > index_head:
# Case 5
self._rebuild_index_from_log(catchup=True)
elif log_head == index_head:
pass # Case 6. No action required. This is normal startup, albeit with a degraded Log.
elif log_head < index_head:
# Case 7
hdrfslog.warning("Mounting read-only as the index is not in sync with the log")
self.readonly = True
else:
sys.exit("Impossible?")
else:
# Case 8
sys.exit("Cannot start with no index and missing volumes.")
else:
if db_file_already_exists:
self.I = HDRFSIndex(db_file)
index_head = self.I.get_head_pointer()
if log_head > index_head:
# Case 1
self._rebuild_index_from_log(catchup=True)
elif log_head == index_head:
pass # Case 2. No action required - this is normal startup.
elif log_head < index_head:
# Case 3
hdrfslog.warning("Mounting read-only as the index is not in sync with the log")
self.readonly = True
else:
# Case 4
self.I = HDRFSIndex(db_file, create_new=True)
self._rebuild_index_from_log()
self.open_handles = {}
# {filehandle: (inode_number, timepoint)}
self.open_inodes = {} # A cache shared between all open file handles
self._writebuffer = {"fh": None, "offset": None, "data": None} #
# Give the Log a reference to the Index. Essential for dumping the links table during new volume creation
self.L.register_index(self.I)
# TODO: Some startup sanity checks on the index? Like ensuring no rows for inodes with no links?
if options.get("dump_log_to_text_file") is not None:
self.L._dump_log_to_text_file(options["dump_log_to_text_file"])
sys.exit()
if options.get("startup_notification"):
print("STARTUP COMPLETE")
sys.stdout.flush()
@staticmethod
def _mode2type(st_mode):
"""Translate st_mode values into one-character codes"""
if stat.S_ISDIR(st_mode):
return 'd'
if stat.S_ISCHR(st_mode):
return 'c'
if stat.S_ISBLK(st_mode):
return 'b'
if stat.S_ISREG(st_mode):
return 'f'
if stat.S_ISFIFO(st_mode):
return 'p'
if stat.S_ISLNK(st_mode):
return 'l'
if stat.S_ISSOCK(st_mode):
return 's'
else:
raise Exception("Unknown file mode {}!".format(st_mode))
def _initialise_root_dir(self):
# The first thing we write to the data file is the root directory.
# Note the pattern of writing to the log first, then to the Index.
# The log is never inconsistent. The worst that could happen is
# having an incomplete extent written to it.
timepoint = int(time.time()*1000000)
volpos, logpos = self.L.initialise_root_dir(timepoint)
self.I.initialise_root_dir(volpos, logpos, timepoint)
def _allocate_new_handle(self):
current_handles = set(self.open_handles.keys())
possible_handles = set(range(0,len(self.open_handles)+1))
return min(possible_handles - current_handles)
def _parse_path(self, path):
"""Parses a path to determine if it encodes a timepoint. Returns either
the parsed timepoint, or None, along with the remainder of the
path"""
if path.startswith('/'+self.options["history_directory"]) and len(path) > len(self.options["history_directory"])+1: # /history doesn't get timestamp-parsed. /history/ANYTHING does
parsed = path.split('/', 3)
if len(parsed) < 3:
raise Exception("Impossible?")
else:
timestamp = parsed[2]
if len(parsed) == 3:
remainder = '/'
elif len(parsed) > 3:
remainder = '/' + parsed[3]
try:
timepoint = datetime.datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f%z')
except ValueError:
raise FuseOSError(errno.EINVAL)
return int(timepoint.timestamp()*1000000), remainder # Timepoints are always microsecond integers
else:
return None, path
def _cache_inode(self, inode_number, timepoint):
# Upon open, build a data structure which caches metadata, including the logical->physical mapping of the file data.
# This doesn't get written back to the database until an fsync is called, or the file is closed.
# No action if the inode is already cached
if self.open_inodes.get((inode_number, timepoint)) is None:
self.open_inodes[(inode_number, timepoint)] = self.I.get_inode(inode_number, timepoint) # refcount will default to zero
else:
pass
def _closeall(self):
"Close all open resources, to aid a clean shutdown and eliminate ResourceWarnings"
self.L.closeall()
self.I.closeall()
def _rebuild_index_from_log(self, catchup=True):
hdrfslog.info("""Rebuilding index from logs."""
""" This involves reading every part of every log file so rebuilding a"""
""" large filesystem requires patience.""")
# The general strategy is to parse a stream of Block objects.
if catchup:
volpos, logpos = self.I.get_head_pointer()
else:
volpos = 0
logpos = 0
maxinode = 0 # TODO: Should we check for each block that it references no inodes higher than the maxinode seen so far?
last_log_timestamp = 0 # Track and confirm that blocks are in time order.
try:
for (volcursor, block_start), block in self.L._parse_log(volcursor=volpos, logcursor=logpos):
if type(block) not in (BlockHeader, BlockNull, BlockLinkTable): # These blocks do not have log_timestamp fields
if block.log_timestamp < last_log_timestamp:
e = LogParserException("Out of order block: {} (prev was {})".format(block.log_timestamp, last_log_timestamp),
volcursor, block_start)
if self.options["ignore_metadata_errors"]:
hdrfslog.warning(repr(e))
else:
raise e
last_log_timestamp = block.log_timestamp
if type(block) in (BlockHeader, BlockNull, BlockLinkTable, BlockData):
pass
elif type(block) == BlockInode:
if block.inode_number == 0:
self.I.initialise_root_dir(0, 0, block.log_timestamp) # TODO: does it matter that we don't use a real value for volpos and logpos?
else:
self.I.flush_inodes([block], block.log_timestamp) # Syncs only one inode
maxinode = max(block.inode_number, maxinode)
elif type(block) == BlockLink:
self.I.write_link(block.child_inode, block.parent_inode, block.objname, timepoint=block.log_timestamp)
path = self.I.get_path_for_inode(block.parent_inode, block.log_timestamp)
inode = self.I.get_inode(block.child_inode, block.log_timestamp)
self.I.write_path(os.path.join(path, block.objname), block.child_inode, self._mode2type(inode.st_mode), block.log_timestamp)
elif type(block) == BlockUnlink:
# Look up the path of the parent inode.
# It will always be unique because the parent must be a directory and directories cannot be hard linked!
parent_path = self.I.get_path_for_inode(block.parent_inode, block.log_timestamp)
self.I.unlink(os.path.join(parent_path, block.objname), block.log_timestamp)
elif type(block) == BlockXattr:
self.I.setxattr(block)
elif type(block) == BlockRemovedXattr:
self.I.removexattr(block)
elif type(block) == BlockRename:
self.I.rename(block.oldpath, block.newpath, block.log_timestamp)
else:
sys.exit("Impossible?!")
except NonContiguityError as e:
hdrfslog.error("Attempted to rebuild log but missing volume {}".format(e.missing_vol_number))
except LogParserException as e:
if not self.options["nuclear_fsck"]:
hdrfslog.error("Error attempting to rebuild index: {}. Now would be a good time to restore this volume from backup."
" Use the --ignore-data-errors or --ignore-metadata-errors options to continue processing the Log,"
" though this may or may not result in a usable filesystem. Alternatively, truncate the Log back to the"
" last non-corrupt block using the --nuclear-fsck option, but NOTE THAT THIS IS A DESTRUCTIVE OPERATION.".format(e.message))
os.remove(self.I.db_file)
sys.exit()
else:
# Truncate the log from the offending block.
self.L.truncate_log(e.volpos, e.logpos)
if (e.volpos, e.logpos) == (0,0): # If we've truncated all the way back to zero, delete the index - a whole new FS is required.
os.remove(self.I.db_file)
sys.exit("Corrupt data from block 0. Removing whole filesystem including index.")
hdrfslog.info("Log truncated.")
new_volpos, new_logpos = self.L.get_head_pointer()
self.I.update_istat(new_volpos, new_logpos)
self.I.set_maxinode(maxinode)
self.I.commit()
hdrfslog.info("""Index rebuild complete.""")
def _flushwritebuffer(self):
if self._writebuffer["fh"] is not None:
self.write(None, self._writebuffer["data"], self._writebuffer["offset"], self._writebuffer["fh"], buffered=False)
self._writebuffer["offset"] = None
self._writebuffer["data"] = None
self._writebuffer["fh"] = None
def read(self, path, size, offset, fh):
"Ignore path - use file handle"
assert type(path) == str
assert type(size) == int
assert type(offset) == int
assert type(fh) == int
try:
inode_number, timepoint = self.open_handles[fh]
except KeyError:
raise FuseOSError(errno.EBADF)
# Check to see if the writebuffer has any data pending for this inode.
if self._writebuffer["fh"] is not None:
pending_inode_number, _ = self.open_handles[self._writebuffer["fh"]]
if pending_inode_number == inode_number:
self._flushwritebuffer()
self._cache_inode(inode_number, timepoint) # Likely to already be cached, but may have been uncached
# by a metadata write.
extent_list = self.open_inodes[(inode_number, timepoint)].extent_list
st_size = self.open_inodes[(inode_number, timepoint)].st_size
buf = self.L.read(extent_list, size, offset, st_size)
if len(buf) > 0 and self.options["atime"] and timepoint is None: # Don't update atime when reading historical files
now = int(time.time()*1000000)
self.open_inodes[(inode_number, timepoint)].st_atime = now
self.open_inodes[(inode_number, timepoint)].dirty = True
return buf
def readdir(self, path, offset):
dirents = ['.', '..']
if path == '/':
dirents.append(self.options["history_directory"])
if path == '/' + self.options["history_directory"]:
granularity = self.options["history_directory_granularity"]
return dirents + self.I.get_historical_timepoints(granularity)
timepoint, path = self._parse_path(path)
return dirents + self.I.readdir(path, offset, timepoint)
def destroy(self, path):
"path is always /. Cleans up as part of a clean shutdown of the filesystem."
self.fsync()
with open(self.dedup_file, 'wb') as f:
pickle.dump(self.dedup, f)
self._closeall()
def mkdir(self, path, st_mode):
"""Write to Log, Write to Index.
st_mode is an int representing only the permission bits! 0o777, not 0100777 - and not a tuple either
"""
if self.readonly:
raise FuseOSError(errno.EROFS)
parent_dir, this_dir = os.path.split(path)
parent_dir_inode_number = self.I.get_inode_for_path(parent_dir)
path_inode = self.I.get_inode_for_path(path)
if path_inode is not None:
raise FuseOSError(errno.EEXIST)
elif parent_dir_inode_number is None:
raise FuseOSError(errno.ENOENT)
else:
self._flushwritebuffer() # Always clear the write buffer before writing metadata to the Log
new_inode_number = self.I.get_next_inode()
now = int(time.time()*1000000)
st_uid, st_gid, _ = fuse_get_context()
# POSIX requires that the mtime and ctime of the parent directory are updated
parent_dir_inode = self.I.get_inode(parent_dir_inode_number, now) # Don't need to worry about consulting the cache - dirs are never cached
parent_dir_inode.st_mtime = now
parent_dir_inode.st_ctime = now
self.L.write_metadata(parent_dir_inode)
new_inode = BlockInode(new_inode_number, now, stat.S_IFDIR | st_mode, st_uid, st_gid, now, now, now, now)
self.L.write_metadata(new_inode)
block_link = BlockLink(now, new_inode_number, parent_dir_inode_number, this_dir)
self.L.write_metadata(block_link)
volpos, logpos = self.L.get_head_pointer()
self.I.flush_inodes([parent_dir_inode], now)
self.I.write_inode(new_inode)
self.I.write_link(new_inode_number, parent_dir_inode_number, this_dir)
self.I.write_path(path, new_inode_number, 'd')
self.I.update_istat(volpos, logpos)
self.I.commit()
return 0
def create(self, path, mode):
if self.readonly:
raise FuseOSError(errno.EROFS)
return self.open(path, (mode,))
def mknod(self, path, mode, rdev):
"Note no return value. TODO: Do something with rdev?"
self.open(path, (mode,))
def open(self, path, st_mode, create=True):
"Mode is passed as a 1-tuple. By default will create the file, but this may not be desirable e.g. for hard links"