Repository navigation
Expand file tree
/
Copy pathlf_interop_qos.py
More file actions
executable file
·3999 lines (3768 loc) · 219 KB
/
Copy pathlf_interop_qos.py
File metadata and controls
executable file
·3999 lines (3768 loc) · 219 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
"""
NAME: lf_interop_qos.py
PURPOSE: lf_interop_qos.py will provide the available devices and allows user to run the qos traffic
with particular tos on particular devices in upload, download directions.
NOTES: 1. Use './lf_interop_qos.py --help' to see command line usage and options
2. Please pass tos in CAPITALS as shown :"BK,VI,BE,VO"
3. Please enter the download or upload rate in bps
4. After passing cli, a list will be displayed on terminal which contains available resources to run test.
The following sentence will be displayed
Enter the desired resources to run the test:
Please enter the port numbers seperated by commas ','.
Example:
Enter the desired resources to run the test:1.10,1.11,1.12,1.13,1.202,1.203,1.303
EXAMPLES: # Command Line Interface to run download scenario with tos : Voice
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.209.223 --mgr_port 8080 --ssid Cisco
--passwd cisco@123 --security wpa2 --upstream eth1 --test_duration 1m --download 1000000 --upload 0
--traffic_type lf_udp --tos "VO"
# Command Line Interface to run download scenario with tos : Voice and Video
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.209.223 --mgr_port 8080 --ssid Cisco
--passwd cisco@123 --security wpa2 --upstream eth1 --test_duration 1m --download 1000000 --upload 0
--traffic_type lf_udp --tos "VO,VI"
# Load scenario with tos : Background, Besteffort, Video and Voice
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.209.223 --mgr_port 8080 --ssid Cisco
--passwd cisco@123 --security wpa2 --upstream eth1 --test_duration 1m --download 0 --upload 1000000
--traffic_type lf_udp --tos "BK,BE,VI,VO"
# Command Line Interface to run bi-directional scenario with tos : Video and Voice
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.209.223 --mgr_port 8080 --ssid Cisco
--passwd cisco@123 --security wpa2 --upstream eth1 --test_duration 1m --download 1000000 --upload 1000000
--traffic_type lf_udp --tos "VI,VO"
# Command Line Interface to run upload scenario by setting the same expected Pass/Fail value for all devices
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.244.97 --test_duration 1m --upstream_port eth1 --upload 1000000
--mgr_port 8080 --traffic_type lf_udp --tos "VI,VO,BE,BK" --ssid DLI-LPC992 --passwd Password@123
--security wpa2 --expected_passfail_value 0.3
# Command Line Interface to run upload scenario by setting device specific Pass/Fail values in the csv file
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.244.97 --test_duration 1m --upstream_port eth1 --upload 1000000
--mgr_port 8080 --traffic_type lf_udp --tos "VI,VO,BE,BK" --ssid DLI-LPC992 --passwd Password@123
--security wpa2 --device_csv_name device_config.csv
# Command Line Interface to run upload scenario by Configuring Real Devices with SSID, Password, and Security
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.244.97 --test_duration 1m --upstream_port eth1 --upload 1000000
--mgr_port 8080 --traffic_type lf_udp --tos "VI,VO,BE,BK" --ssid DLI-LPC992 --passwd Password@123
--security wpa2 --config
# Command Line Interface to run upload scenario by setting the same expected Pass/Fail value for all devices with configuration
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.244.97 --test_duration 1m --upstream_port eth1 --upload 1000000
--mgr_port 8080 --traffic_type lf_udp --tos "VI,VO,BE,BK" --ssid DLI-LPC992 --passwd Password@123
--security wpa2 --config --expected_passfail_value 0.3
# Command Line Interface to run upload scenario by Configuring Devices in Groups with Specific Profiles
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.244.97 --test_duration 1m --upstream_port eth1 --upload 1000000
--mgr_port 8080 --traffic_type lf_udp --tos "VI,VO,BE,BK" --file_name g219 --group_name grp1 --profile_name Open3
# Command Line Interface to run upload scenario by Configuring Devices in Groups with Specific Profiles with expected Pass/Fail values
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.244.97 --test_duration 1m --upstream_port eth1 --upload 1000000
--mgr_port 8080 --traffic_type lf_udp --tos "VI,VO,BE,BK" --file_name g219 --group_name grp1 --profile_name Open3
--expected_passfail_value 0.3 --wait_time 30
# Command Line Interface to run the Test along with IOT without device list
./lf_interop_qos.py --mgr 192.168.207.78 --upstream_port eth1 --security None --ssid "NETGEAR_2G_wpa2" --passwd "" --traffic_type lf_tcp --download 10000000
--upload 0 --test_duration 1m --tos VO,VI,BE,BK --device_list 1.5,1.13
--iot_test --iot_testname "IotTest" --iot_delay 5
# Command Line Interface to run the Test along with IOT with device list
./lf_interop_qos.py --mgr 192.168.207.78 --upstream_port eth1 --security None --ssid "NETGEAR_2G_wpa2" --passwd "" --traffic_type lf_tcp --download 10000000
--upload 0 --test_duration 1m --tos VO,VI,BE,BK --device_list 1.13 --iot_test --iot_ip 127.0.0.1 --iot_port 8000 --iot_iterations 1
--iot_delay 5 --iot_device_list "switch.smart_plug_1_socket_1" --iot_testname "QosWithIot" --iot_increment ""
# Command Line Interface to run the QOS Test along with Robot by enabling rotation at the specified coordinates
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.207.78 --test_duration 1m --upstream_port eth1 --upload 1000000 --mgr_port 8080 --traffic_type lf_udp
--tos "VI,VO,BE,BK" --ssid DLI-LPC992 --passwd Password@123 --security wpa2 --robot_ip 192.168.204.101 --rotation 30,90 --coordinate 3,4 --robot_test
# Command Line Interface to run the QOS Test along with Robot at the specified coordinates without any rotation
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.207.78 --test_duration 1m --upstream_port eth1 --upload 1000000 --mgr_port 8080 --traffic_type lf_udp
--tos "VI,VO,BE,BK" --ssid DLI-LPC992 --passwd Password@123 --security wpa2 --robot_ip 192.168.204.101 --coordinate 3,4 --robot_test
# Command Line Interface to run the QOS Test along with Robot by enabling band steering at the specified coordinates.
./lf_interop_qos.py --ap_name Cisco --mgr 192.168.207.78 --test_duration 1m --upstream_port eth1 --upload 1000000 --mgr_port 8080 --traffic_type lf_udp
--tos "VI,VO,BE,BK" --ssid DLI-LPC992 --passwd Password@123 --security wpa2 --robot_ip 192.168.204.101 --coordinate 3,4 --robot_test --do_bandsteering
--cycles 1 --bssids 7a:1d:35:c8:da:b9
SCRIPT_CLASSIFICATION:
Test
SCRIPT_CATEGORIES:
Performance, Functional, Report Generation
STATUS: BETA RELEASE
VERIFIED_ON:
Working date: 26/07/2023
Build version: 5.4.8
Kernel version: 6.2.16+
LICENSE: Free to distribute and modify. LANforge systems must be licensed.
Copyright (C) 2020-2026 Candela Technologies Inc
"""
from lf_base_robo import RobotClass
import time
import argparse
import sys
import os
import pandas as pd
import importlib
import copy
import logging
import json
import shutil
import asyncio
import csv
import re
from datetime import datetime, timedelta
from collections import defaultdict
import threading
from collections import OrderedDict, Counter
if sys.version_info[0] != 3:
print("This script requires Python 3")
exit(1)
if 'py-json' not in sys.path:
sys.path.append(os.path.join(os.path.abspath('..'), 'py-json'))
# For whatever reason this import is required to run....but isn't directly used
from LANforge import LFUtils # noqa: F401
realm = importlib.import_module("py-json.realm")
Realm = realm.Realm
from lf_report import lf_report # noqa: E402
from lf_graph import lf_bar_graph, lf_bar_graph_horizontal # noqa: E402
logger = logging.getLogger(__name__)
lf_logger_config = importlib.import_module("py-scripts.lf_logger_config")
# Importing DeviceConfig to apply device configurations for ADB devices and laptops
DeviceConfig = importlib.import_module("py-scripts.DeviceConfig")
iot_scripts_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../local/interop-webGUI/IoT/scripts/"))
if os.path.exists(iot_scripts_path):
sys.path.insert(0, iot_scripts_path)
from test_automation import Automation # noqa: E402
class ThroughputQOS(Realm):
def __init__(self,
tos,
ssid=None,
security=None,
password=None,
name_prefix=None,
upstream=None,
num_stations=10,
host="localhost",
file_name=None,
profile_name=None,
group_name=None,
port=8080,
test_name=None,
device_list=None,
result_dir=None,
ap_name="",
traffic_type=None,
direction="",
side_a_min_rate=0, side_a_max_rate=0,
side_b_min_rate=56, side_b_max_rate=0,
number_template="00000",
test_duration="2m",
use_ht160=False,
_debug_on=False,
_exit_on_error=False,
_exit_on_fail=False,
dowebgui=False,
ip="localhost",
user_list=None,
real_client_list=None,
real_client_list1=None,
hw_list=None,
laptop_list=None,
android_list=None,
mac_list=None,
windows_list=None,
linux_list=None,
total_resources_list=None,
working_resources_list=None,
hostname_list=None,
username_list=None,
eid_list=None,
devices_available=None,
input_devices_list=None,
mac_id1_list=None,
mac_id_list=None,
eap_method=None,
eap_identity=None,
ieee80211=None,
ieee80211u=None,
ieee80211w=None,
enable_pkc=None,
bss_transition=None,
power_save=None,
disable_ofdma=None,
roam_ft_ds=None,
key_management=None,
pairwise=None,
private_key=None,
ca_cert=None,
client_cert=None,
pk_passwd=None,
pac_file=None,
config=False,
csv_direction=None,
expected_passfail_val=None,
csv_name=None,
wait_time=60,
get_live_view=False,
total_floors=0,
robot_test=False,
robot_ip=None,
coordinate=None,
rotation=None,
rotation_enabled=None,
angle_list=None,
do_bandsteering=False,
cycles=None,
bssids=None,
duration_to_skip=None):
super().__init__(lfclient_host=host,
lfclient_port=port)
self.ssid_list = []
self.upstream = upstream
self.host = host
self.port = port
self.test_name = test_name
self.device_list = device_list if device_list else []
self.result_dir = result_dir
self.ssid = ssid
self.security = security
self.password = password
self.num_stations = num_stations
self.ap_name = ap_name
self.traffic_type = traffic_type
self.direction = direction
self.tos = tos.split(",")
self.number_template = number_template
self.debug = _debug_on
self.name_prefix = name_prefix
self.test_duration = test_duration
self.station_profile = self.new_station_profile()
self.cx_profile = self.new_l3_cx_profile()
self.station_profile.lfclient_url = self.lfclient_url
self.station_profile.ssid = self.ssid
self.station_profile.ssid_pass = self.password
self.station_profile.security = self.security
self.station_profile.number_template_ = self.number_template
self.station_profile.debug = self.debug
self.station_profile.use_ht160 = use_ht160
self.cx_profile.host = self.host
self.cx_profile.port = self.port
self.cx_profile.name_prefix = self.name_prefix
self.cx_profile.side_a_min_bps = side_a_min_rate
self.cx_profile.side_a_max_bps = side_a_max_rate
self.cx_profile.side_b_min_bps = side_b_min_rate
self.cx_profile.side_b_max_bps = side_b_max_rate
self.hw_list = hw_list if hw_list else []
self.laptop_list = laptop_list if laptop_list else []
self.android_list = android_list if android_list else []
self.mac_list = mac_list if mac_list else []
self.windows_list = windows_list if windows_list else []
self.linux_list = linux_list if linux_list else []
self.total_resources_list = total_resources_list if total_resources_list else []
self.working_resources_list = working_resources_list if working_resources_list else []
self.hostname_list = hostname_list if hostname_list else []
self.username_list = username_list if username_list else []
self.eid_list = eid_list if eid_list else []
self.devices_available = devices_available if devices_available else []
self.input_devices_list = input_devices_list if input_devices_list else []
self.real_client_list = real_client_list if real_client_list else []
self.real_client_list1 = real_client_list1 if real_client_list1 else []
self.user_list = user_list if user_list else []
self.mac_id_list = mac_id_list if mac_id_list else []
self.mac_id1_list = mac_id1_list if mac_id1_list else []
self.dowebgui = dowebgui
self.ip = ip
self.device_found = False
self.profile_name = profile_name
self.file_name = file_name
self.group_name = group_name
self.eap_method = eap_method
self.eap_identity = eap_identity
self.ieee80211 = ieee80211
self.ieee80211u = ieee80211u
self.ieee80211w = ieee80211w
self.enable_pkc = enable_pkc
self.bss_transition = bss_transition
self.power_save = power_save
self.disable_ofdma = disable_ofdma
self.roam_ft_ds = roam_ft_ds
self.key_management = key_management
self.pairwise = pairwise
self.private_key = private_key
self.ca_cert = ca_cert
self.client_cert = client_cert
self.pk_passwd = pk_passwd
self.pac_file = pac_file
self.csv_direction = csv_direction
self.expected_passfail_val = expected_passfail_val
self.csv_name = csv_name
self.wait_time = wait_time
self.group_device_map = {}
self.config = config
self.get_live_view = get_live_view
self.total_floors = total_floors
self.qos_data = {}
self.throughput_data = []
self.band_steering_df = []
self.missing_cx_logged = set()
self.missing_signal_logged = set()
self.cx_endpoint_lookup_failed_logged = set()
self.cx_not_running_logged = set()
self.monitor_start_time = None
self.device_issue_log = []
self.actual_monitoring_duration_seconds = 0
self.all_devices_stopped = False
self.do_bandsteering = do_bandsteering
self.bssids = bssids.split(",") if bssids else []
# Initializing robot test parameters
self.robot_test = robot_test
self.cycles = cycles
if robot_test:
if self.dowebgui:
self.get_live_view = True if not self.do_bandsteering else False
self.robot_ip = robot_ip
self.coordinate = coordinate
self.rotation = rotation
self.test_stopped_by_user = False
self.coordinate_list = coordinate.split(',')
self.rotation_list = rotation.split(',')
self.current_coordinate = None
self.current_angle = None
self.angle_list = angle_list
self.rotation_enabled = rotation_enabled
self.robot = RobotClass(robo_ip=self.robot_ip, angle_list=self.angle_list)
self.last_rotated_angles = []
self.charge_point_name = None
self.robot.coordinate_list = self.coordinate_list
self.robot.time_to_reach = duration_to_skip
self.robot.total_cycles = cycles
def os_type(self):
response = self.json_get("/resource/all")
for key, value in response.items():
if key == "resources":
for element in value:
for _a, b in element.items():
if "Apple" in b['hw version']:
if b['kernel'] == '':
self.hw_list.append('iOS')
else:
self.hw_list.append(b['hw version'])
else:
self.hw_list.append(b['hw version'])
for hw_version in self.hw_list:
if "Win" in hw_version:
self.windows_list.append(hw_version)
elif "Linux" in hw_version:
self.linux_list.append(hw_version)
elif "Apple" in hw_version:
self.mac_list.append(hw_version)
elif "iOS" in hw_version:
self.mac_list.append(hw_version)
else:
if hw_version != "":
self.android_list.append(hw_version)
self.laptop_list = self.windows_list + self.linux_list + self.mac_list
def phantom_check(self):
obj = DeviceConfig.DeviceConfig(lanforge_ip=self.host, file_name=self.file_name, wait_time=self.wait_time)
config_devices = {}
upstream = self.change_port_to_ip(self.upstream)
config_dict = {
'ssid': self.ssid,
'passwd': self.password,
'enc': self.security,
'eap_method': self.eap_method,
'eap_identity': self.eap_identity,
'ieee80211': self.ieee80211,
'ieee80211u': self.ieee80211u,
'ieee80211w': self.ieee80211w,
'enable_pkc': self.enable_pkc,
'bss_transition': self.bss_transition,
'power_save': self.power_save,
'disable_ofdma': self.disable_ofdma,
'roam_ft_ds': self.roam_ft_ds,
'key_management': self.key_management,
'pairwise': self.pairwise,
'private_key': self.private_key,
'ca_cert': self.ca_cert,
'client_cert': self.client_cert,
'pk_passwd': self.pk_passwd,
'pac_file': self.pac_file,
'server_ip': upstream,
}
# Case 1: Group name, file name, and profile name are provided
if self.group_name and self.file_name and self.device_list == [] and self.profile_name:
selected_groups = self.group_name.split(',')
selected_profiles = self.profile_name.split(',')
for i in range(len(selected_groups)):
config_devices[selected_groups[i]] = selected_profiles[i]
obj.initiate_group()
self.group_device_map = obj.get_groups_devices(data=selected_groups, groupdevmap=True)
# Configure devices in the selected group with the selected profile
self.device_list = asyncio.run(obj.connectivity(config=config_devices, upstream=upstream))
# Case 2: Device list is already provided
elif self.device_list != []:
all_devices = obj.get_all_devices()
self.device_list = self.device_list.split(',')
# If config is false, the test will exclude all inactive devices
if self.config:
# If config is True, attempt to bring up all devices in the list and perform tests on those that become active
# Configure devices in the device list with the provided SSID, Password and Security
self.device_list = asyncio.run(obj.connectivity(device_list=self.device_list, wifi_config=config_dict))
# Case 3: Device list is empty but config flag is True — prompt the user to input device details for configuration
elif self.device_list == [] and self.config:
all_devices = obj.get_all_devices()
device_list = []
for device in all_devices:
if device["type"] == 'laptop':
device_list.append(device["shelf"] + '.' + device["resource"] + " " + device["hostname"])
else:
device_list.append(device["eid"] + " " + device["serial"])
logger.info(f"Available devices: {device_list}")
self.device_list = input("Enter the desired resources to run the test:").split(',')
if self.config:
# Configure devices entered by the user with the provided SSID, Password and Security
self.device_list = asyncio.run(obj.connectivity(device_list=self.device_list, wifi_config=config_dict))
port_eid_list, same_eid_list, original_port_list = [], [], []
response = self.json_get("/resource/all")
for key, value in response.items():
if key == "resources":
for element in value:
for _a, b in element.items():
if b['phantom'] is False:
self.working_resources_list.append(b["hw version"])
if "Win" in b['hw version']:
self.eid_list.append(b['eid'])
self.windows_list.append(b['hw version'])
self.devices_available.append(b['eid'] + " " + 'Win' + " " + b['hostname'])
elif "Linux" in b['hw version']:
if ('ct' not in b['hostname']):
if ('lf' not in b['hostname']):
self.eid_list.append(b['eid'])
self.linux_list.append(b['hw version'])
self.devices_available.append(b['eid'] + " " + 'Lin' + " " + b['hostname'])
elif "Apple" in b['hw version']:
if b['kernel'] == '':
self.eid_list.append(b['eid'])
self.mac_list.append(b['hw version'])
self.devices_available.append(b['eid'] + " " + 'iOS' + " " + b['hostname'])
else:
self.eid_list.append(b['eid'])
self.mac_list.append(b['hw version'])
self.devices_available.append(b['eid'] + " " + 'Mac' + " " + b['hostname'])
else:
self.eid_list.append(b['eid'])
self.android_list.append(b['hw version'])
self.devices_available.append(b['eid'] + " " + 'android' + " " + b['user'])
# All the available resources are fetched from resource mgr tab ----
response_port = self.json_get("/port/all")
for interface in response_port['interfaces']:
for port, port_data in interface.items():
if (not port_data['phantom'] and not port_data['down'] and port_data['parent dev'] == "wiphy0" and port_data['alias'] != 'p2p0'):
for id in self.eid_list:
if (id + '.' in port):
original_port_list.append(port)
port_eid_list.append(str(self.name_to_eid(port)[0]) + '.' + str(self.name_to_eid(port)[1]))
self.mac_id1_list.append(str(self.name_to_eid(port)[0]) + '.' + str(self.name_to_eid(port)[1]) + ' ' + port_data['mac'])
for i in range(len(self.eid_list)):
for j in range(len(port_eid_list)):
if self.eid_list[i] == port_eid_list[j]:
same_eid_list.append(self.eid_list[i])
same_eid_list = [_eid + ' ' for _eid in same_eid_list]
# All the available ports from port manager are fetched from port manager tab ---
for eid in same_eid_list:
for device in self.devices_available:
if eid in device:
print(eid + ' ' + device)
if device not in self.user_list:
self.user_list.append(device)
# checking for the availability of selected devices to run test
obj.adb_obj.get_devices()
logging.info(self.user_list)
# Case 4: Config is False, no device list is provided, and no group is selected
if self.config is False and len(self.device_list) == 0 and self.group_name is None:
logger.info("AVAILABLE DEVICES TO RUN TEST : {}".format(self.user_list))
# Prompt the user to manually input devices for running the test
self.device_list = input("Enter the desired resources to run the test:").split(',')
if len(self.device_list) == 0:
devices_list = ""
if len(self.device_list) != 0:
devices_list = self.device_list
available_list = []
not_available = []
for input_device in devices_list:
found = False
for device in self.devices_available:
if input_device + " " in device:
available_list.append(input_device)
found = True
break
if found is False:
not_available.append(input_device)
logger.warning(input_device + " is not available to run test")
if len(available_list) > 0:
logger.info("Test is initiated on devices: {}".format(available_list))
devices_list = ','.join(available_list)
self.device_found = True
else:
devices_list = ""
self.device_found = False
logger.warning("Test can not be initiated on any selected devices")
if devices_list == "" or devices_list == ",":
logger.error("Selected Devices are not available in the lanforge. devices_list: '%s'", devices_list)
exit(1)
resource_eid_list = devices_list.split(',')
logger.info(f"devices list {devices_list}")
resource_eid_list2 = [eid + ' ' for eid in resource_eid_list]
resource_eid_list1 = [resource + '.' for resource in resource_eid_list]
logger.info(f"resource eid list {resource_eid_list}")
# User desired eids are fetched ---
for eid in resource_eid_list1:
for ports_m in original_port_list:
if eid in ports_m:
self.input_devices_list.append(ports_m)
logger.info("INPUT DEVICES LIST {}".format(self.input_devices_list))
# user desired real client list 1.1 wlan0 ---
for i in resource_eid_list2:
for j in range(len(self.user_list)):
if i in self.user_list[j]:
if self.user_list[j] not in self.real_client_list:
self.real_client_list.append(self.user_list[j])
self.real_client_list1.append((self.user_list[j])[:25])
logger.info("REAL CLIENT LIST{}".format(self.real_client_list))
self.num_stations = len(self.real_client_list)
for eid in resource_eid_list2:
for i in self.mac_id1_list:
if eid in i:
self.mac_id_list.append(i.split(' ', 1)[1])
logger.info("MAC ID LIST {}" .format(self.mac_id_list))
return self.input_devices_list, self.real_client_list, self.mac_id_list, config_devices
# user desired real client list 1.1 OnePlus, 1.1 Apple for report generation ---
def start(self, print_pass=False, print_fail=False):
if len(self.cx_profile.created_cx) > 0:
for cx in self.cx_profile.created_cx.keys():
req_url = "cli-json/set_cx_report_timer"
data = {
"test_mgr": "all",
"cx_name": cx,
"milliseconds": 1000
}
self.json_post(req_url, data)
self.cx_profile.start_cx()
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 updating_webui_runningjson(self, obj):
data = {}
with open(self.result_dir + "/../../Running_instances/{}_{}_running.json".format(self.host, self.test_name),
'r') as file:
data = json.load(file)
for key in obj:
data[key] = obj[key]
with open(self.result_dir + "/../../Running_instances/{}_{}_running.json".format(self.host, self.test_name),
'w') as file:
json.dump(data, file, indent=4)
def stop(self):
self.cx_profile.stop_cx()
self.station_profile.admin_down()
def pre_cleanup(self):
# self.cx_profile.cleanup_prefix()
self.cx_profile.cleanup()
def cleanup(self):
self.cx_profile.cleanup()
def port_label_from_cx_name(self, cx_name):
"""Extracts the leading resource id (e.g. "1.16") from a CX name for device issue reports."""
match = re.match(r'^[0-9]+\.[0-9]+', cx_name)
return match.group() if match else cx_name
def record_device_issue(self, device, issue, api_response=None):
"""Records a timestamped device issue, later written to the clients_issue.csv."""
self.device_issue_log.append({
"Time": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
"Device": device,
"Issue": issue,
"API Response": api_response if api_response is not None else '',
})
@staticmethod
def _parse_float(value):
"""Converts value to float, returning 0.0 when it is blank or non-numeric."""
if (isinstance(value, str) and not value.replace('.', '', 1).isdigit()) or value is None:
return 0.0
return float(value)
def format_monitoring_duration(self):
"""Formats the actual time spent monitoring as "Xm Ys"."""
total_seconds = int(self.actual_monitoring_duration_seconds)
minutes, seconds = divmod(total_seconds, 60)
return "{}m {}s".format(minutes, seconds)
def build(self):
self.create_cx()
print("cx build finished")
def create_cx(self):
direction = ''
if (int(self.cx_profile.side_b_min_bps)) != 0 and (int(self.cx_profile.side_a_min_bps)) != 0:
self.direction = "Bi-direction"
direction = 'Bi-di'
elif int(self.cx_profile.side_b_min_bps) != 0:
self.direction = "Download"
direction = 'DL'
else:
if int(self.cx_profile.side_a_min_bps) != 0:
self.direction = "Upload"
direction = 'UL'
traffic_type = (self.traffic_type.strip("lf_")).upper()
traffic_direction_list, cx_list, traffic_type_list = [], [], []
for _client in range(len(self.real_client_list)):
traffic_direction_list.append(direction)
traffic_type_list.append(traffic_type)
logger.info("tos: {}".format(self.tos))
for ip_tos in self.tos:
for i in self.real_client_list1:
for j in traffic_direction_list:
for k in traffic_type_list:
cxs = "%s_%s_%s_%s" % (i, k, j, ip_tos)
cx_names = cxs.replace(" ", "")
cx_list.append(cx_names)
logger.info('cx_list {}'.format(cx_list))
count = 0
for ip_tos in range(len(self.tos)):
for device in range(len(self.input_devices_list)):
logger.info("## ip_tos: {}".format(ip_tos))
logger.info("Creating connections for endpoint type: %s TOS: %s cx-count: %s" % (
self.traffic_type, self.tos[ip_tos], self.cx_profile.get_cx_count()))
self.cx_profile.create(endp_type=self.traffic_type, side_a=[self.input_devices_list[device]],
side_b=self.upstream,
sleep_time=0, tos=self.tos[ip_tos], cx_name="%s-%i" % (cx_list[count], len(self.cx_profile.created_cx)))
count += 1
logger.info("cross connections with TOS type created.")
def monitor_cx(self):
"""
This function waits for up to 20 iterations to allow all CXs (connections) to be created.
If some CXs are still not created after 20 iterations, then the CXs related to that device are removed,
along with their associated client and MAC entries from all relevant lists.
"""
max_retry = 20
current_retry = 0
while current_retry < max_retry:
not_running_cx = []
overallresponse = self.json_get('/cx/all') # Get all current CXs from the layer-3 tab
created_cx_list = list(self.cx_profile.created_cx.keys())
l3_existing_cx = list(overallresponse.keys())
count_of_cx = 0
for created_cxs in created_cx_list:
if created_cxs in l3_existing_cx:
count_of_cx += 1
else:
# Extract base device name (e.g., from '1.16androidsamsunga7_UDP_UL_BE-8' to '1.16androidsamsunga7')
# to track the whole device if any TOS-based CX fails.
not_running_cx.append(created_cxs.split('_')[0]) # CX was not created
if count_of_cx == len(created_cx_list):
break
logger.info(f"Try {current_retry + 1} out of 20: Waiting for the cross-connection to be created.")
time.sleep(2)
current_retry += 1
cxs_to_remove = []
# Collect all CXs related to the failed device (from `not_running_cx`),
# including those created for other TOS types, and add them to `cxs_to_remove`.
for cx in self.cx_profile.created_cx:
for not_created_cx in not_running_cx:
if not_created_cx in cx:
cxs_to_remove.append(cx)
# Remove each failed CX and delete it from the created CX tracking dictionary.
for cx in cxs_to_remove:
logger.info(f"Removing failed CX: {cx}")
super().rm_cx(cx)
del self.cx_profile.created_cx[cx]
devices_to_be_removed = []
for item in not_running_cx:
match = re.match(r'^[0-9.]+', item)
if match:
devices_to_be_removed.append(match.group())
# If there are devices to remove, filter them out from all related client and MAC lists
# to keep the lists consistent with the currently considered devices.
if len(devices_to_be_removed) != 0:
self.real_client_list1 = [item for item in self.real_client_list1 if item.split()[0] not in devices_to_be_removed]
self.input_devices_list = [item for item in self.input_devices_list if item.split('.')[0] + '.' + item.split('.')[1] not in devices_to_be_removed]
filtered = [(dev, mac) for dev, mac in zip(self.real_client_list, self.mac_id_list) if dev.split()[0] not in devices_to_be_removed]
self.real_client_list, self.mac_id_list = zip(*filtered) if filtered else ([], [])
self.real_client_list = list(self.real_client_list)
self.mac_id_list = list(self.mac_id_list)
self.num_stations = len(self.real_client_list)
def wait_for_any_cx_recovery(self, timeout=40, poll_interval=5):
"""Polls for any CX to reappear (or a user stop) for up to `timeout` seconds.
Returns True on recovery or stop, False if the timeout elapses with none.
"""
wait_start = datetime.now()
cx_list = list(self.cx_profile.created_cx.keys())
while (datetime.now() - wait_start).total_seconds() < timeout:
time.sleep(poll_interval)
if self.dowebgui == "True":
with open(self.result_dir + "/../../Running_instances/{}_{}_running.json".format(
self.ip, self.test_name), 'r') as file:
data = json.load(file)
if data["status"] != "Running":
logger.info("Test is stopped by the user during the device-recovery wait.")
self.test_stopped_by_user = True
return True
try:
# 'endpoint' is a single dict (not a list) when there's only one CX; normalize to a list
endp_api_url = '/endp/list?fields=rx rate (last),rx drop %25,name'
endp_response = self.json_get(endp_api_url)
endpoint_data = endp_response['endpoint']
l3_endp_data = endpoint_data if isinstance(endpoint_data, list) else [endpoint_data]
matched_cx = {next(iter(i.items()))[0][0:-2] for i in l3_endp_data}
except Exception:
matched_cx = set()
elapsed = (datetime.now() - wait_start).total_seconds()
if any(cx in matched_cx for cx in cx_list):
logger.info("Device(s) responded again after {:.0f}s, resuming.".format(elapsed))
return True
logger.warning("Still no devices responding after {:.0f}s, retrying...".format(elapsed))
return False
def monitor(self, curr_coordinate=None, curr_rotation=None, monitor_charge_time=None):
# TODO: Fix this. This is poor style
throughput, upload, download, upload_throughput, download_throughput, connections_upload, connections_download, avg_upload, avg_download, avg_upload_throughput, avg_download_throughput, connections_download_avg, connections_upload_avg, avg_drop_a, avg_drop_b, dropa_connections, dropb_connections = { # noqa: E501
}, [], [], [], [], {}, {}, [], [], [], [], {}, {}, [], [], {}, {}
if self.robot_test:
curr_coordinate = self.current_coordinate
# Initialized seperate variables for average values for report changes
drop_a, drop_a_per, drop_b, drop_b_per, avg_drop_b_per, avg_drop_a_per = [], [], [], [], [], []
if (self.test_duration is None) or (int(self.test_duration) <= 1):
raise ValueError("Monitor test duration should be > 1 second")
if self.cx_profile.created_cx is None:
raise ValueError("Monitor needs a list of Layer 3 connections")
# monitor columns
start_time = datetime.now()
if self.do_bandsteering:
# Bandsteering invokes monitor() repeatedly as a per-tick callback within one
# continuous session, so only set this once for the whole session.
if self.monitor_start_time is None:
self.monitor_start_time = start_time
else:
# Every other robot_test flow (plain coordinate loop, rotation loop) calls
# monitor() once per coordinate/rotation, with CXs freshly restarted just before
# each call - restart the grace period each time instead of only on the very
# first coordinate.
self.monitor_start_time = start_time
test_start_time = datetime.now().strftime("%Y %d %H:%M:%S")
if not self.do_bandsteering:
print("Test started at: ", test_start_time)
print("Monitoring cx and endpoints")
end_time = start_time + timedelta(seconds=int(self.test_duration))
if not self.robot_test:
self.overall = []
self.df_for_webui = []
index = -1
connections_upload = dict.fromkeys(list(self.cx_profile.created_cx.keys()), float(0))
connections_download = dict.fromkeys(list(self.cx_profile.created_cx.keys()), float(0))
connections_upload_realtime = dict.fromkeys(list(self.cx_profile.created_cx.keys()), float(0))
connections_download_realtime = dict.fromkeys(list(self.cx_profile.created_cx.keys()), float(0))
# Initialize dictionaries for average values of connections (upload, download and drop)
connections_upload_avg = dict.fromkeys(list(self.cx_profile.created_cx.keys()), float(0))
connections_download_avg = dict.fromkeys(list(self.cx_profile.created_cx.keys()), float(0))
dropa_connections = dict.fromkeys(list(self.cx_profile.created_cx.keys()), float(0))
dropb_connections = dict.fromkeys(list(self.cx_profile.created_cx.keys()), float(0))
[(upload.append([]), download.append([]), drop_a.append([]), drop_b.append([]), avg_upload.append([]), avg_download.append([]), avg_drop_a.append([]), avg_drop_b.append([])) for i in
range(len(self.cx_profile.created_cx))]
if self.dowebgui == "True":
runtime_dir = self.result_dir
# added a dictionary to store real time data
self.real_time_data = {}
for endp in connections_download_realtime.keys():
self.real_time_data.update(
{
endp: {
'BE': {
'time': [],
'bps rx a': [],
'bps rx b': [],
'rx drop % a': [],
'rx drop % b': []
},
'BK': {
'time': [],
'bps rx a': [],
'bps rx b': [],
'rx drop % a': [],
'rx drop % b': []
},
'VI': {
'time': [],
'bps rx a': [],
'bps rx b': [],
'rx drop % a': [],
'rx drop % b': []
},
'VO': {
'time': [],
'bps rx a': [],
'bps rx b': [],
'rx drop % a': [],
'rx drop % b': []
}
}
}
)
previous_time = datetime.now()
time_break = 0
# Added background_run to allow the test to continue running, bypassing the duration limit for nile requirement.
rates_data = defaultdict(list)
individual_device_data = {}
cx_list = list(self.cx_profile.created_cx.keys())
for cx in cx_list:
columns = ['bps rx a', 'bps rx b']
individual_device_data[cx] = pd.DataFrame(columns=columns)
while datetime.now() < end_time or getattr(self, "background_run", None):
if self.all_devices_stopped:
# already gave up on recovery earlier; don't re-run the 40s wait on every
# bandsteering tick
if self.do_bandsteering:
return pd.DataFrame(self.band_steering_df)
break
if self.robot_test:
# monitor_charge_time is None on the bandsteering monitor_function tick, so
# skip this check instead of crashing on None.
if self.rotation_enabled and monitor_charge_time is not None:
if (datetime.now() - monitor_charge_time).total_seconds() >= 300:
logger.info("Checking battery status (5-minute interval)...")
pause_start = datetime.now()
pause = False
# Check battery level: if below 20% robot charges fully before resuming
pause, test_stopped_by_user = self.robot.wait_for_battery(stop=self.stop)
if test_stopped_by_user:
break
if pause:
# Return robot to the last saved coordinate after charging
reached = self.robot.move_to_coordinate(curr_coordinate)
if not reached:
test_stopped_by_user = True
break
if self.rotation_enabled:
# Restore robot's previous orientation before resuming the test
rotation_moni = self.robot.rotate_angle(curr_rotation)
if not rotation_moni:
test_stopped_by_user = True
break
self.start(False, False)
pause_end = datetime.now()
charge_pause = pause_end - pause_start
end_time += charge_pause
# overall_end_time += charge_pause
previous_time = datetime.now()
monitor_charge_time = datetime.now()
index += 1
current_time = datetime.now()
# removed the fields query from endp so that the cx names will be given in the reponse as keys instead of cx_ids
t_response = {}
overallresponse = self.json_get('/cx/all')
try:
# for dynamic data, taken rx rate (last) from layer3 endp tab
# 'endpoint' is a single dict (not a list) when there's only one CX; normalize to a list
endp_api_url = '/endp/list?fields=rx rate (last),rx drop %25,name'
endp_response = self.json_get(endp_api_url)
endpoint_data = endp_response['endpoint']
l3_endp_data = endpoint_data if isinstance(endpoint_data, list) else [endpoint_data]
port_mgr_data = self.json_get('/ports/all/')['interfaces']
matched_ports = set()
for value in port_mgr_data:
for port, port_data in value.items():
if port_data['parent dev'] == "wiphy0" and port in self.input_devices_list:
matched_ports.add(port)
rates_data['.'.join(port.split('.')[:2]) + ' rx_rate'].append(port_data['rx-rate'])
rates_data['.'.join(port.split('.')[:2]) + ' tx_rate'].append(port_data['tx-rate'])
rates_data['.'.join(port.split('.')[:2]) + ' RSSI'].append(port_data['signal'])
rates_data['.'.join(port.split('.')[:2]) + ' BSSID'].append(port_data['ap'])
rates_data['.'.join(port.split('.')[:2]) + ' Channel'].append(port_data['channel'])
# warn once when a device's port drops out, and log once when it reappears
for port in self.input_devices_list:
if port not in matched_ports:
if port not in self.missing_signal_logged:
logger.warning(
"Signal data for device on port {} is unavailable, it may have "
"disconnected. Continuing the test with the remaining devices.".format(port)
)
self.missing_signal_logged.add(port)
self.record_device_issue(
port,
"Signal data unavailable (device may have disconnected)",
api_response=[key for interface in port_mgr_data
if isinstance(interface, dict) for key in interface])
elif port in self.missing_signal_logged:
logger.info("Signal data for device on port {} is available again.".format(port))
self.missing_signal_logged.discard(port)
cx_list = list(self.cx_profile.created_cx.keys())
# t_response data order - [rx rate(last)_A,rx rate(last)_B,rx drop % A,rx drop %B] A or B will considered based upon the name in L3 Endps tab
for cx in cx_list:
t_response[cx] = [0, 0, 0.0, 0.0]
matched_cx = set()
for cx in cx_list:
# track which side (A/B) each tos actually got data for this round
tos_sides_seen = {}
for i in l3_endp_data:
key, cx_data = next(iter(i.items()))
cx_name = key[0:-2]
if cx == cx_name:
matched_cx.add(cx_name)
traffic_tos = key.split('_')[-1].split('-')[0]
endp = key[-1]
tos_sides_seen.setdefault(traffic_tos, set()).add(endp)
if endp == 'A':
rx_rate_a = self._parse_float(cx_data['rx rate (last)'])
self.real_time_data[cx_name][traffic_tos]['bps rx a'].append(rx_rate_a / 1000000)
t_response[cx_name][0] = rx_rate_a
rx_drop_a = self._parse_float(cx_data['rx drop %'])
self.real_time_data[cx_name][traffic_tos]['rx drop % a'].append(rx_drop_a)
t_response[cx_name][2] = rx_drop_a
elif endp == 'B':
rx_rate_b = self._parse_float(cx_data['rx rate (last)'])
self.real_time_data[cx_name][traffic_tos]['bps rx b'].append(rx_rate_b / 1000000)
t_response[cx_name][1] = rx_rate_b
rx_drop_b = self._parse_float(cx_data['rx drop %'])
self.real_time_data[cx_name][traffic_tos]['rx drop % b'].append(rx_drop_b)
t_response[cx_name][3] = rx_drop_b
# fill 0 for whichever side didn't report, so every list for this tos stays the same length
for traffic_tos, sides in tos_sides_seen.items():
tos_data = self.real_time_data[cx][traffic_tos]
if 'A' not in sides:
tos_data['bps rx a'].append(0.0)
tos_data['rx drop % a'].append(0.0)
if 'B' not in sides:
tos_data['bps rx b'].append(0.0)
tos_data['rx drop % b'].append(0.0)
tos_data['time'].append(datetime.now().strftime('%H:%M:%S'))
# warn once when a CX drops out of this tick's data, and log once when it reappears