-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlf_interop_ping.py
More file actions
executable file
·1895 lines (1692 loc) · 98.4 KB
/
lf_interop_ping.py
File metadata and controls
executable file
·1895 lines (1692 loc) · 98.4 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_ping.py
PURPOSE: lf_interop_ping.py will let the user select real devices, virtual devices or both and then allows them to run
ping test for user given duration and packet interval on the given target IP or domain name.
EXAMPLE-1:
Command Line Interface to run ping test with only virtual clients
python3 lf_interop_ping.py --mgr 192.168.200.103 --target 192.168.1.3 --virtual --num_sta 1 --radio 1.1.wiphy2 --ssid RDT_wpa2 --security wpa2
--passwd OpenWifi --ping_interval 1 --ping_duration 1 --server_ip 192.168.1.61 --debug
EXAMPLE-2:
Command Line Interface to run ping test with only real clients
python3 lf_interop_ping.py --mgr 192.168.200.103 --real --target 192.168.1.3 --ping_interval 1 --ping_duration 1 --server_ip 192.168.1.61 --ssid RDT_wpa2 --security wpa2_personal
--passwd OpenWifi
EXAMPLE-3:
Command Line Interface to run ping test with both real and virtual clients
python3 lf_interop_ping.py --mgr 192.168.200.103 --target 192.168.1.3 --real --virtual --num_sta 1 --radio 1.1.wiphy2 --ssid RDT_wpa2 --security wpa2
--passwd OpenWifi --ping_interval 1 --ping_duration 1 --server_ip 192.168.1.61
EXAMPLE-4:
Command Line Interface to run ping test with existing Wi-Fi configuration on the real devices
python3 lf_interop_ping.py --mgr 192.168.200.63 --real --target 192.168.1.61 --ping_interval 5 --ping_duration 1 --passwd OpenWifi --use_default_config
EXAMPLE-5:
Command Line Interface to run ping test by setting device specific Pass/Fail values in the csv file
python3 lf_interop_ping.py --mgr 192.168.244.97 --real --target 192.168.1.3 --ping_interval 1 --ping_duration 1 --device_csv_name device.csv
--use_default_config
EXAMPLE-6:
Command Line Interface to run ping test by setting the same expected Pass/Fail value for all devices
python3 lf_interop_ping.py --mgr 192.168.244.97 --real --target 192.168.1.3 --ping_interval 1 --ping_duration 1 --expected_passfail_value 3
--use_default_config
EXAMPLE-7:
Command Line Interface to run ping test by configuring Real Devices with SSID, Password, and Security
python3 lf_interop_ping.py --mgr 192.168.244.97 --real --target 192.168.1.3 --ping_interval 1 --ping_duration 1 --ssid RDT_wpa2 --security wpa2
--passwd OpenWifi --server_ip 192.168.244.97 --wait_time 30
EXAMPLE-8:
Command Line Interface to run ping test by Configuring Devices in Groups with Specific Profiles
python3 lf_interop_ping.py --mgr 192.168.244.97 --real --target 192.168.1.3 --ping_interval 1 --ping_duration 1 --group_name grp3 --file_name g219 --profile_name Open5
--server_ip 192.168.204.60
EXAMPLE-9:
Command Line Interface to run ping test by Configuring Devices in Groups with Specific Profiles with expected Pass/Fail values
python3 lf_interop_ping.py --mgr 192.168.244.97 --real --target 192.168.1.3 --ping_interval 1 --ping_duration 1 --group_name grp3 --file_name g219 --profile_name Open5
--expected_passfail_value 3 --server_ip 192.168.204.60
EXAMPLE-10:
Command Line Interface for Configuring Devices in Groups with Specific Profiles with device_csv_name
python3 lf_interop_ping.py --mgr 192.168.244.97 --real --target 192.168.1.3 --ping_interval 1 --ping_duration 1 --group_name grp3 --file_name g219 --profile_name Open5
--device_csv_name device.csv --server_ip 192.168.204.60
SCRIPT_CLASSIFICATION : Test
SCRIPT_CATEGORIES: Performance, Functional, Report Generation
NOTES:
1.Use './lf_interop_ping.py --help' to see command line usage and options
2.Please pass ping_duration in minutes
3.Please pass ping_interval in seconds
4.After passing the cli, if --real flag is selected, then a list of available real devices will be displayed on the terminal.
5.Enter the real device resource numbers seperated by commas (,)
STATUS: BETA RELEASE
VERIFIED_ON:
Working date - 20/09/2023
Build version - 5.4.7
kernel version - 6.2.16+
License: Free to distribute and modify. LANforge systems must be licensed.
Copyright 2023 Candela Technologies Inc.
'''
import argparse
import time
import sys
import os
import pandas as pd
import importlib
import logging
import traceback
import asyncio
import csv
import time
import shutil
from datetime import datetime, timedelta
if 'py-json' not in sys.path:
sys.path.append(os.path.join(os.path.abspath('..'), 'py-json'))
if 'py-scripts' not in sys.path:
sys.path.append('/home/lanforge/lanforge-scripts/py-scripts')
from lf_base_interop_profile import RealDevice
from lf_graph import lf_bar_graph_horizontal
from lf_report import lf_report
from station_profile import StationProfile
from typing import List, Optional
from LANforge import LFUtils
# Importing DeviceConfig to apply device configurations for ADB devices and laptops
DeviceConfig = importlib.import_module("py-scripts.DeviceConfig")
logger = logging.getLogger(__name__)
lf_logger_config = importlib.import_module("py-scripts.lf_logger_config")
if sys.version_info[0] != 3:
print("This script requires Python 3")
exit(1)
realm = importlib.import_module("py-json.realm")
Realm = realm.Realm
class Ping(Realm):
def __init__(self,
host=None,
port=None,
ssid=None,
security=None,
password=None,
radio=None,
target=None,
interval=None,
lanforge_password='lanforge',
sta_list=None,
virtual=None,
duration=1,
real=None,
debug=False, file_name=None,
profile_name=None,
group_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,
server_ip=None,
expected_passfail_val=None,
csv_name=None,
wait_time=60,
total_floors: int = None,
get_live_view: bool = None,
result_dir: str = None):
super().__init__(lfclient_host=host,
lfclient_port=port)
self.ssid_list = []
self.host = host
self.lanforge_password = lanforge_password
self.port = port
self.lfclient_host = host
self.lfclient_port = port
self.ssid = ssid
self.security = security
self.password = password
self.radio = radio
self.target = target
self.interval = interval
self.debug = debug
self.sta_list = sta_list
self.real_sta_list = []
self.real_sta_data_dict = {}
self.enable_virtual = virtual
self.enable_real = real
self.duration = duration
self.android = 0
self.virtual = 0
self.linux = 0
self.windows = 0
self.mac = 0
self.result_json = {}
self.generic_endps_profile = self.new_generic_endp_profile()
self.generic_endps_profile.type = 'lfping'
self.generic_endps_profile.dest = self.target
self.generic_endps_profile.interval = self.interval
self.Devices = None
self.total_floors = total_floors
self.get_live_view = get_live_view
self.result_dir = result_dir
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.profile_name = profile_name
self.file_name = file_name
self.group_name = group_name
self.server_ip = server_ip
self.real = real
self.expected_passfail_val = expected_passfail_val
self.csv_name = csv_name
self.pass_fail_list = []
self.test_input_list = []
self.percent_pac_loss = []
self.wait_time = wait_time
self.last_written_seq = {}
self.last_Result_per_Station = {}
self.start_time = None
def change_target_to_ip(self):
# checking if target is an IP or a port
if (self.target.count('.') != 3 and self.target.split('.')[-2].isnumeric()):
# checking if target is eth1 or 1.1.eth1
target_port_list = self.name_to_eid(self.target)
shelf, resource, port, _ = target_port_list
try:
target_port_ip = self.json_get('/port/{}/{}/{}?fields=ip'.format(shelf, resource, port))['interface']['ip']
except Exception:
tb_str = traceback.format_exc() # capture traceback as string
logger.error("An exception occurred:\n%s", tb_str)
logging.error('The target port {} not found on the LANforge. Please change the target.'.format(self.target))
exit(0)
self.target = target_port_ip
print(self.target)
else:
print(self.target)
def cleanup(self):
if (self.enable_virtual):
# removing virtual stations if existing
for station in self.sta_list:
logging.info('Removing the station {} if exists'.format(station))
self.generic_endps_profile.created_cx.append(
'CX_generic-{}'.format(station.split('.')[2]))
self.generic_endps_profile.created_endp.append(
'generic-{}'.format(station.split('.')[2]))
self.rm_port(station, check_exists=True)
if (not LFUtils.wait_until_ports_disappear(base_url=self.host, port_list=self.sta_list, debug=self.debug)):
logging.info('All stations are not removed or a timeout occured.')
logging.error('Aborting the test.')
exit(0)
if (self.enable_real):
# removing generic endpoints for real devices if existing
for station in self.real_sta_list:
self.generic_endps_profile.created_cx.append(
'CX_generic-{}'.format(station))
self.generic_endps_profile.created_endp.append(
'generic-{}'.format(station))
logging.info('Cleaning up generic endpoints if exists')
self.generic_endps_profile.cleanup()
self.generic_endps_profile.created_cx = []
self.generic_endps_profile.created_endp = []
logging.info('Cleanup Successful')
# Args:
# devices: Connected RealDevice object which has already populated tracked real device
# resources through call to get_devices()
def select_real_devices(self, real_devices, real_sta_list=None, base_interop_obj=None, device_list=None):
if real_sta_list is None:
self.real_sta_list, _, _ = real_devices.query_user(device_list=device_list)
else:
self.real_sta_list = real_sta_list
if base_interop_obj is not None:
self.Devices = base_interop_obj
# Need real stations to run interop test
if (len(self.real_sta_list) == 0):
logger.error('There are no real devices in this testbed. Aborting test')
exit(0)
logging.info(self.real_sta_list)
for sta_name in self.real_sta_list:
if sta_name not in real_devices.devices_data:
logger.error('Real station not in devices data, ignoring it from testing')
continue
# raise ValueError('Real station not in devices data')
self.real_sta_data_dict[sta_name] = real_devices.devices_data[sta_name]
# Track number of selected devices
self.android = self.Devices.android
self.windows = self.Devices.windows
self.mac = self.Devices.mac
self.linux = self.Devices.linux
d_list = []
for i in self.real_sta_list:
device = i.split('.')
d_list.append(device[0] + '.' + device[1])
return d_list
def buildstation(self):
logging.info('Creating Stations {}'.format(self.sta_list))
for station_index in range(len(self.sta_list)):
shelf, resource, port = self.sta_list[station_index].split('.')
logging.info('{} {} {}'.format(shelf, resource, port))
station_object = StationProfile(lfclient_url='http://{}:{}'.format(self.host, self.port), local_realm=self, ssid=self.ssid,
ssid_pass=self.password, security=self.security, number_template_='00', up=True, resource=resource, shelf=shelf)
station_object.use_security(
security_type=self.security, ssid=self.ssid, passwd=self.password)
station_object.create(radio=self.radio, sta_names_=[
self.sta_list[station_index]])
station_object.admin_up()
if self.wait_for_ip([self.sta_list[station_index]]):
self._pass("All stations got IPs", print_=True)
else:
self._fail(
"Stations failed to get IPs", print_=True)
def check_tab_exists(self):
response = self.json_get("generic")
if response is None:
return False
else:
return True
def create_generic_endp(self):
# Virtual stations are tracked in same list as real stations, so need to separate them
# in order to create generic endpoints for just the virtual stations
virtual_stations = list(set(self.sta_list).difference(set(self.real_sta_list)))
if (self.enable_virtual):
if (self.generic_endps_profile.create(ports=virtual_stations, sleep_time=.5)):
logging.info('Virtual client generic endpoint creation completed.')
else:
logging.error('Virtual client generic endpoint creation failed.')
exit(0)
if (self.enable_real):
real_sta_os_types = [self.real_sta_data_dict[real_sta_name]['ostype'] for real_sta_name in self.real_sta_data_dict]
if (self.generic_endps_profile.create(ports=self.real_sta_list, sleep_time=.5, real_client_os_types=real_sta_os_types)):
logging.info('Real client generic endpoint creation completed.')
else:
logging.error('Real client generic endpoint creation failed.')
exit(0)
def start_generic(self):
self.generic_endps_profile.start_cx()
def monitor_virtual(self, result_data,ports_data,ping_stats,rtts,rtts_list):
if isinstance(result_data, dict):
for station in self.sta_list:
if station not in self.real_sta_list:
current_device_data = ports_data[station]
if station.split('.')[2] in result_data['name']:
self.result_json[station] = {
'command': result_data['command'],
'sent': result_data['tx pkts'],
'recv': result_data['rx pkts'],
'dropped': result_data['dropped'],
'mac': current_device_data['mac'],
'ip': current_device_data['ip'],
'bssid': current_device_data['ap'],
'ssid': current_device_data['ssid'],
'channel': current_device_data['channel'],
'mode': current_device_data['mode'],
'name': station,
'os': 'Virtual',
'remarks': [],
'last_result': self.get_safe_last_result(ping_data.get('last results', ''))
}
ping_stats[station]['sent'].append(result_data['tx pkts'])
ping_stats[station]['received'].append(result_data['rx pkts'])
ping_stats[station]['dropped'].append(result_data['dropped'])
self.result_json[station]['ping_stats'] = ping_stats[station]
if len(result_data['last results']) != 0 and 'min/avg/max' in result_data['last results']:
temp_last_results = result_data['last results'].split('\n')[0: len(result_data['last results']) - 1]
drop_count = 0 # let dropped = 0 initially
dropped_packets = []
# sample result - 64 bytes from 192.168.1.61: icmp_seq=28 time=3.66 ms *** drop: 0 (0, 0.000) rx: 28 fail: 0 bytes: 1792 min/avg/max: 2.160/3.422/5.190
for result in temp_last_results:
try:
# fetching the first part of the last result e.g., 64 bytes from 192.168.1.61: icmp_seq=28 time=3.66 ms into t_result and the remaining part into t_fail
t_result, t_fail = result.split('***')
except BaseException:
continue
t_result = t_result.split()
if 'icmp_seq=' not in result and 'time=' not in result:
continue
for t_data in t_result:
if 'icmp_seq=' in t_data:
seq_number = int(t_data.strip('icmp_seq='))
if 'time=' in t_data:
rtt = float(t_data.strip('time='))
rtts[station][seq_number] = rtt
rtts_list.append(rtt)
# finding dropped packets
t_fail = t_fail.split() # [' drop:', '0', '(0, 0.000)', 'rx:', '28', 'fail:', '0', 'bytes:', '1792', 'min/avg/max:', '2.160/3.422/5.190']
t_drop_val = t_fail[1] # t_drop_val = '0'
t_drop_val = int(t_drop_val) # type cast string to int
if t_drop_val != drop_count:
current_drop_packets = t_drop_val - drop_count
drop_count = t_drop_val
for drop_packet in range(1, current_drop_packets + 1):
dropped_packets.append(seq_number - drop_packet)
if rtts_list == []:
rtts_list = [0]
min_rtt = str(min(rtts_list))
avg_rtt = str(sum(rtts_list) / len(rtts_list))
max_rtt = str(max(rtts_list))
self.result_json[station]['min_rtt'] = min_rtt
self.result_json[station]['avg_rtt'] = avg_rtt
self.result_json[station]['max_rtt'] = max_rtt
if list(rtts[station].keys()) != []:
required_sequence_numbers = list(range(1, max(rtts[station].keys())))
for seq in required_sequence_numbers:
if seq not in rtts[station].keys():
if seq in dropped_packets:
rtts[station][seq] = 0
else:
rtts[station][seq] = 0.11
else:
self.result_json[station]['rtts'] = {}
self.result_json[station]['rtts'] = rtts[station]
self.result_json[station]['remarks'] = self.generate_remarks(self.result_json[station])
# self.result_json[station]['dropped_packets'] = dropped_packets
else:
for station in self.sta_list:
if station not in self.real_sta_list:
current_device_data = ports_data[station]
for ping_device in result_data:
ping_endp, ping_data = list(ping_device.keys())[
0], list(ping_device.values())[0]
if station.split('.')[2] in ping_endp:
self.result_json[station] = {
'command': ping_data['command'],
'sent': ping_data['tx pkts'],
'recv': ping_data['rx pkts'],
'dropped': ping_data['dropped'],
'mac': current_device_data['mac'],
'ip': current_device_data['ip'],
'bssid': current_device_data['ap'],
'ssid': current_device_data['ssid'],
'channel': current_device_data['channel'],
'mode': current_device_data['mode'],
'name': station,
'os': 'Virtual',
'remarks': [],
'last_result': self.get_safe_last_result(ping_data.get('last results', ''))
}
ping_stats[station]['sent'].append(ping_data['tx pkts'])
ping_stats[station]['received'].append(ping_data['rx pkts'])
ping_stats[station]['dropped'].append(ping_data['dropped'])
self.result_json[station]['ping_stats'] = ping_stats[station]
if len(ping_data['last results']) != 0 and 'min/avg/max' in ping_data['last results']:
temp_last_results = ping_data['last results'].split('\n')[0: len(ping_data['last results']) - 1]
drop_count = 0 # let dropped = 0 initially
dropped_packets = []
# sample result - 64 bytes from 192.168.1.61: icmp_seq=28 time=3.66 ms *** drop: 0 (0, 0.000) rx: 28 fail: 0 bytes: 1792 min/avg/max: 2.160/3.422/5.190
for result in temp_last_results:
try:
# fetching the first part of the last result e.g., 64 bytes from 192.168.1.61: icmp_seq=28 time=3.66 ms into t_result and the remaining part into t_fail
t_result, t_fail = result.split('***')
except BaseException:
continue # first line of ping result
t_result = t_result.split()
if 'icmp_seq=' not in result and 'time=' not in result:
continue
for t_data in t_result:
if 'icmp_seq=' in t_data:
seq_number = int(t_data.strip('icmp_seq='))
if 'time=' in t_data:
rtt = float(t_data.strip('time='))
rtts[station][seq_number] = rtt
rtts_list.append(rtt)
# finding dropped packets
t_fail = t_fail.split() # [' drop:', '0', '(0, 0.000)', 'rx:', '28', 'fail:', '0', 'bytes:', '1792', 'min/avg/max:', '2.160/3.422/5.190']
t_drop_val = t_fail[1] # t_drop_val = '0'
t_drop_val = int(t_drop_val) # type cast string to int
if t_drop_val != drop_count:
current_drop_packets = t_drop_val - drop_count
drop_count = t_drop_val
for drop_packet in range(1, current_drop_packets + 1):
dropped_packets.append(seq_number - drop_packet)
if rtts_list == []:
rtts_list = [0]
min_rtt = str(min(rtts_list))
avg_rtt = str(sum(rtts_list) / len(rtts_list))
max_rtt = str(max(rtts_list))
self.result_json[station]['min_rtt'] = min_rtt
self.result_json[station]['avg_rtt'] = avg_rtt
self.result_json[station]['max_rtt'] = max_rtt
if list(rtts[station].keys()) != []:
required_sequence_numbers = list(range(1, max(rtts[station].keys())))
for seq in required_sequence_numbers:
if seq not in rtts[station].keys():
if seq in dropped_packets:
rtts[station][seq] = 0
else:
rtts[station][seq] = 0.11
else:
self.result_json[station]['rtts'] = {}
self.result_json[station]['rtts'] = rtts[station]
self.result_json[station]['remarks'] = self.generate_remarks(self.result_json[station])
# self.result_json[station]['dropped_packets'] = dropped_packets
def monitor_real(self,result_data,Devices,ping_stats,rtts,rtts_list):
if isinstance(result_data, dict):
for station in self.real_sta_list:
current_device_data = Devices.devices_data[station]
# logging.info(current_device_data)
if station in result_data['name']:
# logging.info(result_data['last results'].split('\n'))
if len(result_data['last results']) != 0:
result = result_data['last results'].split('\n')
if len(result) > 1:
last_result = result[-2]
else:
last_result = result[-1]
else:
last_result = ""
hw_version = current_device_data['hw version']
if "Win" in hw_version:
os = "Windows"
elif "Linux" in hw_version:
os = "Linux"
elif "Apple" in hw_version:
os = "Mac"
else:
os = "Android"
self.result_json[station] = {
'command': result_data['command'],
'sent': result_data['tx pkts'],
'recv': result_data['rx pkts'],
'dropped': result_data['dropped'],
'mac': current_device_data['mac'],
'ip': current_device_data['ip'],
'bssid': current_device_data['ap'],
'ssid': current_device_data['ssid'],
'channel': current_device_data['channel'],
'mode': current_device_data['mode'],
'name': [current_device_data['user'] if current_device_data['user'] != '' else current_device_data['hostname']][0],
'os': os,
'remarks': [],
'last_result': [last_result][0]
}
ping_stats[station]['sent'].append(result_data['tx pkts'])
ping_stats[station]['received'].append(result_data['rx pkts'])
ping_stats[station]['dropped'].append(result_data['dropped'])
self.result_json[station]['ping_stats'] = ping_stats[station]
if len(result_data['last results']) != 0:
temp_last_results = result_data['last results'].split('\n')[0: len(result_data['last results']) - 1]
drop_count = 0 # let dropped = 0 initially
dropped_packets = []
# sample result - 64 bytes from 192.168.1.61: icmp_seq=28 time=3.66 ms *** drop: 0 (0, 0.000) rx: 28 fail: 0 bytes: 1792 min/avg/max: 2.160/3.422/5.190
for result in temp_last_results:
try:
# fetching the first part of the last result e.g., 64 bytes from 192.168.1.61: icmp_seq=28 time=3.66 ms into t_result and the remaining part into t_fail
t_result, t_fail = result.split('***')
except BaseException:
continue
t_result = t_result.split()
if 'icmp_seq=' not in result and 'time=' not in result:
continue
for t_data in t_result:
if 'icmp_seq=' in t_data:
seq_number = int(t_data.strip('icmp_seq='))
if 'time=' in t_data:
rtt = float(t_data.strip('time='))
rtts[station][seq_number] = rtt
rtts_list.append(rtt)
# finding dropped packets
t_fail = t_fail.split() # [' drop:', '0', '(0, 0.000)', 'rx:', '28', 'fail:', '0', 'bytes:', '1792', 'min/avg/max:', '2.160/3.422/5.190']
t_drop_val = t_fail[1] # t_drop_val = '0'
t_drop_val = int(t_drop_val) # type cast string to int
if t_drop_val != drop_count:
current_drop_packets = t_drop_val - drop_count
drop_count = t_drop_val
for drop_packet in range(1, current_drop_packets + 1):
dropped_packets.append(seq_number - drop_packet)
if rtts_list == []:
rtts_list = [0]
min_rtt = str(min(rtts_list))
avg_rtt = str(sum(rtts_list) / len(rtts_list))
max_rtt = str(max(rtts_list))
self.result_json[station]['min_rtt'] = min_rtt
self.result_json[station]['avg_rtt'] = avg_rtt
self.result_json[station]['max_rtt'] = max_rtt
if self.result_json[station]['os'] == 'Android' and isinstance(rtts, dict) and rtts != {}:
if list(rtts[station].keys()) == []:
self.result_json[station]['sent'] = str(0)
self.result_json[station]['recv'] = str(0)
self.result_json[station]['dropped'] = str(0)
else:
self.result_json[station]['sent'] = str(max(list(rtts[station].keys())))
self.result_json[station]['recv'] = str(len(rtts[station].keys()))
self.result_json[station]['dropped'] = str(int(self.result_json[station]['sent']) - int(self.result_json[station]['recv']))
if len(rtts[station].keys()) != 0:
required_sequence_numbers = list(range(1, max(rtts[station].keys())))
for seq in required_sequence_numbers:
if seq not in rtts[station].keys():
if seq in dropped_packets:
rtts[station][seq] = 0
else:
rtts[station][seq] = 0.11
self.result_json[station]['rtts'] = rtts[station]
self.result_json[station]['remarks'] = self.generate_remarks(self.result_json[station])
else:
for station in self.real_sta_list:
current_device_data = Devices.devices_data[station]
for ping_device in result_data:
ping_endp, ping_data = list(ping_device.keys())[
0], list(ping_device.values())[0]
eid = str(ping_data['eid'])
self.sta_list = list(self.sta_list)
# Removing devices with UNKNOWN CX
if 'UNKNOWN' in ping_endp:
device_id = eid.split('.')[0] + '.' + eid.split('.')[1]
if device_id == station.split('.')[0] + '.' + station.split('.')[1]:
self.sta_list.remove(station)
self.real_sta_list.remove(station)
logger.info(result_data)
logger.info("Excluding {} from report as there is no valid generic endpoint creation during the test(UNKNOWN CX)".format(device_id))
continue
if station in ping_endp:
if len(ping_data['last results']) != 0:
result = ping_data['last results'].split('\n')
if len(result) > 1:
last_result = result[-2]
else:
last_result = result[-1]
else:
last_result = ""
hw_version = current_device_data['hw version']
if "Win" in hw_version:
os = "Windows"
elif "Linux" in hw_version:
os = "Linux"
elif "Apple" in hw_version:
os = "Mac"
else:
os = "Android"
self.result_json[station] = {
'command': ping_data['command'],
'sent': ping_data['tx pkts'],
'recv': ping_data['rx pkts'],
'dropped': ping_data['dropped'],
'mac': current_device_data['mac'],
'ip': current_device_data['ip'],
'bssid': current_device_data['ap'],
'ssid': current_device_data['ssid'],
'channel': current_device_data['channel'],
'mode': current_device_data['mode'],
'name': [current_device_data['user'] if current_device_data['user'] != '' else current_device_data['hostname']][0],
'os': os,
'remarks': [],
'last_result': [last_result][0]
}
ping_stats[station]['sent'].append(ping_data['tx pkts'])
ping_stats[station]['received'].append(ping_data['rx pkts'])
ping_stats[station]['dropped'].append(ping_data['dropped'])
self.result_json[station]['ping_stats'] = ping_stats[station]
if len(ping_data['last results']) != 0 and 'min/avg/max' in ping_data['last results']:
temp_last_results = ping_data['last results'].split('\n')[0: len(ping_data['last results']) - 1]
drop_count = 0 # let dropped = 0 initially
dropped_packets = []
for result in temp_last_results:
# sample result - 64 bytes from 192.168.1.61: icmp_seq=28 time=3.66 ms *** drop: 0 (0, 0.000) rx: 28 fail: 0 bytes: 1792 min/avg/max: 2.160/3.422/5.190
if 'time=' in result:
try:
# fetching the first part of the last result e.g., 64 bytes from 192.168.1.61: icmp_seq=28 time=3.66 ms into t_result and the remaining part into t_fail
t_result, t_fail = result.split('***')
except BaseException:
continue
t_result = t_result.split()
if 'icmp_seq=' not in result and 'time=' not in result:
continue
for t_data in t_result:
if 'icmp_seq=' in t_data:
seq_number = int(t_data.strip('icmp_seq='))
if 'time=' in t_data:
rtt = float(t_data.strip('time='))
rtts[station][seq_number] = rtt
rtts_list.append(rtt)
# finding dropped packets
t_fail = t_fail.split() # [' drop:', '0', '(0, 0.000)', 'rx:', '28', 'fail:', '0', 'bytes:', '1792', 'min/avg/max:', '2.160/3.422/5.190']
t_drop_val = t_fail[1] # t_drop_val = '0'
t_drop_val = int(t_drop_val) # type cast string to int
if t_drop_val != drop_count:
current_drop_packets = t_drop_val - drop_count
drop_count = t_drop_val
for drop_packet in range(1, current_drop_packets + 1):
dropped_packets.append(seq_number - drop_packet)
if rtts_list == []:
rtts_list = [0]
min_rtt = str(min(rtts_list))
avg_rtt = str(sum(rtts_list) / len(rtts_list))
max_rtt = str(max(rtts_list))
self.result_json[station]['min_rtt'] = min_rtt
self.result_json[station]['avg_rtt'] = avg_rtt
self.result_json[station]['max_rtt'] = max_rtt
if self.result_json[station]['os'] == 'Android' and isinstance(rtts, dict) and rtts != {}:
if list(rtts[station].keys()) == []:
self.result_json[station]['sent'] = str(0)
self.result_json[station]['recv'] = str(0)
self.result_json[station]['dropped'] = str(0)
else:
self.result_json[station]['sent'] = str(max(list(rtts[station].keys())))
self.result_json[station]['recv'] = str(len(rtts[station].keys()))
self.result_json[station]['dropped'] = str(int(self.result_json[station]['sent']) - int(self.result_json[station]['recv']))
if len(rtts[station].keys()) != 0:
required_sequence_numbers = list(range(1, max(rtts[station].keys())))
for seq in required_sequence_numbers:
if seq not in rtts[station].keys():
if seq in dropped_packets:
rtts[station][seq] = 0
else:
rtts[station][seq] = 0.11
# print(station, rtts[station])
self.result_json[station]['rtts'] = rtts[station]
self.result_json[station]['remarks'] = self.generate_remarks(self.result_json[station])
# self.result_json[station]['dropped_packets'] = dropped_packets
def generate_real_time_csv(self):
# if not self.start_time:
# return
csv_dir = "csv_reports"
print("We are coming in this function.")
os.makedirs(csv_dir,exist_ok=True)
interval = timedelta(seconds=int(self.interval))
for device_name, device_data in self.result_json.items():
if 'rtts' not in device_data or not device_data['rtts']:
continue
if device_data['os'] == "Virtual":
csv_file = os.path.join(csv_dir, f"sta_{device_name.replace('.', '_')}.csv")
else:
csv_file = os.path.join(csv_dir, f"device_{device_name.replace('.', '_')}.csv")
logger.info(csv_file)
file_exists = os.path.exists(csv_file)
with open(csv_file, 'a', newline='') as file:
writer = csv.writer(file)
if not file_exists or os.path.getsize(csv_file) == 0:
writer.writerow(['Time', 'RTT (ms)', 'Sent', 'Received', 'Dropped'])
sorted_seqs = sorted(device_data['rtts'].keys(), key=int)
last_written_seq = self.last_written_seq.get(device_name, 0)
for seq in sorted_seqs:
seq = int(seq)
if seq <= last_written_seq:
continue
rtt = device_data['rtts'][seq]
timestamp = (
(seq - 1) * interval + self.start_time
).strftime("%d/%m/%Y %H:%M:%S")
# Calculate sent/recv/dropped properly
if device_name not in self.last_Result_per_Station:
sent = 1
received = 0 if rtt == 0 else 1
dropped = 1 if rtt == 0 else 0
else:
last_sent = self.last_Result_per_Station[device_name][2]
last_received = self.last_Result_per_Station[device_name][3]
last_dropped = self.last_Result_per_Station[device_name][4]
sent = last_sent + 1
if rtt == 0:
received = last_received
dropped = last_dropped + 1
else:
received = last_received + 1
dropped = last_dropped
self.last_Result_per_Station[device_name] = [
timestamp, rtt, sent, received, dropped
]
# Skip synthetic missing packets (0.11)
if rtt != 0.11:
writer.writerow([timestamp, rtt, sent, received, dropped])
self.last_written_seq[device_name] = seq
def get_safe_last_result(self, last_results):
if not last_results or last_results.strip() == "":
return ""
lines = [line for line in last_results.split('\n') if line.strip()]
if not lines:
return ""
if len(lines) >= 2:
return lines[-2]
return lines[-1]
def stop_generic(self):
self.generic_endps_profile.stop_cx()
def get_results(self):
logging.debug(self.generic_endps_profile.created_endp)
results = self.json_get(
"/generic/{}".format(','.join(self.generic_endps_profile.created_endp)))
if (len(self.generic_endps_profile.created_endp) > 1):
results = results['endpoints']
else:
results = results['endpoint']
return (results)
def generate_remarks(self, station_ping_data):
remarks = []
# NOTE if there are any more ping failure cases that are missed, add them here.
# checking if ping output is not empty
if (station_ping_data['last_result'] == ""):
remarks.append('No output for ping')
# illegal division by zero error. Issue with arguments.
if ('Illegal division by zero' in station_ping_data['last_result']):
remarks.append('Illegal division by zero error. Please re-check the arguments passed.')
# unknown host
if ('Totals: *** dropped: 0 received: 0 failed: 0 bytes: 0' in station_ping_data['last_result'] or 'unknown host' in station_ping_data['last_result']):
remarks.append('Unknown host. Please re-check the target')
# checking if IP is existing in the ping command or not for Windows device
if (station_ping_data['os'] == 'Windows'):
if ('None' in station_ping_data['command'] or station_ping_data['command'].split('-n')[0].split('-S')[-1] == " "):
remarks.append('Station has no IP')
# network buffer overflow
if ('ping: sendmsg: No buffer space available' in station_ping_data['last_result']):
remarks.append('Network buffer overlow')
# checking for no ping states
if (float(station_ping_data['min_rtt']) == 0 and float(station_ping_data['max_rtt']) == 0 and float(station_ping_data['avg_rtt']) == 0):
# Destination Host Unreachable state
if ('Destination Host Unreachable' in station_ping_data['last_result']):
remarks.append('Destination Host Unrechable')
# Name or service not known state
if ('Name or service not known' in station_ping_data['last_result']):
remarks.append('Name or service not known')
# network buffer overflow
if ('ping: sendmsg: No buffer space available' in station_ping_data['last_result']):
remarks.append('Network buffer overlow')
return (remarks)
# Converts an upstream port name to its corresponding IP address if it's not already in IP format.
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
# Calculates pass/fail status for each client based on their result compared to the expected value.
def get_pass_fail_list(self, os_type):
# When csv_name is provided, for pass/fail criteria, respective values for each client will be used
if not self.expected_passfail_val:
res_list = []
test_input_list = []
pass_fail_list = []
interop_tab_data = self.json_get('/adb/')["devices"]
for client in range(len(os_type)):
if os_type[client] != 'Android':
# Example: From "DESKTOP-DDPI3HE Windows", extract "DESKTOP-DDPI3HE"
res_list.append(self.device_names[client].split(' ')[0:-1][0])
else:
for dev in interop_tab_data:
for item in dev.values():
if item['user-name'] == self.device_names[client].split(' ')[0:-1][0]:
res_list.append(item['name'].split('.')[2])
with open(self.csv_name, mode='r') as file:
reader = csv.DictReader(file)
rows = list(reader)
# fieldnames = reader.fieldnames
for device in res_list:
found = False
for row in rows:
if row['DeviceList'] == device and row['PingPacketLoss %'].strip() != '':
test_input_list.append(row['PingPacketLoss %'])
found = True
break
if not found:
logging.info(f"Ping result for device {device} not found in CSV. Using default packet loss = 10%")
test_input_list.append(10)
self.percent_pac_loss = []
for i in range(len(self.packets_sent)):
if self.packets_sent[i] != 0:
self.percent_pac_loss.append(((self.packets_sent[i] - self.packets_received[i]) / self.packets_sent[i]) * 100)
else:
self.percent_pac_loss.append(0)
for i in range(len(test_input_list)):
if self.packets_sent[i] == 0:
pass_fail_list.append('FAIL')
elif float(test_input_list[i]) >= self.percent_pac_loss[i]:
pass_fail_list.append('PASS')
else:
pass_fail_list.append('FAIL')
self.pass_fail_list = pass_fail_list
self.test_input_list = test_input_list
# When expected_passfail_val is provided, for pass/fail criteria, the same value will be used for all clients
else:
self.test_input_list = [self.expected_passfail_val for val in range(len(self.device_names))]
self.percent_pac_loss = []
for i in range(len(self.packets_sent)):
if self.packets_sent[i] != 0:
self.percent_pac_loss.append(((self.packets_sent[i] - self.packets_received[i]) / self.packets_sent[i]) * 100)
else:
self.percent_pac_loss.append(0)
pass_fail_list = []
for i in range(len(self.test_input_list)):
if self.packets_sent[i] == 0:
pass_fail_list.append('FAIL')
elif float(self.expected_passfail_val) >= self.percent_pac_loss[i]:
pass_fail_list.append("PASS")
else:
pass_fail_list.append("FAIL")
self.pass_fail_list = pass_fail_list
def add_live_view_images_to_report(self, report: lf_report, report_path: str):
"""
This function looks for throughput and RSSI images for each floor
in the 'live_view_images' folder within `self.result_dir`.
It waits up to **60 seconds** for each image. If an image is found,
it's added to the `report` on a new page; otherwise, it's skipped.
"""
test_name = os.path.basename(report_path)
for floor in range(int(self.total_floors)):
# Construct expected image paths
packet_sent_image = os.path.join(self.result_dir, "heatmap_images", f"{test_name}_ping_packet_sent_{floor + 1}.png")
packet_recv_image = os.path.join(self.result_dir, "heatmap_images", f"{test_name}_ping_packet_recv_{floor + 1}.png")
packet_loss_image = os.path.join(self.result_dir, "heatmap_images", f"{test_name}_ping_packet_loss_{floor + 1}.png")
# Wait for all required images to be generated (up to timeout)
timeout = 60 # seconds
start_time = time.time()
while not (os.path.exists(packet_sent_image) and os.path.exists(packet_recv_image) and os.path.exists(packet_loss_image)):
if time.time() - start_time > timeout:
print(f"Timeout: Heatmap images for floor {floor + 1} not found within {timeout} seconds.")
break
time.sleep(1)
report.set_custom_html("<h2>Ping Packet Sent vs Recevied vs Lost: </h2>")
report.build_custom()
# Generate report sections for each image if it exists
for image_path in [packet_sent_image, packet_recv_image, packet_loss_image]:
if os.path.exists(image_path):