Exemplo n.º 1
0
    def handleClientInterestNotificationCfg(self, interest):
        """Client can send cfg message to specify which notification message it
        is interested in, this handler will handle this request. All the
        notification interest mapping are stored in a dict, the key is the
        notification type and value is a list, which hold all the clients.

        :param cfg: the interest message from the client
        :return: None

        """
        if interest is None:
            msg = "Cannot handle a none interest configuration."
            self.logger.error(msg)
            raise Exception(msg)

        # Get the interest msg types and put them in mapping tables
        cfgMsg = interest.msg
        self.logger.info("handle client interest request from[%s]: %s" %
                         (cfgMsg.ClientID, cfgMsg))
        for item in cfgMsg.ClientNotificationMessages:
            client = self._getClientFromDb(cfgMsg.ClientID)
            if client is None:
                self.logger.error(
                    "Cannot handle a message without client, msg:%s", cfgMsg)
                rspMsg = HalMessage("HalClientInterestNotificationCfgRsp",
                                    ClientID="",
                                    Rsp={
                                        "Status":
                                        HalCommon_pb2.FAILED,
                                        "ErrorDescription":
                                        "No ClientID or no runtime client"
                                    })
                self.logger.info(
                    "Send client interest response to requester:%s" %
                    rspMsg.msg)
                ret = self.transport.send(rspMsg.Serialize())
                if ret is False:
                    self.logger.error("Send client interest response failed")
                return
            else:
                if item not in HalGlobal.gNotificationMapping:
                    HalGlobal.gNotificationMapping[item] = list()
                # check if we have register the message
                if client in HalGlobal.gNotificationMapping[item]:
                    pass
                else:
                    HalGlobal.gNotificationMapping[item].append(client)

        rspMsg = HalMessage("HalClientInterestNotificationCfgRsp",
                            ClientID=cfgMsg.ClientID,
                            Rsp={
                                "Status": HalCommon_pb2.SUCCESS,
                                "ErrorDescription": "Successful"
                            })
        self.logger.info("Send client interest response to requester:%s" %
                         rspMsg.msg)
        ret = self.transport.send(rspMsg.Serialize())
        if ret is False:
            self.logger.error("Send client interest response failed")
Exemplo n.º 2
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())
Exemplo n.º 3
0
    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
Exemplo n.º 4
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
Exemplo n.º 5
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
Exemplo n.º 6
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
Exemplo n.º 7
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
Exemplo n.º 8
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())
Exemplo n.º 9
0
    def register(self, clientID):
        """
        send a register message to Hal and get the device ID from the Hal.
        :return:
        """
        if clientID is None:
            registerMsg = HalMessage("HalClientRegister",
                                     ClientName=self.appName,
                                     ClientDescription=self.appDesc,
                                     ClientVersion=self.appVer)
        else:
            registerMsg = HalMessage("HalClientRegister",
                                     ClientName=self.appName,
                                     ClientDescription=self.appDesc,
                                     ClientVersion=self.appVer,
                                     ClientID=clientID)

        if self.mgrConnection is None:
            errMsg = "Cannot send the register since the mgr connection is not setup"
            self.logger.error(errMsg)
            raise HalClientError(errMsg)
        self.logger.debug("Send the register msg to Hal...")
        self.mgrConnection.send(registerMsg.Serialize())
        bin = self.mgrConnection.recv()
        rsp = HalMessage.DeSerialize(bin)
        self.recvRegisterMsgCb(rsp)
Exemplo n.º 10
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
Exemplo n.º 11
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())
Exemplo n.º 12
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())
Exemplo n.º 13
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())
Exemplo n.º 14
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
Exemplo n.º 15
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())
Exemplo n.º 16
0
    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)
Exemplo n.º 17
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())
Exemplo n.º 18
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
Exemplo n.º 19
0
    def sendCfgRspMsg(self, cfg, rsp=None):
        """The configuration response routine, the driver implementor should
        fill sth into this function.

        :param cfg: The original configuration message
        :return:

        """
        cfgMsg = cfg.msg
        rsp = {"Status": HalCommon_pb2.SUCCESS, "ErrorDescription": ""}
        msg = HalMessage("HalConfigRsp",
                         SrcClientID=cfgMsg.SrcClientID,
                         SeqNum=cfgMsg.SeqNum,
                         Rsp=rsp,
                         CfgMsgType=cfgMsg.CfgMsgType,
                         CfgMsgPayload=cfgMsg.CfgMsgPayload)
        self.pushSock.send(msg.Serialize())
Exemplo n.º 20
0
    def sendCfgRspMsg(self, cfg, rsp=None):
        """The configuration response routine, the driver implementor should
        fill sth into this function.

        :param cfg: The original configuration message
        :param rsp: respond
        :return:

        """
        cfgMsg = cfg.msg
        msg = HalMessage("HalConfigRsp",
                         SrcClientID=cfgMsg.SrcClientID,
                         SeqNum=cfgMsg.SeqNum,
                         Rsp=rsp,
                         CfgMsgType=cfgMsg.CfgMsgType,
                         CfgMsgPayload=cfgMsg.CfgMsgPayload)
        self.send(msg.Serialize())
Exemplo n.º 21
0
    def test_sendMsg(self):
        """test the method of halAgentClient#sendMsg if the normall halmessage
        can be send without exception, this case pass.

        :keyword:halAgentClient#sendMsg
        :exception:assertIsNone(str(e))

        """
        # construct the Hello message
        try:
            helloMsg = HalMessage("HalClientRegister",
                                  ClientName="abc",
                                  ClientDescription="abc",
                                  ClientVersion="1.2.3",
                                  ClientSupportedMessages=[1, 2, 3],
                                  ClientSupportedNotificationMessages=[])
            self.halAgentClient.sendMsg(helloMsg.Serialize())
        except Exception as e:
            self.assertIsNone(str(e))
Exemplo n.º 22
0
    def register(self, clientID):
        """Send a register message to Hal and get the client ID from the Hal.

        :return:

        """
        if clientID is None:
            if len(self.supportedMsgType) > 0:
                registerMsg = HalMessage(
                    "HalClientRegister",
                    ClientName=self.appName,
                    ClientDescription=self.appDesc,
                    ClientVersion=self.appVer,
                    ClientSupportedMessages=self.supportedMsgType)
            else:
                registerMsg = HalMessage("HalClientRegister",
                                         ClientName=self.appName,
                                         ClientDescription=self.appDesc,
                                         ClientVersion=self.appVer)
        else:
            if len(self.supportedMsgType) > 0:
                registerMsg = HalMessage(
                    "HalClientRegister",
                    ClientName=self.appName,
                    ClientDescription=self.appDesc,
                    ClientVersion=self.appVer,
                    ClientSupportedMessages=self.supportedMsgType,
                    ClientID=clientID)
            else:
                registerMsg = HalMessage("HalClientRegister",
                                         ClientName=self.appName,
                                         ClientDescription=self.appDesc,
                                         ClientVersion=self.appVer,
                                         ClientID=clientID)

        if self.mgrConnection is None:
            errMsg = "Cannot send the register since the mgr connection is not setup"
            self.logger.error(errMsg)
            raise HalClientError(errMsg)
        self.logger.debug("Send the register msg to Hal...")
        self.mgrConnection.send(registerMsg.Serialize())
Exemplo n.º 23
0
    def setHalDebugLevel(self, module, level):
        """Set the HAl debug level.

        :param module: the Hal module name
        :param level: the logging level
        :return:

        """
        self.logger.info("Set hal module[%s] to level [%s]" %
                         (module, logging.getLevelName(level)))

        if self.disconnected:
            self.logger.warn("Cannot send the HAL debug configuration to HAL"
                             " since the client is in disconnected  state.")
            return
        msg = HalMessage("HalSetLoggingLevel",
                         ClientID=self.clientID,
                         Module=module,
                         LoggingLevel=level)

        self.mgrConnection.send(msg.Serialize())
Exemplo n.º 24
0
    def handleClientQuery(self, query):
        """handle the drivers query request. The handler will go through the
        gClientDB and find the all the drivers and send these info to client.

        :param query: the query message, we will use the clientID in this message
        :return return a message to client

        """
        if query is None:
            msg = "Cannot handle a none client query"
            self.logger.error(msg)
            raise Exception(msg)

        clientList = list()
        for clientID in HalGlobal.gClientDB:
            msg = HalGlobal.gClientDB[clientID]["msg"]
            retDict = dict()
            retDict["ClientID"] = clientID
            retDict["ClientName"] = msg.msg.ClientName
            retDict["ClientDescription"] = msg.msg.ClientDescription
            retDict["ClientVersion"] = msg.msg.ClientVersion

            retDict["ClientSupportedMessages"] = list()
            for item in msg.msg.ClientSupportedMessages:
                retDict["ClientSupportedMessages"].append(item)

            retDict["ClientSupportedNotificationMessages"] = list()
            for item in msg.msg.ClientSupportedNotificationMessages:
                retDict["ClientSupportedNotificationMessages"].append(item)
            clientList.append(retDict)

        rsp = HalMessage("HalClientQueryRsp",
                         ClientID=query.msg.ClientID,
                         Clients=clientList)
        self.logger.debug("Send client query response to requester:%s" %
                          rsp.msg)

        ret = self.transport.send(rsp.Serialize())
        if ret is False:
            self.logger.error("Send client query response failed")
Exemplo n.º 25
0
    def handleClientHello(self, hello):
        """The Hello message handler.

        :param hello: which is a HalMessage, hold all the info about the hello message
        :return:  NA

        """
        self.logger.debug("Send out the hello rsp message")

        # update the stats
        self.stats.NrMsgs += 1
        self.stats.NrHelloMsgs += 1
        if hello is None:
            msg = "Cannot handle a none client hello message"
            self.logger.error(msg)
            self.stats.NrErrorMsgs += 1
            raise Exception(msg)

        rsp = HalMessage("HalClientHelloRsp",
                         ClientID=hello.msg.ClientID)
        # send out
        self.transportPush.send(rsp.Serialize())
        self.stats.NrHelloRspMsgs += 1
Exemplo n.º 26
0
    def clientQuery(self):
        """
        Send a client query message to get all registered client info
        :return:
        """

        if self.disconnected:
            self.logger.error("The client is on disconencted state,"
                              " skip to send the message.")
            return None
        self.logger.debug("Send a client query message to Hal")
        clientQueryMsg = HalMessage("HalClientQuery", ClientID=self.clientID)
        self.mgrConnection.send(clientQueryMsg.Serialize())
        try:
            bin = self.mgrConnection.recv()
        except Exception as e:
            print("Got exception when receiving the msg, reason:%s" % str(e))
            return None
        rsp = HalMessage.DeSerialize(bin)
        if rsp.msg.MsgType != "HalClientQueryRsp":
            self.logger.error("Cannot Query client, "
                              "reason[msgType mismatch:%s]" % rsp.msg.MsgType)
            return None
        return rsp
Exemplo n.º 27
0
    def getClientstats(self, clientId):
        """
        Send a client statistics request message
        :return:
        """

        if self.disconnected:
            self.logger.error("The client is on disconencted state,"
                              " skip to send the message.")
            return None
        self.logger.debug("Send a client statistics message to Hal")
        statsQueryMsg = HalMessage("HalAgentStatsReq", ClientID=clientId)
        self.mgrConnection.send(statsQueryMsg.Serialize())
        try:
            bin = self.mgrConnection.recv()
        except Exception as e:
            print("Got exception when receiving the msg, reason:%s" % str(e))
            return None
        rsp = HalMessage.DeSerialize(bin)
        if rsp.msg.MsgType != "HalAgentStatsRsp":
            self.logger.error("Cannot Query client statistics, "
                              "reason[msgType mismatch:%s]" % rsp.msg.MsgType)
            return None
        return rsp
Exemplo n.º 28
0
    def sendCfgRspMsg(self, cfg, rsp=None):
        """The configuration response routine, the driver implementor should
        fill sth into this function.

        :param cfg: The original configuration message
        :param rsp: Reponse of the cfgmsg
        :return:

        """
        cfgMsg = cfg.msg
        hal_rsp = {"Status": HalCommon_pb2.SUCCESS, "ErrorDescription": ""}
        l2tpcfgSessionmsgType = (HalConfiMsg.MsgTypeL2tpv3SessionReqDsOfdm,
                                 HalConfiMsg.MsgTypeL2tpv3SessionReqDsOfdmPlc,
                                 HalConfiMsg.MsgTypeL2tpv3SessionReqDsScqam,
                                 HalConfiMsg.MsgTypeL2tpv3SessionReqUsAtdma,
                                 HalConfiMsg.MsgTypeL2tpv3SessionReqUsOfdma,
                                 HalConfiMsg.MsgTypeL2tpv3SessionReqScte551Fwd,
                                 HalConfiMsg.MsgTypeL2tpv3SessionReqScte551Ret,
                                 HalConfiMsg.MsgTypeL2tpv3SessionReqScte552Fwd,
                                 HalConfiMsg.MsgTypeL2tpv3SessionReqScte552Ret,
                                 HalConfiMsg.MsgTypeL2tpv3SessionReqNdf,
                                 HalConfiMsg.MsgTypeL2tpv3SessionReqNdr)
        if cfgMsg.CfgMsgType in l2tpcfgSessionmsgType:
            rsp = L2tpv3Hal_pb2.t_l2tpSessionRsp()
            req = L2tpv3Hal_pb2.t_l2tpSessionReq()
            req.ParseFromString(cfgMsg.CfgMsgPayload)
            # fill session_selector
            rsp.session_selector.local_session_id = req.session_selector.local_session_id
            rsp.session_selector.remote_session_id = req.session_selector.remote_session_id
            rsp.session_selector.local_ip = req.session_selector.local_ip
            rsp.session_selector.remote_ip = req.session_selector.remote_ip
            rsp.session_selector.lcce_id = req.session_selector.lcce_id
            rsp.result = True
            rsp.req_data.CopyFrom(req.req_data)
            payload = rsp.SerializeToString()

            try:
                self.logger.debug("msg content:%s", req)
                with open("/tmp/fakedriver-l2tp.db", "a+w") as db:
                    db.write(cfgMsg.CfgMsgPayload)
                    db.close()
            except Exception:
                self.logger.error("open file fakedriver-l2tp.db failure")

        elif cfgMsg.CfgMsgType == HalConfiMsg.MsgTypePtpStatusGet:
            payload = "ALIGNED"
        elif cfgMsg.CfgMsgType == HalConfiMsg.MsgTypeL2tpv3LcceIdAssignment:
            rsp = L2tpv3Hal_pb2.t_l2tpLcceAssignmentRsp()
            req = L2tpv3Hal_pb2.t_l2tpLcceAssignmentReq()
            req.ParseFromString(cfgMsg.CfgMsgPayload)
            # fill lcce info
            rsp.lcce_info.local_mac = req.lcce_info.local_mac
            rsp.lcce_info.remote_mac = req.lcce_info.remote_mac
            rsp.lcce_info.local_ip = req.lcce_info.local_ip
            rsp.lcce_info.remote_ip = req.lcce_info.remote_ip
            rsp.lcce_info.mtu = req.lcce_info.mtu
            rsp.lcce_id = req.lcce_id
            rsp.result = True
            payload = rsp.SerializeToString()
        elif cfgMsg.CfgMsgType == HalConfiMsg.MsgTypeRpdCapabilities:
            rsp = t_RcpMessage()
            rsp.ParseFromString(cfgMsg.CfgMsgPayload)
            self.dummy_rpd_cap(rsp.RpdDataMessage.RpdData.RpdCapabilities)
            rsp.RcpDataResult = t_RcpMessage.RCP_RESULT_OK
            payload = rsp.SerializeToString()
            self.save_rsp_db(rsp, cfgMsg.CfgMsgPayload)
        elif cfgMsg.CfgMsgType == HalConfiMsg.MsgTypeRpdInfo:
            rsp = t_RcpMessage()
            rsp.ParseFromString(cfgMsg.CfgMsgPayload)
            hal_rsp = self.dummy_rpd_info(rsp)
            rsp.RcpDataResult = t_RcpMessage.RCP_RESULT_OK
            payload = rsp.SerializeToString()
            self.save_rsp_db(rsp, cfgMsg.CfgMsgPayload)
        else:
            rsp = t_RcpMessage()
            rsp.ParseFromString(cfgMsg.CfgMsgPayload)
            rsp.RcpDataResult = t_RcpMessage.RCP_RESULT_OK
            payload = rsp.SerializeToString()
            self.save_rsp_db(rsp, cfgMsg.CfgMsgPayload)

        msg = HalMessage("HalConfigRsp",
                         SrcClientID=cfgMsg.SrcClientID,
                         SeqNum=cfgMsg.SeqNum,
                         Rsp=hal_rsp,
                         CfgMsgType=cfgMsg.CfgMsgType,
                         CfgMsgPayload=payload)
        # time.sleep(15)
        self.send(msg.Serialize())
Exemplo n.º 29
0
    def send_cfg_rsp_msg(self, cfg):
        """The configuration response routine

        :param cfg: The original configuration message
        :return:

        """
        result = HalCommon_pb2.SUCCESS
        cfgMsg = cfg.msg
        l2tpcfgmsgType = (HalConfigMsg.MsgTypeL2tpv3SessionReqDsOfdm,
                          HalConfigMsg.MsgTypeL2tpv3SessionReqDsOfdmPlc,
                          HalConfigMsg.MsgTypeL2tpv3SessionReqDsScqam,
                          HalConfigMsg.MsgTypeL2tpv3SessionReqUsAtdma,
                          HalConfigMsg.MsgTypeL2tpv3SessionReqUsOfdma,
                          HalConfigMsg.MsgTypeL2tpv3SessionReqScte551Fwd,
                          HalConfigMsg.MsgTypeL2tpv3SessionReqScte551Ret,
                          HalConfigMsg.MsgTypeL2tpv3SessionReqScte552Fwd,
                          HalConfigMsg.MsgTypeL2tpv3SessionReqScte552Ret,
                          HalConfigMsg.MsgTypeL2tpv3SessionReqNdf,
                          HalConfigMsg.MsgTypeL2tpv3SessionReqNdr,
                          HalConfigMsg.MsgTypeL2tpv3CinIfAssignment,
                          HalConfigMsg.MsgTypeL2tpv3LcceIdAssignment)
        if cfgMsg.CfgMsgType in l2tpcfgmsgType:
            rsp = L2tpv3Hal_pb2.t_l2tpSessionRsp()
            req = L2tpv3Hal_pb2.t_l2tpSessionReq()
            req.ParseFromString(cfgMsg.CfgMsgPayload)
            # fill session_selector
            rsp.session_selector.local_session_id = req.session_selector.local_session_id
            rsp.session_selector.remote_session_id = req.session_selector.remote_session_id
            rsp.session_selector.local_ip = req.session_selector.local_ip
            rsp.session_selector.remote_ip = req.session_selector.remote_ip
            rsp.result = True
        elif (cfgMsg.CfgMsgType == HalConfigMsg.MsgTypeVspAvpExchange):
            rsp = L2tpv3VspAvp_pb2.t_l2tpVspAvpMsg()
            rsp.ParseFromString(cfgMsg.CfgMsgPayload)
            self.logger.debug(
                "vsp_avp_handler re-parse srcClientID: %s, Seq num:  %d, "
                "op: %d, vid %d, attr %d, strVal %s" %
                (cfg.msg.SrcClientID, cfg.msg.SeqNum, rsp.oper, rsp.vendorId,
                 rsp.attrType, rsp.attrValBuf))
            if rsp.rspCode == L2tpv3VspAvp_pb2.t_l2tpVspAvpMsg(
            ).VSP_AVP_STATUS_FAILURE:
                # send HalConfigRsp with failure status if OpenRPD driver can't handle this.
                result = HalCommon_pb2.FAILED
        elif (cfgMsg.CfgMsgType == HalConfigMsg.MsgTypeRcpVendorSpecific):
            rsp = t_RcpMessage()
            rsp.ParseFromString(cfgMsg.CfgMsgPayload)
            self.logger.debug("send_cfg_rsp_msg payload: %s, result: %d" %
                              (rsp.RpdDataMessage.RpdData, rsp.RcpDataResult))
        else:
            rsp = t_RcpMessage()
            rsp.ParseFromString(cfgMsg.CfgMsgPayload)
            self.logger.debug("send_cfg_rsp_msg payload: %s" %
                              rsp.RpdDataMessage.RpdData)
            rsp.RcpDataResult = t_RcpMessage.RCP_RESULT_OK
        payload = rsp.SerializeToString()

        self.logger.debug("cfg response srcClientID: %s, Seq num:  %d" %
                          (cfgMsg.SrcClientID, cfgMsg.SeqNum))
        msg = HalMessage("HalConfigRsp",
                         SrcClientID=cfgMsg.SrcClientID,
                         SeqNum=cfgMsg.SeqNum,
                         Rsp={
                             "Status": HalCommon_pb2.SUCCESS,
                             "ErrorDescription": ""
                         },
                         CfgMsgType=cfgMsg.CfgMsgType,
                         CfgMsgPayload=payload)
        self.logger.debug("sending cfg response - type: %d, msg: %s" %
                          (cfgMsg.CfgMsgType, msg))
        self.pushSock.send(msg.Serialize())
Exemplo n.º 30
0
    print ClientID
    print pull
    print push

    # Create the Pull interface
    context = HalTransport.context

    pullSock = context.socket(zmq.PULL)
    pushSock = context.socket(zmq.PUSH)

    pushSock.connect("ipc://" + pull)
    pullSock.connect("ipc://" + push)

    # construct the Hello message
    helloMsg = HalMessage("HalClientHello", ClientID=ClientID)
    pushSock.send(helloMsg.Serialize())

    bin = pullSock.recv()
    rsp = HalMessage.DeSerialize(bin)

    print rsp.msg
    """
	notfication = HalNotification()
	notfication.ClientID = ClientID
	notfication.HalNotificationType = 10
	notfication.HalNotificationPayLoad = "hello"
	"""
    notfication = HalMessage("HalNotification",
                             ClientID=ClientID,
                             HalNotificationType=10,
                             HalNotificationPayLoad="hello")