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
| | 'use strict';
| | const APP_VERSION = 'v4-20260222';
| |
| | // ============================================================
| | // OPS Dashboard — Vanilla JS Application (v4)
| | // ============================================================
| |
| | // ---------------------------------------------------------------------------
| | // State
| | // ---------------------------------------------------------------------------
| | let allServices = [];
| | let currentPage = 'dashboard';
| | let viewMode = 'cards'; // 'cards' | 'table'
| | let tableFilter = null; // null | 'healthy' | 'down' | 'project:name' | 'env:name'
| | let tableFilterLabel = '';
| | let drillLevel = 0; // 0=projects, 1=environments, 2=services
| | let drillProject = null;
| | let drillEnv = null;
| | let refreshTimer = null;
| | const REFRESH_INTERVAL = 30000;
| |
| | // Backup filter state
| | let backupFilterProject = null; // null = all
| | let backupFilterEnv = null; // null = all
| |
| | // Log modal state
| | let logCtx = { project: null, env: null, service: null };
| |
| | // ---------------------------------------------------------------------------
| | // Helpers
| | // ---------------------------------------------------------------------------
| | function fmtBytes(b) {
| | if (b == null) return '\u2014';
| | const n = Number(b);
| | if (isNaN(n) || n === 0) return '0 B';
| | const k = 1024, s = ['B', 'KB', 'MB', 'GB', 'TB'];
| | const i = Math.floor(Math.log(Math.abs(n)) / Math.log(k));
| | return (n / Math.pow(k, i)).toFixed(i === 0 ? 0 : 1) + ' ' + s[i];
| | }
| |
| | function esc(str) {
| | const d = document.createElement('div');
| | d.textContent = str;
| | return d.innerHTML;
| | }
| |
| | function dotClass(status, health) {
| | const s = (status || '').toLowerCase(), h = (health || '').toLowerCase();
| | if (s === 'up' && (h === 'healthy' || !h)) return 'status-dot-green';
| | if (s === 'up' && h === 'unhealthy') return 'status-dot-red';
| | if (s === 'up' && h === 'starting') return 'status-dot-yellow';
| | if (s === 'down' || s === 'exited') return 'status-dot-red';
| | return 'status-dot-gray';
| | }
| |
| | function badgeCls(status, health) {
| | const s = (status || '').toLowerCase(), h = (health || '').toLowerCase();
| | if (s === 'up' && (h === 'healthy' || !h)) return 'badge-green';
| | if (s === 'up' && h === 'unhealthy') return 'badge-red';
| | if (s === 'up' && h === 'starting') return 'badge-yellow';
| | if (s === 'down' || s === 'exited') return 'badge-red';
| | return 'badge-gray';
| | }
| |
| | function diskColor(pct) {
| | const n = parseInt(pct);
| | if (n >= 90) return 'disk-danger';
| | if (n >= 75) return 'disk-warn';
| | return 'disk-ok';
| | }
| |
| | function isHealthy(svc) {
| | return svc.status === 'Up' && (svc.health === 'healthy' || !svc.health);
| | }
| |
| | function isDown(svc) { return !isHealthy(svc); }
| |
| | function filterServices(list) {
| | if (!tableFilter) return list;
| | if (tableFilter === 'healthy') return list.filter(isHealthy);
| | if (tableFilter === 'down') return list.filter(isDown);
| | if (tableFilter.startsWith('project:')) {
| | const p = tableFilter.slice(8);
| | return list.filter(s => s.project === p);
| | }
| | if (tableFilter.startsWith('env:')) {
| | const e = tableFilter.slice(4);
| | return list.filter(s => s.env === e);
| | }
| | return list;
| | }
| |
| | // ---------------------------------------------------------------------------
| | // Auth
| | // ---------------------------------------------------------------------------
| | function getToken() { return localStorage.getItem('ops_token'); }
| |
| | function doLogin() {
| | const input = document.getElementById('login-token');
| | const err = document.getElementById('login-error');
| | const token = input.value.trim();
| | if (!token) { err.textContent = 'Please enter a token'; err.style.display = 'block'; return; }
| | err.style.display = 'none';
| | fetch('/api/status/', { headers: { 'Authorization': 'Bearer ' + token } })
| | .then(r => { if (!r.ok) throw new Error(); return r.json(); })
| | .then(data => {
| | localStorage.setItem('ops_token', token);
| | allServices = data;
| | document.getElementById('login-overlay').style.display = 'none';
| | document.getElementById('app').style.display = 'flex';
| | const vEl = document.getElementById('app-version'); if (vEl && typeof APP_VERSION !== 'undefined') vEl.textContent = APP_VERSION;
| | showPage('dashboard');
| | startAutoRefresh();
| | })
| | .catch(() => { err.textContent = 'Invalid token.'; err.style.display = 'block'; });
| | }
| |
| | function doLogout() {
| | localStorage.removeItem('ops_token');
| | stopAutoRefresh();
| | document.getElementById('app').style.display = 'none';
| | document.getElementById('login-overlay').style.display = 'flex';
| | document.getElementById('login-token').value = '';
| | }
| |
| | // ---------------------------------------------------------------------------
| | // API
| | // ---------------------------------------------------------------------------
| | async function api(path, opts = {}) {
| | const token = getToken();
| | const headers = { ...(opts.headers || {}), 'Authorization': 'Bearer ' + token };
| | const resp = await fetch(path, { ...opts, headers });
| | if (resp.status === 401) { doLogout(); throw new Error('Session expired'); }
| | if (!resp.ok) { const b = await resp.text(); throw new Error(b || 'HTTP ' + resp.status); }
| | const ct = resp.headers.get('content-type') || '';
| | return ct.includes('json') ? resp.json() : resp.text();
| | }
| |
| | async function fetchStatus() { allServices = await api('/api/status/'); }
| |
| | // ---------------------------------------------------------------------------
| | // Toast
| | // ---------------------------------------------------------------------------
| | function toast(msg, type = 'info') {
| | const c = document.getElementById('toast-container');
| | const el = document.createElement('div');
| | el.className = 'toast toast-' + type;
| | el.innerHTML = `<span>${esc(msg)}</span><span class="toast-dismiss" onclick="this.parentElement.remove()">×</span>`;
| | c.appendChild(el);
| | setTimeout(() => { el.classList.add('toast-out'); setTimeout(() => el.remove(), 200); }, 4000);
| | }
| |
| | // ---------------------------------------------------------------------------
| | // Navigation
| | // ---------------------------------------------------------------------------
| | function toggleSidebar() {
| | document.getElementById('sidebar').classList.toggle('open');
| | document.getElementById('mobile-overlay').classList.toggle('open');
| | }
| |
| | function showPage(page) {
| | currentPage = page;
| | drillLevel = 0; drillProject = null; drillEnv = null;
| | if (page !== 'dashboard') { viewMode = 'cards'; tableFilter = null; tableFilterLabel = ''; }
| |
| | document.querySelectorAll('#sidebar-nav .sidebar-link').forEach(el =>
| | el.classList.toggle('active', el.dataset.page === page));
| | document.getElementById('sidebar').classList.remove('open');
| | document.getElementById('mobile-overlay').classList.remove('open');
| |
| | renderPage();
| | }
| |
| | function renderPage() {
| | const c = document.getElementById('page-content');
| | c.innerHTML = '<div style="text-align:center;padding:3rem;"><div class="spinner spinner-lg"></div></div>';
| | updateViewToggle();
| |
| | switch (currentPage) {
| | case 'dashboard': renderDashboard(); break;
| | case 'backups': renderBackups(); break;
| | case 'system': renderSystem(); break;
| | case 'restore': renderRestore(); break;
| | default: renderDashboard();
| | }
| | }
| |
| | function refreshCurrentPage() {
| | showSpin();
| | fetchStatus().then(() => renderPage()).catch(e => toast('Refresh failed: ' + e.message, 'error')).finally(hideSpin);
| | }
| |
| | // ---------------------------------------------------------------------------
| | // View Mode & Filters
| | // ---------------------------------------------------------------------------
| | function setViewMode(mode) {
| | viewMode = mode;
| | if (mode === 'cards') { tableFilter = null; tableFilterLabel = ''; }
| | updateViewToggle();
| | renderDashboard();
| | }
| |
| | function setTableFilter(filter, label) {
| | tableFilter = filter;
| | tableFilterLabel = label || filter;
| | viewMode = 'table';
| | updateViewToggle();
| | renderDashboard();
| | }
| |
| | function clearFilter() {
| | tableFilter = null; tableFilterLabel = '';
| | renderDashboard();
| | }
| |
| | function updateViewToggle() {
| | const wrap = document.getElementById('view-toggle-wrap');
| | const btnCards = document.getElementById('btn-view-cards');
| | const btnTable = document.getElementById('btn-view-table');
| | if (currentPage === 'dashboard') {
| | wrap.style.display = '';
| | btnCards.classList.toggle('active', viewMode === 'cards');
| | btnTable.classList.toggle('active', viewMode === 'table');
| | } else {
| | wrap.style.display = 'none';
| | }
| | }
| |
| | // ---------------------------------------------------------------------------
| | // Auto-refresh
| | // ---------------------------------------------------------------------------
| | function startAutoRefresh() {
| | stopAutoRefresh();
| | refreshTimer = setInterval(() => {
| | fetchStatus().then(() => { if (currentPage === 'dashboard') renderPage(); }).catch(() => {});
| | }, REFRESH_INTERVAL);
| | }
| | function stopAutoRefresh() { if (refreshTimer) { clearInterval(refreshTimer); refreshTimer = null; } }
| | function showSpin() { document.getElementById('refresh-indicator').classList.remove('paused'); }
| | function hideSpin() { document.getElementById('refresh-indicator').classList.add('paused'); }
| |
| | // ---------------------------------------------------------------------------
| | // Breadcrumbs
| | // ---------------------------------------------------------------------------
| | function updateBreadcrumbs() {
| | const bc = document.getElementById('breadcrumbs');
| | let h = '';
| |
| | if (currentPage === 'dashboard') {
| | if (viewMode === 'table') {
| | h = '<a onclick="setViewMode(\'cards\')">Dashboard</a><span class="sep">/</span>';
| | h += '<span class="current">All Services</span>';
| | if (tableFilter) {
| | h += ' <span class="filter-badge">' + esc(tableFilterLabel) +
| | ' <button onclick="clearFilter()">×</button></span>';
| | }
| | } else if (drillLevel === 0) {
| | h = '<span class="current">Dashboard</span>';
| | } else if (drillLevel === 1) {
| | h = '<a onclick="drillBack(0)">Dashboard</a><span class="sep">/</span><span class="current">' + esc(drillProject) + '</span>';
| | } else if (drillLevel === 2) {
| | h = '<a onclick="drillBack(0)">Dashboard</a><span class="sep">/</span><a onclick="drillBack(1)">' + esc(drillProject) + '</a><span class="sep">/</span><span class="current">' + esc(drillEnv) + '</span>';
| | }
| | } else {
| | const names = { backups: 'Backups', system: 'System', restore: 'Restore' };
| | h = '<span class="current">' + (names[currentPage] || currentPage) + '</span>';
| | }
| | bc.innerHTML = h;
| | }
| |
| | function drillBack(level) {
| | if (level === 0) { drillLevel = 0; drillProject = null; drillEnv = null; }
| | else if (level === 1) { drillLevel = 1; drillEnv = null; }
| | renderDashboard();
| | }
| |
| | // ---------------------------------------------------------------------------
| | // Dashboard — Cards + Table modes
| | // ---------------------------------------------------------------------------
| | function renderDashboard() {
| | currentPage = 'dashboard';
| | if (viewMode === 'table') { renderDashboardTable(); }
| | else if (drillLevel === 0) { renderProjects(); }
| | else if (drillLevel === 1) { renderEnvironments(); }
| | else { renderDrillServices(); }
| | updateBreadcrumbs();
| | }
| |
| | function renderProjects() {
| | const c = document.getElementById('page-content');
| | const projects = groupBy(allServices, 'project');
| | const totalUp = allServices.filter(isHealthy).length;
| | const totalDown = allServices.length - totalUp;
| |
| | let h = '<div class="page-enter">';
| |
| | // Stat tiles — clickable
| | h += '<div class="grid-stats" style="margin-bottom:1.5rem;">';
| | h += statTile('Projects', Object.keys(projects).length, '#3b82f6');
| | h += statTile('Services', allServices.length, '#8b5cf6', "setViewMode('table')");
| | h += statTile('Healthy', totalUp, '#10b981', "setTableFilter('healthy','Healthy')");
| | h += statTile('Down', totalDown, totalDown > 0 ? '#ef4444' : '#6b7280', totalDown > 0 ? "setTableFilter('down','Down')" : null);
| | h += '</div>';
| |
| | // Project cards
| | h += '<div class="grid-auto">';
| | for (const [name, svcs] of Object.entries(projects)) {
| | const up = svcs.filter(isHealthy).length;
| | const total = svcs.length;
| | const envs = [...new Set(svcs.map(s => s.env))];
| | h += `<div class="card card-clickable" onclick="drillToProject('${esc(name)}')">
| | <div style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0.75rem;">
| | <span class="status-dot ${up === total ? 'status-dot-green' : 'status-dot-red'}"></span>
| | <span style="font-weight:600;font-size:1.0625rem;color:#f3f4f6;">${esc(name)}</span>
| | <span style="margin-left:auto;font-size:0.8125rem;color:#6b7280;">${total} svc</span>
| | </div>
| | <div style="display:flex;flex-wrap:wrap;gap:0.375rem;margin-bottom:0.5rem;">
| | ${envs.map(e => `<span class="badge badge-blue">${esc(e)}</span>`).join('')}
| | </div>
| | <div style="font-size:0.8125rem;color:#9ca3af;">${up}/${total} healthy</div>
| | </div>`;
| | }
| | h += '</div></div>';
| | c.innerHTML = h;
| | }
| |
| | function renderEnvironments() {
| | const c = document.getElementById('page-content');
| | const envs = groupBy(allServices.filter(s => s.project === drillProject), 'env');
| |
| | let h = '<div class="page-enter"><div class="grid-auto">';
| | for (const [envName, svcs] of Object.entries(envs)) {
| | const up = svcs.filter(isHealthy).length;
| | const total = svcs.length;
| | h += `<div class="card card-clickable" onclick="drillToEnv('${esc(envName)}')">
| | <div style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0.75rem;">
| | <span class="status-dot ${up === total ? 'status-dot-green' : 'status-dot-red'}"></span>
| | <span style="font-weight:600;font-size:1.0625rem;color:#f3f4f6;">${esc(envName).toUpperCase()}</span>
| | <span style="margin-left:auto;font-size:0.8125rem;color:#6b7280;">${total} svc</span>
| | </div>
| | <div style="display:flex;flex-wrap:wrap;gap:0.375rem;margin-bottom:0.5rem;">
| | ${svcs.map(s => `<span class="badge ${badgeCls(s.status, s.health)}">${esc(s.service)}</span>`).join('')}
| | </div>
| | <div style="font-size:0.8125rem;color:#9ca3af;">${up}/${total} healthy</div>
| | </div>`;
| | }
| | h += '</div></div>';
| | c.innerHTML = h;
| | }
| |
| | function renderDrillServices() {
| | const c = document.getElementById('page-content');
| | const svcs = allServices.filter(s => s.project === drillProject && s.env === drillEnv);
| | let h = '<div class="page-enter"><div class="grid-auto">';
| | for (const svc of svcs) h += serviceCard(svc);
| | h += '</div></div>';
| | c.innerHTML = h;
| | }
| |
| | function drillToProject(name) { drillProject = name; drillLevel = 1; renderDashboard(); }
| | function drillToEnv(name) { drillEnv = name; drillLevel = 2; renderDashboard(); }
| |
| | // ---------------------------------------------------------------------------
| | // Dashboard — Table View
| | // ---------------------------------------------------------------------------
| | function renderDashboardTable() {
| | const c = document.getElementById('page-content');
| | const svcs = filterServices(allServices);
| |
| | let h = '<div class="page-enter">';
| |
| | // Quick filter row
| | h += '<div style="display:flex;flex-wrap:wrap;gap:0.5rem;margin-bottom:1rem;">';
| | h += filterBtn('All', null);
| | h += filterBtn('Healthy', 'healthy');
| | h += filterBtn('Down', 'down');
| | h += '<span style="color:#374151;">|</span>';
| | const projects = [...new Set(allServices.map(s => s.project))].sort();
| | for (const p of projects) {
| | h += filterBtn(p, 'project:' + p);
| | }
| | h += '</div>';
| |
| | // Table
| | if (svcs.length === 0) {
| | h += '<div class="card" style="text-align:center;color:#6b7280;padding:2rem;">No services match this filter.</div>';
| | } else {
| | h += '<div class="table-wrapper"><table class="ops-table">';
| | h += '<thead><tr><th>Project</th><th>Env</th><th>Service</th><th>Status</th><th>Health</th><th>Uptime</th><th>Actions</th></tr></thead><tbody>';
| | for (const svc of svcs) {
| | h += `<tr>
| | <td><a style="color:#60a5fa;cursor:pointer;" onclick="setTableFilter('project:${esc(svc.project)}','${esc(svc.project)}')">${esc(svc.project)}</a></td>
| | <td><span class="badge badge-blue">${esc(svc.env)}</span></td>
| | <td class="mono">${esc(svc.service)}</td>
| | <td><span class="badge ${badgeCls(svc.status, svc.health)}">${esc(svc.status)}</span></td>
| | <td>${esc(svc.health || 'n/a')}</td>
| | <td>${esc(svc.uptime || 'n/a')}</td>
| | <td style="white-space:nowrap;">
| | <button class="btn btn-ghost btn-xs" onclick="viewLogs('${esc(svc.project)}','${esc(svc.env)}','${esc(svc.service)}')">Logs</button>
| | <button class="btn btn-warning btn-xs" onclick="restartService('${esc(svc.project)}','${esc(svc.env)}','${esc(svc.service)}')">Restart</button>
| | </td>
| | </tr>`;
| | }
| | h += '</tbody></table></div>';
| | }
| |
| | h += '</div>';
| | c.innerHTML = h;
| | }
| |
| | // ---------------------------------------------------------------------------
| | // Shared Components
| | // ---------------------------------------------------------------------------
| | function serviceCard(svc) {
| | const p = esc(svc.project), e = esc(svc.env), s = esc(svc.service);
| | return `<div class="card">
| | <div style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0.5rem;">
| | <span class="status-dot ${dotClass(svc.status, svc.health)}"></span>
| | <span style="font-weight:600;color:#f3f4f6;">${s}</span>
| | <span class="badge ${badgeCls(svc.status, svc.health)}" style="margin-left:auto;">${esc(svc.status)}</span>
| | </div>
| | <div style="font-size:0.8125rem;color:#9ca3af;margin-bottom:0.75rem;">
| | Health: ${esc(svc.health || 'n/a')} · Uptime: ${esc(svc.uptime || 'n/a')}
| | </div>
| | <div style="display:flex;gap:0.5rem;">
| | <button class="btn btn-ghost btn-xs" onclick="viewLogs('${p}','${e}','${s}')">Logs</button>
| | <button class="btn btn-warning btn-xs" onclick="restartService('${p}','${e}','${s}')">Restart</button>
| | </div>
| | </div>`;
| | }
| |
| | function statTile(label, value, color, onclick) {
| | const click = onclick ? ` onclick="${onclick}"` : '';
| | const cls = onclick ? ' stat-tile' : '';
| | return `<div class="card${cls}" style="text-align:center;"${click}>
| | <div style="font-size:1.75rem;font-weight:700;color:${color};">${value}</div>
| | <div style="font-size:0.8125rem;color:#9ca3af;">${label}</div>
| | </div>`;
| | }
| |
| | function filterBtn(label, filter) {
| | const active = tableFilter === filter;
| | const cls = active ? 'btn btn-primary btn-xs' : 'btn btn-ghost btn-xs';
| | if (filter === null) {
| | return `<button class="${cls}" onclick="tableFilter=null;tableFilterLabel='';renderDashboard()">${label}</button>`;
| | }
| | return `<button class="${cls}" onclick="setTableFilter('${filter}','${label}')">${label}</button>`;
| | }
| |
| | function metricBar(label, used, total, unit, color) {
| | if (!total || total === 0) return '';
| | const pct = Math.round(used / total * 100);
| | const cls = pct >= 90 ? 'disk-danger' : pct >= 75 ? 'disk-warn' : color || 'disk-ok';
| | return `<div class="card">
| | <div style="display:flex;justify-content:space-between;margin-bottom:0.5rem;">
| | <span style="font-weight:500;color:#f3f4f6;">${label}</span>
| | <span style="font-size:0.8125rem;color:#9ca3af;">${fmtBytes(used)} / ${fmtBytes(total)} (${pct}%)</span>
| | </div>
| | <div class="progress-bar-track">
| | <div class="progress-bar-fill ${cls}" style="width:${pct}%;"></div>
| | </div>
| | </div>`;
| | }
| |
| | // ---------------------------------------------------------------------------
| | // Backups
| | // ---------------------------------------------------------------------------
| | function fmtBackupDate(raw) {
| | if (!raw) return '\u2014';
| | // YYYYMMDD_HHMMSS -> YYYY-MM-DD HH:MM
| | const m = String(raw).match(/^(\d{4})(\d{2})(\d{2})[_T](\d{2})(\d{2})/);
| | if (m) return `${m[1]}-${m[2]}-${m[3]} ${m[4]}:${m[5]}`;
| | // YYYY-MM-DD passthrough
| | return raw;
| | }
| |
| | async function renderBackups() {
| | updateBreadcrumbs();
| | const c = document.getElementById('page-content');
| | try {
| | const [local, offsite] = await Promise.all([
| | api('/api/backups/'),
| | api('/api/backups/offsite').catch(() => []),
| | ]);
| |
| | // Apply filters
| | const filteredLocal = local.filter(b => {
| | if (backupFilterProject && b.project !== backupFilterProject) return false;
| | if (backupFilterEnv && (b.env || b.environment || '') !== backupFilterEnv) return false;
| | return true;
| | });
| | const filteredOffsite = offsite.filter(b => {
| | if (backupFilterProject && b.project !== backupFilterProject) return false;
| | if (backupFilterEnv && (b.env || b.environment || '') !== backupFilterEnv) return false;
| | return true;
| | });
| |
| | let h = '<div class="page-enter">';
| |
| | // Quick backup buttons
| | h += '<div style="margin-bottom:1.5rem;">';
| | h += '<h2 style="font-size:1.125rem;font-weight:600;color:#f3f4f6;margin-bottom:0.75rem;">Create Backup</h2>';
| | h += '<div style="display:flex;flex-wrap:wrap;gap:0.5rem;">';
| | for (const p of ['mdf', 'seriousletter']) {
| | for (const e of ['dev', 'int', 'prod']) {
| | h += `<button class="btn btn-ghost btn-sm" onclick="createBackup('${p}','${e}')">${p}/${e}</button>`;
| | }
| | }
| | h += '</div></div>';
| |
| | // Filter bar
| | const activeStyle = 'background:rgba(59,130,246,0.2);color:#60a5fa;';
| | h += '<div style="display:flex;flex-wrap:wrap;gap:0.5rem;align-items:center;margin-bottom:1.5rem;padding:0.75rem 1rem;background:#1f2937;border-radius:0.5rem;">';
| | h += '<span style="color:#9ca3af;font-size:0.875rem;margin-right:0.25rem;">Project:</span>';
| | h += `<button class="btn btn-ghost btn-xs" style="${backupFilterProject === null ? activeStyle : ''}" onclick="setBackupFilter('project',null)">All</button>`;
| | h += `<button class="btn btn-ghost btn-xs" style="${backupFilterProject === 'mdf' ? activeStyle : ''}" onclick="setBackupFilter('project','mdf')">mdf</button>`;
| | h += `<button class="btn btn-ghost btn-xs" style="${backupFilterProject === 'seriousletter' ? activeStyle : ''}" onclick="setBackupFilter('project','seriousletter')">seriousletter</button>`;
| | h += '<span style="color:#374151;margin:0 0.25rem;">|</span>';
| | h += '<span style="color:#9ca3af;font-size:0.875rem;margin-right:0.25rem;">Env:</span>';
| | h += `<button class="btn btn-ghost btn-xs" style="${backupFilterEnv === null ? activeStyle : ''}" onclick="setBackupFilter('env',null)">All</button>`;
| | h += `<button class="btn btn-ghost btn-xs" style="${backupFilterEnv === 'dev' ? activeStyle : ''}" onclick="setBackupFilter('env','dev')">dev</button>`;
| | h += `<button class="btn btn-ghost btn-xs" style="${backupFilterEnv === 'int' ? activeStyle : ''}" onclick="setBackupFilter('env','int')">int</button>`;
| | h += `<button class="btn btn-ghost btn-xs" style="${backupFilterEnv === 'prod' ? activeStyle : ''}" onclick="setBackupFilter('env','prod')">prod</button>`;
| | h += '</div>';
| |
| | // Local
| | h += '<h2 style="font-size:1.125rem;font-weight:600;color:#f3f4f6;margin-bottom:0.75rem;">Local Backups</h2>';
| | if (filteredLocal.length === 0) {
| | h += '<div class="card" style="color:#6b7280;">No local backups match the current filter.</div>';
| | } else {
| | h += '<div class="table-wrapper"><table class="ops-table"><thead><tr><th>Project</th><th>Env</th><th>File</th><th>Date</th><th>Size</th></tr></thead><tbody>';
| | for (const b of filteredLocal) {
| | h += `<tr>
| | <td>${esc(b.project||'')}</td>
| | <td><span class="badge badge-blue">${esc(b.env||b.environment||'')}</span></td>
| | <td class="mono" style="font-size:0.8125rem;">${esc(b.name||b.file||'')}</td>
| | <td>${esc(fmtBackupDate(b.date||b.timestamp||''))}</td>
| | <td>${esc(b.size_human||b.size||'')}</td>
| | </tr>`;
| | }
| | h += '</tbody></table></div>';
| | }
| |
| | // Offsite
| | h += '<h2 style="font-size:1.125rem;font-weight:600;color:#f3f4f6;margin:1.5rem 0 0.75rem;">Offsite Backups</h2>';
| | if (filteredOffsite.length === 0) {
| | h += '<div class="card" style="color:#6b7280;">No offsite backups match the current filter.</div>';
| | } else {
| | h += '<div class="table-wrapper"><table class="ops-table"><thead><tr><th>Project</th><th>Env</th><th>File</th><th>Date</th><th>Size</th></tr></thead><tbody>';
| | for (const b of filteredOffsite) {
| | h += `<tr>
| | <td>${esc(b.project||'')}</td>
| | <td><span class="badge badge-blue">${esc(b.env||b.environment||'')}</span></td>
| | <td class="mono" style="font-size:0.8125rem;">${esc(b.name||'')}</td>
| | <td>${esc(fmtBackupDate(b.date||''))}</td>
| | <td>${esc(b.size||'')}</td>
| | </tr>`;
| | }
| | h += '</tbody></table></div>';
| | }
| |
| | h += '</div>';
| | c.innerHTML = h;
| | } catch (e) {
| | c.innerHTML = '<div class="card" style="color:#f87171;">Failed to load backups: ' + esc(e.message) + '</div>';
| | }
| | }
| |
| | // ---------------------------------------------------------------------------
| | // System
| | // ---------------------------------------------------------------------------
| | async function renderSystem() {
| | updateBreadcrumbs();
| | const c = document.getElementById('page-content');
| | try {
| | const [disk, health, timers, info] = await Promise.all([
| | api('/api/system/disk').catch(e => ({ filesystems: [], raw: e.message })),
| | api('/api/system/health').catch(e => ({ checks: [], raw: e.message })),
| | api('/api/system/timers').catch(e => ({ timers: [], raw: e.message })),
| | api('/api/system/info').catch(e => ({ uptime: 'error', load: 'error' })),
| | ]);
| |
| | let h = '<div class="page-enter">';
| |
| | // Resource metrics (CPU, Memory, Swap)
| | h += '<h2 style="font-size:1.125rem;font-weight:600;color:#f3f4f6;margin-bottom:0.75rem;">Resources</h2>';
| | h += '<div class="grid-metrics" style="margin-bottom:1.5rem;">';
| |
| | if (info.cpu) {
| | const cpu = info.cpu;
| | const cpuPct = cpu.usage_percent || 0;
| | const cpuCls = cpuPct >= 90 ? 'disk-danger' : cpuPct >= 75 ? 'disk-warn' : 'disk-ok';
| | h += `<div class="card">
| | <div style="display:flex;justify-content:space-between;margin-bottom:0.5rem;">
| | <span style="font-weight:500;color:#f3f4f6;">CPU</span>
| | <span style="font-size:0.8125rem;color:#9ca3af;">${cpuPct}% (${cpu.cores} cores)</span>
| | </div>
| | <div class="progress-bar-track">
| | <div class="progress-bar-fill ${cpuCls}" style="width:${cpuPct}%;"></div>
| | </div>
| | </div>`;
| | }
| |
| | if (info.memory) {
| | h += metricBar('Memory', info.memory.used, info.memory.total);
| | }
| |
| | if (info.swap && info.swap.total > 0) {
| | h += metricBar('Swap', info.swap.used, info.swap.total);
| | }
| |
| | h += '</div>';
| |
| | // Quick stats row
| | h += '<div class="grid-stats" style="margin-bottom:1.5rem;">';
| | h += statTile('Uptime', info.uptime || 'n/a', '#3b82f6');
| | h += statTile('Load', info.load || 'n/a', '#8b5cf6');
| | h += '</div>';
| |
| | // Disk usage — only real filesystems
| | h += '<h2 style="font-size:1.125rem;font-weight:600;color:#f3f4f6;margin-bottom:0.75rem;">Disk Usage</h2>';
| | const realFs = (disk.filesystems || []).filter(f => f.filesystem && f.filesystem.startsWith('/dev'));
| | if (realFs.length > 0) {
| | h += '<div class="grid-metrics" style="margin-bottom:1.5rem;">';
| | for (const fs of realFs) {
| | const pct = parseInt(fs.use_percent) || 0;
| | h += `<div class="card">
| | <div style="display:flex;justify-content:space-between;margin-bottom:0.5rem;">
| | <span class="mono" style="font-size:0.8125rem;">${esc(fs.mount || fs.filesystem)}</span>
| | <span style="font-size:0.8125rem;color:#9ca3af;">${esc(fs.used)} / ${esc(fs.size)} (${esc(fs.use_percent)})</span>
| | </div>
| | <div class="progress-bar-track">
| | <div class="progress-bar-fill ${diskColor(fs.use_percent)}" style="width:${pct}%;"></div>
| | </div>
| | </div>`;
| | }
| | h += '</div>';
| | } else {
| | h += '<div class="card" style="color:#6b7280;">No disk data.</div>';
| | }
| |
| | // Health checks
| | h += '<h2 style="font-size:1.125rem;font-weight:600;color:#f3f4f6;margin-bottom:0.75rem;">Health Checks</h2>';
| | if (health.checks && health.checks.length > 0) {
| | h += '<div style="display:grid;gap:0.5rem;margin-bottom:1.5rem;">';
| | for (const ck of health.checks) {
| | const st = (ck.status || '').toUpperCase();
| | const cls = st === 'OK' ? 'badge-green' : st === 'FAIL' ? 'badge-red' : 'badge-gray';
| | h += `<div class="card" style="display:flex;align-items:center;gap:0.75rem;padding:0.75rem 1rem;">
| | <span class="badge ${cls}">${esc(st)}</span>
| | <span style="font-size:0.875rem;">${esc(ck.check)}</span>
| | </div>`;
| | }
| | h += '</div>';
| | } else {
| | h += '<div class="card" style="color:#6b7280;">No health check data.</div>';
| | }
| |
| | // Timers
| | h += '<h2 style="font-size:1.125rem;font-weight:600;color:#f3f4f6;margin-bottom:0.75rem;">Systemd Timers</h2>';
| | if (timers.timers && timers.timers.length > 0) {
| | h += '<div class="table-wrapper"><table class="ops-table"><thead><tr><th>Unit</th><th>Next</th><th>Left</th><th>Last</th><th>Passed</th></tr></thead><tbody>';
| | for (const t of timers.timers) {
| | h += `<tr><td class="mono">${esc(t.unit)}</td><td>${esc(t.next)}</td><td>${esc(t.left)}</td><td>${esc(t.last)}</td><td>${esc(t.passed)}</td></tr>`;
| | }
| | h += '</tbody></table></div>';
| | } else {
| | h += '<div class="card" style="color:#6b7280;">No timers found.</div>';
| | }
| |
| | h += '</div>';
| | c.innerHTML = h;
| | } catch (e) {
| | c.innerHTML = '<div class="card" style="color:#f87171;">Failed to load system info: ' + esc(e.message) + '</div>';
| | }
| | }
| |
| | // ---------------------------------------------------------------------------
| | // Restore
| | // ---------------------------------------------------------------------------
| | function renderRestore() {
| | updateBreadcrumbs();
| | const c = document.getElementById('page-content');
| | let h = '<div class="page-enter">';
| | h += '<h2 style="font-size:1.125rem;font-weight:600;color:#f3f4f6;margin-bottom:0.75rem;">Restore Backup</h2>';
| | h += '<div class="card" style="max-width:480px;">';
| | h += '<div style="margin-bottom:1rem;"><label class="form-label">Project</label><select id="restore-project" class="form-select"><option value="mdf">mdf</option><option value="seriousletter">seriousletter</option></select></div>';
| | h += '<div style="margin-bottom:1rem;"><label class="form-label">Environment</label><select id="restore-env" class="form-select"><option value="dev">dev</option><option value="int">int</option><option value="prod">prod</option></select></div>';
| | h += '<div style="margin-bottom:1rem;"><label class="form-label">Source</label><select id="restore-source" class="form-select"><option value="local">Local</option><option value="offsite">Offsite</option></select></div>';
| | h += '<div style="margin-bottom:1rem;"><label style="display:flex;align-items:center;gap:0.5rem;font-size:0.875rem;color:#9ca3af;"><input type="checkbox" id="restore-dry" checked> Dry run (preview only)</label></div>';
| | h += '<button class="btn btn-danger" onclick="startRestore()">Start Restore</button>';
| | h += '</div>';
| | h += '<div id="restore-output" style="display:none;margin-top:1rem;"><h3 style="font-size:1rem;font-weight:600;color:#f3f4f6;margin-bottom:0.5rem;">Output</h3><div id="restore-terminal" class="terminal" style="max-height:400px;"></div></div>';
| | h += '</div>';
| | c.innerHTML = h;
| | }
| |
| | async function startRestore() {
| | const project = document.getElementById('restore-project').value;
| | const env = document.getElementById('restore-env').value;
| | const source = document.getElementById('restore-source').value;
| | const dryRun = document.getElementById('restore-dry').checked;
| | if (!confirm(`Restore ${project}/${env} from ${source}${dryRun ? ' (dry run)' : ''}?`)) return;
| |
| | const out = document.getElementById('restore-output');
| | const term = document.getElementById('restore-terminal');
| | out.style.display = 'block';
| | term.textContent = 'Starting restore...\n';
| |
| | const url = `/api/restore/${project}/${env}?source=${source}&dry_run=${dryRun}&token=${encodeURIComponent(getToken())}`;
| | const es = new EventSource(url);
| | es.onmessage = function(e) {
| | const d = JSON.parse(e.data);
| | if (d.done) {
| | es.close();
| | term.textContent += d.success ? '\n--- Restore complete ---\n' : '\n--- Restore FAILED ---\n';
| | toast(d.success ? 'Restore completed' : 'Restore failed', d.success ? 'success' : 'error');
| | return;
| | }
| | if (d.line) { term.textContent += d.line + '\n'; term.scrollTop = term.scrollHeight; }
| | };
| | es.onerror = function() { es.close(); term.textContent += '\n--- Connection lost ---\n'; toast('Connection lost', 'error'); };
| | }
| |
| | // ---------------------------------------------------------------------------
| | // Service Actions
| | // ---------------------------------------------------------------------------
| | async function restartService(project, env, service) {
| | if (!confirm(`Restart ${service} in ${project}/${env}?`)) return;
| | toast('Restarting ' + service + '...', 'info');
| | try {
| | const r = await api(`/api/services/restart/${project}/${env}/${service}`, { method: 'POST' });
| | toast(r.message || 'Restarted', 'success');
| | setTimeout(refreshCurrentPage, 3000);
| | } catch (e) { toast('Restart failed: ' + e.message, 'error'); }
| | }
| |
| | async function viewLogs(project, env, service) {
| | logCtx = { project, env, service };
| | document.getElementById('log-modal-title').textContent = `Logs: ${project}/${env}/${service}`;
| | document.getElementById('log-modal-content').textContent = 'Loading...';
| | document.getElementById('log-modal').style.display = 'flex';
| | await refreshLogs();
| | }
| |
| | async function refreshLogs() {
| | if (!logCtx.project) return;
| | try {
| | const d = await api(`/api/services/logs/${logCtx.project}/${logCtx.env}/${logCtx.service}?lines=200`);
| | const t = document.getElementById('log-modal-content');
| | t.textContent = d.logs || 'No logs available.';
| | t.scrollTop = t.scrollHeight;
| | } catch (e) { document.getElementById('log-modal-content').textContent = 'Error: ' + e.message; }
| | }
| |
| | function closeLogModal() {
| | document.getElementById('log-modal').style.display = 'none';
| | logCtx = { project: null, env: null, service: null };
| | }
| |
| | function setBackupFilter(type, value) {
| | if (type === 'project') backupFilterProject = value;
| | if (type === 'env') backupFilterEnv = value;
| | renderBackups();
| | }
| |
| | async function createBackup(project, env) {
| | if (!confirm(`Create backup for ${project}/${env}?`)) return;
| | toast('Creating backup...', 'info');
| | try {
| | await api(`/api/backups/${project}/${env}`, { method: 'POST' });
| | toast('Backup created for ' + project + '/' + env, 'success');
| | if (currentPage === 'backups') renderBackups();
| | } catch (e) { toast('Backup failed: ' + e.message, 'error'); }
| | }
| |
| | // ---------------------------------------------------------------------------
| | // Utilities
| | // ---------------------------------------------------------------------------
| | function groupBy(arr, key) {
| | const m = {};
| | for (const item of arr) { const k = item[key] || 'other'; (m[k] = m[k] || []).push(item); }
| | return m;
| | }
| |
| | // ---------------------------------------------------------------------------
| | // Init
| | // ---------------------------------------------------------------------------
| | (function init() {
| | const token = getToken();
| | if (token) {
| | fetch('/api/status/', { headers: { 'Authorization': 'Bearer ' + token } })
| | .then(r => { if (!r.ok) throw new Error(); return r.json(); })
| | .then(data => {
| | allServices = data;
| | document.getElementById('login-overlay').style.display = 'none';
| | document.getElementById('app').style.display = 'flex';
| | const vEl = document.getElementById('app-version'); if (vEl && typeof APP_VERSION !== 'undefined') vEl.textContent = APP_VERSION;
| | showPage('dashboard');
| | startAutoRefresh();
| | })
| | .catch(() => { localStorage.removeItem('ops_token'); });
| | }
| | document.addEventListener('keydown', e => { if (e.key === 'Escape') closeLogModal(); });
| | })();
|
|