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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
|
// --- JWT Constants ---
const JWT_TOKEN_KEY = 'metrics_jwt_token';
// --- Global DOM Elements ---
// These will be properly initialized in DOMContentLoaded
let chartModal = null;
let chartModalTitle = null;
let closeChartModalBtn = null;
let closeChartBtn = null;
let expandedChart = null;
let metricsSection = null;
let viewMetricsBtn = null;
let passwordModal = null;
let passwordInput = null;
let submitPasswordBtn = null;
let closeModalBtn = null;
let passwordError = null;
let metricsControls = null;
// --- DOM Ready Flag ---
let domReady = false;
// --- Server Stats Logic ---
async function getServerStats() {
const statusElement = document.getElementById('server-status');
const uptimeElement = document.getElementById('uptime');
if (!statusElement || !uptimeElement) {
return;
}
try {
const response = await fetch('/stat/.server-stats.json');
if (!response || !response.ok) {
throw new Error(`Could not fetch server stats (status: ${response?.status})`);
}
const data = await response.json();
let status = "green";
const load1 = parseFloat(data.load_1min);
const cores = parseInt(data.cores, 10) || 1;
if (!isNaN(load1)) {
if (load1 > (cores * 0.7)) status = "yellow";
if (load1 > (cores * 0.9)) status = "red";
} else {
status = "yellow";
}
statusElement.className = `status-light ${status}`; // More direct class setting
statusElement.title = status === "green" ? "Server running normally" :
status === "yellow" ? "Server under medium load" :
status === "red" ? "Server under heavy load" : "Unknown status";
uptimeElement.textContent = `Uptime: ${data.uptime || 'Unknown'} (Load: ${data.load_1min || '?'}, ${data.load_5min || '?'}, ${data.load_15min || '?'})`;
// Store service status in a global variable for later use when metrics are displayed
window.serviceStatusData = {
http_status: data.service_http_status,
ssh_status: data.service_ssh_status
};
// Update the service status if it's currently visible
updateServiceStatusDisplay();
} catch (error) {
statusElement.className = 'status-light yellow';
statusElement.title = "Status check failed - server may still be operational";
uptimeElement.textContent = 'Status: Available (Stats unavailable)';
// Clear service status data on error
window.serviceStatusData = null;
}
}
// Function to create/update service status display
function updateServiceStatusDisplay() {
// Only update if metrics section is visible
if (metricsSection && metricsSection.style.display === 'block' && window.serviceStatusData) {
let serviceStatusElement = document.getElementById('service-status');
// Create the element if it doesn't exist
if (!serviceStatusElement) {
serviceStatusElement = document.createElement('div');
serviceStatusElement.id = 'service-status';
serviceStatusElement.className = 'service-status';
// Insert at the beginning of metrics section for better visibility
if (metricsSection.firstChild) {
metricsSection.insertBefore(serviceStatusElement, metricsSection.firstChild);
} else {
metricsSection.appendChild(serviceStatusElement);
}
}
// Update the content
const httpStatus = window.serviceStatusData.http_status === 1 ? "Up" : "Down";
const sshStatus = window.serviceStatusData.ssh_status === 1 ? "Up" : "Down";
const httpClass = window.serviceStatusData.http_status === 1 ? "green" : "red";
const sshClass = window.serviceStatusData.ssh_status === 1 ? "green" : "red";
serviceStatusElement.innerHTML = `
<div class="service-item">
<div class="status-light ${httpClass}"></div>
<span>HTTP: ${httpStatus}</span>
</div>
<div class="service-item">
<div class="status-light ${sshClass}"></div>
<span>SSH: ${sshStatus}</span>
</div>
`;
}
}
// --- Metrics Authentication & Display Logic ---
// Constants and variables will now be initialized when DOM is ready
// Functions stay decoupled from global DOM element references
function getToken() {
return localStorage.getItem(JWT_TOKEN_KEY);
}
function setToken(token) {
localStorage.setItem(JWT_TOKEN_KEY, token);
}
function removeToken() {
localStorage.removeItem(JWT_TOKEN_KEY);
}
function showMetrics() {
if (!metricsSection) {
console.error("Metrics section not found in DOM");
return;
}
try {
metricsSection.style.display = 'block';
createOrShowHideButton();
// Display the service status when metrics are shown
updateServiceStatusDisplay();
// Initialize metrics UI if not already initialized
if (!chartsInitialized) {
initializeMetricsUI();
} else {
startDataUpdates();
}
} catch (error) {
console.error("Error showing metrics:", error);
alert("There was an error displaying the metrics. Please try refreshing the page.");
}
}
function hideMetrics() {
if (!metricsSection) return;
metricsSection.style.display = 'none';
removeHideButton();
// Remove the service status element when metrics are hidden
const serviceStatusElement = document.getElementById('service-status');
if (serviceStatusElement) {
serviceStatusElement.remove();
}
if (typeof stopDataUpdates === 'function') {
stopDataUpdates();
}
}
function createOrShowHideButton() {
if (!metricsControls) return;
let hideBtn = document.getElementById('hide-metrics-btn');
if (!hideBtn) {
hideBtn = document.createElement('button');
hideBtn.id = 'hide-metrics-btn';
hideBtn.className = 'button';
hideBtn.textContent = 'Hide Server Metrics';
hideBtn.style.marginLeft = '10px';
hideBtn.addEventListener('click', () => {
removeToken(); // Optionally clear token on hide
hideMetrics();
});
metricsControls.appendChild(hideBtn);
}
hideBtn.style.display = 'inline-block'; // Ensure it's visible
}
function removeHideButton() {
const hideBtn = document.getElementById('hide-metrics-btn');
if (hideBtn) {
hideBtn.remove();
}
}
function openPasswordModal() {
if (!passwordModal || !passwordInput || !passwordError) return;
passwordInput.value = '';
passwordError.textContent = '';
passwordError.style.opacity = 0;
passwordModal.style.display = 'block';
setTimeout(() => {
passwordModal.classList.add('show');
passwordInput.focus();
}, 10);
}
function closePasswordModal() {
if (!passwordModal) return;
passwordModal.classList.remove('show');
setTimeout(() => {
passwordModal.style.display = 'none';
}, 300);
}
async function login() {
if (!passwordInput || !passwordError) return;
const password = passwordInput.value;
if (!password) {
showPasswordError('Please enter a password');
return;
}
try {
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password: password })
});
if (response.ok) {
const data = await response.json();
if (data.token) {
setToken(data.token); // Store JWT
closePasswordModal();
showMetrics();
} else {
showPasswordError('Login failed: No token received.');
}
} else {
const errorData = await response.json().catch(() => ({ error: 'Unknown login error' }));
showPasswordError(`Login failed: ${errorData.error || response.statusText}`);
passwordInput.value = '';
}
} catch (error) {
showPasswordError('Login request error. Check connection.');
}
}
function showPasswordError(message) {
if (!passwordError || !passwordInput) return;
passwordError.textContent = message;
passwordError.style.opacity = 1;
passwordInput.classList.add('shake');
setTimeout(() => { passwordInput.classList.remove('shake'); }, 500);
}
// --- SNMP Charts Logic ---
const API_ENDPOINT = '/api/metrics';
const UPDATE_INTERVAL = 10000;
const CHART_HISTORY = 60;
let charts = {};
let chartsInitialized = false;
let updateIntervalId;
let metricsDefinitions = {};
const chartColors = {
networkIn: '#88B7B5',
networkOut: '#FDCFF3',
cpu: '#88B7B5',
memory: '#FDCFF3',
system: '#88B7B5',
generic: '#88B7B5',
// Colors for application performance metrics
appResponse: '#4CAF50', // Green for response time
appError: '#F44336', // Red for error rate
appRequests: '#2196F3', // Blue for request count
serviceStatus: '#FF9800' // Orange for service status
};
// formatBytes, formatTime, calculateRates - Keep these utility functions as they were
function formatBytes(bytes, decimals = 2) {
if (bytes === undefined || bytes === null || bytes === 0) return '0 Bytes';
const k = 1024, dm = decimals < 0 ? 0 : decimals, sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(Math.abs(bytes)) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
function formatTime(centiseconds) {
if (!centiseconds || centiseconds < 0) return '0s';
const totalSeconds = Math.floor(centiseconds / 100);
const days = Math.floor(totalSeconds / 86400), hours = Math.floor((totalSeconds % 86400) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60), seconds = totalSeconds % 60;
if (days > 0) return `${days}d ${hours}h ${minutes}m`;
if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`;
if (minutes > 0) return `${minutes}m ${seconds}s`;
return `${seconds}s`;
}
function calculateRates(data) {
if (!data || data.length < 2) {
return [];
}
const rates = [];
for (let i = 1; i < data.length; i++) {
const timeDiff = (data[i].timestamp - data[i-1].timestamp) / 1000;
const valueDiff = data[i].value - data[i-1].value;
if (timeDiff < 0.001) continue;
// Detect counter wrap/reset (when a counter resets to 0)
const rate = valueDiff >= 0 ?
valueDiff / timeDiff :
(4294967295 + valueDiff) / timeDiff;
rates.push({ timestamp: data[i].timestamp, value: rate });
}
return rates;
}
function createChartContainers(metrics) {
if (!domReady) {
console.warn("DOM not ready for creating chart containers");
// Wait a bit and try again
setTimeout(() => createChartContainers(metrics), 300);
return;
}
if (!metricsSection) {
metricsSection = document.getElementById('metrics-section');
if (!metricsSection) {
console.error("Metrics section not found in DOM");
return;
}
}
const metricGrid = metricsSection.querySelector('.metric-grid');
if (!metricGrid) {
console.error("Metric grid not found in DOM");
return;
}
try {
metricGrid.innerHTML = ''; // Clear previous
charts = {}; // Clear chart objects
// Group the metrics into two sections
const networkAndSystemMetrics = {};
const appPerformanceMetrics = {};
const serviceStatusMetrics = {};
// First categorize the metrics
for (const [metricName, definition] of Object.entries(metrics)) {
// Skip system_uptime and memory metrics (as requested)
if (metricName === 'system_uptime' ||
metricName.includes('memory_total') ||
metricName === 'memory_size') {
continue;
}
// Categorize based on metric name
if (metricName.startsWith('app_')) {
appPerformanceMetrics[metricName] = definition;
} else if (metricName.startsWith('service_')) {
serviceStatusMetrics[metricName] = definition;
} else {
networkAndSystemMetrics[metricName] = definition;
}
}
// Create section headers and containers
if (Object.keys(networkAndSystemMetrics).length > 0) {
const sectionHeader = document.createElement('h4');
sectionHeader.textContent = 'Network & System Metrics';
sectionHeader.className = 'metric-section-header';
metricGrid.appendChild(sectionHeader);
// Create containers for network & system metrics
for (const [metricName, definition] of Object.entries(networkAndSystemMetrics)) {
createMetricCard(metricGrid, metricName, definition);
}
}
// Application Performance section
if (Object.keys(appPerformanceMetrics).length > 0) {
const sectionHeader = document.createElement('h4');
sectionHeader.textContent = 'Application Performance';
sectionHeader.className = 'metric-section-header';
metricGrid.appendChild(sectionHeader);
// Create containers for app performance metrics
for (const [metricName, definition] of Object.entries(appPerformanceMetrics)) {
createMetricCard(metricGrid, metricName, definition);
}
}
} catch (error) {
console.error("Error creating chart containers:", error);
}
}
function createMetricCard(container, metricName, definition) {
if (!container) return;
try {
const displayName = definition.label || metricName;
const metricCard = document.createElement('div');
metricCard.className = 'metric-card';
metricCard.innerHTML = `<h5>${displayName}</h5><div class="chart-container" data-metric="${metricName}" data-label="${displayName}"><canvas id="${metricName}Chart"></canvas></div>`;
container.appendChild(metricCard);
// Add click event for chart expansion
const chartContainer = metricCard.querySelector('.chart-container');
if (chartContainer) {
chartContainer.addEventListener('click', function() {
try {
const metricAttr = this.getAttribute('data-metric');
const labelAttr = this.getAttribute('data-label');
if (metricAttr && labelAttr && typeof expandChart === 'function') {
// Wait until DOM is ready before trying to expand
if (domReady) {
expandChart(metricAttr, labelAttr);
} else {
console.warn("DOM not ready for chart expansion, delaying...");
// Delay expansion until DOM is ready
setTimeout(() => {
if (typeof expandChart === 'function') {
expandChart(metricAttr, labelAttr);
}
}, 500);
}
}
} catch (error) {
console.error("Error expanding chart:", error);
// Fallback if there's an error - show a simple alert
alert(`Could not expand the ${displayName} chart. Please try again later.`);
}
});
}
} catch (error) {
console.error("Error creating metric card:", error);
}
}
function startDataUpdates() {
if (updateIntervalId) {
return; // Don't start if already running
}
updateCharts();
updateIntervalId = setInterval(updateCharts, UPDATE_INTERVAL);
}
function stopDataUpdates() {
if (updateIntervalId) {
clearInterval(updateIntervalId);
updateIntervalId = null;
}
}
async function fetchWithAuth(url, options = {}) {
const token = getToken();
const headers = { ...options.headers };
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
try {
const response = await fetch(url, { ...options, headers });
if (response.status === 401) {
// Unauthorized - Token is invalid or expired
removeToken();
hideMetrics(); // Hide metrics section
openPasswordModal(); // Prompt for login
throw new Error('Unauthorized'); // Prevent further processing
}
return response;
} catch (error) {
throw error;
}
}
function initCharts(metrics) {
// Common options are reused from previous logic
const commonOptions = {
responsive: true,
maintainAspectRatio: false,
animation: { duration: 300 },
scales: {
x: {
type: 'time',
time: { unit: 'minute', tooltipFormat: 'HH:mm:ss' },
grid: { color: 'rgba(255, 255, 255, 0.1)' },
ticks: { color: '#E8F1F2', maxTicksLimit: 5 }
},
y: {
beginAtZero: true,
grid: { color: 'rgba(255, 255, 255, 0.1)' },
ticks: { color: '#E8F1F2' }
}
},
plugins: {
legend: {
display: true,
labels: { color: '#E8F1F2', font: { family: "'IBM Plex Sans', sans-serif" } }
},
tooltip: {
enabled: true,
mode: 'index',
intersect: false,
backgroundColor: 'rgba(17, 17, 17, 0.8)',
titleColor: '#FDCFF3',
bodyColor: '#E8F1F2',
borderColor: '#333',
borderWidth: 1
}
}
};
for (const [metricName, definition] of Object.entries(metrics)) {
// Skip system_uptime and memory metrics (as requested)
if (metricName === 'system_uptime' ||
metricName.includes('memory_total') ||
metricName === 'memory_size') {
continue;
}
// Skip service status metrics - they're shown in the server stats
if (metricName.startsWith('service_')) {
continue;
}
const canvas = document.getElementById(`${metricName}Chart`);
if (!canvas) {
continue;
}
const ctx = canvas.getContext('2d');
if (!ctx) {
continue;
}
let chartOptions = JSON.parse(JSON.stringify(commonOptions)); // Deep clone options
let datasets = [];
let label = definition.label || metricName;
let color = chartColors.generic;
// Configure chart based on metric type
if (metricName === 'network_in' || metricName === 'network_out') {
chartOptions.scales.y.title = { display: true, text: 'Bytes/sec', color: '#E8F1F2' };
chartOptions.scales.y.ticks.callback = function(value) { return formatBytes(value, 0); };
label = metricName === 'network_in' ? 'In' : 'Out';
color = metricName === 'network_in' ? chartColors.networkIn : chartColors.networkOut;
} else if (metricName === 'cpu_load') {
chartOptions.scales.y.title = { display: true, text: 'Load/Usage', color: '#E8F1F2' };
label = 'CPU'; color = chartColors.cpu;
} else if (metricName === 'system_processes') {
chartOptions.scales.y.title = { display: true, text: 'Count', color: '#E8F1F2' };
label = 'Processes'; color = chartColors.system;
}
// New application performance metrics
else if (metricName === 'app_response_time_avg') {
chartOptions.scales.y.title = { display: true, text: 'Time (ms)', color: '#E8F1F2' };
label = 'Response Time';
color = chartColors.appResponse;
} else if (metricName === 'app_error_rate') {
chartOptions.scales.y.title = { display: true, text: 'Error Rate (%)', color: '#E8F1F2' };
label = 'Error Rate';
color = chartColors.appError;
} else if (metricName === 'app_request_count') {
chartOptions.scales.y.title = { display: true, text: 'Requests', color: '#E8F1F2' };
label = 'Request Count';
color = chartColors.appRequests;
} else {
chartOptions.scales.y.title = { display: true, text: 'Value', color: '#E8F1F2' };
}
datasets = [{
label: label,
borderColor: color,
backgroundColor: `${color}33`,
borderWidth: 2,
data: [],
pointRadius: 0,
fill: true
}];
// Destroy existing chart if it exists to prevent memory leaks
if (charts[metricName]) {
try {
charts[metricName].destroy();
} catch (e) {
// Silent error handling
}
}
try {
charts[metricName] = new Chart(ctx, {
type: 'line',
data: { datasets },
options: chartOptions
});
} catch (error) {
// Silent error handling
}
}
chartsInitialized = true;
}
// Modified to handle sparse data better
async function updateCharts() {
// Only run if metrics section is visible
if (!metricsSection || metricsSection.style.display === 'none') return;
try {
const response = await fetchWithAuth(API_ENDPOINT);
if (!response.ok) {
return;
}
const data = await response.json();
// Combine metrics from both regular metrics and app performance metrics
const allMetrics = { ...data.metrics };
// Update chart data for each metric
for (const [metricName, metricData] of Object.entries(allMetrics)) {
// Skip metrics we're not displaying
if (!charts[metricName]) {
continue;
}
if (!metricData || !Array.isArray(metricData) || metricData.length === 0) {
continue;
}
// Process the data
let chartData;
// For network metrics, try to calculate rates, but fall back to actual values if needed
if (metricName === 'network_in' || metricName === 'network_out') {
chartData = calculateRates(metricData);
// If rate calculation failed due to insufficient data, use the raw values directly
if (!chartData || chartData.length === 0) {
chartData = [...metricData];
}
} else {
// For other metrics, use the data directly
chartData = [...metricData];
}
if (!chartData || !Array.isArray(chartData) || chartData.length === 0) {
continue;
}
// Map the data to chart format
const formattedData = chartData.map(point => {
if (!point || typeof point !== 'object' || point.timestamp === undefined || point.value === undefined) {
return null;
}
let value = point.value;
if (typeof value === 'string') {
const match = value.match(/[\d.]+/); // Allow decimals
value = match ? parseFloat(match[0]) : 0;
} else if (typeof value !== 'number') {
value = 0;
}
return { x: point.timestamp, y: value };
}).filter(point => point !== null);
if (formattedData.length === 0) {
continue;
}
// Update the chart - wrap in try/catch to prevent errors from breaking all charts
try {
charts[metricName].data.datasets[0].data = formattedData;
charts[metricName].update('none'); // Use 'none' mode for better performance
} catch (e) {
// Silent error handling
}
}
} catch (error) {
if (error.message !== 'Unauthorized') {
// Silent error handling
}
}
}
// Modified initializeMetricsUI to better handle edge cases
function initializeMetricsUI() {
if (chartsInitialized) {
startDataUpdates();
return;
}
// Ensure we are authenticated before trying to fetch
if (!getToken()) {
openPasswordModal();
return;
}
// Fetch metrics data
fetchWithAuth(API_ENDPOINT)
.then(response => {
if (!response.ok) {
return Promise.reject(new Error(`HTTP error: ${response.status}`));
}
return response.json();
})
.then(data => {
if (!data || typeof data !== 'object') {
return Promise.reject(new Error("Invalid metrics data format"));
}
if (!data.metrics || !data.definitions) {
// Create empty objects if missing rather than failing
data.metrics = data.metrics || {};
data.definitions = data.definitions || {};
}
// Store definitions
metricsDefinitions = data.definitions || {};
// Check specifically for app performance metrics
const appMetrics = Object.keys(metricsDefinitions)
.filter(key => key.startsWith('app_'));
if (appMetrics.length === 0) {
// Add placeholder definitions if they don't exist
if (!metricsDefinitions['app_response_time_avg']) {
metricsDefinitions['app_response_time_avg'] = {
label: 'Avg Response Time (ms)',
type: 'calculated'
};
}
if (!metricsDefinitions['app_error_rate']) {
metricsDefinitions['app_error_rate'] = {
label: 'Error Rate (%)',
type: 'calculated'
};
}
if (!metricsDefinitions['app_request_count']) {
metricsDefinitions['app_request_count'] = {
label: 'Request Count',
type: 'calculated'
};
}
}
// Create UI
createChartContainers(metricsDefinitions);
initCharts(metricsDefinitions);
// Start updates
startDataUpdates();
})
.catch(error => {
if (error.message === 'Unauthorized') {
openPasswordModal();
} else {
alert('Error loading metrics. Please try again.');
}
});
}
// Function to handle metrics visibility changes
function handleMetricsVisibilityChange() {
if (!metricsSection) return;
try {
if (metricsSection.offsetParent !== null) {
// Metrics section is visible
if (!chartsInitialized) {
initializeMetricsUI();
} else {
startDataUpdates();
}
} else {
// Metrics section is hidden
stopDataUpdates();
}
} catch (error) {
console.error("Error handling metrics visibility change:", error);
// Don't show alert here since this might be called repeatedly
// Just log the error to console
}
}
// --- Chart expansion functionality ---
function expandChart(metricName, displayName) {
// Always try to get references to modal elements when function is called
// This ensures we have the most up-to-date references
const chartModal = document.getElementById('chart-modal');
const chartModalTitle = document.getElementById('chart-modal-title');
const closeChartModalBtn = document.querySelector('#chart-modal .close-button');
const closeChartBtn = document.getElementById('close-chart-modal');
// Safety check - if elements not found, show error and exit
if (!chartModal || !chartModalTitle) {
console.error("Chart modal elements not found");
alert("Unable to display expanded chart. Please refresh the page and try again.");
return;
}
// Set the modal title
chartModalTitle.textContent = displayName;
// Show the modal
chartModal.style.display = 'block';
setTimeout(() => chartModal.classList.add('show'), 10);
// Create an expanded version of the chart
const expandedChartCanvas = document.getElementById('expandedChart');
if (!expandedChartCanvas) {
console.error("Expanded chart canvas not found");
return;
}
// Set up close button event listeners if they exist
if (closeChartModalBtn) {
closeChartModalBtn.addEventListener('click', () => closeChartModal(chartModal));
}
if (closeChartBtn) {
closeChartBtn.addEventListener('click', () => closeChartModal(chartModal));
}
const ctx = expandedChartCanvas.getContext('2d');
if (!ctx) {
console.error("Could not get canvas context");
return;
}
// If there's already an expanded chart, destroy it first
if (window.expandedChart) {
try {
window.expandedChart.destroy();
} catch (error) {
console.warn("Error destroying previous chart:", error);
}
}
// Clone the options and data from the original chart
const originalChart = charts[metricName];
if (!originalChart) {
console.error(`Chart for ${metricName} not found`);
return;
}
try {
const chartOptions = JSON.parse(JSON.stringify(originalChart.options));
// Adjust options for the expanded view
chartOptions.maintainAspectRatio = false;
if (chartOptions.scales && chartOptions.scales.y) {
chartOptions.scales.y.ticks.maxTicksLimit = 10; // More ticks for expanded view
}
// Create the expanded chart with cloned data
const chartData = {
datasets: originalChart.data.datasets.map(dataset => ({
...dataset,
data: [...dataset.data],
pointRadius: 3 // Show points in expanded view
}))
};
window.expandedChart = new Chart(ctx, {
type: 'line',
data: chartData,
options: chartOptions
});
} catch (error) {
console.error("Error creating expanded chart:", error);
}
}
// Close modal events
function closeChartModal(modalElement) {
// If called with a specific modal element, use that
// Otherwise try to get it from the DOM
const chartModal = modalElement || document.getElementById('chart-modal');
if (!chartModal) {
console.error("Chart modal element not found");
return;
}
try {
chartModal.classList.remove('show');
setTimeout(() => {
chartModal.style.display = 'none';
}, 300);
} catch (error) {
console.error("Error closing chart modal:", error);
}
}
// --- Initialize everything when DOM is loaded ---
document.addEventListener('DOMContentLoaded', function() {
// Set DOM ready flag
domReady = true;
// Initialize all DOM elements
chartModal = document.getElementById('chart-modal');
chartModalTitle = document.getElementById('chart-modal-title');
closeChartModalBtn = document.querySelector('#chart-modal .close-button');
closeChartBtn = document.getElementById('close-chart-modal');
metricsSection = document.getElementById('metrics-section');
viewMetricsBtn = document.getElementById('view-metrics-btn');
passwordModal = document.getElementById('password-modal');
passwordInput = document.getElementById('metrics-password');
submitPasswordBtn = document.getElementById('submit-password');
passwordError = document.getElementById('password-error');
metricsControls = document.getElementById('metrics-controls');
// Log any missing critical elements
if (!chartModal) console.warn("Chart modal element not found in DOM");
if (!chartModalTitle) console.warn("Chart modal title element not found in DOM");
if (!metricsSection) console.warn("Metrics section element not found in DOM");
if (!passwordModal) console.warn("Password modal element not found in DOM");
// For debugging - log all initialized elements
console.log("DOM elements initialized:", {
chartModal: !!chartModal,
chartModalTitle: !!chartModalTitle,
closeChartModalBtn: !!closeChartModalBtn,
closeChartBtn: !!closeChartBtn,
metricsSection: !!metricsSection,
viewMetricsBtn: !!viewMetricsBtn,
passwordModal: !!passwordModal
});
// Dispatch a custom event to indicate DOM is ready
document.dispatchEvent(new Event('dom-fully-ready'));
// Start server stats check
getServerStats();
setInterval(getServerStats, 30000);
// Apply styles to submit button
if (submitPasswordBtn) submitPasswordBtn.classList.add('submit-button');
// Set up password input event listener
if (passwordInput) {
passwordInput.addEventListener('keyup', function(event) {
if (event.key === 'Enter') {
submitPasswordBtn.click();
}
});
}
// Set up view metrics button
if (viewMetricsBtn) {
viewMetricsBtn.addEventListener('click', function() {
if (getToken()) {
showMetrics();
} else {
openPasswordModal();
}
});
}
// Set up password modal submit button
if (submitPasswordBtn) {
submitPasswordBtn.addEventListener('click', login);
}
// Set up password modal close button
const passwordCloseBtn = document.querySelector('#password-modal .close-button');
if (passwordCloseBtn) {
passwordCloseBtn.addEventListener('click', closePasswordModal);
}
// Close password modal when clicking outside
if (passwordModal) {
passwordModal.addEventListener('click', function(event) {
if (event.target === passwordModal) {
closePasswordModal();
}
});
}
// Check if already authenticated and show metrics if so
if (getToken()) showMetrics();
// Observer for metrics section visibility
if (metricsSection) {
const observer = new MutationObserver(handleMetricsVisibilityChange);
observer.observe(metricsSection, { attributes: true, attributeFilter: ['style'] });
}
// Set up chart modal event listeners if the elements exist
if (chartModal && closeChartModalBtn && closeChartBtn) {
// Close button in the top right
closeChartModalBtn.addEventListener('click', function() {
closeChartModal(chartModal);
});
// Close button at the bottom
closeChartBtn.addEventListener('click', function() {
closeChartModal(chartModal);
});
// Close modal when clicking outside of it
chartModal.addEventListener('click', function(event) {
if (event.target === chartModal) {
closeChartModal(chartModal);
}
});
}
// Close modals with Escape key
document.addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
const chartModal = document.getElementById('chart-modal');
if (chartModal && chartModal.classList.contains('show')) {
closeChartModal(chartModal);
} else if (passwordModal && passwordModal.style.display === 'block') {
closePasswordModal();
}
}
});
});
// Ensure chart elements are initialized when DOM is fully ready
document.addEventListener('dom-fully-ready', function() {
// Get fresh references to chart elements
const chartModalEl = document.getElementById('chart-modal');
const chartModalTitleEl = document.getElementById('chart-modal-title');
const closeChartModalBtnEl = document.querySelector('#chart-modal .close-button');
const closeChartBtnEl = document.getElementById('close-chart-modal');
// Store in global variables for access in other functions
if (chartModalEl) chartModal = chartModalEl;
if (chartModalTitleEl) chartModalTitle = chartModalTitleEl;
if (closeChartModalBtnEl) closeChartModalBtn = closeChartModalBtnEl;
if (closeChartBtnEl) closeChartBtn = closeChartBtnEl;
// Verify modal elements were found
const allElementsFound = !!chartModal && !!chartModalTitle &&
!!closeChartModalBtn && !!closeChartBtn;
console.log("Chart elements initialized on dom-fully-ready event:", {
chartModal: !!chartModal,
chartModalTitle: !!chartModalTitle,
closeChartModalBtn: !!closeChartModalBtn,
closeChartBtn: !!closeChartBtn
});
// Set up event listeners if they weren't set up properly before
if (allElementsFound) {
// Add event listeners for closing the chart modal
closeChartModalBtn.addEventListener('click', () => closeChartModal(chartModal));
closeChartBtn.addEventListener('click', () => closeChartModal(chartModal));
// Close modal when clicking outside
chartModal.addEventListener('click', (event) => {
if (event.target === chartModal) {
closeChartModal(chartModal);
}
});
} else {
console.error("Some chart modal elements are still missing after DOM is fully ready");
}
});
|