示例#1
0
    def test_read_notification_handler(self):

        rcp_msg = t_RcpMessage()
        rcp_msg.RcpDataResult = t_RcpMessage.RCP_RESULT_OK
        rcp_msg.RcpMessageType = t_RcpMessage.RPD_CONFIGURATION
        evcfg = config()
        # test PendingOrLocalLog 0
        notify_req = evcfg.EventNotification.add()
        notify_req.PendingOrLocalLog = 0
        rcp_msg.RpdDataMessage.RpdData.CopyFrom(evcfg)
        rcp_msg.RpdDataMessage.RpdDataOperation = 2
        payload = rcp_msg.SerializeToString()

        ntMsg = HalMessage("HalConfig",
                           SrcClientID="testRpdFM",
                           SeqNum=322,
                           CfgMsgType=MsgTypetEventNotification,
                           CfgMsgPayload=payload)

        self.fm.fault_ipc.read_notification_handler(ntMsg)
        # test PendingOrLocalLog 1
        notify_req.PendingOrLocalLog = 1
        rcp_msg.RpdDataMessage.RpdData.CopyFrom(evcfg)
        rcp_msg.RpdDataMessage.RpdDataOperation = 2
        payload = rcp_msg.SerializeToString()

        ntMsg = HalMessage("HalConfig",
                           SrcClientID="testRpdFM",
                           SeqNum=322,
                           CfgMsgType=MsgTypetEventNotification,
                           CfgMsgPayload=payload)

        self.fm.fault_ipc.read_notification_handler(ntMsg)
示例#2
0
    def test_set_operational_mode(self):
        led_msg = t_LED()
        led_msg.setLed.ledType = led_msg.LED_TYPE_STATUS
        led_msg.setLed.color = led_msg.LED_COLOR_GREEN
        led_msg.setLed.action = led_msg.LED_ACTION_LIT

        payload = led_msg.SerializeToString()

        cfgMsg = HalMessage("HalConfig",
                            SrcClientID="testRpdFM",
                            SeqNum=322,
                            CfgMsgType=MsgTypeSetLed,
                            CfgMsgPayload=payload)

        self.fm.fault_ipc.set_operational_mode(cfgMsg.msg.CfgMsgPayload)

        led_msg.setLed.action = led_msg.LED_ACTION_DARK
        payload = led_msg.SerializeToString()

        cfgMsg = HalMessage("HalConfig",
                            SrcClientID="testRpdFM",
                            SeqNum=322,
                            CfgMsgType=MsgTypeSetLed,
                            CfgMsgPayload=payload)

        self.fm.fault_ipc.set_operational_mode(cfgMsg.msg.CfgMsgPayload)
示例#3
0
    def sendCfgRspMsg(self, cfg):
        cfgMsg = cfg.msg
        self.logger.debug("RPDInfo configuration message:" + str(cfg.msg))
        if cfgMsg.CfgMsgType == MsgTypeRpdSysUpTime:
            rsp = t_RcpMessage()
            req = t_RcpMessage()
            req.ParseFromString(cfgMsg.CfgMsgPayload)
            rsp.RpdDataMessage.RpdDataOperation = req.RpdDataMessage.RpdDataOperation
            rsp.RcpMessageType = req.RcpMessageType

            self.logger.debug("%s" % str(req))

            req.RpdDataMessage.RpdData.RpdSysUptime = self.getSysUpTime()
            rsp = req
            rsp.RcpDataResult = t_RcpMessage.RCP_RESULT_OK

            self.logger.debug("%s"%str(rsp))
            payload = rsp.SerializeToString()

            msg = HalMessage(
                "HalConfigRsp", SrcClientID=cfgMsg.SrcClientID,
                SeqNum=cfgMsg.SeqNum,
                Rsp={
                    "Status": HalCommon_pb2.SUCCESS,
                    "ErrorDescription": ""
                },
                CfgMsgType=cfgMsg.CfgMsgType,
                CfgMsgPayload=payload)
            if self.pushSock:
                self.pushSock.send(msg.Serialize())
示例#4
0
    def test_lcceId_bad_recvCfgMsgRspCb_NOTSUUPPORT(self):
        self.conn.fsm.recvGoodSCCRQ()
        self.conn.fsm.recvGoodSCCCN()
        rsp = L2tpv3Hal_pb2.t_l2tpLcceAssignmentReq()
        rsp.lcce_id = self.conn.localConnID
        rsp.lcce_info.local_ip = "10.79.41.138"
        rsp.lcce_info.remote_ip = "10.79.41.139"
        rsp.lcce_info.local_mac = L2tpHalClient.get_mac_of_ip(rsp.lcce_info.local_ip)
        rsp.lcce_info.remote_mac = L2tpHalClient.get_mac_of_ip(rsp.lcce_info.remote_ip)
        rsp.lcce_info.mtu = 2342
        rsp.msg_type = L2tpv3Hal_pb2.t_l2tpLcceAssignmentReq.ADD_L2TPv3_LCCE
        payload = rsp.SerializeToString()
        msg = HalMessage("HalConfigRsp", SrcClientID="123", SeqNum=3,
                         Rsp={
                             "Status": HalCommon_pb2.NOTSUPPORTED,
                             "ErrorDescription": ""
                         },
                         CfgMsgType=HalConfigMsg.MsgTypeL2tpv3LcceIdAssignment,
                         CfgMsgPayload=payload)
        ret = self.hal_client.recvCfgMsgRspCb(msg)
        self.assertFalse(ret)

        # case exception
        fake_msg = HalMessage("HalClientRegisterRsp",
                              Rsp={
                                  "Status": HalCommon_pb2.NOTSUPPORTED,
                                  "ErrorDescription": ""
                              },
                              ClientID="214")
        ret = self.hal_client.recvCfgMsgRspCb(cfg=fake_msg)
        self.assertFalse(ret)
示例#5
0
    def sendNotificationMsg(self, notificationType, notificationPayload):
        """Send a notification to Hal.

        :param notificationType: The notification type, the client must
         declare the notification type to Hal first
        :param notificationPayload: the string payload, Hal will not touch
         this part
        :return:

        """
        self.logger.debug("send a a notification message to Hal")
        if self.disconnected:
            self.logger.warning(
                "The client is on disconnected state,"
                " skip to send the message, notification type:%s",
                notificationType)
            return

        if notificationType is None or not isinstance(notificationPayload,
                                                      str):
            self.logger.warning("Cannot send a None or incorrect type to HAL, "
                                "str is required for msg.")
            return

        notification = HalMessage("HalNotification",
                                  ClientID=self.drvID,
                                  HalNotificationType=notificationType,
                                  HalNotificationPayLoad=notificationPayload)
        self.send(notification.Serialize())
示例#6
0
    def sendRpdCapReq(self):
        try:
            if self.rpd_cap:
                self.logger.debug(
                    "Already has Rpd cap in store, no need to send req")
                return True
            rcp_msg = t_RcpMessage()
            rcp_msg.RcpDataResult = t_RcpMessage.RCP_RESULT_OK
            rcp_msg.RcpMessageType = t_RcpMessage.RPD_CONFIGURATION
            rpd_data_msg = t_RpdDataMessage()
            rpd_data_msg.RpdDataOperation = t_RpdDataMessage.RPD_CFG_READ
            rcp_cfg = config()
            sub_tlv = rcp_cfg.RpdCapabilities
            GCPObject.default_gpb(gpb=sub_tlv)
            rpd_data_msg.RpdData.CopyFrom(rcp_cfg)
            rcp_msg.RpdDataMessage.CopyFrom(rpd_data_msg)

            cfgMsgContent = rcp_msg.SerializeToString()
            msg = HalMessage("HalConfig",
                             SrcClientID=self.drvID,
                             SeqNum=self.seqNum,
                             CfgMsgType=MsgTypeRpdCapabilities,
                             CfgMsgPayload=cfgMsgContent)
            self.send(msg.Serialize())
            self.seqNum += 1
            self.logger.debug("send RPD capabilities req to hal driver")
            return True
        except Exception as e:
            self.logger.warning("send RPD cap req failed :%s", str(e))
            return False
示例#7
0
    def cfgMsgTimeoutCb(self, args):
        """
        :param args: the callback parameters, we need the srcClient agent, original message
        :return:

        """
        agent = args["agent"]
        cfgMsg = args["originalMsg"].msg

        self.logger.warn(
            "Send a timeout message to client [%s] for message %s" %
            (agent.clientID, cfgMsg))

        seqNum = cfgMsg.SeqNum if hasattr(cfgMsg, "SeqNum") else 0
        msg = HalMessage(
            "HalConfigRsp",
            SrcClientID=cfgMsg.SrcClientID,
            SeqNum=seqNum,
            Rsp={
                "Status":
                HalCommon_pb2.TIMEOUT,
                "ErrorDescription":
                'timeout happened when sending the msg to dstClient, is dstClient dead :(?'
            },
            CfgMsgType=cfgMsg.CfgMsgType,
            CfgMsgPayload=cfgMsg.CfgMsgPayload)

        # Do some stats here
        agent.stats.NrErrorMsgs += 1
        agent.stats.NrCfgRspMsgs += 1
        agent.stats.NrTimeoutMsgs += 1

        agent.transportPush.send(msg.Serialize())
示例#8
0
 def getRpdPtpState(self, cfg):
     rsp = t_RcpMessage()
     rsp.ParseFromString(cfg.msg.CfgMsgPayload)
     config = rsp.RpdDataMessage.RpdData
     try:
         config.RpdState.LocalPtpSyncStatus = \
             True if self.ptp_result == t_GeneralNotification.PTPSYNCHRONIZED else False
         cfg.CfgMsgPayload = config.SerializeToString()
         rsp.RpdDataMessage.RpdData.CopyFrom(config)
         rsp.RcpDataResult = t_RcpMessage.RCP_RESULT_OK
         payload = rsp.SerializeToString()
         self.logger.info("Send rpd state LocalPtpSyncStatus response, %s" %
                          rsp)
         msg = HalMessage("HalConfigRsp",
                          SrcClientID=cfg.msg.SrcClientID,
                          SeqNum=cfg.msg.SeqNum,
                          Rsp={
                              "Status":
                              HalCommon_pb2.SUCCESS,
                              "ErrorDescription":
                              "PTP LOCALPTPSYNCSTATUS query success"
                          },
                          CfgMsgType=cfg.msg.CfgMsgType,
                          CfgMsgPayload=payload)
         self.pushSock.send(msg.Serialize())
     except Exception as e:
         self.logger.error("excpetipn:%s", str(e))
     return
示例#9
0
文件: ssd_cli.py 项目: hujiangyi/or
    def sendHalMsg(self, cfgMsg):
        hal_ipc = self.cli.hal_ipc
        if hal_ipc.disconnected:
            hal_ipc.logger.error("The client is on disconencted state,"
                                 "skip to send the message.")
            return

        if cfgMsg is None:
            hal_ipc.logger.error("Cannot send a None or incorrect type to HAL")
            return

        for desc, value in cfgMsg.ListFields():
            if desc.name not in self.CfgMsgId_dict:
                hal_ipc.logger.error("Cannot not find %s" % desc.name)
                return
            msg = HalMessage("HalConfig",
                             SrcClientID=hal_ipc.clientID,
                             SeqNum=hal_ipc.seqNum,
                             CfgMsgType=self.CfgMsgId_dict[desc.name],
                             CfgMsgPayload=cfgMsg.SerializeToString())
            hal_ipc._send(msg.Serialize())

            seq = hal_ipc.seqNum
            hal_ipc.seqNum += 1
            return seq
示例#10
0
    def register(self, driverID):
        """Send a register message to Hal and get the client ID from the Hal.

        :return:

        """
        if driverID is None:
            registerMsg = HalMessage(
                "HalClientRegister",
                ClientName=self.drvname,
                ClientDescription=self.drvDesc,
                ClientVersion=self.drvVer,
                ClientSupportedMessages=self.supportedMsgType,
                ClientSupportedNotificationMessages=self.
                supportedNotificationMsgs)
        else:
            registerMsg = HalMessage(
                "HalClientRegister",
                ClientName=self.drvname,
                ClientDescription=self.drvDesc,
                ClientVersion=self.drvVer,
                ClientSupportedMessages=self.supportedMsgType,
                ClientSupportedNotificationMessages=self.
                supportedNotificationMsgs,
                ClientID=driverID)

        if self.mgrConnection is None:
            errMsg = "Cannot send the register since the mgr connection is not setup"
            self.logger.error(errMsg)
            raise HalDriverClientError(errMsg)
        self.logger.debug("Send the register msg to Hal...")
        self.mgrConnection.send(registerMsg.Serialize())
示例#11
0
    def sendCfgMsg(self, cfgMsgType, cfgMsgContent):
        """The configutaion response routine, the driver implementor should
        fill sth into this function.

        :param cfg: The original configuration message
        :return:

        """
        self.logger.debug("Send a config message to HAL: %r", cfgMsgContent)

        if self.disconnected:
            self.logger.warn(
                "The client is on disconencted state, skip to send the message."
            )
            return

        if cfgMsgContent is None or not isinstance(cfgMsgContent, str):
            self.logger.error(
                "Cannot send a None or incorrect type to HAL, str is required for msg"
            )
            return

        msg = HalMessage("HalConfig",
                         SrcClientID=self.drvID,
                         SeqNum=self.seqNum,
                         CfgMsgType=cfgMsgType,
                         CfgMsgPayload=cfgMsgContent)
        self._sendMsg(msg.Serialize())

        seq = self.seqNum
        self.seqNum += 1
        return seq
示例#12
0
    def test_Deserialize(self):
        """test HalMessage#DeSerialize,

        check the string message can't be
        deserialized, if not case fail

        check the unnormal binary HalMessage
        can't be deserialized, if not case fail.

        :keyword:HalMessage#DeSerialize
        :exception:"The input binary is None",
                   "Cannot parse the message since the msgType"
        :parameter:
        :return:

        """
        try:
            mas = HalMessage.DeSerialize("a")
        except Exception as e:
            self.assertEqual("The input binary is None", str(e))

        try:
            msg = HalMessage.DeSerialize(
                "00000))))))00000))))))00000))))))00000))))))00000))))))00000))))))00000)))))"
                ")00000))))))00000))))))")
        except Exception as e:
            self.assertEqual(
                str(e).startswith(
                    "Cannot parse the message since the msgType"), True)
示例#13
0
    def sendMsg(self, cfgMsg):
        """
        The configutaion response routine, the driver implementor should fill
        sth into this function
        :param cfg: The original configutaion message
        :return:
        """
        if self.disconnected:
            self.logger.error("The client is on disconencted state,"
                              " skip to send the message.")
            return

        if cfgMsg is None or not isinstance(cfgMsg, t_CliMessage):
            self.logger.error("Cannot send a None or incorrect type to HAL")
            return

        for desc, value in cfgMsg.CliData.ListFields():
            if desc.name not in self.CfgMsgId_dict:
                self.logger.error("Cannot not find %s" % desc.name)
                return
            msg = HalMessage("HalConfig", SrcClientID=self.clientID,
                             SeqNum=self.seqNum,
                             CfgMsgType=self.CfgMsgId_dict[desc.name],
                             CfgMsgPayload=cfgMsg.SerializeToString())
            self._send(msg.Serialize())

            seq = self.seqNum
            self.seqNum += 1
            return seq
示例#14
0
    def dispatchCfgMessage(self, sendAgent, cfg):
        """Dispatch the client cfg msg.

        :param sendAgent: the agent that sends the configuration message.
        :param cfg: the HalMessage type.
        :return: -1 for error, should add it to resend list;
                 0 for normal process

        """
        # check the CfgMsgType and routing it to the correct dstClient
        cfgMsg = cfg.msg
        if cfg.msg.CfgMsgType not in HalGlobal.gMsgTypeClientMapping:
            self.logger.warn(
                "There is no client support this config message currently, will resend it later: %s.",
                cfgMsg)
            sendAgent.stats.NrErrorMsgs += 1  # the message cannot be supported, will resend it later
            return -1

        agent_list = HalGlobal.gMsgTypeClientMapping[cfgMsg.CfgMsgType]
        cfgMsg.SeqNum = cfgMsg.SeqNum if cfgMsg.HasField("SeqNum") else 0
        cfgMsg.SrcClientID = sendAgent.clientID

        for agent_obj in agent_list:
            agent = agent_obj["agent"]

            if agent is sendAgent:
                self.logger.warn("agent %s: Cannot send seq %d to itself",
                                 agent.clientID, cfgMsg.SeqNum)
                msg = HalMessage("HalConfigRsp",
                                 SrcClientID=cfgMsg.SrcClientID,
                                 SeqNum=cfgMsg.SeqNum,
                                 Rsp={
                                     "Status":
                                     HalCommon_pb2.FAILED,
                                     "ErrorDescription":
                                     'Cannot send configuration msg to itself'
                                 },
                                 CfgMsgType=cfgMsg.CfgMsgType,
                                 CfgMsgPayload=cfgMsg.CfgMsgPayload)

                agent.transportPush.send(msg.Serialize())
                continue

            client_id = agent_obj["clientID"]

            cfgMsg.DstClientID = client_id
            # we should rewrite the srcClientID
            agent.transportPush.send(cfg.Serialize())
            sendAgent.addToRuntimeObjList(cfgMsg.SeqNum, sendAgent.timeout,
                                          (self.cfgMsgTimeoutCb, {
                                              "agent": sendAgent,
                                              "originalMsg": cfg
                                          }))

            agent.stats.NrCfgMsgs += 1
            self.logger.debug(
                "Dispatching the msg[%d] from srcClient[%s] to dstClient[%s]" %
                (cfgMsg.CfgMsgType, cfgMsg.SrcClientID, cfgMsg.DstClientID))

        return 0
示例#15
0
 def sayHelloToHal(self):
     """
     Send a hello message to verify the agent path is correct
     :return:
     """
     self.logger.debug("Send a Hello message to Hal")
     helloMsg = HalMessage("HalClientHello", ClientID=self.clientID)
     self._send(helloMsg.Serialize())
示例#16
0
 def send_cfg_msg(self, cfgMsgType, payload):
     msg = HalMessage("HalConfig",
                      SrcClientID=self.drvID,
                      CfgMsgType=cfgMsgType,
                      SeqNum=self.seqNum,
                      CfgMsgPayload=payload)
     self.logger.debug("sending config - type: %d, msg: %s" %
                       (cfgMsgType, msg))
     self.pushSock.send(msg.Serialize())
     self.seqNum += 1
     return
示例#17
0
    def sayHelloToHal(self):
        """Send a hello message to verify the agent path is correct.

        :return:

        """
        self.logger.debug(" ".join([
            str(self.drvname),
            str(self.drvID), ":Send a Hello message to Hal"
        ]))
        helloMsg = HalMessage("HalClientHello", ClientID=self.drvID)
        self.send(helloMsg.Serialize())
示例#18
0
文件: HalAgent.py 项目: hujiangyi/or
    def processResendList(self, test=False):
        """go through the resend list, find the timeout ones and send a
        unsupported message to client.

        for the un-timeout ones, we will send the message to the dispatcher, if the dispatch successfully process the
        message, we will remove from the list
        :return:

        """
        if len(self.resendList) <= 0:
            return

        self.logger.debug(
            "Process the resend list, and send the msg to driver")

        removeList = list()
        for i in xrange(len(self.resendList)):
            msg = self.resendList[i]
            seq = msg["seq"]
            if msg["time"] < time():
                # send a timeout msg to the original sender
                cfgMsg = msg["msg"].msg
                unSupportedMsg = HalMessage(
                    "HalConfigRsp",
                    SrcClientID=cfgMsg.SrcClientID,
                    SeqNum=seq,
                    Rsp={
                        "Status":
                        HalCommon_pb2.NOTSUPPORTED,
                        "ErrorDescription":
                        'No Driver can handle this message, please check '
                        'if the driver has registered, or if the registered'
                        ' driver can supported this message type'
                    },
                    CfgMsgType=cfgMsg.CfgMsgType,
                    CfgMsgPayload=cfgMsg.CfgMsgPayload)
                if not test:
                    msg["sendAgent"].transportPush.send(
                        unSupportedMsg.Serialize())
                removeList.append(msg)
                continue

            # invoke dispatcher
            ret = HalGlobal.gDispatcher.dispatchCfgMessage(
                msg["sendAgent"], msg["msg"])
            if ret == 0:
                removeList.append(msg)

        # Process the removeList
        for msg in removeList:
            self.resendList.remove(msg)
示例#19
0
    def sendNotificationMsg(self, notificationType, notificationPayload):
        """Send a notification to Hal.

        :param notificationType: The notification type, the client must declare the notification type to Hal first
        :param notificationPayload: the string payload, Hal will not touch this part
        :return:

        """
        self.logger.debug("send a a notification message to Hal")
        notfication = HalMessage("HalNotification",
                                 ClientID=self.drvID,
                                 HalNotificationType=notificationType,
                                 HalNotificationPayLoad=notificationPayload)
        self.send(notfication.Serialize())
示例#20
0
 def test_recvCfgMsgCb(self):
     cfg = t_RcpMessage()
     cfg.RcpMessageType = t_RcpMessage.RPD_CONFIGURATION
     payload = cfg.SerializeToString()
     self.cfgMsg = HalMessage("HalConfig",
                              SrcClientID="testRpdRes",
                              SeqNum=322,
                              CfgMsgType=MsgTypeHostResources,
                              CfgMsgPayload=payload)
     cfg_rsp_msg = HalMessage("HalClientRegisterRsp")
     cfg_rsp_msg.msg.Rsp.Status = 2
     self.rpdhostres.recvRegisterMsgCb(cfg_rsp_msg)
     self.assertTrue(self.rpdhostres.disconnected)
     self.assertEqual(None, self.rpdhostres.recvCfgMsgCb(self.cfgMsg))
示例#21
0
    def test_cfgMsgTimeoutCb(self):
        """Construct client agent msg and original msg."""

        try:
            self.clientMgr.handleRegisterRequest(None)
        except Exception as e:
            self.assertEqual(
                "Cannot handle the client register "
                "request since the register msg is None", str(e))

        # Create a client msg
        agent = HalAgentClient(self.poller,
                               clientID="123",
                               disconnectHandler=None,
                               reuseIndex=None)

        # Create a original message
        oricfgMsg = HalMessage("HalConfig",
                               SrcClientID="123",
                               SeqNum=33,
                               CfgMsgType=1,
                               CfgMsgPayload="test HalDispatcher")

        # Test cfgMsgTimeoutCb
        currentErrorMsgs = HalGlobalStats.NrErrorMsgs
        self.halDispatcher.cfgMsgTimeoutCb(
            args={"agent": agent, "originalMsg": oricfgMsg})
        self.assertEqual(HalGlobalStats.NrErrorMsgs, currentErrorMsgs + 1)
示例#22
0
    def openrpd_drv_hal_cb(self, sock, mask):
        self.logger.debug("Driver received hal cb event")
        if self.pushSock is not None and sock == self.pushSock.monitor:
            self.pushSock.monitorHandler(recv_monitor_message(sock))
            return
        if self.pullSock is not None and sock == self.pullSock.monitor:
            self.pullSock.monitorHandler(recv_monitor_message(sock))
            return

        if sock == self.mgrConnection.monitor:
            self.mgrConnection.monitorHandler(recv_monitor_message(sock))
            return

        while sock.getsockopt(zmq.EVENTS) and zmq.POLLIN:
            try:
                bin = sock.recv(flags=zmq.NOBLOCK)
                msg = HalMessage.DeSerialize(bin)
                self.logger.debug("Got a zmq msg:%s type:%s" %
                                  (msg.msg, msg.type))
                if msg.type in self.HalMsgsHandler:
                    handler = self.HalMsgsHandler[msg.type]
                    handler(msg)
            except zmq.ZMQError as e:
                self.logger.debug(
                    "Got an error when trying with nonblock read:" + str(e))
                break
            except Exception as e:
                self.logger.error("Got an un-expected error:%s", str(e))
                break
示例#23
0
    def fault_management_cb(self, sock, mask):  # pragma: no cover
        """Fault management callback.

        :param sock: zmq socket
        :param mask: event mask
        :return:

        """

        if self.pushSock is not None and sock == self.pushSock.monitor:
            self.pushSock.monitorHandler(recv_monitor_message(sock))
            return
        if self.pullSock is not None and sock == self.pullSock.monitor:
            self.pullSock.monitorHandler(recv_monitor_message(sock))
            return
        if self.mgrConnection is not None and sock == self.mgrConnection.monitor:
            self.mgrConnection.monitorHandler(recv_monitor_message(sock))
            return

        while sock.getsockopt(zmq.EVENTS) and zmq.POLLIN:
            try:
                bin = sock.recv(flags=zmq.NOBLOCK)
                msg = HalMessage.DeSerialize(bin)
                self.logger.debug("###########Got a zmq msg:%s" % msg.msg)
                if msg.type in self.HalMsgsHandler:
                    handler = self.HalMsgsHandler[msg.type]
                    handler(msg)
            except zmq.ZMQError as e:
                self.logger.debug(
                    "Getting an error when trying with nonblock read:" +
                    str(e))
                break
            except Exception as e:
                self.logger.error("Error happens, reason:%s" % str(e))
                break
示例#24
0
    def test_HandleUnnormalConfigRsp(self):
        """test the method of halAgentClient#HandleConfigRsp check the
        HalConfigRsp HalMessage can be handle with specific exception, once
        catch the error message, case pass.

        :keyword:halAgentClient#HandleConfigRsp
        :exception:"Cannot create a msg since we can not find the msg definition"

        """
        try:
            self.halAgentClient.handleConfigRsp(None)
        except Exception as e:
            self.assertEqual(str(e),
                             "Cannot handle a none config response message")

        # try:
        tmp = HalGlobalStats.NrErrorMsgs
        cfgMsg = HalMessage("HalConfigRsp",
                            SrcClientID="0123456789",
                            SeqNum=0,
                            Rsp={
                                "Status": HalCommon_pb2.FAILED,
                                "ErrorDescription": "test"
                            },
                            CfgMsgType=123,
                            CfgMsgPayload="Hello")
        self.halAgentClient.handleConfigRsp(cfgMsg)
        self.assertEqual(HalGlobalStats.NrErrorMsgs, tmp + 1)
示例#25
0
    def processCfgMsg(self, cfgMsg):
        rsp = t_RcpMessage()
        # rsp.ParseFromString(cfgMsg.CfgMsgPayload)
        req = t_RcpMessage()
        req.ParseFromString(cfgMsg.CfgMsgPayload)

        rsp.RpdDataMessage.RpdDataOperation = req.RpdDataMessage.RpdDataOperation
        rsp.RcpMessageType = req.RcpMessageType

        # load the rpd host resources information
        hr = rsp.RpdDataMessage.RpdData.HostResources
        hr.hrMemorySize = self.getMemorySize()
        hr.hrProcessorLoad = self.getProcessorLoad()
        self.getStorages(hr.hrStorages)
        self.getProcesses(hr.hrProcesses)

        rsp.RcpDataResult = t_RcpMessage.RCP_RESULT_OK
        payload = rsp.SerializeToString()

        msg = HalMessage("HalConfigRsp",
                         SrcClientID=cfgMsg.SrcClientID,
                         SeqNum=cfgMsg.SeqNum,
                         Rsp={
                             "Status": HalCommon_pb2.SUCCESS,
                             "ErrorDescription": ""
                         },
                         CfgMsgType=cfgMsg.CfgMsgType,
                         CfgMsgPayload=payload)
        return msg
示例#26
0
    def provmgr_cb(self, sock, mask):
        if self.pushSock is not None and sock == self.pushSock.monitor:
            self.pushSock.monitorHandler(recv_monitor_message(sock))
            return
        if self.pullSock is not None and sock == self.pullSock.monitor:
            self.pullSock.monitorHandler(recv_monitor_message(sock))
            return
        if self.mgrConnection is not None and sock == self.mgrConnection.monitor:
            self.mgrConnection.monitorHandler(recv_monitor_message(sock))
            return

        while sock.getsockopt(zmq.EVENTS) and zmq.POLLIN:
            try:
                bin = sock.recv(flags=zmq.NOBLOCK)
                msg = HalMessage.DeSerialize(bin)
                if msg.type in self.HalMsgsHandler:
                    handler = self.HalMsgsHandler[msg.type]
                    handler(msg)
            except zmq.ZMQError as e:
                self.logger.debug(
                    "Got an error when trying with non-block read:" + str(e))
                break
            except Exception as e:
                self.logger.warn(
                    "Exception happens when provmgr hal recv socket, reason:%s"
                    % str(e))
                break
示例#27
0
 def test_recvRpdServerCtrlMsgCb(self):
     rcp_msg = t_RcpMessage()
     rcp_msg.RcpMessageType = t_RcpMessage.RPD_CONFIGURATION
     rcp_msg.RpdDataMessage.RpdDataOperation = t_RpdDataMessage.RPD_CFG_WRITE
     cfg_msg = config()
     rpdCtrl = cfg_msg.RpdCtrl
     rpdServerCtrlCfg = rpdCtrl.CrashDataServerCtrl
     rpdServerCtrlCfg.DestIpAddress = "127.0.0.1"
     rpdServerCtrlCfg.DestPath = "/bootflash/"
     rpdServerCtrlCfg.Protocol = 2
     rcp_msg.RpdDataMessage.RpdData.CopyFrom(cfg_msg)
     cfg_payload = rcp_msg.SerializeToString()
     self.cfgMsg = HalMessage("HalConfig",
                              SrcClientID="testRpdRes",
                              SeqNum=322,
                              CfgMsgType=MsgTypeRpdCtrl,
                              CfgMsgPayload=cfg_payload)
     crashFileCtrl = self.rpdhostres.crashFileCtrlHandler
     self.assertEqual(None, self.rpdhostres.recvCfgMsgCb(self.cfgMsg))
     crashDataServerInfo = crashFileCtrl.get_server_info()
     self.assertEqual(crashDataServerInfo.destIpAddress,
                      rpdServerCtrlCfg.DestIpAddress)
     self.assertEqual(crashDataServerInfo.destPath,
                      rpdServerCtrlCfg.DestPath)
     self.assertEqual(crashDataServerInfo.protocol,
                      rpdServerCtrlCfg.Protocol)
示例#28
0
 def sendInterestedNotifications(self, notifications):
     """
     Send the notifications to the HAL
     :param notifications:
     :return:
     """
     self.logger.debug("Send a Interested notification configuration msg to HAL")
     if notifications is not None and not isinstance(notifications, tuple) and not isinstance(notifications, list):
         self.logger.error("Cannot set an notification with wrong type, you can pass a tuple or list to it ")
         return
     configMsg = HalMessage("HalClientInterestNotificationCfg", ClientID=self.clientID,
                            ClientNotificationMessages=notifications)
     self.mgrConnection.send(configMsg.Serialize())
     # REQ/RSP
     bin = self.mgrConnection.recv()
     return bin
示例#29
0
    def test_L2tpv3Hall_GCPP(self):
        index = 0
        rcp_msg = t_RcpMessage()
        rcp_msg.RcpMessageType = t_RcpMessage.RPD_CONFIGURATION
        rcp_msg.RpdDataMessage.RpdDataOperation = \
            t_RpdDataMessage.RPD_CFG_WRITE
        cfg_msg = config()
        staticPwConfig = cfg_msg.StaticPwConfig
        self.retCfg = StaticL2tpProvision()
        self.retCfg.add_usStaticSession(staticPwConfig, index + 163, False,
                                        False)
        self.retCfg.add_commStaticSession(staticPwConfig, index + 163,
                                          0x80007111 + index, index, 32768,
                                          True)
        rcp_msg.RpdDataMessage.RpdData.CopyFrom(cfg_msg)
        cfg_payload = rcp_msg.SerializeToString()
        staticL2tpMsg = HalMessage("HalConfig", SrcClientID="testGCPPL2Static",
                                   SeqNum=325,
                                   CfgMsgType=HalConfigMsg.MsgTypeGcppToL2tp,
                                   CfgMsgPayload=cfg_payload)

        self.hal_client.recvCfgMsgCb(staticL2tpMsg)
        ses = StaticL2tpSession(index + 163)
        ses.read()
        self.assertTrue(self.fwdCfg.check_StaticSession(staticPwConfig, ses))
示例#30
0
    def test_GCPP_recvCfgMsgRspCb_FAILED(self):
        self.fwdCfg = StaticL2tpProvision()
        staticPwCfg = StaticPwConfig_pb2.t_StaticPwConfig()
        self.fwdCfg.add_commStaticSession(staticPwCfg, 11, 0x80001111, 3,
                                          32768, False)
        self.fwdCfg.add_dsStaticSession(staticPwCfg, 11, False, False)
        ses = StaticL2tpSession(11)
        ses.updateFwdStaticPseudowire(staticPwCfg)
        ses.updateComStaticPseudowire(staticPwCfg)
        ses.write()
        self.assertTrue(self.fwdCfg.check_StaticSession(staticPwCfg, ses))

        rsp = L2tpv3Hal_pb2.t_l2tpSessionRsp()
        rsp.session_selector.local_ip = \
            L2tpv3GcppSession.L2tpv3GcppProvider.getLocalIp(
                "127.0.0.1")
        rsp.session_selector.remote_ip = "127.0.0.1"
        rsp.session_selector.lcce_id = 0
        rsp.session_selector.local_session_id = 0x80001111
        rsp.session_selector.remote_session_id = 0x80001111
        rsp.result = True
        payload = rsp.SerializeToString()
        msg = HalMessage("HalConfigRsp", SrcClientID="123", SeqNum=2,
                         Rsp={"Status": HalCommon_pb2.FAILED,
                              "ErrorDescription": ""},
                         CfgMsgType=HalConfigMsg.MsgTypeL2tpv3SessionReqUsAtdma,
                         CfgMsgPayload=payload)
        ret = self.hal_client.recvCfgMsgRspCb(msg)
        self.assertFalse(ret)