-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkubebrowse_benchmark.py
More file actions
1960 lines (1667 loc) · 88.1 KB
/
kubebrowse_benchmark.py
File metadata and controls
1960 lines (1667 loc) · 88.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
KubeBrowse Comprehensive Benchmarking Suite
===========================================
This suite performs load testing and monitoring for the KubeBrowse application
with detailed metrics collection and visualization for white paper analysis.
"""
import asyncio
import threading
import time
import json
import logging
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional
from dataclasses import dataclass, asdict
from concurrent.futures import ThreadPoolExecutor, as_completed
import subprocess
import signal
import sys
import os
import argparse
# Core libraries
import pandas as pd
import numpy as np
# Set matplotlib backend before importing pyplot to avoid GUI issues
import matplotlib
matplotlib.use('Agg') # Use non-interactive backend
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.animation import FuncAnimation
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px
# Kubernetes and monitoring
from kubernetes import client, config
import psutil
import requests
import websocket
from prometheus_client.parser import text_string_to_metric_families
# Selenium for browser automation
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import TimeoutException, WebDriverException
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('kubebrowse_benchmark.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
@dataclass
class BenchmarkConfig:
"""Configuration for benchmark parameters"""
target_url: str = "http://4.156.203.206/"
namespace: str = "browser-sandbox"
max_concurrent_users: int = 50
ramp_up_duration: int = 300 # 5 minutes
test_duration: int = 1800 # 30 minutes
ramp_down_duration: int = 300 # 5 minutes
polling_interval: int = 10 # seconds
websocket_timeout: int = 30
api_timeout: int = 10
save_visualizations: bool = True # Enable periodic visualization saving
save_interval: int = 60 # Save visualizations every 60 seconds
output_dir: str = "benchmark_snapshots" # Directory for saved visualizations
kubeconfig_path: Optional[str] = None # Custom kubeconfig file path
sessions_api_url: Optional[str] = None # Sessions API endpoint URL
sessions_api_insecure: bool = False # Allow insecure HTTPS connections
enable_sessions_monitoring: bool = False # Enable sessions API monitoring
browser_init_wait: int = 2 # Wait time after browser window initiation in seconds
session_start_interval: float = 1.0 # Time interval between starting new sessions in seconds
headless: bool = False # Run browser in headless mode
@dataclass
class MetricPoint:
"""Single metric measurement"""
timestamp: datetime
value: float
metadata: Dict[str, Any] = None
@dataclass
class SessionMetrics:
"""Metrics for a single user session"""
session_id: str
start_time: datetime
end_time: Optional[datetime] = None
pod_creation_time: Optional[float] = None
websocket_connection_time: Optional[float] = None
first_click_response_time: Optional[float] = None
total_api_calls: int = 0
failed_api_calls: int = 0
errors: List[str] = None
console_errors: List[Dict[str, Any]] = None # New field for console errors
def __post_init__(self):
if self.errors is None:
self.errors = []
if self.console_errors is None:
self.console_errors = []
class KubernetesMonitor:
"""Monitor Kubernetes cluster metrics"""
def __init__(self, namespace: str, kubeconfig_path: Optional[str] = None):
self.namespace = namespace
self.kubeconfig_path = kubeconfig_path
try:
if kubeconfig_path:
logger.info(f"Using custom kubeconfig: {kubeconfig_path}")
config.load_kube_config(config_file=kubeconfig_path)
else:
try:
config.load_incluster_config()
logger.info("Using in-cluster configuration")
except:
config.load_kube_config()
logger.info("Using default kubeconfig from kubectl context")
except Exception as e:
logger.error(f"Failed to load Kubernetes configuration: {e}")
raise
self.v1 = client.CoreV1Api()
self.apps_v1 = client.AppsV1Api()
self.metrics_v1beta1 = client.CustomObjectsApi()
def get_node_metrics(self) -> Dict[str, Dict[str, float]]:
"""Get CPU and memory usage for all nodes"""
metrics = {}
try:
nodes = self.v1.list_node()
for node in nodes.items:
node_name = node.metadata.name
# Get node metrics from metrics server
try:
node_metrics = self.metrics_v1beta1.get_cluster_custom_object(
group="metrics.k8s.io",
version="v1beta1",
plural="nodes",
name=node_name
)
cpu_usage = self._parse_cpu(node_metrics['usage']['cpu'])
memory_usage = self._parse_memory(node_metrics['usage']['memory'])
# Get allocatable resources
cpu_allocatable = self._parse_cpu(node.status.allocatable['cpu'])
memory_allocatable = self._parse_memory(node.status.allocatable['memory'])
metrics[node_name] = {
'cpu_usage_cores': cpu_usage,
'memory_usage_bytes': memory_usage,
'cpu_usage_percent': (cpu_usage / cpu_allocatable) * 100,
'memory_usage_percent': (memory_usage / memory_allocatable) * 100,
'cpu_allocatable': cpu_allocatable,
'memory_allocatable': memory_allocatable
}
except Exception as e:
logger.warning(f"Could not get metrics for node {node_name}: {e}")
except Exception as e:
logger.error(f"Error getting node metrics: {e}")
return metrics
def get_pod_metrics(self, label_selector: str = None) -> Dict[str, Dict[str, Any]]:
"""Get pod information and metrics"""
pods_info = {}
try:
if label_selector:
pods = self.v1.list_namespaced_pod(
namespace=self.namespace,
label_selector=label_selector
)
else:
pods = self.v1.list_namespaced_pod(namespace=self.namespace)
for pod in pods.items:
pod_name = pod.metadata.name
# Fix container status checking
container_statuses = pod.status.container_statuses or []
ready_containers = [cs for cs in container_statuses if cs.ready]
total_containers = len(container_statuses)
pods_info[pod_name] = {
'status': pod.status.phase,
'node_name': pod.spec.node_name,
'creation_timestamp': pod.metadata.creation_timestamp,
'labels': pod.metadata.labels or {},
'ready': len(ready_containers) == total_containers and total_containers > 0,
'restart_count': sum(cs.restart_count for cs in container_statuses)
}
# Try to get pod metrics
try:
pod_metrics = self.metrics_v1beta1.get_namespaced_custom_object(
group="metrics.k8s.io",
version="v1beta1",
namespace=self.namespace,
plural="pods",
name=pod_name
)
for container in pod_metrics.get('containers', []):
container_name = container['name']
cpu_usage = self._parse_cpu(container['usage']['cpu'])
memory_usage = self._parse_memory(container['usage']['memory'])
pods_info[pod_name][f'{container_name}_cpu_usage'] = cpu_usage
pods_info[pod_name][f'{container_name}_memory_usage'] = memory_usage
except Exception as e:
logger.debug(f"Could not get metrics for pod {pod_name}: {e}")
except Exception as e:
logger.error(f"Error getting pod metrics: {e}")
return pods_info
def get_hpa_status(self) -> Dict[str, Dict[str, Any]]:
"""Get HPA status for all HPAs in namespace"""
hpa_status = {}
try:
hpa_v2 = client.AutoscalingV2Api()
hpas = hpa_v2.list_namespaced_horizontal_pod_autoscaler(self.namespace)
for hpa in hpas.items:
hpa_name = hpa.metadata.name
hpa_status[hpa_name] = {
'current_replicas': hpa.status.current_replicas or 0,
'desired_replicas': hpa.status.desired_replicas or 0,
'min_replicas': hpa.spec.min_replicas or 0,
'max_replicas': hpa.spec.max_replicas or 0,
'target_ref': hpa.spec.scale_target_ref.name,
'current_metrics': []
}
if hpa.status.current_metrics:
for metric in hpa.status.current_metrics:
if metric.resource:
hpa_status[hpa_name]['current_metrics'].append({
'type': 'resource',
'name': metric.resource.name,
'current_utilization': metric.resource.current.average_utilization
})
elif metric.pods:
hpa_status[hpa_name]['current_metrics'].append({
'type': 'pods',
'name': metric.pods.metric.name,
'current_value': metric.pods.current.average_value
})
except Exception as e:
logger.error(f"Error getting HPA status: {e}")
return hpa_status
@staticmethod
def _parse_cpu(cpu_str: str) -> float:
"""Parse CPU string to cores"""
if cpu_str.endswith('n'):
return float(cpu_str[:-1]) / 1e9
elif cpu_str.endswith('u'):
return float(cpu_str[:-1]) / 1e6
elif cpu_str.endswith('m'):
return float(cpu_str[:-1]) / 1000
else:
return float(cpu_str)
@staticmethod
def _parse_memory(memory_str: str) -> float:
"""Parse memory string to bytes"""
units = {'Ki': 1024, 'Mi': 1024**2, 'Gi': 1024**3, 'Ti': 1024**4}
for unit, multiplier in units.items():
if memory_str.endswith(unit):
return float(memory_str[:-len(unit)]) * multiplier
return float(memory_str)
class WebSocketTester:
"""Test WebSocket connections"""
def __init__(self, url: str, timeout: int = 30):
self.url = url
self.timeout = timeout
self.connection_time = None
self.error = None
def test_connection(self) -> float:
"""Test WebSocket connection and return connection time"""
start_time = time.time()
try:
ws = websocket.create_connection(self.url, timeout=self.timeout)
self.connection_time = time.time() - start_time
ws.close()
return self.connection_time
except Exception as e:
self.error = str(e)
return -1
class BrowserSimulator:
"""Simulate browser sessions using Selenium"""
def __init__(self, config: BenchmarkConfig, session_id: str):
self.config = config
self.session_id = session_id
self.driver = None
self.metrics = SessionMetrics(session_id=session_id, start_time=datetime.now())
def setup_driver(self):
"""Setup Chrome driver with options"""
chrome_options = Options()
if self.config.headless:
chrome_options.add_argument('--headless=new')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
# chrome_options.add_argument('--disable-gpu') # Added above if headless
chrome_options.add_argument('--window-size=1920,1080')
chrome_options.add_argument('--start-maximized') # Start with maximized window
chrome_options.add_argument('--disable-extensions') # Disable extensions for faster startup
chrome_options.add_argument('--disable-plugins') # Disable plugins for faster startup
chrome_options.add_argument('--disable-images') # Disable image loading for faster page loads
# Enable logging to capture console errors
chrome_options.add_argument('--enable-logging')
chrome_options.add_argument('--log-level=0')
chrome_options.set_capability('goog:loggingPrefs', {
'browser': 'ALL',
'driver': 'ALL',
'performance': 'ALL'
})
try:
self.driver = webdriver.Chrome(options=chrome_options)
self.driver.set_page_load_timeout(self.config.api_timeout)
# Minimal wait after browser initiation - prioritize quick start
logger.debug(f"Session {self.session_id}: Browser initiated, starting immediately")
time.sleep(0.5) # Minimal wait for browser stability
return True
except Exception as e:
self.metrics.errors.append(f"Driver setup failed: {e}")
return False
def capture_console_errors(self):
"""Capture console errors from browser logs"""
try:
if not self.driver:
return
# Get browser logs
logs = self.driver.get_log('browser')
for log_entry in logs:
if log_entry['level'] in ['SEVERE', 'WARNING']:
console_error = {
'timestamp': datetime.now().isoformat(),
'level': log_entry['level'],
'message': log_entry['message'],
'source': log_entry.get('source', 'unknown')
}
self.metrics.console_errors.append(console_error)
# Also add to regular errors for backward compatibility
error_msg = f"Console {log_entry['level']}: {log_entry['message']}"
if error_msg not in self.metrics.errors:
self.metrics.errors.append(error_msg)
except Exception as e:
logger.debug(f"Session {self.session_id}: Could not capture console logs: {e}")
def run_session(self) -> SessionMetrics:
"""Run a complete browser session simulation"""
logger.info(f"Session {self.session_id}: Starting session")
if not self.setup_driver():
self.metrics.end_time = datetime.now()
return self.metrics
try:
# Navigate to application immediately
logger.info(f"Session {self.session_id}: Navigating to {self.config.target_url}")
start_time = time.time()
self.driver.get(self.config.target_url)
self.metrics.total_api_calls += 1
# Capture initial console errors after page load
time.sleep(1) # Brief wait for page to load and generate any errors
self.capture_console_errors()
# Wait for page load with shorter timeout
WebDriverWait(self.driver, 5).until(
EC.presence_of_element_located((By.TAG_NAME, "body"))
)
logger.info(f"Session {self.session_id}: Page loaded, starting interactions")
# Start interactions immediately - no additional wait
self._simulate_user_interactions()
except Exception as e:
self.metrics.errors.append(f"Session error: {e}")
self.metrics.failed_api_calls += 1
logger.error(f"Session {self.session_id}: Error - {e}")
finally:
# Capture final console errors before ending session
self.capture_console_errors()
# Don't quit the driver automatically - keep window open
# if self.driver:
# self.driver.quit()
self.metrics.end_time = datetime.now()
return self.metrics
def _simulate_user_interactions(self):
"""Simulate the user interactions from the test"""
try:
# Minimal wait for page stability - prioritize immediate interaction
logger.debug(f"Session {self.session_id}: Starting click simulation immediately")
time.sleep(0.5) # Very short wait for DOM stability
# Click first element if available - start timing immediately
first_click_start = time.time()
logger.info(f"Session {self.session_id}: Attempting first click")
element = WebDriverWait(self.driver, 8).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, ".mb-6:nth-child(1) .ml-3"))
)
element.click()
self.metrics.first_click_response_time = time.time() - first_click_start
self.metrics.total_api_calls += 1
logger.info(f"Session {self.session_id}: First click completed in {self.metrics.first_click_response_time:.3f}s")
# Capture console errors after first click
time.sleep(0.5)
self.capture_console_errors()
# Click first py-2 button
logger.info(f"Session {self.session_id}: Looking for py-2 elements")
py2_elements = self.driver.find_elements(By.CSS_SELECTOR, ".py-2")
if py2_elements and py2_elements[0].is_enabled() and py2_elements[0].is_displayed():
py2_elements[0].click()
self.metrics.total_api_calls += 1
logger.info(f"Session {self.session_id}: Clicked first py-2 button")
# Capture console errors after py-2 click
time.sleep(0.5)
self.capture_console_errors()
# Check for second py-2 button or wait like in selenium test
py2_elements_after = self.driver.find_elements(By.CSS_SELECTOR, ".py-2")
if len(py2_elements_after) > 1:
# Multiple py-2 elements found, click the second one
if py2_elements_after[1].is_enabled() and py2_elements_after[1].is_displayed():
py2_elements_after[1].click()
self.metrics.total_api_calls += 1
logger.info(f"Session {self.session_id}: Successfully clicked second py-2 button")
# Capture console errors after second click
time.sleep(0.5)
self.capture_console_errors()
else:
# Keep window open like in selenium test - use proper wait mechanism
logger.info(f"Session {self.session_id}: Keeping browser window open...")
# Use a proper wait mechanism instead of extremely large sleep
try:
# Wait for user to manually close or for a reasonable timeout
# This prevents the timestamp overflow issue
wait_time = 3600 # 1 hour maximum wait
start_wait = time.time()
while time.time() - start_wait < wait_time:
if not self.driver or not self.driver.service.is_connectable():
break
time.sleep(30) # Check every 30 seconds if browser is still open
except Exception as e:
logger.info(f"Session {self.session_id}: Wait interrupted: {e}")
else:
logger.warning(f"Session {self.session_id}: No py-2 elements found or not clickable")
except TimeoutException:
self.metrics.errors.append("Timeout waiting for elements")
self.metrics.failed_api_calls += 1
logger.error(f"Session {self.session_id}: Timeout waiting for elements")
except Exception as e:
self.metrics.errors.append(f"Interaction error - {e}")
self.metrics.failed_api_calls += 1
logger.error(f"Session {self.session_id}: Interaction error - {e}")
def close_driver(self):
"""Manually close the driver when needed"""
if self.driver:
self.driver.quit()
self.driver = None
class SessionsAPIMonitor:
"""Monitor active sessions via API endpoint"""
def __init__(self, api_url: str, insecure: bool = False, timeout: int = 10):
self.api_url = api_url
self.timeout = timeout
self.session = requests.Session()
if insecure:
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
self.session.verify = False
def get_active_sessions(self) -> Dict[str, Any]:
"""Get active sessions from API endpoint"""
try:
response = self.session.get(self.api_url, timeout=self.timeout)
response.raise_for_status()
data = response.json()
return {
'active_sessions': data.get('active_sessions', 0),
'connection_ids': data.get('connection_ids', []),
'total_connections': len(data.get('connection_ids', [])),
'timestamp': datetime.now()
}
except requests.exceptions.RequestException as e:
logger.warning(f"Failed to fetch sessions data from API: {e}")
return {
'active_sessions': 0,
'connection_ids': [],
'total_connections': 0,
'timestamp': datetime.now(),
'error': str(e)
}
except Exception as e:
logger.error(f"Error parsing sessions API response: {e}")
return {
'active_sessions': 0,
'connection_ids': [],
'total_connections': 0,
'timestamp': datetime.now(),
'error': str(e)
}
class MetricsCollector:
"""Collect and store all metrics during benchmark"""
def __init__(self, config: BenchmarkConfig):
self.config = config
self.k8s_monitor = KubernetesMonitor(config.namespace, config.kubeconfig_path)
self.sessions_monitor = None
if config.enable_sessions_monitoring and config.sessions_api_url:
self.sessions_monitor = SessionsAPIMonitor(
config.sessions_api_url,
config.sessions_api_insecure,
config.api_timeout
)
self.metrics_data = {
'timestamps': [],
'node_metrics': {},
'pod_counts': [],
'hpa_metrics': {},
'session_metrics': [],
'websocket_metrics': [],
'api_latency': [],
'api_sessions': [] # New field for API sessions data
}
self.running = False
def start_collection(self):
"""Start metrics collection in background thread"""
self.running = True
self.collection_thread = threading.Thread(target=self._collect_loop)
self.collection_thread.daemon = True
self.collection_thread.start()
def stop_collection(self):
"""Stop metrics collection"""
self.running = False
if hasattr(self, 'collection_thread'):
self.collection_thread.join(timeout=5)
def _collect_loop(self):
"""Main collection loop"""
while self.running:
timestamp = datetime.now()
self.metrics_data['timestamps'].append(timestamp)
try:
# Collect node metrics
node_metrics = self.k8s_monitor.get_node_metrics()
for node_name, metrics in node_metrics.items():
if node_name not in self.metrics_data['node_metrics']:
self.metrics_data['node_metrics'][node_name] = {
'cpu_usage': [], 'memory_usage': [],
'cpu_percent': [], 'memory_percent': []
}
self.metrics_data['node_metrics'][node_name]['cpu_usage'].append(
metrics['cpu_usage_cores']
)
self.metrics_data['node_metrics'][node_name]['memory_usage'].append(
metrics['memory_usage_bytes'] / (1024**3) # GB
)
self.metrics_data['node_metrics'][node_name]['cpu_percent'].append(
metrics['cpu_usage_percent']
)
self.metrics_data['node_metrics'][node_name]['memory_percent'].append(
metrics['memory_usage_percent']
)
# Collect pod counts
browser_pods = self.k8s_monitor.get_pod_metrics(
label_selector="app=browser-sandbox-test"
)
running_pods = sum(1 for pod in browser_pods.values()
if pod['status'] == 'Running')
self.metrics_data['pod_counts'].append(running_pods)
# Collect sessions API data
if self.sessions_monitor:
sessions_data = self.sessions_monitor.get_active_sessions()
self.metrics_data['api_sessions'].append(sessions_data)
# Collect HPA metrics
hpa_status = self.k8s_monitor.get_hpa_status()
for hpa_name, status in hpa_status.items():
if hpa_name not in self.metrics_data['hpa_metrics']:
self.metrics_data['hpa_metrics'][hpa_name] = {
'current_replicas': [], 'desired_replicas': [],
'cpu_utilization': [], 'memory_utilization': []
}
self.metrics_data['hpa_metrics'][hpa_name]['current_replicas'].append(
status['current_replicas']
)
self.metrics_data['hpa_metrics'][hpa_name]['desired_replicas'].append(
status['desired_replicas']
)
# Extract CPU and memory utilization
cpu_util = next((m['current_utilization'] for m in status['current_metrics']
if m['type'] == 'resource' and m['name'] == 'cpu'), 0)
memory_util = next((m['current_utilization'] for m in status['current_metrics']
if m['type'] == 'resource' and m['name'] == 'memory'), 0)
self.metrics_data['hpa_metrics'][hpa_name]['cpu_utilization'].append(cpu_util)
self.metrics_data['hpa_metrics'][hpa_name]['memory_utilization'].append(memory_util)
logger.debug(f"Collected metrics at {timestamp}")
except Exception as e:
logger.error(f"Error collecting metrics: {e}")
time.sleep(self.config.polling_interval)
def add_session_metrics(self, session_metrics: SessionMetrics):
"""Add session metrics to collection"""
self.metrics_data['session_metrics'].append(asdict(session_metrics))
def save_metrics(self, filename: str = None):
"""Save all collected metrics to file"""
if filename is None:
filename = f"kubebrowse_metrics_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
# Convert datetime objects to strings for JSON serialization
serializable_data = self._make_serializable(self.metrics_data.copy())
with open(filename, 'w') as f:
json.dump(serializable_data, f, indent=2)
logger.info(f"Metrics saved to {filename}")
return filename
def _make_serializable(self, obj):
"""Convert datetime objects to strings for JSON serialization"""
if isinstance(obj, datetime):
return obj.isoformat()
elif isinstance(obj, dict):
return {key: self._make_serializable(value) for key, value in obj.items()}
elif isinstance(obj, list):
return [self._make_serializable(item) for item in obj]
else:
return obj
class PeriodicVisualizationSaver:
"""Save visualizations at periodic intervals during benchmark"""
def __init__(self, metrics_collector: MetricsCollector, config: BenchmarkConfig):
self.metrics_collector = metrics_collector
self.config = config
self.running = False
self.save_counter = 0
self._lock = threading.Lock() # Add thread lock for safety
# Create output directory
os.makedirs(self.config.output_dir, exist_ok=True)
def start_saving(self):
"""Start periodic visualization saving in background thread"""
if not self.config.save_visualizations:
return
self.running = True
self.save_thread = threading.Thread(target=self._save_loop)
self.save_thread.daemon = True
self.save_thread.start()
logger.info(f"Started periodic visualization saving every {self.config.save_interval} seconds")
def stop_saving(self):
"""Stop periodic visualization saving"""
self.running = False
if hasattr(self, 'save_thread'):
self.save_thread.join(timeout=5)
def _save_loop(self):
"""Main saving loop"""
while self.running:
time.sleep(self.config.save_interval)
if self.running: # Check again after sleep
self._save_current_visualizations()
def _save_current_visualizations(self):
"""Save current state visualizations"""
with self._lock: # Thread safety
try:
self.save_counter += 1
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
snapshot_dir = f"{self.config.output_dir}/snapshot_{self.save_counter:03d}_{timestamp}"
os.makedirs(snapshot_dir, exist_ok=True)
data = self.metrics_collector.metrics_data
# Only save if we have data
if not data['timestamps']:
logger.debug("No data available for visualization yet")
return
timestamps = data['timestamps']
# Ensure matplotlib is using non-interactive backend
plt.ioff()
matplotlib.use('Agg')
# Create enhanced dashboard visualization with console errors
try:
fig, axes = plt.subplots(3, 3, figsize=(20, 15))
fig.suptitle(f'KubeBrowse Comprehensive Performance Dashboard - {timestamp}', fontsize=16, fontweight='bold')
# Node CPU Usage
axes[0, 0].set_title('Node CPU Usage (%)')
axes[0, 0].set_xlabel('Time Points')
axes[0, 0].set_ylabel('CPU %')
axes[0, 0].grid(True, alpha=0.3)
if data['node_metrics']:
time_points = list(range(len(timestamps)))
for node_name, metrics in data['node_metrics'].items():
if metrics['cpu_percent']:
axes[0, 0].plot(time_points[-len(metrics['cpu_percent']):],
metrics['cpu_percent'],
label=f'{node_name}', marker='o', markersize=3)
axes[0, 0].legend()
# Node Memory Usage
axes[0, 1].set_title('Node Memory Usage (%)')
axes[0, 1].set_xlabel('Time Points')
axes[0, 1].set_ylabel('Memory %')
axes[0, 1].grid(True, alpha=0.3)
if data['node_metrics']:
time_points = list(range(len(timestamps)))
for node_name, metrics in data['node_metrics'].items():
if metrics['memory_percent']:
axes[0, 1].plot(time_points[-len(metrics['memory_percent']):],
metrics['memory_percent'],
label=f'{node_name}', marker='s', markersize=3)
axes[0, 1].legend()
# Running Pods
axes[0, 2].set_title('Running Pods')
axes[0, 2].set_xlabel('Time Points')
axes[0, 2].set_ylabel('Pod Count')
axes[0, 2].grid(True, alpha=0.3)
if data['pod_counts']:
time_points = list(range(len(data['pod_counts'])))
axes[0, 2].plot(time_points, data['pod_counts'],
color='blue', marker='o', markersize=4)
axes[0, 2].fill_between(time_points, data['pod_counts'], alpha=0.3)
# API Active Sessions (NEW)
axes[1, 0].set_title('API Active Sessions')
axes[1, 0].set_xlabel('Time Points')
axes[1, 0].set_ylabel('Active Sessions')
axes[1, 0].grid(True, alpha=0.3)
if data['api_sessions']:
time_points = list(range(len(data['api_sessions'])))
active_sessions = [s.get('active_sessions', 0) for s in data['api_sessions']]
total_connections = [s.get('total_connections', 0) for s in data['api_sessions']]
axes[1, 0].plot(time_points, active_sessions,
color='green', marker='o', markersize=4, label='Active Sessions')
axes[1, 0].plot(time_points, total_connections,
color='orange', marker='s', markersize=4, label='Total Connections')
axes[1, 0].legend()
axes[1, 0].fill_between(time_points, active_sessions, alpha=0.3, color='green')
# Session Summary
axes[1, 1].set_title('Session Summary')
axes[1, 1].set_xlabel('Status')
axes[1, 1].set_ylabel('Count')
axes[1, 1].grid(True, alpha=0.3)
if data['session_metrics']:
total_sessions = len(data['session_metrics'])
successful_sessions = sum(1 for s in data['session_metrics']
if s.get('failed_api_calls', 0) == 0)
failed_sessions = total_sessions - successful_sessions
axes[1, 1].bar(['Successful', 'Failed'],
[successful_sessions, failed_sessions],
color=['green', 'red'], alpha=0.7)
# Response Times
axes[1, 2].set_title('Recent Response Times')
axes[1, 2].set_xlabel('Recent Sessions')
axes[1, 2].set_ylabel('Response Time (s)')
axes[1, 2].grid(True, alpha=0.3)
if data['session_metrics']:
recent_sessions = data['session_metrics'][-20:]
response_times = [s.get('first_click_response_time', 0)
for s in recent_sessions
if s.get('first_click_response_time') is not None]
if response_times:
axes[1, 2].plot(range(len(response_times)), response_times,
'go-', markersize=4)
axes[1, 2].axhline(y=np.mean(response_times),
color='red', linestyle='--',
label=f'Avg: {np.mean(response_times):.2f}s')
axes[1, 2].legend()
# HPA Replica Counts (NEW)
axes[2, 0].set_title('HPA Replica Counts')
axes[2, 0].set_xlabel('Time Points')
axes[2, 0].set_ylabel('Replicas')
axes[2, 0].grid(True, alpha=0.3)
if data['hpa_metrics']:
time_points = list(range(len(timestamps)))
for hpa_name, metrics in data['hpa_metrics'].items():
if metrics['current_replicas']:
axes[2, 0].plot(time_points[-len(metrics['current_replicas']):],
metrics['current_replicas'],
label=f'{hpa_name} Current', marker='o', markersize=3)
axes[2, 0].plot(time_points[-len(metrics['desired_replicas']):],
metrics['desired_replicas'],
label=f'{hpa_name} Desired', marker='s', markersize=3, linestyle='--')
axes[2, 0].legend()
# API vs Browser Sessions Correlation (NEW)
axes[2, 1].set_title('API vs Browser Sessions')
axes[2, 1].set_xlabel('Time Points')
axes[2, 1].set_ylabel('Session Count')
axes[2, 1].grid(True, alpha=0.3)
if data['api_sessions'] and data['session_metrics']:
time_points = list(range(min(len(data['api_sessions']), len(timestamps))))
api_sessions = [data['api_sessions'][i].get('active_sessions', 0) for i in range(len(time_points))]
# Calculate browser sessions over time (cumulative)
browser_sessions_count = []
for i in range(len(time_points)):
# Count sessions active at this time point
if i < len(timestamps):
current_time = timestamps[i]
active_browser_sessions = sum(1 for s in data['session_metrics']
if datetime.fromisoformat(s['start_time']) <= current_time and
(s.get('end_time') is None or datetime.fromisoformat(s['end_time']) >= current_time))
browser_sessions_count.append(active_browser_sessions)
else:
browser_sessions_count.append(0)
axes[2, 1].plot(time_points, api_sessions,
color='green', marker='o', markersize=4, label='API Active Sessions')
axes[2, 1].plot(time_points, browser_sessions_count,
color='blue', marker='s', markersize=4, label='Browser Sessions')
axes[2, 1].legend()
# Success Rate Over Time
axes[2, 2].set_title('Success Rate Over Time')
axes[2, 2].set_xlabel('Time Buckets')
axes[2, 2].set_ylabel('Success Rate (%)')
axes[2, 2].grid(True, alpha=0.3)
axes[2, 2].set_ylim(0, 105)
if data['session_metrics'] and len(data['session_metrics']) > 5:
bucket_size = max(1, len(data['session_metrics']) // 10)
success_rates = []
for i in range(0, len(data['session_metrics']), bucket_size):
bucket = data['session_metrics'][i:i+bucket_size]
total_calls = sum(s.get('total_api_calls', 0) for s in bucket)
failed_calls = sum(s.get('failed_api_calls', 0) for s in bucket)
if total_calls > 0:
success_rate = ((total_calls - failed_calls) / total_calls) * 100
success_rates.append(success_rate)
if success_rates:
axes[2, 2].plot(range(len(success_rates)), success_rates,
'b-o', markersize=4)
axes[2, 2].axhline(y=np.mean(success_rates),
color='green', linestyle='--',
label=f'Avg: {np.mean(success_rates):.1f}%')
axes[2, 2].legend()
plt.tight_layout()
# Save the dashboard
dashboard_file = f"{snapshot_dir}/dashboard.png"
plt.savefig(dashboard_file, dpi=300, bbox_inches='tight', facecolor='white', edgecolor='none')
# Properly close the figure to free memory
plt.close(fig)
plt.clf() # Clear any remaining state
except Exception as plot_error:
logger.error(f"Error creating plot: {plot_error}")
# Try to clean up any partial plot state
try:
plt.close('all')
plt.clf()
except:
pass
# Save metrics data snapshot
metrics_file = f"{snapshot_dir}/metrics_snapshot.json"
serializable_data = self.metrics_collector._make_serializable(data.copy())
with open(metrics_file, 'w') as f:
json.dump(serializable_data, f, indent=2)
# Create enhanced summary file with console errors
summary_file = f"{snapshot_dir}/summary.txt"
with open(summary_file, 'w') as f:
f.write(f"Benchmark Snapshot - {timestamp}\n")
f.write("=" * 40 + "\n\n")
f.write(f"Timestamp: {timestamp}\n")
f.write(f"Data points collected: {len(timestamps)}\n")
f.write(f"Total sessions: {len(data['session_metrics'])}\n")
f.write(f"Running pods: {data['pod_counts'][-1] if data['pod_counts'] else 0}\n")
# Add API sessions summary
if data['api_sessions']:
latest_api_data = data['api_sessions'][-1]
f.write(f"API Active Sessions: {latest_api_data.get('active_sessions', 0)}\n")
f.write(f"API Total Connections: {latest_api_data.get('total_connections', 0)}\n")
if data['session_metrics']:
successful = sum(1 for s in data['session_metrics']
if s.get('failed_api_calls', 0) == 0)
f.write(f"Successful sessions: {successful}\n")
f.write(f"Failed sessions: {len(data['session_metrics']) - successful}\n")
response_times = [s.get('first_click_response_time')
for s in data['session_metrics']
if s.get('first_click_response_time') is not None]
if response_times:
f.write(f"Average response time: {np.mean(response_times):.3f}s\n")
f.write(f"Max response time: {max(response_times):.3f}s\n")
# Add console errors summary
if data['session_metrics']:
total_console_errors = sum(len(s.get('console_errors', [])) for s in data['session_metrics'])
total_severe_errors = sum(
sum(1 for err in s.get('console_errors', []) if err.get('level') == 'SEVERE')
for s in data['session_metrics']
)
f.write(f"Total console errors: {total_console_errors}\n")
f.write(f"Severe console errors: {total_severe_errors}\n")
if total_console_errors > 0:
f.write(f"Avg console errors per session: {total_console_errors / len(data['session_metrics']):.1f}\n")
logger.info(f"Saved visualization snapshot {self.save_counter} to {snapshot_dir}")