| 1 |
# Copyright 2009 Shikhar Bhushan |
| 2 |
# Copyright 2011 Leonidas Poulopoulos |
| 3 |
# |
| 4 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
# you may not use this file except in compliance with the License. |
| 6 |
# You may obtain a copy of the License at |
| 7 |
# |
| 8 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
# |
| 10 |
# Unless required by applicable law or agreed to in writing, software |
| 11 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
# See the License for the specific language governing permissions and |
| 14 |
# limitations under the License. |
| 15 |
|
| 16 |
"Methods for creating, parsing, and dealing with XML and ElementTree objects." |
| 17 |
|
| 18 |
|
| 19 |
import io |
| 20 |
import types |
| 21 |
from io import BytesIO, StringIO |
| 22 |
|
| 23 |
from lxml import etree |
| 24 |
|
| 25 |
# In case issues come up with XML generation/parsing |
| 26 |
# make sure you have the ElementTree v1.2.7+ lib as |
| 27 |
# well as lxml v3.0+ |
| 28 |
|
| 29 |
from ncclient import NCClientError |
| 30 |
|
| 31 |
parser = etree.XMLParser(recover=False) |
| 32 |
huge_parser = etree.XMLParser(recover=False, huge_tree=True) |
| 33 |
|
| 34 |
|
| 35 |
def _get_parser(huge_tree=False): |
| 36 |
return huge_parser if huge_tree else parser |
| 37 |
|
| 38 |
|
| 39 |
class XMLError(NCClientError): |
| 40 |
pass |
| 41 |
|
| 42 |
### Namespace-related |
| 43 |
|
| 44 |
#: Base NETCONF namespace |
| 45 |
BASE_NS_1_0 = "urn:ietf:params:xml:ns:netconf:base:1.0" |
| 46 |
#: YANG (RFC 6020/RFC 7950) namespace |
| 47 |
YANG_NS_1_0 = "urn:ietf:params:xml:ns:yang:1" |
| 48 |
#: NXOS_1_0 |
| 49 |
NXOS_1_0 = "http://www.cisco.com/nxos:1.0" |
| 50 |
#: NXOS_IF |
| 51 |
NXOS_IF = "http://www.cisco.com/nxos:1.0:if_manager" |
| 52 |
#: Namespace for Tail-f core data model |
| 53 |
TAILF_AAA_1_1 = "http://tail-f.com/ns/aaa/1.1" |
| 54 |
#: Namespace for Tail-f execd data model |
| 55 |
TAILF_EXECD_1_1 = "http://tail-f.com/ns/execd/1.1" |
| 56 |
#: Namespace for Cisco data model |
| 57 |
CISCO_CPI_1_0 = "http://www.cisco.com/cpi_10/schema" |
| 58 |
#: Namespace for Flowmon data model |
| 59 |
FLOWMON_1_0 = "http://www.liberouter.org/ns/netopeer/flowmon/1.0" |
| 60 |
#: Namespace for Juniper 9.6R4. Tested with Junos 9.6R4+ |
| 61 |
JUNIPER_1_1 = "http://xml.juniper.net/xnm/1.1/xnm" |
| 62 |
#: Namespace for Huawei data model |
| 63 |
HUAWEI_NS = "http://www.huawei.com/netconf/vrp" |
| 64 |
#: Namespace for Huawei private |
| 65 |
HW_PRIVATE_NS = "http://www.huawei.com/netconf/capability/base/1.0" |
| 66 |
#: Namespace for H3C data model |
| 67 |
H3C_DATA_1_0 = "http://www.h3c.com/netconf/data:1.0" |
| 68 |
#: Namespace for H3C config model |
| 69 |
H3C_CONFIG_1_0 = "http://www.h3c.com/netconf/config:1.0" |
| 70 |
#: Namespace for H3C action model |
| 71 |
H3C_ACTION_1_0 = "http://www.h3c.com/netconf/action:1.0" |
| 72 |
#: Namespace for netconf monitoring |
| 73 |
NETCONF_MONITORING_NS = "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring" |
| 74 |
#: Namespace for netconf notifications |
| 75 |
NETCONF_NOTIFICATION_NS = "urn:ietf:params:xml:ns:netconf:notification:1.0" |
| 76 |
#: Namespace for netconf with-defaults (RFC 6243) |
| 77 |
NETCONF_WITH_DEFAULTS_NS = "urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults" |
| 78 |
#: Namespace for Alcatel-Lucent SR OS Base r13 YANG models |
| 79 |
ALU_CONFIG = "urn:alcatel-lucent.com:sros:ns:yang:conf-r13" |
| 80 |
#: Namespace for Nokia SR OS global operations |
| 81 |
SROS_GLOBAL_OPS_NS = "urn:nokia.com:sros:ns:yang:sr:oper-global" |
| 82 |
|
| 83 |
|
| 84 |
try: |
| 85 |
register_namespace = etree.register_namespace |
| 86 |
except AttributeError: |
| 87 |
def register_namespace(prefix, uri): |
| 88 |
from xml.etree import ElementTree |
| 89 |
# cElementTree uses ElementTree's _namespace_map, so that's ok |
| 90 |
ElementTree._namespace_map[uri] = prefix |
| 91 |
|
| 92 |
for (ns, pre) in { |
| 93 |
BASE_NS_1_0: 'nc', |
| 94 |
NETCONF_MONITORING_NS: 'ncm', |
| 95 |
NXOS_1_0: 'nxos', |
| 96 |
NXOS_IF: 'if', |
| 97 |
TAILF_AAA_1_1: 'aaa', |
| 98 |
TAILF_EXECD_1_1: 'execd', |
| 99 |
CISCO_CPI_1_0: 'cpi', |
| 100 |
FLOWMON_1_0: 'fm', |
| 101 |
JUNIPER_1_1: 'junos', |
| 102 |
}.items(): |
| 103 |
register_namespace(pre, ns) |
| 104 |
|
| 105 |
qualify = lambda tag, ns=BASE_NS_1_0: tag if ns is None else "{%s}%s" % (ns, tag) |
| 106 |
"""Qualify a *tag* name with a *namespace*, in :mod:`~xml.etree.ElementTree` fashion i.e. *{namespace}tagname*.""" |
| 107 |
|
| 108 |
|
| 109 |
def to_xml(ele, encoding="UTF-8", pretty_print=False): |
| 110 |
"Convert and return the XML for an *ele* (:class:`~xml.etree.ElementTree.Element`) with specified *encoding*." |
| 111 |
xml = etree.tostring(ele, encoding=encoding, pretty_print=pretty_print) |
| 112 |
return xml.decode('UTF-8') if xml.startswith(b'<?xml') \ |
| 113 |
else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml.decode('UTF-8')) |
| 114 |
|
| 115 |
|
| 116 |
def to_ele(x, huge_tree=False): |
| 117 |
"""Convert and return the :class:`~xml.etree.ElementTree.Element` for the XML document *x*. If *x* is already an :class:`~xml.etree.ElementTree.Element` simply returns that. |
| 118 |
|
| 119 |
*huge_tree*: parse XML with very deep trees and very long text content |
| 120 |
""" |
| 121 |
return x if etree.iselement(x) else etree.fromstring(x.encode('UTF-8'), parser=_get_parser(huge_tree)) |
| 122 |
|
| 123 |
|
| 124 |
def parse_root(raw): |
| 125 |
"Efficiently parses the root element of a *raw* XML document, returning a tuple of its qualified name and attribute dictionary." |
| 126 |
fp = BytesIO(raw.encode('UTF-8')) |
| 127 |
for event, element in etree.iterparse(fp, events=('start',)): |
| 128 |
return (element.tag, element.attrib) |
| 129 |
|
| 130 |
def validated_element(x, tags=None, attrs=None): |
| 131 |
"""Checks if the root element of an XML document or Element meets the supplied criteria. |
| 132 |
|
| 133 |
*tags* if specified is either a single allowable tag name or sequence of allowable alternatives |
| 134 |
|
| 135 |
*attrs* if specified is a sequence of required attributes, each of which may be a sequence of several allowable alternatives |
| 136 |
|
| 137 |
Raises :exc:`XMLError` if the requirements are not met. |
| 138 |
""" |
| 139 |
ele = to_ele(x) |
| 140 |
if tags: |
| 141 |
if isinstance(tags, (str, bytes)): |
| 142 |
tags = [tags] |
| 143 |
if ele.tag not in tags: |
| 144 |
raise XMLError("Element [%s] does not meet requirement" % ele.tag) |
| 145 |
if attrs: |
| 146 |
for req in attrs: |
| 147 |
if isinstance(req, (str, bytes)): req = [req] |
| 148 |
for alt in req: |
| 149 |
if alt in ele.attrib: |
| 150 |
break |
| 151 |
else: |
| 152 |
raise XMLError("Element [%s] does not have required attributes" % ele.tag) |
| 153 |
return ele |
| 154 |
|
| 155 |
XPATH_NAMESPACES = { |
| 156 |
're':'http://exslt.org/regular-expressions' |
| 157 |
} |
| 158 |
|
| 159 |
|
| 160 |
class NCElement: |
| 161 |
def __init__(self, result, transform_reply, huge_tree=False): |
| 162 |
self.__result = result |
| 163 |
self.__transform_reply = transform_reply |
| 164 |
self.__huge_tree = huge_tree |
| 165 |
if isinstance(transform_reply, types.FunctionType): |
| 166 |
self.__doc = self.__transform_reply(result._root) |
| 167 |
else: |
| 168 |
self.__doc = self.remove_namespaces(self.__result) |
| 169 |
|
| 170 |
def xpath(self, expression, namespaces={}): |
| 171 |
"""Perform XPath navigation on an object |
| 172 |
|
| 173 |
Args: |
| 174 |
expression: A string representing a compliant XPath |
| 175 |
expression. |
| 176 |
namespaces: A dict of caller supplied prefix/xmlns to |
| 177 |
append to the static dict of XPath namespaces. |
| 178 |
Returns: |
| 179 |
A list of 'lxml.etree._Element' should a match on the |
| 180 |
expression be successful. Otherwise, an empty list will |
| 181 |
be returned to the caller. |
| 182 |
""" |
| 183 |
self.__expression = expression |
| 184 |
self.__namespaces = XPATH_NAMESPACES |
| 185 |
self.__namespaces.update(namespaces) |
| 186 |
return self.__doc.xpath(self.__expression, namespaces=self.__namespaces) |
| 187 |
|
| 188 |
def find(self, expression): |
| 189 |
"""return result for a call to lxml ElementPath find()""" |
| 190 |
self.__expression = expression |
| 191 |
return self.__doc.find(self.__expression) |
| 192 |
|
| 193 |
def findtext(self, expression): |
| 194 |
"""return result for a call to lxml ElementPath findtext()""" |
| 195 |
self.__expression = expression |
| 196 |
return self.__doc.findtext(self.__expression) |
| 197 |
|
| 198 |
def findall(self, expression): |
| 199 |
"""return result for a call to lxml ElementPath findall()""" |
| 200 |
self.__expression = expression |
| 201 |
return self.__doc.findall(self.__expression) |
| 202 |
|
| 203 |
def __str__(self): |
| 204 |
"""syntactic sugar for str() - alias to tostring""" |
| 205 |
return self.tostring.decode('UTF-8') |
| 206 |
|
| 207 |
@property |
| 208 |
def tostring(self): |
| 209 |
"""return a pretty-printed string output for rpc reply""" |
| 210 |
parser = etree.XMLParser(remove_blank_text=True, huge_tree=self.__huge_tree) |
| 211 |
outputtree = etree.XML(etree.tostring(self.__doc), parser) |
| 212 |
return etree.tostring(outputtree, pretty_print=True) |
| 213 |
|
| 214 |
@property |
| 215 |
def data_xml(self): |
| 216 |
"""return an unmodified output for rpc reply""" |
| 217 |
return to_xml(self.__doc) |
| 218 |
|
| 219 |
def remove_namespaces(self, rpc_reply): |
| 220 |
"""remove xmlns attributes from rpc reply""" |
| 221 |
self.__xslt=self.__transform_reply |
| 222 |
self.__parser = etree.XMLParser(remove_blank_text=True, huge_tree=self.__huge_tree) |
| 223 |
self.__xslt_doc = etree.parse(io.BytesIO(self.__xslt), self.__parser) |
| 224 |
self.__transform = etree.XSLT(self.__xslt_doc) |
| 225 |
self.__root = etree.fromstring(str(self.__transform(etree.parse(StringIO(str(rpc_reply)), |
| 226 |
parser=self.__parser))), |
| 227 |
parser=self.__parser) |
| 228 |
return self.__root |
| 229 |
|
| 230 |
def parent_ns(node): |
| 231 |
if node.prefix: |
| 232 |
return node.nsmap[node.prefix] |
| 233 |
return None |
| 234 |
|
| 235 |
def yang_action(name, attrs): |
| 236 |
"""Instantiate a YANG action element |
| 237 |
|
| 238 |
Args: |
| 239 |
name: A string representing the first descendant name of the |
| 240 |
XML element for the YANG action. |
| 241 |
attrs: A dict of attributes to apply to the XML element |
| 242 |
(e.g. namespaces). |
| 243 |
Returns: |
| 244 |
A tuple of 'lxml.etree._Element' values. The first value |
| 245 |
represents the top-level YANG action element and the second |
| 246 |
represents the caller supplied initial node. |
| 247 |
""" |
| 248 |
node = new_ele('action', attrs={'xmlns': YANG_NS_1_0}) |
| 249 |
return (node, sub_ele(node, name, attrs)) |
| 250 |
|
| 251 |
|
| 252 |
def replace_namespace(root, old_ns, new_ns): |
| 253 |
""" |
| 254 |
Substitute old_ns with new_ns for all the xml elements including and below root |
| 255 |
:param root: top element (root for this change) |
| 256 |
:param old_ns: old namespace |
| 257 |
:param new_ns: new namespace |
| 258 |
:return: |
| 259 |
""" |
| 260 |
for elem in root.getiterator(): |
| 261 |
# Comments don't have a namespace |
| 262 |
if elem.tag is not etree.Comment: |
| 263 |
# handle tag |
| 264 |
qtag = etree.QName(elem) |
| 265 |
if qtag.namespace == old_ns: |
| 266 |
elem.tag = etree.QName(new_ns, qtag.localname) |
| 267 |
|
| 268 |
# handle attributes |
| 269 |
attribs_dict = elem.attrib |
| 270 |
for attr in attribs_dict.keys(): |
| 271 |
qattr = etree.QName(attr) |
| 272 |
if qattr.namespace == old_ns: |
| 273 |
attribs_dict[etree.QName(new_ns, qattr.localname)] = attribs_dict.pop(attr) |
| 274 |
|
| 275 |
|
| 276 |
new_ele_nsmap = lambda tag, nsmap, attrs={}, **extra: etree.Element(qualify(tag), attrs, nsmap, **extra) |
| 277 |
|
| 278 |
new_ele = lambda tag, attrs={}, **extra: etree.Element(qualify(tag), attrs, **extra) |
| 279 |
|
| 280 |
new_ele_ns = lambda tag, ns, attrs={}, **extra: etree.Element(qualify(tag,ns), attrs, **extra) |
| 281 |
|
| 282 |
sub_ele = lambda parent, tag, attrs={}, **extra: etree.SubElement(parent, qualify(tag, parent_ns(parent)), attrs, **extra) |
| 283 |
|
| 284 |
sub_ele_ns = lambda parent, tag, ns, attrs={}, **extra: etree.SubElement(parent, qualify(tag, ns), attrs, **extra) |