-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathlf_webpage.py
More file actions
executable file
·3329 lines (3073 loc) · 160 KB
/
lf_webpage.py
File metadata and controls
executable file
·3329 lines (3073 loc) · 160 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_webpage.py
PURPOSE:
lf_webpage.py will verify that N clients are connected on a specified band and can download
some amount of file data from the HTTP server while measuring the time taken by clients to download the file and number of
times the file is downloaded.
EXAMPLE-1:
Command Line Interface to run download scenario for Real clients
python3 lf_webpage.py --ap_name "Cisco" --mgr 192.168.200.165 --ssid Cisco-5g --security wpa2 --passwd sharedsecret
--upstream_port eth1 --duration 10m --bands 5G --client_type Real --file_size 2MB
EXAMPLE-2:
Command Line Interface to run download scenario on 5GHz band for Virtual clients
python3 lf_webpage.py --ap_name "Cisco" --mgr 192.168.200.165 --fiveg_ssid Cisco-5g --fiveg_security wpa2 --fiveg_passwd sharedsecret
--fiveg_radio wiphy0 --upstream_port eth1 --duration 1h --bands 5G --client_type Virtual --file_size 2MB --num_stations 3
EXAMPLE-3:
Command Line Interface to run download scenario on 2.4GHz band for Virtual clients
python3 lf_webpage.py --ap_name "Cisco" --mgr 192.168.200.165 --twog_ssid Cisco-2g --twog_security wpa2 --twog_passwd sharedsecret
--twog_radio wiphy0 --upstream_port eth1 --duration 1h --bands 2.4G --client_type Virtual --file_size 2MB --num_stations 3
EXAMPLE-4:
Command Line Interface to run download scenario on 6GHz band for Virtual clients
python3 lf_webpage.py --ap_name "Cisco" --mgr 192.168.200.165 --sixg_ssid Cisco-6g --sixg_security wpa3 --sixg_passwd sharedsecret
--sixg_radio wiphy0 --upstream_port eth1 --duration 1h --bands 6G --client_type Virtual --file_size 2MB --num_stations 3
EXAMPLE-5:
Command Line Interface to run download scenario for Real clients with device list
python3 lf_webpage.py --ap_name "Cisco" --mgr 192.168.214.219 --ssid Cisco-5g --security wpa2 --passwd sharedsecret --upstream_port eth1
--duration 1m --bands 5G --client_type Real --file_size 2MB --device_list 1.12,1.22
EXAMPLE-6:
Command Line Interface to run download scenario for Real clients with device list and Expected Pass/Fail CSV
python3 lf_webpage.py --file_size 1MB --mgr 192.168.213.218 --duration 1m --client_type Real --bands 5G --upstream_port eth1 --device_list 1.11,1.95 --device_csv_name test.csv
EXAMPLE-7:
Command Line Interface to run download scenario for Real clients with device list and expected passfail value
python3 lf_webpage.py --file_size 1MB --mgr 192.168.204.74 --duration 1m --client_type Real --bands 5G --upstream_port eth1 --device_list 1.11,1.95 --expected_passfail_value 5
EXAMPLE-8:
Command Line Interface to run download scenario for Real clients with Groups and Profiles
python3 lf_webpage.py --file_size 1MB --mgr 192.168.213.218 --duration 1m --client_type Real --bands 5G --upstream_port eth1 --file_name grp218 --group_name laptops --profile_name Opensd
EXAMPLE-9:
Command Line Interface to run download scenario for Real clients with device list and config
python3 lf_webpage.py --file_size 1MB --mgr 192.168.244.97 --duration 1m --client_type Real --bands 5G --upstream_port eth1 --ssid
xiab_2G_WPA2 --passwd lanforge --security wpa2 --device_list 1.160,1.146,1.13,1.20 --config
EXAMPLE-10:
Command Line Interface to run the Test along with IOT without device list
python3 lf_webpage.py --ap_name "Cisco" --mgr 192.168.207.78 --ssid Cisco-5g --security wpa2 --passwd sharedsecret --upstream_port eth1
--duration 1m --bands 5G --client_type Real --file_size 2MB --iot_test --iot_testname "httpiot"
EXAMPLE-11:
Command Line Interface to run the Test along with IOT with device list
python3 lf_webpage.py --ap_name "Cisco" --mgr 192.168.207.78 --ssid Cisco-5g --security wpa2 --passwd sharedsecret --upstream_port eth1
--duration 1m --bands 5G --client_type Real --file_size 2MB --iot_test --iot_testname "httpiot" --iot_device_list "switch.smart_plug_1_socket_1"
EXAMPLE-12:
Command Line Interface to run download scenario for Real clients with Robot with only coordinates
python3 lf_webpage.py --ap_name "Netgear" --mgr 192.168.204.78 --ssid NETGEAR_2G_wpa2 --security wpa2 --passwd Password@123
--upstream_port eth1 --duration 10m --bands 5G --client_type Real --file_size 2MB --robot_ip 192.168.204.101 --coordinate 3,4 --robot_test
EXAMPLE-13:
Command Line Interface to run download scenario for Real clients with Robot with coordinates and rotations
python3 lf_webpage.py --ap_name "Netgear" --mgr 192.168.204.78 --ssid NETGEAR_2G_wpa2 --security wpa2 --passwd Password@123
--upstream_port eth1 --duration 10m --bands 5G --client_type Real --file_size 2MB --robot_ip 192.168.204.101 --coordinate 3,4 --rotation 30,45 --robot_test
EXAMPLE-14:
Command Line Interface to run download scenario for Real clients with Robot with coordinates and band steering enabled
python3 lf_webpage.py --ap_name "Netgear" --mgr 192.168.204.75 --ssid NETGEAR_2G_wpa2 --security wpa2 --passwd Password@123 --upstream_port eth1
--duration 1m --bands 5G --client_type Real --file_size 2MB --robot_test --coordinate 3,4 --robot_ip 192.168.204.101 --do_bandsteering --cycles 1 --bssids 7a:1d:35:c8:da:b9
SCRIPT_CLASSIFICATION : Test
SCRIPT_CATEGORIES: Performance, Functional, Report Generation
NOTES:
1.Please enter the duration in s,m,h (seconds or minutes or hours).Eg: 30s,5m,48h.
2.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
STATUS : Functional
VERIFIED_ON:
26-JULY-2024,
GUI Version: 5.4.8
Kernel Version: 6.2.16+
LICENSE :
Copyright (C) 2020-2026 Candela Technologies Inc
Free to distribute and modify. LANforge systems must be licensed.
INCLUDE_IN_README: False
"""
# from lf_interop_qos import ThroughputQOS
import sys
import os
import importlib
import time
import argparse
import paramiko
from datetime import datetime, timedelta
import pandas as pd
import logging
import requests
import shutil
import json
from lf_graph import lf_bar_graph_horizontal, lf_bar_graph
import traceback
import threading
from collections import OrderedDict, Counter
import asyncio
from typing import List, Optional
import csv
from lf_base_robo import RobotClass
sys.path.append(os.path.join(os.path.abspath(__file__ + "../../../")))
LFUtils = importlib.import_module("py-json.LANforge.LFUtils")
lfcli_base = importlib.import_module("py-json.LANforge.lfcli_base")
LFCliBase = lfcli_base.LFCliBase
realm = importlib.import_module("py-json.realm")
Realm = realm.Realm
PortUtils = realm.PortUtils
lf_report = importlib.import_module("py-scripts.lf_report")
lf_graph = importlib.import_module("py-scripts.lf_graph")
lf_kpi_csv = importlib.import_module("py-scripts.lf_kpi_csv")
lf_logger_config = importlib.import_module("py-scripts.lf_logger_config")
DeviceConfig = importlib.import_module("py-scripts.DeviceConfig")
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
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 HttpDownload(Realm):
def __init__(self, lfclient_host, lfclient_port, upstream, num_sta, security, ssid, password, ap_name,
target_per_ten, file_size, bands, start_id=0, twog_radio=None, fiveg_radio=None, sixg_radio=None, _debug_on=False, _exit_on_error=False,
test_name=None, _exit_on_fail=False, client_type="", port_list=None, devices_list=None, macid_list=None, lf_username="lanforge", lf_password="lanforge", result_dir="", dowebgui=False,
device_list=None, get_url_from_file=None, file_path=None, device_csv_name='', expected_passfail_value=None, file_name=None, group_name=None, profile_name=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, wait_time=60, get_live_view=False, total_floors=0, robot_test=False,
robot_ip=None, coordinate=None, rotation=None, duration=None, do_bandsteering=False, cycles=None, bssids=None, duration_to_skip=None):
# super().__init__(lfclient_host=lfclient_host,
# lfclient_port=lfclient_port)
self.ssid_list = []
self.devices = []
self.mode_list = []
self.channel_list = []
self.host = lfclient_host
self.port = lfclient_port
self.upstream = upstream
self.num_sta = num_sta
self.security = security
self.ssid = ssid
self.sta_start_id = start_id
self.password = password
self.twog_radio = twog_radio
self.fiveg_radio = fiveg_radio
self.sixg_radio = sixg_radio
self.target_per_ten = target_per_ten
self.file_size = file_size
self.bands = bands
self.debug = _debug_on
self.port_list = port_list
self.result_dir = result_dir
self.test_name = test_name
self.dowebgui = dowebgui
self.device_list = device_list
self.eid_list = []
self.devices_list = devices_list
self.macid_list = []
self.client_type = client_type
self.lf_username = lf_username
self.lf_password = lf_password
self.ap_name = ap_name
self.windows_ports = []
self.windows_eids = []
self.local_realm = realm.Realm(lfclient_host=self.host, lfclient_port=self.port)
self.station_profile = self.local_realm.new_station_profile()
self.http_profile = self.local_realm.new_http_profile()
self.http_profile.requests_per_ten = self.target_per_ten
# self.http_profile.url = self.url
self.port_util = PortUtils(self.local_realm)
self.http_profile.debug = _debug_on
self.created_cx = {}
self.station_list = []
self.radio = []
self.failed_cx = []
self.tracking_map = {}
self.get_url_from_file = get_url_from_file
self.file_path = file_path
self.file_name = file_name
self.group_name = group_name
self.profile_name = profile_name
# for advanced config
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.expected_passfail_value = expected_passfail_value
self.device_csv_name = device_csv_name
self.wait_time = wait_time
self.config = config
self.api_url = 'http://{}:{}'.format(self.host, self.port)
self.group_device_map = {}
self.individual_device_csv_names = []
self.get_live_view = get_live_view
self.duration = duration
self.total_floors = total_floors
# Robot Automation parameters
self.robot_test = robot_test
self.robot_ip = robot_ip
self.coordinate = coordinate
self.rotation = rotation
self.rotation_enabled = False
if self.robot_test:
# To consider coordinates list and rotation list when running with robot
self.coordinate_list = coordinate.split(',')
self.rotation_list = rotation.split(',')
self.current_coordinate = ""
self.current_angle = 0
self.robot_data = {}
self.robot_obj = {}
self.individual_device_data = {}
self.rx_rate_val = []
self.max_bytes_rd = []
self.do_bandsteering = do_bandsteering
self.cycles = cycles
self.bssids = bssids.split(',') if bssids else []
self.duration_to_skip = duration_to_skip
# The 'phantom_check' will be handled within the 'get_real_client_list' function
def get_real_client_list(self):
user_list = []
real_client_list1 = []
real_client_list2 = []
android_list = []
mac_list = []
windows_list = []
linux_list = []
working_resources_list = []
eid_list = []
devices_available = []
input_devices_list = []
mac_id_list1 = []
mac_id_list2 = []
port_eid_list = []
same_eid_list = []
original_port_list = []
device_found = False
obj = DeviceConfig.DeviceConfig(lanforge_ip=self.host, file_name=self.file_name, wait_time=self.wait_time)
config_devices = {}
# upstream port IP for configuration
upstream_port_ip = 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_port_ip,
}
# When groups and profiles specified for configuration
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(',')
if len(selected_groups) == len(selected_profiles):
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)
# Configuration of group of devices for the corresponding profiles
self.device_list = asyncio.run(obj.connectivity(config_devices, upstream=upstream_port_ip))
if len(self.device_list) == 0:
devices_list = ""
elif self.device_list != []:
obj.get_all_devices()
self.device_list = self.device_list.split(',')
# Configuration of devices with SSID,Password and Security when device list is specified
if self.config:
self.device_list = asyncio.run(obj.connectivity(device_list=self.device_list, wifi_config=config_dict))
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["shelf"] + '.' + device["resource"] + " " + device["serial"])
logger.info("Available devices: %s", device_list)
self.device_list = input("Enter the desired resources to run the test:").split(',')
# Configuration of devices with SSID , Password and Security when the device list is not specified
if self.config:
self.device_list = asyncio.run(obj.connectivity(device_list=self.device_list, wifi_config=config_dict))
response = self.local_realm.json_get("/resource/all")
for key, value in response.items():
if key == "resources":
for element in value:
for _, b in element.items():
if not b['phantom']:
working_resources_list.append(b["hw version"])
if "Win" in b['hw version']:
eid_list.append(b['eid'])
windows_list.append(b['hw version'])
# self.hostname_list.append(b['eid']+ " " +b['hostname'])
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']):
eid_list.append(b['eid'])
linux_list.append(b['hw version'])
# self.hostname_list.append(b['eid']+ " " +b['hostname'])
devices_available.append(b['eid'] + " " + 'Lin' + " " + b['hostname'])
elif "Apple" in b['hw version']:
if b['kernel'] == '':
continue
else:
eid_list.append(b['eid'])
mac_list.append(b['hw version'])
# self.hostname_list.append(b['eid']+ " " +b['hostname'])
devices_available.append(b['eid'] + " " + 'Mac' + " " + b['hostname'])
else:
eid_list.append(b['eid'])
android_list.append(b['hw version'])
# self.username_list.append(b['eid']+ " " +b['user'])
devices_available.append(b['eid'] + " " + 'android' + " " + b['user'])
# print("hostname list :",self.hostname_list)
# print("username list :", self.username_list)
# print("Available resources in resource tab :", devices_available)
# print("eid_list : ",eid_list)
# All the available resources are fetched from resource mgr tab ----
response_port = self.local_realm.json_get("/port/all")
# print(response_port)
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 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]))
mac_id_list1.append(str(self.name_to_eid(port)[0]) + '.' + str(self.name_to_eid(port)[1]) + ' ' + port_data['mac'])
# print("port eid list",port_eid_list)
for i in range(len(eid_list)):
for j in range(len(port_eid_list)):
if eid_list[i] == port_eid_list[j]:
same_eid_list.append(eid_list[i])
same_eid_list = [_eid + ' ' for _eid in same_eid_list]
# print("same eid list",same_eid_list)
# print("mac_id list",mac_id_list)
# All the available ports from port manager are fetched from port manager tab ---
for eid in same_eid_list:
for device in devices_available:
if eid in device:
logger.info("%s %s", eid, device)
user_list.append(device)
if not self.config and len(self.device_list) == 0 and self.group_name is None:
logger.info("AVAILABLE DEVICES TO RUN TEST : {}".format(user_list))
self.device_list = input("Enter the desired resources to run the test:")
self.device_list = self.filter_iOS_devices(self.device_list).split(',')
# checking for the availability of slected devices to run test
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 user_list:
if input_device + " " in device:
available_list.append(input_device)
found = True
break
if not found:
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)
device_found = True
else:
devices_list = ""
device_found = False
logger.warning("Test can not be initiated on any selected devices")
else:
devices_list = ""
if devices_list == "" or devices_list == ",":
logger.error("Selected Devices are not available in the lanforge")
exit(1)
resource_eid_list = devices_list.split(',')
logger.info("devices list {} {}".format(devices_list, resource_eid_list))
resource_eid_list2 = [eid + ' ' for eid in resource_eid_list]
resource_eid_list1 = [resource + '.' for resource in resource_eid_list]
logger.info("resource eid list {} {}".format(resource_eid_list1, original_port_list))
# User desired eids are fetched ---
for eid in resource_eid_list1:
for ports_m in original_port_list:
if eid in ports_m:
input_devices_list.append(ports_m)
logger.info("INPUT DEVICES LIST {}".format(input_devices_list))
# user desired real client list 1.1 wlan0 ---
for i in resource_eid_list2:
for j in range(len(user_list)):
if i in user_list[j]:
real_client_list1.append(user_list[j])
real_client_list2.append((user_list[j])[:25])
logger.info("REAL CLIENT LIST: %s", real_client_list1)
self.num_sta = len(real_client_list1)
for eid in resource_eid_list2:
for i in mac_id_list1:
if eid in i:
mac_id_list2.append(i.strip(eid + ' '))
logger.info("MAC ID LIST: %s", mac_id_list2)
self.port_list, self.devices_list, self.macid_list = input_devices_list, real_client_list1, mac_id_list2
# user desired real client list 1.1 OnePlus, 1.1 Apple for report generation ---
# Todo- Make use of lf_base_interop_profile.py : Real device class to fetch available devices data
for port in self.port_list:
eid = self.name_to_eid(port)
self.eid_list.append(str(eid[0]) + '.' + str(eid[1]))
for eid in self.eid_list:
for device in self.devices_list:
if ("Win" in device) and (eid + ' ' in device):
self.windows_eids.append(eid)
for eid in self.windows_eids:
for port in self.port_list:
if eid + '.' in port:
self.windows_ports.append(port)
if self.dowebgui == "True":
if not device_found:
print("No Device is available to run the test hence aborting the testllmlml")
df1 = pd.DataFrame([{
"client": [],
"status": "Stopped",
"url_data": 0
}]
)
df1.to_csv('{}/http_datavalues.csv'.format(self.result_dir), index=False)
raise ValueError("Aborting the test....")
return self.port_list, self.devices_list, self.macid_list, config_devices
def api_get(self, endp: str):
"""
Sends a GET request to fetch data
Args:
endp (str): API endpoint
Returns:
response: response code for the request
data: data returned in the response
"""
if endp[0] != '/':
endp = '/' + endp
response = requests.get(url=self.api_url + endp)
data = response.json()
return response, data
def filter_iOS_devices(self, device_list):
modified_device_list = device_list
if type(device_list) is str:
modified_device_list = device_list.split(',')
filtered_list = []
for device in modified_device_list:
if device.count('.') == 1:
shelf, resource = device.split('.')
elif device.count('.') == 2:
shelf, resource, port = device.split('.')
elif device.count('.') == 0:
shelf, resource = 1, device
response_code, device_data = self.api_get('/resource/{}/{}'.format(shelf, resource))
if 'status' in device_data and device_data['status'] == 'NOT_FOUND':
logger.info("Device %s is not found.", device)
continue
device_data = device_data['resource']
# print(device_data)
if 'Apple' in device_data['hw version'] and (device_data['app-id'] != '') and (device_data['app-id'] != '0' or device_data['kernel'] == ''):
logger.info("%s is an iOS device. Currently, we do not support iOS devices.", device)
else:
filtered_list.append(device)
if type(device_list) is str:
filtered_list = ','.join(filtered_list)
self.device_list = filtered_list
return filtered_list
def set_values(self):
# This method will set values according user input
if self.bands == "5G":
self.radio = [self.fiveg_radio]
self.station_list = [LFUtils.portNameSeries(prefix_="http_sta", start_id_=self.sta_start_id,
end_id_=self.num_sta - 1, padding_number_=10000,
radio=self.fiveg_radio)]
elif self.bands == "6G":
self.radio = [self.sixg_radio]
self.station_list = [LFUtils.portNameSeries(prefix_="http_sta", start_id_=self.sta_start_id,
end_id_=self.num_sta - 1, padding_number_=10000,
radio=self.sixg_radio)]
elif self.bands == "2.4G":
self.radio = [self.twog_radio]
self.station_list = [LFUtils.portNameSeries(prefix_="http_sta", start_id_=self.sta_start_id,
end_id_=self.num_sta - 1, padding_number_=10000,
radio=self.twog_radio)]
elif self.bands == "Both":
self.radio = [self.twog_radio, self.fiveg_radio]
# self.num_sta = self.num_sta // 2
self.station_list = [
LFUtils.portNameSeries(prefix_="http_sta", start_id_=self.sta_start_id,
end_id_=self.num_sta - 1, padding_number_=10000,
radio=self.twog_radio),
LFUtils.portNameSeries(prefix_="http_sta", start_id_=self.sta_start_id,
end_id_=self.num_sta - 1, padding_number_=10000,
radio=self.fiveg_radio)
]
def precleanup(self):
self.count = 0
for rad in range(len(self.radio)):
if self.radio[rad] == self.fiveg_radio:
# select an mode
self.station_profile.mode = 14
self.count = self.count + 1
elif self.radio[rad] == self.sixg_radio:
# select an mode
self.station_profile.mode = 15
self.count = self.count + 1
elif self.radio[rad] == self.twog_radio:
# select an mode
self.station_profile.mode = 13
self.count = self.count + 1
if self.count == 2:
self.sta_start_id = self.num_sta
self.num_sta = 2 * (self.num_sta)
self.station_profile.mode = 10
self.http_profile.cleanup()
# cleanup station list which started sta_id 20
self.station_profile.cleanup(self.station_list[rad], debug_=self.local_realm.debug)
LFUtils.wait_until_ports_disappear(base_url=self.local_realm.lfclient_url,
port_list=self.station_list[rad],
debug=self.local_realm.debug)
return
# clean dlayer4 ftp traffic
self.http_profile.cleanup()
# cleans stations
self.station_profile.cleanup(self.station_list[rad], delay=1, debug_=self.local_realm.debug)
LFUtils.wait_until_ports_disappear(base_url=self.local_realm.lfclient_url,
port_list=self.station_list[rad],
debug=self.local_realm.debug)
time.sleep(1)
print("precleanup done")
def build(self):
# enable http on ethernet
self.port_util.set_http(port_name=self.local_realm.name_to_eid(self.upstream)[2],
resource=self.local_realm.name_to_eid(self.upstream)[1], on=True)
if self.client_type == "Virtual":
if self.bands == "2.4G":
self.station_profile.mode = 13
elif self.bands == "5G":
self.station_profile.mode = 14
elif self.bands == "6G":
self.station_profile.mode = 15
for rad in range(len(self.radio)):
self.station_profile.use_security(self.security[rad], self.ssid[rad], self.password[rad])
self.station_profile.set_command_flag("add_sta", "create_admin_down", 1)
self.station_profile.set_command_param("set_port", "report_timer", 1500)
self.station_profile.set_command_flag("set_port", "rpt_timer", 1)
self.station_profile.create(radio=self.radio[rad], sta_names_=self.station_list[rad], debug=self.local_realm.debug)
self.local_realm.wait_until_ports_appear(sta_list=self.station_list[rad])
self.station_profile.admin_up()
if self.local_realm.wait_for_ip(self.station_list[rad], timeout_sec=60):
self.local_realm._pass("All stations got IPs")
else:
self.local_realm._fail("Stations failed to get IPs")
# building layer4
self.http_profile.direction = 'dl'
self.http_profile.dest = '/dev/null'
data = self.local_realm.json_get("ports/list?fields=IP")
# getting eth ip
eid = self.local_realm.name_to_eid(self.upstream)
for i in data["interfaces"]:
for j in i:
if "{shelf}.{resource}.{port}".format(shelf=eid[0], resource=eid[1], port=eid[2]) == j:
ip_upstream = i["{shelf}.{resource}.{port}".format(
shelf=eid[0], resource=eid[1], port=eid[2])]['ip']
# create http profile
if self.get_url_from_file: # enabling the GET-URL-FROM-FILE flag if its ture
self.http_profile.create(ports=self.station_profile.station_names, sleep_time=.5,
suppress_related_commands_=None, http=True, user=self.lf_username,
passwd=self.lf_password, http_ip=self.file_path, proxy_auth_type=0x200,
timeout=1000, get_url_from_file=True)
else:
self.http_profile.create(ports=self.station_profile.station_names, sleep_time=.5,
suppress_related_commands_=None, http=True, user=self.lf_username,
passwd=self.lf_password, http_ip=ip_upstream + "/webpage.html",
proxy_auth_type=0x200, timeout=1000)
if self.count == 2:
self.station_profile.mode = 6
else:
if self.client_type == "Real":
self.http_profile.direction = 'dl'
data = self.local_realm.json_get("ports/list?fields=IP")
# getting eth ip
eid = self.local_realm.name_to_eid(self.upstream)
for i in data["interfaces"]:
for j in i:
if "{shelf}.{resource}.{port}".format(shelf=eid[0], resource=eid[1], port=eid[2]) == j:
ip_upstream = i["{shelf}.{resource}.{port}".format(
shelf=eid[0], resource=eid[1], port=eid[2])]['ip']
self.http_profile.create(ports=self.port_list, sleep_time=.5,
suppress_related_commands_=None, http=True, interop=True,
user=self.lf_username, passwd=self.lf_password,
http_ip=ip_upstream + "/webpage.html", proxy_auth_type=0x200, timeout=1000, windows_list=self.windows_ports)
print("Test Build done")
def start(self):
self.http_profile.start_cx()
try:
for i in self.http_profile.created_cx.keys():
while self.local_realm.json_get("/cx/" + i).get(i).get('state') != 'Run':
continue
except Exception:
# TODO: Handle exception
pass
def stop(self):
self.http_profile.stop_cx()
# To update status of devices and remaining_time in ftp_datavalues.csv file to stopped and 0 respectively.
if self.client_type == 'Real':
if not self.robot_test:
self.data["status"] = ["STOPPED"] * len(self.macid_list)
self.data["remaining_time"] = ["0"] * len(self.macid_list)
df1 = pd.DataFrame(self.data)
df1.to_csv("http_datavalues.csv", index=False)
if not self.do_bandsteering and self.robot_test:
# For Robot test, save data for each coordinate and rotation
if self.rotation_enabled:
self.robot_data.setdefault(self.current_coordinate, {})[self.current_angle] = self.data
else:
self.robot_data[self.current_coordinate] = self.data
if self.dowebgui:
df1.to_csv(f"{self.result_dir}/{self.current_coordinate}_http_datavalues.csv", index=False)
else:
df1.to_csv(f"{self.current_coordinate}_http_datavalues.csv", index=False)
def update_stop_status_robot(self):
# To update status of devices in csv file to stopped.
self.data["status"] = ["STOPPED"] * len(self.macid_list)
df1 = pd.DataFrame(self.data)
df1.to_csv("http_datavalues.csv", index=False)
if self.dowebgui:
df1.to_csv(f"{self.result_dir}/{self.current_coordinate}_http_datavalues.csv", index=False)
else:
df1.to_csv(f"{self.current_coordinate}_http_datavalues.csv", index=False)
def get_layer4_data(self):
"""
Fetch Layer 4 stats (uc-avg, uc-min, uc-max, urls, rx rate, bytes read, errors)
for all connections in self.cx_list.
Returns:
dict: mapping of metric names to lists of values, one per CX.
"""
cx_list = list(self.http_profile.created_cx.keys())
try:
url_str = 'layer4/{}/list?fields=uc-avg,uc-max,uc-min,total-urls,rx rate (1m),bytes-rd,total-err'.format(','.join(cx_list))
l4_data = self.local_realm.json_get(url_str)['endpoint']
except Exception:
logger.error("l4 DATA not found")
exit(1)
l4_dict = {
'uc_avg_data': [],
'uc_max_data': [],
'uc_min_data': [],
'url_times': [],
'rx_rate': [],
'bytes_rd': [],
'total_err': []
}
if not isinstance(l4_data, list):
l4_data = [{l4_data['name']: l4_data}]
idx = 0
for cx in cx_list:
cx_found = False
for i in l4_data:
for cx_name, value in i.items():
if cx == cx_name:
l4_dict['uc_avg_data'].append(value['uc-avg'])
l4_dict['uc_max_data'].append(value['uc-max'])
l4_dict['uc_min_data'].append(value['uc-min'])
l4_dict['url_times'].append(value['total-urls'])
l4_dict['rx_rate'].append(value['rx rate (1m)'])
l4_dict['bytes_rd'].append(value['bytes-rd'])
l4_dict['total_err'].append(value['total-err'])
cx_found = True
if not cx_found:
self.failed_cx.append(cx)
l4_dict['uc_avg_data'].append(0 if not self.tracking_map else self.tracking_map['uc_avg_data'][idx])
l4_dict['uc_max_data'].append(0 if not self.tracking_map else self.tracking_map['uc_max_data'][idx])
l4_dict['uc_min_data'].append(0 if not self.tracking_map else self.tracking_map['uc_min_data'][idx])
l4_dict['url_times'].append(0 if not self.tracking_map else self.tracking_map['url_times'][idx])
l4_dict['rx_rate'].append(0 if not self.tracking_map else self.tracking_map['rx_rate'][idx])
l4_dict['bytes_rd'].append(0 if not self.tracking_map else self.tracking_map['bytes_rd'][idx])
l4_dict['total_err'].append(0 if not self.tracking_map else self.tracking_map['total_err'][idx])
idx += 1
self.tracking_map = l4_dict.copy()
return l4_dict
def aggregate_rx_bytes(self, rx_rate, bytes_rd):
"""
Compute average RX rate and update max bytes read.
- Calculate device-wise average RX rate considering the values from start of test (ignore zero values)
- Store averaged RX rates in self.rx_rate (rounded to 4 decimals)
- Convert RX rate from bps to Mbps
- Update self.bytes_rd with maximum values observed so far
Args:
rx_rate_val (list of list): RX rate values per device over time
max_bytes_rd (list): Previously recorded max bytes read
Returns:
rx_rate (list): Current averaged RX rates in Mbps
bytes_rd (list): Current updated max bytes read
"""
if len(self.max_bytes_rd) == 0:
self.max_bytes_rd = list(bytes_rd)
for i in range(len(self.max_bytes_rd)):
bytes_rd[i] = max(self.max_bytes_rd[i], bytes_rd[i])
self.max_bytes_rd = list(bytes_rd)
self.rx_rate_val.append(list(rx_rate))
# taking average of rx-rate from the previous and current in the first row
for j in range(len(self.rx_rate_val[0])):
rx_rate_sum = 0
non_zero = 0
for i in range(len(self.rx_rate_val)):
if self.rx_rate_val[i][j] != 0:
rx_rate_sum += self.rx_rate_val[i][j]
non_zero += 1
rx_rate_avg = rx_rate_sum / non_zero if non_zero > 0 else 0 # updating each device's rx rate average in 1st row
rx_rate[j] = round(rx_rate_avg, 4)
return list(rx_rate), list(bytes_rd)
def monitor_for_runtime_csv(self, duration):
time_now = datetime.now()
starttime = time_now.strftime("%d/%m %I:%M:%S %p")
# duration = self.traffic_duration
endtime = time_now + timedelta(seconds=duration)
end_time = endtime
# endtime = endtime
current_time = datetime.now()
self.data = {}
self.data["client"] = self.devices_list
# self.data["url_data"] = []
self.data_for_webui = {}
self.data_for_webui["client"] = self.devices_list
self.get_device_port_details()
# Creating individual Dataframe for each device
for port in self.port_list:
# Added this check to handle multiple external monitor calls for band steering.
# This is common to both cases and does not affect the current execution.
# It simply ensures safe handling when the monitor is invoked from lf_base_robo.
if port not in self.individual_device_data:
columns = ['TIMESTAMP', 'Bytes-rd', 'total urls', 'download_rate', 'rx_rate', 'tx_rate', 'RSSI', 'BSSID', 'Channel']
if self.do_bandsteering:
columns.append('From Coordinate')
columns.append('To Coordinate')
columns.append('Robot X')
columns.append('Robot Y')
self.individual_device_data[port] = pd.DataFrame(columns=columns)
test_stopped_by_user = False
monitor_charge_time = current_time
while (current_time < endtime):
# If robot test mode is enabled, periodically check if a battery pause is needed
if self.robot_test:
# Check if enough time has passed to trigger a battery check (300 sec)
if (datetime.now() - monitor_charge_time).total_seconds() >= 300:
pause_start = datetime.now()
# Wait for the robot to charge. Returns whether we paused and whether user aborted.
pause, test_stopped_by_user = self.robot_obj.wait_for_battery(stop=self.stop)
if test_stopped_by_user:
break
if pause:
# After charging, return to the last coordinate
reached, abort = self.robot_obj.move_to_coordinate(self.current_coordinate)
# If user stopped the test during movement
if abort:
test_stopped_by_user = True
break
if not reached:
# test_stopped_by_user = True
break
# Restore orientation if rotation is enabled
if self.rotation_enabled:
rotation_moni = self.robot_obj.rotate_angle(self.current_angle)
if not rotation_moni:
test_stopped_by_user = True
break
# restart traffic
self.start()
# Add pause duration to overall end time
pause_end = datetime.now()
charge_pause = pause_end - pause_start
endtime += charge_pause
# Reset battery-monitor timer
monitor_charge_time = datetime.now()
# IMPORTANT: Update loop time
current_time = datetime.now()
# data in json format
# data = self.json_get("layer4/list?fields=bytes-rd")
# uc_avg_data = self.json_get("layer4/list?fields=uc-avg")
# uc_max_data = self.json_get("layer4/list?fields=uc-max")
# uc_min_data = self.json_get("layer4/list?fields=uc-min")
# total_url_data = self.json_get("layer4/list?fields=total-urls")
# bytes_rd = self.json_get("layer4/list?fields=bytes-rd")
l4_dict = self.get_layer4_data()
uc_avg_data = l4_dict['uc_avg_data']
uc_max_data = l4_dict['uc_max_data']
uc_min_data = l4_dict['uc_min_data']
url_times = l4_dict['url_times']
rx_rate = l4_dict['rx_rate']
bytes_rd = l4_dict['bytes_rd']
total_err = l4_dict['total_err']
urls_downloaded = []
for i in range(len(total_err)):
urls_downloaded.append(url_times[i] - total_err[i])
url_times = list(urls_downloaded)
self.data["MAC"] = self.macid_list
self.data["SSID"] = self.ssid_list
self.data["Channel"] = self.channel_list
self.data["Mode"] = self.mode_list
rssi_list, tx_rate_list, rx_rate_list, bssid_list, channel_list = self.get_signal_and_link_speed_data() # these data collected from port manager
individual_rx_data = []
individual_rx_data.extend([current_time])
for i, port in enumerate(self.port_list):
# logger.info(f"row data HTTP",row_data)
try:
row_data = [current_time, bytes_rd[i], url_times[i], rx_rate[i], rx_rate_list[i], tx_rate_list[i], rssi_list[i], bssid_list[i], channel_list[i]]
if self.do_bandsteering:
robo_x, robo_y, from_coord, to_coord = self.robot_obj.get_robot_pose()
row_data.extend([from_coord, to_coord, robo_x, robo_y])
self.individual_device_data[port].loc[len(self.individual_device_data[port])] = row_data
except Exception:
# Fail-safe: if any list index/key mismatch occurs while adding row_data,
# stop execution to avoid inconsistent results.
tb_str = traceback.format_exc() # capture traceback as string
logger.error("An exception occurred:\n%s", tb_str)
exit(1)
rx_rate, bytes_rd = self.aggregate_rx_bytes(rx_rate, bytes_rd)
# dataset = [round(x / 1000000,4) for x in dataset] #converting bps to mbps
if len(url_times) == len(self.devices_list):
self.data["status"] = ["RUNNING"] * len(self.devices_list)
self.data["url_data"] = url_times
self.data["uc_min"] = uc_min_data
self.data["uc_max"] = uc_max_data
self.data["uc_avg"] = uc_avg_data
self.data["bytes_rd"] = bytes_rd
self.data["rx rate (1m)"] = rx_rate
self.data["total_err"] = total_err
else:
self.data["status"] = ["RUNNING"] * len(self.devices_list)
self.data["url_data"] = [0] * len(self.devices_list)
self.data["uc_avg"] = [0] * len(self.devices_list)
self.data["uc_max"] = [0] * len(self.devices_list)
self.data["uc_min"] = [0] * len(self.devices_list)
self.data["bytes_rd"] = [0] * len(self.devices_list)
self.data["rx rate (1m)"] = [0] * len(self.devices_list)
self.data["total_err"] = [0] * len(self.devices_list)
time_difference = abs(end_time - datetime.now())
total_hours = time_difference.total_seconds() / 3600
remaining_minutes = (total_hours % 1) * 60
self.data["start_time"] = [starttime] * len(self.devices_list)
if self.robot_test:
# To update end time at each interval
end_time = endtime
self.data["end_time"] = [end_time.strftime("%d/%m %I:%M:%S %p")] * len(self.devices_list)
self.data["remaining_time"] = [[str(int(total_hours)) + " hr and " + str(
int(remaining_minutes)) + " min" if int(total_hours) != 0 or int(remaining_minutes) != 0 else '<1 min'][
0]] * len(self.devices_list)
if self.robot_test and self.rotation_enabled:
self.data["current_angle"] = [self.current_angle] * len(self.devices_list)
try:
df1 = pd.DataFrame(self.data)
except Exception:
tb_str = traceback.format_exc() # capture traceback as string
logger.error("An exception occurred:\n%s", tb_str)
exit(1)
if self.dowebgui:
df1.to_csv('{}/http_datavalues.csv'.format(self.result_dir), index=False)
if not self.do_bandsteering and self.robot_test:
df1.to_csv(f"{self.result_dir}/{self.current_coordinate}_http_datavalues.csv", index=False)
elif self.client_type == 'Real':
df1.to_csv("http_datavalues.csv", index=False)
# IF ROBOT TEST PERFORMED
if not self.do_bandsteering and self.robot_test:
# Save FTP data values for the current coordinate when in robot test
df1.to_csv(f"{self.current_coordinate}_http_datavalues.csv", index=False)
# No sleep is added here for band steering, as we need to capture data every second.
# The per-second sleep interval is already handled in lf_base_robo.
if not self.do_bandsteering:
time.sleep(5)
if self.dowebgui == "True":
with open(self.result_dir + "/../../Running_instances/{}_{}_running.json".format(self.host,
self.test_name),
'r') as file:
data = json.load(file)
if data["status"] != "Running":
print('Test is stopped by the user')
self.data["end_time"] = [datetime.now().strftime("%d/%m %I:%M:%S %p")] * len(self.devices_list)
test_stopped_by_user = True
break
current_time = datetime.now()
# Reusing monitor logic for band steering, but only need one record per call,
# so break after first iteration instead of running for full duration.
if self.do_bandsteering:
break
individual_device_csv_names = [] # To store individial device csv names
# Iterate over each port and its corresponding DataFrame in the dictionary Saving the DataFrame to CSV
for port, df in self.individual_device_data.items():
df.to_csv(f"{endtime}-http-{port}.csv", index=False)
individual_device_csv_names.append(f'{endtime}-http-{port}')
self.individual_device_csv_names = individual_device_csv_names.copy()
try:
all_l4_data = self.get_all_l4_data()
df = pd.DataFrame(all_l4_data)
df.to_csv("all_l4_data.csv", index=False)
except Exception:
logger.error("All l4 data not found")
return test_stopped_by_user
def get_all_l4_data(self):
"""
Fetches the complete set of Layer-4 data and writes it to a dictionary
Returns: