-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1960 lines (1770 loc) · 79.1 KB
/
app.py
File metadata and controls
1960 lines (1770 loc) · 79.1 KB
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
# sudo apt install python3-flask python3-psutil python3-xgboost python3-joblib python3-pandas smartmontools python3-sklearn python3-flask-socketio
from flask import Flask, render_template, jsonify, request, abort, url_for, redirect, send_file, session, flash, current_app, make_response, send_from_directory
import subprocess
import psutil
from datetime import datetime, timedelta
import json
import os
import csv
import queue
import threading
from config_manager import ConfigManager
from setup_wizard import setup, install_systemd_tasks
import logging
from user_manager import UserManager, login_required, admin_required
from flask_socketio import SocketIO
from logging.handlers import RotatingFileHandler
import sys
import time
from system_utils import SystemUtils
from smb_manager import SMBManager
from tempfile import NamedTemporaryFile
from runtime import get_runtime, get_fake_state
try:
import pandas as pd
from xgboost import XGBClassifier
import joblib
except (ImportError, OSError):
pd = None
XGBClassifier = None
joblib = None
app = Flask(__name__)
app.secret_key = os.urandom(24) # Required for session management
socketio = SocketIO(app)
runtime = get_runtime()
fake_state = get_fake_state() if runtime.is_fake else None
user_manager = UserManager(runtime=runtime)
system_utils = SystemUtils(runtime=runtime)
smb_manager = SMBManager(runtime=runtime)
# Configure logging
log_dir = str(runtime.logs_dir)
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, 'app.log')
handler = RotatingFileHandler(log_file, maxBytes=10000000, backupCount=5)
handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
))
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
app.logger.setLevel(logging.INFO)
app.logger.info('SimpleSaferServer startup')
# Initialize configuration
config_manager = ConfigManager(runtime=runtime)
# Register setup blueprint
app.register_blueprint(setup)
# Paths for the XGBoost model and threshold
MODEL_PATH = str(runtime.model_dir / "xgb_model.json")
THRESHOLD_PATH = str(runtime.model_dir / "optimal_threshold_xgb.pkl")
# Load model and threshold once on startup
model = None
optimal_threshold = 0.5
if XGBClassifier is not None and joblib is not None:
model = XGBClassifier()
try:
model.load_model(MODEL_PATH)
optimal_threshold = joblib.load(THRESHOLD_PATH)
except Exception as exc:
print(f"Failed to load model: {exc}")
model = None
optimal_threshold = 0.5
def read_msmtp_config():
"""Read the current msmtp config and return the parsed values that this app manages."""
msmtp_config = {}
try:
with open(runtime.msmtp_config_path, 'r') as f:
content = f.read()
except FileNotFoundError:
return msmtp_config
for line in content.split('\n'):
line = line.strip()
if line.startswith('host '):
msmtp_config['smtp_server'] = line.split(' ', 1)[1]
elif line.startswith('port '):
msmtp_config['smtp_port'] = line.split(' ', 1)[1]
elif line.startswith('from '):
msmtp_config['from_address'] = line.split(' ', 1)[1]
elif line.startswith('user '):
msmtp_config['smtp_username'] = line.split(' ', 1)[1]
elif line.startswith('password '):
msmtp_config['smtp_password'] = line.split(' ', 1)[1]
return msmtp_config
def predict_failure_probability(smart):
if model is not None and pd is not None:
df = pd.DataFrame([smart])
probabilities = model.predict_proba(df)
return float(probabilities[0, 1])
if runtime.is_fake:
temperature = float(smart.get('smart_194_raw', 30.0) or 30.0)
reallocated = float(smart.get('smart_5_raw', 0.0) or 0.0)
pending = float(smart.get('smart_197_raw', 0.0) or 0.0)
probability = 0.03 + min(0.25, reallocated * 0.02) + min(0.25, pending * 0.05)
if temperature > 40:
probability += min(0.15, (temperature - 40) * 0.01)
return min(0.95, probability)
return None
# SMART attributes used for telemetry/model with their default values and descriptions
SMART_FIELDS = {
"smart_1_raw": {
"default": 0.0,
"name": "Read Error Rate",
"description": "The rate of hardware read errors that occurred when reading data from the disk surface. A non-zero value may indicate problems with the disk surface or read/write heads.",
"short_desc": "Rate of hardware read errors"
},
"smart_3_raw": {
"default": 0.0,
"name": "Spin-Up Time",
"description": "Average time (in milliseconds) for the disk to spin up from a stopped state to full speed. Higher values may indicate mechanical problems.",
"short_desc": "Time to reach full speed"
},
"smart_4_raw": {
"default": 0.0,
"name": "Start/Stop Count",
"description": "The number of times the disk has been powered on and off. This is a lifetime counter that increases with each power cycle.",
"short_desc": "Number of power cycles"
},
"smart_5_raw": {
"default": 0.0,
"name": "Reallocated Sectors Count",
"description": "The number of bad sectors that have been found and remapped. A non-zero value indicates the disk has had some problems, and the value should not increase over time.",
"short_desc": "Number of remapped sectors"
},
"smart_7_raw": {
"default": 0.0,
"name": "Seek Error Rate",
"description": "The rate of seek errors that occur when the drive's heads try to position themselves over a track. Higher values may indicate mechanical problems.",
"short_desc": "Rate of positioning errors"
},
"smart_10_raw": {
"default": 0.0,
"name": "Spin Retry Count",
"description": "The number of times the drive had to retry spinning up. A non-zero value indicates problems with the drive's motor or power supply.",
"short_desc": "Number of spin-up retries"
},
"smart_192_raw": {
"default": 0.0,
"name": "Emergency Retract Count",
"description": "The number of times the drive's heads were retracted due to power loss or other emergency conditions. High values may indicate power problems.",
"short_desc": "Number of emergency head retractions"
},
"smart_193_raw": {
"default": 0.0,
"name": "Load Cycle Count",
"description": "The number of times the drive's heads have been loaded and unloaded. This is a lifetime counter that increases with each load/unload cycle.",
"short_desc": "Number of head load/unload cycles"
},
"smart_194_raw": {
"default": 25.0,
"name": "Temperature",
"description": "The current temperature of the drive in Celsius. Normal operating temperature is typically between 30-50°C. Higher temperatures may indicate cooling problems.",
"short_desc": "Current drive temperature"
},
"smart_197_raw": {
"default": 0.0,
"name": "Current Pending Sectors",
"description": "The number of sectors that are waiting to be remapped. A non-zero value indicates the drive has found bad sectors that it hasn't been able to remap yet.",
"short_desc": "Number of sectors waiting to be remapped"
},
"smart_198_raw": {
"default": 0.0,
"name": "Offline Uncorrectable",
"description": "The number of sectors that could not be corrected during offline testing. A non-zero value indicates the drive has sectors that are permanently damaged.",
"short_desc": "Number of uncorrectable sectors"
}
}
def get_fake_smart_attributes():
attrs = {field: info["default"] for field, info in SMART_FIELDS.items()}
attrs.update({
"smart_1_raw": 0.0,
"smart_3_raw": 1420.0,
"smart_4_raw": 321.0,
"smart_5_raw": 0.0,
"smart_7_raw": 0.0,
"smart_10_raw": 0.0,
"smart_192_raw": 2.0,
"smart_193_raw": 145.0,
"smart_194_raw": 31.0,
"smart_197_raw": 0.0,
"smart_198_raw": 0.0,
})
return attrs, []
def get_smart_attributes(device=None):
"""Return SMART attributes as a dictionary using smartctl JSON output."""
if runtime.is_fake:
return get_fake_smart_attributes()
try:
# If device is not specified, get UUID from config and resolve to device
if device is None:
uuid = config_manager.get_value('backup', 'uuid', None)
if not uuid:
print("No UUID found in config for backup partition.")
return None, None
# Find the partition device with this UUID
blkid_out = subprocess.run(['blkid', '-t', f'UUID={uuid}', '-o', 'device'], capture_output=True, text=True)
partition_device = blkid_out.stdout.strip()
if not partition_device:
print(f"No partition found with UUID {uuid}")
return None, None
# Get the parent drive (e.g. /dev/sda)
device = system_utils.get_parent_device(partition_device)
if not device:
print(f"Could not determine parent device for partition {partition_device}")
return None, None
result = subprocess.run(
["sudo", "smartctl", "-A", "-j", device], capture_output=True, text=True, check=True
)
data = json.loads(result.stdout)
# Initialize dictionary with default values for all required SMART fields
attrs = {field: info["default"] for field, info in SMART_FIELDS.items()}
missing_attrs = set(SMART_FIELDS.keys())
# Update with actual values from smartctl output
for item in data.get("ata_smart_attributes", {}).get("table", []):
field_name = f"smart_{item['id']}_raw"
if field_name in SMART_FIELDS:
try:
# Temperature is a special case, it is a 16 bit value, but we only want the lowest byte
# Extract the lowest byte for smart_194_raw (Temperature)
if field_name == "smart_194_raw":
attrs[field_name] = float(int(item["raw"]["value"]) & 0xFF)
else:
attrs[field_name] = float(item["raw"]["value"])
missing_attrs.remove(field_name)
except (ValueError, KeyError, TypeError):
print(f"Warning: Could not parse value for {field_name}")
continue
return attrs, list(missing_attrs)
except subprocess.CalledProcessError as e:
print(f"Failed to execute smartctl: {e}")
return None, None
except json.JSONDecodeError as e:
print(f"Failed to parse smartctl JSON output: {e}")
return None, None
except Exception as e:
print(f"Unexpected error reading SMART data: {e}")
return None, None
def append_telemetry(data_dict, prediction):
"""Append SMART data and prediction to telemetry.csv."""
if not data_dict:
return
telemetry_path = runtime.telemetry_path
telemetry_path.parent.mkdir(parents=True, exist_ok=True)
file_exists = telemetry_path.exists()
with open(telemetry_path, "a", newline="") as csvfile:
writer = csv.writer(csvfile)
if not file_exists:
writer.writerow(list(SMART_FIELDS.keys()) + ["failure"])
row = [data_dict.get(field, "") for field in SMART_FIELDS.keys()]
row.append(prediction)
writer.writerow(row)
# a service can either be running right now, or could have succeeded or failed last time it ran
class Status:
RUNNING = "Running"
SUCCESS = "Success"
FAILURE = "Failure"
MISSING = "Missing"
NOT_RUN_YET = "Not Run Yet"
ERROR = "Error"
STOPPED = "Stopped"
# use actual dates for next run and last run
class Task:
def __init__(self, name, service_name, timer_name):
self.name = name
self.service_name = service_name
self.timer_name = timer_name
def get_logs(self, lines: int = 50) -> str:
"""Return the latest systemd journal logs for this service."""
if runtime.is_fake:
return fake_state.get_task_log(self.name)
try:
result = subprocess.run(
[
"journalctl",
"-u",
self.service_name,
"-n",
str(lines),
"--no-pager",
],
capture_output=True,
text=True,
check=True,
)
return result.stdout
except subprocess.CalledProcessError:
return "Retrieval Error"
def start(self):
"""Start the associated service asynchronously."""
if runtime.is_fake:
start_fake_task(self.name)
return
try:
subprocess.Popen(
["systemctl", "start", self.service_name, "--no-block"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except Exception as exc:
raise RuntimeError(f"Failed to start {self.service_name}: {exc}")
def stop(self):
"""Stop the associated service asynchronously."""
if runtime.is_fake:
with fake_task_lock:
thread = fake_task_threads.get(self.name)
cancel_event = fake_task_cancel_events.get(self.name)
is_running = bool(thread and thread.is_alive() and cancel_event)
if is_running:
cancel_event.set()
if is_running:
fake_state.append_task_log(self.name, f"Stopped {self.name} in fake mode.")
else:
fake_state.append_task_log(self.name, f"Stop requested for {self.name}, but it was not running.")
# Keep stop idempotent in fake mode so the UI does not fail on repeated clicks.
fake_state.set_task_state(self.name, status=Status.STOPPED)
return
try:
subprocess.Popen(
["systemctl", "stop", self.service_name, "--no-block"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except Exception as exc:
raise RuntimeError(f"Failed to stop {self.service_name}: {exc}")
@property
def next_run(self):
"""
Returns the next run time of the systemd timer by executing
a system command.
"""
if runtime.is_fake:
return fake_state.get_next_run(self.name, config_manager.get_value('schedule', 'backup_cloud_time', '03:00'))
try:
# Example: using 'systemctl list-timers' or 'systemctl show'
result = subprocess.run(
["systemctl", "show", self.timer_name, "--property=NextElapseUSecRealtime"],
capture_output=True,
text=True,
check=True
)
# Parse the output (this will depend on your exact command and output format)
output = result.stdout.strip()
print(f"Next run output: {output}") # Debugging line
if "=" in output:
return output.split("=")[-1].strip()
return "Unknown"
except subprocess.CalledProcessError as e:
# Handle error gracefully
return f"Retrieval Error"
@property
def last_run(self):
"""
Returns the last run time of the systemd service.
"""
if runtime.is_fake:
task_state = fake_state.get_task_state(self.name)
return task_state.get("last_run") or "Not Run Yet"
try:
result = subprocess.run(
["systemctl", "show", self.service_name, "--property=ExecMainStartTimestamp"],
capture_output=True,
text=True,
check=True
)
output = result.stdout.strip()
if "=" in output:
return output.split("=")[-1].strip()
return "Unknown"
except subprocess.CalledProcessError as e:
return f"Retrieval Error"
@property
def last_run_duration(self):
"""Return the duration of the last run in a human friendly format."""
if runtime.is_fake:
task_state = fake_state.get_task_state(self.name)
return task_state.get("last_run_duration", "-")
try:
result = subprocess.run(
[
"systemctl",
"show",
self.service_name,
"--property=ExecMainStartTimestampMonotonic",
"--property=ExecMainExitTimestampMonotonic",
],
capture_output=True,
text=True,
check=True,
)
start = exit_ts = None
for line in result.stdout.splitlines():
if line.startswith("ExecMainStartTimestampMonotonic="):
value = line.split("=", 1)[1].strip()
if value:
start = int(value)
elif line.startswith("ExecMainExitTimestampMonotonic="):
value = line.split("=", 1)[1].strip()
if value:
exit_ts = int(value)
if start is not None and exit_ts is not None and exit_ts >= start:
delta = timedelta(microseconds=exit_ts - start)
total_seconds = int(delta.total_seconds())
months, days = divmod(delta.days, 30)
hours, rem = divmod(total_seconds % 86400, 3600)
minutes, seconds = divmod(rem, 60)
parts = []
if months:
parts.append(f"{months}mo")
if days:
parts.append(f"{days}d")
if hours:
parts.append(f"{hours}h")
if minutes:
parts.append(f"{minutes}m")
parts.append(f"{seconds}s")
return " ".join(parts)
return "Unknown"
except subprocess.CalledProcessError:
return "Retrieval Error"
@property
def status(self):
"""
Returns the status of the service: Running, Success, or Failure.
"""
if runtime.is_fake:
task_state = fake_state.get_task_state(self.name)
return task_state.get("status", Status.NOT_RUN_YET)
try:
# Check if the service exists
result = subprocess.run(
["systemctl", "show", self.service_name, "--property=LoadState"],
capture_output=True,
text=True,
check=True
)
output = result.stdout.strip()
if "not-found" in output:
return Status.MISSING
# Check if the service is active
result = subprocess.run(
["systemctl", "is-active", self.service_name],
capture_output=True,
text=True,
check=False # Allow non-zero exit codes (inactive)
)
output = result.stdout.strip()
if output == "activating":
return Status.RUNNING
# If not running, check the last exit code/status
result = subprocess.run(
["systemctl", "show", self.service_name, "--property=Result"],
capture_output=True,
text=True,
check=True
)
result_output = result.stdout.strip()
if "=" in result_output:
result_value = result_output.split("=")[-1].strip()
if result_value == "success":
# Check if the service has not run yet
result = subprocess.run(
["systemctl", "show", self.service_name, "--property=ExecMainStartTimestamp"],
capture_output=True,
text=True,
check=True
)
output = result.stdout.strip()
if output.endswith('=') or output == '':
return Status.NOT_RUN_YET
else:
return Status.SUCCESS
else:
return Status.FAILURE
return Status.ERROR # Default to Error if parsing fails
except subprocess.CalledProcessError:
return Status.ERROR
@app.route('/')
def index():
"""Main entry point - redirects to appropriate page based on setup status"""
if not config_manager.is_setup_complete():
return redirect(url_for('setup.setup_page'))
return redirect(url_for('dashboard'))
@app.route('/login', methods=['GET', 'POST'])
def login():
"""Login page - only accessible after setup is complete"""
if not config_manager.is_setup_complete():
return redirect(url_for('setup.setup_page'))
if 'username' in session:
return redirect(url_for('dashboard'))
if request.method == 'POST':
# Reload user data to ensure we have the latest
user_manager.users = user_manager._load_users()
username = request.form['username']
password = request.form['password']
if user_manager.verify_user(username, password):
# Check if user is admin before allowing login
if user_manager.is_admin(username):
session['username'] = username
session.pop('skip_login_disabled', None)
if request.accept_mimetypes.best == 'application/json':
return jsonify({"success": True, "redirect": url_for('dashboard')})
return redirect(url_for('dashboard'))
else:
msg = 'This account does not have administrator privileges. Only administrators can access the SimpleSaferServer management interface. Please contact your system administrator for access or view the accompanying documentation for information on how to mount any network file shares that you have been given access to.'
if request.accept_mimetypes.best == 'application/json':
return jsonify({"success": False, "message": msg})
flash(msg, 'error')
return render_template('login.html')
else:
msg = 'Invalid username or password'
if request.accept_mimetypes.best == 'application/json':
return jsonify({"success": False, "message": msg})
flash(msg, 'error')
return render_template('login.html')
def get_auto_login_username():
configured_username = config_manager.get_value('system', 'username', '')
user_manager.users = user_manager._load_users()
return user_manager.get_preferred_admin_username(configured_username)
@app.before_request
def auto_login_fake_mode_user():
if not runtime.is_fake or not runtime.skip_login:
return None
if request.endpoint in {'static'}:
return None
if session.get('skip_login_disabled'):
return None
if 'username' in session:
return None
if not config_manager.is_setup_complete():
return None
username = get_auto_login_username()
if username and user_manager.is_admin(username):
session['username'] = username
session['auto_logged_in'] = True
return None
@app.route('/network_file_sharing')
@login_required
def network_file_sharing():
backup_mount_point = config_manager.get_value('backup', 'mount_point', runtime.default_mount_point)
return render_template('network_file_sharing.html', username=session.get('username'), backup_mount_point=backup_mount_point)
@app.route('/users')
@login_required
def users():
return render_template('users.html', username=session.get('username'))
@app.route('/logout')
def logout():
session.clear()
if runtime.is_fake and runtime.skip_login:
session['skip_login_disabled'] = True
return redirect(url_for('login'))
@app.route('/dashboard')
@login_required
def dashboard():
if not config_manager.is_setup_complete():
return redirect(url_for('setup.setup_page'))
# Get tasks from config
config = config_manager.get_all_config()
# Get task information
tasks = []
for task in TASKS:
try:
# Get next run time
next_run = task.next_run
# Get last run time
last_run = task.last_run
# Get status using Task.status property
status = task.status
# Get last run duration if implemented
last_run_duration = getattr(task, 'last_run_duration', 'N/A')
tasks.append({
'name': task.name,
'next_run': next_run,
'last_run': last_run,
'status': status,
'last_run_duration': last_run_duration
})
except Exception as e:
print(f"Error getting task info for {task.name}: {e}")
tasks.append({
'name': task.name,
'next_run': 'Error',
'last_run': 'Error',
'status': 'Error',
'last_run_duration': 'Error'
})
# Get system metrics
mount_point = config_manager.get_value('backup', 'mount_point', runtime.default_mount_point)
mounted = system_utils.is_mounted(mount_point)
try:
disk = psutil.disk_usage(mount_point)
except Exception:
disk = psutil.disk_usage(runtime.repo_root)
cpu_percent = psutil.cpu_percent()
ram_percent = psutil.virtual_memory().percent
return render_template('dashboard.html',
used_storage=f"{disk.used / (1024**3):.1f}",
total_storage=f"{disk.total / (1024**3):.1f}",
storage_usage=f"{disk.percent}%",
cloud_backup_status='Active' if config.get('cloud_backup_enabled') else 'Inactive',
health_status='Good',
hdd_temp='35', # Just the number, template will add °C
cpu_usage=f"{cpu_percent}%",
ram_usage=f"{ram_percent}%",
mount_info={'is_mounted': mounted, 'mount_point': mount_point},
tasks=tasks
)
@app.route("/task/<task_name>")
@login_required
def task_detail(task_name):
task = get_task(task_name)
if not task:
abort(404)
logs = task.get_logs()
return render_template("task_detail.html", task=task, logs=logs)
@app.route("/task/<task_name>/logs")
@login_required
def task_logs(task_name):
"""Return latest logs for the given task."""
task = get_task(task_name)
if not task:
abort(404)
lines = int(request.args.get("lines", 50))
logs = task.get_logs(lines)
return logs, 200, {"Content-Type": "text/plain; charset=utf-8"}
@app.route("/task/<task_name>/start", methods=["POST"])
@login_required
def start_task(task_name):
task = get_task(task_name)
if not task:
if request.accept_mimetypes.best == 'application/json':
return jsonify({"success": False, "message": "Task not found"}), 404
abort(404)
try:
task.start()
if request.accept_mimetypes.best == 'application/json':
return jsonify({"success": True, "message": f"Started {task_name}."})
return redirect(url_for("task_detail", task_name=task_name))
except Exception as e:
if request.accept_mimetypes.best == 'application/json':
return jsonify({"success": False, "message": str(e)}), 500
abort(500)
@app.route("/task/<task_name>/stop", methods=["POST"])
@login_required
def stop_task(task_name):
task = get_task(task_name)
if not task:
if request.accept_mimetypes.best == 'application/json':
return jsonify({"success": False, "message": "Task not found"}), 404
abort(404)
try:
task.stop()
if request.accept_mimetypes.best == 'application/json':
return jsonify({"success": True, "message": f"Stopped {task_name}."})
return redirect(url_for("task_detail", task_name=task_name))
except Exception as e:
app.logger.exception("Failed to stop task %s", task_name)
if request.accept_mimetypes.best == 'application/json':
return jsonify({"success": False, "message": str(e)}), 500
return redirect(url_for("task_detail", task_name=task_name))
# API route for running a task
@app.route("/run_task/<task_name>", methods=["POST"])
@login_required
def run_task(task_name):
task = get_task(task_name)
if not task:
return jsonify({"success": False, "message": "Task not found"}), 404
try:
task.start()
# Do not return a json response here, just redirect to the task detail page
return redirect(url_for("task_detail", task_name=task_name))
except Exception as e:
return jsonify({"success": False, "message": str(e)}), 500
# API route for unmounting storage
@app.route("/unmount", methods=["POST"])
@login_required
def unmount():
mount_point = config_manager.get_value('backup', 'mount_point', runtime.default_mount_point)
try:
if runtime.is_fake:
fake_state.set_mount(False)
fake_state.append_task_log('Check Mount', f'Backup source disconnected from {mount_point}.')
return jsonify({"success": True, "message": "Local backup source disconnected."})
# 1. Disconnect all SMB users (if possible)
try:
subprocess.run(["sudo", "smbcontrol", "all", "close-share", mount_point], check=False)
except Exception:
pass # Ignore errors, just try to close sessions
# 2. Stop all systemd tasks
for service in ["check_mount.service", "check_health.service", "backup_cloud.service"]:
subprocess.run(["sudo", "systemctl", "stop", service], check=False)
# 3. Stop smbd and nmbd
subprocess.run(["sudo", "systemctl", "stop", "smbd"], check=False)
subprocess.run(["sudo", "systemctl", "stop", "nmbd"], check=False)
# 4. Unmount the drive
subprocess.run(["sudo", "umount", mount_point], check=True)
# 5. Power down the drive (try hdparm, ignore errors if not supported)
try:
uuid = config_manager.get_value('backup', 'uuid', None)
if uuid:
blkid_out = subprocess.run(['blkid', '-t', f'UUID={uuid}', '-o', 'device'], capture_output=True, text=True)
partition_device = blkid_out.stdout.strip()
if partition_device:
parent_device = system_utils.get_parent_device(partition_device)
if parent_device:
subprocess.run(["sudo", "hdparm", "-y", parent_device], check=False)
except Exception:
pass
# 6. Start smbd and nmbd again so network file sharing is available
try:
subprocess.run(["sudo", "systemctl", "start", "smbd"], check=False)
subprocess.run(["sudo", "systemctl", "start", "nmbd"], check=False)
except Exception:
pass
return jsonify({"success": True, "message": "Drive unmounted and powered down. It is now safe to remove the drive."})
except subprocess.CalledProcessError as e:
return jsonify({"success": False, "message": f"Failed to unmount drive: {e}"}), 500
except Exception as e:
return jsonify({"success": False, "message": f"Unexpected error: {e}"}), 500
# API route for restarting the system
@app.route("/restart", methods=["POST"])
@admin_required
def restart():
try:
if runtime.is_fake:
return jsonify({"success": True, "message": "Fake mode: restart simulated."})
subprocess.run(["sudo", "systemctl", "reboot"], check=True)
return jsonify({"success": True, "message": "System is restarting..."})
except subprocess.CalledProcessError as e:
return jsonify({"success": False, "message": f"Failed to restart system: {e}"}), 500
except Exception as e:
return jsonify({"success": False, "message": f"Unexpected error: {e}"}), 500
# API route for shutting down the system
@app.route("/shutdown", methods=["POST"])
@admin_required
def shutdown():
try:
if runtime.is_fake:
return jsonify({"success": True, "message": "Fake mode: shutdown simulated."})
subprocess.run(["sudo", "systemctl", "poweroff"], check=True)
return jsonify({"success": True, "message": "System is shutting down..."})
except subprocess.CalledProcessError as e:
return jsonify({"success": False, "message": f"Failed to shut down system: {e}"}), 500
except Exception as e:
return jsonify({"success": False, "message": f"Unexpected error: {e}"}), 500
# Drive health page
@app.route("/drives", methods=["GET", "POST"])
@login_required
def drives():
prediction = None
probability = None
error = None
smart = None
missing_attrs = None
if request.method == "POST":
result = get_smart_attributes()
if result is None:
error = "Could not retrieve SMART data"
else:
smart, missing_attrs = result
prob = predict_failure_probability(smart)
if prob is not None:
prediction = int(prob >= optimal_threshold)
probability = prob
append_telemetry(smart, prediction)
else:
error = "Model not loaded"
return render_template(
"drive_health.html",
smart=smart,
prediction=prediction,
probability=probability,
error=error,
missing_attrs=missing_attrs,
smart_fields=SMART_FIELDS,
)
@app.route("/download_telemetry")
@login_required
def download_telemetry():
if runtime.telemetry_path.exists():
return send_file(runtime.telemetry_path, as_attachment=True)
abort(404)
def run_fake_cloud_backup(cancel_event: threading.Event):
source = config_manager.get_value('backup', 'mount_point', runtime.default_mount_point)
destination = config_manager.get_value('backup', 'rclone_dir', '').strip()
rclone_config_path = runtime.rclone_config_dir / 'rclone.conf'
if not source:
raise RuntimeError('No source folder configured.')
if not os.path.isdir(source):
raise RuntimeError(f'Source folder does not exist: {source}')
if not destination:
raise RuntimeError('No cloud destination configured.')
if ':' in destination and not rclone_config_path.exists():
raise RuntimeError(f'Rclone config not found at {rclone_config_path}')
fake_state.append_task_log('Cloud Backup', f'Starting backup from {source} to {destination}')
bandwidth_limit = config_manager.get_value('backup', 'bandwidth_limit', '').strip()
command = ['rclone', 'sync', source, destination, '--create-empty-src-dirs', '-v']
if rclone_config_path.exists():
command.extend(['--config', str(rclone_config_path)])
if bandwidth_limit:
command.extend(['--bwlimit', bandwidth_limit])
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
)
output_queue: queue.Queue[tuple[str, str]] = queue.Queue()
def _drain_stream(stream, stream_name: str):
try:
for line in iter(stream.readline, ''):
output_queue.put((stream_name, line))
finally:
stream.close()
stdout_thread = threading.Thread(
target=_drain_stream,
args=(proc.stdout, 'stdout'),
name='fake-cloud-backup-stdout',
daemon=True,
)
stderr_thread = threading.Thread(
target=_drain_stream,
args=(proc.stderr, 'stderr'),
name='fake-cloud-backup-stderr',
daemon=True,
)
stdout_thread.start()
stderr_thread.start()
stdout_chunks: list[str] = []
stderr_chunks: list[str] = []
while True:
while True:
try:
stream_name, chunk = output_queue.get_nowait()
except queue.Empty:
break
if stream_name == 'stdout':
stdout_chunks.append(chunk)
else:
stderr_chunks.append(chunk)
if proc.poll() is not None:
break
if cancel_event.is_set():
proc.terminate()
try:
proc.wait(timeout=5.0)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
break
time.sleep(0.1)
stdout_thread.join(timeout=1.0)
stderr_thread.join(timeout=1.0)
while True:
try:
stream_name, chunk = output_queue.get_nowait()
except queue.Empty:
break
if stream_name == 'stdout':
stdout_chunks.append(chunk)
else:
stderr_chunks.append(chunk)
output = ''.join(stdout_chunks + stderr_chunks)
if output.strip():
fake_state.append_task_log('Cloud Backup', output.strip())
if cancel_event.is_set():
raise RuntimeError('Cloud backup was cancelled.')
if proc.returncode != 0:
raise RuntimeError(output.strip() or 'Cloud backup failed.')
fake_task_threads: dict[str, threading.Thread] = {}
fake_task_cancel_events: dict[str, threading.Event] = {}
fake_task_lock = threading.Lock()
def start_fake_task(task_name: str):
with fake_task_lock:
existing_thread = fake_task_threads.get(task_name)
if existing_thread and existing_thread.is_alive():
raise RuntimeError(f'{task_name} is already running.')
cancel_event = threading.Event()
fake_task_cancel_events[task_name] = cancel_event
fake_state.set_task_state(task_name, status=Status.RUNNING)
fake_state.append_task_log(task_name, f'Starting {task_name} in fake mode.')
thread = threading.Thread(
target=run_fake_task,
args=(task_name, cancel_event),
name=f'fake-task-{task_name.lower().replace(" ", "-")}',
daemon=True,
)
fake_task_threads[task_name] = thread
thread.start()
def run_fake_task(task_name: str, cancel_event: threading.Event):
start_time = datetime.now()
try:
if task_name == 'Check Mount':
mount_point = config_manager.get_value('backup', 'mount_point', runtime.default_mount_point)
if not os.path.isdir(mount_point):