Ejemplo n.º 1
0
    def start_traffic(self):
        """Start traffic routine"""
        try:
            #            [te.start() for te in self.__traffic_executors]
            self.lgr.info(
                to_string("{}: Total traffic executors: [{}]", self.clientid,
                          self.__traffic_executors.qsize()))
            while self.__traffic_executors.qsize() > 0 and Agent.initialized:
                self.lgr.info(
                    to_string("{}: executors: {}, agent init: {}",
                              self.clientid, self.__traffic_executors.qsize(),
                              Agent.initialized))
                te = self.__traffic_executors.get()
                te.run()
                pub_status(
                    self.mqclient, rt.tcfg.mqtt_qos, {
                        T_TRAFFIC_STATUS: TrafficStatus.RUNNING.name,
                        T_CLIENTID: self.clientid,
                        T_TID: te.tid,
                    })
#                te.finished.wait()
#                self.lgr.debug(to_string("{} finished", te))
        except Exception as ex:
            self.lgr.error(to_string("Exception on running traffic: {}", ex))
            pub_status(
                self.mqclient, rt.tcfg.mqtt_qos, {
                    T_TRAFFIC_STATUS: TrafficStatus.AGENTFAILED.name,
                    T_VERSION: __version__,
                    T_MQTT_VERSION: mqtt.VERSION_NUMBER,
                    T_CLIENTID: self.clientid,
                    T_MSG: 'Start traffic failed',
                })
Ejemplo n.º 2
0
 def _read(self, rdbyte=0):
     """Read data ultility"""
     #        rdsize = rdbyte == 0 and self.dev.inWaiting() or rdbyte
     rdbuf = ''
     try:
         while self.running:
             if self.reporter:
                 self.reporter.loop()
             rdbuf = self._read_one()
             if self.tsh_on:
                 pub_reply(self.reporter,
                           data={
                               T_NODE: self,
                               T_MSG: rdbuf,
                           })
                 self.tsh_on = False
             if len(rdbuf) > 0:
                 self.report_read(rdbuf)
     except serial.SerialException as ex:
         self.lgr.error(to_string("Serial exception on reading: {}", ex))
         pub_status(self.reporter,
                    data={
                        T_TRAFFIC_STATUS: TrafficStatus.AGENTFAILED.name,
                        T_NODE: self,
                        T_MSG: str(ex),
                    })
Ejemplo n.º 3
0
    def fire(self):

        if not self.running or self.current >= self.end:
            self.lgr.debug(
                to_string("Traffic stopped: {}/{}", self.current, self.end))
            self.stop_trigger()
            return

        self.lgr.debug(
            to_string("{} firing: {}/{}", self, self.current, self.end))

        try:
            with self._mutex:
                self.node.traffic(self.request)
                #               self.nextshot.wait(self.interval)
                #               self.nextshot.clear()
                self.current = time.time()

            if self.running and self.current < self.end:
                self.nextshot()
            else:
                self.stop_trigger()
        except Exception as ex:
            self.lgr.error(to_string("Traffic exception: {}", ex))
            self.running = False
            self.node.in_traffic = False
            pub_status(self.mqclient,
                       data={
                           T_TRAFFIC_STATUS: TrafficStatus.AGENTFAILED.name,
                           T_TID: self.tid,
                           T_MSG: str(ex),
                       })
Ejemplo n.º 4
0
    def on_topic_nwlayout(client, userdata, message):
        """Network layout handler"""
        self = userdata
        try:
            data = extract_payload(message.payload)
            if not self.is_msg_for_me([data.get(T_CLIENTID)]):
                return
            self.lgr.debug(to_string("JOIN: {}", data))
            naddr = data.get(T_NODE)
            if naddr is None:
                self.lgr.error(to_string("JOIN: Incorrect command {}", data))
                return

            node = self.addr2node.get(naddr)
            if node is None:
                self.lgr.error(to_string("JOIN: Node {} not connected", naddr))
                return
            #TODO remove addr->node map
            if node.addr:
                self.lgr.debug(to_string("JOIN: Found node: {}", node))
                node.joined = False
                node.writable.set()
                node.join(data)
            else:  # DEBUG
                self.lgr.error(
                    to_string("{}: Node [{}] not found", self.clientid, naddr))
        except Exception as ex:
            self.lgr.error(
                to_string("Failure on handling nwlayout request: {}", ex))
            pub_status(
                self.mqclient, rt.tcfg.mqtt_qos, {
                    T_TRAFFIC_STATUS: TrafficStatus.AGENTFAILED.name,
                    T_CLIENTID: self.clientid,
                    T_MSG: 'Failed to configure network',
                })
Ejemplo n.º 5
0
 def start(self):
     """Start Agent routine"""
     if not Agent.initialized:
         self.lgr.error(to_string("Agent not initialized"))
         return
     status_msg = 'Agent fine'
     try:
         self.lgr.info(to_string("Starting Agent {}", self.clientid))
         if self.worker:
             self.worker.start()
         self.alive_notification()
         self.mqclient.loop_forever()
     except KeyboardInterrupt:
         status_msg = to_string("Agent received keyboard interrupt")
         self.lgr.error(status_msg)
     except NameError as ex:
         self.lgr.error(to_string("ERR: {}", ex))
         raise
     except Exception as ex:
         status_msg = to_string("Exception on Agent: {}", ex)
         self.lgr.error(status_msg)
         pub_status(
             self.mqclient, rt.tcfg.mqtt_qos, {
                 T_TRAFFIC_STATUS: TrafficStatus.AGENTFAILED.name,
                 T_CLIENTID: self.clientid,
                 T_MSG: status_msg,
             })
     self.teardown(status_msg)
     self.lgr.info(to_string("Agent terminated"))
Ejemplo n.º 6
0
    def alive_notification(self, scan_required=True):
        """Post alive notification
        @scan_nodes Whether need to scan connected nodes before post
        """
        self.lgr.info(to_string("Alive notification"))
        try:
            if scan_required:
                self.lgr.info(to_string("Got scan nodes request"))
                with Agent.__mutex:
                    scan_nodes(
                        self.adapter)  #[to_string(DEV_TTY, T_EVERYONE)])
                    self.addr_to_node()

            self.lgr.info(
                to_string("Connected nodes: [{}]", len(self.adapter.nodes)))
            data = {
                T_CLIENTID: self.clientid,
                T_HOST: self.host,
                T_NODES: [str(node) for node in self.adapter.nodes.values()],
                T_VERSION: __version__,
                T_MQTT_VERSION: mqtt.VERSION_NUMBER,
            }
            pub_heartbeat(self.mqclient, rt.tcfg.mqtt_qos, data)
        except Exception as ex:
            self.lgr.error(to_string("Alive notification exception:{}", ex))
            pub_status(
                self.mqclient, rt.tcfg.mqtt_qos, {
                    T_TRAFFIC_STATUS: TrafficStatus.AGENTFAILED.name,
                    T_VERSION: __version__,
                    T_MQTT_VERSION: mqtt.VERSION_NUMBER,
                    T_CLIENTID: self.clientid,
                    T_MSG: 'Hearbeat failed, check me out',
                })
            self.teardown()
Ejemplo n.º 7
0
    def on_traffic_scmd(self, data):
        """Serial command handler
        """
        self.lgr.debug(to_string("TRAFFIC: {}", data))
        naddr = data.get(T_NODE)
        if naddr is None:
            self.lgr.error(to_string("TRAFFIC: Incorrect command {}", data))
            return

        node = self.addr2node.get(naddr)
        if node is None:
            self.lgr.error(to_string("TRAFFIC: Node {} not connected", naddr))
            return

        if node.addr and node.addr == data.get(T_SRC):
            self.lgr.debug(to_string("TRAFFIC: Found node: {}", node))
            request = {
                T_HOST: self.host,
                T_CLIENTID: self.clientid,
                T_GENID: data.get(T_GENID),
                T_TRAFFIC_TYPE: data.get(T_TRAFFIC_TYPE),
                T_NODE: data.get(T_NODE).encode(),
                T_SRC: data.get(T_SRC).encode(),
                T_DESTS: [d.encode() for d in data.get(T_DESTS)],
                T_PKGSIZE: data.get(T_PKGSIZE),
            }
            te = None
            #            if rt.tcfg.enable_localdebug:
            #                dest = None
            #                if data.get(T_DEST) == TRAFFIC_BROADCAST_ADDRESS:
            #                    dest = set(self.addr2node.values())
            #                else:
            #                    dest = set([self.addr2node.get(data.get(T_DEST))])
            #                te = TrafficExecutor(node, data.get(T_INTERVAL), data.get(T_DURATION),\
            #                    request=request, lgr=self.lgr, mqclient=self.mqclient, tid=data.get(T_TID),\
            #                    data=dest)
            #            else:
            te = TrafficExecutor(node, float(data.get(T_INTERVAL)), float(data.get(T_DURATION)), float(data.get(T_JITTER)),\
                request=request, lgr=self.lgr, mqclient=self.mqclient, tid=data.get(T_TID))

            self.__traffic_executors.put(te)
            pub_status(
                self.mqclient, rt.tcfg.mqtt_qos, {
                    T_TRAFFIC_STATUS: TrafficStatus.REGISTERED.name,
                    T_CLIENTID: self.clientid,
                    T_TID: data.get(T_TID),
                })
            # start on registered
#            te.start()
#            pub_status(self.mqclient, rt.tcfg.mqtt_qos, {
#                T_TRAFFIC_STATUS: TrafficStatus.RUNNING.name,
#                T_CLIENTID: self.clientid,
#                T_TID: te.tid,
#            })
        else:
            self.lgr.error(
                to_string("{}: Node [{}] not found", self.clientid, naddr))
Ejemplo n.º 8
0
    def stop_trigger(self):

        with self._mutex:
            if not self.running:
                return
            to_console("{}: Stopping trigger", self)
            self.node.in_traffic = False
            self.running = False
            #        self.stop_timer.cancel()
            if self.trigger:
                self.trigger.cancel()
            if self.mqclient is not None:
                pub_status(self.mqclient,
                           data={
                               T_TRAFFIC_STATUS: TrafficStatus.FINISHED.name,
                               T_TID: self.tid,
                           })
Ejemplo n.º 9
0
 def on_topic_traffic(client, userdata, message):
     """Traffic topic handler"""
     self = userdata
     #        self.lgr.info(to_string("On topic traffic"))
     try:
         data = extract_payload(message.payload)
         if not self.is_msg_for_me([data.get(T_CLIENTID)]):
             return
         self.lgr.debug(to_string("Traffic data: {}", data))
         self.traffic_dispatch(data)
     except Exception as ex:
         self.lgr.error(
             to_string("Failure on handling traffic request: {}", ex))
         pub_status(
             self.mqclient, rt.tcfg.mqtt_qos, {
                 T_TRAFFIC_STATUS: TrafficStatus.AGENTFAILED.name,
                 T_CLIENTID: self.clientid,
                 T_MSG: 'Failed to register traffic',
             })
Ejemplo n.º 10
0
 def __do_init(self):
     """
     __host: IP address of agent
     __clientid: identity in MQ network
     """
     self.lgr.info(to_string("Do initialization"))
     try:
         self.create_mqtt_client(*rt.tcfg.mqtt)
         self.adapter = NodeAdapter(self.mqclient, lgr=self.lgr)
         Agent.initialized = True
     except Exception as ex:
         self.lgr.error(to_string("Failed to initialize: {}", ex))
         pub_status(
             self.mqclient, rt.tcfg.mqtt_qos, {
                 T_TRAFFIC_STATUS: TrafficStatus.INITFAILED.name,
                 T_CLIENTID: self.clientid,
                 T_MSG: str(ex),
             })
         raise RuntimeError(to_string("Failed to initialize: {}", ex))
Ejemplo n.º 11
0
 def teardown(self, msg='Teardown'):
     """Cleanup"""
     if not Agent.initialized:
         return
     self.lgr.info(to_string("Agent teardown: {}", self.clientid))
     try:
         if Agent.initialized:
             Agent.initialized = False
             msg = to_string("{}:{}", self.clientid, msg)
             self.stop_traffic_trigger()
             if self._heartbeat is not None:
                 self._heartbeat.stop()
             if self.adapter is not None:
                 self.adapter.teardown()
             if self.worker:
                 self.worker.stop()
             pub_status(self.mqclient, rt.tcfg.mqtt_qos, {T_MSG: msg})
             self.unregister()
             self.mqclient.disconnect()
     except Exception as ex:
         self.lgr.error(to_string("Exception on teardown: {}", ex))