-
Notifications
You must be signed in to change notification settings - Fork 217
/
snapshots.py
2784 lines (2307 loc) · 102 KB
/
snapshots.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
# Back In Time
# Copyright (C) 2008-2022 Oprea Dan, Bart de Koning, Richard Bailey, Germar Reitze, Taylor Raack
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import json
import os
import pathlib
import stat
import datetime
import gettext
import bz2
import pwd
import grp
import subprocess
import shutil
import time
import re
import fcntl
from tempfile import TemporaryDirectory
import config
import configfile
import logger
import tools
import encfstools
import mount
import progress
import snapshotlog
from applicationinstance import ApplicationInstance
from exceptions import MountException, LastSnapshotSymlink
_ = gettext.gettext
class Snapshots:
"""
Collection of take-snapshot and restore commands.
BUHTZ 2022-10-09: In my understanding this the representation of a
snapshot in the "application layer". This seems to be the difference to
the class `SID` which represents a snapshot in the "data layer".
Args:
cfg (config.Config): current config
"""
SNAPSHOT_VERSION = 3
GLOBAL_FLOCK = '/tmp/backintime.lock'
def __init__(self, cfg = None):
self.config = cfg
if self.config is None:
self.config = config.Config()
self.snapshotLog = snapshotlog.SnapshotLog(self.config)
self.clearIdCache()
self.clearNameCache()
#rsync --info=progress2 output
#search for: 517.38K 26% 14.46MB/s 0:02:36
#or: 497.84M 4% -449.39kB/s ??:??:??
#but filter out: 517.38K 26% 14.46MB/s 0:00:53 (xfr#53, to-chk=169/452)
# because this shows current run time
self.reRsyncProgress = re.compile(r'.*?' #trash at start
r'(\d*[,\.]?\d+[KkMGT]?)\s+' #bytes sent
r'(\d*)%\s+' #percent done
r'(-?\d*[,\.]?\d*[KkMGT]?B/s)\s+' #speed
r'([\d\?]+:[\d\?]{2}:[\d\?]{2})' #estimated time of arrival
r'(.*$)') #trash at the end
self.lastBusyCheck = datetime.datetime(1,1,1)
self.flock = None
self.restorePermissionFailed = False
#TODO: make own class for takeSnapshotMessage
def clearTakeSnapshotMessage(self):
files = (self.config.takeSnapshotMessageFile(), \
self.config.takeSnapshotProgressFile())
for f in files:
if os.path.exists(f):
os.remove(f)
#TODO: make own class for takeSnapshotMessage
def takeSnapshotMessage(self):
wait = datetime.datetime.now() - datetime.timedelta(seconds = 5)
if self.lastBusyCheck < wait:
self.lastBusyCheck = datetime.datetime.now()
if not self.busy():
self.clearTakeSnapshotMessage()
return None
if not os.path.exists(self.config.takeSnapshotMessageFile()):
return None
try:
with open(self.config.takeSnapshotMessageFile(), 'rt') as f:
items = f.read().split('\n')
except Exception as e:
logger.debug('Failed to get takeSnapshot message from %s: %s'
%(self.config.takeSnapshotMessageFile(), str(e)),
self)
return None
if len(items) < 2:
return None
mid = 0
try:
mid = int(items[0])
except Exception as e:
logger.debug('Failed extract message ID from %s: %s'
%(items[0], str(e)),
self)
del items[0]
message = '\n'.join(items)
return(mid, message)
#TODO: make own class for takeSnapshotMessage
def setTakeSnapshotMessage(self, type_id, message, timeout = -1):
data = str(type_id) + '\n' + message
try:
with open(self.config.takeSnapshotMessageFile(), 'wt') as f:
f.write(data)
except Exception as e:
logger.debug('Failed to set takeSnapshot message to %s: %s'
%(self.config.takeSnapshotMessageFile(), str(e)),
self)
if 1 == type_id:
self.snapshotLog.append('[E] ' + message, 1)
else:
self.snapshotLog.append('[I] ' + message, 3)
try:
profile_id =self.config.currentProfile()
profile_name = self.config.profileName(profile_id)
self.config.PLUGIN_MANAGER.message(profile_id, profile_name, type_id, message, timeout)
except Exception as e:
logger.debug('Failed to send message to plugins: %s'
%str(e),
self)
def busy(self):
instance = ApplicationInstance(self.config.takeSnapshotInstanceFile(), False)
return instance.busy()
def pid(self):
instance = ApplicationInstance(self.config.takeSnapshotInstanceFile(), False)
return instance.readPidFile()[0]
def clearNameCache(self):
"""
Reset the cache for user and group names.
"""
self.userCache = {}
self.groupCache = {}
def clearIdCache(self):
"""
Reset the cache for UIDs and GIDs.
"""
self.uidCache = {}
self.gidCache = {}
def uid(self, name, callback = None, backup = None):
"""
Get the User identifier (UID) for the user in ``name``.
name->uid will be cached to speed up subsequent requests.
Args:
name (:py:class:`str`, :py:class:`bytes`):
username to search for
callback (method): callable which will handle a given message
backup (int): UID which will be used if the username is unknown
on this machine
Returns:
int: UID of the user in name or -1 if not found
"""
if isinstance(name, bytes):
name = name.decode()
if name in self.uidCache:
return self.uidCache[name]
else:
uid = -1
try:
uid = pwd.getpwnam(name).pw_uid
except Exception as e:
if backup:
uid = backup
msg = "UID for '%s' is not available on this system. Using UID %s from snapshot." %(name, backup)
logger.info(msg, self)
if callback is not None:
callback(msg)
else:
self.restorePermissionFailed = True
msg = 'Failed to get UID for %s: %s' %(name, str(e))
logger.error(msg, self)
if callback:
callback(msg)
self.uidCache[name] = uid
return uid
def gid(self, name, callback = None, backup = None):
"""
Get the Group identifier (GID) for the group in ``name``.
name->gid will be cached to speed up subsequent requests.
Args:
name (:py:class:`str`, :py:class:`bytes`):
groupname to search for
callback (method): callable which will handle a given message
backup (int): GID which will be used if the groupname is unknown
on this machine
Returns:
int: GID of the group in name or -1 if not found
"""
if isinstance(name, bytes):
name = name.decode()
if name in self.gidCache:
return self.gidCache[name]
else:
gid = -1
try:
gid = grp.getgrnam(name).gr_gid
except Exception as e:
if backup is not None:
gid = backup
msg = "GID for '%s' is not available on this system. Using GID %s from snapshot." %(name, backup)
logger.info(msg, self)
if callback:
callback(msg)
else:
self.restorePermissionFailed = True
msg = 'Failed to get GID for %s: %s' %(name, str(e))
logger.error(msg, self)
if callback:
callback(msg)
self.gidCache[name] = gid
return gid
def userName(self, uid):
"""
Get the username for the given uid.
uid->name will be cached to speed up subsequent requests.
Args:
uid (int): User identifier (UID) to search for
Returns:
str: name of the user with UID uid or '-' if not found
"""
if uid in self.userCache:
return self.userCache[uid]
else:
name = '-'
try:
name = pwd.getpwuid(uid).pw_name
except Exception as e:
logger.debug('Failed to get user name for UID %s: %s'
%(uid, str(e)),
self)
self.userCache[uid] = name
return name
def groupName(self, gid):
"""
Get the groupname for the given gid.
gid->name will be cached to speed up subsequent requests.
Args:
gid (int): Group identifier (GID) to search for
Returns:
str: name of the Group with GID gid or '.' if not found
"""
if gid in self.groupCache:
return self.groupCache[gid]
else:
name = '-'
try:
name = grp.getgrgid(gid).gr_name
except Exception as e:
logger.debug('Failed to get group name for GID %s: %s'
%(gid, str(e)),
self)
self.groupCache[gid] = name
return name
def restoreCallback(self, callback, ok, msg):
"""
Format messages thrown by restore depending on whether they where
successful or failed.
Args:
callback (method): callable instance which will handle the message
ok (bool): ``True`` if the logged action was successful
or ``False`` if it failed
msg (str): message that should be send to callback
"""
if not callback is None:
if not ok:
msg = msg + " : " + _("FAILED")
self.restorePermissionFailed = True
callback(msg)
def restorePermission(self, key_path, path, fileInfoDict, callback = None):
"""
Restore permissions (owner, group and mode). If permissions are
already identical with the new ones just skip. Otherwise try to
'chown' to new owner and new group. If that fails (most probably because
we are not running as root and normal user has no rights to change
ownership of files) try to at least 'chgrp' to the new group. Finally
'chmod' the new mode.
Args:
key_path (bytes): original path during backup.
Same as in fileInfoDict.
path (bytes): current path of file that should be changed.
fileInfoDict (FileInfoDict): FileInfoDict
"""
assert isinstance(key_path, bytes), 'key_path is not bytes type: %s' % key_path
assert isinstance(path, bytes), 'path is not bytes type: %s' % path
assert isinstance(fileInfoDict, FileInfoDict), 'fileInfoDict is not FileInfoDict type: %s' % fileInfoDict
if key_path not in fileInfoDict or not os.path.exists(path):
return
info = fileInfoDict[key_path]
#restore uid/gid
uid = self.uid(info[1], callback)
gid = self.gid(info[2], callback)
#current file stats
st = os.stat(path)
# logger.debug('%(path)s: uid %(target_uid)s/%(cur_uid)s, gid %(target_gid)s/%(cur_gid)s, mod %(target_mod)s/%(cur_mod)s'
# %{'path': path.decode(),
# 'target_uid': uid,
# 'cur_uid': st.st_uid,
# 'target_gid': gid,
# 'cur_gid': st.st_gid,
# 'target_mod': info[0],
# 'cur_mod': st.st_mode
# })
if uid != -1 or gid != -1:
ok = False
if uid != st.st_uid:
try:
os.chown(path, uid, gid)
ok = True
except:
pass
self.restoreCallback(callback, ok, "chown %s %s : %s" % (path.decode(errors = 'ignore'), uid, gid))
st = os.stat(path)
#if restore uid/gid failed try to restore at least gid
if not ok and gid != st.st_gid:
try:
os.chown(path, -1, gid)
ok = True
except:
pass
self.restoreCallback(callback, ok, "chgrp %s %s" % (path.decode(errors = 'ignore'), gid))
st = os.stat(path)
#restore perms
ok = False
if info[0] != st.st_mode:
try:
os.chmod(path, info[0])
ok = True
except:
pass
self.restoreCallback(callback, ok, "chmod %s %04o" % (path.decode(errors = 'ignore'), info[0]))
def restore(self,
sid,
paths,
callback = None,
restore_to = '',
delete = False,
backup = True,
only_new = False):
"""
Restore one or more files from snapshot ``sid`` to either original
or a different destination. Restore is done with rsync. If available
permissions will be restored from ``fileinfo.bz2``.
Args:
sid (SID): snapshot from whom to restore
paths (:py:class:`list`, :py:class:`tuple` or :py:class:`str`):
single path (str) or multiple
paths (list, tuple) that should be
restored. For every path this will run
a new rsync process. Permissions will be
restored for all paths in one run
callback (method): callable instance which will handle
messages
restore_to (str): full path to restore to. If empty
restore to original destination
delete (bool): delete newer files which are not in the
snapshot
backup (bool): create backup files (*.backup.YYYYMMDD)
before changing or deleting local files.
only_new (bool): Only restore files which does not exist
or are newer than those in destination.
Using "rsync --update" option.
"""
instance = ApplicationInstance(
pidFile=self.config.restoreInstanceFile(),
autoExit=False,
flock=True)
if instance.check():
instance.startApplication()
else:
logger.warning('Restore is already running', self)
return
if restore_to.endswith('/'):
restore_to = restore_to[: -1]
if not isinstance(paths, (list, tuple)):
paths = (paths,)
logger.info("Restore: %s to: %s"
%(', '.join(paths), restore_to),
self)
info = sid.info
cmd_prefix = tools.rsyncPrefix(self.config, no_perms=False, use_mode=['ssh'])
cmd_prefix.extend(('-R', '-v'))
if backup:
cmd_prefix.extend(('--backup', '--suffix=%s' % self.backupSuffix()))
if delete:
cmd_prefix.append('--delete')
cmd_prefix.append('--filter=protect %s' % self.config.snapshotsPath())
cmd_prefix.append('--filter=protect %s' % self.config._LOCAL_DATA_FOLDER)
cmd_prefix.append('--filter=protect %s' % self.config._MOUNT_ROOT)
if only_new:
cmd_prefix.append('--update')
restored_paths = []
for path in paths:
tools.makeDirs(os.path.dirname(path))
src_path = path
src_delta = 0
src_base = sid.pathBackup(use_mode = ['ssh'])
if not src_base.endswith(os.sep):
src_base += os.sep
cmd = cmd_prefix[:]
if restore_to:
items = os.path.split(src_path)
aux = items[0].lstrip(os.sep)
# bugfix: restore system root ended in <src_base>//.<src_path>
if aux:
src_base = os.path.join(src_base, aux) + '/'
src_path = '/' + items[1]
if items[0] == '/':
src_delta = 0
else:
src_delta = len(items[0])
cmd.append(self.rsyncRemotePath('%s.%s' % (src_base, src_path), use_mode=['ssh'], quote=''))
cmd.append('%s/' % restore_to)
proc = tools.Execute(cmd,
callback=callback,
filters=(self.filterRsyncProgress,),
parent=self)
self.restoreCallback(callback, True, proc.printable_cmd)
proc.run()
self.restoreCallback(callback, True, ' ')
restored_paths.append((path, src_delta))
try:
os.remove(self.config.takeSnapshotProgressFile())
except Exception as e:
logger.debug('Failed to remove snapshot progress file %s: %s'
%(self.config.takeSnapshotProgressFile(), str(e)),
self)
#restore permissions
logger.info('Restore permissions', self)
self.restoreCallback(callback, True, ' ')
self.restoreCallback(callback, True, _("Restore permissions:"))
self.restorePermissionFailed = False
fileInfoDict = sid.fileInfo
#cache uids/gids
for uid, name in info.listValue('user', ('int:uid', 'str:name')):
self.uid(name.encode(), callback = callback, backup = uid)
for gid, name in info.listValue('group', ('int:gid', 'str:name')):
self.gid(name.encode(), callback = callback, backup = gid)
if fileInfoDict:
all_dirs = [] #restore dir permissions after all files are done
for path, src_delta in restored_paths:
#explore items
snapshot_path_to = sid.pathBackup(path).rstrip('/')
root_snapshot_path_to = sid.pathBackup().rstrip('/')
#use bytes instead of string from here
if isinstance(path, str):
path = path.encode()
if isinstance(restore_to, str):
restore_to = restore_to.encode()
if not restore_to:
path_items = path.strip(b'/').split(b'/')
curr_path = b'/'
for path_item in path_items:
curr_path = os.path.join(curr_path, path_item)
if curr_path not in all_dirs:
all_dirs.append(curr_path)
else:
if path not in all_dirs:
all_dirs.append(path)
if os.path.isdir(snapshot_path_to) and not os.path.islink(snapshot_path_to):
head = len(root_snapshot_path_to.encode())
for explore_path, dirs, files in os.walk(snapshot_path_to.encode()):
for item in dirs:
item_path = os.path.join(explore_path, item)[head:]
if item_path not in all_dirs:
all_dirs.append(item_path)
for item in files:
item_path = os.path.join(explore_path, item)[head:]
real_path = restore_to + item_path[src_delta:]
self.restorePermission(item_path, real_path, fileInfoDict, callback)
all_dirs.reverse()
for item_path in all_dirs:
real_path = restore_to + item_path[src_delta:]
self.restorePermission(item_path, real_path, fileInfoDict, callback)
self.restoreCallback(callback, True, '')
if self.restorePermissionFailed:
status = _('FAILED')
else:
status = _('Done')
self.restoreCallback(callback, True, _("Restore permissions:") + ' ' + status)
instance.exitApplication()
def backupSuffix(self):
"""
Get suffix for backup files.
Returns:
str: backup suffix in form of '.backup.YYYYMMDD'
"""
return '.backup.' + datetime.date.today().strftime('%Y%m%d')
def remove(self, sid):
"""
Remove snapshot ``sid``.
BUHTZ 2022-10-11: From my understanding rsync is used here to sync the
directory of a concret snapshot (``sid```) against an empty temporary
directory. In the consequence the sid directory is empty but not
deleted.
To delete that directory simple `rm` call (via `shutil` package) is
used to delete the directory. No need to do this via SSH because the
directory is temporary mounted.
It is not clear for me why it is done that way. Why not simply "rm"
the directory when it is mounted instead of using rsync in a previous
step?! But I won't change it yet.
Args:
sid (SID): snapshot to remove
Returns:
(bool): ``True`` if succedeed otherwise ``False``.
"""
if isinstance(sid, RootSnapshot):
return
# build the rsync command and it's arguments
rsync = tools.rsyncRemove(self.config)
# an empty temporary directory
# e.g. /tmp/tmp8g59onuz
with TemporaryDirectory() as d:
# the temp dir
rsync.append(d + os.sep)
# the real remote path of a concrete snapshot (a "sid")
# e.g. user@myserver:"/MyBackup/.backintime/backintime/HOST/user/ \
# MyProfile/20221005-000003-880"
rsync.append(
self.rsyncRemotePath(
sid.path(use_mode=['ssh', 'ssh_encfs']),
# No quoting because of new argument protection of rsync.
quote=''
)
)
# Syncing the empty tmp directory against the sid directory
# will clear the sid directory.
rc = tools.Execute(rsync).run()
#
if rc != 0:
logger.error(
f'Last rsync command failed with return code "{rc}". '
'See previous WARNING message in the logs for details.')
return False
# Delete the sid dir. BUT here isn't the remote path used but the
# temporary mounted variant of it.
# e.g. /home/user/.local/share/backintime/mnt/4_8030/backintime/ \
# HOST/user/MyProfile/20221005-000003-880
shutil.rmtree(sid.path())
return True
def backup(self, force = False):
"""
Wrapper for :py:func:`takeSnapshot` which will prepare and clean up
things for the main :py:func:`takeSnapshot` method. This will check
that no other snapshots are running at the same time, there is nothing
prohibing a new snapshot (e.g. on battery) and the profile is configured
correctly. This will also mount and unmount remote destinations.
Args:
force (bool): force taking a new snapshot even if the profile is
not scheduled or the machine is running on battery
Returns:
bool: ``True`` if there was an error
"""
ret_val, ret_error = False, True
sleep = True
self.config.PLUGIN_MANAGER.load(self)
if not self.config.isConfigured():
logger.warning('Not configured', self)
self.config.PLUGIN_MANAGER.error(1) #not configured
elif not force and self.config.noSnapshotOnBattery() and tools.onBattery():
self.setTakeSnapshotMessage(0, _('Deferring backup while on battery'))
logger.info('Deferring backup while on battery', self)
logger.warning('Backup not performed', self)
ret_error = False
elif not force and not self.config.backupScheduled():
logger.info('Profile "%s" is not scheduled to run now.'
%self.config.profileName(), self)
ret_error = False
else:
instance = ApplicationInstance(self.config.takeSnapshotInstanceFile(), False, flock = True)
restore_instance = ApplicationInstance(self.config.restoreInstanceFile(), False)
if not instance.check():
logger.warning('A backup is already running. The pid of the \
already running backup is in file %s. Maybe delete it' % instance.pidFile , self )
self.config.PLUGIN_MANAGER.error(2) #a backup is already running
elif not restore_instance.check():
logger.warning('Restore is still running. Stop backup until \
restore is done. The pid of the already running restore is in %s. Maybe delete it'\
% restore_instance.pidFile, self)
else:
if self.config.noSnapshotOnBattery () and not tools.powerStatusAvailable():
logger.warning('Backups disabled on battery but power status is not available', self)
instance.startApplication()
self.flockExclusive()
logger.info('Lock', self)
now = datetime.datetime.today()
#inhibit suspend/hibernate during snapshot is running
self.config.inhibitCookie = tools.inhibitSuspend(toplevel_xid = self.config.xWindowId)
#mount
try:
hash_id = mount.Mount(cfg = self.config).mount()
except MountException as ex:
logger.error(str(ex), self)
instance.exitApplication()
logger.info('Unlock', self)
time.sleep(2)
return True
else:
self.config.setCurrentHashId(hash_id)
include_folders = self.config.include()
if not include_folders:
logger.info('Nothing to do', self)
elif not self.config.PLUGIN_MANAGER.processBegin():
logger.info('A plugin prevented the backup', self)
else:
#take snapshot process begin
self.setTakeSnapshotMessage(0, '...')
self.snapshotLog.new(now)
profile_id = self.config.currentProfile()
profile_name = self.config.profileName()
logger.info("Take a new snapshot. Profile: %s %s"
%(profile_id, profile_name), self)
if not self.config.canBackup(profile_id):
if self.config.PLUGIN_MANAGER.hasGuiPlugins and self.config.notify():
self.setTakeSnapshotMessage(1,
_('Can\'t find snapshots folder.\nIf it is on a removable drive please plug it.') +
'\n' +
gettext.ngettext('Waiting %s second.', 'Waiting %s seconds.', 30) % 30,
30)
counter = 0
for counter in range(0, 30):
logger.debug("Cannot start snapshot yet: target directory not accessible. Waiting 1s.")
time.sleep(1)
if self.config.canBackup():
break
if counter != 0:
logger.info("Waited %d seconds for target directory to be available", counter)
if not self.config.canBackup(profile_id):
logger.warning('Can\'t find snapshots folder!', self)
self.config.PLUGIN_MANAGER.error(3) #Can't find snapshots directory (is it on a removable drive ?)
else:
ret_error = False
sid = SID(now, self.config)
if sid.exists():
logger.warning("Snapshot path \"%s\" already exists" %sid.path(), self)
self.config.PLUGIN_MANAGER.error(4, sid) #This snapshots already exists
else:
try:
ret_val, ret_error = self.takeSnapshot(sid, now, include_folders)
except:
new = NewSnapshot(self.config)
if new.exists():
new.saveToContinue = False
new.failed = True
raise
if not ret_val:
self.remove(sid)
if ret_error:
logger.error('Failed to take snapshot !!!', self)
self.setTakeSnapshotMessage(1, _('Failed to take snapshot %s !!!') % sid.displayID)
time.sleep(2)
else:
logger.warning("No new snapshot", self)
else:
ret_error = False
if not ret_error:
self.freeSpace(now)
self.setTakeSnapshotMessage(0, _('Finalizing'))
time.sleep(2)
sleep = False
if ret_val:
self.config.PLUGIN_MANAGER.newSnapshot(sid, sid.path()) #new snapshot
self.config.PLUGIN_MANAGER.processEnd() #take snapshot process end
if sleep:
time.sleep(2)
sleep = False
if not ret_error:
self.clearTakeSnapshotMessage()
#unmount
try:
mount.Mount(cfg = self.config).umount(self.config.current_hash_id)
except MountException as ex:
logger.error(str(ex), self)
instance.exitApplication()
self.flockRelease()
logger.info('Unlock', self)
if sleep:
time.sleep(2) #max 1 backup / second
#release inhibit suspend
if self.config.inhibitCookie:
self.config.inhibitCookie = tools.unInhibitSuspend(*self.config.inhibitCookie)
return ret_error
def filterRsyncProgress(self, line):
"""
Filter rsync's stdout for progress information and store them in
'~/.local/share/backintime/worker<N>.progress' file.
Args:
line (str): stdout line from rsync
Returns:
str: ``line`` if it had no progress infos. ``None`` if
``line`` was a progress
"""
ret = []
for l in line.split('\n'):
m = self.reRsyncProgress.match(l)
if m:
# if m.group(5).strip():
# return
pg = progress.ProgressFile(self.config)
pg.setIntValue('status', pg.RSYNC)
pg.setStrValue('sent', m.group(1))
pg.setIntValue('percent', int(m.group(2)))
pg.setStrValue('speed', m.group(3))
#pg.setStrValue('eta', m.group(4))
pg.save()
del(pg)
else:
ret.append(l)
return '\n'.join(ret)
def rsyncCallback(self, line, params):
"""
Parse rsync's stdout, send it to takeSnapshotMessage and
takeSnapshotLog. Also check if there has been changes or errors in
current rsync.
Args:
line (str): stdout line from rsync
params (list): list of two bool '[error, changes]'. Using siteefect
on changing list items will change original
list, too. If rsync reported an error ``params[0]``
will be set to ``True``. If rsync reported a changed
file ``params[1]`` will be set to ``True``
"""
if not line:
return
self.setTakeSnapshotMessage(0, _('Take snapshot') + " (rsync: %s)" % line)
if line.endswith(')'):
if line.startswith('rsync:'):
if not line.startswith('rsync: chgrp ') and not line.startswith('rsync: chown '):
params[0] = True
self.setTakeSnapshotMessage(1, 'Error: ' + line)
if len(line) >= 13:
if line.startswith('BACKINTIME: '):
if line[12] != '.' and line[12:14] != 'cd':
params[1] = True
self.snapshotLog.append('[C] ' + line[12:], 2)
def makeDirs(self, path):
"""
Wrapper for :py:func:`tools.makeDirs()`. Create directories ``path``
recursive and return success. If not successful send error-message to
log.
Args:
path (str): fullpath to directories that should be created
Returns:
bool: ``True`` if successful
"""
if not tools.makeDirs(path):
logger.error("Can't create folder: %s" % path, self)
self.setTakeSnapshotMessage(1, _('Can\'t create folder: %s') % path)
time.sleep(2) #max 1 backup / second
return False
return True
def backupConfig(self, sid):
"""
Backup the config file to the snapshot and to the backup root if backup
is encrypted.
Args:
sid (SID): snapshot in which the config should be stored
"""
logger.info('Save config file', self)
self.setTakeSnapshotMessage(0, _('Saving config file...'))
with open(self.config._LOCAL_CONFIG_PATH, 'rb') as src:
with open(sid.path('config'), 'wb') as dst1:
dst1.write(src.read())
if self.config.snapshotsMode() == 'local_encfs':
src.seek(0)
dst2_path = os.path.join(
self.config.localEncfsPath(),
'config'
)
with open(dst2_path, 'wb') as dst2:
dst2.write(src.read())
elif self.config.snapshotsMode() == 'ssh_encfs':
cmd = tools.rsyncPrefix(self.config, no_perms=False)
cmd.append(self.config._LOCAL_CONFIG_PATH)
remote_path = self.rsyncRemotePath(
self.config.sshSnapshotsPath(),
# no quoting becausse of rsyncs modern argument
# protection (argument -s)
quote=''
)
cmd.append(remote_path)
proc = tools.Execute(cmd, parent=self)
rc = proc.run()
# WORKAROUND
# tools.Execute only create warnings if 'cmd' fails.
# But we need a real ERROR here.
if rc != 0:
logger.error(
f'Backup the config in "{self.config.snapshotsMode()}"'
f' mode failed! The return code was {rc} and the'
f' command was {cmd}. Also see the previous '
'WARNING message for a more details.', parent=self)
def backupInfo(self, sid):
"""
Save infos about the snapshot into the 'info' file.
Args:
sid (SID): snapshot that should get an info file
"""
logger.info("Create info file", self)
machine = self.config.host()
user = self.config.user()
profile_id = self.config.currentProfile()
i = configfile.ConfigFile()
i.setIntValue('snapshot_version', self.SNAPSHOT_VERSION)
i.setStrValue('snapshot_date', sid.withoutTag)
i.setStrValue('snapshot_machine', machine)
i.setStrValue('snapshot_user', user)
i.setIntValue('snapshot_profile_id', profile_id)
i.setIntValue('snapshot_tag', sid.tag)
i.setListValue('user', ('int:uid', 'str:name'), list(self.userCache.items()))
i.setListValue('group', ('int:gid', 'str:name'), list(self.groupCache.items()))
i.setStrValue('filesystem_mounts', json.dumps(tools.filesystemMountInfo()))
sid.info = i
def backupPermissions(self, sid):
"""
Save permissions (owner, group, read-, write- and executable)
for all files in Snapshot ``sid`` into snapshots fileInfoDict.
Args:
sid (SID): snapshot that should be scanned
Returns:
int: Return code of rsync.
"""
logger.info('Save permissions', self)
self.setTakeSnapshotMessage(0, _('Saving permissions...'))
fileInfoDict = FileInfoDict()
if self.config.snapshotsMode() == 'ssh_encfs':
decode = encfstools.Decode(self.config, False)
else:
decode = encfstools.Bounce()
# backup permissions of /
# bugfix for https://github.com/bit-team/backintime/issues/708