-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmenu.py
More file actions
734 lines (641 loc) · 26.1 KB
/
Copy pathmenu.py
File metadata and controls
734 lines (641 loc) · 26.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
import os
import sys
from datetime import datetime
from dotenv import load_dotenv
from models.database import get_session, DeviceStatus, SnmpMetric, InterfaceTraffic
from backup.supabase_backup import run as backup_run, get_supabase_client, RETAIN_ROWS
from utils.logger import get_logger
load_dotenv()
logger = get_logger('menu')
# ── Helper tampilan ──────────────────────────────────────────
def clear():
os.system('clear')
def header(title: str):
print("=" * 52)
print(f" {title}")
print("=" * 52)
def pause():
input("\nTekan Enter untuk kembali ke menu...")
def fmt_bytes(b: int) -> str:
if b >= 1_000_000_000:
return f"{b/1_000_000_000:.2f} GB"
elif b >= 1_000_000:
return f"{b/1_000_000:.2f} MB"
elif b >= 1_000:
return f"{b/1_000:.2f} KB"
return f"{b} B"
def print_table(headers: list, rows: list, col_widths: list):
fmt = " ".join(f"{{:<{w}}}" for w in col_widths)
print(fmt.format(*headers))
print(" ".join("-" * w for w in col_widths))
for row in rows:
print(fmt.format(*[str(v) for v in row]))
# ── Menu 1 — Status Perangkat Realtime ──────────────────────
def menu_status():
clear()
header("STATUS PERANGKAT — REALTIME")
session = get_session()
try:
# Ambil data terbaru per device
from sqlalchemy import func
subq = (
session.query(
DeviceStatus.device,
func.max(DeviceStatus.id).label('max_id')
).group_by(DeviceStatus.device).subquery()
)
records = (
session.query(DeviceStatus)
.join(subq, DeviceStatus.id == subq.c.max_id)
.order_by(DeviceStatus.device)
.all()
)
if not records:
print("\n Belum ada data. Jalankan main.py terlebih dahulu.")
else:
print()
print_table(
['Perangkat', 'IP', 'Status', 'Latency', 'Terakhir Dicek'],
[
[
r.device,
r.ip_address,
'✓ UP' if r.status == 'up' else '✗ DOWN',
f"{r.latency_ms} ms" if r.latency_ms else '-',
r.checked_at.strftime('%Y-%m-%d %H:%M:%S')
]
for r in records
],
[16, 16, 8, 12, 22]
)
finally:
session.close()
pause()
# ── Menu 2 — Log Lokal ──────────────────────────────────────
def menu_log_lokal():
clear()
header("LOG LOKAL — 20 DATA TERBARU")
print("\n [1] Ping / Device Status")
print(" [2] SNMP Metrics")
print(" [3] Interface Traffic")
print(" [0] Kembali")
print()
pilih = input("Pilih: ").strip()
session = get_session()
try:
if pilih == '1':
clear()
header("LOG — DEVICE STATUS (20 terbaru)")
records = session.query(DeviceStatus).order_by(
DeviceStatus.id.desc()).limit(20).all()
print()
print_table(
['Waktu', 'Perangkat', 'Status', 'Latency (ms)'],
[[r.checked_at.strftime('%Y-%m-%d %H:%M:%S'),
r.device, r.status,
r.latency_ms if r.latency_ms else '-']
for r in records],
[22, 16, 8, 12]
)
elif pilih == '2':
clear()
header("LOG — SNMP METRICS (20 terbaru)")
records = session.query(SnmpMetric).order_by(
SnmpMetric.id.desc()).limit(20).all()
print()
print_table(
['Waktu', 'Perangkat', 'Metric', 'Value'],
[[r.collected_at.strftime('%Y-%m-%d %H:%M:%S'),
r.device, r.metric_name,
str(r.metric_value)[:30]]
for r in records],
[22, 16, 18, 32]
)
elif pilih == '3':
clear()
header("LOG — INTERFACE TRAFFIC (20 terbaru)")
records = session.query(InterfaceTraffic).order_by(
InterfaceTraffic.id.desc()).limit(20).all()
print()
print_table(
['Waktu', 'Perangkat', 'Interface', 'In', 'Out'],
[[r.collected_at.strftime('%Y-%m-%d %H:%M:%S'),
r.device, r.interface_name,
fmt_bytes(r.bytes_in), fmt_bytes(r.bytes_out)]
for r in records],
[22, 16, 12, 12, 12]
)
elif pilih == '0':
return
else:
print(" Pilihan tidak valid.")
finally:
session.close()
pause()
# ── Menu 3 — Lihat Backup Supabase ──────────────────────────
def menu_log_supabase():
clear()
header("LOG BACKUP — SUPABASE (20 terbaru)")
print("\n [1] Device Status")
print(" [2] SNMP Metrics")
print(" [3] Interface Traffic")
print(" [0] Kembali")
print()
pilih = input("Pilih: ").strip()
if pilih == '0':
return
try:
client = get_supabase_client()
if pilih == '1':
clear()
header("BACKUP SUPABASE — DEVICE STATUS")
res = (client.table('device_status_backup')
.select('checked_at,device,status,latency_ms')
.order('checked_at', desc=True).limit(20).execute())
print()
print_table(
['Waktu', 'Perangkat', 'Status', 'Latency (ms)'],
[[r['checked_at'][:19], r['device'],
r['status'], r['latency_ms'] or '-']
for r in res.data],
[22, 16, 8, 12]
)
elif pilih == '2':
clear()
header("BACKUP SUPABASE — SNMP METRICS")
res = (client.table('snmp_metrics_backup')
.select('collected_at,device,metric_name,metric_value')
.order('collected_at', desc=True).limit(20).execute())
print()
print_table(
['Waktu', 'Perangkat', 'Metric', 'Value'],
[[r['collected_at'][:19], r['device'],
r['metric_name'], str(r['metric_value'])[:30]]
for r in res.data],
[22, 16, 18, 32]
)
elif pilih == '3':
clear()
header("BACKUP SUPABASE — INTERFACE TRAFFIC")
res = (client.table('interface_traffic_backup')
.select('collected_at,device,interface_name,bytes_in,bytes_out')
.order('collected_at', desc=True).limit(20).execute())
print()
print_table(
['Waktu', 'Perangkat', 'Interface', 'In', 'Out'],
[[r['collected_at'][:19], r['device'],
r['interface_name'],
fmt_bytes(r['bytes_in']), fmt_bytes(r['bytes_out'])]
for r in res.data],
[22, 16, 12, 12, 12]
)
else:
print(" Pilihan tidak valid.")
except Exception as e:
print(f"\n Error koneksi Supabase: {e}")
pause()
# ── Menu 4 — Backup Manual ──────────────────────────────────
def menu_backup_manual():
clear()
header("BACKUP MANUAL KE SUPABASE")
print("\n Menjalankan backup sekarang...")
print()
backup_run()
pause()
# ── Menu 5 — Statistik Database ─────────────────────────────
def menu_statistik():
clear()
header("STATISTIK DATABASE")
session = get_session()
try:
ds_total = session.query(DeviceStatus).count()
sm_total = session.query(SnmpMetric).count()
it_total = session.query(InterfaceTraffic).count()
ds_oldest = session.query(DeviceStatus).order_by(DeviceStatus.id.asc()).first()
ds_newest = session.query(DeviceStatus).order_by(DeviceStatus.id.desc()).first()
print()
print(" DATABASE LOKAL (MariaDB)")
print_table(
['Tabel', 'Total Row', 'Retain Max', 'Penuh (%)'],
[
['device_status', ds_total,
RETAIN_ROWS['device_status'],
f"{ds_total/RETAIN_ROWS['device_status']*100:.1f}%"],
['snmp_metrics', sm_total,
RETAIN_ROWS['snmp_metrics'],
f"{sm_total/RETAIN_ROWS['snmp_metrics']*100:.1f}%"],
['interface_traffic', it_total,
RETAIN_ROWS['interface_traffic'],
f"{it_total/RETAIN_ROWS['interface_traffic']*100:.1f}%"],
],
[20, 10, 12, 10]
)
if ds_oldest and ds_newest:
print()
print(f" Data terlama : {ds_oldest.checked_at.strftime('%Y-%m-%d %H:%M:%S')}")
print(f" Data terbaru : {ds_newest.checked_at.strftime('%Y-%m-%d %H:%M:%S')}")
# Statistik Supabase
print()
print(" DATABASE BACKUP (Supabase)")
try:
client = get_supabase_client()
for tbl in ['device_status_backup', 'snmp_metrics_backup', 'interface_traffic_backup']:
res = client.table(tbl).select('id', count='exact').execute()
print(f" {tbl:<35} {res.count} records")
except Exception as e:
print(f" Gagal koneksi Supabase: {e}")
finally:
session.close()
pause()
# ── Menu 6 — Export CSV ─────────────────────────────────────
import csv
def menu_export_csv():
clear()
header("EXPORT DATA KE CSV")
print()
print(" Sumber data:")
print(" [1] Dari MariaDB lokal")
print(" [2] Dari Supabase backup")
print(" [0] Kembali")
print()
sumber = input("Pilih sumber: ").strip()
if sumber == '0':
return
print()
print(" Data yang diekspor:")
print(" [1] Device Status")
print(" [2] SNMP Metrics")
print(" [3] Interface Traffic")
print(" [4] Semua (3 file sekaligus)")
print(" [0] Kembali")
print()
pilih = input("Pilih data: ").strip()
if pilih == '0':
return
# Tentukan folder output
export_dir = os.path.join(os.path.dirname(__file__), 'exports')
os.makedirs(export_dir, exist_ok=True)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
if sumber == '1':
_export_csv_lokal(pilih, export_dir, timestamp)
elif sumber == '2':
_export_csv_supabase(pilih, export_dir, timestamp)
else:
print(" Pilihan tidak valid.")
pause()
def _export_csv_lokal(pilih: str, export_dir: str, timestamp: str):
session = get_session()
try:
if pilih in ('1', '4'):
records = session.query(DeviceStatus).order_by(DeviceStatus.id.desc()).all()
fname = os.path.join(export_dir, f'device_status_{timestamp}.csv')
with open(fname, 'w', newline='') as f:
w = csv.writer(f)
w.writerow(['id', 'device', 'ip_address', 'status', 'latency_ms', 'checked_at'])
for r in records:
w.writerow([r.id, r.device, r.ip_address, r.status,
r.latency_ms, r.checked_at])
print(f"\n ✓ Disimpan: {fname}")
print(f" {len(records)} records diekspor")
if pilih in ('2', '4'):
records = session.query(SnmpMetric).order_by(SnmpMetric.id.desc()).all()
fname = os.path.join(export_dir, f'snmp_metrics_{timestamp}.csv')
with open(fname, 'w', newline='') as f:
w = csv.writer(f)
w.writerow(['id', 'device', 'ip_address', 'metric_name',
'metric_value', 'collected_at'])
for r in records:
w.writerow([r.id, r.device, r.ip_address,
r.metric_name, r.metric_value, r.collected_at])
print(f"\n ✓ Disimpan: {fname}")
print(f" {len(records)} records diekspor")
if pilih in ('3', '4'):
records = session.query(InterfaceTraffic).order_by(
InterfaceTraffic.id.desc()).all()
fname = os.path.join(export_dir, f'interface_traffic_{timestamp}.csv')
with open(fname, 'w', newline='') as f:
w = csv.writer(f)
w.writerow(['id', 'device', 'ip_address', 'interface_name',
'bytes_in', 'bytes_out', 'packets_in',
'packets_out', 'collected_at'])
for r in records:
w.writerow([r.id, r.device, r.ip_address,
r.interface_name, r.bytes_in, r.bytes_out,
r.packets_in, r.packets_out, r.collected_at])
print(f"\n ✓ Disimpan: {fname}")
print(f" {len(records)} records diekspor")
if pilih not in ('1', '2', '3', '4'):
print(" Pilihan tidak valid.")
finally:
session.close()
pause()
def _export_csv_supabase(pilih: str, export_dir: str, timestamp: str):
try:
client = get_supabase_client()
if pilih in ('1', '4'):
res = (client.table('device_status_backup')
.select('*').order('checked_at', desc=True).execute())
fname = os.path.join(export_dir, f'device_status_backup_{timestamp}.csv')
with open(fname, 'w', newline='') as f:
if res.data:
w = csv.DictWriter(f, fieldnames=res.data[0].keys())
w.writeheader()
w.writerows(res.data)
print(f"\n ✓ Disimpan: {fname}")
print(f" {len(res.data)} records diekspor")
if pilih in ('2', '4'):
res = (client.table('snmp_metrics_backup')
.select('*').order('collected_at', desc=True).execute())
fname = os.path.join(export_dir, f'snmp_metrics_backup_{timestamp}.csv')
with open(fname, 'w', newline='') as f:
if res.data:
w = csv.DictWriter(f, fieldnames=res.data[0].keys())
w.writeheader()
w.writerows(res.data)
print(f"\n ✓ Disimpan: {fname}")
print(f" {len(res.data)} records diekspor")
if pilih in ('3', '4'):
res = (client.table('interface_traffic_backup')
.select('*').order('collected_at', desc=True).execute())
fname = os.path.join(export_dir, f'interface_traffic_backup_{timestamp}.csv')
with open(fname, 'w', newline='') as f:
if res.data:
w = csv.DictWriter(f, fieldnames=res.data[0].keys())
w.writeheader()
w.writerows(res.data)
print(f"\n ✓ Disimpan: {fname}")
print(f" {len(res.data)} records diekspor")
if pilih not in ('1', '2', '3', '4'):
print(" Pilihan tidak valid.")
except Exception as e:
print(f"\n Error koneksi Supabase: {e}")
pause()
# ── Menu 7 — Manajemen Device ────────────────────────────────
def menu_device():
while True:
clear()
header("MANAJEMEN DEVICE")
print()
print(" [1] Lihat semua device")
print(" [2] Tambah device baru")
print(" [3] Toggle aktif / nonaktif")
print(" [4] Hapus device permanen")
print(" [0] Kembali")
print()
pilih = input("Pilih: ").strip()
if pilih == '0': break
elif pilih == '1': _device_list()
elif pilih == '2': _device_add()
elif pilih == '3': _device_toggle()
elif pilih == '4': _device_delete()
else:
print(" Pilihan tidak valid.")
pause()
def _device_list():
clear()
header("DAFTAR SEMUA DEVICE")
from models.database import Device
session = get_session()
try:
devices = session.query(Device).order_by(Device.id).all()
if not devices:
print("\n Belum ada device terdaftar.")
else:
print()
print_table(
['ID', 'Nama', 'IP', 'Tipe', 'SNMP', 'Status', 'Keterangan'],
[[d.id, d.name, d.ip_address, d.type,
d.snmp_community,
'AKTIF' if d.is_active else 'NONAKTIF',
d.description or '-']
for d in devices],
[4, 16, 16, 10, 8, 10, 20]
)
finally:
session.close()
pause()
def _device_list_simple():
from models.database import Device
session = get_session()
try:
devices = session.query(Device).order_by(Device.id).all()
print_table(
['ID', 'Nama', 'IP', 'Status'],
[[d.id, d.name, d.ip_address,
'AKTIF' if d.is_active else 'NONAKTIF']
for d in devices],
[4, 18, 18, 10]
)
finally:
session.close()
def _device_add():
clear()
header("TAMBAH DEVICE BARU")
print()
name = input(" Nama device (contoh: router-baru) : ").strip()
ip = input(" IP address : ").strip()
dtype = input(" Tipe [mikrotik/openwrt/linux] : ").strip()
ssh_user = input(" SSH user (default: admin) : ").strip() or 'admin'
ssh_pass = input(" SSH password (kosong = tidak ada): ").strip()
community = input(" SNMP community (default: public) : ").strip() or 'public'
desc = input(" Deskripsi : ").strip()
if not name or not ip or not dtype:
print("\n Error: nama, IP, dan tipe wajib diisi!")
pause()
return
if dtype not in ('mikrotik', 'openwrt', 'linux'):
print("\n Error: tipe harus mikrotik, openwrt, atau linux!")
pause()
return
from models.database import Device
session = get_session()
try:
existing = session.query(Device).filter(Device.name == name).first()
if existing:
print(f"\n Error: device '{name}' sudah ada!")
pause()
return
device = Device(
name=name, ip_address=ip, type=dtype,
ssh_user=ssh_user, ssh_pass=ssh_pass,
snmp_community=community, description=desc,
is_active=1
)
session.add(device)
session.commit()
print(f"\n ✓ Device '{name}' ({ip}) berhasil ditambahkan!")
print(" Monitoring akan mulai pada siklus berikutnya.")
except Exception as e:
session.rollback()
print(f"\n Error: {e}")
finally:
session.close()
pause()
def _device_toggle():
clear()
header("TOGGLE AKTIF / NONAKTIF DEVICE")
print()
_device_list_simple()
print()
try:
device_id = int(input(" Masukkan ID device: ").strip())
except ValueError:
print(" ID tidak valid.")
pause()
return
from models.database import Device
session = get_session()
try:
device = session.query(Device).filter(Device.id == device_id).first()
if not device:
print(f"\n Device ID {device_id} tidak ditemukan!")
pause()
return
device.is_active = 0 if device.is_active == 1 else 1
session.commit()
status = "DIAKTIFKAN" if device.is_active == 1 else "DINONAKTIFKAN"
print(f"\n ✓ Device '{device.name}' berhasil {status}!")
if device.is_active == 0:
print(" Monitoring akan berhenti pada siklus berikutnya.")
else:
print(" Monitoring akan mulai pada siklus berikutnya.")
except Exception as e:
session.rollback()
print(f"\n Error: {e}")
finally:
session.close()
pause()
def _device_delete():
clear()
header("HAPUS DEVICE PERMANEN")
print()
print(" PERINGATAN: Semua data monitoring device akan:")
print(" 1. Di-archive ke Supabase (deleted_* tables)")
print(" 2. Dihapus dari database lokal")
print(" 3. Device dihapus dari daftar monitoring")
print()
_device_list_simple()
print()
try:
device_id = int(input(" Masukkan ID device yang akan dihapus: ").strip())
except ValueError:
print(" ID tidak valid.")
pause()
return
from models.database import Device, DeviceStatus, SnmpMetric, InterfaceTraffic
from backup.supabase_backup import get_supabase_client
session = get_session()
try:
device = session.query(Device).filter(Device.id == device_id).first()
if not device:
print(f"\n Device ID {device_id} tidak ditemukan!")
pause()
return
# Hitung jumlah data
ds_count = session.query(DeviceStatus).filter(DeviceStatus.device == device.name).count()
sm_count = session.query(SnmpMetric).filter(SnmpMetric.device == device.name).count()
it_count = session.query(InterfaceTraffic).filter(InterfaceTraffic.device == device.name).count()
print(f"\n Device : {device.name} ({device.ip_address})")
print(f" Data yang akan di-archive & dihapus:")
print(f" device_status : {ds_count} records")
print(f" snmp_metrics : {sm_count} records")
print(f" interface_traffic : {it_count} records")
print()
konfirmasi = input(" Ketik 'ya' untuk konfirmasi: ").strip()
if konfirmasi.lower() != 'ya':
print(" Dibatalkan.")
pause()
return
name = device.name
now = datetime.now().isoformat()
device_info = {
'id': device.id, 'name': device.name,
'ip_address': device.ip_address, 'type': device.type,
}
print(f"\n Mengarchive data ke Supabase...")
client = get_supabase_client()
# Archive device_status
ds_records = session.query(DeviceStatus).filter(DeviceStatus.device == name).all()
if ds_records:
client.table('deleted_device_status').insert([{
'device': r.device, 'ip_address': r.ip_address,
'status': r.status, 'latency_ms': r.latency_ms,
'checked_at': r.checked_at.isoformat(),
'deleted_at': now, 'device_info': device_info,
} for r in ds_records]).execute()
print(f" ✓ Archive {len(ds_records)} device_status records")
# Archive snmp_metrics
sm_records = session.query(SnmpMetric).filter(SnmpMetric.device == name).all()
if sm_records:
for i in range(0, len(sm_records), 500):
batch = sm_records[i:i+500]
client.table('deleted_snmp_metrics').insert([{
'device': r.device, 'ip_address': r.ip_address,
'metric_name': r.metric_name, 'metric_value': r.metric_value,
'collected_at': r.collected_at.isoformat(),
'deleted_at': now, 'device_info': device_info,
} for r in batch]).execute()
print(f" ✓ Archive {len(sm_records)} snmp_metrics records")
# Archive interface_traffic
it_records = session.query(InterfaceTraffic).filter(InterfaceTraffic.device == name).all()
if it_records:
for i in range(0, len(it_records), 500):
batch = it_records[i:i+500]
client.table('deleted_interface_traffic').insert([{
'device': r.device, 'ip_address': r.ip_address,
'interface_name': r.interface_name,
'bytes_in': r.bytes_in, 'bytes_out': r.bytes_out,
'packets_in': r.packets_in, 'packets_out': r.packets_out,
'collected_at': r.collected_at.isoformat(),
'deleted_at': now, 'device_info': device_info,
} for r in batch]).execute()
print(f" ✓ Archive {len(it_records)} interface_traffic records")
# Hapus dari lokal
print(f"\n Menghapus data dari database lokal...")
session.query(DeviceStatus).filter(DeviceStatus.device == name).delete()
session.query(SnmpMetric).filter(SnmpMetric.device == name).delete()
session.query(InterfaceTraffic).filter(InterfaceTraffic.device == name).delete()
session.delete(device)
session.commit()
print(f" ✓ Device '{name}' dan semua datanya berhasil dihapus!")
print(f" ✓ Data tersimpan di Supabase (deleted_* tables)")
except Exception as e:
session.rollback()
print(f"\n Error: {e}")
finally:
session.close()
pause()
# ── Main Menu ────────────────────────────────────────────────
def main():
while True:
clear()
print("=" * 52)
print(" NETWORK MONITORING — MENU UTAMA")
print("=" * 52)
print(f" Waktu : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 52)
print(" [1] Status perangkat (realtime)")
print(" [2] Lihat log lokal")
print(" [3] Lihat backup Supabase")
print(" [4] Backup manual ke Supabase")
print(" [5] Statistik database")
print(" [6] Export data ke CSV")
print(" [7] Manajemen device")
print(" [0] Keluar")
print("=" * 52)
pilih = input("Pilih menu: ").strip()
if pilih == '1': menu_status()
elif pilih == '2': menu_log_lokal()
elif pilih == '3': menu_log_supabase()
elif pilih == '4': menu_backup_manual()
elif pilih == '5': menu_statistik()
elif pilih == '6': menu_export_csv()
elif pilih == '7': menu_device()
elif pilih == '0':
print("\n Keluar dari menu. Monitoring tetap berjalan.\n")
sys.exit(0)
else:
print(" Pilihan tidak valid.")
pause()
if __name__ == '__main__':
main()