forked from bitdust-io/devel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup_fs.py
2367 lines (2040 loc) · 79.7 KB
/
backup_fs.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/python
# backup_fs.py
#
# Copyright (C) 2008 Veselin Penev, https://bitdust.io
#
# This file (backup_fs.py) is part of BitDust Software.
#
# BitDust is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# BitDust Software 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with BitDust Software. If not, see <http://www.gnu.org/licenses/>.
#
# Please contact us if you have any questions at [email protected]
#
#
#
#
"""
.. module:: backup_fs.
This is some kind of file system.
To store backed up data on remote peers we can not use original files and folders names -
they must be encrypted or indexed. I decide to use index, but keep the files and folders structure.
Instead of names I am using numbers.
For example::
C:/Documents and Settings/veselin/Application Data/Google/
Can have a path ID like this::
0/2/0/5/23
Linux paths can be indexed same way::
/home/veselin/Documents/document.pdf
Can be translated to::
0/2/4/18
The software keeps 2 index dictionaries in the memory:
* path -> ID
* ID -> path
Those dictionaries are trees - replicates the file system structure.
"""
#------------------------------------------------------------------------------
from __future__ import absolute_import
from __future__ import print_function
from six.moves import range
from io import StringIO
#------------------------------------------------------------------------------
_Debug = False
_DebugLevel = 10
#------------------------------------------------------------------------------
import os
import sys
import time
import json
import random
#------------------------------------------------------------------------------
if __name__ == '__main__':
import os.path as _p
sys.path.insert(0, _p.abspath(_p.join(_p.dirname(_p.abspath(sys.argv[0])), '..')))
#------------------------------------------------------------------------------
from bitdust.lib import strng
from bitdust.logs import lg
from bitdust.system import bpio
from bitdust.main import settings
from bitdust.main import listeners
from bitdust.services import driver
from bitdust.lib import misc
from bitdust.lib import packetid
from bitdust.lib import jsn
from bitdust.crypt import my_keys
from bitdust.contacts import identitycache
from bitdust.interface import api
from bitdust.userid import global_id
from bitdust.userid import id_url
from bitdust.userid import my_id
#------------------------------------------------------------------------------
INFO_KEY = 'i'
UNKNOWN = -1
FILE = 0
DIR = 1
TYPES = {
UNKNOWN: 'UNKNOWN',
FILE: 'FILE',
DIR: 'DIR',
}
#------------------------------------------------------------------------------
_FileSystemIndexByName = {}
_FileSystemIndexByID = {}
_RevisionNumber = {}
_Stats = {}
#------------------------------------------------------------------------------
def init():
"""
Some initial steps can be done here.
"""
if _Debug:
lg.out(_DebugLevel, 'backup_fs.init')
LoadAllIndexes()
SaveIndex()
def shutdown():
"""
Should be called when the program is finishing.
"""
if _Debug:
lg.out(_DebugLevel, 'backup_fs.shutdown')
ClearAllIndexes()
#------------------------------------------------------------------------------
def fs(customer_idurl=None, key_alias='master'):
"""
Access method for forward index: [path] -> [ID].
"""
global _FileSystemIndexByName
if customer_idurl is None:
customer_idurl = my_id.getIDURL()
customer_idurl = id_url.field(customer_idurl)
if customer_idurl not in _FileSystemIndexByName:
_FileSystemIndexByName[customer_idurl] = {}
if _Debug:
lg.dbg(_DebugLevel, 'new customer registered : %r' % customer_idurl)
if key_alias is None:
return _FileSystemIndexByName[customer_idurl]
if key_alias not in _FileSystemIndexByName[customer_idurl]:
_FileSystemIndexByName[customer_idurl][key_alias] = {}
if _Debug:
lg.dbg(_DebugLevel, 'new key alias registered for customer %r : %r' % (customer_idurl, key_alias))
return _FileSystemIndexByName[customer_idurl][key_alias]
def fsID(customer_idurl=None, key_alias='master'):
"""
Access method for backward index: [ID] -> [path].
"""
global _FileSystemIndexByID
if customer_idurl is None:
customer_idurl = my_id.getIDURL()
customer_idurl = id_url.field(customer_idurl)
if customer_idurl not in _FileSystemIndexByID:
_FileSystemIndexByID[customer_idurl] = {}
if _Debug:
lg.dbg(_DebugLevel, 'new customer registered : %r' % customer_idurl)
if key_alias is None:
return _FileSystemIndexByID[customer_idurl]
if key_alias not in _FileSystemIndexByID[customer_idurl]:
_FileSystemIndexByID[customer_idurl][key_alias] = {}
if _Debug:
lg.dbg(_DebugLevel, 'new key alias registered for customer %r : %r' % (customer_idurl, key_alias))
return _FileSystemIndexByID[customer_idurl][key_alias]
#------------------------------------------------------------------------------
def revision(customer_idurl=None, key_alias='master'):
"""
Method to access current revision number of the corresponding catalogue.
"""
global _RevisionNumber
if customer_idurl is None:
customer_idurl = my_id.getIDURL()
customer_idurl = id_url.field(customer_idurl)
if customer_idurl not in _RevisionNumber:
_RevisionNumber[customer_idurl] = {}
if _Debug:
lg.dbg(_DebugLevel, 'new customer registered : %r' % customer_idurl)
if key_alias not in _RevisionNumber[customer_idurl]:
_RevisionNumber[customer_idurl][key_alias] = -1
if _Debug:
lg.dbg(_DebugLevel, 'new key alias registered for customer %r : %r' % (customer_idurl, key_alias))
return _RevisionNumber[customer_idurl][key_alias]
def commit(new_revision_number=None, customer_idurl=None, key_alias='master'):
"""
Need to be called after any changes in the index database.
This increase revision number by 1 or set revision to ``new_revision_number`` if not None.
"""
global _RevisionNumber
if customer_idurl is None:
customer_idurl = my_id.getIDURL()
customer_idurl = id_url.field(customer_idurl)
if customer_idurl not in _RevisionNumber:
_RevisionNumber[customer_idurl] = {}
if _Debug:
lg.dbg(_DebugLevel, 'new customer registered : %r' % customer_idurl)
if key_alias not in _RevisionNumber[customer_idurl]:
_RevisionNumber[customer_idurl][key_alias] = 0
if _Debug:
lg.dbg(_DebugLevel, 'new key alias registered for customer %r : %r' % (customer_idurl, key_alias))
old_v = _RevisionNumber[customer_idurl][key_alias]
if new_revision_number is not None:
_RevisionNumber[customer_idurl][key_alias] = new_revision_number
else:
_RevisionNumber[customer_idurl][key_alias] += 1
new_v = _RevisionNumber[customer_idurl][key_alias]
if _Debug:
lg.args(_DebugLevel, old=old_v, new=new_v, c=customer_idurl, k=key_alias)
if old_v == -1 and new_v > old_v:
lg.info('committed first revision %r for customer:%s key_alias:%s' % (new_v, customer_idurl, key_alias))
return old_v, new_v
def forget(customer_idurl=None, key_alias=None):
"""
Release currently known revision number for the corresponding index.
"""
global _RevisionNumber
if _Debug:
lg.args(_DebugLevel, c=customer_idurl, k=key_alias)
if customer_idurl is None:
_RevisionNumber.clear()
return
customer_idurl = id_url.field(customer_idurl)
if customer_idurl not in _RevisionNumber:
lg.warn('customer %r was not registered' % customer_idurl)
return
if key_alias is None:
_RevisionNumber[customer_idurl].clear()
return
if key_alias not in _RevisionNumber[customer_idurl]:
lg.warn('key alias %r was not registered for customer %r' % (key_alias, customer_idurl))
return
_RevisionNumber[customer_idurl].pop(key_alias)
#------------------------------------------------------------------------------
def known_customers():
global _FileSystemIndexByID
return list(_FileSystemIndexByID.keys())
def known_keys_aliases(customer_idurl):
global _FileSystemIndexByID
if customer_idurl is None:
customer_idurl = my_id.getIDURL()
customer_idurl = id_url.field(customer_idurl)
return list(_FileSystemIndexByID.get(customer_idurl, {}).keys())
#------------------------------------------------------------------------------
def stats(customer_idurl=None, key_alias='master'):
global _Stats
if customer_idurl is None:
customer_idurl = my_id.getIDURL()
customer_idurl = id_url.field(customer_idurl)
if customer_idurl not in _Stats:
return {}
if key_alias not in _Stats[customer_idurl]:
return {}
return _Stats[customer_idurl][key_alias]
def set_stat(dict_value, customer_idurl=None, key_alias='master'):
global _Stats
if customer_idurl is None:
customer_idurl = my_id.getIDURL()
customer_idurl = id_url.field(customer_idurl)
if customer_idurl not in _Stats:
_Stats[customer_idurl] = {}
if key_alias not in _Stats[customer_idurl]:
_Stats[customer_idurl][key_alias] = {
'items': 0,
'files': 0,
'folders': 0,
'size_files': 0,
'size_folders': 0,
'size_backups': 0,
}
v = _Stats[customer_idurl][key_alias]
v.update(dict_value)
_Stats[customer_idurl][key_alias] = v
def total_stats(customer_idurl=None, exclude=False):
global _Stats
if customer_idurl is None:
customer_idurl = my_id.getIDURL()
customer_idurl = id_url.field(customer_idurl)
ret = {
'items': 0,
'files': 0,
'folders': 0,
'size_files': 0,
'size_folders': 0,
'size_backups': 0,
'keys': 0,
}
if exclude:
for another_customer_idurl in known_customers():
if id_url.is_the_same(customer_idurl, another_customer_idurl):
continue
for val in _Stats.get(another_customer_idurl, {}).values():
for k in val.keys():
ret[k] += val[k]
ret['keys'] += 1
else:
for val in _Stats.get(customer_idurl, {}).values():
for k in val.keys():
ret[k] += val[k]
ret['keys'] += 1
return ret
#------------------------------------------------------------------------------
def counter(customer_idurl=None, key_alias='master'):
"""
Software keeps track of total number of indexed items, this returns that
value.
"""
return stats(customer_idurl=customer_idurl, key_alias=key_alias).get('items')
def numberfiles(customer_idurl=None, key_alias='master'):
"""
Number of indexed files.
"""
return stats(customer_idurl=customer_idurl, key_alias=key_alias).get('files')
def numberfolders(customer_idurl=None, key_alias='master'):
"""
Number of indexed files.
"""
return stats(customer_idurl=customer_idurl, key_alias=key_alias).get('folders')
def sizefiles(customer_idurl=None, key_alias='master'):
"""
Total size of all indexed files.
"""
return stats(customer_idurl=customer_idurl, key_alias=key_alias).get('size_files')
def sizefolders(customer_idurl=None, key_alias='master'):
"""
Total size of all indexed folders.
May be incorrect, because folder size is not calculated regular yet.
"""
return stats(customer_idurl=customer_idurl, key_alias=key_alias).get('size_folders')
def sizebackups(customer_idurl=None, key_alias='master'):
"""
Total size of all indexed backups.
"""
return stats(customer_idurl=customer_idurl, key_alias=key_alias).get('size_backups')
#------------------------------------------------------------------------------
class FSItemInfo():
"""
A class to represent a remote file or folder.
"""
def __init__(self, name='', path_id='', typ=UNKNOWN, key_id=None):
self.unicodename = strng.to_text(name)
self.path_id = path_id
self.type = typ
self.size = -1
self.key_id = key_id
self.versions = {}
def __repr__(self):
return '<%s %s %d %s>' % (TYPES[self.type], misc.unicode_to_str_safe(self.name()), self.size, self.key_id)
def to_json(self):
return {
'name': self.unicodename,
'path_id': self.path_id,
'type': self.type,
'size': self.size,
'key_id': self.key_id,
'versions': self.versions,
}
def filename(self):
return os.path.basename(self.unicodename)
def name(self):
return self.unicodename
def key_alias(self):
if not self.key_id:
return 'master'
return self.key_id.split('$')[0]
def exist(self):
return self.size != -1
def set_size(self, sz):
self.size = sz
def read_stats(self, path):
if not bpio.pathExist(path):
return False
if bpio.pathIsDir(path):
return False
try:
s = os.stat(path)
except:
try:
s = os.stat(path.decode('utf-8'))
except:
lg.exc()
return False
self.size = int(s.st_size)
return True
def read_versions(self, local_path):
path = bpio.portablePath(local_path)
if not bpio.pathExist(path):
return 0
if not os.access(path, os.R_OK):
return 0
totalSize = 0
for version in bpio.list_dir_safe(path):
if self.get_version_info(version)[0] >= 0:
continue
versionSize = 0
maxBlock = -1
if not packetid.IsCanonicalVersion(version):
continue
versionpath = os.path.join(path, version)
if not bpio.pathExist(versionpath):
continue
if not os.access(versionpath, os.R_OK):
return 0
for filename in bpio.list_dir_safe(versionpath):
filepath = os.path.join(versionpath, filename)
if not packetid.IsPacketNameCorrect(filename):
lg.warn('incorrect file name found: %s' % filepath)
continue
try:
blockNum, supplierNum, _ = filename.split('-')
blockNum, supplierNum = int(blockNum), int(supplierNum)
except:
lg.warn('incorrect file name found: %s' % filepath)
continue
try:
sz = int(os.path.getsize(filepath))
except:
lg.exc()
sz = 0
# TODO:
# add some bytes because on remote machines all files are stored as signed.Packet()
# so they have a header and files size will be bigger than on local machine
# we do not know how big head is, so just add an approximate value
versionSize += sz + 1024
maxBlock = max(maxBlock, blockNum)
self.set_version_info(version, maxBlock, versionSize)
totalSize += versionSize
return totalSize
def add_version(self, version):
self.versions[version] = [-1, -1]
def set_version_info(self, version, maxblocknum, sizebytes):
self.versions[version] = [maxblocknum, sizebytes]
def get_version_info(self, version):
return self.versions.get(version, [-1, -1])
def get_version_size(self, version):
return self.versions.get(version, [-1, -1])[1]
def delete_version(self, version):
self.versions.pop(version, None)
def has_version(self, version):
return version in self.versions
def any_version(self):
return len(self.versions) > 0
def list_versions(self, sorted=False, reverse=False):
if sorted:
return misc.sorted_versions(list(self.versions.keys()), reverse)
return list(self.versions.keys())
def get_versions(self):
return self.versions
def get_latest_version(self):
if len(self.versions) == 0:
return None
return self.list_versions(True)[0]
def pack_versions(self):
out = []
for version in self.list_versions(True):
info = self.versions[version]
out.append(version + ':' + str(info[0]) + ':' + str(info[1]))
return ' '.join(out)
def unpack_versions(self, inpt):
for word in inpt.split(' '):
if not word.strip():
continue
try:
version, maxblock, sz = word.split(':')
maxblock, sz = int(maxblock), int(sz)
except:
version, maxblock, sz = word, -1, -1
self.set_version_info(version, maxblock, sz)
def serialize(self, encoding='utf-8', to_json=False):
if _Debug:
lg.args(_DebugLevel, k=self.key_id, pid=self.path_id, v=list(self.versions.keys()), i=id(self), iv=id(self.versions))
if to_json:
return {
'n': strng.to_text(self.unicodename, encoding=encoding),
'i': strng.to_text(self.path_id),
't': self.type,
's': self.size,
'k': self.key_id,
'v': [{
'n': v,
'b': self.versions[v][0],
's': self.versions[v][1],
} for v in self.list_versions(sorted=True)],
}
e = strng.to_text(self.unicodename, encoding=encoding)
return '%s %d %d %s\n%s\n' % (self.path_id, self.type, self.size, self.pack_versions(), e)
def unserialize(self, src, decoding='utf-8', from_json=False):
if from_json:
try:
self.unicodename = strng.to_text(src['n'], encoding=decoding)
self.path_id = strng.to_text(src['i'], encoding=decoding)
self.type = src['t']
self.size = src['s']
self.key_id = my_keys.latest_key_id(strng.to_text(src['k'], encoding=decoding))
self.versions = {strng.to_text(v['n']): [v['b'], v['s']] for v in src['v']}
except:
lg.exc()
raise KeyError('Incorrect item format:\n%s' % src)
if _Debug:
lg.args(_DebugLevel, k=self.key_id, pid=self.path_id, v=list(self.versions.keys()), i=id(self), iv=id(self.versions))
return True
try:
details, name = strng.to_text(src, encoding=decoding).split('\n')[:2]
except:
raise Exception('incorrect item format:\n%s' % src)
if not details or not name:
raise Exception('incorrect item format:\n%s' % src)
try:
self.unicodename = name
details = details.split(' ')
self.path_id, self.type, self.size = details[:3]
self.type, self.size = int(self.type), int(self.size)
self.unpack_versions(' '.join(details[3:]))
except:
lg.exc()
raise KeyError('incorrect item format:\n%s' % src)
if _Debug:
lg.args(_DebugLevel, k=self.key_id, pid=self.path_id, v=list(self.versions.keys()), i=id(self), iv=id(self.versions))
return True
#------------------------------------------------------------------------------
def MakeID(itr, randomized=True):
"""
Create a new unique number for the file or folder to create a index ID.
Parameter ``itr`` is a reference for a single item in the ``fs()``.
"""
current_ids = []
for k in itr.keys():
if k == 0:
continue
if k == settings.BackupIndexFileName() or packetid.IsIndexFileName(k):
continue
try:
if isinstance(itr[k], int):
current_ids.append(int(itr[k]))
elif isinstance(itr[k], dict) and 0 in itr[k]:
current_ids.append(int(itr[k][0]))
else:
continue
except:
lg.exc()
continue
new_id = 0
if randomized:
digits = 1
while True:
attempts = 0
new_id = int(random.choice('0123456789'))
while new_id in current_ids and attempts <= 2:
new_id = int(''.join([v() for v in [
lambda: random.choice('0123456789'),
]*digits]))
attempts += 1
if new_id not in current_ids:
return new_id
digits += 1
while new_id in current_ids:
new_id += 1
return new_id
#------------------------------------------------------------------------------
def AddFile(path, read_stats=False, iter=None, iterID=None, key_id=None):
"""
Scan all components of the ``path`` and create an item in the index for
that file.
>>> import backup_fs
>>> backup_fs.AddFile('C:/Documents and Settings/veselin/Application Data/Google/GoogleEarth/myplaces.kml')
('0/0/0/0/0/0/0', {0: 0, u'myplaces.kml': 0}, {'i': <PARENT GoogleEarth -1>, 0: <FILE myplaces.kml -1>})
Here path must be in "portable" form - only '/' allowed, assume path is a file, not a folder.
"""
parts = bpio.remotePath(path).split('/')
key_alias = 'master'
if key_id:
key_alias = key_id.split('$')[0]
if iter is None:
iter = fs(key_alias=key_alias)
if iterID is None:
iterID = fsID(key_alias=key_alias)
resultID = ''
parentKeyID = None
# build whole tree, skip the last part
for i in range(len(parts) - 1):
name = parts[i]
if not name:
continue
p = '/'.join(parts[:i + 1])
if bpio.Linux() or bpio.Mac():
p = '/' + p
if name not in iter:
# made a new ID for this folder, ID starts from 0. new folders will get the last ID +1
# or it may find a free place in the middle, if some folders or files were removed before
# this way we try to protect the files and directories names. we store index in the encrypted files
id = MakeID(iter)
# build a unique backup id for that file including all indexed ids
resultID += '/' + str(id)
# make new sub folder
ii = FSItemInfo(name=name, path_id=resultID.lstrip('/'), typ=DIR, key_id=(key_id or parentKeyID))
if read_stats:
ii.read_stats(p)
# we use 0 key as decimal value, all files and folders are strings - no conflicts possible 0 != '0'
iter[ii.name()] = {0: id}
# also save index from opposite side
iterID[id] = {INFO_KEY: ii}
else:
# get an existing ID from the index
id = iter[name][0]
# go down into the existing forest
resultID += '/' + str(id)
# move down to the next level
parentKeyID = iterID[id][INFO_KEY].key_id
iter = iter[name]
iterID = iterID[id]
# the last part of the path is a filename
filename = parts[-1]
# make an ID for the filename
id = MakeID(iter)
resultID += '/' + str(id)
resultID = resultID.lstrip('/')
ii = FSItemInfo(name=filename, path_id=resultID, typ=FILE, key_id=(key_id or parentKeyID))
if read_stats:
ii.read_stats(path)
iter[ii.name()] = id
iterID[id] = ii
# finally make a complete backup id - this a relative path to the backed up file
return resultID, ii, iter, iterID
def AddDir(path, read_stats=False, iter=None, iterID=None, key_id=None, force_path_id=None):
"""
Add specific local directory to the index, but do not read content of the folder.
"""
parts = bpio.remotePath(path).split('/')
force_path_id_parts = []
if force_path_id is not None:
force_path_id_parts = bpio.remotePath(force_path_id).split('/')
key_alias = 'master' if not key_id else key_id.split('$')[0]
if iter is None:
iter = fs(key_alias=key_alias)
if iterID is None:
iterID = fsID(key_alias=key_alias)
resultID = ''
parentKeyID = None
ii = None
for i in range(len(parts)):
name = parts[i]
if not name:
continue
p = '/'.join(parts[:i + 1])
if bpio.Linux() or bpio.Mac():
p = '/' + p
if name not in iter:
id = 0
if force_path_id_parts:
id = int(force_path_id_parts[0])
force_path_id_parts = force_path_id_parts[1:]
else:
id = MakeID(iter)
resultID += '/' + str(id)
ii = FSItemInfo(name, path_id=resultID.lstrip('/'), typ=DIR, key_id=(key_id or parentKeyID))
if read_stats:
ii.read_stats(p)
iter[ii.name()] = {0: id}
iterID[id] = {INFO_KEY: ii}
else:
id = iter[name][0]
resultID += '/' + str(id)
parentKeyID = iterID[id][INFO_KEY].key_id
iter = iter[name]
iterID = iterID[id]
if i == len(parts) - 1:
if iterID[INFO_KEY].type != DIR:
lg.warn('not a dir: %s' % iterID[INFO_KEY])
iterID[INFO_KEY].type = DIR
return resultID.lstrip('/'), ii, iter, iterID
def AddLocalPath(localpath, read_stats=False, iter=None, iterID=None, key_id=None):
"""
Operates like ``AddDir()`` but also recursively reads the entire folder and
put all items in the index. Parameter ``localpath`` can be a file or folder path.
"""
def recursive_read_dir(local_path, path_id, iter, iterID):
c = 0
lastID = -1
path = bpio.portablePath(local_path)
if not os.access(path, os.R_OK):
return c
for localname in bpio.list_dir_safe(path):
p = os.path.join(path, localname)
name = strng.to_text(localname)
if bpio.pathIsDir(p):
if name not in iter:
id = MakeID(iter, lastID)
ii = FSItemInfo(name=name, path_id=(path_id + '/' + str(id)).lstrip('/'), typ=DIR, key_id=key_id)
iter[ii.name()] = {0: id}
if read_stats:
ii.read_stats(p)
iterID[id] = {INFO_KEY: ii}
lastID = id
else:
id = iter[name][0]
c += recursive_read_dir(p, path_id + '/' + str(id), iter[name], iterID[id])
else:
id = MakeID(iter, lastID)
ii = FSItemInfo(name=name, path_id=(path_id + '/' + str(id)).lstrip('/'), typ=FILE, key_id=key_id)
if read_stats:
ii.read_stats(p)
iter[ii.name()] = id
iterID[id] = ii
c += 1
lastID = id
return c
localpath = bpio.portablePath(localpath)
if bpio.pathIsDir(localpath):
path_id, itemInfo, iter, iterID = AddDir(localpath, read_stats=read_stats, iter=iter, iterID=iterID, key_id=key_id)
num = recursive_read_dir(localpath, path_id, iter, iterID)
return path_id, iter, iterID, num
else:
path_id, itemInfo, iter, iterID = AddFile(localpath, read_stats=read_stats, iter=iter, iterID=iterID, keyID=key_id)
return path_id, iter, iterID, 1
return None, None, None, 0
def PutItem(name, parent_path_id, as_folder=False, iter=None, iterID=None, key_id=None):
"""
Acts like AddFile() but do not follow the directory structure. This just
"bind" some local path (file or folder) to one single item in the catalog - by default as a top level item.
The name of new item will be equal to the local filename.
"""
remote_path = bpio.remotePath(name)
key_alias = 'master' if not key_id else key_id.split('$')[0]
if iter is None:
iter = fs(key_alias=key_alias)
if iterID is None:
iterID = fsID(key_alias=key_alias)
# make an ID for the filename
newItemID = MakeID(iter)
resultID = (parent_path_id.strip('/') + '/' + str(newItemID)).strip('/')
typ = DIR if as_folder else FILE
ii = FSItemInfo(name=remote_path, path_id=resultID, typ=typ, key_id=key_id)
iter[ii.name()] = newItemID
iterID[newItemID] = ii
return resultID, ii, iter, iterID
#------------------------------------------------------------------------------
def SetFile(item, customer_idurl=None):
"""
Put existing FSItemInfo ``item`` (for some single file) into the index.
This is used when loading index from file. Should create all parent
items in the index.
Returns two boolean flags: success or not, modified or not
"""
key_alias = item.key_alias()
iter = fs(customer_idurl, key_alias)
iterID = fsID(customer_idurl, key_alias)
parts = item.path_id.lstrip('/').split('/')
for j in range(len(parts)):
part = parts[j]
id = misc.ToInt(part, part)
if j == len(parts) - 1:
if item.name() not in iter:
iter[item.name()] = id
iterID[id] = item
return True, True
if item.pack_versions() == iterID[id].pack_versions():
return True, False
iterID[id] = item
lg.warn('updated list of versions for %r' % item)
return True, True
found = False
for name in iter.keys():
if name == 0:
continue
if isinstance(iter[name], dict):
if iter[name][0] == id:
iter = iter[name]
iterID = iterID[id]
found = True
break
continue
if not found:
return False, False
return False, False
def SetDir(item, customer_idurl=None):
"""
Same, but ``item`` is a folder.
"""
key_alias = item.key_alias()
iter = fs(customer_idurl, key_alias)
iterID = fsID(customer_idurl, key_alias)
parts = item.path_id.lstrip('/').split('/')
itemname = item.name()
for j in range(len(parts)):
part = parts[j]
id = misc.ToInt(part, part)
if j == len(parts) - 1:
modified = False
if itemname not in iter:
iter[itemname] = {}
modified = True
if iter[itemname].get(0) != int(id):
modified = True
iter[itemname][0] = int(id)
if id not in iterID:
iterID[id] = {}
modified = True
cur_item = iterID[id].get(INFO_KEY)
if not cur_item:
modified = True
iterID[id][INFO_KEY] = item
return True, modified
found = False
for name in iter.keys():
if name == 0:
continue
if isinstance(iter[name], int):
continue
if isinstance(iter[name], dict):
if iter[name][0] == id:
iter = iter[name]
iterID = iterID[id]
found = True
break
continue
if strng.is_string(iter[name]):
if iter[name] == itemname:
iter = iter[name]
iterID = iterID[id]
found = True
break
continue
raise Exception('wrong data type in the index')
if not found:
return False, False
return False, False
#------------------------------------------------------------------------------
def WalkByPath(path, iter=None):
"""
Search for ``path`` in the index - starting from root node if ``iter`` is None.
Return None or tuple (iterator, ID).
>>> backup_fs.WalkByPath('C:/Program Files/7-Zip/7z.exe')
(3, '0/0/0/3')
>>> backup_fs.WalkByPath('C:/Program Files/7-Zip/Lang/')
({0: 10, u'ru.txt': 1, u'en.ttt': 0}, '0/0/0/10')
"""
if iter is None:
iter = fs()
ppath = bpio.remotePath(path)
if ppath in iter:
if isinstance(iter[ppath], int):
return iter, str(iter[path])
return iter[ppath], str(iter[ppath][0])
if ppath == '' or ppath == '/':
return iter, iter[0] if 0 in iter else ''
path_id = ''
parts = ppath.lstrip('/').split('/')
for j in range(len(parts)):
name = parts[j]
if name not in iter:
return None
if isinstance(iter[name], dict):
if 0 not in iter[name]:
raise Exception('file or directory ID missed in the index')
path_id += '/' + str(iter[name][0])
elif isinstance(iter[name], int):
if j != len(parts) - 1:
return None
path_id += '/' + str(iter[name])
else:
raise Exception('wrong data type in the index')
if j == len(parts) - 1:
return iter[name], path_id.lstrip('/')
iter = iter[name]
return None
def WalkByID(pathID, iterID=None):
"""
Same, but search by ID: