-
Notifications
You must be signed in to change notification settings - Fork 0
/
Backupper.py
1881 lines (1566 loc) · 73.3 KB
/
Backupper.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
"""
This file is part of the FloppyCat Simple Backup Utility distribution
(https://github.com/F33RNI/FloppyCat)
Copyright (C) 2023-2024 Fern Lane
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 long with this program.
If not, see <http://www.gnu.org/licenses/>.
"""
from datetime import datetime, timedelta
import logging
import multiprocessing
import os
from pathlib import Path
import queue
import threading
import time
from typing import Dict, List, Tuple
from PyQt5 import QtCore
import ConfigManager
from DisplayablePath import DisplayablePath
from tree_parser import tree_parser, PATH_FILE, PATH_DIR, PATH_SYMLINK, PATH_UNKNOWN
from checksums import parse_checksums_from_file, calculate_checksums
from delete_files import delete_files
from copy_entries import copy_entries
from _control_values import PROCESS_CONTROL_WORK, PROCESS_CONTROL_PAUSE, PROCESS_CONTROL_EXIT
# Filter to smooth left time
TIME_LEFT_FILTER = 0.99998
# States after backup / validation finished
EXIT_CODE_SUCCESSFULLY = 0
EXIT_CODE_ERROR = 1
EXIT_CODE_CANCELED = 2
# Mode definitions
MODE_IDLE = 0
MODE_BACKUP = 1
MODE_VALIDATION = 2
class Backupper:
def __init__(self, config_manager: ConfigManager.ConfigManager, logging_queue: multiprocessing.Queue) -> None:
self._config_manager = config_manager
self._logging_queue = logging_queue
# Set any of this flag to manage backupper process
self.request_pause = False
self.request_resume = False
self.request_cancel = False
# Current state
self.paused = False
# Current mode
self.mode_current = MODE_IDLE
# Time calculation of backup/validation
self._time_started = 0.0
self._time_passed_prev = 0.0
self._progress_total_prev = 0.0
self._progress_steps_prev = 0.0
self._time_left_stage_filtered = 0.0
self._time_left_total_filtered = 0.0
self._time_passed_str = "00:00:00"
# Stages counters for progress
self._stage_current = 0
self._stages_total = 0
# PyQt signals
self._time_passed_signal = None
self._time_left_signal = None
self._progress_set_value_signal = None
self._statusbar_show_message_signal = None
self._backup_paused_resumed_signal = None
self._finished_signal = None
# Backup results
self._stats_tree_parsed_dirs = multiprocessing.Value("i", 0)
self._stats_tree_parsed_files = multiprocessing.Value("i", 0)
self._stats_tree_parsed_symlinks = multiprocessing.Value("i", 0)
self._stats_tree_parsed_unknown = multiprocessing.Value("i", 0)
self._stats_checksums_calculate_ok_value = multiprocessing.Value("i", 0)
self._stats_checksums_calculate_error_value = multiprocessing.Value("i", 0)
self._stats_deleted_ok_value = multiprocessing.Value("i", 0)
self._stats_deleted_error_value = multiprocessing.Value("i", 0)
self._stats_created_dirs_ok_value = multiprocessing.Value("i", 0)
self._stats_created_dirs_error_value = multiprocessing.Value("i", 0)
self._stats_created_symlinks_value = multiprocessing.Value("i", 0)
self._stats_copied_ok_value = multiprocessing.Value("i", 0)
self._stats_copied_error_value = multiprocessing.Value("i", 0)
# Validate results
self._stats_validate_match = multiprocessing.Value("i", 0)
self._stats_validate_not_match = multiprocessing.Value("i", 0)
self._stats_validate_not_exist = multiprocessing.Value("i", 0)
def stats_reset(self) -> None:
"""Resets all backup and validation statistics"""
self._stats_tree_parsed_dirs.value = 0
self._stats_tree_parsed_files.value = 0
self._stats_tree_parsed_symlinks.value = 0
self._stats_tree_parsed_unknown.value = 0
self._stats_checksums_calculate_ok_value.value = 0
self._stats_checksums_calculate_error_value.value = 0
self._stats_deleted_ok_value.value = 0
self._stats_deleted_error_value.value = 0
self._stats_created_dirs_ok_value.value = 0
self._stats_created_dirs_error_value.value = 0
self._stats_created_symlinks_value.value = 0
self._stats_copied_ok_value.value = 0
self._stats_copied_error_value.value = 0
self._stats_validate_match.value = 0
self._stats_validate_not_match.value = 0
self._stats_validate_not_exist.value = 0
def stats_to_str(self) -> str:
"""Parses backup statistics
Returns:
str: backup statistics as multiline str
"""
stats = f"Time passed: {self._time_passed_str}\n\n"
stats += f"Files and directories copied: {self._stats_copied_ok_value.value}, "
stats += f"errors: {self._stats_copied_error_value.value}\n"
stats += f"Files and directories deleted: {self._stats_deleted_ok_value.value}, "
stats += f"errors: {self._stats_deleted_error_value.value}\n"
stats += f"Directories created: {self._stats_created_dirs_ok_value.value}, "
stats += f"errors: {self._stats_created_dirs_error_value.value}\n"
stats += f"Symlinks created: {self._stats_created_symlinks_value.value}\n\n"
stats += f"(Files viewed: {self._stats_tree_parsed_files.value}, "
stats += f"dirs: {self._stats_tree_parsed_dirs.value}, "
stats += f"symlinks: {self._stats_tree_parsed_symlinks.value}, "
stats += f"unknown: {self._stats_tree_parsed_unknown.value})\n"
stats += f"(Checksums calculated: {self._stats_checksums_calculate_ok_value.value}, "
stats += f"errors: {self._stats_checksums_calculate_error_value.value})\n\n"
stats += "See logs for details"
return stats
def validation_stats_to_str(self) -> str:
"""Parses validation statistics
Returns:
str: validation statistics as multiline str
"""
stats = f"Time passed: {self._time_passed_str}\n\n"
if (self._stats_validate_match.value + self._stats_validate_not_match.value) != 0:
invalid_rate = (
self._stats_validate_not_match.value
/ (self._stats_validate_match.value + self._stats_validate_not_match.value)
* 100
)
stats += f"Error rate: {invalid_rate:.2f}%\n"
else:
stats += ""
stats += f"Matches: {self._stats_validate_match.value}\n"
stats += f"Mismatches: {self._stats_validate_not_match.value}\n"
stats += f"Checksums not found: {self._stats_validate_not_exist.value}\n\n"
stats += f"(Files viewed: {self._stats_tree_parsed_files.value}, "
stats += f"dirs: {self._stats_tree_parsed_dirs.value}, "
stats += f"symlinks: {self._stats_tree_parsed_symlinks.value}, "
stats += f"unknown: {self._stats_tree_parsed_unknown.value})\n"
stats += f"(Checksums calculated: {self._stats_checksums_calculate_ok_value.value}, "
stats += f"errors: {self._stats_checksums_calculate_error_value.value})\n\n"
stats += "See logs for details"
return stats
def stats_to_statusbar(self) -> str:
"""Parses statistics to fit statusbar
Returns:
str: statistics as single line str
"""
stats = f"S: {self._stage_current} / {self._stages_total} "
with self._stats_tree_parsed_files.get_lock():
stats += f"Fv: {self._stats_tree_parsed_files.value} "
with self._stats_tree_parsed_dirs.get_lock():
stats += f"Dv: {self._stats_tree_parsed_dirs.value} "
with self._stats_tree_parsed_symlinks.get_lock():
stats += f"Sv: {self._stats_tree_parsed_symlinks.value} "
with self._stats_tree_parsed_unknown.get_lock():
stats += f"Uv: {self._stats_tree_parsed_unknown.value} "
with self._stats_checksums_calculate_ok_value.get_lock():
stats += f"C: {self._stats_checksums_calculate_ok_value.value}, "
with self._stats_checksums_calculate_error_value.get_lock():
stats += f"{self._stats_checksums_calculate_error_value.value} "
# Backup-only stats
if self.mode_current == MODE_BACKUP:
with self._stats_copied_ok_value.get_lock():
stats += f"cp: {self._stats_copied_ok_value.value}, "
with self._stats_copied_error_value.get_lock():
stats += f"{self._stats_copied_error_value.value} "
with self._stats_deleted_ok_value.get_lock():
stats += f"del: {self._stats_deleted_ok_value.value}, "
with self._stats_deleted_error_value.get_lock():
stats += f"{self._stats_deleted_error_value.value} "
with self._stats_created_dirs_ok_value.get_lock():
stats += f"Dcr: {self._stats_created_dirs_ok_value.value}, "
with self._stats_created_dirs_error_value.get_lock():
stats += f"{self._stats_created_dirs_error_value.value} "
with self._stats_created_symlinks_value.get_lock():
stats += f"Scr: {self._stats_created_symlinks_value.value} "
# Validation-only stats
elif self.mode_current == MODE_VALIDATION:
with self._stats_validate_match.get_lock():
stats += f"Cvld: {self._stats_validate_match.value}, "
with self._stats_validate_not_match.get_lock():
stats += f"{self._stats_validate_not_match.value}, "
with self._stats_validate_not_exist.get_lock():
stats += f"{self._stats_validate_not_exist.value}"
return stats
def get_max_cpu_numbers(self) -> int:
"""Converts workload_profile to maximum number of allowed cpu cores
Returns:
int: allowed CPU processes
"""
# Get workload profile
workload_profile = self._config_manager.get_config("workload_profile").lower()
# Get number of cpu cores
cpu_cores = multiprocessing.cpu_count()
# Very low -> only 1 CPU core
if workload_profile == "very low":
return 1
# Low -> 25% of CPU
if workload_profile == "low":
return int(cpu_cores * 0.25)
# High -> 75% of CPU
if workload_profile == "high":
return int(cpu_cores * 0.75)
# Insane -> full CPU
if workload_profile == "insane":
return cpu_cores
# Normal -> 50% of CPU
else:
return cpu_cores // 2
def parse_input_entries(self) -> Dict:
"""Checks and parses input entries from config
Raises:
Exception: duplicated path / doesn't exists
Returns:
Dict: {"path": skip} ex. {"path_1": True, "path_2": False, ...}
"""
input_paths = self._config_manager.get_config("input_paths")
input_entries = {}
for input_entry in input_paths:
if "path" in input_entry and "skip" in input_entry:
# Extract path
input_path = input_entry["path"].strip()
# Check it's length
if not input_path or len(input_path) == 0:
logging.warning(f"Empty path: {input_path}")
continue
# Try to normalize it
try:
input_path = os.path.normpath(input_path)
except:
input_path = None
if not input_path:
logging.warning(f"Wrong path: {input_path}")
continue
# Extract current skip flag
skip_current = input_entry["skip"]
# Convert to relative path (as it will be in backup dir)
input_path_rel = os.path.relpath(input_path, os.path.dirname(input_path))
# Prevent non-skipped duplicates
for existing_path, existing_path_skip in input_entries.items():
# Convert to relative path
existing_path_rel = os.path.relpath(existing_path, os.path.dirname(existing_path))
# Check if it's the same path
if os.path.normpath(existing_path_rel) == os.path.normpath(input_path_rel):
# If existing one was not skipped and new one also now -> raise an error
if not existing_path_skip and not skip_current:
raise Exception(f"Duplicated path: {input_path}")
# Check if it exists
if not skip_current and not os.path.exists(input_path):
raise Exception(f"Path {input_path} doesn't exists and not skipped")
# Add it to the dict
input_entries[input_path] = input_entry["skip"]
logging.info(f"{len(input_entries)} entries parsed")
return input_entries
def _show_stats(self, stage_step: int, stage_steps: int, inverted: bool = False) -> None:
"""Sets progress bar value, statusbar text and time information
Args:
stage_step (int): current step inside stage (starting from 0 or 1)
stage_steps (int): total number of steps inside stage
inverted (bool, optional): are steps progress inside stage inverted? Defaults to False.
"""
# Update progress bar
progress_total = 0.0
steps_progress = 0.0
if self._progress_set_value_signal is not None and self._stages_total > 0 and stage_steps != 0:
# Calculate stage's step progress
if inverted:
steps_progress = (stage_steps - stage_step) / stage_steps
else:
steps_progress = stage_step / stage_steps
steps_progress = max(min(steps_progress, 1.0), 0.0)
# Calculate stage progress
stage_progress_prev = (self._stage_current - 1) / self._stages_total
stage_progress = self._stage_current / self._stages_total
# Calculate total progress
progress_total = steps_progress * (stage_progress - stage_progress_prev) + stage_progress_prev
# Set value
self._progress_set_value_signal.emit(int(progress_total * 100.0))
# Update statusbar
if self._statusbar_show_message_signal is not None:
self._statusbar_show_message_signal.emit(self.stats_to_statusbar())
# Update time
if self._time_passed_signal is not None and self._time_left_signal is not None:
# Calculate passed time
time_passed = time.time() - self._time_started
# Check it to be > 0 and less then 24h
if time_passed <= 0.0 or time_passed >= 86399.0:
return
# Set time passed
self._time_passed_str = str(datetime.strptime(str(timedelta(seconds=int(time_passed))), "%H:%M:%S").time())
self._time_passed_signal.emit(self._time_passed_str)
# No more time left
if int(progress_total * 100.0) == 100:
self._time_left_signal.emit("00:00:00 | 00:00:00")
return
# Calculate current step
time_delta = time_passed - self._time_passed_prev
# Check it (just in case)
if time_delta <= 0.0:
return
# Calculate deltas
progress_stage_delta = steps_progress - self._progress_steps_prev
progress_total_delta = progress_total - self._progress_total_prev
# Save data for next cycle
self._progress_steps_prev = steps_progress
self._progress_total_prev = progress_total
self._time_passed_prev = time_passed
# Check them
if progress_stage_delta <= 0.0 or progress_total_delta <= 0.0:
return
# Calculate stage time left
time_left_stage = time_delta / progress_stage_delta
# Calculate total time left
time_left_total = time_delta / progress_total_delta
# Filter them
if self._time_left_total_filtered < 1.0:
self._time_left_total_filtered = time_left_total
else:
self._time_left_total_filtered *= TIME_LEFT_FILTER
self._time_left_total_filtered += time_left_total * (1.0 - TIME_LEFT_FILTER)
if self._time_left_stage_filtered < 1.0:
self._time_left_stage_filtered = time_left_stage
else:
self._time_left_stage_filtered *= TIME_LEFT_FILTER
self._time_left_stage_filtered += time_left_stage * (1.0 - TIME_LEFT_FILTER)
# Convert to seconds
seconds_left_total = int(self._time_left_total_filtered)
seconds_left_stage = int(self._time_left_stage_filtered)
# Check it
if (
seconds_left_total < 0
or seconds_left_total >= 86400
or seconds_left_stage < 0
or seconds_left_stage >= 86400
):
self._time_left_signal.emit("--:--:-- | --:--:--")
return
# Set time left
time_left_stage_str = str(datetime.strptime(str(timedelta(seconds=seconds_left_stage)), "%H:%M:%S").time())
time_left_total_str = str(datetime.strptime(str(timedelta(seconds=seconds_left_total)), "%H:%M:%S").time())
self._time_left_signal.emit(f"{time_left_stage_str} | {time_left_total_str}")
def _time_clear_start(self) -> None:
"""Resets and initializes time-related variables
(must be called before backup / validation)
"""
self._time_started = time.time()
self._time_passed_prev = 0.0
self._progress_total_prev = 0.0
self._progress_steps_prev = 0.0
self._time_left_stage_filtered = 0.0
self._time_left_total_filtered = 0.0
self._time_passed_str = "--:--:--"
if self._time_passed_signal is not None:
self._time_passed_signal.emit(self._time_passed_str)
if self._time_left_signal is not None:
self._time_left_signal.emit("--:--:-- | --:--:--")
def _exit(self, exit_status_: int) -> None:
"""Emits signals and resets requests
Args:
exit_status_ (int): exit code
"""
if self._finished_signal is not None:
self._finished_signal.emit(exit_status_)
if self._progress_set_value_signal is not None:
self._progress_set_value_signal.emit(100)
self.request_pause = False
self.request_resume = False
self.request_cancel = False
self.paused = False
self.mode_current = MODE_IDLE
if self._time_left_signal is not None:
self._time_left_signal.emit("00:00:00 | 00:00:00")
def _pause(self) -> bool:
"""Waits until self.request_resume or self.request_cancel
Returns:
bool: True if resumed, False if cancel requested during pause
"""
# Set flags, log and emit signal
self.request_pause = False
self.paused = True
logging.info("Backup paused. Waiting for resume or cancel request")
if self._backup_paused_resumed_signal is not None:
self._backup_paused_resumed_signal.emit(True)
# Wait until any flag
while not self.request_resume and not self.request_cancel:
time.sleep(0.01)
# Cancel requested
if self.request_cancel:
logging.info("Cancel requested during pause")
return False
# Resume requested
else:
self.request_resume = False
self.paused = False
self._time_left_stage_filtered = 0.0
self._time_left_total_filtered = 0.0
logging.info("Backup resumed")
if self._backup_paused_resumed_signal is not None:
self._backup_paused_resumed_signal.emit(False)
return True
def _process_controller(
self,
processes: List,
control_value: multiprocessing.Value,
filler_exit_flag: Dict or None = None,
process_output_queue: multiprocessing.Queue or None = None,
) -> int:
"""Checks self.request_cancel and self.request_pause and calls _cancel and _pause and kills all processes
Args:
processes (List): list of processes
control_value (multiprocessing.Value): Value to communicate with processes
filler_exit_flag (Dict or None, optional): dict to communicate with filler thread
process_output_queue (multiprocessing.Queue or None, optional): output from processes to clean it on exit
Returns:
int: >= 0 in case of exit or error
"""
def _process_killer(
processes_: List,
control_value_: multiprocessing.Value,
process_output_queue_: multiprocessing.Queue or None,
) -> None:
"""Kills active processes and cleans queue if needed
TODO: This DEFINITELY needs refactoring!
Args:
processes_ (List): list of processes
control_value_ (multiprocessing.Value): Value to communicate with processes
process_output_queue_ (multiprocessing.Queue or None, optional): output from processes
"""
def __queue_cleaner(process_output_queue__: multiprocessing.Queue or None) -> None:
"""Clears queue
Args:
process_output_queue__ (multiprocessing.Queue or None): output from processes
"""
if process_output_queue__ is not None:
while True:
try:
process_output_queue__.get_nowait()
except queue.Empty:
break
# Request exit from all processes
with control_value_.get_lock():
logging.info("Requesting processes exit")
control_value_.value = PROCESS_CONTROL_EXIT
# Clear queue and give them some time
sleep_timer_ = time.time()
while time.time() - sleep_timer_ < 1:
__queue_cleaner(process_output_queue_)
time.sleep(0.1)
# Check and kill them until they finished
while True:
killed_all_ = True
for process_ in processes_:
# Kill if still alive
if process_ is not None and process_.is_alive():
killed_all_ = False
try:
logging.info(f"Killing {process_.pid}")
process_.kill()
time.sleep(0.1)
except Exception as e:
logging.warning(f"Error killing process with PID {process_.pid}: {str(e)}")
# Exit when no alive process remained
if killed_all_:
break
# Clear queue and give them some time
sleep_timer_ = time.time()
while time.time() - sleep_timer_ < 1:
__queue_cleaner(process_output_queue_)
time.sleep(0.1)
# Done killing
logging.info("All process finished!")
# Check cancel flag
if self.request_cancel:
logging.warning("Received cancel request!")
# Request filler exit
if filler_exit_flag is not None:
filler_exit_flag["exit"] = True
# Kill all processes and exit
_process_killer(processes, control_value, process_output_queue)
self._exit(EXIT_CODE_CANCELED)
return EXIT_CODE_CANCELED
# Check pause flag
if self.request_pause:
logging.warning("Received pause request!")
# Request pause
with control_value.get_lock():
control_value.value = PROCESS_CONTROL_PAUSE
# Cancel during pause
if not self._pause():
# Request filler exit
if filler_exit_flag is not None:
filler_exit_flag["exit"] = True
# Kill all processes and exit
_process_killer(processes, control_value, process_output_queue)
self._exit(EXIT_CODE_CANCELED)
return EXIT_CODE_CANCELED
# Resume processes
with control_value.get_lock():
control_value.value = PROCESS_CONTROL_WORK
# No exit requested
return -1
def _generate_tree(
self,
entries: Dict,
follow_symlinks: bool = False,
root_relative_to_dirname: bool = False,
) -> Tuple[Dict, List[str]] or int:
"""Parses entries and generates dict of files, dirs and symlinks with the following structure:
({
"files": {
"file_1_relative_to_root_path": {
"root": "file_1_root_directory"
},
"file_2_relative_to_root_path": {
"root": "file_2_root_directory"
}
},
"dirs": {
"dir_1_relative_to_root_path": {
"root": "dir_1_root_directory"
"empty": False,
"mode": 0o755
},
"dir_2_relative_to_root_path": {
"root": "dir_2_root_directory"
"empty": True
"mode": 0o777
}
},
"symlinks": {
"file_1_symlink": {
"root": "symlink_1_root_directory"
}
}
"unknown": {
"this_path_is_wrong_or_does_not_exists": {
"root": "path_1_root_directory"
}
}
}, ["skipped_abs_path_1", "skipped_abs_path_2"])
Args:
entries (Dict): {"path": skip} ex. {"path_1": True, "path_2": False, ...}
follow_symlinks (bool): True to follow symlinks instead of adding them to the "symlinks" tree
root_relative_to_dirname (bool): True to calculate path relative to dirname(root_dir) instead of root_dir
Returns:
Tuple[Dict, List[str]] or int: parsed tree and skipped entries or exit status in case of cancel
"""
logging.info(f"Generating tree for {len(entries)} entries")
# Create recursion queue (and add each root dir after that)
directories_to_parse_queue = multiprocessing.Queue(-1)
# Create output queue (and add each file, dir and unknown path after that)
parsed_queue = multiprocessing.Queue(-1)
# Skipped entries as list of absolute paths
skipped_entries_abs = []
# Add each entry
for path_abs, skip in entries.items():
# Skipped entry
if skip:
skipped_entries_abs.append(path_abs)
continue
# Extract root directory
root_dir = os.path.dirname(path_abs) if root_relative_to_dirname else path_abs
# Get path type
path_type = PATH_UNKNOWN
if os.path.islink(path_abs) and not follow_symlinks:
path_type = PATH_SYMLINK
elif os.path.isfile(path_abs):
path_type = PATH_FILE
elif os.path.isdir(path_abs):
path_type = PATH_DIR
# Try to get permission mask
st_mode = 0
if path_type == PATH_DIR:
try:
st_mode = os.stat(path_abs).st_mode & 0o777
except:
pass
# Add to the output queue if not self
# (relative path, root dir path, PATH_..., is empty directory, permission mask)
if root_relative_to_dirname:
parsed_queue.put((os.path.relpath(path_abs, root_dir), root_dir, path_type, False, st_mode))
# Parse tree if it's a directory
if path_type == PATH_DIR:
# Extract parent directory
parent_dir = os.path.relpath(path_abs, root_dir) if root_relative_to_dirname else ""
# Add to the recursion queue (parent dir, abs root path)
if not skip:
directories_to_parse_queue.put((parent_dir, root_dir))
# Create control Value for pause and cancel
control_value = multiprocessing.Value("i", PROCESS_CONTROL_WORK)
# Output data
tree = {"files": {}, "dirs": {}, "symlinks": {}, "unknown": {}}
# Start processes
processes_num = self.get_max_cpu_numbers()
processes = []
for i in range(processes_num):
process = multiprocessing.Process(
target=tree_parser,
args=(
directories_to_parse_queue,
parsed_queue,
skipped_entries_abs,
follow_symlinks,
self._stats_tree_parsed_dirs,
self._stats_tree_parsed_files,
self._stats_tree_parsed_symlinks,
self._stats_tree_parsed_unknown,
control_value,
self._logging_queue,
),
)
logging.info(f"Starting process {i + 1} / {processes_num}")
process.start()
processes.append(process)
# Loop until they all finished
while True:
# Check processes
finished = True
for process in processes:
if process.is_alive():
finished = False
break
# Retrieve data from parsed_queue
while not parsed_queue.empty():
try:
# Get data
path_rel, root_dir, path_type, is_empty, st_mode = parsed_queue.get(block=True, timeout=0.1)
# Convert to absolute path
path_abs = os.path.join(root_dir, path_rel)
# Put into tree
if path_type is PATH_FILE:
tree["files"][path_rel] = {"root": root_dir}
elif path_type is PATH_DIR:
tree["dirs"][path_rel] = {"root": root_dir, "empty": is_empty, "mode": st_mode}
elif path_type is PATH_SYMLINK:
tree["symlinks"][path_rel] = {"root": root_dir}
else:
tree["unknown"][path_rel] = {"root": root_dir}
except queue.Empty:
break
# Handle pause and cancel requests even inside this loop
exit_code = self._process_controller(processes, control_value, process_output_queue=parsed_queue)
if exit_code >= 0:
return exit_code
# Done!
if finished:
logging.info("Tree generation finished!")
break
# Update statusbar
if self._statusbar_show_message_signal is not None:
self._statusbar_show_message_signal.emit(self.stats_to_statusbar())
# Handle pause and cancel requests
exit_code = self._process_controller(processes, control_value, process_output_queue=parsed_queue)
if exit_code >= 0:
return exit_code
# Prevent overloading
time.sleep(0.1)
# Return generated tree
return tree, skipped_entries_abs
def _calculate_checksum(
self,
checksum_out_file: str or None,
exclude_checksums: Dict or None,
checksum_alg: str,
files_tree: Dict,
output_as_absolute_paths: bool,
) -> Dict or int:
"""Calculates checksum of local_files_queue using multiprocessing
Args:
checksum_out_file (str or None): file to append (a+) checksums or None to don't write to it
exclude_checksums (Dist): exclude from calculating checksum:
{
"file_1_to_exclude_relative_to_root_path": {
"root": "file_1_root_directory",
"checksum": "file_1_checksum"
},
...
}
checksum_alg (str): MD5 / SHA256 / SHA512
files_tree (Dict): dict of "files" of tree to calculate checksum of:
{
"file_1_relative_to_root_path": {
"root": "file_1_root_directory"
},
"file_2_relative_to_root_path": {
"root": "file_2_root_directory"
}
}
output_as_absolute_paths (bool): True to write filepaths as absolute paths instead of relative to root dir,
only matters if checksum_out_file is specified
Returns:
Dict or int: checksums as dictionary or exit status in case of cancel
Output dict will have this format:
{
"file_1_relative_to_root_path": {
"root": "file_1_root_directory",
"checksum": "file_1_checksum"
},
"file_2_relative_to_root_path": {
"root": "file_2_root_directory",
"checksum": "file_2_checksum"
}
}
"""
def _files_tree_queue_filler(
files_tree_: Dict,
filepaths_queue_: multiprocessing.Queue,
exclude_checksums_: Dict or None,
exit_flag_: Dict,
) -> None:
"""Thread body that dynamically puts files from files_tree_ into filepaths_queue_
Args:
files_tree_ (Dict): dict of "files" of tree to calculate checksum
filepaths_queue_ (multiprocessing.Queue): queue of file paths as tuples (root dir, local path)
exclude_checksums (Dist): exclude from calculating checksum
exit_flag_ (Dict): {"exit": False}
"""
logging.info("Filler thread started")
update_progress_timer_ = time.time()
progress_counter = 0
skipped_counter = 0
size_total_ = len(files_tree_)
for path_relative_, root_ in files_tree_.items():
# Check if we need to exit
if exit_flag_["exit"]:
break
# Extract root dir
root_ = root_["root"]
# Check if we need to exclude it
if exclude_checksums_ is not None and path_relative_ in exclude_checksums_:
skipped_counter += 1
continue
# Put in the queue as (relative path, root dir)
filepaths_queue_.put((path_relative_, root_), block=True)
# Increment items counter
progress_counter += 1
# Update progress every 100ms
if time.time() - update_progress_timer_ >= 0.1:
self._show_stats(progress_counter, size_total_)
# Done
logging.info(f"Filler thread finished. Skipped {skipped_counter} checksums")
# Create control Value for pause and cancel
control_value = multiprocessing.Value("i", PROCESS_CONTROL_WORK)
# Create Lock to prevent writing to the file at the same time
if checksum_out_file is not None:
checksum_out_file_lock = multiprocessing.Manager().Lock()
else:
checksum_out_file_lock = None
# Create queue if we need to return checksums as dictionary instead of writing them to the file
if checksum_out_file is None:
checksum_out_queue = multiprocessing.Queue(-1)
else:
checksum_out_queue = None
# Calculate started size (for processes_num)
size_started = len(files_tree)
skip_str = (
" and skipping some of them" if (exclude_checksums is not None and len(exclude_checksums) != 0) else ""
)
logging.info(f"Calculating checksums for {size_started} files{skip_str}")
# Calculate number of processes
processes_num = min(size_started, self.get_max_cpu_numbers())
# Calculate filepaths_queue size as 10 files per process (seems enough for me ¯\_(ツ)_/¯)
filepaths_queue_size = processes_num * 10
# Generate input queue
filepaths_queue = multiprocessing.Queue(filepaths_queue_size)
# Start filler as thread
filler_exit_flag = {"exit": False}
logging.info("Starting filler thread")
threading.Thread(
target=_files_tree_queue_filler,
args=(
files_tree,
filepaths_queue,
exclude_checksums,
filler_exit_flag,
),
).start()
# Dictionary to store calculated checksums
checksums = {}
# Start processes
processes = []
for i in range(processes_num):
process = multiprocessing.Process(
target=calculate_checksums,
args=(
checksum_out_file,
checksum_out_queue,
checksum_alg,
filepaths_queue,
output_as_absolute_paths,
self._stats_checksums_calculate_ok_value,
self._stats_checksums_calculate_error_value,
control_value,
checksum_out_file_lock,
self._logging_queue,
),
)
logging.info(f"Starting process {i + 1} / {processes_num}")
process.start()
processes.append(process)
# Loop until they all finished
while True:
# Check processes
finished = True
for process in processes:
if process.is_alive():
finished = False
break
# Retrieve data from queue
if checksum_out_queue is not None:
while not checksum_out_queue.empty():
try:
filepath_rel, filepath_root_dir, checksum = checksum_out_queue.get(block=True, timeout=0.1)
checksums[filepath_rel] = {"root": filepath_root_dir, "checksum": checksum}
except queue.Empty:
break
# Handle pause and cancel requests even inside this loop
exit_code = self._process_controller(
processes, control_value, filler_exit_flag, checksum_out_queue
)
if exit_code >= 0:
return exit_code
# Done!
if finished:
filler_exit_flag["exit"] = True
logging.info("Checksum calculating finished!")
break
# Handle pause and cancel requests
exit_code = self._process_controller(processes, control_value, filler_exit_flag, checksum_out_queue)
if exit_code >= 0:
return exit_code
# Prevent overloading