Пример #1
0
    def __cmp__(self, other):
        """
        the function is used for comparation, the compared sequence is defined in TLV definition.
        :param other: the object who has the IpAddrType, GroupIpAddr, SrcIpAddr, SessionId
        :return:
        """
        if not hasattr(other, "IpAddrType"):
            return 0

        if self.IpAddrType != other.IpAddrType:
            return self.IpAddrType.__cmp__(other.IpAddrType)

        if not hasattr(other, "GroupIpAddr"):
            return 0

        if self.GroupIpAddr != other.GroupIpAddr:
            return Convert.compare_ip(self.GroupIpAddr, other.GroupIpAddr)

        if not hasattr(other, "SrcIpAddr"):
            return 0

        if self.SrcIpAddr != other.SrcIpAddr:
            return Convert.compare_ip(self.SrcIpAddr, other.SrcIpAddr)

        if not hasattr(other, "SessionId"):
            return 0

        return self.SessionId.__cmp__(other.SessionId)
Пример #2
0
    def __cmp__(self, other):
        if not hasattr(other, "sessionIpAddrType"):
            return 0
        if self.sessionIpAddrType != other.sessionIpAddrType:
            return self.sessionIpAddrType.__cmp__(other.sessionIpAddrType)

        if not hasattr(other, "ccapLcceIpAddr"):
            return 0
        if self.ccapLcceIpAddr != other.ccapLcceIpAddr:
            return Convert.compare_ip(self.ccapLcceIpAddr,
                                      other.ccapLcceIpAddr)

        if not hasattr(other, "rpdLcceIpAddr"):
            return 0
        if self.rpdLcceIpAddr != other.rpdLcceIpAddr:
            return Convert.compare_ip(self.rpdLcceIpAddr,
                                      other.rpdLcceIpAddr)

        if not hasattr(other, "direction"):
            return 0
        if self.direction != other.direction:
            return self.direction.__cmp__(other.direction)

        if not hasattr(other, "l2tpSessionId"):
            return 0
        if self.l2tpSessionId != other.l2tpSessionId:
            return self.l2tpSessionId.__cmp__(other.l2tpSessionId)

        return 0
Пример #3
0
    def add_ccap_cores(self,
                       ccap_cores,
                       port_master=GCPSessionDescriptor.DEFAULT_PORT_MASTER):
        """Create GCP descriptors based on addresses of CCAP cores received
        from DHCP server to orchestrator.

        :param ccap_cores: list of "interface;core ip"
        :type ccap_cores: list(string)
        :return:

        """
        descriptors = []

        for core_addr in ccap_cores:
            interface, core = core_addr.split(';')
            if not Convert.is_valid_ip_address(core):
                self.logger.warn("Malformed IP address received: %s", core)
                continue

            is_ipv6 = Convert.is_valid_ipv6_address(core)
            family = (AF_INET, AF_INET6)[is_ipv6]
            addr_local = SysTools.get_ip_address(str(interface), family)
            # TODO pass also local address to use specific interface
            descriptors.append(
                GCPSlaveDescriptor(core,
                                   port_master=port_master,
                                   addr_local=addr_local,
                                   interface_local=interface,
                                   addr_family=family))
        self.orchestrator.add_sessions(descriptors)
Пример #4
0
    def __init__(self, localAddr, connID):
        """Init the L2TP socket and bind to it.

        :param localAddr: The local IP address that we want to bind L2TP socket to it.
        :param connID: The connection ID, in L2tpv3 domain, it means the lcoal connection ID.

        """
        self.socket = None
        self.addr = localAddr
        self.connID = connID
        if Convert.is_valid_ipv4_address(localAddr):
            self.socket = socket.socket(
                socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_L2TP)
            self.socket.setblocking(False)  # Set the socket to non-block mode
            self.socket.bind((localAddr, connID))
            self.logger.info(
                "Create L2TP socket and bind to it, local IP address:%s, local Connection ID:%d, socket: %d" %
                (localAddr, connID, self.socket.fileno()))
        elif Convert.is_valid_ipv6_address(localAddr):
            self.socket = socket.socket(
                socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_L2TP)
            self.socket.setblocking(False)  # Set the socket to non-block mode
            self.socket.bind(('', connID))
            self.logger.info(
                "Create L2TP socket and bind to any adress, local Connection ID:%d, socket: %d" %
                (connID, self.socket.fileno()))
        else:
            self.logger.info(
                "Create L2TP socket failed, invalid local IP address:%s, local Connection ID:%d" %
                (localAddr, connID))
            self.socket = None
Пример #5
0
 def _to_gpb_value(self, value):
     """Converts the value into the GPB representation according to
     format."""
     if self.format.value_is_mac():
         return Convert.bytes_to_mac_str(value)
     if self.format.value_is_ip_addr():
         return Convert.bytes_to_ip_addr(value)
     return value
Пример #6
0
 def test_compip(self):
     ret = Convert.compare_ip("10.79.41.31", "10.79.41.31")
     self.assertEquals(ret, 0)
     ret = Convert.compare_ip("10.79.41.30", "10.79.41.31")
     self.assertEquals(ret, -1)
     ret = Convert.compare_ip("10.79.41.30", "10.25.41.31")
     self.assertEquals(ret, 1)
     ret = Convert.compare_ip("fe80::6a5b:35ff:feb2:8dcf",
                              "fe80::6a5b:35ff:feb2:8d6f")
     self.assertEquals(ret, 1)
Пример #7
0
 def _from_gpb_value(self, value):
     """Translates value from GPB's representation into the internal
     representation suitable for encoding."""
     if self.format.format_str == DataDescription.MAC_FMT:
         return Convert.mac_to_tuple_of_bytes(value)
     elif self.format.format_str == DataDescription.IP_FMT:
         return Convert.ipaddr_to_tuple_of_bytes(value)
     elif isinstance(value, unicode):
         return str(value)
     return value
Пример #8
0
    def test_IP_positive(self):
        ip4_str = "1.2.3.4"
        ip4_tuple = (0x1, 0x2, 0x3, 0x4)
        self.assertEqual(Convert.ipaddr_to_tuple_of_bytes(ip4_str), ip4_tuple)

        ip6_str = '1111::2222'
        ip6_tuple = (0x11, 0x11, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
                     0x0, 0x0, 0x0, 0x22, 0x22)
        self.assertEqual(Convert.ipaddr_to_tuple_of_bytes(ip6_str), ip6_tuple)

        ip6_str = '::'
        ip6_tuple = (0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
                     0x0, 0x0, 0x0, 0x0, 0x0)
        self.assertEqual(Convert.ipaddr_to_tuple_of_bytes(ip6_str), ip6_tuple)
Пример #9
0
    def upload_with_tftp(self, crashFileCtrlInfo, crashDataServerInfo):
        """
        upload the crash file in tftp mode
        :param tftp_options:
        :param crashFileCtrlInfo:
        :return:
        """
        tftp_options = {}
        if Convert.is_valid_ipv4_address(str(crashDataServerInfo.destIpAddress)):
            blksize = 1042
            tftp_options['blksize'] = int(blksize)
        elif Convert.is_valid_ipv6_address(str(crashDataServerInfo.destIpAddress)):
            blksize = 1048
            tftp_options['blksize'] = int(blksize)
        fileName = crashFileCtrlInfo.fileName
        if crashDataServerInfo.destPath.endswith('/'):
            destFileName = crashDataServerInfo.destPath + fileName
        else:
            destFileName = crashDataServerInfo.destPath + '/' + fileName
        srcFileName = CrashFileCtrlHandler.CORE_FILE_PATH + fileName
        self.logger.debug("Tftp upload destFileName:%s srcFileName:%s destIpAddress:%s" %
                          (destFileName, srcFileName, crashDataServerInfo.destIpAddress))
        try:

            self.update_crash_file_status(CrashFileCtrlHandler.STATUS_UPLOADINPROGRESS,
                                          crashFileCtrlInfo)
            tclient = tftpy.TftpClient(crashDataServerInfo.destIpAddress, int(self.TFTP_PORT),
                                       tftp_options)
            tclient.upload(str(destFileName), str(srcFileName))
            self.logger.debug("tftp upload %s complete", srcFileName)
            self.update_crash_file_status(CrashFileCtrlHandler.STATUS_UPLOADCOMPLETED,
                                          crashFileCtrlInfo)
        except TftpTimeout as err:
            self.update_crash_file_status(CrashFileCtrlHandler.STATUS_ERROR,
                                          crashFileCtrlInfo)
            self.logger.warn(
                "Error: File {0:s} fail to upload with TftpException {1:s}"
                .format(fileName, str(err)))
        except TftpException as err:
            self.update_crash_file_status(CrashFileCtrlHandler.STATUS_ERROR,
                                          crashFileCtrlInfo)
            self.logger.warn("Error: File %s fail to upload with TftpException %s" %
                             (fileName, str(err)))
        except Exception as err:
            self.update_crash_file_status(CrashFileCtrlHandler.STATUS_ERROR,
                                          crashFileCtrlInfo)
            self.logger.warn("Error: File %s fail to upload with TftpException %s" %
                             (fileName, str(err)))
            if tclient.context is not None:
                tclient.context.end()
Пример #10
0
 def _is_valid(self, value, name):
     try:
         fmt = self.rcptlv.child_dict_by_name[name]
         if fmt.value_is_mac():
             value = Convert.mac_to_tuple_of_bytes(value)
         elif fmt.value_is_ip_addr():
             value = Convert.ipaddr_to_tuple_of_bytes(value)
         fmt.validate(value)
         return True
     except GCPInvalidDataValueError:
         return False
     except ValueError:
         return False
     except TypeError:
         return False
Пример #11
0
    def _verify_dhcp_data(self):
        """Verify data from msg sent by DHCP client. Invalid or bad formatted
        data are removed.

        :return:

        """
        for descr, value in self.dhcp_data.ListFields():
            self.logger.info("%s = %s", descr.name, str(value))
            if descr.name in ['CCAPCores', 'LogServers', 'TimeServers']:
                # Walk list of IP addresses and check one-by-one
                for ip_addr in value[:]:
                    # Remove all invalid values
                    if not Convert.is_valid_ip_address(ip_addr):
                        self.logger.warn(
                            "Unexpected format of value: "
                            "%s = %s", descr.name, ip_addr)
                        value.remove(ip_addr)

            elif descr.name == 'TimeOffset':
                # Nothing to be checked (int32)
                pass
            else:
                self.logger.error("Unknown value found: %s", descr.name)

        self.store_dhcp_data()
Пример #12
0
    def _get_specific_core_para(rcp_msg, args):
        try:
            interface_local = None
            ccap_core_ip = None
            if rcp_msg.RcpMessageType in [
                    t_RcpMessage.CONNECT_CLOSE_NOTIFICATION,
                    t_RcpMessage.SESSION_INITIATED,
                    t_RcpMessage.REDIRECT_NOTIFICATION
            ]:
                core_para = json.loads(rcp_msg.parameter)
                ccap_core_ip = core_para[
                    'addr_remote'] if None is not core_para[
                        'addr_remote'] else ''
                interface_local = core_para[
                    'interface_local'] if None is not core_para[
                        'interface_local'] else ''
            elif rcp_msg.RcpMessageType in [
                    t_RcpMessage.RPD_CONFIGURATION,
                    t_RcpMessage.RPD_CONFIGURATION_DONE,
                    t_RcpMessage.IRA_RECEIVED, t_RcpMessage.REX_RECEIVED
            ]:
                if args:
                    session, transaction_identifier, trans_id = args
                    interface_local = session.get_descriptor().interface_local
                    ccap_core_ip = Convert.format_ip(
                        session.get_descriptor().addr_remote)
            specific = (interface_local, ccap_core_ip)
            return specific

        except Exception as e:
            return None
Пример #13
0
    def get_gcp_info(self, args=None):
        """
        :return: gcp info

        """
        gcp_info = []
        try:
            agent_id = ProcessAgent.AGENTTYPE_GCP
            for ccap_core_id in CCAPCore.ccap_core_db:
                ccap_core = CCAPCore.ccap_core_db[ccap_core_id]
                status = ccap_core.agent_status[agent_id]
                para = ccap_core.parameters
                principal = ccap_core.is_principal
                is_ipv6 = Convert.is_valid_ipv6_address(ccap_core.ccap_core_network_address)
                family = (socket.AF_INET, socket.AF_INET6)[is_ipv6]
                if agent_id in para and ';' in para[agent_id]:
                    intf, core_ip = para[agent_id].split(';')
                    local_ip = SysTools.get_ip_address(str(intf), family=family)
                    value = {
                        "Core-ID": ccap_core_id, "Core-IP": core_ip, "Local-IP": local_ip,
                        "Principal": 'Yes' if principal == CoreDescription.CORE_ROLE_PRINCIPAL else 'No',
                        'Status': status}

                    gcp_info.append(value)
            return True, gcp_info
        except Exception as e:
            return False, str(e)
Пример #14
0
    def get_dhcp_info(self, args=None):
        """
        :return: dhcp info

        """
        dhcp_info = {'Interface': [], 'Details': []}
        try:
            nic_info = net_if_addrs()
            for intf in self.mgr.dhcp_parameter:
                netmask = '0.0.0.0'
                is_ipv6 = Convert.is_valid_ipv6_address(self.mgr.dhcp_parameter[intf]['CCAPCores'][0])
                family = (socket.AF_INET, socket.AF_INET6)[is_ipv6]
                for item in nic_info[intf]:
                    if item.family == family:
                        netmask = item.netmask
                        break
                local_ip = SysTools.get_ip_address(str(intf), family=family)
                value = {"Interface": intf, 'IP-Address': local_ip, "Subnet-Mask": netmask}
                dhcp_info['Interface'].append(value)
                addr_type = "IPv4"
                if is_ipv6:
                    if self.mgr.dhcp_parameter[intf]['Slaac']:
                        addr_type = "IPv6<Stateless>"
                    else:
                        addr_type = "IPv6<Stateful>"
                intf_dhcp_parameter = self.mgr.dhcp_parameter[intf]
                intf_dhcp_parameter["AddrType"] = addr_type
                dhcp_info['Details'].append((intf, intf_dhcp_parameter))

            return True, dhcp_info
        except Exception as e:
            return False, str(e)
Пример #15
0
    def config_rsyslog(self, address):
        """Set address of remote log server,support rsyslog.

        - For now only one log-server(rsyslog) is supported (TCP is used)

        :param address: rsyslog server IP address (v4 or v6) or None to
         disable remotelogging feature
        :param logging_level: string or None
        :param rotate_size: rotatation size for log file
        :return:

        """
        if None is address:
            # disable remote logging feature
            # restart rsyslog
            self.restart_rsyslog()
            return

        if not Convert.is_valid_ip_address(address):
            self.logger.warning(
                "Invalid IP address provided for remote logging: %s", address)
            return

        try:
            # enable remote logging feature
            self.config_rsyslog_remote(address)
            # restart rsyslogd
            self.restart_rsyslog()
        except (OSError, ValueError):
            self.logger.error("Failed remote logging configuration")
Пример #16
0
    def connect(self, ipv4_addr):
        """Creates socket and connects it to the IT API server identified by
        IPv4 address.

        :param ipv4_addr: IPv4 address of the IT API server's interface.
        :type ipv4_addr: String
        :returns: True if connected successfully, False otherwise.

        """
        if None is ipv4_addr:
            raise AttributeError("No IPv4 address of server passed")

        if not Convert.is_valid_ipv4_address(ipv4_addr):
            self.logger.error("Invalid IPv4 address passed: %s", ipv4_addr)
            return False

        port = DEFAULT_IT_API_PORT
        self.logger.debug("Openning socket and connecting to server: %s:%s",
                          ipv4_addr, port)

        ctx = zmq.Context.instance()
        self.it_api_socket = ctx.socket(zmq.REQ)
        self.it_api_socket.connect("tcp://{}:{}".format(ipv4_addr, port))

        self.logger.info("Connected to IT API server: %s:%s", ipv4_addr, port)

        return True
Пример #17
0
    def update_mcast_session_to_db(self, session):
        """

        :param session: (local_ip, remote_ip, local_session, remote_session)
        :return:
        """
        try:
            local_ip, remote_ip, local_session, remote_session, = session
            record = DepiMcastSessionRecord()
            record.updateDepiMcastSessionKey(
                IpAddrType=DepiMcastSessionRecord.get_inetaddr_type(
                    self.grp_ip),
                GroupIpAddr=self.grp_ip,
                SrcIpAddr=self.src_ip,
                SessionId=local_session)

            record.updateDepiMcastSessionData(
                LocalLcceIpAddr=local_ip,
                RemoteLcceIpAddr=remote_ip,
                JoinTime=Convert.pack_timestamp_to_string(self.lastchange))
            record.write()
        except Exception as e:
            self.logger.warning(
                "%s failed to update ses:%s into db for exception %s",
                str(self), str(session), str(e))
Пример #18
0
    def create_ipv4_ipv6_record(self, test_count=1000):
        sessRec = DepiMcastSessionRecord()
        print "#########: write %s session in db." % (test_count * 2)
        current_time = time.time()
        print "current time is: " + str(
            datetime.datetime.fromtimestamp(current_time))
        for test_session in range(0, test_count):
            sessRec.updateDepiMcastSessionKey(IpAddrType=1,
                                              GroupIpAddr="10.79.31.1",
                                              SrcIpAddr="10.90.31.1",
                                              SessionId=test_session + 1)
            test_time = Convert.pack_timestamp_to_string(time.time())

            sessRec.updateDepiMcastSessionData("10.1.1.1", "1.1.1.1",
                                               time.time())
            sessRec.write()
            sessRec.updateDepiMcastSessionKey(IpAddrType=2,
                                              GroupIpAddr="2001::1",
                                              SrcIpAddr="2001::2",
                                              SessionId=test_session + 1)

            sessRec.updateDepiMcastSessionData("2001::1", "2001::1", test_time)
            sessRec.write()
        current_time = time.time()
        print "end time is: " + str(
            datetime.datetime.fromtimestamp(current_time))
        return True
Пример #19
0
 def read_ipv6_scope(interface, ip):
     scope = 11  # unknown scope
     ipv6_info = open("/proc/net/if_inet6", "r").readlines()
     for info in ipv6_info:
         if interface in info:
             if_ip = Convert.format_proc_address(info.split(' ')[0])
             if if_ip == ip:
                 scope = int(info.split(' ')[3])
     return scope
Пример #20
0
 def test_MAC_negative(self):
     self.assertIsNone(Convert.mac_to_tuple_of_bytes(1))
     self.assertIsNone(Convert.mac_to_tuple_of_bytes(""))
     self.assertIsNone(Convert.mac_to_tuple_of_bytes("11:"))
     self.assertIsNone(Convert.mac_to_tuple_of_bytes("01:02:03:04:05"))
     self.assertIsNone(Convert.mac_to_tuple_of_bytes("GG:02:03:04:05:06"))
     self.assertIsNone(Convert.mac_to_tuple_of_bytes("125:02:03:04:05"))
Пример #21
0
    def change_eth1_ip_addr(self, ip_addr):
        """Change IP address on eth1 NOTE: Do not forget to restart services if
        already running.

        :param ip_addr: IP address to be assigned to eth1 interface. In format:
         1.2.3.4. This is applicable only for 'external' images.
         RPD image requires DHCP managed eth1 interface. Support for mask and
         gateway change can be added in the future.
        :return:

        """
        if not Convert.is_valid_ip_address(ip_addr):
            raise TypeError("Invalid IP address string provided: %s", ip_addr)
        is_ipv4 = Convert.is_valid_ipv4_address(ip_addr)
        if is_ipv4:
            self.ip_addresses = (self.ip_addresses[0], ip_addr)
            net_name = 'lan'
        else:
            self.ipv6_addresses = (self.ipv6_addresses[0], ip_addr)
            net_name = 'lanV6'
        # Check if protocol on eth1 is set to static (truth only on external)
        try:
            proto = self.run_command(
                "uci show network.{}.proto".format(net_name))
            if proto[0].strip().split('=')[1] != '\'static\'':
                raise TypeError("IP address is not static - not server side?")
            # Configure IP address provided
            if is_ipv4:
                cmd = "uci set network.{net}.ipaddr={ip_addr}; "
            else:
                cmd = "uci set network.{net}.ip6addr={ip_addr}/64; "
            # Commit changes to network configuration
            cmd += "uci commit network; "
            # Apply config to interface
            cmd += "ifup {net}"
            self.run_command(cmd.format(net=net_name, ip_addr=ip_addr))
        except subprocess.CalledProcessError as exception:
            self.logger.error(
                "Failed to set IP address to host: %s", exception.message)
            return
Пример #22
0
    def test_bytes_convert(self):
        illegal_var = '01:02:03:192.168.0.1:0a:0b:'
        try:
            Convert.bytes_to_mac_str(illegal_var)
        except TypeError:
            pass
        else:
            self.fail('illegal mac been converted')

        try:
            Convert.bytes_to_ipv4_str(illegal_var)
        except TypeError:
            pass
        else:
            self.fail('illegal ipv4 been converted')

        try:
            Convert.bytes_to_ipv6_str(illegal_var)
        except TypeError:
            pass
        else:
            self.fail('illegal ipv6 been converted')

        try:
            Convert.bytes_to_ip_addr(illegal_var)
        except TypeError:
            pass
        else:
            self.fail('illegal ip been converted')

        # try:
        ret = Convert.mac_to_tuple_of_bytes('-1:-2:-3:-4:-5')
        # except ValueError:
        #    pass
        # else:
        #    self.fail('illegal mac been converted: %s' % ret)
        self.assertIsNone(ret, 'illegal mac been converted: %s' % ret)

        self.assertFalse(Convert.is_valid_ipv4_address('a.b.c.d'))
Пример #23
0
    def test_IP_negative(self):

        self.assertIsNone(Convert.ipaddr_to_tuple_of_bytes(1))
        self.assertIsNone(Convert.ipaddr_to_tuple_of_bytes("1.2.3.4.5"))
        self.assertIsNone(Convert.ipaddr_to_tuple_of_bytes(""))
        self.assertIsNone(Convert.ipaddr_to_tuple_of_bytes("1.2.3..4"))
        self.assertIsNone(Convert.ipaddr_to_tuple_of_bytes("1.2.256.4"))
        self.assertIsNone(Convert.ipaddr_to_tuple_of_bytes(":::"))
Пример #24
0
 def getLocalIp(core_ip):
     intf = 'eth0'
     family = socket.AF_INET
     if core_ip is not None:
         is_ipv6 = Convert.is_valid_ipv6_address(core_ip)
         family = (socket.AF_INET, socket.AF_INET6)[is_ipv6]
     if core_ip is None or core_ip == "127.0.0.1" or core_ip == "::1":
         intf = 'eth0'
     else:
         intf = SysTools.get_interface()
     local_ip = SysTools.get_ip_address(intf, family)
     if local_ip is None:
         return globalSettings.L2tpv3GlobalSettings.LocalIPAddress
     return local_ip
Пример #25
0
    def test_readwrite(self):
        sessRec = DepiMcastSessionRecord()
        sessRec.updateDepiMcastSessionKey(IpAddrType=1,
                                          GroupIpAddr="10.79.31.1",
                                          SrcIpAddr="10.79.31.1",
                                          SessionId=1)
        self.assertEquals(sessRec.index.IpAddrType, 1)
        self.assertEquals(sessRec.index.SrcIpAddr, "10.79.31.1")
        self.assertEquals(sessRec.index.SessionId, 1)
        sessRec.write()

        # get_all
        ret = []
        for ses in sessRec.get_all():
            ret.append(ses)
        self.assertEquals(len(ret), 1)

        sessRec = None
        sessRec = DepiMcastSessionRecord()
        sessRec.updateDepiMcastSessionKey(IpAddrType=1,
                                          GroupIpAddr="10.79.31.1",
                                          SrcIpAddr="10.79.31.1",
                                          SessionId=1)
        sessRec.read()
        self.assertEquals(sessRec.index.IpAddrType, 1)
        self.assertEquals(sessRec.index.GroupIpAddr, "10.79.31.1")
        self.assertEquals(sessRec.index.SrcIpAddr, "10.79.31.1")
        self.assertEquals(sessRec.index.SessionId, 1)
        self.assertEquals(sessRec.JoinTime, "")
        self.assertEquals(sessRec.LocalLcceIpAddr, "")
        self.assertEquals(sessRec.RemoteLcceIpAddr, "")

        # modify the property
        currtime = Convert.pack_timestamp_to_string(time.time())
        sessRec.JoinTime = currtime
        sessRec.write()
        sessRec.read()
        self.assertEquals(sessRec.index.IpAddrType, 1)
        self.assertEquals(sessRec.index.GroupIpAddr, "10.79.31.1")
        self.assertEquals(sessRec.index.SrcIpAddr, "10.79.31.1")
        self.assertEquals(sessRec.index.SessionId, 1)
        self.assertEquals(sessRec.JoinTime, currtime)
        self.assertEquals(sessRec.LocalLcceIpAddr, "")
        self.assertEquals(sessRec.RemoteLcceIpAddr, "")

        # get_all
        ret = []
        for ses in sessRec.get_all():
            ret.append(ses)
        self.assertEquals(len(ret), 1)
Пример #26
0
    def test_performance(self):
        sessRec = DepiMcastSessionRecord()
        test_count = 1000
        print "#########: perfermance test about %s session in store" % test_count
        current_time = time.time()
        print "current time is: " + str(
            datetime.datetime.fromtimestamp(current_time))
        for test_session in range(0, test_count):
            sessRec.updateDepiMcastSessionKey(IpAddrType=1,
                                              GroupIpAddr="10.79.31.1",
                                              SrcIpAddr="10.90.31.1",
                                              SessionId=test_session)
            test_time = Convert.pack_timestamp_to_string(time.time())
            sessRec.updateDepiMcastSessionData("10.1.1.1", "1.1.1.1",
                                               test_time)
            sessRec.write()
        print "Write " + str(test_count) + " records need : " + str(
            time.time() - current_time)
        current_time = time.time()
        ret = []
        for record in sessRec.get_next_n(count=test_count):
            ret.append(record)
        self.assertEquals(len(ret), test_count)
        print "get_next_n " + str(test_count) + " records need : " + str(
            time.time() - current_time)

        print "current time is: " + str(
            datetime.datetime.fromtimestamp(time.time()))
        current_time = time.time()
        ret = []
        for record in sessRec.get_next_n(count=20):
            ret.append(record)
        self.assertEquals(len(ret), 20)
        end_time = time.time()
        print "get_next_n " + str(20) + " records need : " + str(end_time -
                                                                 current_time)
        print "End time is: " + str(datetime.datetime.fromtimestamp(end_time))
        self.assertEquals(len(ret), 20)

        current_time = time.time()
        ret = []
        for ses in sessRec.get_all():
            ret.append(ses)
        print "get_next_all " + str(test_count) + " records need : " + str(
            time.time() - current_time)
        self.assertEquals(len(ret), test_count)
Пример #27
0
 def upload_with_http(self, crashFileCtrlInfo, crashDataServerInfo):
     """
     upload the crash file in http mode
     :param crashFileCtrlInfo:
     :return:
     """
     corefilepath = CrashFileCtrlHandler.CORE_FILE_PATH + crashFileCtrlInfo.fileName
     self.logger.debug("Upload crash file %s in http mode" % corefilepath)
     self.update_crash_file_status(CrashFileCtrlHandler.STATUS_UPLOADINPROGRESS,
                                   crashFileCtrlInfo)
     if Convert.is_valid_ipv6_address(
             str(crashDataServerInfo.destIpAddress)):
         httpServer = "[" + str(crashDataServerInfo.destIpAddress) + "]"
     else:
         httpServer = str(crashDataServerInfo.destIpAddress)
     try:
         dataForm = MultiDataForm()
         with open(corefilepath, 'rb') as uploadFile:
             dataForm.add_file('file', crashFileCtrlInfo.fileName, uploadFile)
             if not str(crashDataServerInfo.destPath):
                 url = 'http://' + httpServer + ':' + str(self.HTTP_PORT)
             else:
                 url = 'http://' + httpServer + ':' + str(self.HTTP_PORT) + \
                       str(crashDataServerInfo.destPath)
             self.logger.info("Http url is %s" % url)
             request = urllib2.Request(url)
             body = str(dataForm)
             request.add_header('Content-type', dataForm.get_content_type())
             request.add_header('Content-length', len(body))
             request.add_data(body)
             urllib2.urlopen(request).read()
             self.logger.debug("Http upload %s compplete" % (crashFileCtrlInfo.fileName))
             self.update_crash_file_status(CrashFileCtrlHandler.STATUS_UPLOADCOMPLETED,
                                           crashFileCtrlInfo)
     except urllib2.HTTPError as e:
         self.update_crash_file_status(CrashFileCtrlHandler.STATUS_ERROR,
                                       crashFileCtrlInfo)
         self.logger.warn("HTTP Error %s fail to upload: %s" % (corefilepath, str(e)))
     except urllib2.URLError as e:
         self.update_crash_file_status(CrashFileCtrlHandler.STATUS_ERROR,
                                       crashFileCtrlInfo)
         self.logger.error("HTTP Error %s fail to upload: %s" % (corefilepath, str(e)))
     except Exception as e:
         self.update_crash_file_status(CrashFileCtrlHandler.STATUS_ERROR,
                                       crashFileCtrlInfo)
         self.logger.error("HTTP Error %s fail to upload: %s" % (corefilepath, str(e)))
Пример #28
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--rpd-image', required=True, action='append')
    parser.add_argument('--server-image')
    parser.add_argument('--server-addr', help='IP address to be used for eth1')
    parser.add_argument('--disable-terminal', action='store_true')
    parser.add_argument('--destroy-before',
                        action='store_true',
                        help='Destroy all VMs and networks at the beginning')
    args = parser.parse_args()
    # Check arguments
    for image_path in args.rpd_image:
        if not os.path.exists(image_path):
            parser.error("RPD image file not found: {}".format(image_path))
    if args.server_image is not None:
        if not os.path.exists(args.server_image):
            parser.error("Server image file not found: {}".format(
                args.server_image))
    if args.server_addr is not None and \
            not Convert.is_valid_ip_address(args.server_addr):
        parser.error("Server IP address is not valid: {}".format(
            args.server_addr))
    # Create topology and start VMs
    topology = Topology()
    if args.destroy_before:
        topology.stop_all_force()
    if args.server_image is not None:
        topology.create_vm(args.server_image, name='server', start=False)
    for idx, image_path in enumerate(args.rpd_image):
        topology.create_vm(image_path, name='RPD' + str(idx + 1), start=False)
    topology.start_and_wait_for_all()
    # Assign server address
    if None not in (args.server_addr, args.server_image):
        topology.nodes['server'].change_eth1_ip_addr(args.server_addr)
    # Open terminals or print IP addresses
    for node in topology.nodes.values():
        if not args.disable_terminal:
            node.open_terminal()
        else:
            print "VM: '{}': '{}'".format(node.name, node.ip_addresses[0])
    print "Topology should be ready, press anything to kill it"
    raw_input()
    # Destroy topology and delete created files
    topology.cleanup()
    exit(EX_OK)
Пример #29
0
 def test_updateDepiMcastSessionData(self):
     sessRec = DepiMcastSessionRecord()
     sessRec.updateDepiMcastSessionKey(IpAddrType=1,
                                       GroupIpAddr="10.79.31.1",
                                       SrcIpAddr="10.79.31.1",
                                       SessionId=1)
     self.assertEquals(sessRec.index.IpAddrType, 1)
     self.assertEquals(sessRec.index.SrcIpAddr, "10.79.31.1")
     self.assertEquals(sessRec.index.SessionId, 1)
     testIP1 = "127.0.0.1"
     testIP2 = "127.0.0.2"
     testTime = Convert.pack_timestamp_to_string(time.time())
     sessRec.updateDepiMcastSessionData(LocalLcceIpAddr=testIP1,
                                        RemoteLcceIpAddr=testIP2,
                                        JoinTime=testTime)
     self.assertEquals(sessRec.LocalLcceIpAddr, testIP1)
     self.assertEquals(sessRec.RemoteLcceIpAddr, testIP2)
     self.assertEquals(sessRec.JoinTime, testTime)
Пример #30
0
 def learn_arp_us_l2tp_session(self, _):
     arp_addr_dict = \
         L2tpv3GlobalSettings.L2tpv3GlobalSettings.l2tp_hal_client.arp_addr_dict
     try:
         if self.pingSocket is None:
             self.pingSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW,
                                             socket.getprotobyname("icmp"))
         for dest_addr in arp_addr_dict.keys():
             addr_family = (socket.AF_INET if Convert.is_valid_ipv4_address(dest_addr)
                            else socket.AF_INET6)
             if addr_family == socket.AF_INET6:
                 continue
             self.pingSocket.sendto(
                 PingPackage.pack_package(1, PingPackage.ICMP_DATA_STR, False),
                 (dest_addr, 80))
     except Exception as ex:
         self.logger.warning("Got exception when send the arp package: %s",
                             str(ex))