forked from YunoHost/yunohost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup.py
2314 lines (1838 loc) · 85.1 KB
/
backup.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
# -*- coding: utf-8 -*-
""" License
Copyright (C) 2013 YunoHost
This program 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.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses
"""
""" yunohost_backup.py
Manage backups
"""
import os
import re
import json
import time
import tarfile
import shutil
import subprocess
import csv
import tempfile
from datetime import datetime
from glob import glob
from collections import OrderedDict
from moulinette import msignals, m18n
from yunohost.utils.error import YunohostError
from moulinette.utils import filesystem
from moulinette.utils.log import getActionLogger
from moulinette.utils.filesystem import read_file
from yunohost.app import (
app_info, _is_installed, _parse_app_instance_name, _patch_php5
)
from yunohost.hook import (
hook_list, hook_info, hook_callback, hook_exec, CUSTOM_HOOK_FOLDER
)
from yunohost.monitor import binary_to_human
from yunohost.tools import tools_postinstall
from yunohost.service import service_regen_conf
from yunohost.log import OperationLogger
BACKUP_PATH = '/home/yunohost.backup'
ARCHIVES_PATH = '%s/archives' % BACKUP_PATH
APP_MARGIN_SPACE_SIZE = 100 # In MB
CONF_MARGIN_SPACE_SIZE = 10 # IN MB
POSTINSTALL_ESTIMATE_SPACE_SIZE = 5 # In MB
MB_ALLOWED_TO_ORGANIZE = 10
logger = getActionLogger('yunohost.backup')
class BackupRestoreTargetsManager(object):
"""
BackupRestoreTargetsManager manage the targets
in BackupManager and RestoreManager
"""
def __init__(self):
self.targets = {}
self.results = {
"system": {},
"apps": {}
}
def set_result(self, category, element, value):
"""
Change (or initialize) the current status/result of a given target.
Args:
category -- The category of the target
element -- The target for which to change the status/result
value -- The new status/result, among "Unknown", "Success",
"Warning", "Error" and "Skipped"
"""
levels = ["Unknown", "Success", "Warning", "Error", "Skipped"]
assert value in levels
if element not in self.results[category].keys():
self.results[category][element] = value
else:
currentValue = self.results[category][element]
if (levels.index(currentValue) > levels.index(value)):
return
else:
self.results[category][element] = value
def set_wanted(self, category,
wanted_targets, available_targets,
error_if_wanted_target_is_unavailable):
"""
Define and validate targets to be backuped or to be restored (list of
system parts, apps..). The wanted targets are compared and filtered
with respect to the available targets. If a wanted targets is not
available, a call to "error_if_wanted_target_is_unavailable" is made.
Args:
category -- The category (apps or system) for which to set the
targets ;
wanted_targets -- List of targets which are wanted by the user. Can be
"None" or [], corresponding to "No targets" or "All
targets" ;
available_targets -- List of targets which are really available ;
error_if_wanted_target_is_unavailable
-- Callback for targets which are not available.
"""
# If no targets wanted, set as empty list
if wanted_targets is None:
self.targets[category] = []
# If all targets wanted, use all available targets
elif wanted_targets == []:
self.targets[category] = available_targets
# If the user manually specified which targets to backup, we need to
# validate that each target is actually available
else:
self.targets[category] = [part for part in wanted_targets
if part in available_targets]
# Display an error for each target asked by the user but which is
# unknown
unavailable_targets = [part for part in wanted_targets
if part not in available_targets]
for target in unavailable_targets:
self.set_result(category, target, "Skipped")
error_if_wanted_target_is_unavailable(target)
# For target with no result yet (like 'Skipped'), set it as unknown
if self.targets[category] is not None:
for target in self.targets[category]:
self.set_result(category, target, "Unknown")
return self.list(category, exclude=["Skipped"])
def list(self, category, include=None, exclude=None):
"""
List targets in a given category.
The list is filtered with a whitelist (include) or blacklist (exclude)
with respect to the current 'result' of the target.
"""
assert (include and isinstance(include, list) and not exclude) \
or (exclude and isinstance(exclude, list) and not include)
if include:
return [target.encode("Utf-8") for target in self.targets[category]
if self.results[category][target] in include]
if exclude:
return [target.encode("Utf-8") for target in self.targets[category]
if self.results[category][target] not in exclude]
class BackupManager():
"""
This class collect files to backup in a list and apply one or several
backup method on it.
The list contains dict with source and dest properties. The goal of this csv
is to list all directories and files which need to be backup in this
archive. The `source` property is the path of the source (dir or file).
The `dest` property is the path where it could be placed in the archive.
The list is filled by app backup scripts and system/user backup hooks.
Files located in the work_dir are automatically added.
With this list, "backup methods" are able to apply their backup strategy on
data listed in it. It's possible to tar each path (tar methods), to mount
each dir into the work_dir, to copy each files (copy method) or to call a
custom method (via a custom script).
Note: some future backups methods (like borg) are not able to specify a
different place than the original path. That's why the ynh_restore_file
helpers use primarily the SOURCE_PATH as argument.
Public properties:
info (getter)
work_dir (getter) # FIXME currently it's not a getter
is_tmp_work_dir (getter)
paths_to_backup (getter) # FIXME not a getter and list is not protected
name (getter) # FIXME currently it's not a getter
size (getter) # FIXME currently it's not a getter
Public methods:
add(self, method)
set_system_targets(self, system_parts=[])
set_apps_targets(self, apps=[])
collect_files(self)
backup(self)
Usage:
backup_manager = BackupManager(name="mybackup", description="bkp things")
# Add backup method to apply
backup_manager.add(BackupMethod.create('copy','/mnt/local_fs'))
backup_manager.add(BackupMethod.create('tar','/mnt/remote_fs'))
# Define targets to be backuped
backup_manager.set_system_targets(["data"])
backup_manager.set_apps_targets(["wordpress"])
# Collect files to backup from targets
backup_manager.collect_files()
# Apply backup methods
backup_manager.backup()
"""
def __init__(self, name=None, description='', work_dir=None):
"""
BackupManager constructor
Args:
name -- (string) The name of this backup (without spaces). If
None, the name will be generated (default: None)
description -- (string) A description for this future backup archive
(default: '')
work_dir -- (None|string) A path where prepare the archive. If None,
temporary work_dir will be created (default: None)
"""
self.description = description or ''
self.created_at = int(time.time())
self.apps_return = {}
self.system_return = {}
self.methods = []
self.paths_to_backup = []
self.size_details = {
'system': {},
'apps': {}
}
self.targets = BackupRestoreTargetsManager()
# Define backup name if needed
if not name:
name = self._define_backup_name()
self.name = name
# Define working directory if needed and initialize it
self.work_dir = work_dir
if self.work_dir is None:
self.work_dir = os.path.join(BACKUP_PATH, 'tmp', name)
self._init_work_dir()
###########################################################################
# Misc helpers #
###########################################################################
@property
def info(self):
"""(Getter) Dict containing info about the archive being created"""
return {
'description': self.description,
'created_at': self.created_at,
'size': self.size,
'size_details': self.size_details,
'apps': self.apps_return,
'system': self.system_return
}
@property
def is_tmp_work_dir(self):
"""(Getter) Return true if the working directory is temporary and should
be clean at the end of the backup"""
return self.work_dir == os.path.join(BACKUP_PATH, 'tmp', self.name)
def __repr__(self):
return json.dumps(self.info)
def _define_backup_name(self):
"""Define backup name
Return:
(string) A backup name created from current date 'YYMMDD-HHMMSS'
"""
# FIXME: case where this name already exist
return time.strftime('%Y%m%d-%H%M%S', time.gmtime())
def _init_work_dir(self):
"""Initialize preparation directory
Ensure the working directory exists and is empty
exception:
backup_output_directory_not_empty -- (YunohostError) Raised if the
directory was given by the user and isn't empty
(TODO) backup_cant_clean_tmp_working_directory -- (YunohostError)
Raised if the working directory isn't empty, is temporary and can't
be automaticcaly cleaned
(TODO) backup_cant_create_working_directory -- (YunohostError) Raised
if iyunohost can't create the working directory
"""
# FIXME replace isdir by exists ? manage better the case where the path
# exists
if not os.path.isdir(self.work_dir):
filesystem.mkdir(self.work_dir, 0750, parents=True, uid='admin')
elif self.is_tmp_work_dir:
logger.debug("temporary directory for backup '%s' already exists",
self.work_dir)
# FIXME May be we should clean the workdir here
raise YunohostError('backup_output_directory_not_empty')
###########################################################################
# Backup target management #
###########################################################################
def set_system_targets(self, system_parts=[]):
"""
Define and validate targetted apps to be backuped
Args:
system_parts -- (list) list of system parts which should be backuped.
If empty list, all system will be backuped. If None,
no system parts will be backuped.
"""
def unknown_error(part):
logger.error(m18n.n('backup_hook_unknown', hook=part))
self.targets.set_wanted("system",
system_parts, hook_list('backup')["hooks"],
unknown_error)
def set_apps_targets(self, apps=[]):
"""
Define and validate targetted apps to be backuped
Args:
apps -- (list) list of apps which should be backuped. If given an empty
list, all apps will be backuped. If given None, no apps will be
backuped.
"""
def unknown_error(app):
logger.error(m18n.n('unbackup_app', app=app))
target_list = self.targets.set_wanted("apps", apps,
os.listdir('/etc/yunohost/apps'),
unknown_error)
# Additionnaly, we need to check that each targetted app has a
# backup and restore scripts
for app in target_list:
app_script_folder = "/etc/yunohost/apps/%s/scripts" % app
backup_script_path = os.path.join(app_script_folder, "backup")
restore_script_path = os.path.join(app_script_folder, "restore")
if not os.path.isfile(backup_script_path):
logger.warning(m18n.n('backup_with_no_backup_script_for_app', app=app))
self.targets.set_result("apps", app, "Skipped")
elif not os.path.isfile(restore_script_path):
logger.warning(m18n.n('backup_with_no_restore_script_for_app', app=app))
self.targets.set_result("apps", app, "Warning")
###########################################################################
# Management of files to backup / "The CSV" #
###########################################################################
def _import_to_list_to_backup(self, tmp_csv):
"""
Commit collected path from system hooks or app scripts
Args:
tmp_csv -- (string) Path to a temporary csv file with source and
destinations column to add to the list of paths to backup
"""
_call_for_each_path(self, BackupManager._add_to_list_to_backup, tmp_csv)
def _add_to_list_to_backup(self, source, dest=None):
"""
Mark file or directory to backup
This method add source/dest couple to the "paths_to_backup" list.
Args:
source -- (string) Source path to backup
dest -- (string) Destination path in the archive. If it ends by a
slash the basename of the source path will be added. If None,
the source path will be used, so source files will be set up
at the same place and with same name than on the system.
(default: None)
Usage:
self._add_to_list_to_backup('/var/www/wordpress', 'sources')
# => "wordpress" dir will be move and rename as "sources"
self._add_to_list_to_backup('/var/www/wordpress', 'sources/')
# => "wordpress" dir will be put inside "sources/" and won't be renamed
"""
if dest is None:
dest = source
source = os.path.join(self.work_dir, source)
if dest.endswith("/"):
dest = os.path.join(dest, os.path.basename(source))
self.paths_to_backup.append({'source': source, 'dest': dest})
def _write_csv(self):
"""
Write the backup list into a CSV
The goal of this csv is to list all directories and files which need to
be backup in this archive. For the moment, this CSV contains 2 columns.
The first column `source` is the path of the source (dir or file). The
second `dest` is the path where it could be placed in the archive.
This CSV is filled by app backup scripts and system/user hooks.
Files in the work_dir are automatically added.
With this CSV, "backup methods" are able to apply their backup strategy
on data listed in it. It's possible to tar each path (tar methods), to
mount each dir into the work_dir, to copy each files (copy methods) or
a custom method (via a custom script).
Note: some future backups methods (like borg) are not able to specify a
different place than the original path. That's why the ynh_restore_file
helpers use primarily the SOURCE_PATH as argument.
Error:
backup_csv_creation_failed -- Raised if the CSV couldn't be created
backup_csv_addition_failed -- Raised if we can't write in the CSV
"""
self.csv_path = os.path.join(self.work_dir, 'backup.csv')
try:
self.csv_file = open(self.csv_path, 'a')
self.fieldnames = ['source', 'dest']
self.csv = csv.DictWriter(self.csv_file, fieldnames=self.fieldnames,
quoting=csv.QUOTE_ALL)
except (IOError, OSError, csv.Error):
logger.error(m18n.n('backup_csv_creation_failed'))
for row in self.paths_to_backup:
try:
self.csv.writerow(row)
except csv.Error:
logger.error(m18n.n('backup_csv_addition_failed'))
self.csv_file.close()
###########################################################################
# File collection from system parts and apps #
###########################################################################
def collect_files(self):
"""
Collect all files to backup, write its into a CSV and create a
info.json file
Files to backup are listed by system parts backup hooks and by backup
app scripts that have been defined with the set_targets() method.
Some files or directories inside the working directory are added by
default:
info.json -- info about the archive
backup.csv -- a list of paths to backup
apps/ -- some apps generate here temporary files to backup (like
database dump)
conf/ -- system configuration backup scripts could generate here
temporary files to backup
data/ -- system data backup scripts could generate here temporary
files to backup
hooks/ -- restore scripts associated to system backup scripts are
copied here
Exceptions:
"backup_nothings_done" -- (YunohostError) This exception is raised if
nothing has been listed.
"""
self._collect_system_files()
self._collect_apps_files()
# Check if something has been saved ('success' or 'warning')
successfull_apps = self.targets.list("apps", include=["Success", "Warning"])
successfull_system = self.targets.list("system", include=["Success", "Warning"])
if not successfull_apps and not successfull_system:
filesystem.rm(self.work_dir, True, True)
raise YunohostError('backup_nothings_done')
# Add unlisted files from backup tmp dir
self._add_to_list_to_backup('backup.csv')
self._add_to_list_to_backup('info.json')
if len(self.apps_return) > 0:
self._add_to_list_to_backup('apps')
if os.path.isdir(os.path.join(self.work_dir, 'conf')):
self._add_to_list_to_backup('conf')
if os.path.isdir(os.path.join(self.work_dir, 'data')):
self._add_to_list_to_backup('data')
# Write CSV file
self._write_csv()
# Calculate total size
self._compute_backup_size()
# Create backup info file
with open("%s/info.json" % self.work_dir, 'w') as f:
f.write(json.dumps(self.info))
def _get_env_var(self, app=None):
"""
Define environment variables for apps or system backup scripts.
Args:
app -- (string|None) The instance name of the app we want the variable
environment. If you want a variable environment for a system backup
script keep None. (default: None)
Return:
(Dictionnary) The environment variables to apply to the script
"""
env_var = {}
_, tmp_csv = tempfile.mkstemp(prefix='backupcsv_')
env_var['YNH_BACKUP_DIR'] = self.work_dir
env_var['YNH_BACKUP_CSV'] = tmp_csv
if app is not None:
app_id, app_instance_nb = _parse_app_instance_name(app)
env_var["YNH_APP_ID"] = app_id
env_var["YNH_APP_INSTANCE_NAME"] = app
env_var["YNH_APP_INSTANCE_NUMBER"] = str(app_instance_nb)
tmp_app_dir = os.path.join('apps/', app)
tmp_app_bkp_dir = os.path.join(self.work_dir, tmp_app_dir, 'backup')
env_var["YNH_APP_BACKUP_DIR"] = tmp_app_bkp_dir
return env_var
def _collect_system_files(self):
"""
List file to backup for each selected system part
This corresponds to scripts in data/hooks/backup/ (system hooks) and
to those in /etc/yunohost/hooks.d/backup/ (user hooks)
Environment variables:
YNH_BACKUP_DIR -- The backup working directory (in
"/home/yunohost.backup/tmp/BACKUPNAME" or could be
defined by the user)
YNH_BACKUP_CSV -- A temporary CSV where the script whould list paths toi
backup
"""
system_targets = self.targets.list("system", exclude=["Skipped"])
# If nothing to backup, return immediately
if system_targets == []:
return
logger.debug(m18n.n('backup_running_hooks'))
# Prepare environnement
env_dict = self._get_env_var()
# Actual call to backup scripts/hooks
ret = hook_callback('backup',
system_targets,
args=[self.work_dir],
env=env_dict,
chdir=self.work_dir)
if ret["succeed"] != []:
self.system_return = ret["succeed"]
# Add files from targets (which they put in the CSV) to the list of
# files to backup
self._import_to_list_to_backup(env_dict["YNH_BACKUP_CSV"])
# Save restoration hooks for each part that suceeded (and which have
# a restore hook available)
restore_hooks_dir = os.path.join(self.work_dir, "hooks", "restore")
if not os.path.exists(restore_hooks_dir):
filesystem.mkdir(restore_hooks_dir, mode=0750,
parents=True, uid='admin')
restore_hooks = hook_list("restore")["hooks"]
for part in ret['succeed'].keys():
if part in restore_hooks:
part_restore_hooks = hook_info("restore", part)["hooks"]
for hook in part_restore_hooks:
self._add_to_list_to_backup(hook["path"], "hooks/restore/")
self.targets.set_result("system", part, "Success")
else:
logger.warning(m18n.n('restore_hook_unavailable', hook=part))
self.targets.set_result("system", part, "Warning")
for part in ret['failed'].keys():
logger.error(m18n.n('backup_system_part_failed', part=part))
self.targets.set_result("system", part, "Error")
def _collect_apps_files(self):
""" Prepare backup for each selected apps """
apps_targets = self.targets.list("apps", exclude=["Skipped"])
for app_instance_name in apps_targets:
self._collect_app_files(app_instance_name)
def _collect_app_files(self, app):
"""
List files to backup for the app into the paths_to_backup dict.
If the app backup script fails, paths from this app already listed for
backup aren't added to the general list and will be ignored
Environment variables:
YNH_BACKUP_DIR -- The backup working directory (in
"/home/yunohost.backup/tmp/BACKUPNAME" or could be
defined by the user)
YNH_BACKUP_CSV -- A temporary CSV where the script whould list paths toi
backup
YNH_APP_BACKUP_DIR -- The directory where the script should put
temporary files to backup like database dump,
files in this directory don't need to be added to
the temporary CSV.
YNH_APP_ID -- The app id (eg wordpress)
YNH_APP_INSTANCE_NAME -- The app instance name (eg wordpress__3)
YNH_APP_INSTANCE_NUMBER -- The app instance number (eg 3)
Args:
app -- (string) an app instance name (already installed) to backup
Exceptions:
backup_app_failed -- Raised at the end if the app backup script
execution failed
"""
app_setting_path = os.path.join('/etc/yunohost/apps/', app)
# Prepare environment
env_dict = self._get_env_var(app)
tmp_app_bkp_dir = env_dict["YNH_APP_BACKUP_DIR"]
settings_dir = os.path.join(self.work_dir, 'apps', app, 'settings')
logger.debug(m18n.n('backup_running_app_script', app=app))
try:
# Prepare backup directory for the app
filesystem.mkdir(tmp_app_bkp_dir, 0750, True, uid='admin')
# Copy the app settings to be able to call _common.sh
shutil.copytree(app_setting_path, settings_dir)
# Copy app backup script in a temporary folder and execute it
_, tmp_script = tempfile.mkstemp(prefix='backup_')
app_script = os.path.join(app_setting_path, 'scripts/backup')
subprocess.call(['install', '-Dm555', app_script, tmp_script])
hook_exec(tmp_script, args=[tmp_app_bkp_dir, app],
raise_on_error=True, chdir=tmp_app_bkp_dir, env=env_dict)
self._import_to_list_to_backup(env_dict["YNH_BACKUP_CSV"])
except:
abs_tmp_app_dir = os.path.join(self.work_dir, 'apps/', app)
shutil.rmtree(abs_tmp_app_dir, ignore_errors=True)
logger.exception(m18n.n('backup_app_failed', app=app))
self.targets.set_result("apps", app, "Error")
else:
# Add app info
i = app_info(app)
self.apps_return[app] = {
'version': i['version'],
'name': i['name'],
'description': i['description'],
}
self.targets.set_result("apps", app, "Success")
# Remove tmp files in all situations
finally:
filesystem.rm(tmp_script, force=True)
filesystem.rm(env_dict["YNH_BACKUP_CSV"], force=True)
###########################################################################
# Actual backup archive creation / method management #
###########################################################################
def add(self, method):
"""
Add a backup method that will be applied after the files collection step
Args:
method -- (BackupMethod) A backup method. Currently, you can use those:
TarBackupMethod
CopyBackupMethod
CustomBackupMethod
"""
self.methods.append(method)
def backup(self):
"""Apply backup methods"""
for method in self.methods:
logger.debug(m18n.n('backup_applying_method_' + method.method_name))
method.mount_and_backup(self)
logger.debug(m18n.n('backup_method_' + method.method_name + '_finished'))
def _compute_backup_size(self):
"""
Compute backup global size and details size for each apps and system
parts
Update self.size and self.size_details
Note: currently, these sizes are the size in this archive, not really
the size of needed to restore the archive. To know the size needed to
restore we should consider apt/npm/pip dependencies space and database
dump restore operations.
Return:
(int) The global size of the archive in bytes
"""
# FIXME Database dump will be loaded, so dump should use almost the
# double of their space
# FIXME Some archive will set up dependencies, those are not in this
# size info
self.size = 0
for system_key in self.system_return:
self.size_details['system'][system_key] = 0
for app_key in self.apps_return:
self.size_details['apps'][app_key] = 0
for row in self.paths_to_backup:
if row['dest'] != "info.json":
size = disk_usage(row['source'])
# Add size to apps details
splitted_dest = row['dest'].split('/')
category = splitted_dest[0]
if category == 'apps':
for app_key in self.apps_return:
if row['dest'].startswith('apps/' + app_key):
self.size_details['apps'][app_key] += size
break
# OR Add size to the correct system element
elif category == 'data' or category == 'conf':
for system_key in self.system_return:
if row['dest'].startswith(system_key.replace('_', '/')):
self.size_details['system'][system_key] += size
break
self.size += size
return self.size
class RestoreManager():
"""
RestoreManager allow to restore a past backup archive
Currently it's a tar.gz file, but it could be another kind of archive
Public properties:
info (getter)i # FIXME
work_dir (getter) # FIXME currently it's not a getter
name (getter) # FIXME currently it's not a getter
success (getter)
result (getter) # FIXME
Public methods:
set_targets(self, system_parts=[], apps=[])
restore(self)
Usage:
restore_manager = RestoreManager(name)
restore_manager.set_targets(None, ['wordpress__3'])
restore_manager.restore()
if restore_manager.success:
logger.success(m18n.n('restore_complete'))
return restore_manager.result
"""
def __init__(self, name, repo=None, method='tar'):
"""
RestoreManager constructor
Args:
name -- (string) Archive name
repo -- (string|None) Repository where is this archive, it could be a
path (default: /home/yunohost.backup/archives)
method -- (string) Method name to use to mount the archive
"""
# Retrieve and open the archive
# FIXME this way to get the info is not compatible with copy or custom
# backup methods
self.info = backup_info(name, with_details=True)
self.archive_path = self.info['path']
self.name = name
self.method = BackupMethod.create(method)
self.targets = BackupRestoreTargetsManager()
###########################################################################
# Misc helpers #
###########################################################################
@property
def success(self):
successful_apps = self.targets.list("apps", include=["Success", "Warning"])
successful_system = self.targets.list("system", include=["Success", "Warning"])
return len(successful_apps) != 0 \
or len(successful_system) != 0
def _read_info_files(self):
"""
Read the info file from inside an archive
Exceptions:
backup_invalid_archive -- Raised if we can't read the info
"""
# Retrieve backup info
info_file = os.path.join(self.work_dir, "info.json")
try:
with open(info_file, 'r') as f:
self.info = json.load(f)
# Historically, "system" was "hooks"
if "system" not in self.info.keys():
self.info["system"] = self.info["hooks"]
except IOError:
logger.debug("unable to load '%s'", info_file, exc_info=1)
raise YunohostError('backup_invalid_archive')
else:
logger.debug("restoring from backup '%s' created on %s", self.name,
datetime.utcfromtimestamp(self.info['created_at']))
def _postinstall_if_needed(self):
"""
Post install yunohost if needed
Exceptions:
backup_invalid_archive -- Raised if the current_host isn't in the
archive
"""
# Check if YunoHost is installed
if not os.path.isfile('/etc/yunohost/installed'):
# Retrieve the domain from the backup
try:
with open("%s/conf/ynh/current_host" % self.work_dir, 'r') as f:
domain = f.readline().rstrip()
except IOError:
logger.debug("unable to retrieve current_host from the backup",
exc_info=1)
# FIXME include the current_host by default ?
raise YunohostError('backup_invalid_archive')
logger.debug("executing the post-install...")
tools_postinstall(domain, 'yunohost', True)
def clean(self):
"""
End a restore operations by cleaning the working directory and
regenerate ssowat conf (if some apps were restored)
"""
successfull_apps = self.targets.list("apps", include=["Success", "Warning"])
if successfull_apps != []:
# Quickfix: the old app_ssowatconf(auth) instruction failed due to
# ldap restore hooks
os.system('sudo yunohost app ssowatconf')
if os.path.ismount(self.work_dir):
ret = subprocess.call(["umount", self.work_dir])
if ret != 0:
logger.warning(m18n.n('restore_cleaning_failed'))
filesystem.rm(self.work_dir, True, True)
###########################################################################
# Restore target manangement #
###########################################################################
def set_system_targets(self, system_parts=[]):
"""
Define system parts that will be restored
Args:
system_parts -- (list) list of system parts which should be restored.
If an empty list if given, restore all system part in
the archive. If None is given, no system will be restored.
"""
def unknown_error(part):
logger.error(m18n.n("backup_archive_system_part_not_available",
part=part))
target_list = self.targets.set_wanted("system",
system_parts,
self.info['system'].keys(),
unknown_error)
# Now we need to check that the restore hook is actually available for
# all targets we want to restore
# These are the hooks on the current installation
available_restore_system_hooks = hook_list("restore")["hooks"]
for system_part in target_list:
# By default, we'll use the restore hooks on the current install
# if available
# FIXME: so if the restore hook exist we use the new one and not
# the one from backup. So hook should not break compatibility..
if system_part in available_restore_system_hooks:
continue
# Otherwise, attempt to find it (or them?) in the archive
hook_paths = '{:s}/hooks/restore/*-{:s}'.format(self.work_dir, system_part)
hook_paths = glob(hook_paths)
# If we didn't find it, we ain't gonna be able to restore it
if len(hook_paths) == 0:
logger.exception(m18n.n('restore_hook_unavailable', part=system_part))
self.targets.set_result("system", system_part, "Skipped")
continue
# Otherwise, add it from the archive to the system
# FIXME: Refactor hook_add and use it instead
custom_restore_hook_folder = os.path.join(CUSTOM_HOOK_FOLDER, 'restore')
filesystem.mkdir(custom_restore_hook_folder, 755, True)
for hook_path in hook_paths:
logger.debug("Adding restoration script '%s' to the system "
"from the backup archive '%s'", hook_path,
self.archive_path)
shutil.copy(hook_path, custom_restore_hook_folder)
def set_apps_targets(self, apps=[]):
"""
Define and validate targetted apps to be restored
Args:
apps -- (list) list of apps which should be restored. If [] is given,
all apps in the archive will be restored. If None is given,
no apps will be restored.
"""
def unknown_error(app):
logger.error(m18n.n('backup_archive_app_not_found',
app=app))
self.targets.set_wanted("apps",
apps,
self.info['apps'].keys(),
unknown_error)
###########################################################################
# Archive mounting #
###########################################################################
def mount(self):
"""
Mount the archive. We avoid copy to be able to restore on system without
too many space.
Use the mount method from the BackupMethod instance and read info about
this archive
Exceptions:
restore_removing_tmp_dir_failed -- Raised if it's not possible to remove
the working directory
"""
self.work_dir = os.path.join(BACKUP_PATH, "tmp", self.name)