Exemple #1
0
    def rpc_get_config (self, unused_session, rpc, source_elm, unused_filter_elm):
        assert source_elm is not None
        if source_elm.find("nc:running", namespaces=NSMAP) is None:
            raise ncerror.RPCSvrMissingElement(rpc, ncutil.elm("nc:running"))

        config = ncutil.elm("data")

        if self.is_tfm:
            profile_elm = ncutil.elm("j:scan-profile")
            config.append(profile_elm)
            profile_elm.append(ncutil.leaf_elm("j:channel-spacing",
                                               self.device.get_channel_spacing()))
            profile_elm.append(ncutil.leaf_elm("j:frequency-start",
                                               self.device.get_start_freq()))
            profile_elm.append(ncutil.leaf_elm("j:frequency-end",
                                               self.device.get_stop_freq()))
        else:
            for idx in range(1, 17):
                profile_elm = ncutil.elm("j:channel-profile")
                config.append(profile_elm)
                profile_elm.append(ncutil.leaf_elm("j:profile-index", idx))

                channels = self.device.get_channel_profile(idx)
                for freqs, freqe in channels:
                    channel_elm = ncutil.subelm(profile_elm, "j:channel")
                    range_elm = ncutil.subelm(channel_elm, "j:range")
                    range_elm.append(ncutil.leaf_elm("j:frequency-start", freqs))
                    range_elm.append(ncutil.leaf_elm("j:frequency-end", freqe))
        return config
Exemple #2
0
    def rpc_get_config(self, unused_session, rpc, source_elm,
                       unused_filter_elm):
        assert source_elm is not None
        if source_elm.find("nc:running", namespaces=NSMAP) is None:
            raise ncerror.RPCSvrMissingElement(rpc, ncutil.elm("nc:running"))

        config = ncutil.elm("data")

        if self.is_tfm:
            profile_elm = ncutil.elm("j:scan-profile")
            config.append(profile_elm)
            profile_elm.append(
                ncutil.leaf_elm("j:channel-spacing",
                                self.device.get_channel_spacing()))
            profile_elm.append(
                ncutil.leaf_elm("j:frequency-start",
                                self.device.get_start_freq()))
            profile_elm.append(
                ncutil.leaf_elm("j:frequency-end",
                                self.device.get_stop_freq()))
        else:
            for idx in range(1, 17):
                profile_elm = ncutil.elm("j:channel-profile")
                config.append(profile_elm)
                profile_elm.append(ncutil.leaf_elm("j:profile-index", idx))

                channels = self.device.get_channel_profile(idx)
                for freqs, freqe in channels:
                    channel_elm = ncutil.subelm(profile_elm, "j:channel")
                    range_elm = ncutil.subelm(channel_elm, "j:range")
                    range_elm.append(
                        ncutil.leaf_elm("j:frequency-start", freqs))
                    range_elm.append(ncutil.leaf_elm("j:frequency-end", freqe))
        return config
Exemple #3
0
    def rpc_get(self, unused_session, unused_rpc, filter_elm):
        data = ncutil.elm("data")

        get_data_methods = {
            ncutil.qname("j:ocm-type").text: self.device.get_device_type,
            ncutil.qname("j:oper-mode").text: self.device.get_oper_mode,
            ncutil.qname("j:ident-data").text: self.device.get_idn_string,
            ncutil.qname("j:device-info").text: self.device.get_module_info,
            ncutil.qname("j:application-version").text:
            self.device.get_app_version,
            ncutil.qname("j:temp").text: self.device.get_temp_int,
        }
        if not self.device.get_device_type().startswith("tf"):
            get_data_methods[ncutil.qname(
                "j:safe-version").text] = self.device.get_safe_version

        infonode = ncutil.elm("j:info")
        # infonode = etree.Element(ncutil.qname("j:info"), nsmap={ 'j': NSMAP['j'] })

        # Get filter children
        children = []
        if filter_elm is not None:
            children = filter_elm.getchildren(
            ) if filter_elm is not None else []

        def get_all_values():
            leaf_elms = []
            for key, valuef in get_data_methods.items():
                leaf_elms.append(ncutil.leaf_elm(key, valuef()))
            return leaf_elms

        # No filter children return info only
        if not children:
            ncutil.filter_leaf_values(None, infonode, get_all_values(), data)
            return data

        # Look for info filter.
        finfo = filter_elm.find("info") or filter_elm.find("j:info",
                                                           namespaces=NSMAP)
        if finfo is not None:
            children = finfo.getchildren()
            if not children:
                leaf_elms = get_all_values()
            else:
                leaf_elms = []
                for felm in children:
                    tag = felm.tag
                    if tag in get_data_methods:
                        leaf_elms.append(
                            ncutil.leaf_elm(tag, get_data_methods[tag]()))
                        rv = ncutil.filter_leaf_values(finfo, infonode,
                                                       leaf_elms, data)
                        # Some selector doesn't match return empty.
            if rv is False:
                logger.error("XXX returning False")
                return data

        return data
Exemple #4
0
    def unlock_async(self, target):
        """Unlock target datastore asynchronously.

        :param target: A string specifying the config datastore to unlock.
        :return: The RPC message id which can be passed to wait_reply for the results.
        :raises: SessionError
        """
        unlockelm = util.elm("unlock")
        if not hasattr(target, "nsmap"):
            target = util.elm(target)
        util.subelm(util.subelm(unlockelm, "target"), target)
        return self.send_rpc_async(unlockelm)
Exemple #5
0
    def rpc_get (self, unused_session, unused_rpc, filter_elm):
        data = ncutil.elm("data")

        get_data_methods = {
            ncutil.qname("j:ocm-type").text: self.device.get_device_type,
            ncutil.qname("j:oper-mode").text: self.device.get_oper_mode,
            ncutil.qname("j:ident-data").text: self.device.get_idn_string,
            ncutil.qname("j:device-info").text: self.device.get_module_info,
            ncutil.qname("j:application-version").text: self.device.get_app_version,
            ncutil.qname("j:temp").text: self.device.get_temp_int,
        }
        if not self.device.get_device_type().startswith("tf"):
            get_data_methods[ncutil.qname("j:safe-version").text] = self.device.get_safe_version

        infonode = ncutil.elm("j:info")
        # infonode = etree.Element(ncutil.qname("j:info"), nsmap={ 'j': NSMAP['j'] })

        # Get filter children
        children = []
        if filter_elm is not None:
            children = filter_elm.getchildren() if filter_elm is not None else []

        def get_all_values ():
            leaf_elms = []
            for key, valuef in get_data_methods.items():
                leaf_elms.append(ncutil.leaf_elm(key, valuef()))
            return leaf_elms

        # No filter children return info only
        if not children:
            ncutil.filter_leaf_values(None, infonode, get_all_values(), data)
            return data

        # Look for info filter.
        finfo = filter_elm.find("info") or filter_elm.find("j:info", namespaces=NSMAP)
        if finfo is not None:
            children = finfo.getchildren()
            if not children:
                leaf_elms = get_all_values()
            else:
                leaf_elms = []
                for felm in children:
                    tag = felm.tag
                    if tag in get_data_methods:
                        leaf_elms.append(ncutil.leaf_elm(tag, get_data_methods[tag]()))
                        rv = ncutil.filter_leaf_values(finfo, infonode, leaf_elms, data)
                        # Some selector doesn't match return empty.
            if rv is False:
                logger.error("XXX returning False")
                return data

        return data
Exemple #6
0
    def lock_async(self, target):
        """Lock target datastore asynchronously.

        :param target: A string specifying the config datastore to lock.
        :return: The RPC message id which can be passed to wait_reply for the results.
        :raises: SessionError
        """
        lockelm = util.elm("nc:lock")
        if not hasattr(target, "nsmap"):
            target = util.elm(
                target if ":" in target or target.startswith("{") else "nc:" +
                target)
        util.subelm(util.subelm(lockelm, "nc:target"), target)
        return self.send_rpc_async(lockelm)
Exemple #7
0
    def rpc_get(self, session, rpc, filter_or_none):  # pylint: disable=W0613
        """Passed the filter element or None if not present"""
        data = util.elm("nc:data")

        # if False: # If NMDA
        #     sysc = util.subelm(data, "system")
        #     sysc.append(util.leaf_elm("hostname", socket.gethostname()))

        #     # Clock
        #     clockc = util.subelm(sysc, "clock")
        #     tzname = time.tzname[time.localtime().tm_isdst]
        #     clockc.append(util.leaf_elm("timezone-utc-offset", int(time.timezone / 100)))

        sysc = util.subelm(data, "sys:system-state")
        platc = util.subelm(sysc, "sys:system")

        platc.append(util.leaf_elm("sys:os-name", platform.system()))
        platc.append(util.leaf_elm("sys:os-release", platform.release()))
        platc.append(util.leaf_elm("sys:os-version", platform.version()))
        platc.append(util.leaf_elm("sys:machine", platform.machine()))

        # Clock
        clockc = util.subelm(sysc, "sys:clock")
        now = datetime.datetime.now()
        clockc.append(util.leaf_elm("sys:current-datetime", date_time_string(now)))

        if os.path.exists("/proc/uptime"):
            with open('/proc/uptime', 'r') as f:
                uptime_seconds = float(f.readline().split()[0])
            boottime = time.time() - uptime_seconds
            boottime = datetime.datetime.fromtimestamp(boottime)
            clockc.append(util.leaf_elm("sys:boot-datetime", date_time_string(boottime)))

        return util.filter_results(rpc, data, filter_or_none, self.server.debug)
Exemple #8
0
    def _build_yp_establish_subscription_shell(self, datastore,
                                               datastore_subtree_filter,
                                               datastore_xpath_filter):
        es_nsmap = {'yp': 'urn:ietf:params:xml:ns:yang:ietf-yang-push'}
        root = etree.Element(
            'establish-subscription',
            nsmap=es_nsmap,
            attrib={
                'xmlns':
                'urn:ietf:params:xml:ns:yang:ietf-subscribed-notifications'
            })

        datastore_leaf = util.leaf_elm('yp:datastore', f'ds:{datastore}')
        root.append(datastore_leaf)

        if datastore_subtree_filter:
            selection_filter = util.elm('yp:datastore-subtree-filter')
            if isinstance(datastore_subtree_filter, etree.Element):
                selection_filter.append(datastore_subtree_filter)
            else:
                selection_filter.text = datastore_subtree_filter
        elif datastore_xpath_filter:
            selection_filter = util.leaf_elm('yp:datastore-xpath-filter',
                                             datastore_xpath_filter)
        else:
            raise ValueError("Missing selection filter")

        root.append(selection_filter)

        return root
Exemple #9
0
    def send_hello(self, caplist, session_id=None):
        msg = ncutil.elm("hello", attrib={'xmlns': NSMAP['nc']})
        caps = ncutil.elm("capabilities")
        for cap in caplist:
            ncutil.subelm(caps, "capability").text = str(cap)
        if session_id is not None:
            assert hasattr(self, "methods")
            self.methods.nc_append_capabilities(caps)  # pylint: disable=E1101
        msg.append(caps)

        if self.debug:
            logger.debug("%s: Sending HELLO", str(self))
        if session_id is not None:
            msg.append(ncutil.leaf_elm("session-id", str(session_id)))
        msg = etree.tostring(msg)
        self.send_message(msg.decode('utf-8'))
Exemple #10
0
    def rpc_get(self, session, rpc, filter_or_none):  # pylint: disable=W0613
        """Passed the filter element or None if not present"""
        data = util.elm("nc:data")

        self._add_config(data)

        #
        # State Data
        #
        sysd = util.subelm(data, "sys:system-state")

        # System Identification
        platc = util.subelm(sysd, "sys:platform")
        platc.append(util.leaf_elm("sys:os-name", platform.system()))
        platc.append(util.leaf_elm("sys:os-release", platform.release()))
        platc.append(util.leaf_elm("sys:os-version", platform.version()))
        platc.append(util.leaf_elm("sys:machine", platform.machine()))

        # System Clock
        clockc = util.subelm(sysd, "sys:clock")
        now = datetime.datetime.now()
        clockc.append(
            util.leaf_elm("sys:current-datetime", date_time_string(now)))

        if os.path.exists("/proc/uptime"):
            with open('/proc/uptime', 'r') as f:
                uptime_seconds = float(f.readline().split()[0])
            boottime = time.time() - uptime_seconds
            boottime = datetime.datetime.fromtimestamp(boottime)
            clockc.append(
                util.leaf_elm("sys:boot-datetime", date_time_string(boottime)))

        return util.filter_results(rpc, data, filter_or_none,
                                   self.server.debug)
Exemple #11
0
    def rpc_get_config(self, session, rpc, source_elm, filter_or_none):  # pylint: disable=W0613
        assert source_elm is not None
        if source_elm.find("nc:running", namespaces=NSMAP) is None:
            # Really this should be a different error its a bad value for source not missing
            raise ncerror.MissingElementProtoError(rpc, ncutil.qname("nc:running"))

        data = ncutil.elm("data")
        cont = ncutil.subelm(data, "interfaces")
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "Ethernet0/0"))
        listval.append(ncutil.leaf_elm("shutdown", "true"))
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "Ethernet0/1"))
        listval.append(ncutil.leaf_elm("shutdown", "false"))
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "FastEthernet1/0"))
        listval.append(ncutil.leaf_elm("shutdown", "false"))
        listval = ncutil.subelm(cont, "interface")
        listval.append(ncutil.leaf_elm("name", "FastEthernet1/1"))
        listval.append(ncutil.leaf_elm("shutdown", "false"))
        # Missing from operational
        listval.append(ncutil.leaf_elm("name", "GigabitEthernet2/0"))
        listval.append(ncutil.leaf_elm("shutdown", "false"))

        return ncutil.filter_results(rpc, data, filter_or_none)
Exemple #12
0
    def rpc_reset(self, unused, rpc, *params):
        # Input values
        if params:
            raise ncerror.RPCSvrErrBadMsg(rpc)

        self._run_device_method(rpc, self.device.reset)
        return ncutil.elm("ok")
Exemple #13
0
    def rpc_reset (self, unused, rpc, *params):
        # Input values
        if params:
            raise ncerror.RPCSvrErrBadMsg(rpc)

        self._run_device_method(rpc, self.device.reset)
        return ncutil.elm("ok")
Exemple #14
0
    def rpc_full_itu_scan (self, unused_session, rpc, *params):
        # No input values yet
        try:
            if len(params) > 2:
                raise ncerror.RPCSvrInvalidValue(rpc, message="Too many parameters")
            # XXX Should be able to use "j:high-resolution" but it fails
            hires = self._rpc_param_get_boolean(rpc, "high-resolution", False, params)
            power_only = not self._rpc_param_get_boolean(rpc, "detect-presence", False, params)
            if power_only:
                points = self._run_device_method(rpc, self.device.get_itu_power_scan, hires)
            else:
                points = self._run_device_method(rpc, self.device.get_itu_scan, hires)

            result = ncutil.elm("data")
            for tup in points:
                ptelm = ncutil.subelm(result, "j:point")
                ptelm.append(ncutil.leaf_elm("j:frequency", tup[0]))
                if power_only:
                    ptelm.append(ncutil.leaf_elm("j:power", "{:.2f}".format(tup[1].dBm)))
                else:
                    ptelm.append(ncutil.leaf_elm("j:power", "{:.2f}".format(tup[2].dBm)))
                    ptelm.append(ncutil.leaf_elm("j:channel-presence", tup[1]))
            return result
        except jerror.OCMError as ocmerr:
            logger.error("Got OCM error in full itu scan: %s: %s", str(ocmerr),
                         traceback.format_exc())
        except Exception as err:
            logger.error("Got error in full itu scan: %s: %s", str(err),
                         traceback.format_exc())
            raise
Exemple #15
0
    def rpc_bootstrap(self, session, rpc, *params):
        """Passed the filter element or None if not present"""
        #print(etree.tounicode(rpc, pretty_print=True))
        data = util.elm("nc:data")

        xPathResult = rpc.xpath("//nc:bootstrap/nc:bootInfo/nc:bootInfoASN",
                                namespaces=NSMAP)
        if not xPathResult:
            print("no bootstrapping ASN found")
            #data.append(util.leaf_elm("result", "RPC result string"))
        else:
            bootparam_base64 = xPathResult[0].text
            #print (received_record['id'])

        xPathResult = rpc.xpath(
            "//nc:bootstrap/nc:bootInfo/nc:bootInfoSignature",
            namespaces=NSMAP)

        #if there is no signature, just accecpt the unsigned Information
        if not xPathResult:
            print("no siganture found")
            doBootstrap(bootparam_base64)

        #if there is a signature, check the signed ownerCertificate and accept it
        else:
            signature_base64 = xPathResult[0].text
            signature = base64.b64decode(signature_base64)
            if verifyString(self.ownerCertificate, signature,
                            bootparam_base64.encode('ascii'), "sha256"):
                doBootstrap(bootparam_base64)

        return util.filter_results(rpc, data, None)
Exemple #16
0
    def get_config_async(self, source, select):
        """Get config asynchronously for a given source from the server. If `select` is
        specified it is either an XPATH expression or XML subtree filter for
        selecting a subsection of the config.

        :param source: the source of the config, defaults to "running".
        :param select: An XML subtree filter or XPATH expression to select a subsection of config.
        :return: The RPC message id which can be passed to wait_reply for the results.
        :raises: SessionError
        """
        getelm = util.elm("get-config")
        if not hasattr(source, "nsmap"):
            source = util.elm(source)
        util.subelm(util.subelm(getelm, "source"), source)
        _get_selection(getelm, select)
        return self.send_rpc_async(getelm)
Exemple #17
0
    def rpc_get(self, session, rpc, filter_or_none):  # pylint: disable=W0613
        data = ncutil.elm("nc:data")
        cont = ncutil.subelm(data, "t:interfaces")
        # Not in config
        listval = ncutil.subelm(cont, "t:interface")
        listval.append(ncutil.leaf_elm("t:name", "AutoInterface0/0"))
        listval.append(ncutil.leaf_elm("t:shutdown", "false"))
        listval.append(ncutil.leaf_elm("t:state", "up"))
        # In config
        listval = ncutil.subelm(cont, "t:interface")
        listval.append(ncutil.leaf_elm("t:name", "Ethernet0/0"))
        listval.append(ncutil.leaf_elm("t:shutdown", "true"))
        listval.append(ncutil.leaf_elm("t:state", "down"))
        listval = ncutil.subelm(cont, "t:interface")
        listval.append(ncutil.leaf_elm("t:name", "Ethernet0/1"))
        listval.append(ncutil.leaf_elm("t:shutdown", "false"))
        listval.append(ncutil.leaf_elm("t:state", "down"))
        listval = ncutil.subelm(cont, "t:interface")
        listval.append(ncutil.leaf_elm("t:name", "FastEthernet1/0"))
        listval.append(ncutil.leaf_elm("t:shutdown", "false"))
        listval.append(ncutil.leaf_elm("t:state", "up"))
        listval = ncutil.subelm(cont, "t:interface")
        listval.append(ncutil.leaf_elm("t:name", "FastEthernet1/1"))
        listval.append(ncutil.leaf_elm("t:shutdown", "false"))
        listval.append(ncutil.leaf_elm("t:state", "down"))

        return ncutil.filter_results(rpc, data, filter_or_none)
Exemple #18
0
 def rpc_get_config(self, session, rpc, source_elm, filter_or_none):  # pylint: disable=W0613
     """Passed the source element"""
     data = util.elm("nc:data")
     #
     # Config Data
     #
     self._add_config(data)
     return util.filter_results(rpc, data, filter_or_none)
Exemple #19
0
 def rpc_my_cool_rpc(self, session, rpc, *params):
     data = ncutil.elm("nc:data")
     #data = ncutil.elm("data")
     #data.append(ncutil.leaf_elm("pfx:result", "RPC result string"))
     data.append(ncutil.leaf_elm("result", "RPC result string"))
     #print (type(data), data.tag, data.attrib)
     print(etree.tounicode(rpc))
     print(session, params)
     return data
Exemple #20
0
    def _rpc_full_scan (self, method, rpc, *params):
        # No input values yet
        if params:
            logging.error("%s: _rpc_full_scan got unexpected params", str(self))
            raise ncerror.RPCSvrErrBadMsg(rpc)

        rv = self._run_device_method(rpc, method)

        result = ncutil.elm("data")
        for port, points in rv:
            portelm = ncutil.elm("j:port")
            result.append(portelm)
            portelm.append(ncutil.leaf_elm("j:port-index", port))
            for freq, power in points:
                ptelm = ncutil.subelm(portelm, "j:point")
                ptelm.append(ncutil.leaf_elm("j:frequency", freq))
                ptelm.append(ncutil.leaf_elm("j:power", "{:.2f}".format(power.dBm)))
        return result
Exemple #21
0
    def rpc_frequency_power (self, unused, rpc, *params):
        if len(params) > 1:
            # XXX need a function to look for unknown elements and raise exc for those.
            # XXX really need a better error for not handled params
            raise ncerror.RPCSvrInvalidValue(rpc, message="Too many parameter")

        freq = self._rpc_param_get_frequency(rpc, params)
        power = self._run_device_method(rpc, self.device.get_freq_power, freq)
        result = ncutil.elm("data")
        result.append(ncutil.leaf_elm("j:power", "{:.2f}".format(power.dBm)))
        return result
Exemple #22
0
    def _rpc_full_scan(self, method, rpc, *params):
        # No input values yet
        if params:
            logging.error("%s: _rpc_full_scan got unexpected params",
                          str(self))
            raise ncerror.RPCSvrErrBadMsg(rpc)

        rv = self._run_device_method(rpc, method)

        result = ncutil.elm("data")
        for port, points in rv:
            portelm = ncutil.elm("j:port")
            result.append(portelm)
            portelm.append(ncutil.leaf_elm("j:port-index", port))
            for freq, power in points:
                ptelm = ncutil.subelm(portelm, "j:point")
                ptelm.append(ncutil.leaf_elm("j:frequency", freq))
                ptelm.append(
                    ncutil.leaf_elm("j:power", "{:.2f}".format(power.dBm)))
        return result
Exemple #23
0
    def rpc_get(self, session, rpc, filter_or_none):  # pylint: disable=W0613
        """
        Retrieve all or part of specified configuration.

        :param session: the server session with the client
        :type session: NetconfServerSession
        :param rpc: the topmost element in the received message
        :type rpc: lxml.Element
        :param filter_or_none: the filter element if present
        :type filter_or_none: lxml.Element or None
        :return: "nc:data" type containing the requested state
        :rtype: lxml.Element
        """
        logger.debug("GET")
        try:
            # extract bn, En and eq from running configuration datastore using pyangbind format
            eq = str(self.configuration.DRoF_configuration.equalization)
            bn, En = self.extract_bn_and_En(self.configuration)

            # DAC/OSC setup
            result = self.ac.dac_setup(bn, En, eq)

            # modify SNR and BER in running configuration datastore
            SNR = result[0]
            BER = result[1]
            self.modify_SNR_and_BER(BER, SNR)
            logger.info(pybindJSON.dumps(self.configuration))

            # get new SNR and BER from running configuration datastore
            data = etree.XML(pybindIETFXMLEncoder.serialise(
                self.configuration))
            monitor = data.findall(
                ".//xmlns:monitor",
                namespaces={'xmlns': "urn:blueSPACE-DRoF-configuration"})
            ber = data.find(
                ".//xmlns:BER",
                namespaces={'xmlns': "urn:blueSPACE-DRoF-configuration"})

            # create NETCONF rpc-reply message with the new SNR and BER from running configuration datastore
            data_reply = util.elm("data")
            top = util.subelm(
                data_reply,
                "{urn:blueSPACE-DRoF-configuration}DRoF-configuration")
            for value in monitor:
                m = util.subelm(top, 'monitor')
                m.append(util.leaf_elm('subcarrier-id', str(value[0].text)))
                m.append(util.leaf_elm('SNR', str(value[1].text)))
            top.append(util.leaf_elm('BER', str(ber.text)))

            return util.filter_results(rpc, data_reply, filter_or_none)

        except Exception as e:
            logger.error("GET, error: {}".format(e))
            raise e
Exemple #24
0
    def rpc_frequency_power(self, unused, rpc, *params):
        if len(params) > 1:
            # XXX need a function to look for unknown elements and raise exc for those.
            # XXX really need a better error for not handled params
            raise ncerror.RPCSvrInvalidValue(rpc, message="Too many parameter")

        freq = self._rpc_param_get_frequency(rpc, params)
        power = self._run_device_method(rpc, self.device.get_freq_power, freq)
        result = ncutil.elm("data")
        result.append(ncutil.leaf_elm("j:power", "{:.2f}".format(power.dBm)))
        return result
Exemple #25
0
    def rpc_get_config(self, session, rpc, source_elm, filter_or_none):  # pylint: disable=W0613
        """Passed the source element"""
        data = util.elm("nc:data")
        sysc = util.subelm(data, "sys:system")
        sysc.append(util.leaf_elm("sys:hostname", socket.gethostname()))

        # Clock
        clockc = util.subelm(sysc, "sys:clock")
        # tzname = time.tzname[time.localtime().tm_isdst]
        clockc.append(util.leaf_elm("sys:timezone-utc-offset", int(time.timezone / 100)))

        return util.filter_results(rpc, data, filter_or_none)
Exemple #26
0
 def rpc_get_config(self, session, rpc, source_elm, filter_or_none):  # pylint: disable=W0613
     print('rpc--->', rpc, type(rpc))
     print('source_elm--->', source_elm, type(source_elm))
     print('filter_or_none--->', filter_or_none, type(filter_or_none))
     """Passed the source element"""
     data = util.elm("nc:data")
     print(data, type(data))
     print(etree.tostring(data, pretty_print=True).decode())
     #
     # Config Data
     #
     self._add_config(data)
     return util.filter_results(rpc, data, filter_or_none)
Exemple #27
0
    def get_async(self, select):
        """Get operational state asynchronously from the server. If `select` is
        specified it is either an XPATH expression or XML subtree filter for
        selecting a subsection of the state. If `timeout` is not `None` it
        specifies how long to wait for the get operation to complete.

        :param select: A XML subtree filter or XPATH expression to select a subsection of state.
        :return: The RPC message id which can be passed to wait_reply for the results.
        :raises: SessionError
        """

        getelm = util.elm("get")
        _get_selection(getelm, select)
        return self.send_rpc_async(getelm)
Exemple #28
0
    def send_hello (self, caplist, session_id=None):
        msg = elm("hello", attrib={'xmlns': NSMAP['nc']})
        caps = E.capabilities(*[E.capability(x) for x in caplist])
        if session_id is not None:
            assert hasattr(self, "methods")
            self.methods.nc_append_capabilities(caps)       # pylint: disable=E1101
        msg.append(caps)

        if self.debug:
            logger.debug("%s: Sending HELLO", str(self))
        if session_id is not None:
            msg.append(E("session-id", str(session_id)))
        msg = etree.tostring(msg)
        self.send_message(msg.decode('utf-8'))
Exemple #29
0
 def _rpc_param_get_boolean (self, rpc, tag, default, params):
     for param in params:
         if ncutil.filter_tag_match(tag, param.tag):
             if param is None:
                 raise ncerror.RPCSvrBadElement(rpc, param, message="invalid boolean value for " + tag)
             bval = param.text.strip().lower()
             if bval in [ "false", "no", "0" ]:
                 return False
             elif bval in [ "true", "yes", "1" ]:
                 return True
             raise ncerror.RPCSvrBadElement(rpc, param, message="invalid boolean value for " + tag)
     if default is None:
         raise ncerror.RPCSvrMissingElement(rpc, ncutil.elm(tag))
     return default
Exemple #30
0
    def _rpc_param_get_frequency (self, rpc, params):
        for param in params:
            if ncutil.filter_tag_match("j:frequency", param.tag):
                break
        else:
            raise ncerror.RPCSvrMissingElement(rpc, ncutil.elm("j:frequency"))

        freq = param.strip()
        try:
            freq = int(freq.text)
            if not (190000 <= freq <= 198000):
                raise ncerror.RPCSvrBadElement(rpc, freq, message="Frequency not in range [190000, 198000]")
        except ValueError:
            raise ncerror.RPCSvrBadElement(rpc, freq, message="Frequency not an integer")
Exemple #31
0
 def _rpc_param_get_boolean(self, rpc, tag, default, params):
     for param in params:
         if ncutil.filter_tag_match(tag, param.tag):
             if param is None:
                 raise ncerror.RPCSvrBadElement(
                     rpc, param, message="invalid boolean value for " + tag)
             bval = param.text.strip().lower()
             if bval in ["false", "no", "0"]:
                 return False
             elif bval in ["true", "yes", "1"]:
                 return True
             raise ncerror.RPCSvrBadElement(
                 rpc, param, message="invalid boolean value for " + tag)
     if default is None:
         raise ncerror.RPCSvrMissingElement(rpc, ncutil.elm(tag))
     return default
Exemple #32
0
 def load_file(self, filename,
               module_name):  # load configuration to the servers
     logging.debug("---STARTUP CONFIG---")
     xml_root = open(filename, 'r').read()
     logging.info(
         etree.tostring(xml_root, encoding='utf8', xml_declaration=True))
     # node_topo = pybindIETFXMLDecoder.decode(xml_root, bindingTopology, module_name)
     # xml = pybindIETFXMLEncoder.serialise(node_topo)
     tree = etree.XML(xml_root)
     logging.info(
         etree.tostring(tree, encoding='utf8', xml_declaration=True))
     data = util.elm("nc:data")
     data.append(tree)
     logging.info(
         etree.tostring(data, encoding='utf8', xml_declaration=True))
     self.node_topology = data
Exemple #33
0
def _get_selection(elm, select):
    if not select:
        return

    # XXX Do we want to add any namespace stuff to the filter node here?

    felm = util.elm("nc:filter")
    if hasattr(select, "nsmap"):
        felm.attrib["type"] = "subtree"
        felm.append(select)
    elif _is_filter(select):
        felm.attrib["type"] = "subtree"
        felm.append(etree.fromstring(select))
    else:
        felm.attrib["type"] = "xpath"
        felm.attrib["select"] = select

    elm.append(felm)
Exemple #34
0
    def rpc_get(self, session, rpc, filter_or_none):  # pylint: disable=W0613
        logger.debug(
            "Filter of rpc_get is: %s",
            filter_or_none.attrib if filter_or_none is not None else 'None')
        self.ns_of_filter.clear()
        self.pre_process_filter(filter_or_none)
        logger.debug(
            "Filter of rpc_get after process is: %s",
            filter_or_none.attrib if filter_or_none is not None else 'None')
        logger.debug("Namespace in Filter is: %s", self.ns_of_filter)

        # lxml:  http://yshblog.com/blog/151
        data = util.elm("data")
        if len(self.ns_of_filter) > 0:
            data = etree.parse(ns_file_map[self.ns_of_filter[0]]).getroot()

        return util.filter_results(rpc, data, filter_or_none,
                                   self.server.debug)
Exemple #35
0
    def send_notification(self):
        logger.debug(f"Sending notification for subid {self.sub.session_id}")
        push_update = ncutil.elm("yp:push-update")

        # Set notification id
        ncutil.subelm(push_update, "id").text = str(self.sub.session_id)
        datastore_contents = ncutil.subelm(push_update, "datastore-contents")

        if self.sub.datastore_xpath_filter:
            notif_data = self.datasource.get_data(
                self.sub.datastore_xpath_filter)

            for elem in notif_data:
                datastore_contents.append(elem)

        #print(ET.tounicode(push_update, pretty_print=True))

        self.session.send_notification(push_update)
Exemple #36
0
    def _rpc_param_get_frequency(self, rpc, params):
        for param in params:
            if ncutil.filter_tag_match("j:frequency", param.tag):
                break
        else:
            raise ncerror.RPCSvrMissingElement(rpc, ncutil.elm("j:frequency"))

        freq = param.strip()
        try:
            freq = int(freq.text)
            if not (190000 <= freq <= 198000):
                raise ncerror.RPCSvrBadElement(
                    rpc,
                    freq,
                    message="Frequency not in range [190000, 198000]")
        except ValueError:
            raise ncerror.RPCSvrBadElement(rpc,
                                           freq,
                                           message="Frequency not an integer")
Exemple #37
0
    def rpc_edit_config(self, unused_session, rpc, *unused_params):
        """XXX API subject to change -- unfinished"""

        data_response = util.elm("ok")
        data_to_insert = rpc[0][1]

        # Validation.validate_rpc(data_to_insert,"edit-config")

        # data_to_insert = data_to_insert.find("{http://openconfig.net/yang/platform}data")
        data_to_insert_string = etree.tostring(data_to_insert,
                                               pretty_print=True,
                                               encoding='unicode')
        parser = etree.XMLParser(remove_blank_text=True)
        data_to_insert = etree.fromstring(data_to_insert_string, parser=parser)
        data_to_insert_string = etree.tostring(data_to_insert,
                                               pretty_print=True)

        logging.info(data_to_insert_string)

        open("configuration/platform.xml", "w").write(data_to_insert_string)

        return data_response
Exemple #38
0
    def rpc_full_itu_scan(self, unused_session, rpc, *params):
        # No input values yet
        try:
            if len(params) > 2:
                raise ncerror.RPCSvrInvalidValue(rpc,
                                                 message="Too many parameters")
            # XXX Should be able to use "j:high-resolution" but it fails
            hires = self._rpc_param_get_boolean(rpc, "high-resolution", False,
                                                params)
            power_only = not self._rpc_param_get_boolean(
                rpc, "detect-presence", False, params)
            if power_only:
                points = self._run_device_method(
                    rpc, self.device.get_itu_power_scan, hires)
            else:
                points = self._run_device_method(rpc, self.device.get_itu_scan,
                                                 hires)

            result = ncutil.elm("data")
            for tup in points:
                ptelm = ncutil.subelm(result, "j:point")
                ptelm.append(ncutil.leaf_elm("j:frequency", tup[0]))
                if power_only:
                    ptelm.append(
                        ncutil.leaf_elm("j:power",
                                        "{:.2f}".format(tup[1].dBm)))
                else:
                    ptelm.append(
                        ncutil.leaf_elm("j:power",
                                        "{:.2f}".format(tup[2].dBm)))
                    ptelm.append(ncutil.leaf_elm("j:channel-presence", tup[1]))
            return result
        except jerror.OCMError as ocmerr:
            logger.error("Got OCM error in full itu scan: %s: %s", str(ocmerr),
                         traceback.format_exc())
        except Exception as err:
            logger.error("Got error in full itu scan: %s: %s", str(err),
                         traceback.format_exc())
            raise
Exemple #39
0
    def reader_handle_message(self, msg):
        """Handle a message, lock is already held"""
        if not self.session_open:
            return

        # Any error with XML encoding here is going to cause a session close
        # Technically we should be able to return malformed message I think.
        try:
            tree = etree.parse(io.BytesIO(msg.encode("utf-8")))
            if not tree:
                raise ncerror.SessionError(msg, "Invalid XML from client.")
        except etree.XMLSyntaxError:
            logger.warning("Closing session due to malformed message")
            raise ncerror.SessionError(msg, "Invalid XML from client.")

        rpcs = tree.xpath("/nc:rpc", namespaces=NSMAP)
        if not rpcs:
            raise ncerror.SessionError(msg, "No rpc found")

        for rpc in rpcs:
            try:
                msg_id = rpc.get("message-id")
                if self.debug:
                    logger.debug("%s: Received rpc message-id: %s", str(self), msg_id)
            except (TypeError, ValueError):
                raise ncerror.SessionError(msg, "No valid message-id attribute found")

            try:
                # Get the first child of rpc as the method name
                rpc_method = rpc.getchildren()
                if len(rpc_method) != 1:
                    if self.debug:
                        logger.debug("%s: Bad Msg: msg-id: %s", str(self), msg_id)
                    raise ncerror.RPCSvrErrBadMsg(rpc)
                rpc_method = rpc_method[0]

                rpcname = rpc_method.tag.replace(qmap("nc"), "")
                params = rpc_method.getchildren()
                paramslen = len(params)

                if rpcname == "close-session":
                    # XXX should be RPC-unlocking if need be
                    if self.debug:
                        logger.debug("%s: Received close-session msg-id: %s", str(self), msg_id)
                    self.send_rpc_reply(etree.Element("ok"), rpc)
                    self.close()
                    # XXX should we also call the user method if it exists?
                    return
                elif rpcname == "kill-session":
                    # XXX we are supposed to cleanly abort anything underway
                    if self.debug:
                        logger.debug("%s: Received kill-session msg-id: %s", str(self), msg_id)
                    self.send_rpc_reply(etree.Element("ok"), rpc)
                    self.close()
                    # XXX should we also call the user method if it exists?
                    return
                elif rpcname == "get":
                    # Validate GET parameters

                    if paramslen > 1:
                        # XXX need to specify all elements not known
                        raise ncerror.RPCSvrErrBadMsg(rpc)
                    if params and not util.filter_tag_match(params[0], "nc:filter"):
                        raise ncerror.RPCSvrUnknownElement(rpc, params[0])
                    if not params:
                        params = [None]
                elif rpcname == "get-config":
                    # Validate GET-CONFIG parameters

                    # XXX verify that the source parameter is present
                    if paramslen > 2:
                        # XXX need to specify all elements not known
                        raise ncerror.RPCSvrErrBadMsg(rpc)
                    source_param = rpc_method.find("nc:source", namespaces=NSMAP)
                    if source_param is None:
                        raise ncerror.RPCSvrMissingElement(rpc, util.elm("nc:source"))
                    filter_param = None
                    if paramslen == 2:
                        filter_param = rpc_method.find("nc:filter", namespaces=NSMAP)
                        if filter_param is None:
                            unknown_elm = params[0] if params[0] != source_param else params[1]
                            raise ncerror.RPCSvrUnknownElement(rpc, unknown_elm)
                    params = [source_param, filter_param]

                # ------------------
                # Call the method.
                # ------------------

                try:
                    # Handle any namespaces or prefixes in the tag, other than
                    # "nc" which was removed above. Of course, this does not handle
                    # namespace collisions, but that seems reasonable for now.
                    rpcname = rpcname.rpartition("}")[-1]
                    method_name = "rpc_" + rpcname.replace("-", "_")
                    method = getattr(self.methods, method_name, self._rpc_not_implemented)
                    # logger.debug("%s: Calling method: %s", str(self), str(methodname))
                    reply = method(self, rpc, *params)
                    self.send_rpc_reply(reply, rpc)
                except NotImplementedError:
                    raise ncerror.RPCSvrErrNotImpl(rpc)
            except ncerror.RPCSvrErrBadMsg as msgerr:
                if self.new_framing:
                    self.send_message(msgerr.get_reply_msg())
                else:
                    # If we are 1.0 we have to simply close the connection
                    # as we are not allowed to send this error
                    logger.warning("Closing 1.0 session due to malformed message")
                    raise ncerror.SessionError(msg, "Malformed message")
            except ncerror.RPCServerError as error:
                self.send_message(error.get_reply_msg())
            except EOFError:
                if self.debug:
                    logger.debug("Got EOF in reader_handle_message")
            except Exception as exception:
                error = ncerror.RPCSvrException(rpc, exception)
                self.send_message(error.get_reply_msg())