Repository navigation
Expand file tree
/
Copy pathlf_rf_char.py
More file actions
executable file
·2650 lines (2276 loc) · 110 KB
/
Copy pathlf_rf_char.py
File metadata and controls
executable file
·2650 lines (2276 loc) · 110 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_rf_test.py
PURPOSE:
The purpose of this script is to do RF Characteristics Test.
SETUP:
There need to be a vAP in a Virtual Router on LANforge , goal is to eventually have autogenerated
EXAMPLE:
./lf_rf_char.py --lf_mgr 192.168.0.104 --lf_port 8080 --lf_user lanforge --lf_passwd lanforge \
--vap_port 1.1.vap3 --vap_radio 1.1.wiphy3 --vap_channel 36 --vap_antenna all \
--log_level debug --debug --duration 10s --polling_interval 1s --frame 1400 \
--frame_interval .01
COPYRIGHT:
Copyright (C) 2020-2026 Candela Technologies Inc
License: Free to distribute and modify. LANforge systems must be licensed.
INCLUDE_IN_README
"""
# TODO: Done, Set report timer on vap and radios to 1 sec, possibly smaller.
# TODO: Done, Enable extra tx and rx stats on the radios ,
from pprint import pformat
from pprint import pprint
import argparse
import sys
import os
import logging
import importlib
import datetime
import pandas as pd
# import json
# import traceback
# import csv
import time
import re
import platform
import subprocess
import numpy as np
sys.path.append(os.path.join(os.path.abspath(__file__ + "../../../")))
lanforge_api = importlib.import_module("lanforge_client.lanforge_api")
from lanforge_client.logg import Logg # noqa: E402
from lanforge_client.lanforge_api import LFJsonQuery # noqa: E402
from lanforge_client.lanforge_api import LFJsonCommand # noqa: E402
from lanforge_client.lanforge_api import LFSession # noqa: E402
LFUtils = importlib.import_module("py-json.LANforge.LFUtils")
lf_json_api = importlib.import_module("py-scripts.lf_json_api")
lf_report = importlib.import_module("py-scripts.lf_report")
lf_graph = importlib.import_module("py-scripts.lf_graph")
lf_bar_graph = lf_graph.lf_bar_graph
lf_bar_line_graph = lf_graph.lf_bar_line_graph
lf_line_graph = lf_graph.lf_line_graph
lf_kpi_csv = importlib.import_module("py-scripts.lf_kpi_csv")
lf_logger_config = importlib.import_module("py-scripts.lf_logger_config")
realm = importlib.import_module("py-json.realm")
Realm = realm.Realm
logger = logging.getLogger(__name__)
if sys.version_info[0] != 3:
print("This script requires Python 3")
exit(1)
# RF Characteristics Test
# TODO try to have utilites in own file
class RfCharTest(Realm):
ANT_STR_TO_INT = {
"all": 0,
"1x1": 1,
"2x2": 4,
"3x3": 7,
"4x4": 8,
"8x8": 9,
}
def __init__(self,
lf_mgr: str,
lf_port: str,
lf_user: str,
lf_passwd: str,
debug: bool,
vap_port: str,
vap_radio: str,
vap_channel: str,
vap_antenna: str,
vap_txpower: str,
vap_bw: str,
vap_mode: str,
reset_vap: str,
polling_interval: str,
duration: str,
timeout_sec: str,
frame: str,
frame_interval: str,
**kwargs):
super().__init__(lfclient_host=lf_mgr,
lfclient_port=lf_port,
debug_=True)
self.lf_mgr = lf_mgr
self.lf_port = lf_port
self.lf_user = lf_user
self.lf_passwd = lf_passwd
self.debug = debug
self.vap_port = self.vap_eid = vap_port # TODO: Refactor to just vap_port
self.vap_radio = vap_radio
self.vap_channel = vap_channel
self.vap_antenna = RfCharTest.ANT_STR_TO_INT[vap_antenna]
self.vap_txpower = vap_txpower
self.vap_bw = vap_bw
self.vap_mode = LFJsonCommand.AddVapMode[vap_mode].value
self.reset_vap = reset_vap
self.polling_interval = polling_interval
self.duration = duration
self.timeout_sec = timeout_sec # max seconds to establish the traffic command
self.frame = frame
self.frame_interval = frame_interval
# Get shelf and resource from EIDs
# Shelf and resource for parent radio and vAP should be the same, so just reference vAP's
self.shelf, self.resource, self.port_name, *nil = LFUtils.name_to_eid(self.vap_port)
_, _, self.radio_port_name, *nil = LFUtils.name_to_eid(self.vap_radio)
self.gen_endpoint = ''
self.cx_state = ''
self.bookmark_event_id: int = 0
# create api_json
self.json_vap_api = lf_json_api.lf_json_api(lf_mgr=self.lf_mgr,
lf_port=self.lf_port,
lf_user=self.lf_user,
lf_passwd=self.lf_passwd)
self.json_rad_api = lf_json_api.lf_json_api(lf_mgr=self.lf_mgr,
lf_port=self.lf_port,
lf_user=self.lf_user,
lf_passwd=self.lf_passwd)
# create a session
# self.session = LFSession(lfclient_url="http://{lf_mgr}:{lf_port}".format(lf_mgr=self.lf_mgr, lf_port=self.lf_port),
self.session = LFSession(lfclient_url="http://%s:8080" % self.lf_mgr,
debug=debug,
connection_timeout_sec=4.0,
stream_errors=True,
stream_warnings=True,
require_session=True,
exit_on_error=True)
if debug:
Logg.register_method_name("json_post")
Logg.register_method_name("json_get")
Logg.register_method_name("get_as_json")
# type hinting
self.command: LFJsonCommand
self.command = self.session.get_command()
self.query: LFJsonQuery
self.query = self.session.get_query()
# get dut information
self.lf_command = ''
self.dut_mac = ''
self.dut_ip = ''
self.dut_hostname = ''
# tx data
self.tx_interval = []
self.tx_pkts = []
self.tx_retries = []
self.tx_failed = []
# RSSI calculation
self.rssi_signal = []
self.rssi_1 = []
self.rssi_2 = []
self.rssi_3 = []
self.rssi_4 = []
self.rssi_1_count = 0
self.rssi_2_count = 0
self.rssi_3_count = 0
self.rssi_4_count = 0
# logging
self.debug = debug
def remove_generic_cx(self):
# self.command.die_on_error = False
# self.exit_on_error = False
logger.debug("Stopping generic connections")
generics = self.json_get("/generic/list")
if generics:
cx_list = []
ep_list = []
noun = 'endpoints'
if 'endpoints' in generics:
for item in generics[noun]:
k = next(iter(item))
if item[k]['name']:
if item[k]['name'].startswith("UNKNOWN"):
continue
cx_list.append("CX_" + item[k]['name'])
ep_list.append(item[k]['name'])
# else there is no way to stop an un-named endpoint
# such an item is a zombie item
elif 'endpoint' in generics:
if generics['endpoint']['name'] and not generics['endpoint']['name'].startswith("UNKNOWN"):
cx_list.append("CX_" + generics['endpoint']['name'])
ep_list.append(generics['endpoint']['name'])
# else there is no way to stop an un-named endpoint
# such an item is a zombie item
if len(cx_list):
for cx in cx_list:
self.command.post_rm_cx(cx_name=cx,
test_mgr='all',
suppress_related_commands=True,
debug=True)
for ep in ep_list:
self.command.post_rm_endp(endp_name=ep,
suppress_related_commands=True,
debug=True)
def get_recent_lease_events(self):
"""
Check DHCP lease info from DHCP events.
Assumes have bookmarked last event by calling `bookmark_events()`
before calling this function.
"""
events_rec = self.json_get("/events/since/%d" % self.bookmark_event_id, debug_=self.debug)
if not events_rec:
return None
noun = 'events'
if noun not in events_rec:
noun = 'event'
if noun not in events_rec:
return None
dhcp_events = []
for event_entry in events_rec[noun]:
event = event_entry[next(iter(event_entry))]
# pprint(event)
if event['event description'].startswith("DHCPACK on"):
dhcp_events.append(event)
# pprint(["events", dhcp_events])
return dhcp_events
def dut_info(self):
self.json_vap_api.request = 'stations'
json_stations = []
sta_ap = ''
dut_ip = ''
dut_mac = ''
# dut_hostname = ''
self.shelf, self.resource, self.port_name, *nil = LFUtils.name_to_eid(self.vap_port)
self.vap_eid = "%s.%s.%s" % (self.shelf, self.resource, self.port_name)
event_recs = self.get_recent_lease_events()
other_findings: dict = {}
# look for event containing the vap_name then get the station IP from events
logger.info(f"Gathering station DUT info from vAP \'{self.port_name}\' events")
logger.debug(f"Inspecting {len(event_recs)} Events for vAP \'{self.port_name}\'")
for record in event_recs:
if not (('event description' in record) or record['event description']):
continue
hunks: list[str] = record['event description'].split(" ")
if hunks[6] != self.port_name:
if hunks[6] not in other_findings:
other_findings[hunks[6]] = []
other_findings[hunks[6]].append(hunks[4])
continue
if not self.dut_mac:
self.dut_mac = hunks[4]
dut_ip = hunks[2]
self.dut_ip = dut_ip
logger.warning("== == == == Found DUT IP: %s == == == == " % dut_ip)
break
if not self.dut_ip:
for vap in other_findings.keys():
logger.info(" ...%s has: %s" % (vap, ", ".join(other_findings[vap])))
try:
# does not need specific port information
snc = subprocess.Popen("sync")
snc.wait()
if not self.vap_eid:
self.vap_eid = "1.%s.%s" % (self.resource, self.port_name)
self.command.post_probe_port(shelf=1,
resource=self.resource,
port=self.port_name,
key='probe_port.quiet.' + self.vap_eid)
time.sleep(0.5)
json_stations, *nil = self.json_vap_api.get_request_stations_information()
self.dut_mac = json_stations['station']['station bssid']
sta_ap = json_stations['station']['ap']
logger.debug("Station DUT associated to BSSID: {mac}".format(mac=self.dut_mac))
except BaseException:
# Maybe we have multiple stations showing up on multiple VAPs...find the first one that matches our vap.
logger.debug(f"Searching for vAP \'{self.vap_eid}\' in station DUT association info")
try:
pronoun = 'stations'
if pronoun not in json_stations:
pronoun = 'station'
if pronoun not in json_stations:
logger.info("Did not find station DUT, trying again")
return False
for s in json_stations[pronoun]:
keys = list(s.keys())
vals = s[keys[0]]
if vals['ap'] == self.vap_eid:
sta_ap = self.vap_eid
self.dut_mac = vals['station bssid']
logger.warning(" Found sta, ap: %s mac: %s" % (sta_ap, self.dut_mac))
break
except BaseException:
logger.info("waiting on stations")
pass
if sta_ap == "":
logger.info(" No stations using vAP [%s]" % self.vap_eid)
station_macs: list[str] = []
for record in json_stations['stations']:
bss = next(iter(record))
station_macs.append(bss[bss.rindex('.') + 1:])
logger.info(" stations seen: " + ", ".join(station_macs))
# logger.warning(pformat(json_stations))
return False
# Make sure the station is on correct IP vap
if (sta_ap != self.vap_eid):
logger.warning(f"Detected station DUT associated to AP \'{sta_ap}\', expected it to be associated to vAP DUT \'{self.vap_eid}\'")
return False
if not dut_ip:
# get the IP from port probe
logger.warning("Station DUT IP not found in event records, checking port probe instead")
self.lf_command = ["../lf_portmod.pl", "--manager", self.lf_mgr, "--card", str(self.resource), "--port_name", self.port_name,
"--cli_cmd", "probe_port 1 {resource} {port}".format(resource=self.resource, port=self.port_name)]
logger.debug("command: {cmd}".format(cmd=self.lf_command))
summary_output = ''
process_begin_ms = now_millis()
summary = subprocess.Popen(self.lf_command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(summary.stdout.readline, ''):
logger.debug(line)
summary_output += line
# sys.stdout.flush() # please see comments regarding the necessity of this line
summary.wait()
process_end_ms = now_millis()
logger.debug("lfportmod took %d ms" % (process_end_ms - process_begin_ms))
logger.debug(summary_output) # .decode('utf-8', 'ignore'))
search_dhcp_lease = False
search_equals = False
for line in summary_output.splitlines():
if (line.startswith("DHCPD-Lease-File-Contents")):
search_equals = True
continue
if (search_equals and line.startswith("=========")):
search_dhcp_lease = True
continue
if (search_dhcp_lease):
pat = "(\\S+)\\s+(\\S+)\\s+(\\S+)"
m = re.search(pat, line)
if (m is not None):
dut_mac = m.group(1)
dut_ip = m.group(2)
# dut_hostname = m.group(3)
else:
pat = "(\\S+)\\s+(\\S+)"
m = re.search(pat, line)
if (m is not None):
dut_mac = m.group(1)
dut_ip = m.group(2)
# there should only be one connection
logger.debug(f"Port probe MAC: {dut_mac}, IP: {dut_ip}")
if dut_mac != self.dut_mac:
logger.error(f"Port probe MAC mismatch. Expected {self.dut_mac}, found {dut_mac}")
return False
self.dut_ip = dut_ip
# self.dut_hostname = dut_hostname
logger.info(f"Found station DUT with MAC {self.dut_mac} and IPv4 address {self.dut_ip}")
return True
def clear_dhcp_lease(self):
logger.info(f"Clearing vAP DUT \'{self.vap_port}\' DHCP leases")
extra = 'dhcp_leases'
self.command.post_clear_port_counters(shelf=self.shelf,
resource=self.resource,
port=self.port_name,
extra=extra)
def clear_port_counters(self):
logger.info(f"Clearing port counters for vAP DUT \'{self.vap_port}\' and parent radio \'{self.vap_radio}\'")
self.shelf, self.resource, self.port_name, *nil = LFUtils.name_to_eid(self.vap_port)
# may have to add extra to
self.command.post_clear_port_counters(shelf=self.shelf,
resource=self.resource,
port=self.port_name,
extra=None)
# Clear radio stats too
self.shelf, self.resource, self.port_name, *nil = LFUtils.name_to_eid(self.vap_radio)
self.command.post_clear_port_counters(shelf=self.shelf,
resource=self.resource,
port=self.port_name,
extra=None)
# ./lf_generic_ping.pl --mgr 192.168.0.104 --resource 1 --dest 10.10.10.4 -i vap3 --cmd 'lfping -s 1400 -i 0.01 -I vap3 10.10.10.4
# set_port 1 1 vap3 NA NA NA NA NA NA NA NA NA 32768 5000 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
# set_port 1 1 vap3 NA NA NA NA NA NA NA NA NA 32768 1000
def set_port_report_timer(self, port, milliseconds=1000):
self.command.post_set_port(shelf=self.shelf,
resource=self.resource,
port=self.port_name,
interest=32768,
report_timer=int(milliseconds),
debug=self.debug)
# enable extra_rxstatus extra_txstatus
def set_wifi_radio(self, flags_list=[]):
flag_val = 0
# flag_val = LFPost.set_flags(SetWifiRadioFlags0, flag_names=['extra_rxstatus', 'extra_tx_status'])
flag_val = self.command.set_flags(self.command.SetWifiRadioFlags, flag_val, flag_names=flags_list)
self.command.post_set_wifi_radio(shelf=self.shelf,
resource=self.resource,
radio=self.radio_port_name,
flags=flag_val,
flags_mask=flag_val,
# do not adjust radio mode
debug=self.debug)
def generic_ping(self):
self.shelf, self.resource, self.port_name, *nil = LFUtils.name_to_eid(self.vap_port)
self.gen_endpoint = "CX_lfping_{port_name}".format(port_name=self.port_name)
# need to change the current working director to run lf_generic_ping.pl
cwd_orig = os.getcwd()
logger.info("Current Working Directory is :{cwd}".format(cwd=cwd_orig))
os.chdir('../')
cwd_new = os.getcwd()
logger.info("Move up one dir Working Directory is :{cwd}".format(cwd=cwd_new))
self.lf_command = ["./lf_generic_ping.pl", "--mgr", self.lf_mgr, "--resource", str(self.resource), "--dest", self.dut_ip,
"-i", self.port_name, "--cmd", 'lfping -s {frame} -i {frame_interval} -I {port_name} {dut_ip}'.
format(frame=self.frame, frame_interval=self.frame_interval, port_name=self.port_name, dut_ip=self.dut_ip)]
logger.debug("lf_generic_ping.pl : {cmd}".format(cmd=self.lf_command))
summary_output = ''
summary = subprocess.Popen(self.lf_command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(summary.stdout.readline, ''):
logger.debug(line)
summary_output += line
# sys.stdout.flush() # please see comments regarding the necessity of this line
summary.wait()
logger.debug(summary_output) # .decode('utf-8', 'ignore'))
os.chdir(cwd_orig)
cwd_final = os.getcwd()
logger.info("Current Working Directory is :{cwd}".format(cwd=cwd_final))
# for updating the ping information
# ./lf_generic_ping.pl --mgr 192.168.0.104 --resource 1 --dest 10.10.10.4 -i vap3 --cmd 'lfping -s 1400 -i 0.01 -I vap3 10.10.10.4'
# add_gen_endp
# TODO not working yet using perl command
# TODO pass port
def add_gen_endp(self):
self.shelf, self.resource, self.port_name, *nil = LFUtils.name_to_eid(self.vap_port)
# cross connects prepend CX
self.gen_endpoint = "CX_lfping_{port_name}".format(port_name=self.port_name)
self.command.post_add_gen_endp(
alias=self.gen_endpoint,
port=self.port_name,
resource=self.resource,
shelf=self.shelf,
p_type='gen_generic', # gen_generic is default
debug=self.debug
)
# TODO not working yet using perl command
# TODO pass port
# set_gen_cmd
def set_gen_cmd(self):
self.shelf, self.resource, self.port_name, *nil = LFUtils.name_to_eid(self.vap_port)
lf_command = "lfping '-s {frame} -i {frame_interval} -I {port_name} {ip}".format(
frame=self.frame, frame_interval=self.frame_interval, port_name=self.port_name, ip=self.dut_ip)
self.command.post_set_gen_cmd(
command=lf_command,
name=self.gen_endpoint,
debug=self.debug)
self.wait_until_endps(base_url=self.lfclient_url,
endp_list=("lf_ping_%s" % self.vap_port),
debug=False,
timeout=10)
def set_cx_state(self):
self.command.post_set_cx_state(cx_name=self.gen_endpoint,
cx_state=self.cx_state,
test_mgr='all',
debug=self.debug)
def bookmark_events(self):
self.bookmark_event_id = 0
events_rec = self.json_get("/events/last/1", debug_=self.debug)
if events_rec:
noun = "events"
if noun not in events_rec:
noun = "event"
if noun in events_rec:
# pprint(events_rec[noun])
self.bookmark_event_id = int(events_rec[noun]["id"])
def configure_vap(self):
"""Configure vAP including mode, channel, channel width, txpower."""
# Set vAP transmit power. This should already be validated in argument validation step.
# Transmit power can be any integer between -1 and 30, inclusive
if self.vap_txpower == "DEFAULT":
tx_pow = -1
else:
txpower_int_str = self.vap_txpower.strip("dBm")
tx_pow = int(txpower_int_str)
self.command.post_set_wifi_radio(shelf=self.shelf,
resource=self.resource,
radio=self.port_name,
antenna=self.vap_antenna,
channel=self.vap_channel,
txpower=tx_pow,
# do not set radio mode here
debug=self.debug)
vap_flags = "NA"
vap_flagmask = "NA"
t_channel: int = 0
t_band: int = 0
if "e" in self.vap_channel:
# we are 6Ghz
t_channel = int(self.vap_channel[0:-1])
logger.warning("6gz channel is {}".format(t_channel))
if (t_channel >= 1) and (t_channel <= 233):
t_band = 6
else:
t_channel = int(self.vap_channel)
if (t_channel >= 1) and (t_channel <= 15):
t_band = 2
elif (t_channel >= 32) and (t_channel <= 177):
t_band = 5
elif (t_channel >= 191):
t_band = 6
if t_channel == 0:
raise Exception("strange channel: {}".format(self.vap_channel))
if t_band < 2:
raise Exception("strange bandwidth: {}".format(t_band))
default_flags_24g = self.command.AddVapFlags.use_bss_load \
| self.command.AddVapFlags.use_bss_transition \
| self.command.AddVapFlags.use_rrm_report
default_flags_5g = self.command.AddVapFlags.enable_80211d \
| self.command.AddVapFlags.p_80211h_enable \
| self.command.AddVapFlags.use_bss_load \
| self.command.AddVapFlags.use_bss_transition \
| self.command.AddVapFlags.use_rrm_report
default_flags_6g = self.command.AddVapFlags.use_bss_load \
| self.command.AddVapFlags.use_bss_transition \
| self.command.AddVapFlags.use_rrm_report
t_flags: int = -1
t_flagmask: int = self.command.AddVapFlags.disable_ht40 \
| self.command.AddVapFlags.disable_ht80 \
| self.command.AddVapFlags.ht160_enable
if t_band == 6:
# have to specify hostapd_config in flags to make sure that custom config
# checkbox gets turned off
t_flagmask |= self.command.AddVapFlags.hostapd_config
if self.vap_bw and (not t_band or self.vap_bw == "NA"):
# logger.error("unable to set bandwidth without knowing channel")
raise Exception("unable to set bandwidth without knowing channel")
if self.vap_bw:
if t_band == 2:
t_flags = default_flags_24g
t_flagmask |= default_flags_24g
elif t_band == 5:
t_flags = default_flags_5g
t_flagmask |= default_flags_5g
elif t_band == 6:
t_flags = default_flags_6g
t_flagmask |= default_flags_6g
else:
raise ValueError("Unknown band %s" % t_band)
if self.vap_bw == "20":
t_flags |= self.command.AddVapFlags.disable_ht40
# disabling ht80 appears to remove usefulness of disable_ht40
# | self.command.AddVapFlags.disable_ht80
if self.vap_bw == "40":
t_flags |= self.command.AddVapFlags.disable_ht80
if self.vap_bw == "80":
# disabling ht40 implies forcing 20Mhz
# t_flags |= self.command.AddVapFlags.disable_ht40
if t_band == 2:
raise ValueError("80 mhz bandwidth only available within 5ghz and 6gz frequencies")
if self.vap_bw == "160":
if t_band == 2:
raise ValueError("80 mhz bandwidth only available within 5ghz and 6gz frequencies")
if t_band == 5 and not (t_channel in (36, 100)):
raise ValueError("160 mhz bandwidth only available within 5ghz channels 36 and 100")
t_flags |= self.command.AddVapFlags.ht160_enable
if t_flags > -1:
vap_flags = str(hex(t_flags))
vap_flagmask = str(hex(t_flagmask))
else:
logger.warning("t_flags does not look right: %s" % t_flags)
time.sleep(5)
v_name = self.vap_port
if self.vap_port.find('.') > -1:
v_name = self.vap_port[self.vap_port.rindex('.') + 1:]
r_name = self.vap_radio
if self.vap_radio.find('.') > -1:
r_name = self.vap_radio[self.vap_radio.rindex('.') + 1:]
logger.debug("configure_vap: vap_mode [{}]".format(self.vap_mode))
logger.debug("configure_vap: vap_radio [{}]".format(self.vap_radio))
logger.debug("configure_vap: vap_port [{}]".format(self.vap_port))
logger.debug("configure_vap: port_name [{}]".format(self.port_name))
logger.debug("configure_vap: vap_channel [{}]".format(self.vap_channel))
logger.debug("configure_vap: vap_bw [{}]".format(self.vap_bw))
logger.debug("configure_vap: vap_flags [{}]".format(vap_flags))
logger.debug("configure_vap: vap_flagmask [{}]".format(vap_flagmask))
self.command.post_add_vap(shelf=1,
resource=self.resource,
radio=r_name,
ap_name=v_name,
mode=self.vap_mode,
flags=vap_flags,
flags_mask=vap_flagmask,
debug=True)
queried_mode = "none"
e_w: list = []
poll_start_sec = lanforge_api._now_sec()
deadline_sec = poll_start_sec + 16
while (queried_mode == "none") and (deadline_sec > lanforge_api._now_sec()):
response = self.query.get_port(eid_list=["1.1.vap0000"],
requested_col_names=["alias", "mode"],
errors_warnings=e_w,
debug=True)
if not response:
logger.error("No response to query get_port()")
else:
logger.debug(" Response: %s" % pformat(response))
if e_w:
logger.warning("get_port warnings: %s" % pformat(e_w))
if "mode" in response:
queried_mode = response["mode"]
else:
logger.warning("get_port did not provide vap[mode]")
logger.debug("done polling for vap mode")
if self.reset_vap:
logger.warning("resetting vap [{}]".format(self.port_name))
self.command.post_reset_port(shelf=self.shelf,
resource=self.resource,
port=self.port_name)
# Port reset can make everything kinda hang in limbo
# because we wait for report_timer seconds for ports to report
# again. Lets prompt the port and the virtual router to
# refresh to help get our dhcp leases visible as soon as possible
time.sleep(1)
ncsp_flags: int = LFJsonCommand.NcShowPortsProbeFlags.WIFI \
| LFJsonCommand.NcShowPortsProbeFlags.MII \
| LFJsonCommand.NcShowPortsProbeFlags.BRIDGE \
| LFJsonCommand.NcShowPortsProbeFlags.GW
self.command.post_nc_show_ports(shelf=1,
resource=self.resource,
port=self.port_name,
probe_flags=ncsp_flags)
LFUtils.wait_until_ports_admin_up(base_url=self.lfclient_url,
resource_id=self.resource,
port_list=[self.port_name])
self.command.post_show_vr(shelf=1, resource=self.resource, router='all')
self.command.post_show_vrcx(shelf=1, resource=self.resource, cx_name='all')
def verify_dut_stations(self, deadline_millis: int, dhcp_lookup_ms: int, max_dhcp_lookups: int):
"""
Verify that there exists one or more station DUTs with DHCP leases from the vAP DUT.
This method will reset the vAP if necessary.
"""
begin_lease_lookup_ms = now_millis()
last_vap_reset = now_millis()
try_count = int(max_dhcp_lookups)
found_station: bool = False
# Iterate for defined number of tries, counting down 'try_count' until we find
# stations with DHCP leases corresponding to this vAP
while try_count > 0:
if self.dut_info():
found_station = True
break
attempt_num = 1 + max_dhcp_lookups - try_count
logger.info(f"Looking for DUT info from vAP DUT data, attempt {attempt_num}/{max_dhcp_lookups}")
if now_millis() >= deadline_millis:
raise ValueError("Time expired for DHCP lease lookups")
# Request non-cached vAP port update from server
self.command.post_nc_show_ports(shelf=1,
resource=self.resource,
port=self.port_name,
probe_flags=(LFJsonCommand.NcShowPortsProbeFlags.WIFI |
LFJsonCommand.NcShowPortsProbeFlags.MII |
LFJsonCommand.NcShowPortsProbeFlags.ETHTOOL |
LFJsonCommand.NcShowPortsProbeFlags.EASY_IP_INFO),
debug=self.debug)
# rf_char.command.post_show_vr(shelf=1, resource=rf_char.resource, router='all', debug=rf_char.debug)
self.command.post_probe_port(shelf=1,
resource=self.resource,
port=self.port_name,
key='probe_port.quiet.' + self.vap_eid)
time.sleep(dhcp_lookup_ms / 1000)
try_count -= 1
# A vAP can take about 15 seconds to acquire a lease, hopefully 10.
# Do not reset a vAP sooner than that or it just takes longer.
if now_millis() > (last_vap_reset + 16000):
v_name = self.vap_port
logger.warning(f"Resetting vAP port {v_name}")
if v_name.find('.') > -1:
v_name = self.vap_port[self.vap_port.rindex('.') + 1:]
self.command.post_reset_port(shelf=1,
resource=self.resource,
port=v_name)
LFUtils.wait_until_ports_admin_up(base_url=self.lfclient_url,
resource_id=self.resource,
port_list=[self.port_name])
last_vap_reset = now_millis()
if found_station:
lease_lookup_time = float((now_millis() - begin_lease_lookup_ms) / 1000.0)
logger.info(f"Station DUT DHCP lease lookup time took {lease_lookup_time} sec")
else:
logger.error(f"Unable to find station DUT with DHCP lease after {max_dhcp_lookups} inspections of DHCP table")
sys.exit(1)
if now_millis() >= deadline_millis:
raise ValueError("time expired for DHCP lease lookups")
def start(self):
# first read with
self.json_vap_api.port = self.vap_port
self.json_vap_api.update_port_info()
self.json_vap_api.csv_mode = 'write'
self.json_vap_api.update_csv_mode()
self.json_vap_api.request = 'port'
self.json_rad_api.port = self.vap_radio
self.json_rad_api.update_port_info()
self.json_rad_api.csv_mode = 'write'
self.json_rad_api.update_csv_mode()
self.json_rad_api.request = 'port'
self.tx_interval = []
self.tx_interval_time = []
self.tx_pkts = []
self.tx_retries = []
self.tx_failed = []
self.tx_rate = []
self.rx_rate = []
self.rssi_signal = []
self.rssi_1 = []
self.rssi_2 = []
self.rssi_3 = []
self.rssi_4 = []
self.rssi_1_count = 0
self.rssi_2_count = 0
self.rssi_3_count = 0
self.rssi_4_count = 0
# create lfping generic
'''
# Using lanforge_api
logger.info("create generic endpoint")
self.add_gen_endp()
logger.info("set frame {frame} frame_interval {interval}".format(frame=self.frame,interval=self.frame_interval))
self.set_gen_cmd()
'''
# use the lf_generic_ping.pl
self.generic_ping()
logger.info("start the lfping cx traffic frame: {frame} frame_interval: {frame_interval}".format(frame=self.frame, frame_interval=self.frame_interval))
# TODO understand when data is read
# This needs to be removed
time.sleep(1)
self.cx_state = 'RUNNING' # RUNNING< SWITCHB, QUIESCE, STOPPED, or DELETED
self.set_cx_state()
logger.info("clear port counters")
self.clear_port_counters()
jason_vap_port_stats, *nil = self.json_vap_api.get_request_port_information(port=self.vap_port)
if not jason_vap_port_stats:
raise ValueError("json_vap_api.get_request_port_information returned nothing")
tx_pkts_previous = 0
tx_retries_previous = 0
self.json_vap_api.csv_mode = 'append'
self.json_vap_api.update_csv_mode()
cur_time = datetime.datetime.now()
end_time = self.parse_time(self.duration) + cur_time
polling_interval_milliseconds = self.duration_time_to_milliseconds(self.polling_interval)
sleep_interval = (polling_interval_milliseconds / 1000) / 2
interval = 0
# initialize time stamps
json_vap_port_stats, *nil = self.json_vap_api.get_request_port_information(port=self.vap_port)
current_time_stamp = json_vap_port_stats["interface"]["time-stamp"]
previous_time_stamp = current_time_stamp
tx_pkts_previous = json_vap_port_stats["interface"]["tx pkts"]
tx_retries_previous = json_vap_port_stats["interface"]["wifi retries"]
while cur_time < end_time:
interval_time = cur_time + datetime.timedelta(milliseconds=polling_interval_milliseconds)
# check the port time stamp to see if data changed
# check 1/2 polling interval
while cur_time < interval_time:
cur_time = datetime.datetime.now()
# read the current time
time.sleep(sleep_interval)
json_vap_port_stats, *nil = self.json_vap_api.get_request_port_information(port=self.vap_port)
current_time_stamp = json_vap_port_stats["interface"]["time-stamp"]
if current_time_stamp != previous_time_stamp:
logger.debug("new TX stats: time_stamp {time} previous_time_stamp {pre_time}".format(time=current_time_stamp, pre_time=previous_time_stamp))
previous_time_stamp = current_time_stamp
break
# Here check if the time stamp has changed
# json_vap_port_stats, *nil = self.json_vap_api.get_request_port_information(port=self.vap_port)
interval += float(polling_interval_milliseconds) / 1000
self.tx_interval.append(round(interval, 2))
current_time = current_time_stamp.split()
self.tx_interval_time.append(current_time[1])
if tx_pkts_previous <= json_vap_port_stats["interface"]["tx pkts"]:
self.tx_pkts.append(json_vap_port_stats["interface"]["tx pkts"] - tx_pkts_previous)
else:
self.tx_pkts.append(0)
tx_pkts_previous = json_vap_port_stats["interface"]["tx pkts"]
if tx_retries_previous <= json_vap_port_stats["interface"]["wifi retries"]:
self.tx_retries.append(json_vap_port_stats["interface"]["wifi retries"] - tx_retries_previous)
else:
self.tx_retries.append(0)
tx_retries_previous = json_vap_port_stats["interface"]["wifi retries"]
self.tx_failed.append(round(json_vap_port_stats["interface"]["tx-failed %"], 2))
self.rx_rate.append(json_vap_port_stats["interface"]["rx-rate"])
self.tx_rate.append(json_vap_port_stats["interface"]["tx-rate"])
# calculated the transmitted packets compared to number of retries
# take samples of RSSI
self.json_vap_api.request = 'stations'
# port not needed for all
json_stations, *nil = self.json_vap_api.get_request_stations_information()
logger.info("json_stations {json}".format(json=pformat(json_stations)))
chain_rssi: list = []
if "station" in json_stations:
self.rssi_signal.append(json_stations['station']['signal'])
chain_rssi_str = json_stations['station']['chain rssi']
chain_rssi = chain_rssi_str.split(',')
elif "stations" in json_stations:
# Maybe we have multiple stations showing up on multiple VAPs...find the first one that matches our vap.
# pprint(json_stations)
# This should give us faster lookup if I knew how to use it.
# sta_key = "0.0.0.%s"%(self.dut_mac)
# pprint("key: %s"%(sta_key))
for s in json_stations['stations']:
keys = list(s.keys())
vals = s[keys[0]]
if vals['station bssid'] == self.dut_mac:
self.rssi_signal.append(int(vals['signal'].lstrip()))
chain_rssi_str = vals['chain rssi']
chain_rssi = chain_rssi_str.split(',')
break
else:
logger.info("json_stations lacks station info, next...")
continue
if chain_rssi:
logger.info("RSSI chain length {chain}".format(chain=len(chain_rssi)))
if len(chain_rssi) == 1:
self.rssi_1.append(int(chain_rssi[0].lstrip()))
self.rssi_2.append(np.nan)
self.rssi_3.append(np.nan)
self.rssi_4.append(np.nan)
self.rssi_1_count = self.rssi_1_count + 1
elif len(chain_rssi) == 2:
self.rssi_1.append(int(chain_rssi[0].lstrip()))
self.rssi_2.append(int(chain_rssi[1].lstrip()))
self.rssi_3.append(np.nan)
self.rssi_4.append(np.nan)
self.rssi_2_count = self.rssi_2_count + 1
elif len(chain_rssi) == 3:
self.rssi_1.append(int(chain_rssi[0].lstrip()))
self.rssi_2.append(int(chain_rssi[1].lstrip()))
self.rssi_3.append(int(chain_rssi[2].lstrip()))
self.rssi_4.append(np.nan)
self.rssi_3_count = self.rssi_3_count + 1
elif len(chain_rssi) == 4:
self.rssi_1.append(int(chain_rssi[0].lstrip()))
self.rssi_2.append(int(chain_rssi[1].lstrip()))
self.rssi_3.append(int(chain_rssi[2].lstrip()))
self.rssi_4.append(int(chain_rssi[3].lstrip()))
self.rssi_4_count = self.rssi_4_count + 1
else:
self.rssi_1.append(np.nan)
self.rssi_2.append(np.nan)
self.rssi_3.append(np.nan)
self.rssi_4.append(np.nan)
self.rssi_4_count = 0
self.json_vap_api.csv_mode = 'write'
self.json_vap_api.update_csv_mode()
# TODO make the get_request more generic just set the request
self.json_rad_api.request = 'wifi-stats'
# Read the vap device stats, it will also be able to report underlying radio stats as needed.
request_attempts: int = 6
json_wifi_stats: dict = None
while request_attempts >= 0:
request_attempts -= 1
json_wifi_stats, *nil = self.json_rad_api.get_request_wifi_stats_information(port=self.vap_port)
if not json_wifi_stats:
raise ValueError("__name__ get_request_wifi_stats_information unable to create json_wifi_stats")
if self.port_name not in json_wifi_stats:
# raise ValueError("port %s not in json_wifi_stats" % self.port_name)
time.sleep(1)
continue
request_attempts = -1
logger.debug("wifi-stats output, vap-radio: %s radio port name %s:" % (self.vap_radio, self.port_name))
# pprint(json_wifi_stats)
# Stop Traffic
self.cx_state = 'STOPPED' # RUNNING< SWITCHB, QUIESCE, STOPPED, or DELETED
self.set_cx_state()
return jason_vap_port_stats, json_wifi_stats
# gather interval samples read stations to get RX Bytes, TX Bytes, TX Retries,
# read the extended mgr tab to get rx tx MCS, NSS
def read_wifi_stats(self):
pass
def read_stations(self):
pass
# sort the values when in a list
def num_sort(strn):