Beispiel #1
0
    def runTest(self):
        from devices import lan, debian, linux
        if lan.model == "debian":
            # check that lan is derived from LinuxDevice
            assert(issubclass(debian.DebianBox, linux.LinuxDevice))

        #get the mac address of the interface
        lan_mac = lan.get_interface_macaddr(lan.iface_dut)
        assert lan_mac != None, "Failed getting lan mac address"
        print("lan mac address: %s" % lan_mac)

        #check the system uptime
        uptime = lan.get_seconds_uptime()
        assert uptime != None, "Failed getting system uptime"
        print("system uptime is: %s" % uptime)

        #ping ip using function ping from linux.py
        ping_check = lan.ping("8.8.8.8")
        print("ping status is %s" % ping_check)

        #disable ipv6
        ipv6_disable = lan.disable_ipv6(lan.iface_dut)
        #enable ipv6
        ipv6_enable = lan.enable_ipv6(lan.iface_dut)
        board.set_printk()
        print("Test passed")

        #remove neighbour table entries
        lan.ip_neigh_flush()

        #set the link state up
        lan.set_link_state(lan.iface_dut, "up")

        #Checking the interface status
        link = lan.is_link_up(lan.iface_dut)
        assert link != None, "Failed to check the link is up"

        #add sudo when the username is root
        lan.sudo_sendline("ping -c5 '8.8.8.8'")
        lan.expect(lan.prompt, timeout=50)

        #add new user name in linux
        lan.add_new_user("test", "test")
        lan.sendline("userdel test")
        lan.expect(lan.prompt)

        text_file = tempfile.NamedTemporaryFile()
        letters = string.ascii_letters
        fcontent = ''.join(random.choice(letters) for i in range(50))

        text_file.write(fcontent)
        text_file.flush()

        fmd5 = hashlib.md5(open(text_file.name, 'rb').read()).hexdigest()
        print("File orginal md5sum: %s"% fmd5)
        print('copying file to lan at /tmp/dst.txt')
        lan.copy_file_to_server(text_file.name, "/tmp/dst.txt")
        print('Copy Done. Verify the integrity of the file')
        lan.sendline('md5sum /tmp/dst.txt')
        lan.expect(fmd5)
        lan.expect(lan.prompt)

        '''FUnctions moved from openwrt to linux '''
        #Wait until network interfaces have IP Addresses
        board.wait_for_network()
        print "Waited until network interfaces has ip address"

        #Check the available memory of the device
        memory_avail = board.get_memfree()
        print 'Available memory of the device:{}'.format(memory_avail)

        #Getting the vmstat
        vmstat_out = board.get_proc_vmstat()
        assert vmstat_out is not None, 'virtual machine status is None'
        print "Got the vmstat{}".format(vmstat_out)

        #Get the total number of connections in the network
        nw_count = board.get_nf_conntrack_conn_count()
        assert nw_count is not None , 'connections are empty'
        print 'Get the total number of connections in the network{}'.format(nw_count)

        #Getting the DNS server upstream
        ip_addr = board.get_dns_server_upstream()
        assert ip_addr is not None, 'Getting nameserver ip is None'
        print "Got the DNS server upstream{}".format(ip_addr)
        print('Test Passed')
Beispiel #2
0
    def boot(self, reflash=True):
        # start tftpd server on appropriate device
        tftp_servers = [
            x['name'] for x in self.config.board['devices']
            if 'tftpd-server' in x.get('options', "")
        ]
        tftp_device = None
        # start all tftp servers for now
        for tftp_server in tftp_servers:
            # This is a mess, just taking the last tftpd-server?
            tftp_device = getattr(self.config, tftp_server)

        # start dhcp servers
        for device in self.config.board['devices']:
            if 'options' in device and 'no-dhcp-sever' in device['options']:
                continue
            if 'options' in device and 'dhcp-server' in device['options']:
                getattr(self.config, device['name']).setup_dhcp_server()

        if not wan and len(tftp_servers) == 0:
            msg = 'No WAN Device or tftp_server defined, skipping flash.'
            lib.common.test_msg(msg)
            self.skipTest(msg)

        # This still needs some clean up, the fall back is to assuming the
        # WAN provides the tftpd server, but it's not always the case
        if wan:
            wan.configure(kind="wan_device", config=self.config.board)
            if tftp_device is None:
                tftp_device = wan

        tftp_device.start_tftp_server()

        prov = getattr(self.config, 'provisioner', None)
        if prov is not None:
            prov.tftp_device = tftp_device
            board.reprovision(prov)

            if hasattr(prov, 'prov_gateway'):
                gw = prov.prov_gateway if wan.gw in prov.prov_network else prov.prov_ip

                for nw in [
                        prov.cm_network, prov.mta_network, prov.open_network
                ]:
                    wan.sendline('ip route add %s via %s' % (nw, gw))
                    wan.expect(prompt)

            # TODO: don't do this and sort out two interfaces with ipv6
            wan.disable_ipv6('eth0')

            if hasattr(prov, 'prov_gateway_v6'):
                wan.sendline('ip -6 route add default via %s' %
                             str(prov.prov_gateway_v6))
                wan.expect(prompt)

            wan.sendline('ip route')
            wan.expect(prompt)
            wan.sendline('ip -6 route')
            wan.expect(prompt)

        if lan:
            lan.configure(kind="lan_device")

        # tftp_device is always None, so we can set it from config
        board.tftp_server = tftp_device.ipaddr
        # then these are just hard coded defaults
        board.tftp_port = 22
        # but are user/password used for tftp, they are likely legacy and just need to go away
        board.tftp_username = "******"
        board.tftp_password = "******"

        board.reset()
        rootfs = None

        # Reflash only if at least one or more of these
        # variables are set, or else there is nothing to do in u-boot
        meta_interrupt = False
        if self.config.META_BUILD and not board.flash_meta_booted:
            meta_interrupt = True
        if reflash and (meta_interrupt or self.config.ROOTFS or\
                            self.config.KERNEL or self.config.UBOOT):
            # Break into U-Boot, set environment variables
            board.wait_for_boot()
            board.setup_uboot_network(tftp_device.gw)
            if self.config.META_BUILD:
                for attempt in range(3):
                    try:
                        board.flash_meta(self.config.META_BUILD, wan, lan)
                        break
                    except Exception as e:
                        print(e)
                        tftp_device.restart_tftp_server()
                        board.reset(break_into_uboot=True)
                        board.setup_uboot_network(tftp_device.gw)
                else:
                    raise Exception('Error during flashing...')
            if self.config.UBOOT:
                board.flash_uboot(self.config.UBOOT)
            if self.config.ROOTFS:
                # save filename for cases where we didn't flash it
                # but will use it later to load from memory
                rootfs = board.flash_rootfs(self.config.ROOTFS)
            if self.config.NFSROOT:
                board.prepare_nfsroot(self.config.NFSROOT)
            if self.config.KERNEL:
                board.flash_linux(self.config.KERNEL)
            # Boot from U-Boot to Linux
            board.boot_linux(rootfs=rootfs, bootargs=self.config.bootargs)
        if hasattr(board, "pre_boot_linux"):
            board.pre_boot_linux(wan=wan, lan=lan)
        board.linux_booted = True
        board.wait_for_linux()
        if self.config.META_BUILD and board.flash_meta_booted:
            board.flash_meta(self.config.META_BUILD, wan, lan)
        linux_booted_seconds_up = board.get_seconds_uptime()
        # Retry setting up wan protocol
        if self.config.setup_device_networking:
            for i in range(2):
                time.sleep(10)
                try:
                    if "pppoe" in self.config.WAN_PROTO:
                        wan.turn_on_pppoe()
                    board.config_wan_proto(self.config.WAN_PROTO)
                    break
                except:
                    print("\nFailed to check/set the router's WAN protocol.")
                    pass
            board.wait_for_network()
        board.wait_for_mounts()

        # Give other daemons time to boot and settle
        if self.config.setup_device_networking:
            for i in range(5):
                board.get_seconds_uptime()
                time.sleep(5)

        try:
            board.sendline("passwd")
            board.expect("password:"******"password")
            board.expect("password:"******"password")
            board.expect(prompt)
        except:
            print("WARNING: Unable to set root password on router.")

        board.sendline('cat /proc/cmdline')
        board.expect(prompt)
        board.sendline('uname -a')
        board.expect(prompt)

        # we can't have random messsages messages
        board.set_printk()

        if hasattr(self.config,
                   'INSTALL_PKGS') and self.config.INSTALL_PKGS != "":
            for pkg in self.config.INSTALL_PKGS.split(' '):
                if len(pkg) > 0:
                    board.install_package(pkg)

        if board.has_cmts:
            from docsis_lib.docsis import check_valid_docsis_ip_networking
            check_valid_docsis_ip_networking(board)

        # Try to verify router has stayed up (and, say, not suddenly rebooted)
        end_seconds_up = board.get_seconds_uptime()
        print("\nThe router has been up %s seconds." % end_seconds_up)
        if self.config.setup_device_networking:
            assert end_seconds_up > linux_booted_seconds_up

        self.logged['boot_time'] = end_seconds_up

        if board.routing and lan and self.config.setup_device_networking:
            if wan is not None:
                lan.start_lan_client(wan_gw=wan.gw)
            else:
                lan.start_lan_client()
Beispiel #3
0
    def runTest(self):
        legacy = hasattr(self.config, "wan_device")
        lib.common.test_msg("Press Ctrl-] to stop interaction and return to menu")
        board.sendline()
        try:
            board.interact()
        except:
            return

        while True:
            print("\n\nCurrent station")
            print("  Board console: %s" % self.config.board.get('conn_cmd'))
            if legacy:
                self.print_legacy_devices()
            self.print_dynamic_devices()
            print('Pro-tip: Increase kernel message verbosity with\n'
                  '    echo "7 7 7 7" > /proc/sys/kernel/printk')
            print("Menu")
            i = 2
            if board.consoles is None:
                print("  1: Enter console")
                i += 1
            else:
                i = 1
                for c in board.consoles:
                    print("  %s: Enter console" % i)
                    i += 1
            if legacy: 
                print("  %s: Enter wan console" % i)
                i += 1
                print("  %s: Enter lan console" % i)
                i += 1
                print("  %s: Enter wlan console" % i)
                i += 1

            print("  %s: List all tests" % i)
            i += 1
            print("  %s: Run test" % i)
            i += 1
            print("  %s: Reset board" % i)
            i += 1
            print("  %s: Enter interactive python shell" % i)
            i += 1
            if len(self.config.devices) > 0:
                print("  Type a device name to connect: %s" % self.config.devices)
            print("  x: Exit")
            key = raw_input("Please select: ")

            if key in self.config.devices:
                d = getattr(self.config, key)
                d.interact()

            i = 1
            for c in board.consoles:
                if key == str(i):
                    c.interact()
                i += 1

            if legacy:
                if key == str(i):
                    wan.interact()
                    continue
                i += 1

                if key == str(i):
                    lan.interact()
                    continue
                i += 1

                if key == str(i):
                    wlan.interact()
                    continue
                i += 1

            if key == str(i):
                try:
                    # re import the tests
                    test_files = glob.glob(os.path.dirname(__file__)+"/*.py")
                    for x in sorted([os.path.basename(f)[:-3] for f in test_files if not "__" in f]):
                        exec("from %s import *" % x)

                    if 'BFT_OVERLAY' in os.environ:
                        for o in os.environ['BFT_OVERLAY'].split(' ' ):
                            test_files = glob.glob(o + "/tests/*.py")
                            for x in sorted([os.path.basename(f)[:-3] for f in test_files if not "__" in f]):
                                exec("from %s import *" % x)
                except:
                    print("Unable to re-import tests!")
                else:
                    # list what we can re-run
                    rfs_boot = rootfs_boot.RootFSBootTest
                    print("Available tests:")
                    print_subclasses(rfs_boot)
                continue
            i += 1

            if key == str(i):
                try:
                    # re import the tests
                    test_files = glob.glob(os.path.dirname(__file__)+"/*.py")
                    for x in sorted([os.path.basename(f)[:-3] for f in test_files if not "__" in f]):
                        exec("from %s import *" % x)

                    if 'BFT_OVERLAY' in os.environ:
                        for o in os.environ['BFT_OVERLAY'].split(' ' ):
                            test_files = glob.glob(o + "/tests/*.py")
                            for x in sorted([os.path.basename(f)[:-3] for f in test_files if not "__" in f]):
                                exec("from %s import *" % x)
                except:
                    print("Unable to re-import tests!")
                else:
                    # TODO: use an index instead of test name
                    print("Type test to run: ")
                    test = sys.stdin.readline()

                    #try:
                    board.sendline()
                    # default are 1 1 1 7
                    board.set_printk()
                    board.expect(prompt)
                    try:
                        t = eval(test)
                        reload(sys.modules[t.__module__])
                        cls = t(self.config)
                        lib.common.test_msg("\n==================== Begin %s ====================" % cls.__class__.__name__)
                        cls.testWrapper()
                        lib.common.test_msg("\n==================== End %s ======================" % cls.__class__.__name__)
                        board.sendline()
                    except:
                        lib.common.test_msg("Failed to find and/or run test, continuing..")
                        continue
                    #except:
                    #    print("Unable to (re-)run specified test")

                continue
            i += 1

            if key == str(i):
                board.reset()
                print("Press Ctrl-] to stop interaction and return to menu")
                board.interact()
                continue
            i += 1

            if key == str(i):
                print("Enter python shell, press Ctrl-D to exit")
                try:
                    from IPython import embed
                    embed()
                except:
                    try:
                        import readline # optional, will allow Up/Down/History in the console
                        import code
                        vars = globals().copy()
                        vars.update(locals())
                        shell = code.InteractiveConsole(vars)
                        shell.interact()
                    except:
                        print("Unable to spawn interactive shell!")
                continue
            i += 1

            if key == "x":
                break
Beispiel #4
0
    def boot(self, reflash=True):
        # start tftpd server on appropriate device
        tftp_servers = [
            x['name'] for x in self.config.board['devices']
            if 'tftpd-server' in x.get('options', "")
        ]
        tftp_device = None
        # start all tftp servers for now
        for tftp_server in tftp_servers:
            # This is a mess, just taking the last tftpd-server?
            tftp_device = getattr(self.config, tftp_server)

        dhcp_started = False

        # start dhcp servers
        for device in self.config.board['devices']:
            if 'options' in device and 'dhcp-server' in device['options']:
                getattr(self.config, device['name']).setup_dhcp_server()
                dhcp_started = True

        if not wan and len(tftp_servers) == 0:
            msg = 'No WAN Device or tftp_server defined, skipping flash.'
            lib.common.test_msg(msg)
            self.skipTest(msg)

        # This still needs some clean up, the fall back is to assuming the
        # WAN provides the tftpd server, but it's not always the case
        if wan:
            wan.configure(kind="wan_device", config=self.config.board)
            if tftp_device is None:
                tftp_device = wan

        if wan and not dhcp_started:
            wan.setup_dhcp_server()

        tftp_device.start_tftp_server()

        prov = getattr(self.config, 'provisioner', None)
        if prov is not None:
            prov.tftp_device = tftp_device
            prov.provision_board(self.config.board)

            if hasattr(prov, 'prov_gateway'):
                gw = prov.prov_gateway if wan.gw in prov.prov_network else prov.prov_ip

                for nw in [
                        prov.cm_network, prov.mta_network, prov.open_network
                ]:
                    wan.sendline('ip route add %s via %s' % (nw, gw))
                    wan.expect(prompt)

            wan.sendline('ip route')
            wan.expect(prompt)

        if lan:
            lan.configure(kind="lan_device")

        # tftp_device is always None, so we can set it from config
        board.tftp_server = tftp_device.ipaddr
        # then these are just hard coded defaults
        board.tftp_port = 22
        # but are user/password used for tftp, they are likely legacy and just need to go away
        board.tftp_username = "******"
        board.tftp_password = "******"

        board.reset()
        rootfs = None

        # Reflash only if at least one or more of these
        # variables are set, or else there is nothing to do in u-boot
        meta_interrupt = False
        if self.config.META_BUILD and not board.flash_meta_booted:
            meta_interrupt = True
        if reflash and (meta_interrupt or self.config.ROOTFS or\
                            self.config.KERNEL or self.config.UBOOT):
            # Break into U-Boot, set environment variables
            board.wait_for_boot()
            board.setup_uboot_network(tftp_device.gw)
            if self.config.META_BUILD:
                for attempt in range(3):
                    try:
                        board.flash_meta(self.config.META_BUILD, wan, lan)
                        break
                    except Exception as e:
                        print(e)
                        tftp_device.restart_tftp_server()
                        board.reset(break_into_uboot=True)
                        board.setup_uboot_network(tftp_device.gw)
                else:
                    raise Exception('Error during flashing...')
            if self.config.UBOOT:
                board.flash_uboot(self.config.UBOOT)
            if self.config.ROOTFS:
                # save filename for cases where we didn't flash it
                # but will use it later to load from memory
                rootfs = board.flash_rootfs(self.config.ROOTFS)
            if self.config.NFSROOT:
                board.prepare_nfsroot(self.config.NFSROOT)
            if self.config.KERNEL:
                board.flash_linux(self.config.KERNEL)
            # Boot from U-Boot to Linux
            board.boot_linux(rootfs=rootfs, bootargs=self.config.bootargs)
        if hasattr(board, "pre_boot_linux"):
            board.pre_boot_linux(wan=wan, lan=lan)
        board.linux_booted = True
        board.wait_for_linux()
        if self.config.META_BUILD and board.flash_meta_booted:
            board.flash_meta(self.config.META_BUILD, wan, lan)
        linux_booted_seconds_up = board.get_seconds_uptime()
        # Retry setting up wan protocol
        if self.config.setup_device_networking:
            for i in range(2):
                time.sleep(10)
                try:
                    if "pppoe" in self.config.WAN_PROTO:
                        wan.turn_on_pppoe()
                    board.config_wan_proto(self.config.WAN_PROTO)
                    break
                except:
                    print("\nFailed to check/set the router's WAN protocol.")
                    pass
            board.wait_for_network()
        board.wait_for_mounts()

        if self.config.setup_device_networking:
            # Router mac addresses are likely to change, so flush arp
            if lan:
                lan.ip_neigh_flush()
            if wan:
                wan.ip_neigh_flush()

            # Clear default routes perhaps left over from prior use
            if lan:
                lan.sendline('\nip -6 route del default')
                lan.expect(prompt)
            if wan:
                wan.sendline('\nip -6 route del default')
                wan.expect(prompt)

        # Give other daemons time to boot and settle
        if self.config.setup_device_networking:
            for i in range(5):
                board.get_seconds_uptime()
                time.sleep(5)

        try:
            board.sendline("passwd")
            board.expect("password:"******"password")
            board.expect("password:"******"password")
            board.expect(prompt)
        except:
            print("WARNING: Unable to set root password on router.")

        board.sendline('cat /proc/cmdline')
        board.expect(prompt)
        board.sendline('uname -a')
        board.expect(prompt)

        # we can't have random messsages messages
        board.set_printk()

        if hasattr(self.config,
                   'INSTALL_PKGS') and self.config.INSTALL_PKGS != "":
            for pkg in self.config.INSTALL_PKGS.split(' '):
                if len(pkg) > 0:
                    board.install_package(pkg)

        if prov is not None and 'debian-isc-provisioner' in prov.model:
            table = self.config.board['station']
            idx = wan.port  # TODO: how to do this right...?

            start_time = time.time()
            time_for_provisioning = 120

            ips = []
            while (time.time() - start_time < time_for_provisioning):
                # reset IPs incase we got part way through and failed
                ips = []
                try:
                    try:
                        ip = board.get_interface_ipaddr(board.wan_iface)
                        assert ipaddress.IPv4Address(ip.decode('utf-8')) in prov.cm_network, \
                            "Board failed to obtain WAN IP address"
                    except:
                        continue

                    ips += [ip]

                    if hasattr(board, 'erouter_iface'):
                        try:
                            ip = board.get_interface_ipaddr(
                                board.erouter_iface)
                            assert ipaddress.IPv4Address(ip.decode('utf-8')) in prov.open_network, \
                                "Board failed to obtain erouter IP address"
                        except:
                            continue
                        ips += [ip]
                    if hasattr(board, 'mta_iface'):
                        try:
                            ip = board.get_interface_ipaddr(board.mta_iface)
                            assert ipaddress.IPv4Address(ip.decode('utf-8')) in prov.mta_network, \
                                "Board failed to obtain MTA IP address"
                        except:
                            continue
                        ips += [ip]

                    # if we get this far, we have all IPs and can exit while loop
                    break
                except:
                    if time.time() - start_time < time_for_provisioning:
                        raise
                    pass

            check = [
                hasattr(board, 'erouter_iface'),
                hasattr(board, 'mta_iface')
            ]
            if len(ips) != 1 + sum(1 if True else 0 for x in check):
                raise Exception(
                    "Failed to obtain ip address for all configured interfaces!"
                )

            # TODO: don't hard code 300 or mv1-1
            prov.sendline('sed /^%s/d -i /etc/iproute2/rt_tables' % idx)
            prov.expect(prompt)
            prov.sendline('echo "%s     %s" >> /etc/iproute2/rt_tables' %
                          (idx, table))
            prov.expect(prompt)

            for ip in ips:
                prov.sendline('ip rule del from %s' % ip)
                prov.expect(prompt)
                prov.sendline('ip rule add from %s lookup %s' % (ip, table))
                prov.expect(prompt)

            wan_ip = wan.get_interface_ipaddr(wan.iface_dut)
            prov.sendline('ip route add default via %s dev eth1 table %s' %
                          (wan_ip, table))
            prov.expect(prompt)

        # Try to verify router has stayed up (and, say, not suddenly rebooted)
        end_seconds_up = board.get_seconds_uptime()
        print("\nThe router has been up %s seconds." % end_seconds_up)
        if self.config.setup_device_networking:
            assert end_seconds_up > linux_booted_seconds_up

        self.logged['boot_time'] = end_seconds_up

        if board.routing and lan and self.config.setup_device_networking:
            if wan is not None:
                lan.start_lan_client(wan_gw=wan.gw)
            else:
                lan.start_lan_client()