-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
518 lines (472 loc) · 22.6 KB
/
Copy pathapp.py
File metadata and controls
518 lines (472 loc) · 22.6 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
#!/usr/bin/env python3
"""
Backup Manager Web Interface
Clean, modular architecture
"""
import os
import traceback
import cgi
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
# Handlers
from handlers.dashboard import DashboardHandler
from handlers.config_handler import ConfigHandler
from handlers.logs import LogsHandler
from handlers.inspect_handler import InspectHandler
from handlers.network import NetworkHandler
from handlers.backup import BackupHandler
from handlers.job_scheduler import JobSchedulerHandler
from handlers.restic_handler import ResticHandler
from handlers.filesystem_handler import FilesystemHandler
from handlers.api_handler import ApiHandler
from handlers.restore_handler import RestoreHandler
from handlers.notification_test_handler import NotificationTestHandler
from handlers.htmx_form_handler import HTMXFormHandler
# Services
from services.template_service import TemplateService
from services.scheduler_service import SchedulerService
# NOTE: we import bootstrap_schedules lazily inside _initialize_services()
# so a scheduler import error won't take down the whole UI.
from config import BackupConfig
class BackupWebHandler(BaseHTTPRequestHandler):
"""Main request router - delegates to specific handlers"""
# Class-level services (shared across requests)
_backup_config = None
_template_service = None
_scheduler_service = None
_handlers = None
@classmethod
def _initialize_services(cls):
"""Initialize services once at startup (idempotent & resilient)."""
needs_init = (
cls._backup_config is None
or cls._template_service is None
or cls._scheduler_service is None
or cls._handlers is None
)
if not needs_init:
return
# Core services
config_path = os.environ.get('CONFIG_PATH', '/config/config.yaml')
cls._backup_config = cls._backup_config or BackupConfig(config_path)
cls._template_service = cls._template_service or TemplateService(cls._backup_config)
if cls._scheduler_service is None:
cls._scheduler_service = SchedulerService()
# Register schedules (do not bring down UI if this fails)
try:
from services.schedule_loader import bootstrap_schedules
count = bootstrap_schedules(cls._backup_config, cls._scheduler_service)
print(f"Scheduled {count} backup job(s) from config.")
except Exception as e:
print(f"[SCHEDULER] disabled at startup: {e}")
# Build handler map last; if this throws, leave _handlers=None so we retry next request
try:
cls._handlers = {
'dashboard': DashboardHandler(
cls._backup_config,
cls._template_service,
cls._scheduler_service
),
'config': ConfigHandler(cls._backup_config, cls._template_service),
'logs': LogsHandler(cls._template_service, cls._backup_config),
'inspect': InspectHandler(cls._template_service, cls._backup_config),
'network': NetworkHandler(),
'backup': BackupHandler(cls._backup_config, cls._scheduler_service),
'job_scheduler': JobSchedulerHandler(cls._scheduler_service),
'restic': ResticHandler(cls._backup_config),
'filesystem': FilesystemHandler(cls._backup_config),
'api': ApiHandler(cls._backup_config),
'restore': RestoreHandler(cls._backup_config, cls._template_service),
'notification_test': NotificationTestHandler(),
'htmx': HTMXFormHandler(),
}
except Exception:
cls._handlers = None
raise
def __init__(self, *args, **kwargs):
# Initialize services if not already done
self._initialize_services()
super().__init__(*args, **kwargs)
def do_GET(self):
"""Route GET requests to appropriate handlers"""
url_parts = urlparse(self.path)
path = url_parts.path
params = parse_qs(url_parts.query)
try:
# Static files
if path.startswith('/static/'):
self._serve_static_file(path)
return
# Favicon
if path == '/favicon.ico':
self._serve_favicon()
return
# Route to handlers
if path in ['/', '/dashboard']:
self._handlers['dashboard'].show_dashboard(self)
elif path == '/add-job':
self._handlers['dashboard'].show_add_job_form(self)
elif path == '/edit-job':
job_name = params.get('name', [''])[0]
self._handlers['dashboard'].show_edit_job_form(self, job_name)
elif path == '/config':
self._handlers['config'].show_config_manager(self)
elif path == '/config/raw':
self._handlers['config'].show_raw_editor(self)
elif path == '/dev':
log_type = params.get('type', ['app'])[0]
self._handlers['logs'].show_dev_logs(self, log_type)
elif path == '/inspect':
self._handlers['inspect'].show_job_inspect(self)
elif path == '/scan-network':
network_range = params.get('range', ['192.168.1.0/24'])[0]
self._handlers['network'].scan_network_for_rsyncd(self, network_range)
elif path == '/validate-ssh':
source = params.get('source', [''])[0]
self._handlers['dashboard'].validate_ssh_source(self, source)
elif path == '/validate-rsyncd':
hostname = params.get('hostname', [''])[0]
share = params.get('share', [''])[0]
self._handlers['dashboard'].validate_rsyncd_destination(self, hostname, share)
elif path == '/validate-restic':
job_name = params.get('job', [''])[0]
self._handlers['restic'].validate_restic_job(self, job_name)
elif path == '/validate-restic-form':
self._send_405() # Only POST allowed for form validation
elif path == '/check-restic-binary':
job_name = params.get('job', [''])[0]
self._handlers['restic'].check_restic_binary(self, job_name)
elif path == '/restic-repo-info':
job_name = params.get('job', [''])[0]
self._handlers['restic'].get_repository_info(self, job_name)
elif path == '/restic-snapshots':
job_name = params.get('job', [''])[0]
self._handlers['restic'].list_snapshots(self, job_name)
elif path == '/restic-snapshot-stats':
job_name = params.get('job', [''])[0]
snapshot_id = params.get('snapshot', [''])[0]
self._handlers['restic'].get_snapshot_stats(self, job_name, snapshot_id)
elif path == '/restic-browse':
job_name = params.get('job', [''])[0]
snapshot_id = params.get('snapshot', [''])[0]
path = params.get('path', ['/'])[0]
self._handlers['restic'].browse_directory(self, job_name, snapshot_id, path)
elif path == '/restic-init':
job_name = params.get('job', [''])[0]
self._handlers['restic'].init_repository(self, job_name)
elif path == '/filesystem-browse':
self._handlers['filesystem'].browse_filesystem(self)
elif path == '/jobs':
self._handlers['job_scheduler'].list_jobs(self)
elif path == '/history':
job_name = params.get('job', [''])[0]
self._handlers['dashboard'].show_job_history(self, job_name)
elif path == '/reload-config':
self._handlers['config'].reload_config(self)
elif path == '/backup-config':
self._handlers['config'].download_config_backup(self)
elif path == '/api/highball/jobs':
self._handlers['api'].get_jobs(self)
else:
self._send_404()
except Exception as e:
traceback.print_exc()
self._send_error_response(f"Server error: {str(e)}")
def do_POST(self):
"""Route POST requests to appropriate handlers"""
url_parts = urlparse(self.path)
path = url_parts.path
# Read form data - support both multipart and URL-encoded
try:
content_length = int(self.headers.get('Content-Length', 0))
# Check content type to determine parsing method
content_type = self.headers.get('Content-Type', '')
if content_type.startswith('multipart/form-data'):
# Parse multipart form data
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST'}
)
# Convert to dict format expected by handlers
form_data = {}
for field in form.list:
if field.name in form_data:
# Handle multiple values for same field name
if not isinstance(form_data[field.name], list):
form_data[field.name] = [form_data[field.name]]
form_data[field.name].append(field.value)
else:
form_data[field.name] = [field.value]
else:
# Parse URL-encoded form data (legacy support)
post_data = self.rfile.read(content_length).decode('utf-8')
form_data = parse_qs(post_data)
except Exception as e:
traceback.print_exc()
self._send_error_response(f"Invalid form data: {str(e)}")
return
try:
# Route to handlers
if path == '/save-job':
self._handlers['dashboard'].save_backup_job(self, form_data)
elif path == '/delete-job':
job_name = form_data.get('job_name', [''])[0]
self._handlers['dashboard'].delete_backup_job(self, job_name)
elif path == '/restore-job':
job_name = form_data.get('job_name', [''])[0]
self._handlers['dashboard'].restore_backup_job(self, job_name)
elif path == '/purge-job':
job_name = form_data.get('job_name', [''])[0]
self._handlers['dashboard'].purge_backup_job(self, job_name)
elif path == '/run-backup':
job_name = form_data.get('job_name', [''])[0]
# Real run
self._handlers['backup'].run_backup_job(self, job_name, dry_run=False)
elif path == '/dry-run-backup':
job_name = form_data.get('job_name', [''])[0]
self._handlers['backup'].run_backup_job(self, job_name, dry_run=True)
elif path == '/plan-restic-backup':
job_name = form_data.get('job_name', [''])[0]
self._handlers['restic'].plan_backup(self, job_name)
elif path == '/restic-init':
job_name = form_data.get('job_name', [''])[0]
self._handlers['restic'].init_repository(self, job_name)
elif path == '/validate-restic-form':
self._handlers['restic'].validate_restic_form(self, form_data)
elif path == '/validate-source-paths':
self._handlers['dashboard'].validate_source_paths(self, form_data)
elif path == '/initialize-restic-repo':
self._handlers['restic'].initialize_restic_repo(self, form_data)
# HTMX form field updates
elif path == '/htmx/source-fields':
source_type = form_data.get('source_type', [''])[0]
html = self._handlers['htmx'].handle_source_type_change(source_type, dict(form_data))
self._send_htmx_response(html)
return
elif path == '/htmx/dest-fields':
dest_type = form_data.get('dest_type', [''])[0]
html = self._handlers['htmx'].handle_dest_type_change(dest_type, dict(form_data))
self._send_htmx_response(html)
return
# HTMX validation endpoints
elif path == '/htmx/validate-source':
html = self._handlers['htmx'].handle_ssh_validation(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/validate-dest-ssh':
html = self._handlers['htmx'].handle_ssh_validation(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/validate-source-paths':
html = self._handlers['htmx'].handle_source_path_validation(form_data)
self._send_htmx_response(html)
return
# HTMX Restic endpoints
elif path == '/htmx/restic-repo-fields':
html = self._handlers['htmx'].handle_restic_repo_fields(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/restic-uri-preview':
html = self._handlers['htmx'].handle_restic_uri_preview(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/validate-restic':
html = self._handlers['htmx'].handle_restic_validation(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/initialize-restic':
html = self._handlers['htmx'].handle_restic_initialization(form_data)
self._send_htmx_response(html)
return
# HTMX source path management endpoints
elif path == '/htmx/add-source-path':
html = self._handlers['htmx'].handle_add_source_path(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/remove-source-path':
html = self._handlers['htmx'].handle_remove_source_path(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/validate-single-source-path':
html = self._handlers['htmx'].handle_validate_single_source_path(form_data)
self._send_htmx_response(html)
return
# HTMX log management endpoints
elif path == '/htmx/refresh-logs':
job_name = form_data.get('job_name', [''])[0]
if job_name:
html = self._handlers['htmx'].handle_log_refresh(job_name)
self._send_htmx_response(html)
else:
self._send_htmx_response('<div class="error-message">Job name required for log refresh</div>')
return
elif path == '/htmx/clear-logs':
html = self._handlers['htmx'].handle_log_clear()
self._send_htmx_response(html)
return
elif path == '/htmx/cron-field':
html = self._handlers['htmx'].handle_cron_field_toggle(form_data)
self._send_htmx_response(html)
return
# HTMX config management endpoints
elif path == '/htmx/notification-settings':
html = self._handlers['htmx'].handle_notification_settings_toggle(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/queue-settings':
html = self._handlers['htmx'].handle_queue_settings_toggle(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/test-telegram':
html = self._handlers['htmx'].handle_notification_test('telegram', form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/test-email':
html = self._handlers['htmx'].handle_notification_test('email', form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/maintenance-toggle':
html = self._handlers['htmx'].handle_maintenance_toggle(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/maintenance-section':
html = self._handlers['htmx'].handle_maintenance_section_visibility(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/rsyncd-discovery':
html = self._handlers['htmx'].handle_rsyncd_discovery(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/rsyncd-validation':
html = self._handlers['htmx'].handle_rsyncd_validation(form_data)
self._send_htmx_response(html)
return
# HTMX notification management endpoints
elif path == '/htmx/add-notification-provider':
# Get available providers from config (this would need to be implemented)
available_providers = ['telegram', 'email'] # Placeholder
html = self._handlers['htmx'].handle_add_notification_provider(form_data, available_providers)
self._send_htmx_response(html)
return
elif path == '/htmx/remove-notification-provider':
available_providers = ['telegram', 'email'] # Placeholder
html = self._handlers['htmx'].handle_remove_notification_provider(form_data, available_providers)
self._send_htmx_response(html)
return
elif path == '/htmx/toggle-success-message':
print(f"[DEBUG] HTMX toggle-success-message called with form_data: {form_data}")
html = self._handlers['htmx'].handle_toggle_success_message(form_data)
self._send_htmx_response(html)
return
elif path == '/htmx/toggle-failure-message':
html = self._handlers['htmx'].handle_toggle_failure_message(form_data)
self._send_htmx_response(html)
return
elif path == '/save-config':
self._handlers['config'].save_structured_config(self, form_data)
elif path == '/save-config/raw':
self._handlers['config'].save_raw_config(self, form_data)
elif path == '/dismiss-warning':
self._handlers['dashboard'].dismiss_config_warning(self)
elif path == '/schedule-job':
self._handlers['job_scheduler'].schedule_job(self, form_data)
elif path == '/restore':
self._handlers['restore'].process_restore_request(self, form_data)
elif path == '/check-restore-overwrites':
self._handlers['restore'].check_restore_overwrites(self, form_data)
elif path == '/test-telegram-notification':
self._handlers['notification_test'].test_telegram_notification(self, form_data)
elif path == '/test-email-notification':
self._handlers['notification_test'].test_email_notification(self, form_data)
else:
self._send_404()
except Exception as e:
traceback.print_exc()
self._send_error_response(f"Server error: {str(e)}")
def do_OPTIONS(self):
"""Handle CORS preflight requests for API endpoints"""
url_parts = urlparse(self.path)
path = url_parts.path
if path.startswith('/api/'):
self._handlers['api'].handle_options(self)
else:
self._send_405()
def _serve_static_file(self, path):
"""Serve CSS/JS files"""
file_path = path[1:] # Remove leading /
if os.path.exists(file_path):
with open(file_path, 'rb') as f:
content = f.read()
# Set content type
if path.endswith('.css'):
content_type = 'text/css'
elif path.endswith('.js'):
content_type = 'application/javascript'
else:
content_type = 'text/plain'
self.send_response(200)
self.send_header('Content-type', content_type)
self.end_headers()
self.wfile.write(content)
else:
self._send_404()
def _serve_favicon(self):
"""Serve favicon.ico from root directory"""
if os.path.exists('favicon.ico'):
with open('favicon.ico', 'rb') as f:
content = f.read()
self.send_response(200)
self.send_header('Content-type', 'image/x-icon')
self.end_headers()
self.wfile.write(content)
else:
self._send_404()
def _send_404(self):
"""Send 404 error"""
self.send_response(404)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'<html><body><h1>404 Not Found</h1></body></html>')
def _send_405(self):
"""Send 405 Method Not Allowed error"""
self.send_response(405)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'<html><body><h1>405 Method Not Allowed</h1></body></html>')
def _send_htmx_response(self, html_content):
"""Send HTMX HTML fragment response"""
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(html_content.encode())
def _send_error_response(self, message):
"""Send error page"""
import html
html_content = f"""
<html>
<head><title>Error</title></head>
<body>
<h1>Server Error</h1>
<p>{html.escape(message)}</p>
<a href="/">Back to Dashboard</a>
</body>
</html>
"""
self.send_response(500)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(html_content.encode())
def main():
"""Start the web server"""
port = int(os.environ.get('PORT', 8080))
server = HTTPServer(('0.0.0.0', port), BackupWebHandler)
print(f"Backup Manager starting on 0.0.0.0:{port}")
print("Press Ctrl+C to stop")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nShutting down...")
server.server_close()
if __name__ == '__main__':
main()