def __init__(self, host, port, security_debug_on=False, _exit_on_error=False,_exit_on_fail=False):
        super().__init__(host, port, _debug=security_debug_on, _halt_on_error=_exit_on_error, _exit_on_fail=_exit_on_fail)
        self.host = host
        self.port = port

        #Creating a Realm Object
        self.local_realm = Realm(lfclient_host=host, lfclient_port=port)
Beispiel #2
0
def main():
    _principal = '{}@{}'.format(options.join_user, options.join_domain.upper())
    _check_keytab_file()
    # Checking if the user authentication is already created. If don't, do it.
    create_bkp()
    try:
        if not _check_keytab_entry(_principal):
            _inserting_domain_auth(_principal)
        if not _check_keytab_entry('{}@{}'.format(socket.gethostname(),
                                                  options.join_domain)):
            realm = Realm(options.join_domain, options.join_user,
                          options.join_password)
            realm.join()
        if options.manage_sssd:
            sssd_data = {
                'domain': options.join_domain,
                'auth_id': _principal,
                'keytab_file': options.keytab_file,
                'domain_with_only_sid': options.domain_with_only_sid
            }
            sssd = SSSD(**sssd_data)
            sssd.write_sssd_section()
    except Exception as e:
        rollback()
        print(str(e))
Beispiel #3
0
 def __init__(self, lfjson_host, lfjson_port):
     super().__init__(_lfjson_host=lfjson_host,
                      _lfjson_port=lfjson_port,
                      _halt_on_error=True,
                      _debug=False)
     self.localrealm = Realm(lfclient_host=lfjson_host,
                             lfclient_port=lfjson_port,
                             debug=False)
     self.check_connect()
Beispiel #4
0
    def __init__(self,
                 host,
                 port,
                 radio,
                 num_sta,
                 sta_id,
                 ssid,
                 security,
                 password,
                 upstream,
                 protocol,
                 min_bps,
                 max_bps,
                 security_debug_on=True,
                 _exit_on_error=True,
                 _exit_on_fail=True):
        super().__init__(host,
                         port,
                         _debug=security_debug_on,
                         _halt_on_error=_exit_on_error,
                         _exit_on_fail=_exit_on_fail)

        self.host = host
        self.port = port
        self.radio = radio

        self.num_sta = num_sta
        self.sta_id = sta_id

        self.ssid = ssid

        self.security = security
        self.password = password

        self.upstream = upstream
        self.protocol = protocol

        self.min_bps = min_bps
        self.max_bps = max_bps

        #Creating a Realm Object
        self.local_realm = Realm(lfclient_host=host, lfclient_port=port)

        #Creating Profile Objects
        self.station_profile = self.local_realm.new_station_profile()
        self.cx_profile = self.local_realm.new_l3_cx_profile()

        #Setting CX Name
        self.cx_profile.name_prefix_ = "Connection"
        self.cx_names = []
        self.sta_list = []
        self.endp = []
        for i in range(sta_id, sta_id + num_sta):
            self.sta_list.append("sta00")

        #portDhcpUpRequest
        '''
 def __init__(self,
              host,
              port,
              _dut_ssid="jedway-open-1",
              _dut_passwd="NA",
              _dut_bssid="",
              _user="",
              _passwd="",
              _sta_mode="0",
              _radio="wiphy0",
              _resource=1,
              _upstream_resource=1,
              _upstream_port="eth1",
              _sta_name=None,
              debug_=False,
              _dut_security=OPEN,
              _exit_on_error=False,
              _cleanup_on_exit=True,
              _runtime_sec=60,
              _exit_on_fail=False):
     # do not use `super(LFCLiBase,self).__init__(self, host, port, _debugOn)
     # that is py2 era syntax and will force self into the host variable, making you
     # very confused.
     super().__init__(host,
                      port,
                      _debug=debug_,
                      _halt_on_error=_exit_on_error,
                      _exit_on_fail=_exit_on_fail)
     self.debug = debug_
     self.dut_security = _dut_security
     self.dut_ssid = _dut_ssid
     self.dut_passwd = _dut_passwd
     self.dut_bssid = _dut_bssid
     self.user = _user
     self.passwd = _passwd
     self.sta_mode = _sta_mode  # See add_sta LANforge CLI users guide entry
     self.radio = _radio
     self.resource = _resource
     self.upstream_resource = _upstream_resource
     self.upstream_port = _upstream_port
     self.runtime_secs = _runtime_sec
     self.cleanup_on_exit = _cleanup_on_exit
     self.sta_url_map = None  # defer construction
     self.upstream_url = None  # defer construction
     self.station_names = []
     if _sta_name is not None:
         self.station_names = [_sta_name]
     # self.localrealm :Realm = Realm(lfclient_host=host, lfclient_port=port) # py > 3.6
     self.localrealm = Realm(lfclient_host=host,
                             lfclient_port=port)  # py > 3.6
     self.resulting_stations = {}
     self.resulting_endpoints = {}
     self.station_profile = None
     self.l3_udp_profile = None
     self.l3_tcp_profile = None
class FindPorts(LFCliBase):
     def __init__(self, host, port, security_debug_on=False, _exit_on_error=False,_exit_on_fail=False):
        super().__init__(host, port, _debug=security_debug_on, _halt_on_error=_exit_on_error, _exit_on_fail=_exit_on_fail)
        self.host = host
        self.port = port

        #Creating a Realm Object
        self.local_realm = Realm(lfclient_host=host, lfclient_port=port)


     def FindExistingCX(self):

         return self.local_realm.cx_list()

     def FindVAP(self):
         return self.local_realm.vap_list()
Beispiel #7
0
class StationsConnected(LFCliBase):
    def __init__(self, lfjson_host, lfjson_port):
        super().__init__(_lfjson_host=lfjson_host,
                         _lfjson_port=lfjson_port,
                         _halt_on_error=True,
                         _debug=False)
        self.localrealm = Realm(lfclient_host=lfjson_host,
                                lfclient_port=lfjson_port,
                                debug=False)
        self.check_connect()

    def run(self):
        self.clear_test_results()
        fields = "_links,port,alias,ip,ap,port+type"
        self.station_results = self.localrealm.find_ports_like("sta*",
                                                               fields,
                                                               debug_=False)
        #pprint(self.station_results)
        if (self.station_results is None) or (len(self.station_results) < 1):
            self.get_failed_result_list()
            return False
        return True

    def num_associated(self, bssid):
        counter = 0
        # print("there are %d results" % len(self.station_results))
        for eid, record in self.station_results.items():
            #print("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ")
            #pprint(eid)
            #pprint(record)
            if record["ap"] == bssid:
                counter += 1
            #print("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ")
        return counter
Beispiel #8
0
 def __init__(self, worldConf,\
              dbpool,\
              dev_id_cache,\
              offline_message_cache,\
              pushPB, apnPB):
     self.dbpool = dbpool
     Realm.__init__(self, "server", "Mainserver")
     self.worldConf = worldConf
     self.worlds = self.initializeWorlds()
     self.UDP = HideoutUDP(self)
     self.worldList = self.generateWorldList()
     self.deviceIDCache = dev_id_cache
     self.chatStore = offline_message_cache
     self.dbKA = LoopingCall(self.dbKeepAlive)
     self.dbKA.start(3600)
     self.pushPB = pushPB
     self.apnPB = apnPB
Beispiel #9
0
 def __init__(self, worldConf,\
              dbpool,\
              dev_id_cache,\
              offline_message_cache,\
              pushPB, apnPB, fbinv):
     self.dbpool = dbpool
     Realm.__init__(self, "server", "Mainserver")
     self.worldConf = worldConf
     self.worlds = self.initializeWorlds()
     self.worldList = self.generateWorldList()
     self.deviceIDCache = dev_id_cache
     self.chatStore = offline_message_cache
     self.chatStore
     self.dbKA = LoopingCall(self.dbKeepAlive)
     self.dbKA.start(3600)
     self.pushPB = pushPB
     self.apnPB = apnPB
     self.fbinv = fbinv
     self.fbinv.service = self
Beispiel #10
0
 def __init__(self,
              lfhost="localhost",
              lfport=8080,
              debug_=False,
              lanforge_db_=None,
              cv_scenario_=None,
              cv_test_=None,
              test_scenario_=None):
     super().__init__(_lfjson_host=lfhost,
                      _lfjson_port=lfport,
                      _debug=debug_,
                      _halt_on_error=True,
                      _exit_on_error=True,
                      _exit_on_fail=True)
     self.lanforge_db = lanforge_db_
     self.cv_scenario = cv_scenario_
     self.cv_test = cv_test_
     self.test_profile = test_scenario_
     self.localrealm = Realm(lfclient_host=lfhost,
                             lfclient_port=lfport,
                             debug_=debug_)
     self.report_name = None
Beispiel #11
0
import win32con

import bot_config
from bot_config import BotConfig
from common import *
import emu_manager
import time
import screen_processor
import util
from realm import Realm, TICKET_AREAS, MAP_PANEL_DISPLAY, MAX_TICKETS

FINISHED_MAIN_LOOP = False
debug = 0

realm_obj = Realm()
bot_cfg = BotConfig()

logger = util.get_logger()

def set_up():
    logger.info("Setting up emulator...")
    # Find Nox and bring to foreground
    hwnd = emu_manager.get_instance(int(bot_cfg.get_property("Emulator", "use_device")))

    if not hwnd:
        logger.info("ERROR!!! Could not get Nox instance")
        return

    logger.info("Got Nox player!")
    win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
#!/usr/bin/env python3
import pprint
import time
from pprint import pprint
import realm
from realm import Realm
import LANforge
from LANforge import LFUtils

localrealm = Realm("localhost", 8080, True)

print("** Existing Stations **")
try:
    sta_list = localrealm.station_list()
    print("\n%s Station List:" % len(sta_list))
    print(sta_list)
    del sta_list
    sta_map = localrealm.station_map()
    print("\n%s Station Map:" % len(sta_map))
    print(sta_map)
    del sta_map
    print("\n  Stations like wlan+:")
    print(localrealm.find_ports_like("wlan+"))
    print("\n  Stations like wlan0:")
    print(localrealm.find_ports_like("wlan0*"))
    print("\n  Stations between wlan0..wlan2:")
    print(localrealm.find_ports_like("wlan[0..2]"))
except Exception as x:
    pprint(x)
    exit(1)
Beispiel #13
0
class EAPConnect(LFCliBase):
    def __init__(self,
                 host,
                 port,
                 security=None,
                 ssid=None,
                 sta_list=None,
                 number_template="00000",
                 _debug_on=False,
                 _dut_bssid="",
                 _exit_on_error=False,
                 _sta_name=None,
                 _resource=1,
                 radio="wiphy0",
                 key_mgmt="WPA-EAP",
                 eap="",
                 identity="",
                 ttls_passwd="",
                 hessid=None,
                 ttls_realm="",
                 domain="",
                 _sta_prefix='eap',
                 _exit_on_fail=False,
                 _cleanup_on_exit=True):
        super().__init__(host,
                         port,
                         _debug=_debug_on,
                         _halt_on_error=_exit_on_error,
                         _exit_on_fail=_exit_on_fail)
        self.host = host
        self.port = port
        self.ssid = ssid
        self.radio = radio
        self.security = security
        #self.password = password
        self.sta_list = sta_list
        self.key_mgmt = key_mgmt
        self.eap = eap
        self.sta_prefix = _sta_prefix
        self.identity = identity
        self.ttls_passwd = ttls_passwd
        self.ttls_realm = ttls_realm
        self.domain = domain
        self.hessid = hessid
        self.dut_bssid = _dut_bssid
        self.timeout = 120
        self.number_template = number_template
        self.debug = _debug_on
        self.local_realm = realm.Realm(lfclient_host=self.host,
                                       lfclient_port=self.port)
        self.station_profile = self.local_realm.new_station_profile()
        self.station_profile.lfclient_url = self.lfclient_url
        self.station_profile.ssid = self.ssid
        self.station_profile.security = self.security
        self.station_profile.number_template_ = self.number_template
        self.station_profile.mode = 0
        #Added to test_ipv4_ttls code
        self.upstream_url = None  # defer construction
        self.sta_url_map = None
        self.upstream_resource = None
        self.upstream_port = "eth2"
        self.station_names = []
        if _sta_name is not None:
            self.station_names = [_sta_name]
        self.localrealm = Realm(lfclient_host=host, lfclient_port=port)
        self.resource = _resource
        self.cleanup_on_exit = _cleanup_on_exit
        self.resulting_stations = {}
        self.resulting_endpoints = {}
        self.station_profile = None
        self.l3_udp_profile = None
        self.l3_tcp_profile = None

    # def get_realm(self) -> Realm: # py > 3.6
    def get_realm(self):
        return self.localrealm

    def get_station_url(self, sta_name_=None):
        if sta_name_ is None:
            raise ValueError("get_station_url wants a station name")
        if self.sta_url_map is None:
            self.sta_url_map = {}
            for sta_name in self.station_names:
                self.sta_url_map[sta_name] = "port/1/%s/%s" % (self.resource,
                                                               sta_name)
        return self.sta_url_map[sta_name_]

    def get_upstream_url(self):
        if self.upstream_url is None:
            self.upstream_url = "port/1/%s/%s" % (self.upstream_resource,
                                                  self.upstream_port)
        return self.upstream_url

    # Compare pre-test values to post-test values
    def compare_vals(self, name, postVal, print_pass=False, print_fail=True):
        # print(f"Comparing {name}")
        if postVal > 0:
            self._pass("%s %s" % (name, postVal), print_pass)
        else:
            self._fail("%s did not report traffic: %s" % (name, postVal),
                       print_fail)

    def remove_stations(self):
        for name in self.station_names:
            LFUtils.removePort(self.resource, name, self.lfclient_url)

    def num_associated(self, bssid):
        counter = 0
        # print("there are %d results" % len(self.station_results))
        fields = "_links,port,alias,ip,ap,port+type"
        self.station_results = self.localrealm.find_ports_like("%s*" %
                                                               self.sta_prefix,
                                                               fields,
                                                               debug_=False)
        if (self.station_results is None) or (len(self.station_results) < 1):
            self.get_failed_result_list()
        for eid, record in self.station_results.items():
            #print("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ")
            #pprint(eid)
            #pprint(record)
            if record["ap"] == bssid:
                counter += 1
            #print("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ")
        return counter

    def clear_test_results(self):
        self.resulting_stations = {}
        self.resulting_endpoints = {}
        super().clear_test_results()
        #super(StaConnect, self).clear_test_results().test_results.clear()

    def setup(self):
        self.clear_test_results()
        self.check_connect()
        upstream_json = self.json_get("%s?fields=alias,phantom,down,port,ip" %
                                      self.get_upstream_url(),
                                      debug_=False)

        if upstream_json is None:
            self._fail(message="Unable to query %s, bye" % self.upstream_port,
                       print_=True)
            return False

        if upstream_json['interface']['ip'] == "0.0.0.0":
            if self.debug:
                pprint.pprint(upstream_json)
            self._fail("Warning: %s lacks ip address" %
                       self.get_upstream_url(),
                       print_=True)
            return False

        # remove old stations
        print("Removing old stations")
        for sta_name in self.station_names:
            sta_url = self.get_station_url(sta_name)
            response = self.json_get(sta_url)
            if (response is not None) and (response["interface"] is not None):
                for sta_name in self.station_names:
                    LFUtils.removePort(self.resource, sta_name,
                                       self.lfclient_url)
        LFUtils.wait_until_ports_disappear(self.lfclient_url,
                                           self.station_names)

        # Create stations and turn dhcp on
        self.station_profile = self.localrealm.new_station_profile()

        # Build stations
        self.station_profile.use_security(self.security,
                                          self.ssid,
                                          passwd="[BLANK]")
        self.station_profile.set_number_template(self.number_template)
        print("Creating stations")
        self.station_profile.set_command_flag("add_sta", "create_admin_down",
                                              1)
        self.station_profile.set_command_param("set_port", "report_timer",
                                               1500)
        self.station_profile.set_command_flag("set_port", "rpt_timer", 1)
        self.station_profile.set_wifi_extra(key_mgmt=self.key_mgmt,
                                            eap=self.eap,
                                            identity=self.identity,
                                            passwd=self.ttls_passwd,
                                            realm=self.ttls_realm,
                                            domain=self.domain,
                                            hessid=self.hessid)
        self.station_profile.create(radio=self.radio,
                                    sta_names_=self.sta_list,
                                    debug=self.debug,
                                    use_radius=True,
                                    hs20_enable=False)
        self._pass("PASS: Station build finished")

        self.create_traffic = createTraffic(self.localrealm, self.sta_prefix,
                                            self.resource, self.upstream_port)
        self.create_traffic.lf_l3_udp_profile()
        self.create_traffic.lf_l3_tcp_profile()

    def start(self):
        if self.station_profile is None:
            self._fail("Incorrect setup")
        pprint.pprint(self.station_profile)
        if self.station_profile.up is None:
            self._fail("Incorrect station profile, missing profile.up")
        if self.station_profile.up == False:
            print("\nBringing ports up...")
            data = {
                "shelf": 1,
                "resource": self.resource,
                "port": "ALL",
                "probe_flags": 1
            }
            self.json_post("/cli-json/nc_show_ports", data)
            self.station_profile.admin_up()
            LFUtils.waitUntilPortsAdminUp(self.resource, self.lfclient_url,
                                          self.station_names)

        # station_info = self.jsonGet(self.mgr_url, "%s?fields=port,ip,ap" % (self.getStaUrl()))
        duration = 0
        maxTime = 60
        ip = "0.0.0.0"
        ap = ""
        print("Waiting for %s stations to associate to AP: " %
              len(self.station_names),
              end="")
        connected_stations = {}
        while (len(connected_stations.keys()) < len(
                self.station_names)) and (duration < maxTime):
            duration += 3
            time.sleep(3)
            print(".", end="")
            for sta_name in self.station_names:
                sta_url = self.get_station_url(sta_name)
                station_info = self.json_get(sta_url + "?fields=port,ip,ap")

                # LFUtils.debug_printer.pprint(station_info)
                if (station_info is not None) and ("interface"
                                                   in station_info):
                    if "ip" in station_info["interface"]:
                        ip = station_info["interface"]["ip"]
                    if "ap" in station_info["interface"]:
                        ap = station_info["interface"]["ap"]

                if (ap == "Not-Associated") or (ap == ""):
                    if self.debug:
                        print(" -%s," % sta_name, end="")
                else:
                    if ip == "0.0.0.0":
                        if self.debug:
                            print(" %s (0.0.0.0)" % sta_name, end="")
                    else:
                        connected_stations[sta_name] = sta_url
            data = {
                "shelf": 1,
                "resource": self.resource,
                "port": "ALL",
                "probe_flags": 1
            }
            self.json_post("/cli-json/nc_show_ports", data)

        for sta_name in self.station_names:
            sta_url = self.get_station_url(sta_name)
            station_info = self.json_get(sta_url)  # + "?fields=port,ip,ap")
            if station_info is None:
                print("unable to query %s" % sta_url)
            self.resulting_stations[sta_url] = station_info
            ap = station_info["interface"]["ap"]
            ip = station_info["interface"]["ip"]
            if (ap != "") and (ap != "Not-Associated"):
                print(" %s +AP %s, " % (sta_name, ap), end="")
                if self.dut_bssid != "":
                    if self.dut_bssid.lower() == ap.lower():
                        self._pass(sta_name + " connected to BSSID: " + ap)
                        # self.test_results.append("PASSED: )
                        # print("PASSED: Connected to BSSID: "+ap)
                    else:
                        self._fail(
                            "%s connected to wrong BSSID, requested: %s  Actual: %s"
                            % (sta_name, self.dut_bssid, ap))
            else:
                self._fail(sta_name + " did not connect to AP")
                return False

            if ip == "0.0.0.0":
                self._fail("%s did not get an ip. Ending test" % sta_name)
            else:
                self._pass("%s connected to AP: %s  With IP: %s" %
                           (sta_name, ap, ip))

        if self.passes() == False:
            if self.cleanup_on_exit:
                print("Cleaning up...")
                self.remove_stations()
            return False

        # start cx traffic
        print("\nStarting CX Traffic")

        self.create_traffic.l3_udp_profile.start_cx()
        self.create_traffic.l3_tcp_profile.start_cx()
        time.sleep(1)
        self.create_traffic.l3_tcp_profile.refresh_cx()
        self.create_traffic.l3_udp_profile.refresh_cx()

    def collect_endp_stats(self, endp_map):
        print("Collecting Data")
        fields = "?fields=name,tx+bytes,rx+bytes"
        for (cx_name, endps) in endp_map.items():
            try:
                endp_url = "/endp/%s%s" % (endps[0], fields)
                endp_json = self.json_get(endp_url)
                self.resulting_endpoints[endp_url] = endp_json
                ptest_a_tx = endp_json['endpoint']['tx bytes']
                ptest_a_rx = endp_json['endpoint']['rx bytes']

                #ptest = self.json_get("/endp/%s?fields=tx+bytes,rx+bytes" % cx_names[cx_name]["b"])
                endp_url = "/endp/%s%s" % (endps[1], fields)
                endp_json = self.json_get(endp_url)
                self.resulting_endpoints[endp_url] = endp_json

                ptest_b_tx = endp_json['endpoint']['tx bytes']
                ptest_b_rx = endp_json['endpoint']['rx bytes']

                self.compare_vals("testTCP-A TX", ptest_a_tx)
                self.compare_vals("testTCP-A RX", ptest_a_rx)

                self.compare_vals("testTCP-B TX", ptest_b_tx)
                self.compare_vals("testTCP-B RX", ptest_b_rx)

            except Exception as e:
                print("Is this the function having the error?")
                self.error(e)

    def stop(self):
        # stop cx traffic
        print("Stopping CX Traffic")
        self.create_traffic.l3_udp_profile.stop_cx()
        self.create_traffic.l3_tcp_profile.stop_cx()

        # Refresh stats
        print("\nRefresh CX stats")
        self.create_traffic.l3_udp_profile.refresh_cx()
        self.create_traffic.l3_tcp_profile.refresh_cx()

        print("Sleeping for 5 seconds")
        time.sleep(5)

        # get data for endpoints JSON
        self.collect_endp_stats(self.create_traffic.l3_udp_profile.created_cx)
        self.collect_endp_stats(self.create_traffic.l3_tcp_profile.created_cx)
        # print("\n")

    def cleanup(self):
        # remove all endpoints and cxs
        if self.cleanup_on_exit:
            for sta_name in self.station_names:
                LFUtils.removePort(self.resource, sta_name, self.lfclient_url)
            curr_endp_names = []
            removeCX(self.lfclient_url,
                     self.create_traffic.l3_udp_profile.get_cx_names())
            removeCX(self.lfclient_url,
                     self.create_traffic.l3_tcp_profile.get_cx_names())
            for (cx_name, endp_names
                 ) in self.create_traffic.l3_udp_profile.created_cx.items():
                curr_endp_names.append(endp_names[0])
                curr_endp_names.append(endp_names[1])
            for (cx_name, endp_names
                 ) in self.create_traffic.l3_tcp_profile.created_cx.items():
                curr_endp_names.append(endp_names[0])
                curr_endp_names.append(endp_names[1])
            removeEndps(self.lfclient_url, curr_endp_names, debug=self.debug)
Beispiel #14
0
 def __init__(self,
              host,
              port,
              security=None,
              ssid=None,
              sta_list=None,
              number_template="00000",
              _debug_on=False,
              _dut_bssid="",
              _exit_on_error=False,
              _sta_name=None,
              _resource=1,
              radio="wiphy0",
              key_mgmt="WPA-EAP",
              eap="",
              identity="",
              ttls_passwd="",
              hessid=None,
              ttls_realm="",
              domain="",
              _sta_prefix='eap',
              _exit_on_fail=False,
              _cleanup_on_exit=True):
     super().__init__(host,
                      port,
                      _debug=_debug_on,
                      _halt_on_error=_exit_on_error,
                      _exit_on_fail=_exit_on_fail)
     self.host = host
     self.port = port
     self.ssid = ssid
     self.radio = radio
     self.security = security
     #self.password = password
     self.sta_list = sta_list
     self.key_mgmt = key_mgmt
     self.eap = eap
     self.sta_prefix = _sta_prefix
     self.identity = identity
     self.ttls_passwd = ttls_passwd
     self.ttls_realm = ttls_realm
     self.domain = domain
     self.hessid = hessid
     self.dut_bssid = _dut_bssid
     self.timeout = 120
     self.number_template = number_template
     self.debug = _debug_on
     self.local_realm = realm.Realm(lfclient_host=self.host,
                                    lfclient_port=self.port)
     self.station_profile = self.local_realm.new_station_profile()
     self.station_profile.lfclient_url = self.lfclient_url
     self.station_profile.ssid = self.ssid
     self.station_profile.security = self.security
     self.station_profile.number_template_ = self.number_template
     self.station_profile.mode = 0
     #Added to test_ipv4_ttls code
     self.upstream_url = None  # defer construction
     self.sta_url_map = None
     self.upstream_resource = None
     self.upstream_port = "eth2"
     self.station_names = []
     if _sta_name is not None:
         self.station_names = [_sta_name]
     self.localrealm = Realm(lfclient_host=host, lfclient_port=port)
     self.resource = _resource
     self.cleanup_on_exit = _cleanup_on_exit
     self.resulting_stations = {}
     self.resulting_endpoints = {}
     self.station_profile = None
     self.l3_udp_profile = None
     self.l3_tcp_profile = None
class SingleClient(LFCliBase):
    def __init__(self,
                 host,
                 port,
                 _dut_ssid="jedway-open-1",
                 _dut_passwd="NA",
                 _dut_bssid="",
                 _user="",
                 _passwd="",
                 _sta_mode="0",
                 _radio="wiphy0",
                 _resource=1,
                 _upstream_resource=1,
                 _upstream_port="eth1",
                 _sta_name=None,
                 debug_=False,
                 _dut_security=OPEN,
                 _exit_on_error=False,
                 _cleanup_on_exit=True,
                 _runtime_sec=60,
                 _exit_on_fail=False):
        # do not use `super(LFCLiBase,self).__init__(self, host, port, _debugOn)
        # that is py2 era syntax and will force self into the host variable, making you
        # very confused.
        super().__init__(host,
                         port,
                         _debug=debug_,
                         _halt_on_error=_exit_on_error,
                         _exit_on_fail=_exit_on_fail)
        self.debug = debug_
        self.dut_security = _dut_security
        self.dut_ssid = _dut_ssid
        self.dut_passwd = _dut_passwd
        self.dut_bssid = _dut_bssid
        self.user = _user
        self.passwd = _passwd
        self.sta_mode = _sta_mode  # See add_sta LANforge CLI users guide entry
        self.radio = _radio
        self.resource = _resource
        self.upstream_resource = _upstream_resource
        self.upstream_port = _upstream_port
        self.runtime_secs = _runtime_sec
        self.cleanup_on_exit = _cleanup_on_exit
        self.sta_url_map = None  # defer construction
        self.upstream_url = None  # defer construction
        self.station_names = []
        if _sta_name is not None:
            self.station_names = [_sta_name]
        # self.localrealm :Realm = Realm(lfclient_host=host, lfclient_port=port) # py > 3.6
        self.localrealm = Realm(lfclient_host=host,
                                lfclient_port=port)  # py > 3.6
        self.resulting_stations = {}
        self.resulting_endpoints = {}
        self.station_profile = None
        self.l3_udp_profile = None
        self.l3_tcp_profile = None

    # def get_realm(self) -> Realm: # py > 3.6
    def get_realm(self):
        return self.localrealm

    def get_station_url(self, sta_name_=None):
        if sta_name_ is None:
            raise ValueError("get_station_url wants a station name")
        if self.sta_url_map is None:
            self.sta_url_map = {}
            for sta_name in self.station_names:
                self.sta_url_map[sta_name] = "port/1/%s/%s" % (self.resource,
                                                               sta_name)
        return self.sta_url_map[sta_name_]

    def get_upstream_url(self):
        if self.upstream_url is None:
            self.upstream_url = "port/1/%s/%s" % (self.upstream_resource,
                                                  self.upstream_port)
        return self.upstream_url

    # Compare pre-test values to post-test values
    def compare_vals(self, name, postVal, print_pass=False, print_fail=True):
        # print(f"Comparing {name}")
        if postVal > 0:
            self._pass("%s %s" % (name, postVal), print_pass)
        else:
            self._fail("%s did not report traffic: %s" % (name, postVal),
                       print_fail)

    def remove_stations(self):
        for name in self.station_names:
            LFUtils.removePort(self.resource, name, self.lfclient_url)

    def num_associated(self, bssid):
        counter = 0
        # print("there are %d results" % len(self.station_results))
        fields = "_links,port,alias,ip,ap,port+type"
        self.station_results = self.localrealm.find_ports_like("sta*",
                                                               fields,
                                                               debug_=False)
        if (self.station_results is None) or (len(self.station_results) < 1):
            self.get_failed_result_list()
        for eid, record in self.station_results.items():
            #print("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ")
            #pprint(eid)
            #pprint(record)
            if record["ap"] == bssid:
                counter += 1
            #print("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ")
        return counter

    def clear_test_results(self):
        self.resulting_stations = {}
        self.resulting_endpoints = {}
        super().clear_test_results()
        #super(StaConnect, self).clear_test_results().test_results.clear()

    def setup(self):
        self.clear_test_results()
        self.check_connect()
        upstream_json = self.json_get("%s?fields=alias,phantom,down,port,ip" %
                                      self.get_upstream_url(),
                                      debug_=False)

        if upstream_json is None:
            self._fail(message="Unable to query %s, bye" % self.upstream_port,
                       print_=True)
            return False

        if upstream_json['interface']['ip'] == "0.0.0.0":
            if self.debug:
                pprint.pprint(upstream_json)
            self._fail("Warning: %s lacks ip address" %
                       self.get_upstream_url(),
                       print_=True)
            return False

        # remove old stations
        print("Removing old stations")
        for sta_name in self.station_names:
            sta_url = self.get_station_url(sta_name)
            response = self.json_get(sta_url)
            if (response is not None) and (response["interface"] is not None):
                for sta_name in self.station_names:
                    LFUtils.removePort(self.resource, sta_name,
                                       self.lfclient_url)
        LFUtils.wait_until_ports_disappear(self.lfclient_url,
                                           self.station_names)

        # Create stations and turn dhcp on
        self.station_profile = self.localrealm.new_station_profile()

        if self.dut_security == WPA2:
            self.station_profile.use_security(security_type="wpa2",
                                              ssid=self.dut_ssid,
                                              passwd=self.dut_passwd)
        elif self.dut_security == WPA:
            self.station_profile.use_security(security_type="wpa",
                                              ssid=self.dut_ssid,
                                              passwd=self.dut_passwd)
        elif self.dut_security == OPEN:
            self.station_profile.use_security(security_type="open",
                                              ssid=self.dut_ssid,
                                              passwd="[BLANK]")
        elif self.dut_security == WPA:
            self.station_profile.use_security(security_type="wpa",
                                              ssid=self.dut_ssid,
                                              passwd=self.dut_passwd)
        elif self.dut_security == WEP:
            self.station_profile.use_security(security_type="wep",
                                              ssid=self.dut_ssid,
                                              passwd=self.dut_passwd)
        self.station_profile.set_command_flag("add_sta", "create_admin_down",
                                              1)

        print("Adding new stations ", end="")
        self.station_profile.create(radio=self.radio,
                                    sta_names_=self.station_names,
                                    up_=False,
                                    debug=self.debug,
                                    suppress_related_commands_=True)
        LFUtils.wait_until_ports_appear(self.lfclient_url,
                                        self.station_names,
                                        debug=self.debug)

    def start(self):
        if self.station_profile is None:
            self._fail("Incorrect setup")
        pprint.pprint(self.station_profile)
        if self.station_profile.up is None:
            self._fail("Incorrect station profile, missing profile.up")
        if self.station_profile.up == False:
            print("\nBringing ports up...")
            data = {
                "shelf": 1,
                "resource": self.resource,
                "port": "ALL",
                "probe_flags": 1
            }
            self.json_post("/cli-json/nc_show_ports", data)
            self.station_profile.admin_up()
            LFUtils.waitUntilPortsAdminUp(self.resource, self.lfclient_url,
                                          self.station_names)

        # station_info = self.jsonGet(self.mgr_url, "%s?fields=port,ip,ap" % (self.getStaUrl()))
        duration = 0
        maxTime = 100
        ip = "0.0.0.0"
        ap = ""
        print("Waiting for %s stations to associate to AP: " %
              len(self.station_names),
              end="")
        connected_stations = {}
        while (len(connected_stations.keys()) < len(
                self.station_names)) and (duration < maxTime):
            duration += 3
            time.sleep(10)
            print(".", end="")
            for sta_name in self.station_names:
                sta_url = self.get_station_url(sta_name)
                station_info = self.json_get(sta_url + "?fields=port,ip,ap")

                # LFUtils.debug_printer.pprint(station_info)
                if (station_info is not None) and ("interface"
                                                   in station_info):
                    if "ip" in station_info["interface"]:
                        ip = station_info["interface"]["ip"]
                    if "ap" in station_info["interface"]:
                        ap = station_info["interface"]["ap"]

                if (ap == "Not-Associated") or (ap == ""):
                    if self.debug:
                        print(" -%s," % sta_name, end="")
                else:
                    if ip == "0.0.0.0":
                        if self.debug:
                            print(" %s (0.0.0.0)" % sta_name, end="")
                    else:
                        connected_stations[sta_name] = sta_url
            data = {
                "shelf": 1,
                "resource": self.resource,
                "port": "ALL",
                "probe_flags": 1
            }
            self.json_post("/cli-json/nc_show_ports", data)

        for sta_name in self.station_names:
            sta_url = self.get_station_url(sta_name)
            station_info = self.json_get(sta_url)  # + "?fields=port,ip,ap")
            if station_info is None:
                print("unable to query %s" % sta_url)
            self.resulting_stations[sta_url] = station_info
            ap = station_info["interface"]["ap"]
            ip = station_info["interface"]["ip"]
            if (ap != "") and (ap != "Not-Associated"):
                print(" %s +AP %s, " % (sta_name, ap), end="")
                if self.dut_bssid != "":
                    if self.dut_bssid.lower() == ap.lower():
                        self._pass(sta_name + " connected to BSSID: " + ap)
                        # self.test_results.append("PASSED: )
                        # print("PASSED: Connected to BSSID: "+ap)
                    else:
                        self._fail(
                            "%s connected to wrong BSSID, requested: %s  Actual: %s"
                            % (sta_name, self.dut_bssid, ap))
            else:
                self._fail(sta_name + " did not connect to AP")
                return False

            if ip == "0.0.0.0":
                self._fail("%s did not get an ip. Ending test" % sta_name)
            else:
                self._pass("%s connected to AP: %s  With IP: %s" %
                           (sta_name, ap, ip))

        if self.passes() == False:
            if self.cleanup_on_exit:
                print("Cleaning up...")
                self.remove_stations()
            return False

    def udp_profile(self, side_a_min_bps, side_b_min_bps, side_a_min_pdu,
                    side_b_min_pdu):
        # Create UDP endpoint - Alex's code!
        self.l3_udp_tput_profile = self.localrealm.new_l3_cx_profile()
        self.l3_udp_tput_profile.side_a_min_bps = side_a_min_bps
        self.l3_udp_tput_profile.side_b_min_bps = side_b_min_bps
        self.l3_udp_tput_profile.side_a_min_pdu = side_a_min_pdu
        self.l3_udp_tput_profile.side_b_min_pdu = side_b_min_pdu
        self.l3_udp_tput_profile.report_timer = 1000
        self.l3_udp_tput_profile.name_prefix = "udp"
        self.l3_udp_tput_profile.create(
            endp_type="lf_udp",
            side_a=list(self.localrealm.find_ports_like("tput+")),
            side_b="%d.%s" % (self.resource, self.upstream_port),
            suppress_related_commands=True)

    def tcp_profile(self, side_a_min_bps, side_b_min_bps):
        # Create TCP endpoints - original code!
        self.l3_tcp_tput_profile = self.localrealm.new_l3_cx_profile()
        self.l3_tcp_tput_profile.side_a_min_bps = side_a_min_bps
        self.l3_tcp_tput_profile.side_b_min_bps = side_b_min_bps
        self.l3_tcp_tput_profile.name_prefix = "tcp"
        self.l3_tcp_tput_profile.report_timer = 1000
        self.l3_tcp_tput_profile.create(
            endp_type="lf_tcp",
            side_a=list(self.localrealm.find_ports_like("tput+")),
            side_b="%d.%s" % (self.resource, self.upstream_port),
            suppress_related_commands=True)

    # Start UDP Downstream Traffic
    def udp_throughput(self):
        print("\nStarting UDP Traffic")
        self.l3_udp_tput_profile.start_cx()
        time.sleep(1)
        self.l3_udp_tput_profile.refresh_cx()

    def tcp_throughput(self):
        print("\nStarting TCP Traffic")
        self.l3_tcp_tput_profile.start_cx()
        time.sleep(1)
        self.l3_tcp_tput_profile.refresh_cx()

    def udp_stop(self):
        # stop cx traffic
        print("Stopping CX Traffic")
        self.l3_udp_tput_profile.stop_cx()

        # Refresh stats
        print("\nRefresh CX stats")
        self.l3_udp_tput_profile.refresh_cx()

        print("Sleeping for 5 seconds")
        time.sleep(5)

        # get data for endpoints JSON
        return self.collect_client_stats(self.l3_udp_tput_profile.created_cx)
        # print("\n")

    def tcp_stop(self):
        # stop cx traffic
        print("Stopping CX Traffic")
        self.l3_tcp_tput_profile.stop_cx()

        # Refresh stats
        print("\nRefresh CX stats")
        self.l3_tcp_tput_profile.refresh_cx()

        print("Sleeping for 5 seconds")
        time.sleep(5)

        # get data for endpoints JSON
        return self.collect_client_stats(self.l3_tcp_tput_profile.created_cx)
        # print("\n")

    # New Endpoint code to print TX and RX numbers
    def collect_client_stats(self, endp_map):
        print("Collecting Data")
        fields = "?fields=name,tx+bytes,rx+bytes"
        for (cx_name, endps) in endp_map.items():
            try:
                endp_url = "/endp/%s%s" % (endps[0], fields)
                endp_json = self.json_get(endp_url)
                self.resulting_endpoints[endp_url] = endp_json
                ptest_a_tx = endp_json['endpoint']['tx bytes']
                ptest_a_rx = endp_json['endpoint']['rx bytes']

                # ptest = self.json_get("/endp/%s?fields=tx+bytes,rx+bytes" % cx_names[cx_name]["b"])
                endp_url = "/endp/%s%s" % (endps[1], fields)
                endp_json = self.json_get(endp_url)
                self.resulting_endpoints[endp_url] = endp_json
                ptest_b_tx = endp_json['endpoint']['tx bytes']
                ptest_b_rx = endp_json['endpoint']['rx bytes']

                byte_values = []
                byte_values.append("Station TX: " + str(ptest_a_tx))
                byte_values.append("Station RX: " + str(ptest_a_rx))
                byte_values.append("AP TX: " + str(ptest_b_tx))
                byte_values.append("AP RX: " + str(ptest_b_rx))

                return byte_values

            except Exception as e:
                self.error(e)

    def cleanup_udp(self):
        # remove all endpoints and cxs
        if self.cleanup_on_exit:
            for sta_name in self.station_names:
                LFUtils.removePort(self.resource, sta_name, self.lfclient_url)
            curr_endp_names = []
            removeCX(self.lfclient_url,
                     self.l3_udp_tput_profile.get_cx_names())
            for (cx_name,
                 endp_names) in self.l3_udp_tput_profile.created_cx.items():
                curr_endp_names.append(endp_names[0])
                curr_endp_names.append(endp_names[1])
            removeEndps(self.lfclient_url, curr_endp_names, debug=self.debug)

    def cleanup_tcp(self):
        # remove all endpoints and cxs
        if self.cleanup_on_exit:
            for sta_name in self.station_names:
                LFUtils.removePort(self.resource, sta_name, self.lfclient_url)
            curr_endp_names = []
            removeCX(self.lfclient_url,
                     self.l3_tcp_tput_profile.get_cx_names())
            for (cx_name,
                 endp_names) in self.l3_tcp_tput_profile.created_cx.items():
                curr_endp_names.append(endp_names[0])
                curr_endp_names.append(endp_names[1])
            removeEndps(self.lfclient_url, curr_endp_names, debug=self.debug)

    def cleanup(self):
        # remove all endpoints and cxs
        if self.cleanup_on_exit:
            for sta_name in self.station_names:
                LFUtils.removePort(self.resource, sta_name, self.lfclient_url)
            curr_endp_names = []
            removeCX(self.lfclient_url,
                     self.l3_tcp_tput_profile.get_cx_names())
            removeCX(self.lfclient_url,
                     self.l3_udp_tput_profile.get_cx_names())
            for (cx_name,
                 endp_names) in self.l3_tcp_tput_profile.created_cx.items():
                curr_endp_names.append(endp_names[0])
                curr_endp_names.append(endp_names[1])
            for (cx_name,
                 endp_names) in self.l3_udp_tput_profile.created_cx.items():
                curr_endp_names.append(endp_names[0])
                curr_endp_names.append(endp_names[1])
            removeEndps(self.lfclient_url, curr_endp_names, debug=self.debug)

    def udp_unidirectional(self, side_a_min_bps, side_b_min_bps,
                           side_a_min_pdu, side_b_min_pdu, direction,
                           values_line):
        self.udp_profile(side_a_min_bps, side_b_min_bps, side_a_min_pdu,
                         side_b_min_pdu)
        self.start()
        print("Running", direction,
              "Traffic for %s seconds" % self.runtime_secs)
        self.udp_throughput()
        print("napping %f sec" % self.runtime_secs)
        time.sleep(self.runtime_secs)
        values = self.udp_stop()
        print(values)
        # Get value required for measurement
        bytes = values[values_line]
        # Get value in Bits and convert to Mbps
        bits = (int(bytes.split(": ", 1)[1])) * 8
        mpbs = round((bits / 1000000) / self.runtime_secs, 2)
        return mpbs

    def tcp_unidirectional(self, side_a_min_bps, side_b_min_bps, direction,
                           values_line):
        self.tcp_profile(side_a_min_bps, side_b_min_bps)
        self.start()
        print("Running", direction,
              "Traffic for %s seconds" % self.runtime_secs)
        self.tcp_throughput()
        print("napping %f sec" % self.runtime_secs)
        time.sleep(self.runtime_secs)
        values = self.tcp_stop()
        print(values)
        # Get value required for measurement
        bytes = values[values_line]
        # Get value in Bits and convert to Mbps
        bits = (int(bytes.split(": ", 1)[1])) * 8
        mpbs = round((bits / 1000000) / self.runtime_secs, 2)
        return mpbs

    def throughput_csv(csv_file, ssid_name, ap_model, firmware, security,
                       udp_ds, udp_us, tcp_ds, tcp_us):
        # Find band for CSV ---> This code is not great, it SHOULD get that info from LANForge!
        if "5G" in ssid_name:
            frequency = "5 GHz"

        elif "2dot4G" in ssid_name:
            frequency = "2.4 GHz"

        else:
            frequency = "Unknown"

        # Append row to top of CSV file
        row = [
            ap_model, firmware, frequency, security, udp_ds, udp_us, tcp_ds,
            tcp_us
        ]

        with open(csv_file, 'r') as readFile:
            reader = csv.reader(readFile)
            lines = list(reader)
            lines.insert(1, row)

        with open(csv_file, 'w') as writeFile:
            writer = csv.writer(writeFile)
            writer.writerows(lines)

        readFile.close()
        writeFile.close()
def main():
    parser = Realm.create_basic_argparse(
        prog='test_ipv4_variable_time.py',
        formatter_class=argparse.RawTextHelpFormatter,
        epilog='''\
            Create stations to test connection and traffic on VAPs of varying security types (WEP, WPA, WPA2, WPA3, Open)
            ''',
        description='''\
test_ipv4_variable_time.py:
--------------------
Generic command layout:

python3 ./test_ipv4_variable_time.py
    --upstream_port eth1
    --radio wiphy0
    --num_stations 32
    --security {open|wep|wpa|wpa2|wpa3}
    --mode   1
        {"auto"   : "0",
        "a"      : "1",
        "b"      : "2",
        "g"      : "3",
        "abg"    : "4",
        "abgn"   : "5",
        "bgn"    : "6",
        "bg"     : "7",
        "abgnAC" : "8",
        "anAC"   : "9",
        "an"     : "10",
        "bgnAC"  : "11",
        "abgnAX" : "12",
        "bgnAX"  : "13"}
    --ssid netgear
    --password admin123
    --test_duration 2m (default)
    --monitor_interval_ms 
    --a_min 3000
    --b_min 1000
    --ap "00:0e:8e:78:e1:76"
    --output_format csv
    --traffic_type lf_udp
    --report_file ~/Documents/results.csv                       (Example of csv file output  - please use another extension for other file formats)
    --compared_report ~/Documents/results_prev.csv              (Example of csv file retrieval - please use another extension for other file formats) - UNDER CONSTRUCTION
    --layer3_cols 'name','tx bytes','rx bytes','dropped'          (column names from the GUI to print on report -  please read below to know what to put here according to preferences)
    --port_mgr_cols 'ap','ip'                                    (column names from the GUI to print on report -  please read below to know what to put here according to preferences)
    --debug
    
    python3 ./test_ipv4_variable_time.py
    --upstream_port eth1        (upstream POrt)
    --traffic_type lf_udp       (traffic type, lf_udp | lf_tcp)
    --test_duration 5m          (duration to run traffic 5m --> 5 Minutes)
    --create_sta False          (False, means it will not create stations and use the sta_names specified below)
    --sta_names sta000,sta001,sta002 (used if --create_sta False, comma separated names of stations)
        
    
===============================================================================
 ** FURTHER INFORMATION **
    Using the layer3_cols flag:

    Currently the output function does not support inputting the columns in layer3_cols the way they are displayed in the GUI. This quirk is under construction. To output
    certain columns in the GUI in your final report, please match the according GUI column display to it's counterpart to have the columns correctly displayed in
    your report.

    GUI Column Display       Layer3_cols argument to type in (to print in report)

    Name                |  'name'
    EID                 |  'eid'
    Run                 |  'run'
    Mng                 |  'mng'
    Script              |  'script'
    Tx Rate             |  'tx rate'
    Tx Rate (1 min)     |  'tx rate (1&nbsp;min)'
    Tx Rate (last)      |  'tx rate (last)'
    Tx Rate LL          |  'tx rate ll'
    Rx Rate             |  'rx rate'
    Rx Rate (1 min)     |  'rx rate (1&nbsp;min)'
    Rx Rate (last)      |  'rx rate (last)'
    Rx Rate LL          |  'rx rate ll'
    Rx Drop %           |  'rx drop %'
    Tx PDUs             |  'tx pdus'
    Tx Pkts LL          |  'tx pkts ll'
    PDU/s TX            |  'pdu/s tx'
    Pps TX LL           |  'pps tx ll'
    Rx PDUs             |  'rx pdus'
    Rx Pkts LL          |  'pps rx ll'
    PDU/s RX            |  'pdu/s tx'
    Pps RX LL           |  'pps rx ll'
    Delay               |  'delay'
    Dropped             |  'dropped'
    Jitter              |  'jitter'
    Tx Bytes            |  'tx bytes'
    Rx Bytes            |  'rx bytes'
    Replays             |  'replays'
    TCP Rtx             |  'tcp rtx'
    Dup Pkts            |  'dup pkts'
    Rx Dup %            |  'rx dup %'
    OOO Pkts            |  'ooo pkts'
    Rx OOO %            |  'rx ooo %'
    RX Wrong Dev        |  'rx wrong dev'
    CRC Fail            |  'crc fail'
    RX BER              |  'rx ber'
    CX Active           |  'cx active'
    CX Estab/s          |  'cx estab/s'
    1st RX              |  '1st rx'
    CX TO               |  'cx to'
    Pattern             |  'pattern'
    Min PDU             |  'min pdu'
    Max PDU             |  'max pdu'
    Min Rate            |  'min rate'
    Max Rate            |  'max rate'
    Send Buf            |  'send buf'
    Rcv Buf             |  'rcv buf'
    CWND                |  'cwnd'
    TCP MSS             |  'tcp mss'
    Bursty              |  'bursty'
    A/B                 |  'a/b'
    Elapsed             |  'elapsed'
    Destination Addr    |  'destination addr'
    Source Addr         |  'source addr'
            ''')

    parser.add_argument('--mode', help='Used to force mode of stations')
    parser.add_argument('--ap',
                        help='Used to force a connection to a particular AP')
    parser.add_argument('--traffic_type',
                        help='Select the Traffic Type [lf_udp, lf_tcp]',
                        required=True)
    parser.add_argument('--output_format', help='choose either csv or xlsx')
    parser.add_argument('--report_file',
                        help='where you want to store results',
                        default=None)
    parser.add_argument('--a_min',
                        help='--a_min bps rate minimum for side_a',
                        default=256000)
    parser.add_argument('--b_min',
                        help='--b_min bps rate minimum for side_b',
                        default=256000)
    parser.add_argument('--test_duration',
                        help='--test_duration sets the duration of the test',
                        default="2m")
    parser.add_argument(
        '--layer3_cols',
        help='Columns wished to be monitored from layer 3 endpoint tab',
        default=['name', 'tx bytes', 'rx bytes', 'tx rate', 'rx rate'])
    parser.add_argument(
        '--port_mgr_cols',
        help='Columns wished to be monitored from port manager tab',
        default=['ap', 'ip', 'parent dev'])
    parser.add_argument(
        '--compared_report',
        help=
        'report path and file which is wished to be compared with new report',
        default=None)
    parser.add_argument(
        '--monitor_interval',
        help=
        'how frequently do you want your monitor function to take measurements; \, 35s, 2h',
        default='10s')
    parser.add_argument('--influx_token',
                        help='Username for your Influx database')
    parser.add_argument('--influx_bucket',
                        help='Password for your Influx database')
    parser.add_argument('--influx_org', help='Name of your Influx database')
    parser.add_argument('--influx_port',
                        help='Port where your influx database is located',
                        default=8086)
    parser.add_argument(
        '--influx_tag',
        action='append',
        nargs=2,
        help='--influx_tag <key> <val>   Can add more than one of these.')
    parser.add_argument(
        '--influx_mgr',
        help=
        'IP address of the server your Influx database is hosted if different from your LANforge Manager',
        default=None)
    parser.add_argument('--create_sta',
                        help='Used to force a connection to a particular AP',
                        default=True)
    parser.add_argument('--sta_names',
                        help='Used to force a connection to a particular AP',
                        default="sta0000")
    args = parser.parse_args()
    create_sta = True
    if args.create_sta == "False":
        create_sta = False

    num_sta = 2
    if (args.num_stations is not None) and (int(args.num_stations) > 0):
        num_sta = int(args.num_stations)

    # Create directory

    # if file path with output file extension is not given...
    # check if home/lanforge/report-data exists. if not, save
    # in new folder based in current file's directory

    if args.report_file is None:
        new_file_path = str(datetime.datetime.now().strftime(
            "%Y-%m-%d-%H-h-%M-m-%S-s")).replace(
                ':', '-') + '_test_ipv4_variable_time'  # create path name
        try:
            path = os.path.join('/home/lanforge/report-data/', new_file_path)
            os.mkdir(path)
        except:
            curr_dir_path = os.path.dirname(
                os.path.dirname(os.path.abspath(__file__)))
            path = os.path.join(curr_dir_path, new_file_path)
            os.mkdir(path)
        systeminfopath = str(path) + '/systeminfo.txt'

        if args.output_format in [
                'csv', 'json', 'html', 'hdf', 'stata', 'pickle', 'pdf', 'png',
                'parquet', 'xlsx'
        ]:
            report_f = str(path) + '/data.' + args.output_format
            output = args.output_format
        else:
            print(
                'Not supporting this report format or cannot find report format provided. Defaulting to csv data file output type, naming it data.csv.'
            )
            report_f = str(path) + '/data.csv'
            output = 'csv'

    else:
        systeminfopath = str(args.report_file).split('/')[-1]
        report_f = args.report_file
        if args.output_format is None:
            output = str(args.report_file).split('.')[-1]
        else:
            output = args.output_format
    print("IPv4 Test Report Data: {}".format(report_f))

    # Retrieve last data file
    compared_rept = None
    if args.compared_report:
        compared_report_format = args.compared_report.split('.')[-1]
        # if compared_report_format not in ['csv', 'json', 'dta', 'pkl','html','xlsx','parquet','h5']:
        if compared_report_format != 'csv':
            print(
                ValueError(
                    "Cannot process this file type. Please select a different file and re-run script."
                ))
            exit(1)
        else:
            compared_rept = args.compared_report

    if create_sta:
        station_list = LFUtils.portNameSeries(prefix_="sta",
                                              start_id_=0,
                                              end_id_=num_sta - 1,
                                              padding_number_=10000,
                                              radio=args.radio)
    else:
        station_list = args.sta_names.split(",")
    ip_var_test = IPV4VariableTime(host=args.mgr,
                                   port=args.mgr_port,
                                   number_template="0000",
                                   sta_list=station_list,
                                   create_sta=create_sta,
                                   name_prefix="VT",
                                   upstream=args.upstream_port,
                                   ssid=args.ssid,
                                   password=args.passwd,
                                   radio=args.radio,
                                   security=args.security,
                                   test_duration=args.test_duration,
                                   use_ht160=False,
                                   side_a_min_rate=args.a_min,
                                   side_b_min_rate=args.b_min,
                                   mode=args.mode,
                                   ap=args.ap,
                                   traffic_type=args.traffic_type,
                                   _debug_on=args.debug)

    ip_var_test.pre_cleanup()

    ip_var_test.build()
    # exit()
    if create_sta:
        if not ip_var_test.passes():
            print(ip_var_test.get_fail_message())
            ip_var_test.exit_fail()

    try:
        layer3connections = ','.join(
            [[*x.keys()][0] for x in ip_var_test.json_get('endp')['endpoint']])
    except:
        raise ValueError(
            'Try setting the upstream port flag if your device does not have an eth1 port'
        )

    if type(args.layer3_cols) is not list:
        layer3_cols = list(args.layer3_cols.split(","))
        # send col names here to file to reformat
    else:
        layer3_cols = args.layer3_cols
        # send col names here to file to reformat
    if type(args.port_mgr_cols) is not list:
        port_mgr_cols = list(args.port_mgr_cols.split(","))
        # send col names here to file to reformat
    else:
        port_mgr_cols = args.port_mgr_cols
        # send col names here to file to reformat
    if args.debug:
        print("Layer 3 Endp column names are...")
        print(layer3_cols)
        print("Port Manager column names are...")
        print(port_mgr_cols)

    print("Layer 3 Endp column names are...")
    print(layer3_cols)
    print("Port Manager column names are...")
    print(port_mgr_cols)

    try:
        monitor_interval = Realm.parse_time(
            args.monitor_interval).total_seconds()
    except ValueError as error:
        print(str(error))
        print(
            ValueError(
                "The time string provided for monitor_interval argument is invalid. Please see supported time stamp increments and inputs for monitor_interval in --help. "
            ))
        exit(1)
    ip_var_test.start(False, False)

    # if args.influx_mgr is None:
    #    manager = args.mgr
    # else:
    #    manager = args.influx_mgr

    if args.influx_org is not None:
        from InfluxRequest import RecordInflux
        grapher = RecordInflux(  # _influx_host=manager,
            _influx_port=args.influx_port,
            _influx_org=args.influx_org,
            _influx_token=args.influx_token,
            _influx_bucket=args.influx_bucket)
        devices = [station.split('.')[-1] for station in station_list]
        tags = dict()
        tags['script'] = 'test_ipv4_variable_time'
        try:
            for k in args.influx_tag:
                tags[k[0]] = k[1]
        except:
            pass
        grapher.monitor_port_data(longevity=Realm.parse_time(
            args.test_duration).total_seconds(),
                                  devices=devices,
                                  monitor_interval=Realm.parse_time(
                                      args.monitor_interval).total_seconds(),
                                  tags=tags)

    ip_var_test.cx_profile.monitor(
        layer3_cols=layer3_cols,
        sta_list=station_list,
        # port_mgr_cols=port_mgr_cols,
        report_file=report_f,
        systeminfopath=systeminfopath,
        duration_sec=Realm.parse_time(args.test_duration).total_seconds(),
        monitor_interval_ms=monitor_interval,
        created_cx=layer3connections,
        output_format=output,
        compared_report=compared_rept,
        script_name='test_ipv4_variable_time',
        arguments=args,
        debug=args.debug)

    ip_var_test.stop()
    if create_sta:
        if not ip_var_test.passes():
            print(ip_var_test.get_fail_message())
            ip_var_test.exit_fail()
        LFUtils.wait_until_ports_admin_up(port_list=station_list)

        if ip_var_test.passes():
            ip_var_test.success()
    ip_var_test.cleanup()
    print("IPv4 Variable Time Test Report Data: {}".format(report_f))
Beispiel #17
0
class RunCvScenario(LFCliBase):
    def __init__(self,
                 lfhost="localhost",
                 lfport=8080,
                 debug_=False,
                 lanforge_db_=None,
                 cv_scenario_=None,
                 cv_test_=None,
                 test_scenario_=None):
        super().__init__(_lfjson_host=lfhost,
                         _lfjson_port=lfport,
                         _debug=debug_,
                         _halt_on_error=True,
                         _exit_on_error=True,
                         _exit_on_fail=True)
        self.lanforge_db = lanforge_db_
        self.cv_scenario = cv_scenario_
        self.cv_test = cv_test_
        self.test_profile = test_scenario_
        self.localrealm = Realm(lfclient_host=lfhost,
                                lfclient_port=lfport,
                                debug_=debug_)
        self.report_name = None

    def get_report_file_name(self):
        return self.report_name

    def build(self):
        data = {
            "name": "BLANK",
            "action": "overwrite",
            "clean_dut": "yes",
            "clean_chambers": "yes"
        }
        self.json_post("/cli-json/load", data)
        sleep(1)
        port_counter = 0
        attempts = 6
        while (attempts > 0) and (port_counter > 0):
            sleep(1)
            attempts -= 1
            print("looking for ports like vap+")
            port_list = self.localrealm.find_ports_like("vap+")
            alias_map = LFUtils.portListToAliasMap(port_list)
            port_counter = len(alias_map)

            port_list = self.localrealm.find_ports_like("sta+")
            alias_map = LFUtils.portListToAliasMap(port_list)
            port_counter += len(alias_map)
            if port_counter == 0:
                break

        if (port_counter != 0) and (attempts == 0):
            print("There appears to be a vAP in this database, quitting.")
            pprint(alias_map)
            exit(1)

        data = {
            "name": self.lanforge_db,
            "action": "overwrite",
            "clean_dut": "yes",
            "clean_chambers": "yes"
        }
        self.json_post("/cli-json/load", data)
        sleep(1)
        self._pass("Loaded scenario %s" % self.lanforge_db, True)
        return True

    def start(self, debug_=False):
        # /gui_cli takes commands keyed on 'cmd', so we create an array of commands
        commands = [
            "cv apply '%s'" % self.cv_scenario,
            "cv build",
            "sleep 4",
            "cv is_built",
            "cv sync",
            "sleep 2",
            "cv create '%s' test_ref" % self.cv_test,
            "sleep 2",
            "cv load test_ref '%s'" % self.test_profile,
            "sleep 1",
            "cv click test_ref 'Auto Save Report'",
            "sleep 5",
            "cv click test_ref Start",
            "sleep 60",
            "cv get test_ref 'Report Location:'",
            "sleep 5",
            #"cv click test_ref 'Save HTML'",
            "cv click test_ref 'Close'",
            "sleep 1",
            "cv click test_ref Cancel",
            "sleep 1",
            "exit"
        ]
        response_json = []
        for command in commands:
            data = {"cmd": command}
            try:
                debug_par = ""
                if debug_:
                    debug_par = "?_debug=1"
                if command.endswith("is_built"):
                    print("Waiting for scenario to build...", end='')
                    self.localrealm.wait_while_building(debug_=False)
                    print("...proceeding")
                elif command.startswith("sleep "):
                    nap = int(command.split(" ")[1])
                    print("sleeping %d..." % nap)
                    sleep(nap)
                    print("...proceeding")
                else:
                    response_json = []
                    print("running %s..." % command, end='')
                    response = self.json_post(
                        "/gui-json/cmd%s" % debug_par,
                        data,
                        debug_=False,
                        response_json_list_=response_json)
                    if debug_:
                        LFUtils.debug_printer.pprint(response_json)
                    print("...proceeding")

            except Exception as x:
                print(x)

        self._pass("report finished", print_=True)

    def stop(self):
        pass

    def cleanup(self):
        pass
Beispiel #18
0
class StaConnect(LFCliBase):
    def __init__(self,
                 host,
                 port,
                 _dut_ssid="MyAP",
                 _dut_passwd="NA",
                 _dut_bssid="",
                 _user="",
                 _passwd="",
                 _sta_mode="0",
                 _radio="wiphy0",
                 _resource=1,
                 _upstream_resource=1,
                 _upstream_port="eth2",
                 _sta_name=None,
                 _debugOn=False,
                 _dut_security=OPEN,
                 _exit_on_error=False,
                 _cleanup_on_exit=True,
                 _runtime_sec=60,
                 _exit_on_fail=False):
        # do not use `super(LFCLiBase,self).__init__(self, host, port, _debugOn)
        # that is py2 era syntax and will force self into the host variable, making you
        # very confused.
        super().__init__(host,
                         port,
                         _debug=_debugOn,
                         _halt_on_error=_exit_on_error,
                         _exit_on_fail=_exit_on_fail)
        self.debugOn = _debugOn
        self.dut_security = ""
        self.dut_ssid = _dut_ssid
        self.dut_passwd = _dut_passwd
        self.dut_bssid = _dut_bssid
        self.user = _user
        self.passwd = _passwd
        self.sta_mode = _sta_mode  # See add_sta LANforge CLI users guide entry
        self.radio = _radio
        self.resource = _resource
        self.upstream_resource = _upstream_resource
        self.upstream_port = _upstream_port
        self.runtime_secs = _runtime_sec
        self.cleanup_on_exit = _cleanup_on_exit
        self.sta_url_map = None  # defer construction
        self.upstream_url = None  # defer construction
        self.station_names = []
        self.cx_names = {}
        if _sta_name is not None:
            self.station_names = [_sta_name]
        # self.localrealm :Realm = Realm(lfclient_host=host, lfclient_port=port) # py > 3.6
        self.localrealm = Realm(lfclient_host=host,
                                lfclient_port=port)  # py > 3.6
        self.resulting_stations = {}
        self.resulting_endpoints = {}

    # def get_realm(self) -> Realm: # py > 3.6
    def get_realm(self):
        return self.localrealm

    def get_station_url(self, sta_name_=None):
        if sta_name_ is None:
            raise ValueError("get_station_url wants a station name")
        if self.sta_url_map is None:
            self.sta_url_map = {}
            for sta_name in self.station_names:
                self.sta_url_map[sta_name] = "port/1/%s/%s" % (self.resource,
                                                               sta_name)
        return self.sta_url_map[sta_name_]

    def get_upstream_url(self):
        if self.upstream_url is None:
            self.upstream_url = "port/1/%s/%s" % (self.upstream_resource,
                                                  self.upstream_port)
        return self.upstream_url

    # Compare pre-test values to post-test values
    def compare_vals(self, name, postVal, print_pass=False, print_fail=True):
        # print(f"Comparing {name}")
        if postVal > 0:
            self._pass("%s %s" % (name, postVal), print_pass)
        else:
            self._fail("%s did not report traffic: %s" % (name, postVal),
                       print_fail)

    def remove_stations(self):
        for name in self.station_names:
            LFUtils.removePort(self.resource, name, self.lfclient_url)

    def num_associated(self, bssid):
        counter = 0
        # print("there are %d results" % len(self.station_results))
        fields = "_links,port,alias,ip,ap,port+type"
        self.station_results = self.localrealm.find_ports_like("sta*",
                                                               fields,
                                                               debug_=False)
        if (self.station_results is None) or (len(self.station_results) < 1):
            self.get_failed_result_list()
        for eid, record in self.station_results.items():
            #print("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ")
            #pprint(eid)
            #pprint(record)
            if record["ap"] == bssid:
                counter += 1
            #print("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ")
        return counter

    def clear_test_results(self):
        self.resulting_stations = {}
        self.resulting_endpoints = {}
        super().clear_test_results()
        #super(StaConnect, self).clear_test_results().test_results.clear()

    def run(self):
        if not self.setup():
            return False
        if not self.start():
            return False
        time.sleep(self.runtime_secs)
        if not self.stop():
            return False
        if not self.finish():
            return False

        # remove all endpoints and cxs
        if self.cleanup_on_exit:
            if not self.cleanup():
                return False
        return True

    def setup(self):
        self.clear_test_results()
        self.check_connect()
        eth1IP = self.json_get(self.get_upstream_url())
        if eth1IP is None:
            self._fail("Unable to query %s, bye" % self.upstream_port, True)
            return False
        if eth1IP['interface']['ip'] == "0.0.0.0":
            self._fail("Warning: %s lacks ip address" %
                       self.get_upstream_url())
            return False

        for sta_name in self.station_names:
            sta_url = self.get_station_url(sta_name)
            response = self.json_get(sta_url)
            if response is not None:
                if response["interface"] is not None:
                    print("removing old station")
                    for sta_name in self.station_names:
                        LFUtils.removePort(self.resource, sta_name,
                                           self.lfclient_url)
                    LFUtils.waitUntilPortsDisappear(self.resource,
                                                    self.lfclient_url,
                                                    self.station_names)

        # Create stations and turn dhcp on

        flags = 0x10000
        if self.dut_security == WPA2:
            flags += 0x400
        elif self.dut_security == OPEN:
            pass

        add_sta_data = {
            "shelf": 1,
            "resource": self.resource,
            "radio": self.radio,
            "ssid": self.dut_ssid,
            "key": self.dut_passwd,
            "mode": self.sta_mode,
            "mac": "xx:xx:xx:xx:*:xx",
            "flags": flags  # verbose, wpa2
        }
        print("Adding new stations ", end="")
        for sta_name in self.station_names:
            add_sta_data["sta_name"] = sta_name
            print(" %s," % sta_name, end="")
            self.json_post("/cli-json/add_sta",
                           add_sta_data,
                           suppress_related_commands_=True)
            time.sleep(0.01)

        set_port_data = {
            "shelf": 1,
            "resource": self.resource,
            "current_flags": 0x80000000,  # use DHCP, not down
            "interest": 0x4002  # set dhcp, current flags
        }
        print("\nConfiguring ")
        for sta_name in self.station_names:
            set_port_data["port"] = sta_name
            print(" %s," % sta_name, end="")
            self.json_post("/cli-json/set_port",
                           set_port_data,
                           suppress_related_commands_=True)
            time.sleep(0.01)
        print("\nBringing ports up...")
        data = {
            "shelf": 1,
            "resource": self.resource,
            "port": "ALL",
            "probe_flags": 1
        }
        self.json_post("/cli-json/nc_show_ports",
                       data,
                       suppress_related_commands_=True)
        LFUtils.waitUntilPortsAdminUp(self.resource, self.lfclient_url,
                                      self.station_names)

        # station_info = self.jsonGet(self.mgr_url, "%s?fields=port,ip,ap" % (self.getStaUrl()))
        duration = 0
        maxTime = 300
        ip = "0.0.0.0"
        ap = ""
        print("Waiting for %s stations to associate to AP: " %
              len(self.station_names),
              end="")
        connected_stations = {}
        while (len(connected_stations.keys()) < len(
                self.station_names)) and (duration < maxTime):
            duration += 3
            time.sleep(3)
            print(".", end="")
            for sta_name in self.station_names:
                sta_url = self.get_station_url(sta_name)
                station_info = self.json_get(sta_url + "?fields=port,ip,ap")

                # LFUtils.debug_printer.pprint(station_info)
                if (station_info is not None) and ("interface"
                                                   in station_info):
                    if "ip" in station_info["interface"]:
                        ip = station_info["interface"]["ip"]
                    if "ap" in station_info["interface"]:
                        ap = station_info["interface"]["ap"]

                if (ap == "Not-Associated") or (ap == ""):
                    if self.debugOn:
                        print(" -%s," % sta_name, end="")
                else:
                    if ip == "0.0.0.0":
                        if self.debugOn:
                            print(" %s (0.0.0.0)" % sta_name, end="")
                    else:
                        connected_stations[sta_name] = sta_url
            data = {
                "shelf": 1,
                "resource": self.resource,
                "port": "ALL",
                "probe_flags": 1
            }
            self.json_post("/cli-json/nc_show_ports",
                           data,
                           suppress_related_commands_=True)

        # make a copy of the connected stations for test records

        for sta_name in self.station_names:
            sta_url = self.get_station_url(sta_name)
            station_info = self.json_get(sta_url)  # + "?fields=port,ip,ap")
            self.resulting_stations[sta_url] = station_info
            ap = station_info["interface"]["ap"]
            ip = station_info["interface"]["ip"]
            if (ap != "") and (ap != "Not-Associated"):
                print(" %s +AP %s, " % (sta_name, ap), end="")
                if self.dut_bssid != "":
                    if self.dut_bssid.lower() == ap.lower():
                        self._pass(sta_name + " connected to BSSID: " + ap)
                        # self.test_results.append("PASSED: )
                        # print("PASSED: Connected to BSSID: "+ap)
                    else:
                        self._fail(
                            "%s connected to wrong BSSID, requested: %s  Actual: %s"
                            % (sta_name, self.dut_bssid, ap))
            else:
                self._fail(sta_name + " did not connect to AP")
                return False

            if ip == "0.0.0.0":
                self._fail("%s did not get an ip. Ending test" % sta_name)
            else:
                self._pass("%s connected to AP: %s  With IP: %s" %
                           (sta_name, ap, ip))

        if self.passes() == False:
            if self.cleanup_on_exit:
                print("Cleaning up...")
                self.remove_stations()
            return False

        # create endpoints and cxs
        # Create UDP endpoints
        self.cx_names = {}

        for sta_name in self.station_names:
            self.cx_names["testUDP-" + sta_name] = {
                "a": "testUDP-%s-A" % sta_name,
                "b": "testUDP-%s-B" % sta_name
            }
            data = {
                "alias": "testUDP-%s-A" % sta_name,
                "shelf": 1,
                "resource": self.resource,
                "port": sta_name,
                "type": "lf_udp",
                "ip_port": "-1",
                "min_rate": 1000000
            }
            self.json_post("/cli-json/add_endp",
                           data,
                           suppress_related_commands_=True)

            data = {
                "name": "testUDP-%s-A" % sta_name,
                "flag": "UseAutoNAT",
                "val": 1
            }
            self.json_post("/cli-json/set_endp_flag",
                           data,
                           suppress_related_commands_=True)

            data = {
                "alias": "testUDP-%s-B" % sta_name,
                "shelf": 1,
                "resource": self.upstream_resource,
                "port": self.upstream_port,
                "type": "lf_udp",
                "ip_port": "-1",
                "min_rate": 1000000
            }
            self.json_post("/cli-json/add_endp",
                           data,
                           suppress_related_commands_=True)

            data = {
                "name": "testUDP-%s-B" % sta_name,
                "flag": "UseAutoNAT",
                "val": 1
            }
            self.json_post("/cli-json/set_endp_flag",
                           data,
                           suppress_related_commands_=True)

            # Create CX
            data = {
                "alias": "testUDP-%s" % sta_name,
                "test_mgr": "default_tm",
                "tx_endp": "testUDP-%s-A" % sta_name,
                "rx_endp": "testUDP-%s-B" % sta_name,
            }
            self.json_post("/cli-json/add_cx",
                           data,
                           suppress_related_commands_=True)

            data = {
                "test_mgr": "default_tm",
                "cx_name": "testUDP-%s" % sta_name,
                "milliseconds": 1000
            }
            self.json_post("/cli-json/set_cx_report_timer",
                           data,
                           suppress_related_commands_=True)

            # Create TCP endpoints
            self.cx_names["testTCP-" + sta_name] = {
                "a": "testUDP-%s-A" % sta_name,
                "b": "testUDP-%s-B" % sta_name
            }
            data = {
                "alias": "testTCP-%s-A" % sta_name,
                "shelf": 1,
                "resource": self.resource,
                "port": sta_name,
                "type": "lf_tcp",
                "ip_port": "0",
                "min_rate": 1000000
            }
            self.json_post("/cli-json/add_endp",
                           data,
                           suppress_related_commands_=True)

            data = {
                "alias": "testTCP-%s-B" % sta_name,
                "shelf": 1,
                "resource": self.upstream_resource,
                "port": self.upstream_port,
                "type": "lf_tcp",
                "ip_port": "-1",
                "min_rate": 1000000
            }
            self.json_post("/cli-json/add_endp",
                           data,
                           suppress_related_commands_=True)

            # Create CX
            data = {
                "alias": "testTCP-%s" % sta_name,
                "test_mgr": "default_tm",
                "tx_endp": "testTCP-%s-A" % sta_name,
                "rx_endp": "testTCP-%s-B" % sta_name,
            }
            self.json_post("/cli-json/add_cx", data)

            data = {
                "test_mgr": "default_tm",
                "cx_name": "testTCP-%s" % sta_name,
                "milliseconds": 1000
            }
            self.json_post("/cli-json/set_cx_report_timer",
                           data,
                           suppress_related_commands_=True)

        return True

    def start(self):
        # start cx traffic
        print("\nStarting CX Traffic")
        for cx_name in self.cx_names.keys():
            data = {
                "test_mgr": "ALL",
                "cx_name": cx_name,
                "cx_state": "RUNNING"
            }
            self.json_post("/cli-json/set_cx_state", data)

        # Refresh stats

        print("Refresh CX stats")
        for cx_name in self.cx_names.keys():
            data = {"test_mgr": "ALL", "cross_connect": cx_name}
            self.json_post("/cli-json/show_cxe", data)
        return True

    def stop(self):
        # stop cx traffic
        print("Stopping CX Traffic")
        for cx_name in self.cx_names.keys():
            data = {
                "test_mgr": "ALL",
                "cx_name": cx_name,
                "cx_state": "STOPPED"
            }
            self.json_post("/cli-json/set_cx_state", data)
        return True

    def finish(self):
        # Refresh stats
        print("\nRefresh CX stats")
        for cx_name in self.cx_names.keys():
            data = {"test_mgr": "ALL", "cross_connect": cx_name}
            self.json_post("/cli-json/show_cxe", data)

        # print("Sleeping for 5 seconds")
        time.sleep(5)

        # get data for endpoints JSON
        print("Collecting Data")
        for cx_name in self.cx_names.keys():

            try:
                # ?fields=tx+bytes,rx+bytes
                endp_url = "/endp/%s" % self.cx_names[cx_name]["a"]
                ptest = self.json_get(endp_url)
                self.resulting_endpoints[endp_url] = ptest

                ptest_a_tx = ptest['endpoint']['tx bytes']
                ptest_a_rx = ptest['endpoint']['rx bytes']

                #ptest = self.json_get("/endp/%s?fields=tx+bytes,rx+bytes" % self.cx_names[cx_name]["b"])
                endp_url = "/endp/%s" % self.cx_names[cx_name]["b"]
                ptest = self.json_get(endp_url)
                self.resulting_endpoints[endp_url] = ptest

                ptest_b_tx = ptest['endpoint']['tx bytes']
                ptest_b_rx = ptest['endpoint']['rx bytes']

                self.compare_vals("testTCP-A TX", ptest_a_tx)
                self.compare_vals("testTCP-A RX", ptest_a_rx)

                self.compare_vals("testTCP-B TX", ptest_b_tx)
                self.compare_vals("testTCP-B RX", ptest_b_rx)

            except Exception as e:
                self.error(e)

        # Examples of what happens when you add test results that do not begin with PASS
        # self.test_results.append("Neutral message will fail")
        # self.test_results.append("FAILED message will fail")
        # print("\n")

    def cleanup(self):
        for sta_name in self.station_names:
            LFUtils.removePort(self.resource, sta_name, self.lfclient_url)
        endp_names = []
        removeCX(self.lfclient_url, self.cx_names.keys())
        for cx_name in self.cx_names:
            endp_names.append(self.cx_names[cx_name]["a"])
            endp_names.append(self.cx_names[cx_name]["b"])
        removeEndps(self.lfclient_url, endp_names)
Beispiel #19
0
class StaConnect2(LFCliBase):
    def __init__(self,
                 host,
                 port,
                 _dut_ssid="jedway-open-1",
                 _dut_passwd="NA",
                 _dut_bssid="",
                 _user="",
                 _passwd="",
                 _sta_mode="0",
                 _radio="wiphy0",
                 _resource=1,
                 _upstream_resource=1,
                 _upstream_port="eth1",
                 _sta_name=None,
                 _sta_prefix='sta',
                 _bringup_time_sec=300,
                 debug_=False,
                 _dut_security=OPEN,
                 _exit_on_error=False,
                 _cleanup_on_exit=True,
                 _clean_all_sta=False,
                 _runtime_sec=60,
                 _exit_on_fail=False):
        # do not use `super(LFCLiBase,self).__init__(self, host, port, _debugOn)
        # that is py2 era syntax and will force self into the host variable, making you
        # very confused.
        super().__init__(host,
                         port,
                         _debug=debug_,
                         _halt_on_error=_exit_on_error,
                         _exit_on_fail=_exit_on_fail)
        self.debug = debug_
        self.dut_security = _dut_security
        self.dut_ssid = _dut_ssid
        self.dut_passwd = _dut_passwd
        self.dut_bssid = _dut_bssid
        self.user = _user
        self.passwd = _passwd
        self.sta_mode = _sta_mode  # See add_sta LANforge CLI users guide entry
        self.radio = _radio
        self.resource = _resource
        self.upstream_resource = _upstream_resource
        self.upstream_port = _upstream_port
        self.runtime_secs = _runtime_sec
        self.cleanup_on_exit = _cleanup_on_exit
        self.clean_all_sta = _clean_all_sta
        self.sta_url_map = None  # defer construction
        self.upstream_url = None  # defer construction
        self.station_names = []
        if _sta_name is not None:
            self.station_names = [_sta_name]
        self.sta_prefix = _sta_prefix
        self.bringup_time_sec = _bringup_time_sec
        # self.localrealm :Realm = Realm(lfclient_host=host, lfclient_port=port) # py > 3.6
        self.localrealm = Realm(lfclient_host=host,
                                lfclient_port=port)  # py > 3.6
        self.resulting_stations = {}
        self.resulting_endpoints = {}
        self.station_profile = None
        self.l3_udp_profile = None
        self.l3_tcp_profile = None

    # def get_realm(self) -> Realm: # py > 3.6
    def get_realm(self):
        return self.localrealm

    def get_station_url(self, sta_name_=None):
        if sta_name_ is None:
            raise ValueError("get_station_url wants a station name")
        if self.sta_url_map is None:
            self.sta_url_map = {}
            for sta_name in self.station_names:
                self.sta_url_map[sta_name] = "port/1/%s/%s" % (self.resource,
                                                               sta_name)
        return self.sta_url_map[sta_name_]

    def get_upstream_url(self):
        if self.upstream_url is None:
            self.upstream_url = "port/1/%s/%s" % (self.upstream_resource,
                                                  self.upstream_port)
        return self.upstream_url

    # Compare pre-test values to post-test values
    def compare_vals(self, name, postVal, print_pass=False, print_fail=True):
        # print(f"Comparing {name}")
        if postVal > 0:
            self._pass("%s %s" % (name, postVal), print_pass)
        else:
            self._fail("%s did not report traffic: %s" % (name, postVal),
                       print_fail)

    def remove_stations(self):
        for name in self.station_names:
            LFUtils.removePort(self.resource, name, self.lfclient_url)

    def num_associated(self, bssid):
        counter = 0
        # print("there are %d results" % len(self.station_results))
        fields = "_links,port,alias,ip,ap,port+type"
        self.station_results = self.localrealm.find_ports_like("%s*" %
                                                               self.sta_prefix,
                                                               fields,
                                                               debug_=False)
        if (self.station_results is None) or (len(self.station_results) < 1):
            self.get_failed_result_list()
        for eid, record in self.station_results.items():
            #print("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ")
            #pprint(eid)
            #pprint(record)
            if record["ap"] == bssid:
                counter += 1
            #print("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ")
        return counter

    def clear_test_results(self):
        self.resulting_stations = {}
        self.resulting_endpoints = {}
        super().clear_test_results()
        #super(StaConnect, self).clear_test_results().test_results.clear()

    def setup(self):
        self.clear_test_results()
        self.check_connect()
        upstream_json = self.json_get("%s?fields=alias,phantom,down,port,ip" %
                                      self.get_upstream_url(),
                                      debug_=False)

        if upstream_json is None:
            self._fail(message="Unable to query %s, bye" % self.upstream_port,
                       print_=True)
            return False

        if upstream_json['interface']['ip'] == "0.0.0.0":
            if self.debug:
                pprint.pprint(upstream_json)
            self._fail("Warning: %s lacks ip address" %
                       self.get_upstream_url(),
                       print_=True)
            return False

        # remove old stations
        if self.clean_all_sta:
            print("Removing all stations on resource.")
            self.localrealm.remove_all_stations(self.resource)
        else:
            print("Removing old stations to be created by this test.")
            for sta_name in self.station_names:
                sta_url = self.get_station_url(sta_name)
                response = self.json_get(sta_url)
                if (response is not None) and (response["interface"]
                                               is not None):
                    for sta_name in self.station_names:
                        LFUtils.removePort(self.resource, sta_name,
                                           self.lfclient_url)
            LFUtils.wait_until_ports_disappear(self.lfclient_url,
                                               self.station_names)

        # Create stations and turn dhcp on
        self.station_profile = self.localrealm.new_station_profile()

        if self.dut_security == WPA2:
            self.station_profile.use_security(security_type="wpa2",
                                              ssid=self.dut_ssid,
                                              passwd=self.dut_passwd)
        elif self.dut_security == OPEN:
            self.station_profile.use_security(security_type="open",
                                              ssid=self.dut_ssid,
                                              passwd="[BLANK]")
        elif self.dut_security == WPA:
            self.station_profile.use_security(security_type="wpa",
                                              ssid=self.dut_ssid,
                                              passwd=self.dut_passwd)
        elif self.dut_security == WEP:
            self.station_profile.use_security(security_type="wep",
                                              ssid=self.dut_ssid,
                                              passwd=self.dut_passwd)
        self.station_profile.set_command_flag("add_sta", "create_admin_down",
                                              1)

        print("Adding new stations ", end="")
        self.station_profile.create(radio=self.radio,
                                    sta_names_=self.station_names,
                                    up_=False,
                                    debug=self.debug,
                                    suppress_related_commands_=True)
        LFUtils.wait_until_ports_appear(self.lfclient_url,
                                        self.station_names,
                                        debug=self.debug)

        # Create UDP endpoints
        self.l3_udp_profile = self.localrealm.new_l3_cx_profile()
        self.l3_udp_profile.side_a_min_bps = 128000
        self.l3_udp_profile.side_b_min_bps = 128000
        self.l3_udp_profile.side_a_min_pdu = 1200
        self.l3_udp_profile.side_b_min_pdu = 1500
        self.l3_udp_profile.report_timer = 1000
        self.l3_udp_profile.name_prefix = "udp"
        port_list = list(
            self.localrealm.find_ports_like("%s+" % self.sta_prefix))
        if (port_list is None) or (len(port_list) < 1):
            raise ValueError("Unable to find ports named '%s'+" %
                             self.sta_prefix)
        self.l3_udp_profile.create(endp_type="lf_udp",
                                   side_a=port_list,
                                   side_b="%d.%s" %
                                   (self.resource, self.upstream_port),
                                   suppress_related_commands=True)

        # Create TCP endpoints
        self.l3_tcp_profile = self.localrealm.new_l3_cx_profile()
        self.l3_tcp_profile.side_a_min_bps = 128000
        self.l3_tcp_profile.side_b_min_bps = 56000
        self.l3_tcp_profile.name_prefix = "tcp"
        self.l3_tcp_profile.report_timer = 1000
        self.l3_tcp_profile.create(
            endp_type="lf_tcp",
            side_a=list(
                self.localrealm.find_ports_like("%s+" % self.sta_prefix)),
            side_b="%d.%s" % (self.resource, self.upstream_port),
            suppress_related_commands=True)

    def start(self):
        if self.station_profile is None:
            self._fail("Incorrect setup")
        pprint.pprint(self.station_profile)
        if self.station_profile.up is None:
            self._fail("Incorrect station profile, missing profile.up")
        if self.station_profile.up == False:
            print("\nBringing ports up...")
            data = {
                "shelf": 1,
                "resource": self.resource,
                "port": "ALL",
                "probe_flags": 1
            }
            self.json_post("/cli-json/nc_show_ports", data)
            self.station_profile.admin_up()
            LFUtils.waitUntilPortsAdminUp(self.resource, self.lfclient_url,
                                          self.station_names)

        # station_info = self.jsonGet(self.mgr_url, "%s?fields=port,ip,ap" % (self.getStaUrl()))
        duration = 0
        maxTime = self.bringup_time_sec
        ip = "0.0.0.0"
        ap = ""
        print("Waiting for %s stations to associate to AP: " %
              len(self.station_names),
              end="")
        connected_stations = {}
        while (len(connected_stations.keys()) < len(
                self.station_names)) and (duration < maxTime):
            duration += 3
            time.sleep(3)
            print(".", end="")
            for sta_name in self.station_names:
                sta_url = self.get_station_url(sta_name)
                station_info = self.json_get(sta_url + "?fields=port,ip,ap")

                # LFUtils.debug_printer.pprint(station_info)
                if (station_info is not None) and ("interface"
                                                   in station_info):
                    if "ip" in station_info["interface"]:
                        ip = station_info["interface"]["ip"]
                    if "ap" in station_info["interface"]:
                        ap = station_info["interface"]["ap"]

                if (ap == "Not-Associated") or (ap == ""):
                    if self.debug:
                        print(" -%s," % sta_name, end="")
                else:
                    if ip == "0.0.0.0":
                        if self.debug:
                            print(" %s (0.0.0.0)" % sta_name, end="")
                    else:
                        connected_stations[sta_name] = sta_url
            data = {
                "shelf": 1,
                "resource": self.resource,
                "port": "ALL",
                "probe_flags": 1
            }
            self.json_post("/cli-json/nc_show_ports", data)

        for sta_name in self.station_names:
            sta_url = self.get_station_url(sta_name)
            station_info = self.json_get(sta_url)  # + "?fields=port,ip,ap")
            if station_info is None:
                print("unable to query %s" % sta_url)
            self.resulting_stations[sta_url] = station_info
            ap = station_info["interface"]["ap"]
            ip = station_info["interface"]["ip"]
            if (ap != "") and (ap != "Not-Associated"):
                print(" %s +AP %s, " % (sta_name, ap), end="")
                if self.dut_bssid != "":
                    if self.dut_bssid.lower() == ap.lower():
                        self._pass(sta_name + " connected to BSSID: " + ap)
                        # self.test_results.append("PASSED: )
                        # print("PASSED: Connected to BSSID: "+ap)
                    else:
                        self._fail(
                            "%s connected to wrong BSSID, requested: %s  Actual: %s"
                            % (sta_name, self.dut_bssid, ap))
            else:
                self._fail(sta_name + " did not connect to AP")
                return False

            if ip == "0.0.0.0":
                self._fail("%s did not get an ip. Ending test" % sta_name)
            else:
                self._pass("%s connected to AP: %s  With IP: %s" %
                           (sta_name, ap, ip))

        if self.passes() == False:
            if self.cleanup_on_exit:
                print("Cleaning up...")
                self.remove_stations()
            return False

        # start cx traffic
        print("\nStarting CX Traffic")
        self.l3_udp_profile.start_cx()
        self.l3_tcp_profile.start_cx()
        time.sleep(1)
        # Refresh stats
        self.l3_udp_profile.refresh_cx()
        self.l3_tcp_profile.refresh_cx()

    def collect_endp_stats(self, endp_map):
        print("Collecting Data")
        fields = "?fields=name,tx+bytes,rx+bytes"
        for (cx_name, endps) in endp_map.items():
            try:
                endp_url = "/endp/%s%s" % (endps[0], fields)
                endp_json = self.json_get(endp_url)
                self.resulting_endpoints[endp_url] = endp_json
                ptest_a_tx = endp_json['endpoint']['tx bytes']
                ptest_a_rx = endp_json['endpoint']['rx bytes']

                #ptest = self.json_get("/endp/%s?fields=tx+bytes,rx+bytes" % cx_names[cx_name]["b"])
                endp_url = "/endp/%s%s" % (endps[1], fields)
                endp_json = self.json_get(endp_url)
                self.resulting_endpoints[endp_url] = endp_json

                ptest_b_tx = endp_json['endpoint']['tx bytes']
                ptest_b_rx = endp_json['endpoint']['rx bytes']

                self.compare_vals("testTCP-A TX", ptest_a_tx)
                self.compare_vals("testTCP-A RX", ptest_a_rx)

                self.compare_vals("testTCP-B TX", ptest_b_tx)
                self.compare_vals("testTCP-B RX", ptest_b_rx)

            except Exception as e:
                self.error(e)

    def stop(self):
        # stop cx traffic
        print("Stopping CX Traffic")
        self.l3_udp_profile.stop_cx()
        self.l3_tcp_profile.stop_cx()

        # Refresh stats
        print("\nRefresh CX stats")
        self.l3_udp_profile.refresh_cx()
        self.l3_tcp_profile.refresh_cx()

        print("Sleeping for 5 seconds")
        time.sleep(5)

        # get data for endpoints JSON
        self.collect_endp_stats(self.l3_udp_profile.created_cx)
        self.collect_endp_stats(self.l3_tcp_profile.created_cx)
        # print("\n")

    def cleanup(self):
        # remove all endpoints and cxs
        if self.cleanup_on_exit:
            for sta_name in self.station_names:
                LFUtils.removePort(self.resource, sta_name, self.lfclient_url)
            curr_endp_names = []
            removeCX(self.lfclient_url, self.l3_udp_profile.get_cx_names())
            removeCX(self.lfclient_url, self.l3_tcp_profile.get_cx_names())
            for (cx_name,
                 endp_names) in self.l3_udp_profile.created_cx.items():
                curr_endp_names.append(endp_names[0])
                curr_endp_names.append(endp_names[1])
            for (cx_name,
                 endp_names) in self.l3_tcp_profile.created_cx.items():
                curr_endp_names.append(endp_names[0])
                curr_endp_names.append(endp_names[1])
            removeEndps(self.lfclient_url, curr_endp_names, debug=self.debug)
Beispiel #20
0
# Realm of Reckoning
# A Text-based adventure game
# by
# Daniel Ashcom
# GNU GPL v 3.0
#  ==========  End documentation  ==========
###

# imports
##
from realm import Realm

# start game loop
##
world = Realm()
Beispiel #21
0
class CreateSTA_CX(LFCliBase):
    def __init__(self,
                 host,
                 port,
                 radio,
                 num_sta,
                 sta_id,
                 ssid,
                 security,
                 password,
                 upstream,
                 protocol,
                 min_bps,
                 max_bps,
                 security_debug_on=True,
                 _exit_on_error=True,
                 _exit_on_fail=True):
        super().__init__(host,
                         port,
                         _debug=security_debug_on,
                         _halt_on_error=_exit_on_error,
                         _exit_on_fail=_exit_on_fail)

        self.host = host
        self.port = port
        self.radio = radio

        self.num_sta = num_sta
        self.sta_id = sta_id

        self.ssid = ssid

        self.security = security
        self.password = password

        self.upstream = upstream
        self.protocol = protocol

        self.min_bps = min_bps
        self.max_bps = max_bps

        #Creating a Realm Object
        self.local_realm = Realm(lfclient_host=host, lfclient_port=port)

        #Creating Profile Objects
        self.station_profile = self.local_realm.new_station_profile()
        self.cx_profile = self.local_realm.new_l3_cx_profile()

        #Setting CX Name
        self.cx_profile.name_prefix_ = "Connection"
        self.cx_names = []
        self.sta_list = []
        self.endp = []
        for i in range(sta_id, sta_id + num_sta):
            self.sta_list.append("sta00")

        #portDhcpUpRequest
        '''
        upstream_dhcp = LFRequest.LFRequest("http://"+str(host)+":"+str(port)+"/"+"/cli-form/set_port")
        upstream_dhcp.addPostData( LFUtils.portSetDhcpDownRequest(1, upstream))
        upstream_dhcp.formPost()
        time.sleep(2)
        upstream_dhcp.addPostData( LFUtils.portUpRequest(1, upstream))
        upstream_dhcp.formPost()
        print(upstream + "Set to DHCP For Cross Connects")
        '''

    def build(self):

        #Creating Stations of Given Profile Settings
        self.station_profile.use_security(self.security,
                                          self.ssid,
                                          passwd=self.password)
        self.station_profile.create(self.radio,
                                    num_stations=self.num_sta,
                                    sta_names_=self.sta_list)
        self.station_profile.admin_up()
        #Wait for a while
        time.sleep(15)

        #Setting up the Parameters for CX
        self.cx_profile.side_a_min_bps = self.min_bps
        self.cx_profile.side_b_min_bps = self.min_bps
        self.cx_profile.side_a_max_bps = self.max_bps
        self.cx_profile.side_b_max_bps = self.max_bps

        self.cx_profile.side_a_min_pdu = 'Auto'
        self.cx_profile.side_b_min_pdu = 'Auto'
        self.cx_profile.report_timer = 1000
        self.cx_profile.side_a_min_pkt = 'Same'
        self.cx_profile.side_a_max_pkt = 'Same'

        #Create Connections of Given Parameters
        self.cx_profile.create(self.protocol,
                               side_a="1.1." + self.upstream,
                               side_b=list(
                                   self.local_realm.find_ports_like("sta0+")))
        time.sleep(15)

        # Getting all the Endpoint Names for measuring Throughput Later
        for i in self.cx_profile.get_cx_names():
            self.cx_names.append(i)
        for j in self.cx_names:
            x = self.local_realm.json_get("/cx/" + j)
            self.endp.append(x.get(j).get('endpoints')[1])
        #print(self.endp)
        return 0

    def start(self):
        #self.station_profile.admin_up()

        self.cx_profile.start_cx()
        time.sleep(5)
        return 0

    def stop(self):
        self.cx_profile.stop_cx()
        time.sleep(5)
        self.lf_stations.admin_down()
        time.sleep(5)
        return 0

    def cleanup(self):
        # Removing Connections
        self.local_realm.cleanup_cxe_prefix(self.cx_profile.name_prefix)

        vap = self.local_realm.find_ports_like("vap+")
        bridges = self.local_realm.find_ports_like("br+")
        station_map = self.local_realm.find_ports_like("sta+")
        #Removing Bridges
        for eid, record in bridges.items():
            self.local_realm.remove_vlan_by_eid(eid)
            time.sleep(0.03)
        #Removing VAP
        for eid, record in vap.items():
            self.local_realm.remove_vlan_by_eid(eid)
            time.sleep(0.03)

        #Removing stations
        for eid, record in station_map.items():
            self.local_realm.remove_vlan_by_eid(eid)
            time.sleep(0.03)
        del_sta_names = []
        try:
            for eid, value in station_map.items():
                tname = eid[eid.rfind('.'):]
                del_sta_names.append(tname)
        except Exception as x:
            self.local_realm.error(x)
        try:
            LFUtils.waitUntilPortsDisappear(
                base_url=self.local_realm.lfclient_url,
                port_list=del_sta_names,
                debug=True)
            print("Ports Successfully Cleaned up")
            return 0
        except:
            print("Ports Successfully Cleaned up")
        time.sleep(5)
        return 0
def main():
    optional = []
    optional.append({
        'name': '--mode',
        'help': 'Used to force mode of stations'
    })
    optional.append({
        'name': '--ap',
        'help': 'Used to force a connection to a particular AP'
    })
    optional.append({
        'name': '--output_format',
        'help': 'choose either csv or xlsx'
    })
    optional.append({
        'name': '--report_file',
        'help': 'where you want to store results',
        'default': None
    })
    optional.append({
        'name': '--a_min',
        'help': '--a_min bps rate minimum for side_a',
        'default': 256000
    })
    optional.append({
        'name': '--b_min',
        'help': '--b_min bps rate minimum for side_b',
        'default': 256000
    })
    optional.append({
        'name': '--test_duration',
        'help': '--test_duration sets the duration of the test',
        'default': "2m"
    })
    optional.append({
        'name': '--layer3_cols',
        'help': 'Columns wished to be monitored from layer 3 endpoint tab',
        'default': ['name', 'tx bytes', 'rx bytes']
    })
    optional.append({
        'name': '--port_mgr_cols',
        'help': 'Columns wished to be monitored from port manager tab',
        'default': ['ap', 'ip', 'parent dev']
    })
    optional.append({
        'name': '--compared_report',
        'help':
        'report path and file which is wished to be compared with new report',
        'default': None
    })
    optional.append({
        'name': '--monitor_interval',
        'help': 'frequency of monitor polls - ex: 250ms, 35s, 2h',
        'default': '2s'
    })
    optional.append({
        'name':
        '--monitor',
        'help':
        'whether test data should be recorded and stored in a report'
    })
    parser = Realm.create_basic_argparse(
        prog='test_ipv4_variable_time.py',
        formatter_class=argparse.RawTextHelpFormatter,
        epilog='''\
            Create stations to test connection and traffic on VAPs of varying security types (WEP, WPA, WPA2, WPA3, Open)
            ''',
        description='''\
test_ipv4_variable_time.py:
--------------------
Generic command layout:

python3 ./test_ipv4_variable_time.py
    --upstream_port eth1
    --radio wiphy0
    --num_stations 32
    --security {open|wep|wpa|wpa2|wpa3}
    --mode   1
        {"auto"   : "0",
        "a"      : "1",
        "b"      : "2",
        "g"      : "3",
        "abg"    : "4",
        "abgn"   : "5",
        "bgn"    : "6",
        "bg"     : "7",
        "abgnAC" : "8",
        "anAC"   : "9",
        "an"     : "10",
        "bgnAC"  : "11",
        "abgnAX" : "12",
        "bgnAX"  : "13"}
    --ssid netgear
    --password admin123
    --test_duration 2m (default)
    --monitor_interval_ms 
    --monitor 
    --a_min 3000
    --b_min 1000
    --ap "00:0e:8e:78:e1:76"
    --output_format csv
    --report_file ~/Documents/results.csv                       (Example of csv file output  - please use another extension for other file formats)
    --compared_report ~/Documents/results_prev.csv              (Example of csv file retrieval - please use another extension for other file formats) - UNDER CONSTRUCTION
    --layer3_cols'name','tx bytes','rx bytes','dropped'          (column names from the GUI to print on report -  please read below to know what to put here according to preferences)
    --port_mgr_cols 'ap','ip'                                    (column names from the GUI to print on report -  please read below to know what to put here according to preferences)
    --debug
===============================================================================
 ** FURTHER INFORMATION **
    Using the layer3_cols flag:

    Currently the output function does not support inputting the columns in layer3_cols the way they are displayed in the GUI. This quirk is under construction. To output
    certain columns in the GUI in your final report, please match the according GUI column display to it's counterpart to have the columns correctly displayed in
    your report.

    GUI Column Display       Layer3_cols argument to type in (to print in report)

    Name                |  'name'
    EID                 |  'eid'
    Run                 |  'run'
    Mng                 |  'mng'
    Script              |  'script'
    Tx Rate             |  'tx rate'
    Tx Rate (1 min)     |  'tx rate (1&nbsp;min)'
    Tx Rate (last)      |  'tx rate (last)'
    Tx Rate LL          |  'tx rate ll'
    Rx Rate             |  'rx rate'
    Rx Rate (1 min)     |  'rx rate (1&nbsp;min)'
    Rx Rate (last)      |  'rx rate (last)'
    Rx Rate LL          |  'rx rate ll'
    Rx Drop %           |  'rx drop %'
    Tx PDUs             |  'tx pdus'
    Tx Pkts LL          |  'tx pkts ll'
    PDU/s TX            |  'pdu/s tx'
    Pps TX LL           |  'pps tx ll'
    Rx PDUs             |  'rx pdus'
    Rx Pkts LL          |  'pps rx ll'
    PDU/s RX            |  'pdu/s tx'
    Pps RX LL           |  'pps rx ll'
    Delay               |  'delay'
    Dropped             |  'dropped'
    Jitter              |  'jitter'
    Tx Bytes            |  'tx bytes'
    Rx Bytes            |  'rx bytes'
    Replays             |  'replays'
    TCP Rtx             |  'tcp rtx'
    Dup Pkts            |  'dup pkts'
    Rx Dup %            |  'rx dup %'
    OOO Pkts            |  'ooo pkts'
    Rx OOO %            |  'rx ooo %'
    RX Wrong Dev        |  'rx wrong dev'
    CRC Fail            |  'crc fail'
    RX BER              |  'rx ber'
    CX Active           |  'cx active'
    CX Estab/s          |  'cx estab/s'
    1st RX              |  '1st rx'
    CX TO               |  'cx to'
    Pattern             |  'pattern'
    Min PDU             |  'min pdu'
    Max PDU             |  'max pdu'
    Min Rate            |  'min rate'
    Max Rate            |  'max rate'
    Send Buf            |  'send buf'
    Rcv Buf             |  'rcv buf'
    CWND                |  'cwnd'
    TCP MSS             |  'tcp mss'
    Bursty              |  'bursty'
    A/B                 |  'a/b'
    Elapsed             |  'elapsed'
    Destination Addr    |  'destination addr'
    Source Addr         |  'source addr'
            ''',
        more_optional=optional)

    args = parser.parse_args()

    num_sta = 2
    if (args.num_stations is not None) and (int(args.num_stations) > 0):
        num_sta = int(args.num_stations)

    station_list = LFUtils.portNameSeries(prefix_="sta",
                                          start_id_=0,
                                          end_id_=num_sta - 1,
                                          padding_number_=10000,
                                          radio=args.radio)

    #transfer below to l3cxprofile2 or base_profile-----------------------#
    # try:
    #     layer3connections = ','.join([[*x.keys()][0] for x in ip_var_test.json_get('endp')['endpoint']])
    # except:
    #     raise ValueError('Try setting the upstream port flag if your device does not have an eth1 port')

    # if type(args.layer3_cols) is not list:
    #     layer3_cols = list(args.layer3_cols.split(","))
    #     # send col names here to file to reformat
    # else:
    #     layer3_cols = args.layer3_cols
    #     # send col names here to file to reformat
    # if type(args.port_mgr_cols) is not list:
    #     port_mgr_cols = list(args.port_mgr_cols.split(","))
    #     # send col names here to file to reformat
    # else:
    #     port_mgr_cols = args.port_mgr_cols
    #     # send col names here to file to reformat
    # if args.debug:
    #     print("Layer 3 Endp column names are...")
    #     print(layer3_cols)
    #     print("Port Manager column names are...")
    #     print(port_mgr_cols)

    ip_var_test = IPV4VariableTime(host=args.mgr,
                                   port=args.mgr_port,
                                   number_template="0000",
                                   sta_list=station_list,
                                   name_prefix="VT",
                                   upstream=args.upstream_port,
                                   ssid=args.ssid,
                                   password=args.passwd,
                                   radio=args.radio,
                                   security=args.security,
                                   test_duration=args.test_duration,
                                   use_ht160=False,
                                   side_a_min_rate=args.a_min,
                                   side_b_min_rate=args.b_min,
                                   mode=args.mode,
                                   ap=args.ap,
                                   _debug_on=args.debug)

    ip_var_test.begin()
Beispiel #23
0
    def __init__(self,
                 upstream,
                 host="localhost",
                 port=8080,
                 side_a_min_rate=0,
                 side_a_max_rate=56000,
                 side_b_min_rate=0,
                 side_b_max_rate=56000,
                 num_sta_=200,
                 test_duration="30s",
                 _debug_on=True,
                 _exit_on_error=False,
                 _exit_on_fail=False):
        super().__init__(host,
                         port,
                         _debug=_debug_on,
                         _local_realm=Realm(lfclient_host=host,
                                            lfclient_port=port),
                         _halt_on_error=_exit_on_error,
                         _exit_on_fail=_exit_on_fail)
        self.ssid_radio_map = {
            '1.1.wiphy0':
            ("wpa2", "jedway-wpa2-x2048-4-4", "jedway-wpa2-x2048-4-4"),
            '1.1.wiphy1':
            ("wpa2", "jedway-wpa2-x2048-5-1", "jedway-wpa2-x2048-5-1"),
            '1.1.wiphy2':
            ("wpa2", "jedway-wpa2-x2048-4-1", "jedway-wpa2-x2048-4-1"),
            '1.2.wiphy0':
            ("wpa2", "jedway-wpa2-x2048-5-3", "jedway-wpa2-x2048-5-3"),
            '1.2.wiphy1': ("wpa2", "jedway-wpa2-x2048-4-4",
                           "jedway-wpa2-x2048-4-4"),
            '1.2.wiphy2': ("wpa2", "jedway-wpa2-x2048-4-1",
                           "jedway-wpa2-x2048-4-1"),
        }
        if num_sta_ is None:
            raise ValueError("need a number of stations per radio")
        self.num_sta = int(num_sta_)
        self.station_radio_map = {
            # port_name_series(prefix=prefix_, start_id=start_id_, end_id=end_id_, padding_number=padding_number_, radio=radio)
            "1.1.wiphy0":
            LFUtils.port_name_series(start_id=0,
                                     end_id=self.num_sta - 1,
                                     padding_number=10000,
                                     radio="1.1.wiphy0"),
            "1.1.wiphy1":
            LFUtils.port_name_series(start_id=1000,
                                     end_id=1000 + self.num_sta - 1,
                                     padding_number=10000,
                                     radio="1.1.wiphy1"),
            "1.1.wiphy2":
            LFUtils.port_name_series(start_id=2000,
                                     end_id=2000 + self.num_sta - 1,
                                     padding_number=10000,
                                     radio="1.1.wiphy2"),
            "1.2.wiphy0":
            LFUtils.port_name_series(start_id=3000,
                                     end_id=3000 + self.num_sta - 1,
                                     padding_number=10000,
                                     radio="1.2.wiphy0"),
            "1.2.wiphy1":
            LFUtils.port_name_series(start_id=4000,
                                     end_id=4000 + self.num_sta - 1,
                                     padding_number=10000,
                                     radio="1.2.wiphy1"),
            "1.2.wiphy2":
            LFUtils.port_name_series(start_id=5000,
                                     end_id=5000 + self.num_sta - 1,
                                     padding_number=10000,
                                     radio="1.2.wiphy2")
        }
        self.test_duration = test_duration
        self.upstream = upstream
        self.name_prefix = "1k"
        self.cx_profile = self.local_realm.new_l3_cx_profile()
        self.cx_profile.name_prefix = self.name_prefix
        self.cx_profile.side_a_min_bps = side_a_min_rate
        self.cx_profile.side_a_max_bps = side_a_max_rate
        self.cx_profile.side_b_min_bps = side_b_min_rate
        self.cx_profile.side_b_max_bps = side_b_max_rate

        self.station_profile_map = {}