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)
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)
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)
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)
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)
def rpc_get_config(self, session, rpc, source_elm, filter_or_none): # pylint: disable=W0613 logging.debug("---GET CONFIG---") logging.debug(session) # print(etree.tostring(rpc)) # print(etree.tostring(source_elm)) # print_current_config(self.configuration) # caller(print_current_config, args=self.configuration) return util.filter_results(rpc, self.node_topology, filter_or_none)
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)
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
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)
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)
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)
def rpc_ownership(self, session, rpc, *params): """Passed the filter element or None if not present""" data = util.elm("nc:data") data.append(util.leaf_elm("result", "RPC result string")) xPathResult = rpc.xpath( "//nc:ownership/nc:ownerCertificate/nc:certificate", namespaces=NSMAP) if not xPathResult: print("no cert found") else: certString = xPathResult[0].text temp_ownerCert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, certString) #print(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_TEXT, ownerCert).decode("utf-8")) xPathResult = rpc.xpath( "//nc:ownership/nc:ownerCertificate/nc:certificateSignature", namespaces=NSMAP) #if there is no signature at all, just accecpt the unsigned ownerCertificate if not xPathResult: print("no siganture found") self.ownerCertificate = temp_ownerCert #if there is a signature, check the signed ownerCertificate and accept it else: signature_base64 = xPathResult[0].text signature = base64.b64decode(signature_base64) #print(certString) if verifyString(self.manufacturerCert, signature, certString.encode('ascii'), "sha256"): self.ownerCertificate = temp_ownerCert #print(result) #print(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_TEXT, self.ownerCertificate).decode("utf-8")) return util.filter_results(rpc, data, None)
def rpc_edit_config(self, session, rpc, target, method, new_config): # pylint: disable=W0613 logging.debug("---EDIT CONFIG---") logging.debug(session) # print(etree.tostring(rpc)) # print(etree.tostring(method)) # print(etree.tostring(new_config)) # print("RUNNING MONITORING") # subprocess.call(['python', 'application_changes.py']) if 'topology' in new_config[0].tag: topo_path = ".//xmlns:node" topo_namespace = 'urn:node-topology' data_list = new_config.findall( topo_path, namespaces={'xmlns': topo_namespace}) for data in data_list: found = False # print(etree.tostring(data)) for node_id in data.iter("{" + topo_namespace + "}node-id"): topo_list = self.node_topology.findall( topo_path, namespaces={'xmlns': topo_namespace}) for topo in topo_list: # print(etree.tostring(topo)) for node_id2 in topo.iter("{" + topo_namespace + "}node-id"): logging.debug("COMPARING %s - %s" % (node_id.text, node_id2.text)) if node_id.text == node_id2.text: found = True # aux = copy.deepcopy(topo) # aux node topology logging.debug("MATCH") logging.debug("MERGING " + node_id.text) merge(topo, data) # print_config_changes(self.configuration, aux, data, 'modify') # caller(print_config_changes, args=(self.configuration, aux, data, 'modify')) else: logging.debug("NOT MATCH") if not found: logging.debug("APPENDING " + node_id.text) self.node_topology[0].append(data) # print_config_changes(self.configuration, None, data, 'create') # caller(print_config_changes, args=(self.configuration, None, data, 'create')) # print(etree.tostring(self.configuration, encoding='utf8', xml_declaration=True)) return util.filter_results(rpc, self.node_topology, None) elif 'connectivity' in new_config.tag: module_name = 'node-connectivity' connid = new_config.find(".//xmlns:connectionid", namespaces={ 'xmlns': 'urn:node-connectivity' }).text # get connectionid if method.text == "create": logging.debug("CREATING NEW CONNECTION: " + connid) if len(self.node_connectivity.connection ) == 0: # if self.capability is empty self.node_connectivity = new_config logging.debug(self.node_connectivity) # encode to pyangbind format self.node_connectivity = pybindIETFXMLDecoder.decode( etree.tostring(self.node_connectivity), bindingConnection, module_name) else: if connid not in self.node_connectivity.connection: # connectionid no exists tree_config = etree.XML(etree.tostring(new_config)) # decode from pyangbind format xml = pybindIETFXMLEncoder.serialise( self.node_connectivity) tree_node = etree.XML(xml) tree_node.append( tree_config[0]) # adding new connection # encode to pyangbind format self.node_connectivity = pybindIETFXMLDecoder.decode( etree.tostring(tree_node), bindingConnection, 'node-connectivity') elif method.text == "delete": logging.debug("DELETING CONNECTION: " + connid) if connid in self.node_connectivity.connection: # connectionid exists self.node_connectivity.connection.delete(connid) return util.filter_results( rpc, etree.XML( pybindIETFXMLEncoder.serialise(self.node_connectivity)), None)
def rpc_get(self, session, rpc, filter_or_none): # pylint: disable=W0613 if rpc[0].find('{*}filter') is None: # All configuration files should be appended dbclient = MongoClient() db = dbclient.netconfserver data_elm = etree.Element( 'data', nsmap={None: 'urn:ietf:params:xml:ns:netconf:base:1.0'}) i = 1 logging.info(db.list_collections()) for collection_name in db.list_collection_names(): collection = getattr(db, collection_name) collection_data = collection.find_one() collection_data_1 = dict(collection_data) for element in collection_data: if "id" in element: del collection_data_1[element] collection_data = collection_data_1 collection_binding = pybindJSONDecoder.load_ietf_json( collection_data, binding, collection_name) xml_data_string = serialise.pybindIETFXMLEncoder.serialise( collection_binding) xml_data = etree.XML(xml_data_string) data_elm.insert(i, xml_data) i += 1 xml_response = data_elm # Only supportedd datastore so far is platform else: # Parsing the database name form the rpc tag namespace db_base = rpc[0][1][0].tag.split('}')[0].split('/')[-1] db_source = rpc[0][1][0].tag.split('/')[2].split('.')[0] db_name = db_source + "-" + db_base # logging.info(db_name) # Finding the datastore requested dbclient = MongoClient() db = dbclient.netconfserver names = db.list_collection_names() # logging.info(names) if db_name in names: logging.info("Found the datastore requested") # Retrieving the data from the datastore datastore_name = db_name + ":" + rpc[0][1][0].tag.split('}')[1] datastore_data = db[db_name].find_one() datastore_data_1 = dict(datastore_data) for element in datastore_data: if "id" in element: del datastore_data_1[element] datastore_data = datastore_data_1 database_data_binding = pybindJSONDecoder.load_ietf_json( datastore_data, binding, db_name) logging.info(database_data_binding) # Parsing the data to xml xml_data = serialise.pybindIETFXMLEncoder.serialise( database_data_binding) xml_response = etree.XML(xml_data) else: raise AttributeError( "The requested datastore is not supported") # Validation.validate_rpc(response, "get-config") toreturn = util.filter_results(rpc, xml_response, filter_or_none, self.server.debug) if "data" not in toreturn.tag: logging.info("data not header") nsmap = {None: 'urn:ietf:params:xml:ns:netconf:base:1.0'} data_elm = etree.Element( 'data', nsmap={None: 'urn:ietf:params:xml:ns:netconf:base:1.0'}) data_elm.insert(1, toreturn) logging.info(etree.tostring(data_elm, pretty_print=True)) toreturn = data_elm return toreturn
def rpc_edit_config(self, session, rpc, *params): # pylint: disable=W0613 data = util.elm("ok") return util.filter_results(rpc, data, None)
def rpc_edit_config(self, session, rpc, *params): # pylint: disable=W0613 """Passed the source element""" data = util.elm("ok") return util.filter_results(rpc, data, None)
def rpc_edit_config(self, session, rpc, target, method, newconf): # pylint disable=W0613 """ Create, merge or delete all or part of the specified newconf to the running configuration datastore. :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 target: the target of the config, defaults to "running" :type target: str :param method: "merge" (netconf default), "create" or "delete". :type method: str :param newconf: new configuration :type newconf: lxml.Element :return: "nc:data" type containing the requested configuration :rtype: lxml.Element """ # print(etree.tostring(rpc)) # print(etree.tostring(method)) # print(etree.tostring(newconf)) logger.debug("EDIT CONFIG") try: if 'capability' in newconf[0].tag: # TODO to be implemented pass elif 'configuration' in newconf[0].tag: new_xml = pybindIETFXMLDecoder.decode( etree.tostring(newconf), bindingConfiguration, "blueSPACE-DRoF-configuration") if "create" in method.text: # extract NCF, bn, En and eq from newconf NCF = float( new_xml.DRoF_configuration.nominal_central_frequency) eq = str(new_xml.DRoF_configuration.equalization) bn, En = self.extract_bn_and_En(new_xml) # Laser setup self.ac.laser_setup(NCF, self.ac.power_laser) # DAC/OSC setup result = self.ac.dac_setup(bn, En, eq) # save newconf as running configuration self.configuration = new_xml # add SNR and BER to running configuration datastore SNR = result[0] BER = result[1] for i in range(1, len(SNR) + 1): m = self.configuration.DRoF_configuration.monitor.add( i) if np.math.isnan(SNR[i - 1]): m._set_SNR(np.format_float_positional(1e-9)) else: m._set_SNR(SNR[i - 1]) self.configuration.DRoF_configuration._set_BER(BER) logger.info(pybindJSON.dumps(self.configuration)) logger.debug("NEW CONFIGURATION created") elif "merge" in method.text: # extract bn and En from newconf bn, En = self.extract_bn_and_En(new_xml) # extract eq from running configuration datastore eq = str( self.configuration.DRoF_configuration.equalization) # 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) # merge newconf with running configuration datastore for i, x in enumerate(new_xml.DRoF_configuration. constellation.iteritems(), start=1): for j, y in enumerate( self.configuration.DRoF_configuration. constellation.iteritems(), start=1): if i == j: y[1].bitsxsymbol = x[1].bitsxsymbol y[1].powerxsymbol = x[1].powerxsymbol logger.info(pybindJSON.dumps(self.configuration)) logger.debug("NEW CONFIGURATION merged") elif "delete" in method.text: # disable Laser and remove logical associations between DAC and OSC self.ac.disable_laser() self.ac.remove_logical_associations() # remove the running configuration self.configuration = bindingConfiguration.blueSPACE_DRoF_configuration( ) logger.info(pybindJSON.dumps(self.configuration)) logger.debug("CONFIGURATION deleted") return util.filter_results( rpc, etree.XML( pybindIETFXMLEncoder.serialise(self.configuration)), None) except Exception as e: logger.error("EDIT CONFIG method {}, error: {}".format(method, e)) raise e