-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathlf_interop_speedtest.py
More file actions
2050 lines (1737 loc) · 77.7 KB
/
lf_interop_speedtest.py
File metadata and controls
2050 lines (1737 loc) · 77.7 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
'''
NAME: lf_interop_speedtest.py
PURPOSE:
The lf_interop_speedtest.py script enables real-world WiFi speed testing for laptop-based clients
(Linux, Windows, macOS) and Android mobile devices. iOS is not supported.
Instead, it focuses on measuring actual end-user experience by capturing metrics such as download/upload speed,
latency (ping). The script uses the Speedtest.net service (via browser automation for laptops) to run the tests.
TO PERFORM SPEED TEST:
EXAMPLE-1:
Run a default speed test using browser-based automation (Selenium)
./lf_interop_speedtest.py \
--mgr 192.168.204.74 \
--device_list 1.10,1.12 \
--instance_name SAMPLE_TEST \
--iteration 1 \
--upstream_port eth2 \
--cleanup
EXAMPLE-2:
Run speed test on robot with each coordinate and rotation
./lf_interop_speedtest.py \
--mgr 192.168.204.75 \
--device_list 1.10,1.12 \
--instance_name SAMPLE_TEST \
--iteration 1 \
--robot_test \
--coordinate 1,2 \
--rotation 0,90 \
--robot_ip 127.0.0.1:5000 \
--upstream_port eth2 \
--cleanup
EXAMPLE-3:
Run speed test on robot with each coordinate without rotation
./lf_interop_speedtest.py \
--mgr 192.168.204.75 \
--device_list 1.10,1.12 \
--instance_name SAMPLE_TEST \
--iteration 1 \
--robot_test \
--coordinate 1,2 \
--robot_ip 127.0.0.1:5000 \
--upstream_port eth2 \
--cleanup
'''
import json
import sys
import os
import csv
import time
import shutil
import importlib
import logging
import paramiko
import argparse
import pandas as pd
from datetime import datetime
import subprocess
import threading
try:
from tabulate import tabulate
except ImportError:
tabulate = None
if 'py-json' not in sys.path:
sys.path.append(os.path.join(os.path.abspath('..'), 'py-json'))
from lf_graph import lf_bar_graph
from lf_report import lf_report
try:
pass
from lf_base_robo import RobotClass # REAL
except ImportError:
print("[WARN] lf_base_robo not found")
# from lf_robo_base_class import RobotClass # Fake
logger = logging.getLogger(__name__)
if sys.version_info[0] != 3:
print("This script requires Python3")
exit()
realm = importlib.import_module("py-json.realm")
Realm = realm.Realm
class SpeedTest(Realm):
def __init__(
self,
manager_ip=None,
port=8080,
device_list=None,
instance="Speed_Test_Report",
iteration=1,
do_interopability=False,
type='ookla',
result_dir=None,
_debug_on=False,
robot_test=False,
robot_ip=None,
coordinate=None,
rotation=None,
upstream_port=None):
super().__init__(
lfclient_host=manager_ip,
debug_=_debug_on)
self.manager_ip = manager_ip
self.manager_port = port
self.upstream_port = upstream_port
self.device_list = device_list
self.instance = instance
self.iteration = iteration
self.do_interopability = do_interopability
self.result_dir = result_dir
self.type = type
self.devices_data = {}
self.android_data = {}
self.laptop_data = {}
self.generic_endps_profile = self.new_generic_endp_profile()
self.generic_endps_profile.type = 'generic'
self.generic_endps_profile.cmd = ' '
self.result_json = {}
self.stop_time = None
self.start_time = None
self.device_info = {}
self._ingest_lock = threading.Lock()
self._flask_thread = None
self._post_url = None
self.robot_test = robot_test
self.robot_ip = robot_ip
self.robot_port = 5000
self.coordinate = coordinate
self.rotation = rotation
self.coordinate_list = coordinate.split(',') if coordinate else []
if self.rotation is not None:
self.rotation_list = rotation.split(',') if rotation else []
else:
self.rotation_list = None
self.current_coordinate = None
self.current_rotation = None
self.robot_iteration_count = 0
self.total_robot_tests = 0
if self.robot_test:
if self.rotation_list and self.rotation_list[0] != "":
self.total_robot_tests = len(self.coordinate_list) * len(self.rotation_list)
else:
self.total_robot_tests = len(self.coordinate_list)
if self.coordinate is not None:
base_dir = os.path.dirname(os.path.dirname(self.result_dir))
nav_data = os.path.join(base_dir, 'nav_data.json')
with open(nav_data, "w") as file:
json.dump({}, file)
self.robot_obj = RobotClass(robo_ip=self.robot_ip) # REAL
self.robot_obj.nav_data_path = nav_data # REAL
# self.robot_obj = RobotClass() # Fake
# self.robot_obj.result_directory=os.path.dirname(nav_data) # Fake
# self.robot_obj.robo_ip = f"{self.robot_ip}" # Fake
self.robot_obj.runtime_dir = self.result_dir
self.robot_obj.testname = self.instance
else:
self.robot_test = False
if self.upstream_port:
self.upstream_port = self.change_port_to_ip(self.upstream_port)
self._post_url = f"http://{self.upstream_port}:5050/api/speedtest"
else:
self._post_url = f"http://{self.manager_ip}:5050/api/speedtest"
self._start_ingest_server()
# reporting variable
self.selected_device_type = set()
self.selected_resources = None
self.ip_hostname = {}
self.result_dict = {
'ip': [],
'hostname': [],
'download_speed': [],
'upload_speed': [],
'download_lat': [],
'upload_lat': []
}
self.iteration_dict = {}
def get_expected_post_ips(self):
"""Get list of IP addresses expected to POST speed test results to the ingest server.
Returns:
list: List of IP addresses configured with --post_url in their test commands
"""
want = []
for info in self.devices_data.values():
cmd = (info.get('cmd') or '')
ip = (info.get('ip') or '')
if ip and '--post_url' in cmd:
want.append(ip)
# de-dup (stable)
seen, out = set(), []
for ip in want:
if ip not in seen:
seen.add(ip)
out.append(ip)
return out
def has_post_for(self, ip):
"""Check if speed test results have been received from a specific IP address.
Args:
ip (str): IP address to check for received results
Returns:
bool: True if results have been received, False otherwise
"""
k = ip.replace('.', '_')
return (k in self.result_json) or (ip in self.result_json)
def write_results_to_csv(self, current_iter, csv_file):
"""Write speed test results to CSV file for a specific iteration.
Args:
current_iter (int): Current iteration number
csv_file (str): Path to CSV file for storing results
"""
csv_exists = os.path.isfile(csv_file)
csv_data = []
table_data = []
received = {}
for raw_ip, data in self.result_json.items():
ip = raw_ip.replace('_', '.')
received[ip] = {
"download": data.get("download", "N/A"),
"upload": data.get("upload", "N/A"),
"Idle Latency": data.get("Idle Latency", "N/A"),
"Download Latency": data.get("Download Latency", "N/A"),
"Upload Latency": data.get("Upload Latency", "N/A"),
}
expected_ips = list(self.ip_hostname.keys()) or list(self.device_info.keys())
for ip, data in received.items():
dev_type = self.device_info.get(ip, "N/A")
hostname_safe = self.ip_hostname.get(ip, ip)
download = data["download"]
upload = data["upload"]
idle_latency = data["Idle Latency"]
down_latency = data["Download Latency"]
up_latency = data["Upload Latency"]
csv_data.append([
current_iter, self.iteration, ip, dev_type,
download, upload, idle_latency, down_latency, up_latency
])
table_data.append([
current_iter, self.iteration, ip, dev_type,
download, upload, idle_latency, down_latency, up_latency
])
self.result_dict['ip'].append(ip)
self.result_dict['hostname'].append(hostname_safe)
def _num(x):
try:
return float(str(x).split()[0])
except Exception:
return 0.0
self.result_dict['download_speed'].append(_num(download))
self.result_dict['upload_speed'].append(_num(upload))
self.result_dict['download_lat'].append(_num(down_latency))
self.result_dict['upload_lat'].append(_num(up_latency))
missing_ips = [ip for ip in expected_ips if ip not in received]
for ip in missing_ips:
dev_type = self.device_info.get(ip, "N/A")
hostname_safe = self.ip_hostname.get(ip, ip)
csv_data.append([
current_iter, self.iteration, ip, dev_type,
"N/A", "N/A", "N/A", "N/A", "N/A"
])
table_data.append([
current_iter, self.iteration, ip, dev_type,
"N/A", "N/A", "N/A", "N/A", "N/A"
])
self.result_dict['ip'].append(ip)
self.result_dict['hostname'].append(hostname_safe)
self.result_dict['download_speed'].append(0.0)
self.result_dict['upload_speed'].append(0.0)
self.result_dict['download_lat'].append(0.0)
self.result_dict['upload_lat'].append(0.0)
self.iteration_dict[current_iter] = self.result_dict
self.result_dict = {
'ip': [],
'hostname': [],
'download_speed': [],
'upload_speed': [],
'download_lat': [],
'upload_lat': []
}
with open(csv_file, "a", newline="") as csvfile:
writer = csv.writer(csvfile)
if not csv_exists:
writer.writerow([
"Iteration", "Total Iterations", "IP", "Device Type",
"Download", "Upload", "Idle Latency", "Download Latency", "Upload Latency"
])
writer.writerows(csv_data)
print(f"\n Speedtest Results for Iteration {current_iter}")
if tabulate:
print(tabulate(
table_data,
headers=[
"Iteration", "Total Iterations", "IP", "Device Type",
"Download", "Upload", "Idle Latency", "Download Latency", "Upload Latency"],
tablefmt="fancy_grid",
disable_numparse=True
))
else:
headers = [
"Iteration", "Total Iterations", "IP", "Device Type",
"Download", "Upload", "Idle Latency", "Download Latency", "Upload Latency"]
print("\t".join(headers))
for row in table_data:
print("\t".join(str(item) for item in row))
if missing_ips:
print(f"[NOTE] No data received for iteration {current_iter} from: {', '.join(missing_ips)} (filled with N/A)")
print("=" * 158)
def write_robot_results_to_csv(self, test_number, csv_file):
"""Write robot-assisted test results to CSV file with robot metadata.
Args:
test_number (int): Current robot test iteration number
csv_file (str): Path to CSV file for storing results
"""
csv_exists = os.path.isfile(csv_file)
csv_data = []
table_data = []
# Normalize keys we received this test
received = {}
for raw_ip, data in self.result_json.items():
ip = raw_ip.replace('_', '.')
received[ip] = {
"download": data.get("download", "N/A"),
"upload": data.get("upload", "N/A"),
"Idle Latency": data.get("Idle Latency", "N/A"),
"Download Latency": data.get("Download Latency", "N/A"),
"Upload Latency": data.get("Upload Latency", "N/A"),
}
# Expected devices
expected_ips = list(self.ip_hostname.keys()) or list(self.device_info.keys())
# Emit rows for devices
for ip, data in received.items():
dev_type = self.device_info.get(ip, "N/A")
download = data["download"]
upload = data["upload"]
idle_latency = data["Idle Latency"]
down_latency = data["Download Latency"]
up_latency = data["Upload Latency"]
# Add robot-specific columns
csv_data.append([
test_number,
self.total_robot_tests,
self.current_coordinate,
self.current_rotation,
ip,
dev_type,
download,
upload,
idle_latency,
down_latency,
up_latency,
"RUNNING"
])
# Add to table data
table_data.append([
test_number,
self.total_robot_tests,
self.current_coordinate,
self.current_rotation,
ip,
dev_type,
download,
upload,
idle_latency,
down_latency,
up_latency,
"RUNNING"
])
# Handle missing devices
missing_ips = [ip for ip in expected_ips if ip not in received]
for ip in missing_ips:
dev_type = self.device_info.get(ip, "N/A")
csv_data.append([
test_number,
self.total_robot_tests,
self.current_coordinate,
self.current_rotation,
ip,
dev_type,
"N/A", "N/A", "N/A", "N/A", "N/A",
"RUNNING"
])
table_data.append([
test_number,
self.total_robot_tests,
self.current_coordinate,
self.current_rotation,
ip,
dev_type,
"N/A", "N/A", "N/A", "N/A", "N/A",
"RUNNING"
])
# Append to CSV
with open(csv_file, "a", newline="") as csvfile:
writer = csv.writer(csvfile)
if not csv_exists:
writer.writerow([
"Robot Test Number", "Total Robot Tests", "Coordinate", "Rotation",
"IP", "Device Type", "Download", "Upload",
"Idle Latency", "Download Latency", "Upload Latency",
"Status"
])
writer.writerows(csv_data)
# Print table
print(f"\n Robot Speedtest Results for Test #{test_number}")
if tabulate:
print(tabulate(
table_data,
headers=[
"Test#", "Total", "Coordinate", "Rotation", "IP", "Device Type",
"Download", "Upload", "Idle Latency", "Download Latency", "Upload Latency",
"Status"
],
tablefmt="fancy_grid",
disable_numparse=True
))
else:
headers = [
"Test#", "Total", "Coordinate", "Rotation", "IP", "Device Type",
"Download", "Upload", "Idle Latency", "Download Latency", "Upload Latency",
"Status"
]
print("\t".join(headers))
for row in table_data:
print("\t".join(str(item) for item in row))
if missing_ips:
print(f"[NOTE] No data received for robot test {test_number} from: {', '.join(missing_ips)}")
print("=" * 158)
def store_robot_results_in_iteration_dict(self, test_number):
"""Store robot test results in iteration dictionary for report generation.
Args:
test_number (int): Current robot test iteration number
"""
# Initialize the result_dict for this test
self.result_dict = {
'ip': [],
'hostname': [],
'download_speed': [],
'upload_speed': [],
'download_lat': [],
'upload_lat': []
}
# Process received results
received = {}
for raw_ip, data in self.result_json.items():
ip = raw_ip.replace('_', '.')
received[ip] = {
"download": data.get("download", "N/A"),
"upload": data.get("upload", "N/A"),
"Idle Latency": data.get("Idle Latency", "N/A"),
"Download Latency": data.get("Download Latency", "N/A"),
"Upload Latency": data.get("Upload Latency", "N/A"),
}
# Expected devices
expected_ips = list(self.ip_hostname.keys()) or list(self.device_info.keys())
# Store data for devices that reported
for ip, data in received.items():
# dev_type = self.device_info.get(ip, "N/A")
hostname_safe = self.ip_hostname.get(ip, ip)
download = data["download"]
upload = data["upload"]
# idle_latency = data["Idle Latency"]
down_latency = data["Download Latency"]
up_latency = data["Upload Latency"]
# Accumulate into per-iter dicts for graphs/tables
self.result_dict['ip'].append(ip)
self.result_dict['hostname'].append(hostname_safe)
def _num(x):
try:
# Handles values like "24.2 Mbps" or "114 ms" or "N/A"
return float(str(x).split()[0])
except Exception:
return 0.0
self.result_dict['download_speed'].append(_num(download))
self.result_dict['upload_speed'].append(_num(upload))
self.result_dict['download_lat'].append(_num(down_latency))
self.result_dict['upload_lat'].append(_num(up_latency))
# Handle missing devices
missing_ips = [ip for ip in expected_ips if ip not in received]
for ip in missing_ips:
self.device_info.get(ip, "N/A")
hostname_safe = self.ip_hostname.get(ip, ip)
# For graphs: use zeros so categories & lengths stay aligned
self.result_dict['ip'].append(ip)
self.result_dict['hostname'].append(hostname_safe)
self.result_dict['download_speed'].append(0.0)
self.result_dict['upload_speed'].append(0.0)
self.result_dict['download_lat'].append(0.0)
self.result_dict['upload_lat'].append(0.0)
# Store in iteration_dict using test_number as key
self.iteration_dict[test_number] = self.result_dict.copy()
def perform_single_robot_test(self, test_number, csv_file):
"""Execute a single speed test iteration for robot-assisted testing.
Args:
test_number (int): Current robot test iteration number
csv_file (str): Path to CSV file for storing results
"""
print(f"Starting speed test for robot test #{test_number}")
self.start_generic()
print(f"Test started at {self.start_time}")
time.sleep(50) # Speedtest duration wait time
self.stop_generic()
# time.sleep(20)
# Wait for posts from all expected devices
expected_ips = self.get_expected_post_ips()
deadline = time.time() + 120
while time.time() < deadline:
got = [ip for ip in expected_ips if self.has_post_for(ip)]
if len(got) >= len(expected_ips):
break
time.sleep(1)
# Store results in iteration_dict for report generation
self.store_robot_results_in_iteration_dict(test_number)
# Write results with robot metadata
self.write_robot_results_to_csv(test_number, csv_file)
self.result_json = {}
def perform_robot_testing(self, csv_file):
"""Execute robot-assisted testing across all coordinates and rotations.
Args:
csv_file (str): Path to CSV file for storing robot test results
"""
test_count = 0
# Condition 1: Both coordinates and rotations provided
if self.rotation_list and self.rotation_list[0] != "":
for coord in self.coordinate_list:
coord = coord.strip()
print(f"Moving to coordinate: {coord}")
robo_moved, abort = self.robot_obj.move_to_coordinate(coord)
if robo_moved:
for angle in self.rotation_list:
pause_coord, test_stopped_by_user = self.robot_obj.wait_for_battery(self.cleanup)
if pause_coord:
print("Robot battery low. Pausing at current location to charge.")
exit(0)
# angle = angle.strip()
print(f"Rotating to angle: {angle}")
robo_rotated = self.robot_obj.rotate_angle(angle)
if robo_rotated:
test_count += 1
self.current_coordinate = coord
self.current_rotation = angle
self.robot_iteration_count = test_count
print(f"Starting robot test {test_count}/{self.total_robot_tests}")
print(f"Coordinate: {coord}, Rotation: {angle}")
# Perform the speed test
self.perform_single_robot_test(test_count, csv_file)
else:
print(f"Failed to rotate to angle {angle}")
else:
print(f"Failed to move to coordinate {coord}")
# Condition 2: Only coordinates provided (no rotations)
else:
for coord in self.coordinate_list:
pause_coord, test_stopped_by_user = self.robot_obj.wait_for_battery(self.cleanup)
if pause_coord:
print("Robot battery low. Pausing at current location to charge.")
exit(0)
coord = coord.strip()
print(f"Moving to coordinate: {coord}")
robo_moved = self.robot_obj.move_to_coordinate(coord)
if robo_moved:
test_count += 1
self.current_coordinate = coord
self.current_rotation = "None" # No rotation
self.robot_iteration_count = test_count
print(f"Starting robot test {test_count}/{self.total_robot_tests}")
print(f"Coordinate: {coord}, Rotation: None")
# Perform the speed test
self.perform_single_robot_test(test_count, csv_file)
else:
print(f"Failed to move to coordinate {coord}")
print(f"Completed {test_count} robot tests")
def change_port_to_ip(self, upstream_port):
if upstream_port.count('.') != 3:
target_port_list = self.name_to_eid(upstream_port)
shelf, resource, port, _ = target_port_list
try:
target_port_ip = self.json_get(f'/port/{shelf}/{resource}/{port}?fields=ip')['interface']['ip']
upstream_port = target_port_ip
except Exception:
logging.warning(f'The upstream port is not an ethernet port. Proceeding with the given upstream_port {upstream_port}.')
logging.info(f"Upstream port IP {upstream_port}")
else:
logging.info(f"Upstream port IP {upstream_port}")
return upstream_port
def _kill_existing_process(self):
"""
Kill any existing speedtest process using port 5050.
NOTE:
Use this only because port 5050 is dedicated for this speedtest Flask ingest server.
"""
try:
print("[INFO] Checking and clearing existing process on port 5050...")
# Preferred Linux way
result = subprocess.run(
["fuser", "-k", "5050/tcp"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
if result.returncode == 0:
print("[INFO] Existing process on port 5050 killed successfully.")
else:
print("[INFO] No existing process found on port 5050.")
time.sleep(1)
except FileNotFoundError:
print("[WARN] fuser not found. Trying lsof + kill fallback.")
try:
result = subprocess.run(
["lsof", "-ti", ":5050"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
pids = [pid.strip() for pid in result.stdout.splitlines() if pid.strip()]
if not pids:
print("[INFO] No existing process found on port 5050.")
return
for pid in pids:
print(f"[INFO] Killing PID {pid} using port 5050")
subprocess.run(["kill", "-9", pid])
time.sleep(1)
except Exception as e:
print(f"[WARN] Could not clear port 5050 using lsof fallback: {e}")
except Exception as e:
print(f"[WARN] Could not clear port 5050: {e}")
def _start_ingest_server(self):
"""Start Flask server for ingesting speed test results via HTTP POST.
Creates a local server on port 5050 to receive test results from clients.
"""
# Kill Exisiting process with 5050 port
self._kill_existing_process()
try:
from flask import Flask, request, jsonify
except Exception:
print("[WARN] Flask not installed; ingest disabled.")
return
app = Flask(__name__)
parent = self
@app.get("/api/health")
def health():
return jsonify({"ok": True, "ts": time.time()}), 200
@app.route("/api/speedtest", methods=["POST"])
def _ingest():
try:
payload = request.get_json(force=True) or {}
ip = (payload.get("ip") or "").strip()
host = payload.get("hostname")
key = ip.replace('.', '_') if ip else (payload.get("device_id") or payload.get("serial"))
rec = {
"download": f"{payload.get('download_mbps', '0')} Mbps",
"upload": f"{payload.get('upload_mbps', '0')} Mbps",
"Idle Latency": f"{payload.get('idle_ms', '0')} ms",
"Download Latency": f"{payload.get('download_latency_ms', '0')} ms",
"Upload Latency": f"{payload.get('upload_latency_ms', '0')} ms",
"source": "ingest"
}
print('[POST] got payload for key:', key, rec)
with parent._ingest_lock:
parent.result_json[key] = rec
if ip and host:
parent.ip_hostname[ip] = host
print("[INGEST] stored under key:", key)
print('Current result_json:', parent.result_json)
return jsonify({"stored": True}), 200
except Exception as e:
return jsonify({"stored": False, "error": str(e)}), 400
@app.get("/api/data")
def data():
return jsonify(parent.result_json), 200
def run():
# IMPORTANT: bind to all interfaces
app.run(host='0.0.0.0', port=5050, debug=False, use_reloader=False, threaded=True)
import threading
self._flask_thread = threading.Thread(target=run, daemon=True)
self._flask_thread.start()
def _ssh_connect(self, host, username, password):
"""Establish SSH connection to remote host.
Args:
host (str): Remote host IP address or hostname
username (str): SSH username
password (str): SSH password
Returns:
paramiko.SSHClient: Connected SSH client object
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=username, password=password)
return ssh
def get_device_data(self, resource_data):
"""
get_devices_data: Properly collect device data for all compatible devices
"""
resource_ids = set(resource_data.keys())
ports = self.json_get('/ports/all').get('interfaces', [])
adb_devices_list = self.json_get('/adb/all')
adb_by_resource = {}
devices = adb_devices_list.get("devices", {})
# Process ADB devices
if isinstance(devices, list):
for dev in devices:
if not isinstance(dev, dict):
continue
key = next(iter(dev))
info = dev[key]
rid = info.get("resource-id")
if rid:
adb_by_resource[rid] = {
'name': info.get('name'),
'serial': info.get('name') or '',
'shelf_resource': (info.get('name') or '').rsplit('.', 1)[0] if '.' in (info.get('name') or '') else '',
'user_name': info.get('user-name'),
'wifi_mac': info.get('wifi mac'),
'device_type': info.get('device-type', 'Android'),
# 'ssid': info.get('ssid_rpt') or info.get('ssid', ''),
# 'channel': info.get('freq', '')
}
elif isinstance(devices, dict):
rid = devices.get("resource-id")
if rid:
adb_by_resource[rid] = {
'name': devices.get('name'),
'serial': devices.get('name') or '',
'shelf_resource': (devices.get('name') or '').rsplit('.', 1)[0] if '.' in (devices.get('name') or '') else '',
'user_name': devices.get('user-name'),
'wifi_mac': devices.get('wifi mac'),
'device_type': devices.get('device-type', 'Android'),
# 'ssid': devices.get('ssid_rpt') or devices.get('ssid', ''),
# 'channel': devices.get('freq', '')
}
devices_data = {}
# First, collect all ports for each resource to find the best port for each device
resource_ports = {}
for pds in ports:
port_id = next(iter(pds))
pdata = pds[port_id]
parts = port_id.split('.')
if len(parts) < 3:
continue
resource = '.'.join(parts[:2]) # e.g., '1.5'
# Only process ports belonging to selected resources
if resource not in resource_ids:
continue
if resource not in resource_ports:
resource_ports[resource] = []
resource_ports[resource].append((port_id, pdata))
# Now process each selected resource
for resource_id in resource_ids:
res = resource_data.get(resource_id, {})
if not res:
continue
dev_type = res.get('device type', '').strip()
ctrl_ip = res.get('ctrl-ip')
box_hostname = res.get('hostname')
# Skip if no control IP
if not ctrl_ip:
continue
# Determine if this is a compatible device
compatible_devices = ['Linux/Interop', 'Windows', 'Mac OS', 'Android']
if dev_type not in compatible_devices:
continue
# For Android devices
if dev_type == 'Android':
adb_info = adb_by_resource.get(resource_id)
if adb_info:
serial_key = adb_info.get('serial', '').split('.')[-1] if '.' in adb_info.get('serial', '') else adb_info.get('serial', '')
if serial_key:
devices_data[serial_key] = {
'device type': 'Android',
'cmd': None,
'ip': ctrl_ip,
'port': adb_info.get('shelf_resource', resource_id),
'serial': serial_key,
'hostname': adb_info.get('user_name') or res.get('hostname') or box_hostname,
# 'ssid': adb_info.get('ssid', ''),
# 'channel': str(adb_info.get('channel', '')),
'mac': adb_info.get('wifi_mac', ''),
}
if ctrl_ip and adb_info.get('user_name'):
self.ip_hostname[ctrl_ip] = adb_info['user_name']
# For laptop devices
else:
# Find the best port for this device
best_port = None
best_port_data = None
if resource_id in resource_ports:
for port_id, pdata in resource_ports[resource_id]:
# Skip phantom or down ports
if pdata.get('phantom', True) or pdata.get('down', True):
continue
# Check if port has IP
interface_ip = pdata.get('ip')
if not interface_ip or interface_ip == '0.0.0.0':
continue
# Prefer WLAN ports for laptops
port_type = pdata.get('port type', '')
if 'WIFI' in port_type or 'wlan' in port_id.lower():
best_port = port_id
best_port_data = pdata
break # Prefer WiFi over Ethernet
elif not best_port: # If no WiFi found, take first Ethernet
best_port = port_id
best_port_data = pdata
if best_port and best_port_data:
interface_ip = best_port_data.get('ip')
# Extract SSID and channel
# ssid = best_port_data.get('ssid', '')
# channel_raw = best_port_data.get('channel', '')
devices_data[best_port] = {
'device type': dev_type,
'cmd': None,
'ip': interface_ip,
'serial': None,
'hostname': box_hostname,
# 'ssid': ssid,
# 'channel': channel,
'mac': best_port_data.get('mac', ''),
'port': resource_id,
}
# For reporting lookups
# if ctrl_ip and box_hostname:
# self.ip_hostname[ctrl_ip] = box_hostname
if interface_ip and box_hostname:
self.ip_hostname[interface_ip] = box_hostname
# Store device info for reporting
self.device_info[interface_ip] = dev_type
self.devices_data = devices_data
# print(f"DEBUG: Found {len(devices_data)} devices in devices_data")
for key, value in devices_data.items():
print(f" {key}: {value}", end="\n\n")
return devices_data
def filter_devices(self, resources_list):
"""Filter LANforge resources to include only compatible device types."""
resource_data = {}
for resource_data_dict in resources_list:
resource_id = list(resource_data_dict.keys())[0]
resource_data_dict = resource_data_dict[resource_id]
# More flexible device type matching
dev_type = resource_data_dict.get('device type', '').strip()
compatible_types = ['Linux/Interop', 'Windows', 'Mac OS', 'Android',
'Linux', 'Mac', 'Ubuntu', 'Windows 10', 'Windows 11']
# Check if device type contains any compatible string
if any(compat_type in dev_type for compat_type in compatible_types):
resource_data[resource_id] = resource_data_dict
return resource_data
def get_resource_data(self):
"""Retrieve and select device resources from LANforge controller.
Prompts user for device selection if device_list is not pre-configured.
"""
resources_list = self.json_get("/resource/all")["resources"]
resource_data = self.filter_devices(resources_list)