forked from Pectojin/duplicati-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathduplicati_client.py
executable file
·1308 lines (1094 loc) · 45.4 KB
/
duplicati_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import arg_parser as ArgumentParser
import config
import json
import os.path
import sys
import datetime
import time
import yaml
import compatibility
import common
import auth
import helper
from os.path import expanduser
from os.path import splitext
from requests_wrapper import requests_wrapper as requests
def main(**args):
# Command method
method = sys.argv[1]
if method == "version":
message = "Duplicati client version "
message += config.APPLICATION_VERSION
return common.log_output(message, True)
# Default values
data = {
"last_login": None,
"parameters_file": None,
"server": {
"port": "",
"protocol": "http",
"url": "localhost",
"verify": True
},
'token': None,
'token_expires': None,
'verbose': False,
'authorization': ''
}
# Detect home dir for config file
config.CONFIG_FILE = compatibility.get_config_location()
# Load configuration
overwrite = args.get("overwrite", False)
data = load_config(data, overwrite)
param_file = args.get("param-file", None)
# Set parameters file
if method == "params":
data = set_parameters_file(data, args, param_file)
# Load parameters file
args = common.load_parameters(data, args)
# Show parameters
if method == "params" and (args.get("show", False) or param_file is None):
display_parameters(data)
# Toggle verbosity
if method == "verbose":
mode = args.get("mode", None)
data = toggle_verbose(data, mode)
# Write verbosity setting to config variable
config.VERBOSE = data.get("verbose", False)
# Display the config if requested
if method == "config":
display_config(data)
# Display the status if requested
if method == "status":
display_status(data)
# Login
if method == "login":
url = args.get("url", None)
password = args.get("password", None)
basic_user = args.get("basic_user", None)
basic_pass = args.get("basic_pass", None)
certfile = args.get("certfile", None)
insecure = args.get("insecure", False)
verify = auth.determine_ssl_validation(data, certfile, insecure)
interactive = args.get("script", True)
data = auth.login(data, url, password, verify, interactive,
basic_user, basic_pass)
# Logout
if method == "logout":
data = auth.logout(data)
# List resources
if method == "list":
resource_type = args.get("type", None)
list_resources(data, resource_type)
# Get resources
if method == "get":
resource_type = args.get("type", None)
resource_ids = args.get("id", None)
get_resources(data, resource_type, resource_ids)
# Describe resources
if method == "describe":
resource_type = args.get("type", None)
resource_ids = args.get("id", None)
describe_resources(data, resource_type, resource_ids)
# Set resource values
if method == "set":
resource = sys.argv[2]
if resource == "password":
password = args.get("password", None)
disable_login = args.get("disable", False)
interactive = args.get("script", True)
auth.set_password(data, password, disable_login, interactive)
# Repair a database
if method == "repair":
backup_id = args.get("id", None)
repair_database(data, backup_id)
# Vacuum a database
if method == "vacuum":
backup_id = args.get("id", None)
vacuum_database(data, backup_id)
# Verify remote data files
if method == "verify":
backup_id = args.get("id", None)
verify_remote_files(data, backup_id)
# Compact remote data
if method == "compact":
backup_id = args.get("id", None)
compact_remote_files(data, backup_id)
# Dismiss notifications
if method == "dismiss":
resource_id = args.get("id", "all")
if not resource_id.isdigit() and resource_id != "all":
common.log_output("Invalid id: " + resource_id, True)
return
dismiss_notifications(data, resource_id)
# Show logs
if method == "logs":
log_type = args.get("type", None)
backup_id = args.get("id", None)
remote = args.get("remote", False)
follow = args.get("follow", False)
lines = args.get("lines", 10)
show_all = args.get("all", False)
get_logs(data, log_type, backup_id, remote, follow, lines, show_all)
# Run backup
if method == "run":
backup_id = args.get("id", None)
run_backup(data, backup_id)
# Abort backup
if method == "abort":
backup_id = args.get("id", None)
abort_task(data, backup_id)
# Create method
if method == "create":
import_type = args.get("type", None)
import_file = args.get("import-file", None)
import_meta = args.get("import_metadata", None)
import_resource(data, import_type, import_file, None, import_meta)
# Update method
if method == "update":
import_type = args.get("type", None)
import_id = args.get("id", None)
import_file = args.get("import-file", None)
# import-metadata is the inverse of strip-metadata
import_meta = not args.get("strip_metadata", False)
import_resource(data, import_type, import_file, import_id, import_meta)
# Delete a resource
if method == "delete":
resource_id = args.get("id", None)
resource_type = args.get("type", None)
delete_db = args.get("delete_db", False)
confirm = args.get("confirm", False)
recreate = args.get("recreate", False)
delete_resource(data, resource_type, resource_id,
confirm, delete_db, recreate)
# Export method
if method == "export":
resource_id = args.get("id", None)
output_type = args.get("output", None)
path = args.get("output_path", None)
export_passwords = args.get("no_passwords", True)
all_ids = args.get("all", False)
timestamp = args.get("timestamp", False)
print(export_passwords)
export_backup(data, resource_id, output_type, path,
export_passwords, all_ids, timestamp)
# Function for display a list of resources
def list_resources(data, resource):
common.verify_token(data)
if resource == "backups":
resource_list = fetch_backup_list(data)
elif resource == "databases":
resource_list = fetch_database_list(data)
else:
resource_list = fetch_resource_list(data, resource)
resource_list = list_filter(resource_list, resource)
if len(resource_list) == 0:
common.log_output("No items found", True)
sys.exit(2)
# Must use safe_dump for python 2 compatibility
message = yaml.safe_dump(resource_list, default_flow_style=False)
common.log_output(message, True, 200)
# Fetch all backups
def fetch_backup_list(data):
backups = fetch_resource_list(data, "backups")
# Fetch progress state
progress_state, active_id = fetch_progress_state(data)
progress = progress_state.get("OverallProgress", 1)
backup_list = []
for backup in backups:
backup_id = backup.get("Backup", {}).get("ID", 0)
if active_id is not None and backup_id == active_id and progress != 1:
backup["Progress"] = progress_state
backup_list.append(backup)
return backup_list
# Fetch all databases
def fetch_database_list(data):
databases = fetch_resource_list(data, "backups")
database_list = []
for backup in databases:
db_path = backup.get("Backup", {}).get("DBPath", "")
db_exists = validate_database_exists(data, db_path)
database = {
"Backup": backup.get("Backup", {}).get("Name", 0),
"DBPath": db_path,
"ID": backup.get("Backup", {}).get("ID", 0),
"Exists": db_exists
}
database_list.append(database)
return database_list
# Validate that the database exists on the server
def validate_database_exists(data, db_path):
common.verify_token(data)
# api/v1/filesystem/validate
baseurl = common.create_baseurl(data, "/api/v1/filesystem/validate")
cookies = common.create_cookies(data)
headers = common.create_headers(data)
payload = {'path': db_path}
verify = data.get("server", {}).get("verify", True)
r = requests.post(baseurl, headers=headers, params=payload,
cookies=cookies, verify=verify)
common.check_response(data, r.status_code)
if r.status_code != 200:
return False
return True
# Fetch all resources of a certain type
def fetch_resource_list(data, resource):
baseurl = common.create_baseurl(data, "/api/v1/" + resource)
common.log_output("Fetching " + resource + " list from API...", False)
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
r = requests.get(baseurl, headers=headers, cookies=cookies, verify=verify)
common.check_response(data, r.status_code)
if r.status_code == 404:
common.log_output("No entries found", True, r.status_code)
sys.exit(2)
elif r.status_code != 200:
common.log_output("Error connecting", True, r.status_code)
sys.exit(2)
else:
return r.json()
# Filter logic for the list function to facilitate readable output
def list_filter(json_input, resource):
resource_list = []
if resource == "backups":
for key in json_input:
backup = key.get("Backup", None)
schedule = key.get("Schedule", None)
progress_state = key.get("Progress", None)
backup_name = backup.get("Name", "")
backup = {
backup_name: {
"ID": backup.get("ID", ""),
}
}
if backup.get('Metadata', {}).get('SourceSizeString') is not None:
size = backup.get('Metadata', {}).get('SourceSizeString')
backup[backup_name]["Source size"] = size
if schedule is not None:
next_run = helper.format_time(schedule.get("Time", ""))
if next_run is not None:
backup[backup_name]["Next run"] = next_run
last_run = helper.format_time(schedule.get("LastRun", ""))
if last_run is not None:
backup[backup_name]["Last run"] = last_run
if progress_state is not None:
backup[backup_name]["Running"] = {
"Task ID": progress_state.get("TaskID", None),
"State": progress_state.get("Phase", None),
}
resource_list.append(backup)
elif resource == "notifications":
for val in json_input:
notification = {
val.get("Title", ""): {
"Backup ID": val.get("BackupID", ""),
"Notification ID": val.get("ID", ""),
}
}
timestamp = helper.format_time(val.get("Timestamp", ""))
if timestamp is not None:
notification["Timestamp"] = timestamp
resource_list.append(notification)
elif resource == "serversettings":
for key, value in json_input.items():
hidden_values = [
"update-check-latest",
"last-update-check",
"is-first-run",
"update-check-interval",
"server-passphrase",
"server-passphrase-salt",
"server-passphrase-trayicon",
"server-passphrase-trayicon-hash",
"unacked-error",
"unacked-warning",
"has-fixed-invalid-backup-id",
]
if key in hidden_values:
continue
setting = {
key: {
"value": value
}
}
resource_list.append(setting)
else:
resource_list = json_input
return resource_list
# Get one or more resources with somewhat limited fields
def get_resources(data, resource_type, resource_ids):
if resource_type == "backup":
result = fetch_backups(data, resource_ids, "get")
elif resource_type == "notification":
result = fetch_notifications(data, resource_ids, "get")
message = yaml.safe_dump(result, default_flow_style=False)
common.log_output(message, True, 200)
# Get one or more resources with all fields
def describe_resources(data, resource_type, resource_ids):
if resource_type == "backup":
result = fetch_backups(data, resource_ids, "describe")
elif resource_type == "notification":
result = fetch_notifications(data, resource_ids, "describe")
# Must use safe_dump for python 2 compatibility
message = yaml.safe_dump(result, default_flow_style=False)
common.log_output(message, True, 200)
# Fetch notifications
def fetch_notifications(data, notification_ids, method):
common.verify_token(data)
common.log_output("Fetching notifications from API...", False)
baseurl = common.create_baseurl(data, "/api/v1/notifications")
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
notification_list = []
r = requests.get(baseurl, headers=headers, cookies=cookies, verify=verify)
common.check_response(data, r.status_code)
if r.status_code != 200:
id_list = ', '.join(notification_ids)
message = "Error getting notifications " + id_list
common.log_output(message, True, r.status_code)
else:
data = r.json()
for notification in data:
notification_id = notification.get("ID", -1)
if notification_id in notification_ids:
notification_list.append(notification)
# Only get uses a filter
if method == "get":
notification_list = notification_filter(notification_list)
return notification_list
# Filter logic for the notification get command
def notification_filter(json_input):
notification_list = []
for key in json_input:
title = key.get("Title", "Notification")
notification = {
title: {
"Backup ID": key.get("BackupID", ""),
"Notification ID": key.get("ID", ""),
"Message": key.get("Message", ""),
"Type": key.get("Type", ""),
}
}
timestamp = helper.format_time(key.get("Timestamp", ""))
if timestamp is not None:
notification[title]["Timestamp"] = timestamp
notification_list.append(notification)
return notification_list
# Fetch backups
def fetch_backups(data, backup_ids, method):
common.verify_token(data)
common.log_output("Fetching backups from API...", False)
progress_state, active_id = fetch_progress_state(data)
progress = progress_state.get("OverallProgress", 1)
backup_list = []
baseurl = common.create_baseurl(data, "/api/v1/backup/")
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
# Iterate over backup_ids and fetch their info
for backup_id in backup_ids:
r = requests.get(baseurl + str(backup_id), headers=headers,
cookies=cookies, verify=verify)
common.check_response(data, r.status_code)
if r.status_code != 200:
message = "Error getting backup " + str(backup_id)
common.log_output(message, True, r.status_code)
continue
backup = r.json()["data"]
item_id = backup.get("Backup", {}).get("ID", 0)
if active_id is not None and item_id == active_id and progress != 1:
backup["Progress"] = progress_state
backup_list.append(backup)
if len(backup_list) == 0:
sys.exit(2)
# Only get uses a filter
if method == "get":
backup_list = backup_filter(backup_list)
return backup_list
# Fetch backup progress state
def fetch_progress_state(data):
baseurl = common.create_baseurl(data, "/api/v1/progressstate")
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
# Check progress state and get info for the running backup
r = requests.get(baseurl, headers=headers, cookies=cookies, verify=verify)
if r.status_code != 200:
active_id = -1
progress_state = {}
else:
progress_state = r.json()
active_id = progress_state.get("BackupID", -1)
# Don't show progress on finished tasks
phase = progress_state.get("Phase", "")
if phase in ["Backup_Complete", "Error"]:
return {}, 0
return progress_state, active_id
# Filter logic for the fetch backup/backups methods
def backup_filter(json_input):
backup_list = []
for key in json_input:
backup = key.pop("Backup", {})
metadata = backup.pop("Metadata", {})
backup_name = backup.pop("Name", {})
backup = {
"ID": backup.get("ID", ""),
"Local database": backup.get("DBPath", ""),
}
backup["Versions"] = int(metadata.get("BackupListCount", 0))
backup["Last run"] = {
"Duration":
helper.format_duration(metadata.get("LastBackupDuration", "0")),
"Started":
helper.format_time(metadata.get("LastBackupStarted", "0")),
"Stopped":
helper.format_time(metadata.get("LastBackupFinished", "0")),
}
backup["Size"] = {
"Local": metadata.get("SourceSizeString", ""),
"Backend": metadata.get("TargetSizeString", "")
}
schedule = key.get("Schedule", None)
if schedule is not None:
next_run = helper.format_time(schedule.pop("Time", ""))
if next_run is not None:
schedule["Next run"] = next_run
last_run = helper.format_time(schedule.pop("LastRun", ""))
if last_run is not None:
schedule["Last run"] = last_run
schedule.pop("AllowedDays", None)
schedule.pop("ID", None)
schedule.pop("Rule", None)
schedule.pop("Tags", None)
backup["Schedule"] = schedule
progress_state = key.get("Progress", None)
if progress_state is not None:
state = progress_state.get("Phase", None)
speed = progress_state.get("BackendSpeed", 0)
progress = {
"State": state,
"Counting files": progress_state.get("StillCounting", False),
"Backend": {
"Action": progress_state.get("BackendAction", 0)
},
"Task ID": progress_state.get("TaskID", -1),
}
if speed > 0:
readable_speed = helper.format_bytes(speed) + "/s"
progress["Backend"]["Speed"] = readable_speed
# Display item only if relevant
if not progress_state.get("StillCounting", False):
progress.pop("Counting files")
# Avoid 0 division
file_count = progress_state.get("ProcessedFileCount", 0)
total_file_count = progress_state.get("TotalFileCount", 0)
processing = state == "Backup_ProcessingFiles"
if file_count > 0 and total_file_count > 0 and processing:
processed = "{0:.2f}".format(file_count /
total_file_count * 100)
progress["Processed files"] = processed + "%"
# Avoid 0 division
data_size = progress_state.get("ProcessedFileSize", 0)
total_data_size = progress_state.get("TotalFileSize", 0)
processing = state == "Backup_ProcessingFiles"
if data_size > 0 and total_data_size > 0 and processing:
# Calculate percentage
processed = "{0:.2f}".format(data_size / total_data_size * 100)
# Format text "x% (y GB of z GB)"
processed += "% (" + str(helper.format_bytes(data_size))
processed += " of "
processed += str(helper.format_bytes(total_data_size)) + ")"
progress["Processed data"] = processed
# Avoid 0 division
current = progress_state.get("BackendFileProgress", 0)
total = progress_state.get("BackendFileSize", 0)
if current > 0 and total > 0:
backend_progress = "{0:.2f}".format(current / total * 100)
progress["Backend"]["Progress"] = backend_progress + "%"
backup["Progress"] = progress
key = {
backup_name: backup
}
backup_list.append(key)
return backup_list
# Dimiss notifications
def dismiss_notifications(data, resource_id="all"):
common.verify_token(data)
id_list = []
if resource_id == "all":
# Get all notification ID's
notifications = fetch_resource_list(data, "notifications")
for notification in notifications:
id_list.append(notification["ID"])
else:
id_list.append(resource_id)
if len(id_list) == 0:
common.log_output("No notifications", True)
return
for item in id_list:
delete_resource(data, "notification", item, True)
# Fetch logs
def get_logs(data, log_type, backup_id, remote=False,
follow=False, lines=10, show_all=False):
common.verify_token(data)
if log_type == "backup" and backup_id is None:
common.log_output("A backup id must be provided with --id", True)
sys.exit(2)
# Treating functions as objects to allow any function to be "followed"
if log_type == "backup" and remote:
def function():
get_backup_logs(data, backup_id, "remotelog", lines, show_all)
elif log_type == "backup" and not remote:
def function():
get_backup_logs(data, backup_id, "log", lines, show_all)
elif log_type in ["profiling", "information", "warning", "error"]:
def function():
get_live_logs(data, log_type, lines)
elif log_type == "stored":
def function():
get_stored_logs(data, lines, show_all)
# Follow the function or just run it once
if follow:
follow_function(function, 10)
else:
function()
# Get local and remote backup logs
def get_backup_logs(data, backup_id, log_type, page_size=5, show_all=False):
endpoint = "/api/v1/backup/" + str(backup_id) + "/" + log_type
baseurl = common.create_baseurl(data, endpoint)
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
params = {'pagesize': page_size}
r = requests.get(baseurl, headers=headers, cookies=cookies, params=params,
verify=verify)
common.check_response(data, r.status_code)
if r.status_code == 500:
message = "Error getting log, "
message += "database may be locked by backup"
common.log_output(message, True)
return
elif r.status_code != 200:
common.log_output("Error getting log", True, r.status_code)
return
result = r.json()[-page_size:]
logs = []
for log in result:
if log.get("Operation", "") == "list":
log["Data"] = "Expunged"
else:
log["Data"] = json.loads(log.get("Data", "{}"))
size = helper.format_bytes(log["Data"].get("Size", 0))
log["Data"]["Size"] = size
if log.get("Message", None) is not None:
log["Message"] = log["Message"].split("\n")
message_length = len(log["Message"])
if message_length > 15 and not show_all:
log["Message"] = log["Message"][:15]
lines = str(message_length - 15)
hidden_message = lines + " hidden lines (show with --all)"
log["Message"].append(hidden_message)
if log.get("Exception", None) is not None:
log["Exception"] = log["Exception"].split("\n")
exception_length = len(log["Exception"])
if exception_length > 15 and not show_all:
log["Exception"] = log["Exception"][:15]
lines = str(exception_length - 15)
hidden_message = lines + " hidden lines (show with --all)"
log["Exception"].append(hidden_message)
log["Timestamp"] = datetime.datetime.fromtimestamp(
int(log.get("Timestamp", 0))
).strftime("%I:%M:%S %p %d/%m/%Y")
logs.append(log)
message = yaml.safe_dump(logs, default_flow_style=False)
common.log_output(message, True)
# Get live logs
def get_live_logs(data, level, page_size=5, first_id=0):
baseurl = common.create_baseurl(data, "/api/v1/logdata/poll")
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
params = {'level': level, 'id': first_id, 'pagesize': page_size}
r = requests.get(baseurl, headers=headers, cookies=cookies, params=params,
verify=verify)
common.check_response(data, r.status_code)
if r.status_code == 500:
message = "Error getting log, "
message += "database may be locked by backup"
common.log_output(message, True)
return
elif r.status_code != 200:
common.log_output("Error getting log", True, r.status_code)
return
result = r.json()[-page_size:]
logs = []
for log in result:
log["When"] = helper.format_time(log.get("When", ""), True)
logs.append(log)
if len(logs) == 0:
common.log_output("No log entries found", True)
return
message = yaml.safe_dump(logs, default_flow_style=False)
common.log_output(message, True)
# Get stored logs
def get_stored_logs(data, page_size=5, show_all=False):
baseurl = common.create_baseurl(data, "/api/v1/logdata/log")
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
params = {'pagesize': page_size}
r = requests.get(baseurl, headers=headers, cookies=cookies, params=params,
verify=verify)
common.check_response(data, r.status_code)
if r.status_code == 500:
message = "Error getting log, "
message += "database may be locked by backup"
common.log_output(message, True)
return
elif r.status_code != 200:
common.log_output("Error getting log", True, r.status_code)
return
result = r.json()[-page_size:]
logs = []
for log in result:
if log.get("Message", None) is not None:
log["Message"] = log["Message"].split("\n")
message_length = len(log["Message"])
if message_length > 15 and not show_all:
log["Message"] = log["Message"][:15]
lines = str(message_length - 15)
hidden_message = lines + " hidden lines (show with --all)"
log["Message"].append(hidden_message)
if log.get("Exception", None) is not None:
log["Exception"] = log["Exception"].split("\n")
exception_length = len(log["Exception"])
if exception_length > 15 and not show_all:
log["Exception"] = log["Exception"][:15]
lines = str(exception_length - 15)
hidden_message = lines + " hidden lines (show with --all)"
log["Exception"].append(hidden_message)
logs.append(log)
if len(logs) == 0:
common.log_output("No log entries found", True)
return
message = yaml.safe_dump(logs, default_flow_style=False)
common.log_output(message, True)
# Repeatedly call other functions until interrupted
def follow_function(function, interval=5):
try:
while True:
compatibility.clear_prompt()
function()
timestamp = helper.format_time(datetime.datetime.now(), True)
common.log_output(timestamp, True)
common.log_output("Press control+C to quit", True)
time.sleep(interval)
except KeyboardInterrupt:
return
# Call the API to schedule a backup run next
def run_backup(data, backup_id):
common.verify_token(data)
path = "/api/v1/backup/" + str(backup_id) + "/run"
baseurl = common.create_baseurl(data, path)
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
r = requests.post(baseurl, headers=headers, cookies=cookies, verify=verify)
common.check_response(data, r.status_code)
if r.status_code != 200:
common.log_output("Error scheduling backup ", True, r.status_code)
return
common.log_output("Backup scheduled", True, 200)
# Call the API to abort a task
def abort_task(data, task_id):
common.verify_token(data)
path = "/api/v1/task/" + str(task_id) + "/abort"
baseurl = common.create_baseurl(data, path)
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
r = requests.post(baseurl, headers=headers, cookies=cookies, verify=verify)
common.check_response(data, r.status_code)
if r.status_code != 200:
common.log_output("Error aborting task ", True, r.status_code)
return
common.log_output("Task aborted", True, 200)
# Delete wrapper
def delete_resource(data, resource_type, resource_id,
confirm=False, delete_db=False, recreate=False):
if resource_type == "backup":
delete_backup(data, resource_id, confirm, delete_db)
elif resource_type == "database":
delete_database(data, resource_id, confirm, recreate)
elif resource_type == "notification":
delete_notification(data, resource_id)
# Call the API to delete a backup
def delete_backup(data, backup_id, confirm=False, delete_db=False):
common.verify_token(data)
# Check if the backup exists
result = fetch_backups(data, [backup_id], "get")
if result is None or len(result) == 0:
return
if not confirm:
# Confirm deletion with user
name = next(iter(result[0]))
message = 'Delete "' + name + '"? (ID:' + str(backup_id) + ')'
options = '[y/N]:'
agree = input(message + ' ' + options)
if agree not in ["Y", "y", "yes", "YES"]:
common.log_output("Backup not deleted", True)
return
baseurl = common.create_baseurl(data, "/api/v1/backup/" + str(backup_id))
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
# We cannot delete remote files because the captcha is graphical
payload = {'delete-local-db': delete_db, 'delete-remote-files': False}
r = requests.delete(baseurl, headers=headers, cookies=cookies,
params=payload, verify=verify)
common.check_response(data, r.status_code)
if r.status_code != 200:
common.log_output("Error deleting backup", True, r.status_code)
return
common.log_output("Backup deleted", True, 200)
# Call the API to delete a database
def delete_database(data, backup_id, confirm=False, recreate=False):
common.verify_token(data)
# Check if the backup exists
result = fetch_backups(data, [backup_id], "get")
if result is None or len(result) == 0:
return
if not confirm:
# Confirm deletion with user
name = next(iter(result[0]))
message = 'Delete database ' + str(backup_id)
message += ' belonging to "' + name + '"?'
options = '[y/N]:'
agree = input(message + ' ' + options)
if agree not in ["Y", "y", "yes", "YES"]:
common.log_output("Database not deleted", True)
return
baseurl = common.create_baseurl(data, "/api/v1/backup/" +
str(backup_id) + "/deletedb")
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
r = requests.post(baseurl, headers=headers, cookies=cookies,
verify=verify)
common.check_response(data, r.status_code)
if r.status_code != 200:
common.log_output("Error deleting database", True, r.status_code)
return
common.log_output("Database deleted", True, 200)
if recreate:
repair_database(data, backup_id)
# Repair the database
def repair_database(data, backup_id):
url = "/api/v1/backup/" + backup_id + "/repair"
fail_message = "Failed to initialize database repair"
success_message = "Initialized database repair"
call_backup_subcommand(data, url, fail_message, success_message)
# Vacuum the database
def vacuum_database(data, backup_id):
url = "/api/v1/backup/" + backup_id + "/vacuum"
fail_message = "Failed to initialize database vacuum"
success_message = "Initialized database vacuum"
call_backup_subcommand(data, url, fail_message, success_message)
# Verify the remote data files
def verify_remote_files(data, backup_id):
url = "/api/v1/backup/" + backup_id + "/verify"
fail_message = "Failed to initialize remote file verification"
success_message = "Initialized remote file verification"
call_backup_subcommand(data, url, fail_message, success_message)
# Compact the remote data files
def compact_remote_files(data, backup_id):
url = "/api/v1/backup/" + backup_id + "/compact"
fail_message = "Failed to initialize remote data compaction"
success_message = "Initialized remote file compaction"
call_backup_subcommand(data, url, fail_message, success_message)
# Method for calling various subcommands for backups
# E.g. "/api/v1/backup/id/compact"
def call_backup_subcommand(data, url, fail_message, success_message):
common.verify_token(data)
baseurl = common.create_baseurl(data, url)
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
r = requests.post(baseurl, headers=headers, cookies=cookies,
verify=verify)
common.check_response(data, r.status_code)
if r.status_code != 200:
common.log_output(fail_message, True, r.status_code)
return
common.log_output(success_message, True, 200)
# Call the API to delete a notification
def delete_notification(data, notification_id):
common.verify_token(data)
url = "/api/v1/notification/"
baseurl = common.create_baseurl(data, url + str(notification_id))
cookies = common.create_cookies(data)
headers = common.create_headers(data)
verify = data.get("server", {}).get("verify", True)
r = requests.delete(baseurl, headers=headers, cookies=cookies,