Repository navigation
Expand file tree
/
Copy pathlf_interop_real_browser_test.py
More file actions
executable file
·1961 lines (1704 loc) · 93.9 KB
/
Copy pathlf_interop_real_browser_test.py
File metadata and controls
executable file
·1961 lines (1704 loc) · 93.9 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
"""
Purpose: To be generic script for LANforge-Interop devices(Real clients) which runs layer4-7 traffic
For now the test script supports Real Browser test for Androids.
Pre-requisites: Real clients should be connected to the LANforge MGR and Interop app should be open on the real clients which are connected to Lanforge
Example: (python3 or ./)lf_interop_real_browser_test.py --mgr 192.168.214.219 --duration 10m --url "www.google.com"
Example-1 :
Command Line Interface to run url in the Browser with specified URL and duration:
python3 lf_interop_real_browser_test.py --mgr 192.168.214.219 --url "www.google.com" --duration 10m --debug
CASE-1:
If not specified it takes the default url (default url is www.google.com)
Example-2:
Command Line Interface to run url in the Browser with specified Resources:
python3 lf_interop_real_browser_test.py --mgr 192.168.214.219 --url "www.google.com" --duration 10m --device_list 1.10,1.12 --debug
Example-3:
Command Line Interface to run url in the Browser with specified urls_per_tennm (specify the number of url you want to test in the given duration):
python3 lf_interop_real_browser_test.py --mgr 192.168.214.219 --url "www.google.com" --duration 10m --device_list 1.10,1.12 --urls_per_tenm 10 --debug
CASE-1:
If not specified it takes the default urls_per_tenm value (default urls_per_tenm is 100)
Example-4:
Command Line Interface to run the the Real Browser test with incremental Capacity by specifying the --incremental flag
python3 lf_interop_real_browser_test.py --mgr 192.168.214.219 --url "www.google.com" --duration 10m --device_list 1.10,1.12 --urls_per_tenm 10 --incremental --debug
Example-5:
Command Line Interface to run the the Real Browser test in webGUI by specifying the --dowebgui flag
python3 lf_interop_real_browser_test.py --mgr 192.168.214.219 --url "www.google.com" --duration 10m --device_list 1.10,1.12 --urls_per_tenm 10 --dowebgui --debug
Example-6:
Command Line Interface to run url in the Browser with precleanup:
python3 lf_interop_real_browser_test.py --mgr 192.168.214.219 --url "www.google.com" --duration 10m --device_list 1.10,1.12 --precleanup --debug
Example-7:
Command Line Interface to run url in the Browser with postcleanup:
python3 lf_interop_real_browser_test.py --mgr 192.168.214.219 --url "www.google.com" --duration 10m --device_list 1.10,1.12 --postcleanup --debug
SCRIPT CLASSIFICATION: Test
SCRIPT_CATEGORIES: Performance, Functional, Report Generation
NOTES:
1. Use './lf_interop_real_browser_test.py --help' to see command line usage and options.
2. Always specify the duration in minutes (for example: --duration 3 indicates a duration of 3 minutes).
3. If --device_list are not given after passing the CLI, a list of available devices will be displayed on the terminal.
4. For --url, you can specify the URL (e.g., www.google.com).
5. To run the test by specifying the incremental capacity, enable the --incremental flag.
STATUS: BETA RELEASE
VERIFIED_ON:
Working date - 29/07/2024
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.
"""
import sys
import os
import importlib
import argparse
import time
import pandas as pd
import logging
import json
import shutil
from datetime import datetime, timedelta
from lf_graph import lf_bar_graph_horizontal
# Check Python version compatibility
if sys.version_info[0] != 3:
print("This script requires Python3")
exit()
# Add parent directory to the system path
sys.path.append(os.path.join(os.path.abspath(__file__ + "../../../")))
# Import specific modules from custom paths using importlib
interop_modify = importlib.import_module("py-scripts.lf_interop_modify")
base = importlib.import_module('py-scripts.lf_base_interop_profile')
lf_csv = importlib.import_module("py-scripts.lf_csv")
realm = importlib.import_module("py-json.realm")
Realm = realm.Realm
base_RealDevice = base.RealDevice
lf_report = importlib.import_module("py-scripts.lf_report")
lf_report_pdf = importlib.import_module("py-scripts.lf_report")
lf_graph = importlib.import_module("py-scripts.lf_graph")
# Set up logging configuration for the script
logger = logging.getLogger(__name__)
lf_logger_config = importlib.import_module("py-scripts.lf_logger_config")
class RealBrowserTest(Realm):
def __init__(self, host, ssid, passwd, encryp, suporrted_release=None, max_speed=None, url=None,
urls_per_tenm=None, duration=None, resource_ids=None, dowebgui=False, result_dir="", test_name=None, incremental=None, postcleanup=False, precleanup=False):
super().__init__(lfclient_host=host, lfclient_port=8080)
# Initialize attributes with provided parameters
self.host = host
self.ssid = ssid
self.passwd = passwd
self.encryp = encryp
self.supported_release = suporrted_release
self.max_speed = max_speed
self.url = url
self.urls_per_tenm = urls_per_tenm
self.duration = duration
self.resource_ids = resource_ids
self.dowebgui = dowebgui
self.result_dir = result_dir
self.test_name = test_name
self.incremental = incremental
self.postCleanUp = postcleanup
self.preCleanUp = precleanup
# Initialize additional attributes
self.adb_device_list = None
self.phn_name = []
self.device_name = []
self.android_devices = []
self.other_os_list = []
self.android_list = []
self.other_list = []
self.real_sta_data_dict = {}
self.health = None
self.phone_data = None
# Initialize RealDevice instance
self.devices = base_RealDevice(manager_ip=self.host, selected_bands=[])
# Initialize local realm
self.local_realm = realm.Realm(lfclient_host=self.host, lfclient_port=8080)
# Initialize HTTP profile for testing
self.http_profile = self.local_realm.new_http_profile()
# Initialize interoperability instance for WiFi testing
self.interop = base.BaseInteropWifi(manager_ip=self.host,
port=8080,
ssid=self.ssid,
passwd=self.passwd,
encryption=self.encryp,
release=self.supported_release,
screen_size_prcnt=0.4,
_debug_on=False,
_exit_on_error=False)
# Initialize utility
self.utility = base.UtilityInteropWifi(host_ip=self.host)
# Initialize generic endpoints profile
# self.generic_endps_profile = self.new_generic_endp_profile()
# self.generic_endps_profile.type = 'youtube'
# self.generic_endps_profile.name_prefix = "yt"
@property
def run(self):
"""
Property method to execute the browser test.
This method performs several actions:
1. Checks various configurations on the Interop tab using lf_base_interop_profile.py library.
2. Retrieves details of connected devices and logs them.
3. Stops ongoing processes on devices.
4. Applies batch modifications and sets user names.
5. Forgets network connections on devices.
6. Retrieves health status for each device and logs it.
7. Launches the Interop UI for devices connected to the expected SSID.
8. Retrieves and logs resource data of phones.
"""
# Check various configuration things on Interop tab, Uses lf_base_interop_profile.py library
self.adb_device_list = self.interop.check_sdk_release()
# Get device details for each adb device in the list
for i in self.adb_device_list:
self.device_name.append(self.interop.get_device_details(device=i, query="user-name"))
logging.info(self.device_name)
# Stop ongoing processes on devices
self.interop.stop()
# Apply batch modifications and set user names
for i in self.adb_device_list:
self.interop.batch_modify_apply(i)
time.sleep(5)
self.interop.set_user_name(device=self.adb_device_list)
# Forget network connections on devices
for i in self.adb_device_list:
self.utility.forget_netwrk(i)
# Initialize health dictionary for each device
health = dict.fromkeys(self.adb_device_list)
# Getting Health for each device
for i in self.adb_device_list:
# Get the state of the device
dev_state = self.utility.get_device_state(device=i)
logging.info("Device State : {dev_state}".format(dev_state=dev_state))
logging.info("device state" + dev_state)
# Check if the device state indicates it is connected
if dev_state == "COMPLETED,":
logging.info("phone is in connected state")
logging.info("phone is in connected state")
# Get the SSID of the connected device
ssid = self.utility.get_device_ssid(device=i)
# Check if the device is connected to the expected SSID
if ssid == self.ssid:
logging.info("device is connected to expected ssid")
logging.info("device is connected to expected ssid")
# Retrieve and log the health status of the device
health[i] = self.utility.get_wifi_health_monitor(device=i, ssid=self.ssid)
logging.info("health health:: ", health)
logging.info("Launching Interop UI")
logging.info("health :: {health}".format(health=health))
# Launch the Interop UI for the device
logging.info("Launching Interop UI")
self.interop.launch_interop_ui(device=i)
# Store the health dictionary in the instance variable
self.health = health
logging.info("Health:: ", health)
# Retrieve and log resource data of phones
self.phone_data = self.get_resource_data()
logging.info("Phone List : ", self.phone_data)
logging.info("Phone List : {phone_data}".format(phone_data=self.phone_data))
time.sleep(5) # Pause for 5 seconds before completing
def build(self):
"""
If the pre-requisites are satisfied, this function gets the list of real devices connected to LANforge
and processes them for Layer 4-7 traffic profile creation.
"""
# Initialize dictionaries and lists for data storage
self.data = {}
self.total_urls_dict = {}
self.data_for_webui = {}
self.all_cx_list = []
# Initialize lists for required parameters
self.req_total_urls = []
self.req_urls_per_sec = []
self.req_uc_min_val = []
self.req_uc_avg_val = []
self.req_uc_max_val = []
self.req_total_err = []
self.device_type = []
self.username = []
self.ssid = []
self.mac = []
self.mode = []
self.rssi = []
self.channel = []
self.tx_rate = []
self.time_data = []
self.temp = []
self.total_duration = ""
self.formatted_endtime_str = ""
# Retrieve resource data for phones
self.phone_data = self.get_resource_data()
logging.info("Creating Layer-4 endpoints from the user inputs as test parameters")
time.sleep(5)
# Configure HTTP profile settings
self.http_profile.direction = 'dl'
self.http_profile.dest = '/dev/null'
self.http_profile.max_speed = self.max_speed
self.http_profile.requests_per_ten = self.urls_per_tenm
self.http_profile.created_cx = self.convert_to_dict(self.phone_data)
if self.preCleanUp:
self.precleanup()
self.http_profile.created_cx.clear()
# for i in self.phone_data:
# self.phone_data = ['1.16.wlan0', '1.17.xlan0', '1.20.ylan0']
# Create HTTP profile
self.http_profile.create(ports=self.phone_data, sleep_time=.5,
suppress_related_commands_=None, http=True,
http_ip=self.url, interop=True, timeout=1000)
def convert_to_dict(self, input_list):
"""
Creating dictionary for devices for pre_cleanup
"""
output_dict = {}
for item in input_list:
parts = item.split('.')
device = parts[2]
key = f"{device}_http{parts[1]}_l4"
value = f"CX_{device}_http{parts[1]}_l4"
output_dict[key] = value
return output_dict
def get_incremental_capacity_list(self):
keys = list(self.http_profile.created_cx.keys())
incremental_temp = []
created_incremental_values = []
index = 0
if len(self.incremental) == 1 and self.incremental[0] == len(keys):
incremental_temp.append(len(keys[index:]))
elif len(self.incremental) == 1 and len(keys) > 1:
incremental_value = self.incremental[0]
div = len(keys) // incremental_value
mod = len(keys) % incremental_value
for i in range(div):
if len(incremental_temp):
incremental_temp.append(incremental_temp[-1] + incremental_value)
else:
incremental_temp.append(incremental_value)
if mod:
incremental_temp.append(incremental_temp[-1] + mod)
created_incremental_values = incremental_temp
if not created_incremental_values:
created_incremental_values = self.incremental
return created_incremental_values
def start(self):
# Starts the layer 4-7 traffic for created CX end points
"""
Starts the layer 4-7 traffic for created CX endpoints.
This method performs the following actions:
1. Sets the CX state to 'Running'.
2. Waits for each CX endpoint to reach the 'Running' state.
"""
logging.info("Test started at : {0} ".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
logging.info("Setting Cx State to Runnning")
# Start the CX for HTTP profile
self.http_profile.start_cx()
try:
# Loop through each CX endpoint and wait until it reaches the 'Run' state
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 as e: # noqa: F841
pass
def start_specific(self, cx_start_list):
"""
Starts the layer 4-7 traffic for specific CX endpoints.
Parameters:
- cx_start_list (list): List of CX endpoints to start.
performs the following actions:
1. Starts the specified CX endpoints using the provided list.
2. Sets the CX state to 'Running' for each specified CX endpoint.
"""
# Start specific CX endpoints using the provided list
logging.info("Test started at : {0} ".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
logger.info("Starting CXs...")
for cx_name in cx_start_list:
self.json_post("/cli-json/set_cx_state", {
"test_mgr": "default_tm",
"cx_name": self.http_profile.created_cx[cx_name],
"cx_state": "RUNNING"
}, debug_=self.debug)
logging.info("Setting Cx State to Runnning")
try:
# Loop through each CX endpoint and wait until it reaches the 'Run' state
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 as e: # noqa: F841
pass
# def create_generic_endp(self,query_resources,os_types_dict):
# """
# Creates generic endpoints for Real clients based on specified resources and operating system types.
# Parameters:
# - query_resources (list): List of resource identifiers to query.
# - os_types_dict (dict): Dictionary mapping resource identifiers to their respective operating system types.
# This method performs the following actions:
# 1. Retrieves information about available resources from LANforge.
# 2. Matches queried resources with available resources and retrieves their details.
# 3. Identifies matching ports based on control IPs and creates a list of ports.
# 4. Filters out Android devices from the list of operating system types.
# 5. Creates generic endpoints for Real clients using the generic endpoint profile.
# """
# ports_list = []
# eid = ""
# resource_ip = ""
# # Extract only the first two octets of each query resource identifier
# user_resources = ['.'.join(item.split('.')[:2]) for item in query_resources]
# exit_loop = False
# # Retrieve all resources from LANforge
# response = self.json_get("/resource/all")
# # Iterate through the response to find matching resources
# for key, value in response.items():
# if key == "resources" and user_resources:
# for element in value:
# if user_resources:
# for resource_key, resource_values in element.items():
# if resource_key in user_resources:
# eid = resource_values["eid"]
# resource_ip = resource_values['ctrl-ip']
# ports_list.append({'eid': eid, 'ctrl-ip': resource_ip})
# resource_key_index = user_resources.index(resource_key)
# del user_resources[resource_key_index]
# else:
# exit_loop = True
# break
# if exit_loop:
# break
# gen_ports_list = []
# # Retrieve all ports from LANforge
# response_port = self.json_get("/port/all")
# # Iterate through interfaces and ports to find matching ports based on control IPs - to retrieve the management port of the resources
# for interface in response_port['interfaces']:
# for port, port_data in interface.items():
# result = '.'.join(port.split('.')[:2])
# # Check if the result exists in ports_list
# matching_entry = next((entry for entry in ports_list if entry['eid'] == result), None)
# if matching_entry:
# port_ip = port_data['ip']
# if port_ip == matching_entry['ctrl-ip']:
# gen_ports_list.append(port.split('.')[-1])
# break
# gen_ports_list = ",".join(gen_ports_list)
# # Retrieve OS types excluding Android
# real_sta_os_types = [os_types_dict[resource_id] for resource_id in os_types_dict if os_types_dict[resource_id] != 'android']
# # Create generic endpoints using generic_endps_profile
# if (self.generic_endps_profile.create(ports=self.other_list, sleep_time=.5, real_client_os_types=real_sta_os_types, gen_port = gen_ports_list, from_script = "realbrowser")):
# logging.info('Real client generic endpoint creation completed.')
# else:
# logging.error('Real client generic endpoint creation failed.')
# exit(0)
# # Set endpoint report time to ping packet interval
# for endpoint in self.generic_endps_profile.created_endp:
# self.generic_endps_profile.set_report_timer(endp_name=endpoint, timer=250)
def stop(self):
"""
Stops the layer 4-7 traffic for created CX endpoints.
This method performs the following actions:
1. If resource IDs are provided, sets the remaining time in webGUI to "0:00:00".
2. Logs a message indicating the intention to set the CX state to 'Stopped'.
3. Stops the CX for HTTP profile.
"""
# Stops the layer 4-7 traffic for created CX end points
# Set remaining time in webGUI to "0:00:00" if resource IDs are provided
if self.resource_ids:
self.data['remaining_time_webGUI'] = ["0:00:00"] * len(self.data['status'])
logging.info("Setting Cx State to Stopped")
# Stop the CX for HTTP profile
self.http_profile.stop_cx()
def precleanup(self):
self.http_profile.cleanup()
def postcleanup(self):
# Cleans the layer 4-7 traffic for created CX end points
self.http_profile.cleanup()
def cleanup(self, os_types_dict):
"""
Cleans up generic endpoints and associated CX endpoints based on operating system types.
Parameters:
- os_types_dict (dict): Dictionary mapping station identifiers to their respective operating system types.
This method performs the following actions:
1. Checks each station in os_types_dict against self.other_os_list.
2. If a match is found, appends 'CX_yt-{station}' and 'yt-{station}' to created_cx and created_endp lists respectively.
3. Logs a message indicating the start of generic endpoint cleanup.
4. Calls cleanup method of generic_endps_profile to remove created endpoints.
5. Clears created_cx and created_endp lists.
6. Logs a message indicating successful cleanup.
"""
# Check each station in os_types_dict against self.other_os_list
for station in os_types_dict:
if any(item.startswith(station) for item in self.other_os_list):
# Append CX and endpoint names to created_cx and created_endp lists
self.generic_endps_profile.created_cx.append(
'CX_yt-{}'.format(station))
self.generic_endps_profile.created_endp.append(
'yt-{}'.format(station))
logging.info('Cleaning up generic endpoints if exists')
# Call cleanup method of generic_endps_profile to remove created endpoints
# self.generic_endps_profile.cleanup()
# # Clear created_cx and created_endp lists
# self.generic_endps_profile.created_cx = []
# self.generic_endps_profile.created_endp = []
logging.info('Cleanup Successful')
def my_monitor(self, data_mon):
"""
Retrieves monitoring data for the created CX endpoints based on specified data metrics.
Parameters:
- data_mon (str): Data metrics to monitor, provided as a string.
Returns:
- data1 (list): List containing monitoring data for the specified metrics across all created CX endpoints.
This method performs the following actions:
1. Constructs a URL to retrieve monitoring data from LANforge layer 4 API for all created CX endpoints.
2. Retrieves JSON-formatted monitoring data using the constructed URL and specified metrics.
3. Iterates through the retrieved data to extract and append the specified metric values ('data_mon') to 'data1' list.
4. Returns 'data1', which contains monitoring data for the specified metrics across all created CX endpoints.
"""
# data in json format
# Construct URL to retrieve monitoring data for all created CX endpoints
data = self.local_realm.json_get("layer4/%s/list?fields=%s" %
(','.join(self.http_profile.created_cx.keys()), data_mon.replace(' ', '+')))
data1 = []
data = data['endpoint']
# Check if only one CX endpoint is created
if len(self.http_profile.created_cx.keys()) == 1:
for cx in self.http_profile.created_cx.keys():
if cx in data['name']:
data1.append(data[data_mon])
else:
# Iterate through each created CX endpoint
for cx in self.http_profile.created_cx.keys():
for info in data:
if cx in info:
data1.append(info[cx][data_mon])
return data1
def get_resource_data(self):
"""
Retrieves data for Real devices connected to LANforge.
Returns:
- station_name (list): List of station names corresponding to the Real devices connected to LANforge.
This method performs the following actions:
1. Retrieves information about LANforge ports including alias, MAC address, mode, parent device, RX rate, TX rate,
SSID, and signal strength.
2. If self.resource_ids is provided, converts it into a list of integers.
3. Iterates through the retrieved data to extract relevant information for devices connected to WLAN (alias 'wlan0').
4. Filters and collects station names based on specific criteria, appending them to 'station_name'.
5. Returns 'station_name', a list containing station names of Real devices connected to LANforge.
"""
# Gets the list of Real devices connected to LANforge
resource_id_list = []
phone_name_list = []
mac_address = []
user_name = []
phone_radio = []
rx_rate = []
tx_rate = []
station_name = []
ssid = []
# Retrieve data from LANforge port Manager tab including alias, MAC address, mode, parent device, RX rate, TX rate, SSID, and signal strength
eid_data = self.json_get("ports?fields=alias,mac,mode,Parent Dev,rx-rate,tx-rate,ssid,signal")
resource_ids = []
if self.resource_ids:
# Convert self.resource_ids to a list of integers if provided
resource_ids = list(map(int, self.resource_ids.split(',')))
# Iterate through each row in eid_data["interfaces"]
for alias in eid_data["interfaces"]:
for i in alias:
if int(i.split(".")[1]) > 1 and alias[i]["alias"] == 'wlan0':
resource_id_list.append(i.split(".")[1])
resource_hw_data = self.json_get("/resource/" + i.split(".")[0] + "/" + i.split(".")[1])
hw_version = resource_hw_data['resource']['hw version']
# Check if the hardware version does not start with ('Win', 'Linux', 'Apple') and the resource ID is in resource_ids
if not hw_version.startswith(('Win', 'Linux', 'Apple')) and int(resource_hw_data['resource']['eid'].split('.')[1]) in resource_ids:
station_name.append(i)
mac = alias[i]["mac"]
rx = "Unknown" if (alias[i]["rx-rate"] == 0 or alias[i]["rx-rate"] == '') else alias[i]["rx-rate"]
tx = "Unknown" if (alias[i]["tx-rate"] == 0 or alias[i]["rx-rate"] == '') else alias[i]["tx-rate"]
ssid.append(alias[i]["ssid"])
rx_rate.append(rx)
tx_rate.append(tx)
# Get username from resource_hw_data
user = resource_hw_data['resource']['user']
user_name.append(user)
# Get user hardware details/name from resource_hw_data
hw_name = resource_hw_data['resource']['hw version'].split(" ")
name = " ".join(hw_name[0:2])
phone_name_list.append(name)
mac_address.append(mac)
if int(i.split(".")[1]) > 1 and alias[i]["alias"] == 'wlan0' and alias[i]["parent dev"] == 'wiphy0':
# Map radio name to human-readable format
if 'a' not in alias[i]['mode'] or "20" in alias[i]['mode']:
phone_radio.append('2G')
elif 'AUTO' in alias[i]['mode']:
phone_radio.append("AUTO")
else:
phone_radio.append('2G/5G')
return station_name
def monitor_for_runtime_csv(self, duration, file_path, resource_list_sorted=[], cx_list=[]):
"""
Monitors runtime data for a specified duration and saves it to a CSV file.
Parameters:
- duration: int, duration in minutes for monitoring
- file_path: str, path to save the CSV file
- resource_list_sorted: list, sorted list of resource IDs
- cx_list: list, list of CX (connection) IDs to monitor
Returns: None
"""
# if not self.all_cx_list :
# final_end_time_webGUI = datetime.now() + timedelta(minutes=int(self.total_duration))
# final_end_time_webGUI = str(final_end_time_webGUI.isoformat()[0:19])
# dt = datetime.strptime(final_end_time_webGUI, "%Y-%m-%dT%H:%M:%S")
# self.formatted_endtime_str = dt.strftime("%Y-%m-%d %H:%M:%S")
# print("formatted_endtime_str",self.formatted_endtime_str)
self.all_cx_list.extend(cx_list)
resource_ids = list(map(int, self.resource_ids.split(',')))
self.data_for_webui['resources'] = resource_ids
starttime = datetime.now()
# Get names of connections (CX) from my_monitor method
self.data["name"] = self.my_monitor('name')
df = pd.DataFrame(self.data)
# If 'start_time' column not present, initialize it to 0
# if 'start_time' not in df.columns:
# df['start_time'] = 0
# self.data['start_time'] = [starttime] * len(self.data["name"])
# self.data['start_time'] = df.apply(
# lambda row: (
# datetime.now() # Accumulate inc_value
# if row['start_time'] == 0 and row['name'] in cx_list
# else row['start_time'] # Keep existing inc_value
# ),
# axis=1
# )
current_time = datetime.now()
endtime = ""
endtime = starttime + timedelta(minutes=duration)
# final_end_time_webGUI = str(starttime + timedelta(minutes=self.total_duration))
endtime = endtime.isoformat()[0:19]
# dt = datetime.strptime(final_end_time_webGUI, "%Y-%m-%d %H:%M:%S")
# formatted_endtime_str = dt.strftime("%Y-%m-%d %H:%M:%S")
# if 'end_time' not in df.columns:
# df['end_time'] = 0
# Set end_time and remaining_time_webGUI if dowebgui is True
if self.dowebgui:
# self.data['end_time'] = [endtime] * len(self.data["name"])
end_time = datetime.strptime(endtime, "%Y-%m-%dT%H:%M:%S")
self.data["remaining_time"] = [end_time - current_time] * len(self.data['name'])
# else:
# # Set end_time based on conditions for items in cx_list
# # self.data['end_time'] = [0] * len(self.data["name"])
# self.data['end_time'] = df.apply(
# lambda row: (
# endtime # Set endtime if end_time is 0 and name is in cx_list
# if row['end_time'] == 0 and row['name'] in cx_list
# else row['end_time'] # Keep existing end_time
# ),
# axis=1
# )
endtime_check = datetime.strptime(endtime, "%Y-%m-%dT%H:%M:%S")
self.data['status'] = self.my_monitor('status')
self.data['required_count'] = [self.urls_per_tenm] * len(self.data['name'])
self.data['duration'] = [duration] * len(self.data['name'])
self.data['url'] = [self.url] * len(self.data['name'])
# Retrieve device information from LANforge ports
device_type = []
username = []
ssid = []
mac = []
channel = []
mode = []
rssi = []
channel = []
tx_rate = []
rx_rate = []
resource_ids = list(map(int, self.resource_ids.split(',')))
eid_data = self.json_get("ports?fields=alias,mac,mode,Parent Dev,rx-rate,tx-rate,ssid,signal,channel")
for alias in eid_data["interfaces"]:
for i in alias:
# alias[i]['mac'] alias[i]['ssid'] alias[i]['mode'] resource_hw_data['resource']['user']
if int(i.split(".")[1]) > 1 and alias[i]["alias"] == 'wlan0':
resource_hw_data = self.json_get("/resource/" + i.split(".")[0] + "/" + i.split(".")[1])
hw_version = resource_hw_data['resource']['hw version']
# Filter based on hw_version and resource_ids
if not hw_version.startswith(('Win', 'Linux', 'Apple')) and int(resource_hw_data['resource']['eid'].split('.')[1]) in resource_ids:
# Collect device information
device_type.append('Android')
username.append(resource_hw_data['resource']['user'])
ssid.append(alias[i]['ssid'])
mac.append(alias[i]['mac'])
mode.append(alias[i]['mode'])
rssi.append(alias[i]['signal'])
channel.append(alias[i]['channel'])
tx_rate.append(alias[i]['tx-rate'])
rx_rate.append(alias[i]['rx-rate'])
# Store device information in self.data
self.data['device_type'] = device_type
self.data['username'] = username
self.data['ssid'] = ssid
self.data['mac'] = mac
self.data['mode'] = mode
self.data['rssi'] = rssi
self.data['channel'] = channel
# self.data['tx_rate'] = tx_rate
# self.data['rx_rate'] = rx_rate
temp = []
# Initialize temp list for storing time data
for i in range(len(self.all_cx_list)):
temp.append(-1)
iterator = []
# Monitoring loop until current_time exceeds endtime
while current_time < endtime_check:
# Update end_time_webGUI
if self.data['end_time_webGUI'][0] < current_time.strftime('%Y-%m-%d %H:%M:%S'):
self.data['end_time_webGUI'] = [current_time.strftime('%Y-%m-%d %H:%M:%S')] * len(self.data['name'])
curr_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
endtime_dt = datetime.strptime(self.data['end_time_webGUI'][0], "%Y-%m-%d %H:%M:%S")
curr_time_dt = datetime.strptime(curr_time, "%Y-%m-%d %H:%M:%S")
remaining_time_dt = endtime_dt - curr_time_dt
one_minute = timedelta(minutes=1)
# Update remaining_time_webGUI
if remaining_time_dt < one_minute:
self.data['remaining_time_webGUI'] = ["< 1 min"] * len(self.data['status'])
else:
self.data['remaining_time_webGUI'] = [str(datetime.strptime(self.data['end_time_webGUI'][0], "%Y-%m-%d %H:%M:%S") - datetime.strptime(curr_time, "%Y-%m-%d %H:%M:%S"))] * len(self.data['status']) # noqa: E501
# c = 0
# Update status and other metrics using my_monitor method
self.data['status'] = self.my_monitor('status')
self.data["total_urls"] = self.my_monitor('total-urls')
self.data["urls_per_sec"] = self.my_monitor('urls/s')
self.data["uc_min"] = self.my_monitor('uc-min')
self.data["uc_avg"] = self.my_monitor('uc-avg')
self.data["uc_max"] = self.my_monitor('uc-max')
self.data["name"] = self.my_monitor('name')
self.data["total_err"] = self.my_monitor('total-err')
self.data["bad_proto"] = self.my_monitor('bad-proto')
self.data["bad_url"] = self.my_monitor('bad-url')
self.data["rslv_p"] = self.my_monitor('rslv-p')
self.data["rslv_h"] = self.my_monitor('rslv-h')
self.data["!conn"] = self.my_monitor('!conn')
self.data["timeout"] = self.my_monitor('timeout')
# Store metrics specific to this iteration
if cx_list:
iterator = self.all_cx_list
else:
iterator = resource_ids
# len_cx_list = len(cx_list)
# len_all_cx_list = len(self.all_cx_list)
for i in range(len(iterator)):
if self.all_cx_list[i] in cx_list:
# Handle present value conditions
if self.data['total_urls'][i] == self.urls_per_tenm or self.data['total_urls'][i] > self.urls_per_tenm:
if temp[i] == 0:
temp[i] = int((datetime.now() - current_time).total_seconds())
else:
if temp[i] == -1:
temp[i] = 0
else:
# Handle conditions based on total_urls_dict varibale
if self.total_urls_dict:
if ((self.data['total_urls'][i] - self.total_urls_dict[self.all_cx_list[i]][-1]) == self.urls_per_tenm or (self.data['total_urls'][i] - self.total_urls_dict[self.all_cx_list[i]][-1]) > self.urls_per_tenm): # noqa: E501
if temp[i] == -1:
temp[i] = int((datetime.now() - current_time).total_seconds())
# Check if the test is stopped by the user via web GUI
if self.dowebgui:
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":
logging.info('Test is stopped by the user')
k = 0
# Reset time_data if test is stopped
for num in self.time_data:
for j in range(len(num)):
if self.time_data[k][j] == -1:
self.time_data[k][j] = 0
k += 1
self.data["end_time"] = [datetime.now().strftime("%d/%m %I:%M:%S %p")] * len(self.data["end_time"])
break
# Update DataFrame with current data
df1 = pd.DataFrame(self.data)
# Save data to CSV file based on dowebgui condition
if self.dowebgui:
df1.to_csv('{}/rb_datavalues.csv'.format(self.result_dir), index=False)
else:
df1.to_csv(file_path, mode='w', index=False)
# Sleep for 1 second before next iteration
time.sleep(1)
current_time = datetime.now()
# Finalize end_time_webGUI
if self.data['end_time_webGUI'][0] < current_time.strftime('%Y-%m-%d %H:%M:%S'):
self.data['end_time_webGUI'] = [current_time.strftime('%Y-%m-%d %H:%M:%S')] * len(self.data['name'])
curr_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
curr_time_dt = datetime.strptime(curr_time, "%Y-%m-%d %H:%M:%S")
endtime_dt = datetime.strptime(self.data['end_time_webGUI'][0], "%Y-%m-%d %H:%M:%S")
self.data['remaining_time_webGUI'] = ["< 1 min"] * len(self.data['status'])
else:
self.data['remaining_time_webGUI'] = [str(datetime.strptime(self.data['end_time_webGUI'][0], "%Y-%m-%d %H:%M:%S") - datetime.strptime(curr_time, "%Y-%m-%d %H:%M:%S"))] * len(self.data['status']) # noqa: E501
# Update final metrics after monitoring loop completes
self.data["total_urls"] = self.my_monitor('total-urls')
self.data["urls_per_sec"] = self.my_monitor('urls/s')
self.data["uc_min"] = self.my_monitor('uc-min')
self.data["uc_avg"] = self.my_monitor('uc-avg')
self.data["uc_max"] = self.my_monitor('uc-max')
self.data["name"] = self.my_monitor('name')
self.data["total_err"] = self.my_monitor('total-err')
self.data["bad_proto"] = self.my_monitor('bad-proto')
self.data["bad_url"] = self.my_monitor('bad-url')
self.data["rslv_p"] = self.my_monitor('rslv-p')
self.data["rslv_h"] = self.my_monitor('rslv-h')
self.data["!conn"] = self.my_monitor('!conn')
self.data["timeout"] = self.my_monitor('timeout')
self.data["status"] = self.my_monitor('status')
if cx_list:
name = self.my_monitor('name')
total_urls = self.my_monitor('total-urls')
def add_to_dict(index):
for num in index:
key = name[num]
value = total_urls[num]
if key in self.total_urls_dict:
self.total_urls_dict[key].append(value)
else:
self.total_urls_dict[key] = [value]
# Iterate through the name and total_urls lists
index = []
for name_1 in self.all_cx_list:
i = 0
for name_2 in name:
if name_1 == name_2:
index.append(i)
break
i += 1
add_to_dict(index)
# len_cx_list = len(cx_list)
# len_all_cx_list = len(self.all_cx_list)
# Store time data in self.time_data and reset end_time if stopped
for i in range(len(iterator)):
if self.all_cx_list[i] in cx_list:
# present value
if self.data['total_urls'][i] == self.urls_per_tenm or self.data['total_urls'][i] > self.urls_per_tenm:
if temp[i] == 0:
temp[i] = int((datetime.now() - current_time).total_seconds())
else:
if temp[i] == -1:
temp[i] = 0
else:
if self.total_urls_dict:
if (self.data['total_urls'][i] - self.total_urls_dict[self.all_cx_list[i]][-1]) == self.urls_per_tenm or (self.data['total_urls'][i] - self.total_urls_dict[self.all_cx_list[i]][-1]) > self.urls_per_tenm: # noqa: E501
if temp[i] == -1:
temp[i] = int((datetime.now() - current_time).total_seconds())
prev_cx_list = len(self.all_cx_list) - len(cx_list)
for i in range(prev_cx_list):
if temp[i] == -1:
temp[i] = 0
self.time_data.append(temp)
# Storing the necessary data to generate the graph for multiple incremetnal values
labels = []
total_urls_dict_copy = self.total_urls_dict.copy()
keys = list(total_urls_dict_copy.keys())
usernames_csv = {}
df = pd.DataFrame(self.data)
df.apply(
lambda row: (
usernames_csv.update({row['name']: row['username']})
if row['name'] in self.all_cx_list
else None
),
axis=1
)
temp_usernames = []
idx = 0
for i in self.all_cx_list:
if idx < len(keys) and keys[idx] in total_urls_dict_copy and total_urls_dict_copy[keys[idx]]:
if keys[idx] in usernames_csv:
temp_usernames.append(usernames_csv[keys[idx]])
labels.append(temp_usernames)
idx += 1
if labels:
device_type = []
username = []
ssid = []
mac = []
channel = []
mode = []
rssi = []
channel = []
tx_rate = []
resource_ids = list(map(int, self.resource_ids.split(',')))
eid_data = self.json_get("ports?fields=alias,mac,mode,Parent Dev,rx-rate,tx-rate,ssid,signal,channel")
temp_username = []
temp_device_type = []
temp_ssid = []
temp_mac = []
temp_mode = []
temp_rssi = []
temp_channel = []
temp_tx_rate = []
for alias in eid_data["interfaces"]:
for i in alias:
# alias[i]['mac'] alias[i]['ssid'] alias[i]['mode'] resource_hw_data['resource']['user']
if int(i.split(".")[1]) > 1 and alias[i]["alias"] == 'wlan0':
resource_hw_data = self.json_get("/resource/" + i.split(".")[0] + "/" + i.split(".")[1])
hw_version = resource_hw_data['resource']['hw version']
if not hw_version.startswith(('Win', 'Linux', 'Apple')) and int(resource_hw_data['resource']['eid'].split('.')[1]) in resource_ids and resource_hw_data['resource']['user'] in labels[-1]: # noqa: E501
temp_device_type.append('Android')
temp_username.append(resource_hw_data['resource']['user'])
temp_ssid.append(alias[i]['ssid'])
temp_mac.append(alias[i]['mac'])
temp_mode.append(alias[i]['mode'])
temp_rssi.append(alias[i]['signal'])
temp_channel.append(alias[i]['channel'])
temp_tx_rate.append(alias[i]['tx-rate'])
self.username.append(temp_username)
self.device_type.append(temp_device_type)
self.ssid.append(temp_ssid)
self.mac.append(temp_mac)
self.mode.append(temp_mode)
self.rssi.append(temp_rssi)
self.channel.append(temp_channel)
self.tx_rate.append(temp_tx_rate)
total_urls = self.data['total_urls']
uc_min_val = self.data['uc_min']
uc_max_val = self.data['uc_max']
uc_avg_val = self.data['uc_avg']
total_err = self.data['total_err']
status = self.my_monitor('status')
temp_total_urls = []
temp_uc_min_val = []
temp_uc_max_val = []
temp_uc_avg_val = []
temp_total_err = []
for k in range(len(status)):
if status[k] == 'Run':
temp_total_urls.append(total_urls[k])
temp_uc_min_val.append(uc_min_val[k])
temp_uc_avg_val.append(uc_avg_val[k])
temp_uc_max_val.append(uc_max_val[k])
temp_total_err.append(total_err[k])
self.req_total_urls.append(temp_total_urls)
self.req_uc_min_val.append(temp_uc_min_val)
self.req_uc_avg_val.append(temp_uc_avg_val)
self.req_uc_max_val.append(temp_uc_max_val)
self.req_total_err.append(temp_total_err)
df = pd.DataFrame(self.data)
# Store final data in CSV file based on dowebgui condition
if self.dowebgui:
df.to_csv('{}/rb_datavalues.csv'.format(self.result_dir), index=False)
else: