Debian Codegraph @

ncclient/devices/junos.py

raw
1 """
2 Handler for Juniper device specific information.
3
4 Note that for proper import, the classname has to be:
5
6 "<Devicename>DeviceHandler"
7
8 ...where <Devicename> is something like "Default", "Junos", etc.
9
10 All device-specific handlers derive from the DefaultDeviceHandler, which implements the
11 generic information needed for interaction with a Netconf server.
12
13 """
14 import logging
15 import re
16
17 from lxml import etree
18 from lxml.etree import QName
19
20 from ncclient.operations.retrieve import GetSchemaReply
21 from .default import DefaultDeviceHandler
22 from ncclient.operations.third_party.juniper.rpc import GetConfiguration, LoadConfiguration, CompareConfiguration
23 from ncclient.operations.third_party.juniper.rpc import ExecuteRpc, Command, Reboot, Halt, Commit, Rollback
24 from ncclient.operations.rpc import RPCError
25 from ncclient.xml_ import to_ele, replace_namespace, BASE_NS_1_0, NETCONF_MONITORING_NS
26 from ncclient.transport.third_party.junos.parser import JunosXMLParser
27 from ncclient.transport.parser import DefaultXMLParser
28 from ncclient.transport.parser import SAXParserHandler
29
30
31 logger = logging.getLogger(__name__)
32
33
34 class JunosDeviceHandler(DefaultDeviceHandler):
35 """
36 Juniper handler for device specific information.
37
38 """
39
40 def __init__(self, device_params, ignore_errors=None):
41 super(JunosDeviceHandler, self).__init__(device_params, ignore_errors)
42 self.__reply_parsing_error_transform_by_cls = {
43 GetSchemaReply: fix_get_schema_reply
44 }
45
46 def add_additional_operations(self):
47 dict = {}
48 dict["rpc"] = ExecuteRpc
49 dict["get_configuration"] = GetConfiguration
50 dict["load_configuration"] = LoadConfiguration
51 dict["compare_configuration"] = CompareConfiguration
52 dict["command"] = Command
53 dict["reboot"] = Reboot
54 dict["halt"] = Halt
55 dict["commit"] = Commit
56 dict["rollback"] = Rollback
57 return dict
58
59 def perform_qualify_check(self):
60 return False
61
62 def handle_raw_dispatch(self, raw):
63 if 'routing-engine' in raw:
64 raw = re.sub(r'<ok/>', '</routing-engine>\n<ok/>', raw)
65 return raw
66 # check if error is during capabilities exchange itself
67 elif re.search(r'<rpc-reply>.*?</rpc-reply>.*</hello>?', raw, re.M | re.S):
68 errs = re.findall(
69 r'<rpc-error>.*?</rpc-error>', raw, re.M | re.S)
70 err_list = []
71 if errs:
72 add_ns = """
73 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
74 <xsl:output indent="yes"/>
75 <xsl:template match="*">
76 <xsl:element name="{local-name()}" namespace="urn:ietf:params:xml:ns:netconf:base:1.0">
77 <xsl:apply-templates select="@*|node()"/>
78 </xsl:element>
79 </xsl:template>
80 </xsl:stylesheet>"""
81 for err in errs:
82 doc = etree.ElementTree(etree.XML(err))
83 # Adding namespace using xslt
84 xslt = etree.XSLT(etree.XML(add_ns))
85 transformed_xml = etree.XML(etree.tostring(xslt(doc)))
86 err_list.append(RPCError(transformed_xml))
87 return RPCError(to_ele("<rpc-reply>"+''.join(errs)+"</rpc-reply>"), err_list)
88 else:
89 return False
90
91 def handle_connection_exceptions(self, sshsession):
92 c = sshsession._channel = sshsession._transport.open_channel(
93 kind="session")
94 c.set_name("netconf-command-" + str(sshsession._channel_id))
95 c.exec_command("xml-mode netconf need-trailer")
96 return True
97
98 def reply_parsing_error_transform(self, reply_cls):
99 # return transform function if found, else None
100 return self.__reply_parsing_error_transform_by_cls.get(reply_cls)
101
102 def transform_reply(self):
103 reply = '''<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
104 <xsl:output method="xml" indent="no"/>
105
106 <xsl:template match="/|comment()|processing-instruction()">
107 <xsl:copy>
108 <xsl:apply-templates/>
109 </xsl:copy>
110 </xsl:template>
111
112 <xsl:template match="*">
113 <xsl:element name="{local-name()}">
114 <xsl:apply-templates select="@*|node()"/>
115 </xsl:element>
116 </xsl:template>
117
118 <xsl:template match="@*">
119 <xsl:attribute name="{local-name()}">
120 <xsl:value-of select="."/>
121 </xsl:attribute>
122 </xsl:template>
123 </xsl:stylesheet>
124 '''
125 return reply.encode('UTF-8')
126
127 def get_xml_parser(self, session):
128 # use_filter in device_params can be used to enabled using SAX parsing
129 if self.device_params.get('use_filter', False):
130 l = session.get_listener_instance(SAXParserHandler)
131 if l:
132 session.remove_listener(l)
133 del l
134 session.add_listener(SAXParserHandler(session))
135 return JunosXMLParser(session)
136 else:
137 return DefaultXMLParser(session)
138
139
140 def fix_get_schema_reply(root):
141 # Workaround for wrong namespace of the data elem
142 # (issue with some Junos versions, might be corrected by Juniper at some point)
143
144 # get the data element, by local-name
145 data_elems = root.xpath('/nc:rpc-reply/*[local-name()="data"]', namespaces={'nc': BASE_NS_1_0})
146
147 if len(data_elems) != 1:
148 return # Will not alter unexpected content
149
150 data_el = data_elems[0]
151 namespace = QName(data_el).namespace
152
153 if namespace == BASE_NS_1_0:
154 # With the default netconf setting, we may get "{BASE_NS_1_0}data"; warn and fix it
155 logger.warning("The device seems to run non-rfc compliant netconf. You may want to "
156 "configure: 'set system services netconf rfc-compliant'")
157 replace_namespace(data_el, old_ns=BASE_NS_1_0, new_ns=NETCONF_MONITORING_NS)
158 elif namespace is None:
159 # With 'set system services netconf rfc-compliant' we may get "data" (no namespace); fix it
160 # There is no default xmlns and the data el is <data xmlns:ncm="NETCONF_MONITORING_NS">
161 replace_namespace(data_el, old_ns=None, new_ns=NETCONF_MONITORING_NS)