-
Notifications
You must be signed in to change notification settings - Fork 3
/
eblob_kit.py
executable file
·1606 lines (1254 loc) · 59.5 KB
/
eblob_kit.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/env python
# -*- coding: utf-8 -*-
"""Toolkit for working with eblob blobs."""
import errno
import glob
import hashlib
import json
import logging
import os
import re
import struct
import sys
from datetime import datetime
from datetime import timedelta
import click
import pyhash
def dump_digest(verbosity, results_digest):
"""Dump report to console as JSON.
TODO(karapuz): tests
:param int verbosity: verbosity level, dump JSON only if verbosity <= Verbosity.JSON
:param Dict results_digest: report of command execution.
"""
if verbosity > Verbosity.JSON:
return
try:
json.dump({'files': results_digest}, sys.stdout)
except Exception as e:
logging.error('Failed to dump results to console: %s', e)
def dump_to_file(file_name, results):
"""Dump report to file as JSON.
TODO(karapuz): tests
:param str file_name: name of file to write report to.
:param Dict results: dictionary to dump as JSON.
"""
if not file_name:
return
try:
directory_name = os.path.dirname(os.path.abspath(file_name))
if not os.path.exists(directory_name):
os.makedirs(directory_name)
with open(file_name, 'wb') as out:
json.dump({'files': results}, out)
except Exception as e:
logging.error('Failed to dump json report file %s: %s', file_name, e)
def is_destination_writable(src_path, dst_path, overwrite=False):
"""Check if 'dst_path' file writable.
NOTE: always prohibit writing from src_path to dst_path if it is same file.
"""
return not os.path.exists(dst_path) or (not os.path.samefile(src_path, dst_path) and overwrite)
class ReportType(object):
"""Command result report types.
BASIC - basic stat, e.g. counters, flags etc. Use for console digest report.
EXTENDED - BASIC, plus extended report on touched keys (if available). Use for
report to file/database.
"""
BASIC, EXTENDED = ('REPORT_TYPE_BASIC', 'REPORT_TYPE_EXTENDED')
JSON_OUTPUT = 'JSON_OUTPUT'
LOG_FORMAT = '%(asctime)s %(process)d %(levelname)s: %(message)s (at %(filename)s:%(lineno)s)'
class Verbosity(object):
"""Levels of utility output verbosity.
JSON - print json only digest report to stdout and extended to file if --json-out
option is set. Note that logging is directed to stderr by default.
If verbosity > JSON, then output via standard logger, no json format will be used.
Logger could be configured to output via file. Any level > JSON is implicit for now,
but 'enum' is open for appending of new verbosity levels.
JSON is default verbosity level.
"""
JSON = 0
class ChecksumTypes(object):
SHA512 = 'sha512'
CHUNKED = 'chunked'
class Record(object):
"""Represent record stored in blob."""
def __init__(self, blob, index_idx=None, index_disk_control=None, data_disk_control=None):
self._blob = blob
self._index_idx = index_idx
self._index_disk_control = index_disk_control
self._data_disk_control = data_disk_control
self._elliptics_header = None
self._json_header = None
@property
def index_disk_control(self):
"""DiskControl from index file."""
# index_disk_control isn't available if neither index_disk_control or index_idx was specified
if self._index_disk_control is None and self._index_idx is not None:
self._index_disk_control = self._blob.index[self._index_idx]
return self._index_disk_control
@property
def data_disk_control(self):
"""DiskControl from data file."""
if self._data_disk_control is None:
self._data_disk_control = self._blob.data.read_disk_control(self.index_disk_control.position)
return self._data_disk_control
@property
def elliptics_header(self):
"""Elliptics header from data file."""
if self._elliptics_header is None:
if self.data_disk_control.flags.exthdr:
self._elliptics_header = self._blob.data.read_elliptics_header(self.data_disk_control.position)
else:
self._elliptics_header = EllipticsHeader('\0' * EllipticsHeader.size)
return self._elliptics_header
def verify_checksum(self):
"""Verify record's checksum.
Returns:
bool: whether checksum verification succeeded or not.
"""
self._blob.verify_csum(self.data_disk_control)
def mark_removed(self):
"""Mark record as removed."""
logging.warning('Marking key: %s removed, in blob: "%s", with data-offset: %s, index-offset: %s',
self.data_disk_control.key.encode('hex'),
self._blob.data.path,
self.data_disk_control.position,
self._index_idx * DiskControl.size)
removed_flags = struct.pack('<Q', RecordFlags.REMOVED)
flags_offset = DiskControl.key_size
logging.warning('Updating index: %s, offset: %s, flags: %s', self._blob.index.path,
(self._index_idx * DiskControl.size) + flags_offset, removed_flags.encode('hex'))
self._blob.index.file.seek((self._index_idx * DiskControl.size) + flags_offset)
self._blob.index.file.write(removed_flags)
logging.warning('Updating data: %s, offset: %s, flags: %s', self._blob.data.path,
self.data_disk_control.position + flags_offset, removed_flags.encode('hex'))
self._blob.data.file.seek(self.data_disk_control.position + flags_offset)
self._blob.data.file.write(removed_flags)
index_disk_control = self._blob.index[self._index_idx]
data_disk_control = self._blob.data.read_disk_control(self.index_disk_control.position)
assert index_disk_control == data_disk_control
assert index_disk_control.flags.removed and data_disk_control.flags.removed
def restore(self, checksum_type):
logging.warning('Restoring key: %s, in blob: %s, with data-offset: %s, index-offset: %s,',
self.data_disk_control.key.encode('hex'),
self._blob.data.path,
self.data_disk_control.position,
self._index_idx * DiskControl.size)
if not self.data_disk_control.flags.removed or not self.index_disk_control.flags.removed:
logging.error('Key: %s is not marked removed in blob: %s or index: %s',
self.data_disk_control.key.encode('hex'),
self.data_disk_control.flags.removed, self.index_disk_control.flags.removed)
return False
record_flags = RecordFlags.EXTHDR
if checksum_type == ChecksumTypes.CHUNKED:
record_flags |= RecordFlags.CHUNKED_CSUM
elif checksum_type == ChecksumTypes.SHA512:
pass
elif self._blob.verify_chunked_csum(self.data_disk_control):
record_flags |= RecordFlags.CHUNKED_CSUM
elif self._blob.verify_sha15_csum(self.data_disk_control):
pass
else:
# TODO(shaitan): We could set RecordFlags.NOCSUM for such record but
# it can be an error to assume that there is no checksum if we can't determine
# the checksum type. This record can be corrupted or have new type of checksum which isn't supported yet by
# eblob_kit.
logging.error('Can not determine checksum type, key %s can not be restored',
self.data_disk_control.key.encode('hex'))
return False
restored_flags = struct.pack('<Q', record_flags)
flags_offset = DiskControl.key_size
logging.warning('Updating index: %s, offset: %s, flags: %s', self._blob.index.path,
(self._index_idx * DiskControl.size) + flags_offset, RecordFlags(record_flags))
self._blob.index.file.seek((self._index_idx * DiskControl.size) + flags_offset)
self._blob.index.file.write(restored_flags)
logging.warning('Updating data: %s, offset: %s, flags: %s', self._blob.data.path,
self.data_disk_control.position + flags_offset, RecordFlags(record_flags))
self._blob.data.file.seek(self.data_disk_control.position + flags_offset)
self._blob.data.file.write(restored_flags)
index_disk_control = self._blob.index[self._index_idx]
data_disk_control = self._blob.data.read_disk_control(self.index_disk_control.position)
assert index_disk_control == data_disk_control
assert not index_disk_control.flags.removed and not data_disk_control.flags.removed
assert index_disk_control.flags.exthdr and data_disk_control.flags.exthdr
# assert index_disk_control.flags.chunked_csum and data_disk_control.flags.chunked_csum
return True
class EllipticsHeader(object):
"""Elliptics extension header.
TODO(karapuz): construction from byte stream (static method).
TODO(karapuz): tests.
"""
size = 48
def __init__(self, data):
assert len(data) == EllipticsHeader.size
raw = struct.unpack('<4BI5Q', data)
self.version = raw[0]
self.__pad1 = raw[1:4]
self.jhdr_size = raw[4]
self.timestamp = datetime.fromtimestamp(raw[5]) + timedelta(microseconds=raw[6]/1000)
self.user_flags = raw[7]
self.__pad2 = raw[8:]
def __str__(self):
return 'timestamp: {}, user_flags: {}, version: {}'.format(self.timestamp, self.user_flags, self.version)
class RecordFlags(object):
"""Record flags."""
REMOVED = 1 << 0
NOCSUM = 1 << 1
EXTHDR = 1 << 6
UNCOMMITTED = 1 << 7
CHUNKED_CSUM = 1 << 8
CORRUPTED = 1 << 9
_FLAGS = {
REMOVED: 'removed',
NOCSUM: 'nocsum',
EXTHDR: 'exthdr',
UNCOMMITTED: 'uncommitted',
CHUNKED_CSUM: 'chunked_csum',
CORRUPTED: 'corrupted',
}
def __init__(self, flags):
"""Initialize RecordFlags by value."""
self.flags = flags
def _set(self, flag, value):
if value is True:
self.flags |= flag
elif value is False:
self.flags &= ~flag
removed = property(lambda self: self.flags & self.REMOVED,
lambda self, value: self._set(self.REMOVED, value),
lambda self: self._set(self.REMOVED, False))
nocsum = property(lambda self: self.flags & self.NOCSUM,
lambda self, value: self._set(self.NOCSUM, value),
lambda self: self._set(self.NOCSUM, False))
exthdr = property(lambda self: self.flags & self.EXTHDR,
lambda self, value: self._set(self.EXTHDR, value),
lambda self: self._set(self.EXTHDR, False))
uncommitted = property(lambda self: self.flags & self.UNCOMMITTED,
lambda self, value: self._set(self.UNCOMMITTED, value),
lambda self: self._set(self.UNCOMMITTED, False))
chunked_csum = property(lambda self: self.flags & self.CHUNKED_CSUM,
lambda self, value: self._set(self.CHUNKED_CSUM, value),
lambda self: self._set(self.CHUNKED_CSUM, False))
corrupted = property(lambda self: self.flags & self.CORRUPTED,
lambda self, value: self._set(self.CORRUPTED, value),
lambda self: self._set(self.CORRUPTED, False))
def __str__(self):
"""Convert flags to human-readable view."""
flags = '|'.join(self._FLAGS[x] for x in self._FLAGS if self.flags & x)
return '{:#6x} [{}]'.format(self.flags, flags)
def __cmp__(self, other):
"""Compare self and other."""
return self.flags != other.flags
class DiskControl(object):
"""Eblob record header.
TODO(karapuz): properties docs.
"""
size = 96
key_size = 64
def __init__(self, key, data_size, disk_size, flags, position):
"""Construct DiskControl with provided values."""
self.key = key
self.data_size = data_size
self.disk_size = disk_size
self.flags = flags
self.position = position
@staticmethod
def from_raw(data):
"""Initialize from raw @data."""
assert len(data) == DiskControl.size
key = data[:DiskControl.key_size]
raw = struct.unpack('<4Q', data[DiskControl.key_size:])
flags = RecordFlags(raw[0])
data_size = raw[1]
disk_size = raw[2]
position = raw[3]
return DiskControl(key=key, data_size=data_size, disk_size=disk_size, flags=flags, position=position)
@property
def hex_key(self):
"""Stringify key as hex sequence."""
return self.key.encode('hex')
@property
def raw_data(self):
"""Convert DiskControl to raw format."""
raw = struct.pack('<4Q', self.flags.flags, self.data_size, self.disk_size, self.position)
return self.key + raw
def to_dict(self):
return {
'key': self.key,
'position': self.position,
'data_size': self.data_size,
'disk_size': self.disk_size,
'flags': self.flags.flags,
}
def to_json(self):
return json.dumps(self.to_dict())
def __nonzero__(self):
"""Return true if self is valid."""
return self.data_size != 0 and self.disk_size != 0
def __str__(self):
"""Make human-readable string."""
return '{}: position: {:12} data_size: {} ({}) disk_size: {} ({}) flags: {}'.format(
self.hex_key, self.position,
self.data_size, sizeof_fmt(self.data_size),
self.disk_size, sizeof_fmt(self.disk_size),
self.flags)
def __cmp__(self, other):
"""Compare self with other."""
return cmp((self.key, self.flags, self.data_size, self.disk_size, self.position),
(other.key, other.flags, other.data_size, other.disk_size, other.position))
class IndexFile(object):
"""Abstraction to index file."""
def __init__(self, path, mode='rb'):
"""Initialize IndexFile object again @path."""
if path.endswith('.index.sorted'):
self.sorted = True
elif path.endswith('.index'):
self.sorted = False
else:
raise RuntimeError('{} is not index'.format(path))
self._file = open(path, mode)
@staticmethod
def create(path):
"""Create IndexFile for @path.
NOTE: underlying file is truncuated if exists.
"""
return IndexFile(path=path, mode='wb')
@property
def path(self):
"""Return path to the index file."""
return self._file.name
@property
def file(self):
"""Return file."""
return self._file
def append(self, header):
"""Append header to index."""
self._file.write(header.raw_data)
def size(self):
"""Size of the file."""
return os.fstat(self._file.fileno()).st_size
def __getitem__(self, idx):
assert (idx + 1) * DiskControl.size <= self.size()
self._file.seek(idx * DiskControl.size)
return DiskControl.from_raw(self._file.read(DiskControl.size))
def __len__(self):
"""Return number of headers in index file."""
return self.size() / DiskControl.size
def __iter__(self):
"""Iterate over headers in the index."""
self._file.seek(0)
index_content = self._file.read()
for offset in xrange(0, len(index_content), DiskControl.size):
data = index_content[offset: offset + DiskControl.size]
if len(data) != DiskControl.size:
raise EOFError('Failed to read header at offset {} of {} ({})'
.format(offset, self.path, self.size()))
yield DiskControl.from_raw(data)
class DataFile(object):
"""Abstraction to data file."""
def __init__(self, path, mode='rb'):
"""Initialize DataFile object again @path."""
self.sorted = os.path.exists(path + '.data_is_sorted') and \
os.path.exists(path + '.index.sorted')
self._file = open(path, mode)
@property
def path(self):
"""Return path to the data file."""
return self._file.name
@property
def file(self):
"""Return file."""
return self._file
def read_disk_control(self, position):
"""Read DiskControl at @offset."""
return DiskControl.from_raw(self.read(position, DiskControl.size))
def read_elliptics_header(self, position):
"""Read header at position."""
return EllipticsHeader(self.read(position + DiskControl.size, EllipticsHeader.size))
def read(self, offset, size):
"""Read @size bytes from @offset."""
if offset > len(self):
raise EOFError('Illegal seek: offset ({}) is out of file ({})'
.format(offset, len(self)))
if offset + size > len(self):
raise EOFError('Illegal seek: offset + size ({}) is out of file ({})'
.format(offset + size, len(self)))
self._file.seek(offset)
return self._file.read(size)
def __iter__(self):
"""Iterate over headers in the blob."""
self._file.seek(0)
while True:
offset = self._file.tell()
data = self._file.read(DiskControl.size)
if len(data) == 0:
break
if len(data) != DiskControl.size:
raise EOFError('Failed to read header at offset: {}'.format(offset))
header = DiskControl.from_raw(data)
yield header
self._file.seek(offset + header.disk_size)
def __len__(self):
"""Return size of data file."""
return os.fstat(self._file.fileno()).st_size
class Blob(object):
"""Abstraction to blob consisted from index and data files."""
def __init__(self, path, mode='rb'):
"""Initialize Blob object against @path."""
if os.path.exists(path + '.index.sorted'):
self._index_file = IndexFile(path + '.index.sorted', mode)
elif os.path.exists(path + '.index'):
self._index_file = IndexFile(path + '.index', mode)
else:
raise IOError('Could not find index for {}'.format(path))
self._data_file = DataFile(path, mode)
@staticmethod
def create(path, mark_index_sorted=False):
"""Create new Blob at @path.
NOTE: underlying files are truncuated if they are exist.
"""
index_suffix = '.index.sorted' if mark_index_sorted else '.index'
create_mode = 'wb'
# Index is checked for existance on Blob creation, so we should create it
# beforehand, but data file would be created within Blob constructor.
open(path + index_suffix, create_mode).close()
return Blob(path=path, mode=create_mode)
@property
def index(self):
"""Return index file."""
return self._index_file
@property
def data(self):
"""Return data file."""
return self._data_file
def _murmur_chunk(self, chunk):
"""Apply murmurhash to chunk and return raw result."""
chunk_size = 4096
result = 0
hasher = pyhash.murmur2_x64_64a()
while chunk:
result = hasher(chunk[:chunk_size], seed=result)
chunk = chunk[chunk_size:]
return struct.pack('<Q', result)
def murmur_record_data(self, header, chunk_size):
"""Apply murmurhash to record's data pointed by @header."""
self.data.file.seek(header.position + DiskControl.size)
length = header.data_size
while length:
chunk_size = min(length, chunk_size)
yield self._murmur_chunk(self.data.file.read(chunk_size))
length -= chunk_size
def verify_chunked_csum(self, header):
"""Verify chunked checksum of the record pointer by @header."""
footer_size = 8
chunk_size = 1 << 20
chunks_count = ((header.disk_size - DiskControl.size - footer_size - 1) / (chunk_size + footer_size)) + 1
footer_offset = header.position + header.disk_size - (chunks_count + 1) * footer_size
calculated_csum = ''.join(self.murmur_record_data(header, chunk_size))
self.data.file.seek(footer_offset)
stored_csum = self.data.file.read(len(calculated_csum))
if calculated_csum != stored_csum:
logging.error('Invalid csum, stored (%s) != calculated (%s): %s',
stored_csum.encode('hex'),
calculated_csum.encode('hex'),
header)
return False
return True
def verify_sha15_csum(self, header):
"""Verify sha512 checksum of the record pointer by @header."""
self.data.file.seek(header.position + DiskControl.size)
length = header.data_size
chunk = 32768
hasher = hashlib.sha512()
while length:
chunk = min(length, chunk)
hasher.update(self.data.file.read(chunk))
length -= chunk
calculated_csum = hasher.digest()
footer_size = 64 + 8
self.data.file.seek(header.position + header.disk_size - footer_size)
stored_csum = self.data.file.read(footer_size)[:64]
if calculated_csum != stored_csum:
logging.error('Invalid csum, stored (%s) != calculated (%s): %s',
stored_csum.encode('hex'),
calculated_csum.encode('hex'),
header)
return False
return True
def verify_csum(self, header):
"""Verify checksum of the record pointed by @header."""
if header.flags.nocsum:
return True
if header.flags.chunked_csum:
return self.verify_chunked_csum(header)
else:
return self.verify_sha15_csum(header)
def sizeof_fmt(num, suffix='B'):
"""Convert @num into human-readable string."""
for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'):
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Yi', suffix)
def range_fmt(start, end):
"""Format @start, @end range as [{start}, {end}] ({size})."""
return '[{}, {}) ({})'.format(start, end, sizeof_fmt(end - start))
def header_range_fmt(header):
"""Format header as [{start}, {end}] ({size})."""
return range_fmt(header.position, header.position + header.disk_size)
def get_checksum_size(header):
"""Return checksum for the header."""
if header.flags.nocsum:
return 0
if header.flags.chunked_csum:
footer_size = 8
chunk_size = 1 << 20 # 1 MiB
return (((header.data_size - 1) / chunk_size) + 2) * footer_size
else:
return 64
def copy_record(src, dst, header):
"""Copy record from @src to @dst specified by @header."""
new_header = header.key + struct.pack('<4Q', header.flags.flags, header.data_size,
header.disk_size, dst.data.file.tell())
dst.index.file.write(new_header)
dst.data.file.write(new_header)
chunk_size = 409600
length = header.disk_size - DiskControl.size
src.data.file.seek(header.position + DiskControl.size)
while length > 0:
chunk_size = min(chunk_size, length)
dst.data.file.write(src.data.file.read(chunk_size))
length -= chunk_size
def files(path):
"""Iterate over files by pattern."""
blob_re = re.compile(path + '-0.[0-9]+$')
return (filename for filename in glob.iglob(path + '-0.*')
if blob_re.match(filename))
def read_keys(keys_path, short):
with open(keys_path, 'r') as keys_file:
# 28 is 12 bytes + '...' + 12 bytes + '\n' - 'f1ddefc58a5d...89b550cc034c\n'
# 129 is 128 bytes of key + '\n'
return [line[:-1] for line in keys_file if len(line) == (28 if short else 129)]
class BlobRepairerStat(object):
"""Blob repair process stat.
TODO(karapuz): tests
"""
def __init__(self):
"""Construct BlobRepairerStat with zeroed stat."""
self.index_order_error = False
self.invalid_index_size = False
self.index_malformed_headers = 0
self.index_malformed_headers_keys = set()
self.corrupted_data_headers = 0
self.corrupted_data_headers_keys = set()
self.corrupted_data_headers_size = 0
self.index_removed_headers = 0
self.index_removed_headers_keys = set()
self.index_removed_headers_size = 0
self.index_uncommitted_headers = 0
self.index_uncommitted_headers_keys = set()
self.index_uncommitted_headers_size = 0
self.data_recoverable_headers = []
self.mismatched_headers = []
self.holes = 0
self.holes_size = 0
@property
def as_dict(self):
"""Compose stat report as dict.
:rtype: Dict[str, (numeric | List)]
"""
result = self.as_digest_dict
result.update({
'index_malformed_headers_keys':
list(self.index_malformed_headers_keys),
'corrupted_data_headers_keys':
list(self.corrupted_data_headers_keys),
'index_removed_headers_keys':
list(self.index_removed_headers_keys),
'index_uncommitted_headers_keys':
list(self.index_uncommitted_headers_keys),
'data_recoverable_headers_keys': [
k.hex_key for k in self.data_recoverable_headers],
# TODO(karapuz): put here hashes from both index and data.
'mismatched_headers': [
d.hex_key for _, d in self.mismatched_headers],
})
return result
@property
def as_digest_dict(self):
"""Compose repair report digest."""
return {
'index_order_error': self.index_order_error,
'invalid_index_size': self.invalid_index_size,
'index_malformed_headers': self.index_malformed_headers,
'corrupted_data_headers': self.corrupted_data_headers,
'index_removed_headers': self.index_removed_headers,
'index_uncommitted_headers': self.index_uncommitted_headers,
}
class BlobRepairer(object):
"""Check and repair blob."""
def __init__(self, path):
"""Initialize BlobRepairer for blob at @path."""
self._blob = Blob(path)
self._valid = True
self._index_headers = []
self._stat = BlobRepairerStat()
@property
def stat(self):
"""Return BlobRepairerStat object."""
return self._stat
@property
def valid(self):
"""Return current repairer status.
True, if it wasn't any inconsistency found while processing blob.
"""
return self._valid
def check_header(self, header):
"""Check header correctness."""
if header.disk_size == 0:
logging.error('malformed header has empty disk_size: %s', header)
return False
if header.position + header.disk_size > len(self._blob.data):
logging.error('malformed header has position (%d) + disk_size (%d) '
'is out of %s (%d): %s',
header.position, header.disk_size,
self._blob.data.path, len(self._blob.data), header)
return False
if not header.flags.uncommitted and not header.flags.removed:
if header.data_size == 0:
logging.error('malformed header has empty data_size but it is committed: %s', header)
return False
extension_header_size = EllipticsHeader.size if header.flags.exthdr else 0
checksum_size = get_checksum_size(header)
if header.data_size + extension_header_size + checksum_size > header.disk_size:
logging.error('malformed header has data_size (%d) + extension_header_size (%d) + '
'checksum_size (%d) > disk_size (%d): %s',
header.data_size, extension_header_size, checksum_size,
header.disk_size, header)
return False
return True
def check_hole(self, position, end):
"""Check headers in data in area [@position, @end)."""
logging.error('I have found hole in data %s which is not '
'covered by valid headers from index',
range_fmt(position, end))
while position < end:
try:
data_header = self._blob.data.read_disk_control(position)
except EOFError as exc:
logging.error('Failed to read header from data: %s', exc)
break
if data_header.position != position:
logging.error('Header in data at offset %d has invalid offset %d. '
'I will correct position of the record and '
'will try to use corrected version of the header',
position, data_header.position)
data_header.position = position
if not self.check_header(data_header):
logging.error('I have found record which is missed in index and '
'has invalid header in data at %d. I can not recover it, '
'so I will skip it and everything in %s from data: %s',
position, range_fmt(position, end), data_header)
break
elif data_header.position + data_header.disk_size > end:
logging.error('Header (%s) is beyond the hole %s: %s',
header_range_fmt(data_header),
range_fmt(position, end),
data_header)
break
else:
logging.info('I have found valid header at position %d in data and '
'will add it to headers list', position)
if not data_header.flags.removed and not data_header.flags.uncommitted:
self._stat.data_recoverable_headers.append(data_header)
position += data_header.disk_size
if position != end:
self._stat.holes += 1
self._stat.holes_size += end - position
def resolve_mispositioned_record(self, header_idx, position, valid_headers):
"""Try to resolve mispositioned record failure.
Return whether header at @header_idx should be skipped.
"""
header = self._index_headers[header_idx]
assert header_idx > 0, 'Mispositioned record failure can not occur with first header'
previous_header = self._index_headers[header_idx - 1]
assert position == previous_header.position + previous_header.disk_size,\
'Previous header should be placed exactly before position'
assert previous_header.position <= header.position, 'Headers should be sorted by position'
data_header = self._blob.data.read_disk_control(header.position)
if header != data_header:
logging.error('Mispositioned record does not match header from data. Skip it: %s',
header)
return True
elif valid_headers and valid_headers[-1] == previous_header:
logging.error('Mispositioned record does match header from data, so I remove '
'previous conflicting record which was correct. '
'current: %s, previous: %s', header, previous_header)
del valid_headers[-1]
elif self._stat.mismatched_headers and self._stat.mismatched_headers[-1][0] == previous_header:
logging.error('Mispositioned record does match header from data, so I remove '
'previous conflicting record which was mismatched. '
'current: %s, previous: %s', header, previous_header)
del self._stat.mismatched_headers[-1]
return False
def resolve_mismatch(self, index_header, data_header, valid_headers):
"""Try to resolve mismatch if it is detected."""
self._stat.mismatched_headers.append((index_header, data_header))
self._valid = False
logging.error('Headers mismatches: data_header: %s, index_header: %s',
data_header, index_header)
def check_index(self, fast):
"""Check that index file is correct."""
prev_key = None
try:
logging.info('Checking index: %s', self._blob.index.path)
for header in self._blob.index:
if fast and not self._valid:
# return if it is fast-check and there was an error
return
if self.check_header(header):
self._index_headers.append(header)
if prev_key and self._blob.index.sorted:
if prev_key > header.key:
self._valid = False
self._blob.index.sorted = False
self._stat.index_order_error = True
prev_key = header.key
else:
self._stat.index_malformed_headers_keys.add(header.hex_key)
self._stat.index_malformed_headers += 1
self._valid = False
except EOFError as exc:
logging.error('Failed to read header path %s, error %s. Skip other headers in index',
self._blob.index.path,
exc)
self._stat.invalid_index_size = True
self._valid = False
if fast and not self._valid:
return
if self._stat.index_order_error:
logging.error('%s is supposed to be sorted, but it has disordered headers', self._blob.index.path)
if self._stat.index_malformed_headers or self._stat.invalid_index_size:
logging.error('%s has %s malformed and %s valid headers',
self._blob.index.path,
self._stat.index_malformed_headers,
len(self._index_headers))
else:
logging.info('All %d headers in %s are valid',
len(self._index_headers),
self._blob.index.path)
if not fast:
self._index_headers = sorted(self._index_headers, key=lambda h: h.position)
def print_check_report(self):
"""Print report after check."""
if self._valid:
report = '{} is valid and has:'.format(self._blob.data.path)
report += '\n\t{} valid records'.format(len(self._index_headers))
report += '\n\t{} removed records ({})'.format(
self._stat.index_removed_headers, sizeof_fmt(self._stat.index_removed_headers_size))
report += '\n\t{} uncommitted records ({})'.format(
self._stat.index_uncommitted_headers, sizeof_fmt(self._stat.index_uncommitted_headers_size))
logging.info(report)
return
report = '{} has:'.format(self._blob.data.path)
report += '\n\t{} headers ({}) from index are valid'.format(
len(self._index_headers), sizeof_fmt(sum(h.disk_size for h in self._index_headers)))
if self._stat.index_removed_headers:
report += '\n\t{} headers ({}) from index are valid and marked as removed'.format(
self._stat.index_removed_headers, sizeof_fmt(self._stat.index_removed_headers_size))
if self._stat.index_uncommitted_headers:
report += '\n\t{} headers ({}) from index are valid and marked as uncommitted'.format(
self._stat.index_uncommitted_headers, sizeof_fmt(self._stat.index_uncommitted_headers_size))
if self._stat.mismatched_headers:
report += '\n\t{} headers which are different in the blob and in the index'.format(
len(self._stat.mismatched_headers))
if self._stat.data_recoverable_headers:
report += '\n\t{} headers ({}) can be recovered from data'.format(
len(self._stat.data_recoverable_headers),
sizeof_fmt(sum(h.disk_size for h in self._stat.data_recoverable_headers)))
if self._stat.holes:
report += '\n\t{} holes ({}) in blob which are not marked'.format(
self._stat.holes, sizeof_fmt(self._stat.holes_size))
if self._stat.index_order_error:
report += '\n\t{} is supposed to be sorted but it has disordered header'.format(
self._blob.index.path)
if self._stat.corrupted_data_headers:
report += '\n\t{} headers ({}) has corrupted data'.format(
self._stat.corrupted_data_headers, sizeof_fmt(self._stat.corrupted_data_headers_size))