Пример #1
0
def demoL2tp():
    print "demoL2tp thread start!"
    setup_logging('HAL', filename="hal.log", logging_level=logging.DEBUG)
    drv_logger = logging.getLogger("demoL2tp")
    drv_logger.info("hello demoL2tp Log")

    dispatcher = Dispatcher()
    l2tp_dispatcher = L2tpv3Dispatcher(
        dispatcher,
        local_addr=None,
        # since we don't create global listen, set it to None
        create_global_listen=False)
    L2tpv3GlobalSettings.Dispatcher = l2tp_dispatcher

    # setup the halclient
    SupportedCfgMsg = list()
    SupportedCfgMsg.append(MsgTypeVspAvpExchange)
    notificationMsg = list()
    notificationMsg.append(MsgTypeL2tpv3SessionStatusNotification)
    hal_client = L2tpHalClient("L2TP_HAL_CLIENT",
                               "the HAL client of L2TP feature", "1.0",
                               tuple(notificationMsg), dispatcher,
                               SupportedCfgMsg)
    L2tpv3GlobalSettings.l2tp_hal_client = hal_client
    hal_client.start(l2tp_dispatcher.receive_hal_message)
    if L2tpv3GlobalSettings.l2tp_hal_client:
        print("setup l2tp hal client successfully")

    if L2tpv3GlobalSettings.Dispatcher:
        print("l2tp_dispatcher is OK")
        print l2tp_dispatcher

    l2tp_dispatcher.dispatcher.loop()
    print "demoL2tp thread done!"
Пример #2
0
    def setUp(self):
        setup_logging(("PROVISION", "DHCP"), filename="provision_dhcp.log")
        self.agent = DhcpAgent(simulate_mode=True)
        self.agent.ccap_cores['CORE-1234567890'] = {
            "mgr": "MGR-1234567890",
        }
        self.agent.dhcp['eth0'] = {
            "status": self.agent.DOWN,
            "requester": [
                'CORE-1234567890',
            ],
            "lastChangeTime": 1,
            "transport": self.agent.process_transport,
            "initiated_by": None,
            "initiated": False,
        }

        path = "ipc:///tmp/rcp.sock"
        transport = Transport(path, Transport.PUSHSOCK,
                              Transport.TRANSPORT_CLIENT)

        # Add the fsm to our internal database
        self.agent.mgrs["MGR-1234567890"] = {
            "transport": transport,
            "name": "DHCP",
            "para": {},
            "path": path,
        }

        # init agent dhcpv6 process
        self.agent.start_dhcpv6('eth0')
Пример #3
0
def demoRCP():
    print "demoRCP thread start!"
    setup_logging('HAL', filename="hal.log", logging_level=logging.DEBUG)
    drv_logger = logging.getLogger("demoRCP")
    drv_logger.info("hello demoRCP Log")
    RcpGlobalSettings.gDispatcher = Dispatcher()
    rcpProcess = RcpHalProcess("ipc:///tmp/_test_rcp_to_hal.tmp",
                               RcpGlobalSettings.gDispatcher)

    RcpGlobalSettings.hal_ipc = RcpHalIpc("RCP-HalClient",
                                          "This is a RCP test application",
                                          "1.9.0", (1, 100, 102),
                                          rcpProcess,
                                          "../hal/conf/ClientLogging.conf",
                                          shadowLayerConf=TMP_CFG_PATH)

    try:
        if None is not RcpGlobalSettings.hal_ipc:
            RcpGlobalSettings.hal_ipc.start(
                rcpProcess.orchestrator.config_operation_rsp_cb,
                rcpProcess.orchestrator.notification_process_cb)
            RcpGlobalSettings.gDispatcher.loop()
        else:
            print("demoRCP: hal_ipc is NONE")
    except Exception:
        print("socket is destroyed, demoRCP terminated")

    print "demoRCP thread done!"
Пример #4
0
 def test_rpd_logging(self):
     # os.system('export LOG_PATH=/tmp/log_test')
     os.environ['LOG_PATH'] = '/tmp/log_test'
     self.logger.critical(os.getenv('LOG_PATH'))
     setup_logging("HAL", filename="test.log", env_key='LOG_PATH')
     if os.path.exists('/tmp/log_test'):
         os.remove('/tmp/log_test')
Пример #5
0
    def setUp(self):
        create_db_conf()
        start_redis()
        RCPDB.DB_CFG_FILE = CONF_FILE
        setup_logging(("PROVISION", "GCP"), filename="provision_rcp.log")
        self.agent = RcpOverGcp()
        self.agent.ccap_cores['CORE-1234567890'] = {"mgr": "MGR-1234567890", }
        self.agent.rcp[('eth0', '1.1.1.1')] = {
            "status": self.agent.DOWN,
            "requester": ['CORE-1234567890', ],
            "lastChangeTime": 1,
        }

        path = "ipc:///tmp/rcp.sock"
        transport = Transport(
            path, Transport.PUSHSOCK, Transport.TRANSPORT_CLIENT)

        # Add the fsm to our internal database
        self.agent.mgrs["MGR-1234567890"] = {
            "transport": transport,
            "name": "RCP",
            "para": {},
            "path": path,
        }

        seq = RCPSequence(gcp_msg_def.DataStructREQ,
                          rcp_tlv_def.RCP_MSG_TYPE_REX,
                          1,
                          rcp_tlv_def.RCP_OPERATION_TYPE_READ,
                          unittest=True)
        self.agent.rcp_req_group[(1, '1.1.1.1')] = (seq, None, 'transaction_identifier', 'trans_id', time.time() - 5)
Пример #6
0
 def setUp(self):
     self.connection = ""
     self.dispatcher = ""
     self.LocalAddr = "127.0.0.1"
     # self.LocalAddrList = {"127.0.0.2"}
     # self.remoteAddrList = {"127.0.0.1","127.0.0.2"}
     self.remoteAddrList = {"127.0.0.2"}
     setup_logging('L2TP')
Пример #7
0
    def setUpClass(cls):
        setup_logging("GCP", filename="rcp.log")

        cls.dispatcher = Dispatcher()
        cls.desc = GCPSlaveDescriptor(addr_master='localhost',
                                      interface_local='local')
        cls.session = RCPSlaveSession(cls.desc, cls.dispatcher, fake_cb,
                                      fake_cb, fake_cb)
Пример #8
0
 def setUpClass(cls):
     setup_logging("PROVISION", "test.log")
     cls.dispatcher = Dispatcher()
     cls.mgr = FakeManager()
     currentPath = os.path.dirname(os.path.realpath(__file__))
     dirs = currentPath.split("/")
     rpd_index = dirs.index("testing") + 1
     cls.rootpath = "/".join(dirs[:rpd_index])
Пример #9
0
def demoDrvmain():
    print "demoDrvmain thread start!"
    setup_logging('HAL', filename="hal.log", logging_level=logging.DEBUG)
    drv_logger = logging.getLogger("DrvMain")
    drv_logger.info("hello demo DrvMain Log")
    driver = OpenRpdDriver("openrpd_generic_driver",
                           "This is a Generic OpenRPD Driver", "1.0.0",
                           (0, 10000), (2, 3, 4))
    driver.start()
    print "demoDrvmain thread done!"
Пример #10
0
    def setUpClass(cls):
        setup_logging("L2TP")
        setup_test_redis()

        # Construct the API transport path
        ApiPath = L2tpv3GlobalSettings.L2tpv3GlobalSettings.APITransportPath
        print ApiPath
        cls.api = L2tpv3API(ApiPath)
        for key in Mcast.McastDb.keys():
            Mcast.McastDb[key].close()
Пример #11
0
def demoDrvmain():
    print "demoDrvmain thread start!"
    setup_logging('HAL', filename="hal.log", logging_level=logging.DEBUG)
    drv_logger = logging.getLogger("DrvMain")
    drv_logger.info("hello demo DrvMain Log")
    interestedNotification = list()
    interestedNotification.append(MsgTypeVspAvpExchange)
    driver = OpenRpdDriver("openrpd_generic_driver",
                           "This is a Generic OpenRPD Driver", "1.0.0",
                           tuple((0, 5000)), (2, 3, 4), interestedNotification)
    driver.start()
    print "demoDrvmain thread done!"
Пример #12
0
    def setUpClass(cls):
        # open logger
        setup_logging("L2TP")
        setup_test_redis()

        cls.conn_address = '127.0.0.1'
        global_dispatcher = Dispatcher()
        dispatcher = L2tpv3Dispatcher(
            global_dispatcher, cls.conn_address, False, None)
        L2tpv3GlobalSettings.Dispatcher = dispatcher
        # setup the halclient

        notification_list = list()
        notification_list.append(
            HalConfigMsg.MsgTypeL2tpv3SessionStatusNotification)

        cls.hal_client = L2tpHalClient("L2TP_HAL_CLIENT",
                                       "the HAL client of L2TP feature",
                                       "1.0", tuple(L2tpHalClient.notification_list.keys()), global_dispatcher)

        cls.hal_client.handler = dispatcher.receive_hal_message
        cls.conn = L2tpConnection(
            6661, 6662, cls.conn_address, cls.conn_address)
        cls.session = L2tpv3Session(6661, 6662, 'receiver', cls.conn)
        cls.conn.addSession(cls.session)
        localSessionId = L2tpv3RFC3931AVPs.LocalSessionID(6661)
        remoteSessionId = L2tpv3RFC3931AVPs.RemoteSessionID(6662)
        remoteEnd = L2tpv3RFC3931AVPs.RemoteEndID(
            (((0, 3, 0), 0), ((0, 3, 1), 1), ((0, 3, 2), 2)))
        remoteEnd_1 = L2tpv3RFC3931AVPs.RemoteEndID(
            (((0, 3, 3), 3), ((0, 3, 4), 4), ((0, 3, 5), 5)))
        pw_type = L2tpv3RFC3931AVPs.L2SpecificSublayer(3)
        DepiL2SpecificSublayerSubtype = L2tpv3CableLabsAvps.DepiL2SpecificSublayerSubtype(3)
        LocalMTUCableLabs = L2tpv3CableLabsAvps.LocalMTUCableLabs(1500)
        DepiRemoteMulticastJoin = L2tpv3CableLabsAvps.DepiRemoteMulticastJoin(("5.5.5.1", "229.1.1.255"))
        DepiResourceAllocReq = L2tpv3CableLabsAvps.DepiResourceAllocReq(((0, 1), (1, 2)))
        UpstreamFlow = L2tpv3CableLabsAvps.UpstreamFlow(((0, 1), (1, 2)))

        cls.session.avps_icrq.append(localSessionId)
        cls.session.avps_icrq.append(remoteSessionId)
        cls.session.avps_icrq.append(remoteEnd)
        cls.session.avps_icrq.append(remoteEnd_1)
        cls.session.avps_icrq.append(DepiL2SpecificSublayerSubtype)
        cls.session.avps_icrq.append(LocalMTUCableLabs)
        cls.session.avps_icrq.append(pw_type)
        cls.session.avps_icrq.append(DepiRemoteMulticastJoin)
        cls.session.avps_icrq.append(DepiResourceAllocReq)
        cls.session.avps_icrq.append(UpstreamFlow)
Пример #13
0
 def setUpClass(cls):
     setup_logging("GCPP Unit test")
     setup_test_redis()
     cls.fwdCfg = StaticL2tpProvision()
     cls.ApiPath = \
         L2tpv3GlobalSettings.L2tpv3GlobalSettings.APITransportPath
     cls.api = L2tpv3API(cls.ApiPath)
     global_dispatcher = Dispatcher()
     cls.hal_client = L2tpHalClient("L2TP_HAL_CLIENT",
                                    "the HAL client of L2TP feature", "1.0",
                                    tuple(
                                        L2tpHalClient.notification_list.keys()),
                                    global_dispatcher)
     cls.hal_client.pushSock = HalTransport(
         HalTransport.HalTransportClientAgentPull,
         HalTransport.HalClientMode, index=19,
         socketMode=HalTransport.HalSocketPushMode,
         disconnectHandlerCb=None)
Пример #14
0
def demoHalmain():
    print "demoHalmain thread start!"
    HalGlobal.StopHal = False
    setup_logging('HAL', filename="hal.log")
    HalMain.logger = logging.getLogger("HalMain")
    HalMain.logger.info("hello demo HalMain Log")
    HalGlobal.gDispatcher = HalDispatcher()
    HalMain._mainLoop()
    print "clear Manager status!"
    keys = HalGlobal.gClientDB.keys()
    for clientId in keys:
        HalGlobal.gClientMgr.disconnectCb(
            HalGlobal.gClientDB[clientId]['agent'])
    if HalGlobalStats.NrClient != 0:
        raise Exception(
            "Cannot destroy the hal Main, reason: clients is not cleared")

    HalGlobal.StopHal = False
    print "demoHalmain thread done!"
Пример #15
0
    def __init__(self, gpb_msg_class):
        """Creates dispatcher if not passed and initializes instance.
        TODO params dont match

        :param gpb_msg_class: A class of GPB messages which will be exchanged.
        :param rx_cb: User's RX callback which is called when some GPB message
         was received. The callback expects the GPB message as argument.
        :param disp: Dispatcher. New dispatcher is created if None is passed.

        """
        if None is gpb_msg_class:
            raise AttributeError("No any GPB message class passed")

        if gpb_msg_class not in (t_ItApiRpdMessage,
                                 t_ItApiServiceSuiteMessage):
            raise AttributeError("Invalid GPB message class passed")

        self.gpb_msg_class = gpb_msg_class
        self.it_api_socket = None
        setup_logging("ItManager", filename="IT.log")
Пример #16
0
    def setUpClass(cls):
        cls.logger.info("start setup...")
        cls.logger.info("************************************************")
        cls.logger.info("***                setUpClass:               ***")
        cls.logger.info("************************************************")
        # open logger
        setup_logging("L2TP")
        # use the localhost as the default IP address
        global_dispatcher = Dispatcher()
        dispatcher = L2tpv3Dispatcher(
            global_dispatcher,
            L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress,
            create_global_listen=False)
        cls.dispatcher = L2tpv3GlobalSettings.L2tpv3GlobalSettings.Dispatcher = dispatcher

        # create the connection
        cls.connection = L2tpv3Connection.L2tpConnection(
            666, 666, L2tpv3GlobalSettings.L2tpv3GlobalSettings.LocalIPAddress)

        # instance the transport
        cls.transport = cls.connection.transport
Пример #17
0
    def __init__(self, gpb_msg_class, rx_cb, disp=None):
        """Opens socket on the IT API port and listen for GPB messages.

        :param gpb_msg_class: A class of GPB messages which will be exchanged.
        :param rx_cb: User's RX callback which is called when some GPB message
         was received. The callback expects the GPB message as argument.
        :param disp: Dispatcher. New dispatcher is created if None is passed.

        """
        if None is gpb_msg_class:
            raise AttributeError("No GPB message class specified")

        if gpb_msg_class not in [
                t_ItApiRpdMessage, t_ItApiServiceSuiteMessage
        ]:
            raise AttributeError("Unknown GPB message class passed")

        if None is rx_cb:
            raise AttributeError("No rx_cb specified")

        if None is disp:
            self.disp = dispatcher.Dispatcher()
        else:
            self.disp = disp

        self.rx_cb = rx_cb
        self.gpb_msg_class = gpb_msg_class
        setup_logging("ItManager", filename="IT.log")

        ctx = zmq.Context.instance()
        self.it_api_socket = ctx.socket(zmq.REP)
        self.it_api_socket.bind("tcp://*:{}".format(DEFAULT_IT_API_PORT))
        self.disp.fd_register(self.it_api_socket.getsockopt(zmq.FD),
                              self.disp.EV_FD_IN, self._it_api_socket_handler)

        self.logger.debug("Listening for testing requests")
Пример #18
0
 def setUpClass(cls):
     setup_logging("PROVISION", filename="provision_mgr_process.log")
Пример #19
0
        mgr._handle_mgr_gcp_event(event_request_rsp.mgr_event)

        print 'Redundant core Delete'
        # standby core mode active
        caps = {
            "ActiveCoreIpAddress": '1.1.1.10',
            "StandbyCoreIpAddress": '1.1.1.5',
            'interface': 'eth0',
            "operation": 1
        }
        ccap_core[0].is_active = CoreDescription.CORE_MODE_ACTIVE
        event_request_rsp.mgr_event.data = json.dumps("Ha/" + json.dumps(caps))
        mgr._handle_mgr_gcp_event(event_request_rsp.mgr_event)
        # standby core mode standby
        caps = {
            "ActiveCoreIpAddress": '1.1.1.10',
            "StandbyCoreIpAddress": '1.1.1.5',
            'interface': 'eth0',
            "operation": 1
        }
        ccap_core[0].is_active = CoreDescription.CORE_MODE_STANDBY
        event_request_rsp.mgr_event.data = json.dumps("Ha/" + json.dumps(caps))
        mgr._handle_mgr_gcp_event(event_request_rsp.mgr_event)

        mgr.fsm.Error(msg='test fsm error')


if __name__ == '__main__':
    unittest.main()
    setup_logging("PROVISION", "test.log")
Пример #20
0
        except Exception as exception:
            logger.error("Unexpected failure (%s): %s", type(exception),
                         exception)
            exit(EX_OSERR)


def handle_interrrupt_signal(signum, frame):  # pragma: no cover
    sys.exit(0)


def set_test_res_db():
    # Setting the python path
    currentPath = path.dirname(path.realpath(__file__))
    dirs = currentPath.split("/")
    rpd_index = dirs.index('rpd')
    if rpd_index == 0:
        print "Cannot find the rpd directory, please correct it"
        sys.exit(-1)
    RCPDB.DB_CFG_FILE = '/'.join(
        dirs[:rpd_index + 1]) + '/confdb/rpd_res_db.conf'


# register the ctrl C to handle this signal
if __name__ == "__main__":  # pragma: no cover
    signal.signal(signal.SIGINT, handle_interrrupt_signal)

    # setup logging, will search the config files
    setup_logging("GCP", filename="rcp.log")

    main()
Пример #21
0
    def setUpClass(cls):
        setupDB()
        time.sleep(2)

        HalGlobal.gClientMgr = None
        HalGlobal.gPoller = None
        t = threading.Thread(target=demoHalmain)
        t.daemon = True
        t.start()
        time.sleep(2)
        threads_list.append(t)
        if not HalGlobal.gClientMgr or not HalGlobal.gPoller:
            raise Exception("Cannot start the demo halMain")
        t = threading.Thread(target=demoL2tp)
        t.daemon = True
        t.start()
        time.sleep(2)
        threads_list.append(t)
        t = threading.Thread(target=demoDrvmain)
        t.daemon = True
        t.start()
        threads_list.append(t)
        time.sleep(2)

        setup_logging('HAL', filename="hal.log", logging_level=logging.DEBUG)
        cls.logger = logging.getLogger("L2tpHalDrvVspAvpTest")
        cls.logger.info("hello L2tpHalDrvVspAvpTest Log")

        cls.stop = False
        cls.conn_address = '127.0.0.1'
        # Setup connection/session: set it here since global variables are already only after threads are up.
        cls.dispatcher = L2tpv3GlobalSettings.Dispatcher
        cls.hal_client = L2tpv3GlobalSettings.l2tp_hal_client
        # cls.conn = L2tpConnection.L2tpConnection(
        #    6661, 6662, cls.conn_address, cls.conn_address)
        #cls.session = L2tpv3Session.L2tpv3Session(6661, 6662, 'receiver',cls.conn)
        # cls.conn.addSession(cls.session)
        localSessionId = L2tpv3RFC3931AVPs.LocalSessionID(6661)
        remoteSessionId = L2tpv3RFC3931AVPs.RemoteSessionID(6662)
        remoteEnd = L2tpv3RFC3931AVPs.RemoteEndID(
            (((0, 3, 0), 0), ((0, 3, 1), 1), ((0, 3, 2), 2)))
        remoteEnd_1 = L2tpv3RFC3931AVPs.RemoteEndID(
            (((0, 3, 3), 3), ((0, 3, 4), 4), ((0, 3, 5), 5)))
        pw_type = L2tpv3RFC3931AVPs.L2SpecificSublayer(3)
        DepiL2SpecificSublayerSubtype = L2tpv3CableLabsAvps.DepiL2SpecificSublayerSubtype(
            3)
        LocalMTUCableLabs = L2tpv3CableLabsAvps.LocalMTUCableLabs(1500)

        cls.avps_icrq = []
        cls.avps_icrq.append(localSessionId)
        cls.avps_icrq.append(remoteSessionId)
        cls.avps_icrq.append(remoteEnd)
        cls.avps_icrq.append(remoteEnd_1)
        cls.avps_icrq.append(DepiL2SpecificSublayerSubtype)
        cls.avps_icrq.append(LocalMTUCableLabs)
        cls.avps_icrq.append(pw_type)

        cls.icrq_buf = struct.pack(
            '!206B',
            0xc8,
            0x03,
            0x0,
            206,
            0x0,
            0x0,
            0x0,
            0x0,
            0x0,
            0x3,
            0x0,
            0x4,
            0xc,
            8,
            0x0,
            0x0,
            0x0,
            0x0,
            0x0,
            10,
            0xc,
            10,
            0x0,
            0x0,
            0,
            15,
            0,
            0,
            0,
            0,
            0xc,
            10,
            0x0,
            0x0,
            0,
            63,
            0x40,
            0x01,
            0x00,
            0x01,
            0xc,
            10,
            0x0,
            0x0,
            0,
            64,
            0x0,
            0x0,
            0x0,
            0x0,
            0xc,
            40,
            0x0,
            0x0,
            0x0,
            66,
            0x0,
            0x0,
            0x00,
            0x03,
            0x00,
            0x00,
            0x00,
            0x03,
            0x01,
            0x01,
            0x00,
            0x03,
            0x02,
            0x02,
            0x00,
            0x03,
            0x03,
            0x03,
            0x00,
            0x03,
            0x04,
            0x04,
            0x00,
            0x03,
            0x05,
            0x05,
            0x00,
            0x03,
            0x06,
            0x06,
            0x00,
            0x03,
            0x07,
            0x07,
            0xc,
            8,
            0,
            0,
            0,
            68,
            0,
            12,
            0xc,
            8,
            0,
            0,
            0,
            69,
            0,
            3,
            0xc,
            8,
            0,
            0,
            0,
            71,
            0,
            2,
            0xc,
            8,
            0x11,
            0x8b,
            0x0,
            0x2,
            0x1,
            0x0,
            0xc,
            8,
            0x11,
            0x8b,
            0x0,
            0x4,
            0x7,
            0xD0,
            0xc,
            20,
            0x11,
            0x8b,
            0x0,
            15,
            0x0,
            0x1,
            0x0,
            0x2,
            0x0,
            0x3,
            0x0,
            0x6,
            0x0,
            0x8,
            0x0,
            11,
            0x0,
            13,
            0xc,
            8,
            0x11,
            0x8b,
            0x0,
            16,
            0x0,
            0x3,
            0xc,
            8,
            0x11,
            0x8b,
            0x0,
            17,
            0x0,
            0x3,
            0xc,
            40,
            0x11,
            0x8b,
            0x0,
            11,
            0,
            0,
            0x5,
            0x6,
            0x7,
            0x8,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            229,
            1,
            1,
            255,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
        )
Пример #22
0
 def setUpClass(cls):
     setup_logging("PROVISION", "test.log")
     cls.mgr = ManagerProcess(simulator=True, test_flag=True)
Пример #23
0
        """setup cli."""

        cli_db = redis.StrictRedis(unix_socket_path=db_defs.UNIX_SOCKET_PATH,
                                   db=db_defs.CLI_DB)
        while True:
            try:
                cli_db.exists(db_defs.ENABLE_PWD)
                break
            except redis.exceptions.ConnectionError:
                time.sleep(1)
                continue

        cli = CmdRpd(conf_file)
        allow = cli.authenticate()
        if allow:
            BasicCli(cli)
            SsdCli(cli)
            GcpCli(cli)
            ProvisionCli(cli)
            Ikev2Cli(cli)
            MacsecCli(cli)
            L2tpCli(cli)
            cli.cmdloop(cli.intro)


if __name__ == '__main__':
    # setup the logging.
    setup_logging("CLI", "cli.log")
    cli = RPDCLI()
    cli.create_cli(DEF_CONF_FILE_NAME)
Пример #24
0
def main():
    """Everything starts here."""
    global logger
    parser = argparse.ArgumentParser("Hal args parser")
    parser.add_argument("--conf",
                        metavar='C',
                        type=str,
                        help="Hal configuration path")
    args = parser.parse_args()

    config = _parseConfiguraion(args.conf)
    if config is None:
        sys.stderr.write(
            "Cannot load the configuration or the configuration format is not correct"
        )
        sys.exit(-1)

    # setup the log
    setup_logging('HAL', filename="hal.log")
    # setup the logger
    logger = logging.getLogger("HalMain")

    # setup the Dispatcher
    HalGlobal.gDispatcher = HalDispatcher()

    # setup the database
    if "db" not in config:
        sys.stderr.write(
            "Cannot find the redis config information, using the default configuration"
        )
        HalGlobal.gHalMsgDbConnection = HalDatabase("/tmp/redis.sock", 30, 12)
        HalGlobal.gHalClientDbConnection = HalDatabase("/tmp/redis.sock", 30,
                                                       11)
    else:
        dbConf = config["db"]
        logger.info(
            "Setting up the Hal database:\n\tPath:%s\n\tmsgDB:%d\n\tindexDB:%d"
            % (dbConf["address"], dbConf["msgDB"], dbConf["indexDB"]))
        HalGlobal.gHalMsgDbConnection = HalDatabase(dbConf["address"],
                                                    dbConf["timeout"],
                                                    dbConf["msgDB"])
        HalGlobal.gHalClientDbConnection = HalDatabase(dbConf["address"],
                                                       dbConf["timeout"],
                                                       dbConf["indexDB"])

    # Getting the un-handled message from the DB, we don't need to clean up
    # the DB since we have set the expire for keys
    if not HalGlobal.gHalMsgDbConnection.isDatabaseEmpty():
        logger.info("Start to load all the resend messages to runtime memory")
        msgs = HalGlobal.gHalMsgDbConnection.listAllMsgs()
        for msg in msgs:
            logger.info("Loading message %s" % msg["Key"])
            key = msg["Key"]
            gpbMsg = msg["Msg"]
            try:
                HalMsg = HalMessage.DeSerialize(gpbMsg)
                logger.debug("Got a zmq msg:%s" % HalMsg.msg)
                HalGlobal.gRestartResendMsg[key] = HalMsg
            except Exception as e:
                logger.error("Error happened when handling msg, error info:%s",
                             str(e))

    # get all the contents and put it in gClientIndex
    if not HalGlobal.gHalClientDbConnection.isDatabaseEmpty("ClientIndex"):
        logger.info(
            "Start to getting previous registered client ID and index... ")
        msgs = HalGlobal.gHalClientDbConnection.listAllMsgs("ClientIndex")
        for key in msgs:
            HalGlobal.gClientIndex[key] = msgs[key]

    _mainLoop()
Пример #25
0
                rcp_message_id=rcp_tlv_def.RCP_MSG_TYPE_IRA,
                rcp_operation=operation)

            self.orch.add_data_to_send(data)

            print msg
            self.socket.send("")
        except Exception as e:
            MasterAPI.logger.error("")
            print "Error happnens when handle message:" + str(e)


if __name__ == "__main__":

    # setup logging, will search the config files
    setup_logging("MasterSim", filename="rcp_master_sim.log")
    set_test_res_db()
    redis = start_redis()
    time.sleep(2)

    scale_test_packets = 1
    send_no_wait = False

    arg_send_no_wait = '--no_wait'
    arg_pkt_count = '--pkt_count'
    arg_use_interface = '--use_interface'
    arg_ipv6 = "--ipv6"
    identification_file = "/conf/conf_core_identification_v4.json"
    i07_file = "/conf/I07Field_v4.json"

    if sys.argv[-1] != "--help" and sys.argv[-1] != arg_ipv6:
Пример #26
0
        led_msg = t_LED()
        led_msg.setLed.ledType = led_msg.LED_TYPE_STATUS
        led_msg.setLed.color = led_msg.LED_COLOR_GREEN
        if operational:
            led_msg.setLed.action = led_msg.LED_ACTION_LIT
        else:
            led_msg.setLed.action = led_msg.LED_ACTION_DARK
        self.logger.debug("Set led notification message: %s", led_msg)
        self.sendNotificationMsg(MsgTypeSetLed, led_msg.SerializeToString())


class manager(object):
    def __init__(self):
        self.desc = "This is a test manager."


if __name__ == "__main__":
    setup_logging('HAL', filename="provmgr_hal.log")
    dispatcher = Dispatcher()
    mgr = manager()
    haldriver = ProvMgrHalDriver("ProvMgr_HAL_CLIENT",
                                 "This is provision manager hal driver",
                                 "1.0.0",
                                 ProvMgrHalDriver.cfgmsg_list,
                                 ProvMgrHalDriver.ntfmsg_list,
                                 ProvMgrHalDriver.ntfmsg_list,
                                 dispatcher=dispatcher,
                                 mgr=mgr)
    haldriver.start()
    dispatcher.loop()
Пример #27
0
#                    Cable Television Laboratories, Inc. ("CableLabs")
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from rpd.provision.process_agent.agent.fake_agent import FakeAgent
import rpd.provision.process_agent.agent.agent as agent
from rpd.common.rpd_logging import setup_logging, AddLoggerToClass


class PTP(FakeAgent):
    __metaclass__ = AddLoggerToClass

    def __init__(self):
        super(PTP, self).__init__(agent.ProcessAgent.AGENTTYPE_PTP)


if __name__ == "__main__":
    setup_logging("PROVISION", filename="provision_ptp.log")
    pagent = PTP()
    pagent.start()
Пример #28
0
            self.send_cfg_rsp_msg(cfg)
        except Exception as e:
            self.logger.error("Got an error:%s, the cfg msg:%s", str(e),
                              cfg.msg)

    def cleanup_sockets(self):
        for fd in self.fd_to_socket:
            sock = self.fd_to_socket[fd]
            self.poller.unregister(sock)
            sock.close()
        self.fd_to_socket.clear()


def handle_interrupt_signal(signum, frame):
    sys.exit(0)


if __name__ == "__main__":
    setup_logging('HAL', filename="open_rpd_drv.log")
    signal.signal(signal.SIGINT, handle_interrupt_signal)
    driver = OpenRpdDriver("openrpd_generic_driver",
                           "This is a Generic OpenRPD Driver", "1.0.0",
                           (OpenRpdMsgHandler.default_supported_msg_types),
                           (2, 3, 4))
    # test_cfg = HalMessage("HalConfigRsp")
    # test_cfg.msg.SeqNum = 123456
    # test_cfg.msg.Rsp.Status = HalCommon_pb2.SUCCESS
    # cfgMsg = capabilities_get(test_cfg)
    # driver.send_cfg_rsp_msg(cfgMsg)
    driver.start()
Пример #29
0
    def test_verify_negative(self):
        print "\n==================================================="
        print "Begin to test the negative value verify....."
        print "==================================================="
        initcode = {
            "manufacturer": {
                "organizationName": "cisco",
                "codeAccessStart": "20160311122430Z",
                "cvcAccessStart": "20160311122430Z"
            },
            "co-signer": {
                "organizationName": "comcast",
                "codeAccessStart": "20160311122430Z",
                "cvcAccessStart": "20160311122430Z"
            }
        }

        test = CFV(initcode, self.rootca)
        rst = test.verify_cvc('0000000000000000000000000000000', True)
        print "manufacturer CVC verification result: " + str(
            rst[0]) + ", " + RST.ssdErrorMessage[rst[1]]

        rst = test.verify_file('000000000000000000000000000000')
        print "codefile verification result: " + str(
            rst[0]) + ", " + RST.ssdErrorMessage[rst[1]]


if __name__ == '__main__':
    setup_logging('HAL', filename="codefile_verifying.log")
    unittest.main()
Пример #30
0
 def setUpClass(cls):
     setup_logging("L2TP")
     # Construct the API transport path
     cls.ApiPath = L2tpv3GlobalSettings.L2tpv3GlobalSettings.APITransportPath