예제 #1
0
    def _check_interface_status_callback(self, _):
        self.logger.debug("Check the interface status...")
        if len(self.interfaces) == 0:
            return

        stats = net_if_stats()
        for interface in self.interfaces:
            if interface not in stats:
                self.logger.error(
                    "Cannot find the interface[%s] in current system configuration." % interface)
                continue

            current_stat = self.UP if SysTools.is_if_oper_up(interface) else self.DOWN
            self.logger.debug("Check the interface[%s] status, original %s now %s ...",
                              interface, self.interfaces[interface]['status'], current_stat)

            status_changed = False
            # CHeck if there is an status change:
            if SysTools.is_if_oper_up(interface):
                if None is not self.interfaces[interface]["flappingTimer"]:
                    self.dispatcher.timer_unregister(self.interfaces[interface]["flappingTimer"])
                    self.interfaces[interface]["flappingTimer"] = None
                    self.logger.info(
                        "Cancel interface[%s] flappingTimer." % interface)

                if self.interfaces[interface]["status"] != self.UP:
                    self.interfaces[interface]["status"] = self.UP
                    status_changed = True

            elif (not SysTools.is_if_oper_up(interface)) and self.interfaces[interface]["status"] != self.DOWN:
                self.interfaces[interface]["status"] = self.DOWN
                status_changed = True
            else:
                pass

            # send the status change to the requester
            if not status_changed:
                continue

            self.logger.debug("Interface %s status changes to %s",
                              interface, self.interfaces[interface]["status"])

            popup_list = list()
            for ccap_id in self.interfaces[interface]["requester"]:
                if ccap_id not in self.ccap_cores:
                    popup_list.append(ccap_id)
                    continue
                try:
                    self._send_event_notification(
                        ccap_id,
                        protoDef.msg_core_event_notification.OK,
                        "Status changed",
                        result=self.interfaces[interface]["status"])
                except zmq.ZMQError as ex:
                    self.logger.error("failed to send to manager: %s" % str(ex))
            for ccap_id in popup_list:
                self.interfaces[interface]['requester'].remove(ccap_id)
예제 #2
0
    def scan_available_interface(self, _):
        interface_up = list()
        stats = net_if_stats()
        for interface in stats.keys():
            if interface != 'lo':
                if SysTools.is_if_oper_up(interface):
                    interface_up.append(interface)

        # need to check redefined interface proto is provision or not for RPD
        interface_ret = self.filter_proto_interface("'provision'", interface_up)

        # prepare for startup
        if self.init_start:
            for interface in interface_ret:
                SysTools.set_protocol(interface)
            self.init_start = False

        for idx in self.mgrs:
            event_request_rsp = protoDef.msg_event_notification()
            event_request_rsp.mgr_event.mgr_id = idx
            event_request_rsp.mgr_event.event_id = self.id
            event_request_rsp.mgr_event.data = json.dumps(interface_ret)
            try:
                self.mgrs[idx]['transport'].sock.send(
                    event_request_rsp.SerializeToString(), flags=zmq.NOBLOCK)
            except zmq.ZMQError as ex:
                self.logger.error("failed to send to manager: %s" % str(ex))
예제 #3
0
파일: test_utils.py 프로젝트: hujiangyi/or
    def test_sys_tools(self):
        SysTools.touch('/tmp/test_utils')
        SysTools.REBOOT_SKIP_FILES = ('/tmp/test_utils')

        self.assertFalse(SysTools.is_system_openwrt())
        self.assertEqual(SysTools.get_mac_address('if_test'),
                         "00:00:00:00:00:00")
        self.assertEqual(SysTools.get_sys_mac_address(), "00:00:00:00:00:00")

        with open('/tmp/test_mac', 'w') as f:
            f.write('01:02:03:04:05:06')
            f.close()
        SysTools.SYS_MAC_FILE = '/tmp/test_mac'
        self.assertEqual(SysTools.get_sys_mac_address(), "01:02:03:04:05:06")
        SysTools.SYS_MAC_FILE = '/etc/gshadow'
        self.assertEqual(SysTools.get_sys_mac_address(), "00:00:00:00:00:00")

        print(SysTools.get_host_name())
        print(SysTools.get_ip_address('if_test'))
        if not SysTools.reboot():
            SysTools.sys_failure_reboot('skip files exist')
        SysTools.external_reboot(('test', 'test'))
        if os.path.exists('/tmp/test_utils'):
            os.remove('/tmp/test_utils')

        # d = Dispatcher()
        # timestamp = time.time() + 1000
        # SysTools.set_system_time(d, timestamp)
        # SysTools.touch('/etc/openwrt_release')
        # SysTools.set_system_time(d, timestamp)
        # time.sleep(2)
        # self.assertTrue(timestamp > time.time()) #should no permission to change system time
        # del d
        # if os.path.exists('/etc/openwrt_release'):
        #     os.remove('/etc/openwrt_release')
        self.assertIsNotNone(SysTools.sys_up_time())
        ret = SysTools.if_indextoname(1)
        print "ifname of index 1:", ret
        self.assertIsNotNone(ret)
        ret = SysTools.if_indextoname("test")
        self.assertIsNone(ret)
        ret = SysTools.if_indextoname(600)
        self.assertIsNone(ret)

        ret = SysTools.if_nametoindex("lo")
        print "ifindex of lo:", ret
        self.assertIsNotNone(ret)
        ret = SysTools.if_nametoindex(5)
        self.assertIsNone(ret)
        ret = SysTools.if_nametoindex("dafsd")
        self.assertIsNone(ret)
        ret = SysTools.is_if_oper_up('eth0')
        self.assertTrue(ret)
예제 #4
0
파일: dhcp_agent.py 프로젝트: hujiangyi/or
    def _dhcp_no_lease(self, interface):
        """DHCP client failed to get required information.

        (backoff timer increased to maximum value without success)
         * If DHCPv6 failed -> try DHCPv4
         * If DHCPv4 failed -> reboot

        :return: False to represent DHCP fail, True if do not want to report 
                  this fail

        """
        if interface not in self.processes:
            self.logger.warn(
                "Process information about Interface[%s] doesn't exist",
                interface)
            return False

        stats = net_if_stats()
        if interface in stats and not SysTools.is_if_oper_up(interface):
            self.logger.info("Ignore this message caused by link down...")
            return False

        if interface in stats and self.dhcp[interface]['initiated']:
            self.logger.info("Ignore failure for %s previous up",
                             self.processes[interface]['name'])
            return False

        name = self.processes[interface]['name']
        if self.processes[interface]['process']:
            if name == "dhcpv6":
                # when dhcpv6 process failed, check if any duplicated ipv6 address event need to be reported
                self.check_and_report_ipv6_event(interface)
                self.logger.info("Starting DHCPv4 client ...")
                self.start_dhcpv4(interface)
                return False
            elif name == "dhcpv4":
                self.logger.warn("DHCPv4 failure...")
                SysTools.set_protocol(interface)
                self.processes[interface]['process'] = False
                return False
            else:
                raise ValueError("Unexpected process name {}".format(name))

        return False
예제 #5
0
    def process_event_action(self, action):
        """Process the request from the client.

        :param action:
        :return:

        """
        ccap_core_id = action.ccap_core_id
        event_action = action.action

        self.logger.debug("Receive an event action:%s", action)

        if ccap_core_id not in self.ccap_cores:
            self.logger.error(
                "Cannot process the event action for id %s, reason: id is not registered" % ccap_core_id)
            self._send_event_notification(
                ccap_core_id, protoDef.msg_core_event_notification.FAIL,
                "CCAP core ID is not registered")
            return

        if not action.HasField("parameter"):
            self.logger.error(
                "Cannot process the event action for id %s, reason:Parameter is not set" % ccap_core_id)
            # return error
            self._send_event_notification(
                ccap_core_id,
                protoDef.msg_core_event_notification.FAIL,
                "Parameter is not set")
            return
        parameter = action.parameter

        if event_action == protoDef.msg_event.START or event_action == protoDef.msg_event.CHECKSTATUS:
            # check if we are in the requester list, if yes, we just send a current status to it
            if parameter in self.interfaces:
                if ccap_core_id not in self.interfaces[parameter]["requester"]:
                    self.interfaces[parameter]["requester"].append(ccap_core_id)
            else:
                # create a interface in self interfaces
                self.interfaces[parameter] = {
                    "status": self.DOWN,
                    "requester": [ccap_core_id, ],
                    "flappingTimer": None,
                }
                # check interface status when first time created
                stats = net_if_stats()
                if parameter in stats and SysTools.is_if_oper_up(parameter):
                    self.interfaces[parameter]['status'] = self.UP

            self._send_event_notification(
                ccap_core_id, protoDef.msg_core_event_notification.OK,
                "Id has been issue this action, send current status to you",
                result=self.interfaces[parameter]["status"])
            return

        if event_action == protoDef.msg_event.STOP:
            if parameter in self.interfaces:
                if ccap_core_id in self.interfaces[parameter]["requester"]:
                    self.interfaces[parameter]["requester"].remove(ccap_core_id)

                if len(self.interfaces[parameter]["requester"]) == 0 and \
                        self.interfaces[parameter]["status"] == self.DOWN:
                    self.interfaces.pop(parameter)
                self._send_event_notification(
                    ccap_core_id, protoDef.msg_core_event_notification.OK,
                    reason="Successful stop event.")
            else:
                self._send_event_notification(
                    ccap_core_id, protoDef.msg_core_event_notification.FAIL,
                    reason="Cannot stop event since can not find it.")
            return