-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathlf_interop_ping_plotter.py
More file actions
executable file
·3635 lines (3269 loc) · 189 KB
/
lf_interop_ping_plotter.py
File metadata and controls
executable file
·3635 lines (3269 loc) · 189 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_plotter.py
PURPOSE: lf_interop_ping_plotter.py will let the user select real devices, virtual devices or both and then allows them to run
ping plotter test for user given duration and packet interval on the given target IP or domain name and generates realtime ping status and line charts for every device.
EXAMPLE-1:
Command Line Interface to run ping plotter test with only virtual clients with eth1 as the default target
python3 lf_interop_ping_plotter.py --mgr 192.168.200.103 --virtual --num_sta 1 --radio 1.1.wiphy2 --ssid RDT_wpa2 --security wpa2
--passwd OpenWifi --ping_interval 1 --ping_duration 1m --server_ip 192.168.1.61 --debug
EXAMPLE-2:
Command Line Interface to stop cleaning up stations after the test
python3 lf_interop_ping_plotter.py --mgr 192.168.200.103 --virtual --num_sta 1 --radio 1.1.wiphy2 --ssid RDT_wpa2 --security wpa2
--passwd OpenWifi --ping_interval 1 --ping_duration 1m --server_ip 192.168.1.61 --debug --no_cleanup
EXAMPLE-3:
Command Line Interface to run ping plotter test with only real clients
python3 lf_interop_ping_plotter.py --mgr 192.168.200.103 --real --ping_interval 1 --ping_duration 1m --server_ip 192.168.1.61
EXAMPLE-4:
Command Line Interface to run ping plotter test with both real and virtual clients
python3 lf_interop_ping_plotter.py --mgr 192.168.200.103 --real --virtual --num_sta 1 --radio 1.1.wiphy2 --ssid RDT_wpa2 --security wpa2
--passwd OpenWifi --ping_interval 1 --ping_duration 1m --server_ip 192.168.1.61
EXAMPLE-5:
Command Line Interface to run ping plotter test with a different target
python3 lf_interop_ping_plotter.py --mgr 192.168.200.63 --real --ping_interval 5 --ping_duration 1m --target 192.168.1.61
EXAMPLE-6:
Command Line Interface to run ping plotter with existing real stations instead of giving input after starting the test
python3 lf_interop_ping_plotter.py --mgr 192.168.200.63 --real --ping_interval 5 --ping_duration 1m --target 192.168.1.61 --resources 1.10,1.11
EXAMPLE-7:
Command Line Interface to run ping plotter test by setting the same expected Pass/Fail value for all devices
python3 lf_interop_ping_plotter.py --mgr 192.168.204.74 --real --target 192.168.204.66 --ping_interval 1 --ping_duration 1m --expected_passfail_value 3
--use_default_config
EXAMPLE-8:
Command Line Interface to run ping plotter test by setting device specific Pass/Fail values in the csv file
python3 lf_interop_ping_plotter.py --mgr 192.168.204.74 --real --target 192.168.204.66 --ping_interval 1 --ping_duration 1m --device_csv_name device.csv
--use_default_config
EXAMPLE-9:
Command Line Interface to run ping plotter test by configuring Real Devices with SSID, Password, and Security
python3 lf_interop_ping_plotter.py --mgr 192.168.204.74 --real --target 192.168.204.66 --ping_interval 1 --ping_duration 1m --ssid NETGEAR_2G_wpa2
--security wpa2 --passwd Password@123 --server_ip 192.168.204.74 --wait_time 30
EXAMPLE-10:
Command Line Interface to run ping plotter test by setting device specific Pass/Fail values in the csv file
python3 lf_interop_ping_plotter.py --mgr 192.168.204.74 --real --target 192.168.204.66 --ping_interval 1 --ping_duration 1m --ssid NETGEAR_2G_wpa2
--security wpa2 --passwd Password@123 --server_ip 192.168.204.74 --wait_time 30 --device_csv_name device.csv
EXAMPLE-11:
Command Line Interface to run ping plotter test by Configuring Devices in Groups with Specific Profiles
python3 lf_interop_ping_plotter.py --mgr 192.168.204.74 --real --target 192.168.204.66 --ping_interval 1 --ping_duration 1m --group_name grp4
--profile_name Openz --file_name g219 --server_ip 192.168.204.74
EXAMPLE-12:
Command Line Interface to run ping plotter test by Configuring Devices in Groups with Specific Profiles with expected Pass/Fail values
python3 lf_interop_ping_plotter.py --mgr 192.168.204.74 --real --target 192.168.204.66 --ping_interval 1 --ping_duration 1m --group_name grp4,grp5
--profile_name Openz,Openz --file_name g219 --expected_passfail_value 22 --server_ip 192.168.204.74
EXAMPLE-13:
Command Line Interface to run ping plotter test by Configuring Devices in Groups with Specific Profiles with device_csv_name
python3 lf_interop_ping_plotter.py --mgr 192.168.204.74 --real --target 192.168.204.66 --ping_interval 1 --ping_duration 1m --group_name grp4,grp5
--profile_name Openz,Openz --file_name g219 --device_csv_name device.csv --server_ip 192.168.204.74
EXAMPLE-14:
Command Line Interface to run ping plotter test with desired resources at desired points using robo
python3 lf_interop_ping_plotter.py --mgr 192.168.207.78 --real --target 8.8.8.8 --ping_interval 1 --ping_duration 1m --use_default_config
--robot_ip 192.168.204.76 --coordinate 3,4
EXAMPLE-15:
Command Line Interface to run ping plotter test with desired resources at desired points with rotations using robo
python3 lf_interop_ping_plotter.py --mgr 192.168.207.78 --real --target 8.8.8.8 --ping_interval 1 --ping_duration 1m --use_default_config
--robot_ip 192.168.204.76 --coordinate 3,4 --rotation 45,90
EXAMPLE-16:
Command Line Interface to run ping plotter test with desired resources at desired points with bandsteering using robo
python3 lf_interop_ping_plotter.py --mgr 192.168.207.78 --real --target 8.8.8.8 --ping_interval 1 --ping_duration 1m --use_default_config
--robot_ip 192.168.204.76 --coordinate 3,4 --do_bandsteering --total_cycles 3 --bssids 94:A6:7E:74:26:33,94:A6:7E:74:26:22
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.Use 's','m','h' as suffixes for ping_duration in seconds, minutes and hours respectively
3.After passing the cli, if --real flag is selected, then a list of available real devices will be displayed on the terminal
4.Enter the real device resource numbers seperated by commas (,)
5.For --target, you can specify it as eth1, IP address or domain name (e.g., google.com)
STATUS: BETA RELEASE
VERIFIED_ON:
Working date - 06/12/2023
Build version - 5.4.7
kernel version - 6.2.16+
License: Free to distribute and modify. LANforge systems must be licensed.
Copyright (C) 2020-2026 Candela Technologies Inc.
'''
import argparse
import time
import sys
import os
import pandas as pd
import importlib
import logging
import matplotlib.pyplot as plt
import csv
import asyncio
import json
import shutil
import requests
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 datetime import datetime, timedelta
from lf_graph import lf_bar_graph_horizontal, lf_bar_graph
from lf_report import lf_report
from station_profile import StationProfile
from typing import List, Optional
from collections import Counter
from lf_base_robo import RobotClass
# Importing DeviceConfig to apply device configurations for ADB devices and laptops
DeviceConfig = importlib.import_module("py-scripts.DeviceConfig")
from LANforge import LFUtils # noqa: E402
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,
do_webUI=False,
ui_report_dir=None,
debug=False,
file_name=None,
profile_name=None,
group_name=None,
server_ip=None,
expected_passfail_val=None,
csv_name=None,
wait_time=60,
floors=None,
get_live_view=None, robo_ip=None, angle_list=None, coordinate_list=None, rotation_enabled=None, local_lf_report_dir=None, do_bandsteering=False, total_cycles=1, bssids=None,
duration_to_skip=None):
super().__init__(lfclient_host=host,
lfclient_port=port)
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.change_target_to_ip()
self.generic_endps_profile.interval = self.interval
self.Devices = None
self.start_time = ""
self.stop_time = ""
self.do_webUI = do_webUI
self.ui_report_dir = ui_report_dir
self.api_url = 'http://{}:{}'.format(self.host, self.port)
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.wait_time = wait_time
self.floors = floors
self.get_live_view = get_live_view
# variables related to robot
self.coordinate_list = coordinate_list if coordinate_list is not None else []
self.rotation_enabled = rotation_enabled
self.last_rotated_angles = []
self.robo_ip = robo_ip
self.angle_list = angle_list if rotation_enabled else [0]
self.currentangle = None
self.currentcoordinate = None
if robo_ip is not None:
self.robot = RobotClass(robo_ip=self.robo_ip, angle_list=self.angle_list)
self.robot.time_to_reach = duration_to_skip
self.robot.coordinate_list = coordinate_list
self.robot.total_cycles = total_cycles
self.coordinate_json = {}
self.coordinates_completed = []
self.starttime_track = {}
self.local_lf_report_dir = local_lf_report_dir
self.pingduration = None
self.do_bandsteering = do_bandsteering
self.total_cycles = total_cycles
self.bssids = bssids if bssids else []
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']
self.target = target_port_ip
except Exception:
logging.warning('The target is not an ethernet port. Proceeding with the given target {}.'.format(self.target))
logging.info(self.target)
else:
logging.info(self.target)
return self.target
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 isinstance(device_list, 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 {} is not found.'.format(device))
continue
device_data = device_data['resource']
if 'Apple' in device_data['hw version'] and (device_data['app-id'] != '') and (device_data['app-id'] != '0' or device_data['kernel'] == ''):
logger.info('{} is an iOS device. Currently we do not support iOS devices.'.format(device))
else:
filtered_list.append(device)
if isinstance(device_list, str):
filtered_list = ','.join(filtered_list)
self.device_list = filtered_list
return filtered_list
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=""):
if real_sta_list is None:
self.real_sta_list, _, _ = real_devices.query_user(device_list=device_list)
else:
if real_sta_list == ['all']:
self.real_sta_list, _, _ = real_devices.query_user(dowebgui=True, device_list='all')
else:
real_list = []
for i in range(len(real_sta_list)):
real_list.append(real_sta_list[i].split('.')[0] + '.' + real_sta_list[i].split('.')[1])
self.real_sta_list, _, _ = real_devices.query_user(dowebgui=True, device_list=','.join(real_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)
self.real_sta_list = self.filter_iOS_devices(self.real_sta_list)
logging.info('{}'.format(*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
if not self.do_webUI:
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 Virtual Stations: {}'.format(self.sta_list))
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')
station_object.use_security(self.security, self.ssid, self.password)
station_object.set_command_flag("add_sta", "create_admin_down", 1)
station_object.set_command_param("set_port", "report_timer", 1500)
station_object.set_command_flag("set_port", "rpt_timer", 1)
station_object.create(radio=self.radio, sta_names_=self.sta_list)
station_object.admin_up()
if Realm.wait_for_ip(self=self, station_list=self.sta_list, timeout_sec=-1):
self._pass("All stations got IPs", print_=True)
else:
self._fail("Stations failed to get IPs", print_=True)
logger.info("Please re-check the configuration applied")
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)
# setting 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 start_generic(self):
self.generic_endps_profile.start_cx()
self.start_time = datetime.now()
def stop_generic(self):
self.generic_endps_profile.stop_cx()
self.stop_time = datetime.now()
def get_results(self):
# logging.info(self.generic_endps_profile.created_endp)
results = self.json_get(
"/generic/{}".format(','.join(self.generic_endps_profile.created_endp)))
overallres = self.json_get("/generic/all")
if len(self.generic_endps_profile.created_endp) > 1 and 'endpoints' in results.keys():
results = results['endpoints']
else:
try:
results = results['endpoint']
except Exception as e:
logger.info(overallres)
logger.error(f"Endpoint not found {e}")
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'].replace(',', '')) == 0 and float(station_ping_data['max_rtt'].replace(',', '')) == 0 and float(station_ping_data['avg_rtt'].replace(',', '')) == 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)
def generate_uptime_graph(self, coordinate=None, angle=None):
json_data = {}
for station in self.result_json:
json_data[station] = {
'rtts': {},
'sent': "",
'dropped': ""
}
# print('------------',json_data)
# for seq in self.result_json[station]['rtts']:
json_data[station]['rtts'] = self.result_json[station]['rtts']
json_data[station]['sent'] = self.result_json[station]['sent']
json_data[station]['dropped'] = self.result_json[station]['dropped']
self.graph_values = json_data
device_names = list(json_data.keys())
sequence_numbers = list(set(seq for device_data in json_data.values() for seq in device_data.get("rtts", {})))
# print(sequence_numbers)
rtt_values = {}
for seq in sequence_numbers:
rtt_values[seq] = []
for device_data in json_data.values():
if "rtts" in device_data.keys():
if seq in device_data['rtts'].keys():
rtt_values[seq].append(device_data['rtts'][seq])
else:
if device_data['sent'] == device_data['dropped']:
rtt_values[seq].append(0)
elif len(device_data['rtts'].keys()) != 0:
rtt_values[seq].append(1)
else:
rtt_values[seq].append(0)
# rtt_values = {seq: [device_data.get("rtts", {}).get(seq, 0) for device_data in json_data.values()] for seq in sequence_numbers}
# print(rtt_values)
# Set different colors based on RTT values
colors = [['red' if rtt == 0 else 'green' for rtt in rtt_values[seq]] for seq in sequence_numbers]
# Create a stacked horizontal bar graph
fig, ax = plt.subplots(figsize=(20, len(device_names) * .5 + 10))
# y_positions = np.arange(len(device_names)) * (bar_width + 1) # Adjust the 0.1 to control the gap
for i, device_name in enumerate(self.report_names):
# plt.barh(device_name, 1, color='white', height=0.5)
for j, seq in enumerate(sequence_numbers):
plt.barh(device_name, 1, left=int(seq) - 1, color=colors[j][i], height=0.3)
# Customize the plot
plt.xlabel('Time', fontweight='bold', fontsize=15)
plt.ylabel('Client Status', fontweight='bold', fontsize=15)
plt.title('Client Status vs Time')
# plt.legend(sequence_numbers, title='Sequence Numbers', loc='upper right')
# Remove y-axis labels
# plt.yticks([])
# building timestamps
start_time = self.start_time
interval = timedelta(seconds=int(self.interval))
timestamps = []
for seq_num in sequence_numbers:
timestamp = ((int(seq_num) - 1) * interval + start_time).strftime("%d/%m/%Y %H:%M:%S")
timestamps.append(timestamp)
# settings labels for x-axis
# print(list(map(int,sequence_numbers)))
# print(list(map(int,sequence_numbers))[0::10])
# print(timestamps)
# ticks_sequence_numbers = list(map(int,sequence_numbers))
# ticks_sequence_numbers.sort()
sequence_numbers.sort()
timestamps.sort()
# print('--------------')
# print(ticks_sequence_numbers[0::10])
# print(timestamps[0::10])
# settings labels for x-axis
if len(sequence_numbers) > 30:
temp_sequence_numbers = sequence_numbers[:len(sequence_numbers):max(round(len(timestamps) / 30), len(timestamps) // 30)]
temp_timestamps = timestamps[:len(timestamps):max(round(len(timestamps) / 30), len(timestamps) // 30)]
if len(temp_sequence_numbers) != len(temp_timestamps):
temp_sequence_numbers.pop(0)
# plt.xticks(temp_sequence_numbers, temp_timestamps, rotation=45)
ax.set_xticks(temp_sequence_numbers)
ax.set_xticklabels(temp_timestamps, rotation=45, ha='right')
else:
# plt.xticks(sequence_numbers, timestamps, rotation=45)
ax.set_xticks(sequence_numbers)
ax.set_xticklabels(timestamps, rotation=45, ha='right')
# plt.xlim(0, max([max(rtt_values[seq]) for seq in sequence_numbers]))
if len(sequence_numbers) != 0:
plt.xlim(0, max(sequence_numbers))
# print('working xlim', max([max(rtt_values[seq]) for seq in sequence_numbers]))
# fixing the number of ticks to 30 in x-axis
# plt.locator_params(axis='x', nbins=30)
# Show the plot
# plt.show()
# Generate filename dynamically based on provided coordinate and angle
filename = "uptime_graph.png"
if angle:
filename = "uptime_graph_{}_{}.png".format(coordinate, angle)
elif coordinate:
filename = "uptime_graph_{}.png".format(coordinate)
plt.savefig(filename, dpi=96)
plt.close()
logger.debug("{}.png".format("uptime_graph"))
return filename
def build_area_graphs(self, report_obj=None, coordinate=None, angle=None):
json_data = self.graph_values
device_names = list(json_data.keys())
# Plot line graphs for each device
for device_name, device_data in json_data.items():
rtts = []
# dropped_seqs = []
sequence_numbers = []
if 'rtts' in device_data.keys():
for seq in sorted(list(device_data['rtts'].keys())):
if device_data['rtts'][seq] == 0.11:
continue
rtts.append(device_data['rtts'][seq])
sequence_numbers.append(seq)
fig, ax = plt.subplots(figsize=(15, len(device_names) * .5 + 10))
# plt.plot(sequence_numbers, rtts, label=device_name, color="Slateblue", alpha=0.6)
# for area chart
ax.fill_between(sequence_numbers, rtts, color="skyblue", alpha=1)
ax.set_xlabel('Time', fontweight='bold', fontsize=15)
ax.set_ylabel('RTT (ms)', fontweight='bold', fontsize=15)
# Customize the plot
# plt.xlabel('Time')
# plt.ylabel('RTT (ms)')
# plt.title('RTT vs Time for {}'.format(device_name))
# plt.legend(loc='upper right')
# plt.grid(True)
# building timestamps
start_time = self.start_time
interval = timedelta(seconds=int(self.interval))
timestamps = []
for seq_num in sequence_numbers:
timestamp = ((int(seq_num) - 1) * interval + start_time).strftime("%d/%m/%Y %H:%M:%S")
timestamps.append(timestamp)
# generating csv
with open('{}/{}.csv'.format(report_obj.path_date_time, device_name), 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Time', 'RTT (ms)', 'Sent', 'Received', 'Dropped'])
for index in range(len(self.result_json[device_name]['ping_stats']['sent']), len(timestamps)):
self.result_json[device_name]['ping_stats']['sent'].append(str(int(self.result_json[device_name]['ping_stats']['sent'][-1]) + 1))
if rtts[index] == 0:
self.result_json[device_name]['ping_stats']['dropped'].append(str(int(self.result_json[device_name]['ping_stats']['dropped'][-1]) + 1))
self.result_json[device_name]['ping_stats']['received'].append(str(int(self.result_json[device_name]['ping_stats']['received'][-1])))
else:
self.result_json[device_name]['ping_stats']['received'].append(str(int(self.result_json[device_name]['ping_stats']['received'][-1]) + 1))
self.result_json[device_name]['ping_stats']['dropped'].append(str(int(self.result_json[device_name]['ping_stats']['dropped'][-1])))
for row in range(len(timestamps)):
writer.writerow([timestamps[row], rtts[row], self.result_json[device_name]['ping_stats']['sent'][row], self.result_json[device_name]
['ping_stats']['received'][row], self.result_json[device_name]['ping_stats']['dropped'][row]])
# writer.writerows([timestamps, rtts])
sequence_numbers.sort()
timestamps.sort()
# settings labels for x-axis
if len(sequence_numbers) > 30:
temp_sequence_numbers = sequence_numbers[:len(sequence_numbers):max(round(len(timestamps) / 30), len(timestamps) // 30)]
temp_timestamps = timestamps[:len(timestamps):max(round(len(timestamps) / 30), len(timestamps) // 30)]
if len(temp_sequence_numbers) != len(temp_timestamps):
temp_sequence_numbers.pop(0)
# plt.xticks(temp_sequence_numbers, temp_timestamps, rotation=45)
ax.set_xticks(temp_sequence_numbers)
ax.set_xticklabels(temp_timestamps, rotation=45, ha='right')
else:
# plt.xticks(sequence_numbers, timestamps, rotation=45)
ax.set_xticks(sequence_numbers)
ax.set_xticklabels(timestamps, rotation=45, ha='right')
# ax.set_xticks(sequence_numbers)
# ax.set_xticklabels(timestamps, rotation=45, ha='right')
# ax.xaxis.set_major_locator(plt.MaxNLocator(30))
# print(sequence_numbers)
# print(rtts)
# plt.xlim(0, max(rtts))
# plt.xlim(0, max(list(map(int, sequence_numbers))))
if len(sequence_numbers) != 0:
plt.xlim(0, max(sequence_numbers))
# Show the plot
# plt.show()
# set origin on x-axis
if rtts != []:
plt.ylim(0, max(rtts))
# Generate filename dynamically based on provided coordinate and angle
filename = "{}.png".format(device_name)
if angle:
filename = "{}_{}_{}.png".format(device_name, coordinate, angle)
elif coordinate:
filename = "{}_{}.png".format(device_name, coordinate)
plt.savefig(filename, dpi=96)
graph_name = filename
plt.close()
logger.debug("{}.png".format(device_name))
# generating individual table titles and line graphs
report_obj.set_table_title(device_name)
report_obj.build_table_title()
report_obj.set_graph_image(graph_name)
# need to move the graph image to the results directory
report_obj.move_graph_image()
# report.set_csv_filename(uptime_graph)
# report.move_csv_file()
report_obj.build_graph()
def check_stop_status(self):
"""
Check whether the currently running test has been stopped by the user.
This function looks for a JSON file that tracks the running status of a test.
The file is expected to be located in the `Running_instances` directory and
named using the pattern: <host>_<test_name>_running.json.
Returns:
bool:
True -> If the test status exists and is not "Running" (i.e., stopped).
False -> If the file does not exist or the status is still "Running".
"""
test_name = self.ui_report_dir.split("/")[-1]
file_path = os.path.join(
self.ui_report_dir,
"../../Running_instances/{}_{}_running.json".format(self.host, test_name))
if not os.path.exists(file_path):
return False
with open(file_path, 'r') as f:
run_status = json.load(f)
# Check if 'status' key exists and if the test is no longer running
if 'status' in run_status.keys() and run_status["status"] != "Running":
logging.info("Test is stopped by the user")
return True
return False
def store_csv(self, data=None):
if data is None:
data = self.result_json
if 'status' in data.keys() and data['status'] == 'Aborted':
return False
else:
data['status'] = 'Running'
interval = timedelta(seconds=int(self.interval))
for device, device_data in data.items():
if device == 'status':
continue
new_dict = {}
sequence_numbers = {}
for seq in device_data['rtts'].keys():
sequence_numbers[int(seq)] = ((int(seq) - 1) * interval + self.start_time).strftime("%d/%m/%Y %H:%M:%S")
for seq in sorted(list(sequence_numbers.keys())):
new_dict[sequence_numbers[seq]] = device_data['rtts'][seq]
# for seq,rtt in device_data['rtts'].items():
# new_dict[((int(seq) -1) * interval + self.start_time).strftime("%d/%m/%Y %H:%M:%S")] = rtt
data[device]['webui_rtts'] = new_dict
# save runtime ping data based on robo_ip and bandsteering status
if (self.robo_ip and self.do_bandsteering) or (self.robo_ip is None):
with open(self.ui_report_dir + '/runtime_ping_data.json', 'w') as f:
json.dump(data, f, indent=4)
else:
filename = '{}_runtime_ping_data.json'.format(self.currentcoordinate)
filepath = os.path.join(self.ui_report_dir, filename)
data = self.coordinate_json[self.currentcoordinate]
with open(filepath, 'w') as f:
json.dump(data, f, indent=4)
test_name = self.ui_report_dir.split("/")[-1]
with open(self.ui_report_dir + '/../../Running_instances/{}_{}_running.json'.format(self.host, test_name), 'r') as f:
run_status = json.load(f)
if run_status["status"] != "Running":
logging.info('Test is stopped by the user')
return False
return True
def set_webUI_stop(self):
if self.robo_ip is None or self.do_bandsteering:
filename = "runtime_ping_data.json"
else:
filename = "{}_runtime_ping_data.json".format(self.currentcoordinate)
filepath = os.path.join(self.ui_report_dir, filename)
with open(filepath, 'r') as f:
data = json.load(f)
if self.rotation_enabled:
data_for_lastangle = data[self.currentangle]
if 'status' in data_for_lastangle.keys() and data_for_lastangle['status'] != 'Aborted':
data_for_lastangle['status'] = 'Completed'
data[self.currentangle] = data_for_lastangle
with open(filepath, 'w') as f:
json.dump(data, f, indent=4)
elif 'status' in data.keys() and data['status'] != 'Aborted':
data['status'] = 'Completed'
with open(filepath, 'w') as f:
json.dump(data, f, indent=4)
def copy_reports(self, report_path):
logging.info('Copying PDF report and CSVs to webUI result directory')
for file in os.listdir(report_path):
if file.endswith('.csv') or file.endswith('.pdf'):
shutil.copy2(report_path + '/' + file, self.ui_report_dir)
def get_pass_fail_list(self):
# 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 = []
for client in self.report_names:
# Check if the client type (second word in "1.15 android samsungmob") is 'android'
if client.split(' ')[1] != 'Android':
res_list.append(client.split(' ')[2])
else:
interop_tab_data = self.json_get('/adb/')["devices"]
for dev in interop_tab_data:
for item in dev.values():
# Extract the username from the client string (e.g., 'samsungmob' from "1.15 android samsungmob")
if item['user-name'] == client.split(' ')[2]:
res_list.append(item['name'].split('.')[2])
with open(self.csv_name, mode='r') as file:
reader = csv.DictReader(file)
rows = list(reader)
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)
for i in range(len(test_input_list)):
if self.packets_sent[i] == 0.0:
pass_fail_list.append('FAIL')
elif float(test_input_list[i]) >= self.packet_loss_percent[i]:
pass_fail_list.append('PASS')
else:
pass_fail_list.append('FAIL')
# When expected_passfail_val is provided, for pass/fail criteria, the same value will be used for all clients
else:
test_input_list = [self.expected_passfail_val for val in range(len(self.report_names))]
pass_fail_list = []
for i in range(len(test_input_list)):
if self.packets_sent[i] == 0:
pass_fail_list.append('FAIL')
elif float(self.expected_passfail_val) >= self.packet_loss_percent[i]:
pass_fail_list.append("PASS")
else:
pass_fail_list.append("FAIL")
return pass_fail_list, test_input_list
def generate_report(self, result_json=None, result_dir='Ping_Plotter_Test_Report', report_path='', config_devices='', group_device_map=None):
if group_device_map is None:
group_device_map = {}
if result_json is not None:
self.result_json = result_json
logging.info('Generating Report')
# graph for the above
self.packets_sent = []
self.packets_received = []
self.packets_dropped = []
self.packet_loss_percent = []
# self.client_unrechability_percent = []
self.device_names = []
self.device_modes = []
self.device_channels = []
self.device_min = []
self.device_max = []
self.device_avg = []
self.device_mac = []
self.device_ips = []
self.device_bssid = []
self.device_ssid = []
self.device_names_with_errors = []
self.devices_with_errors = []
self.report_names = []
self.remarks = []
# packet_count_data = {}
if self.do_webUI and 'status' in self.result_json.keys():
del self.result_json['status']
for device, device_data in self.result_json.items():
self.packets_sent.append(int(device_data['ping_stats']['sent'][-1]))
self.packets_received.append(int(device_data['ping_stats']['received'][-1]))
self.packets_dropped.append(int(device_data['ping_stats']['dropped'][-1]))
self.device_names.append(device_data['name'])
self.device_modes.append(device_data['mode'])
channel_value = str(device_data.get('channel', ''))
if channel_value in ('', '0', '-1'):
self.device_channels.append('NA')
else:
self.device_channels.append(device_data['channel'])
self.device_mac.append(device_data['mac'])
self.device_ips.append(device_data['ip'])
self.device_bssid.append(device_data['bssid'])
self.device_ssid.append(device_data['ssid'])
if float(device_data['sent']) == 0:
self.packet_loss_percent.append(0)
# self.client_unrechability_percent.append(0)
else:
if device_data['ping_stats']['sent'] == [] or float(device_data['ping_stats']['sent'][-1]) == 0:
self.packet_loss_percent.append(0)
else:
self.packet_loss_percent.append(float(device_data['ping_stats']['dropped'][-1]) / float(device_data['ping_stats']['sent'][-1]) * 100)
# self.client_unrechability_percent.append(float(device_data['dropped']) / (float(self.duration) * 60) * 100)
t_rtt_values = sorted(list(device_data['rtts'].values()))
if t_rtt_values != []:
while (0.11 in t_rtt_values):
t_rtt_values.remove(0.11)
self.device_avg.append(float(sum(t_rtt_values) / len(t_rtt_values)))
self.device_min.append(float(min(t_rtt_values)))
self.device_max.append(float(max(t_rtt_values)))
else:
self.device_avg.append(0)
self.device_min.append(0)
self.device_max.append(0)
# self.device_avg.append(float(sum(t_rtt_values) / len(t_rtt_values)))
# self.device_min.append(float(device_data['min_rtt'].replace(',', '')))
# self.device_max.append(float(device_data['max_rtt'].replace(',', '')))
# self.device_avg.append(float(device_data['avg_rtt'].replace(',', '')))
if device_data['os'] == 'Virtual':
self.report_names.append('{} {}'.format(device, device_data['os'])[0:25])
else:
self.report_names.append('{} {} {}'.format(device, device_data['os'], device_data['name']))
if device_data['remarks'] != []:
self.device_names_with_errors.append(device_data['name'])
self.devices_with_errors.append(device)
self.remarks.append(','.join(device_data['remarks']))
logging.info('{} {} {}'.format(*self.packets_sent,
*self.packets_received,
*self.packets_dropped))
logging.info('{} {} {}'.format(*self.device_min,
*self.device_max,
*self.device_avg))
logging.info('Generating Report')
report = lf_report(_output_pdf='interop_ping.pdf',
_output_html='interop_ping.html',
_results_dir_name=result_dir,
_path=report_path)
report_path = report.get_path()
report_path_date_time = report.get_path_date_time()
logging.info('path: {}'.format(report_path))
logging.info('path_date_time: {}'.format(report_path_date_time))
# setting report title
report.set_title('Ping Plotter Test Report')
report.build_banner()
# test setup info
if self.do_webUI:
self.real_sta_list = self.sta_list
for resource in self.real_sta_list:
shelf, r_id, _ = resource.split('.')
url = 'http://{}:{}/resource/{}/{}?fields=hw version'.format(self.host, self.port, shelf, r_id)
hw_version = requests.get(url)
hw_version = hw_version.json()
if 'resource' in hw_version.keys():
hw_version = hw_version['resource']
if 'hw version' in hw_version.keys():
hw_version = hw_version['hw version']
print(hw_version)
if 'Win' in hw_version:
self.windows += 1
elif 'Lin' in hw_version:
self.linux += 1
elif 'Apple' in hw_version:
self.mac += 1
else:
self.android += 1
else:
logging.warning('Malformed response for hw version query on resource manager.')
else: