Debian Codegraph @

lib/jnpr/junos/transport/tty_netconf.py

raw
1 import re
2 import time
3 from lxml import etree
4 import select
5 import socket
6 import logging
7 import sys
8
9 from lxml.builder import E
10 from lxml.etree import XMLSyntaxError
11 from datetime import datetime, timedelta
12 from ncclient.operations.rpc import RPCReply, RPCError
13 from ncclient.xml_ import to_ele
14 import six
15 from ncclient.transport.session import HelloHandler
16
17
18 class PY6:
19 NEW_LINE = six.b("\n")
20 EMPTY_STR = six.b("")
21 NETCONF_EOM = six.b("]]>]]>")
22 STARTS_WITH = six.b("<!--")
23
24
25 __all__ = ["xmlmode_netconf"]
26
27 _NETCONF_EOM = six.b("]]>]]>")
28 _xmlns = re.compile(six.b("xmlns=[^>]+"))
29 _xmlns_strip = lambda text: _xmlns.sub(PY6.EMPTY_STR, text)
30 _junosns = re.compile(six.b("junos:"))
31 _junosns_strip = lambda text: _junosns.sub(PY6.EMPTY_STR, text)
32
33 logger = logging.getLogger("jnpr.junos.tty_netconf")
34
35 # =========================================================================
36 # xmlmode_netconf
37 # =========================================================================
38
39
40 class tty_netconf(object):
41 """
42 Basic Junos XML API for bootstraping through the TTY
43 """
44
45 def __init__(self, tty):
46 self._tty = tty
47 self.hello = None
48 self._session_id = -1
49
50 # -------------------------------------------------------------------------
51 # NETCONF session open and close
52 # -------------------------------------------------------------------------
53
54 def open(self, at_shell):
55 """start the XML API process and receive the 'hello' message"""
56 nc_cmd = ("junoscript", "xml-mode")[at_shell]
57 self._tty.write(nc_cmd + " netconf need-trailer")
58 mark_start = datetime.now()
59 mark_end = mark_start + timedelta(seconds=15)
60
61 while datetime.now() < mark_end:
62 time.sleep(0.1)
63 line = self._tty.read()
64 if line.startswith(PY6.STARTS_WITH):
65 break
66 else:
67 # exceeded the while loop timeout
68 raise RuntimeError("Error: netconf not responding")
69
70 self.hello = self._receive()
71 self._session_id, _ = HelloHandler.parse(
72 self.hello.decode("utf-8") if isinstance(self.hello, bytes) else self.hello
73 )
74
75 def close(self, force=False):
76 """issue the XML API to close the session"""
77
78 # if we do not have an open connection, then return now.
79 if force is False:
80 if self.hello is None:
81 return
82
83 self.rpc("close-session")
84 # removed flush
85
86 # -------------------------------------------------------------------------
87 # MISC device commands
88 # -------------------------------------------------------------------------
89
90 def zeroize(self):
91 """issue a reboot to the device"""
92 cmd = E.command("request system zeroize")
93 try:
94 encode = None if sys.version < "3" else "unicode"
95 self.rpc(etree.tostring(cmd, encoding=encode))
96 except:
97 return False
98 return True
99
100 # -------------------------------------------------------------------------
101 # XML RPC command execution
102 # -------------------------------------------------------------------------
103
104 def rpc(self, cmd):
105 """
106 Write the XML cmd and return the response as XML object.
107
108 :cmd:
109 <str> of the XML command. if the :cmd: is not XML, then
110 this routine will perform the brackets; i.e. if given
111 'get-software-information', this routine will turn
112 it into '<get-software-information/>'
113
114 NOTES:
115 The return XML object is the first child element after
116 the <rpc-reply>. There is also no error-checking
117 performing by this routine.
118 """
119 if not cmd.startswith("<"):
120 cmd = "<{}/>".format(cmd)
121 rpc = six.b("<rpc>{}</rpc>".format(cmd))
122 logger.info("Calling rpc: %s" % rpc)
123 self._tty.rawwrite(rpc)
124
125 rsp = self._receive()
126 rsp = rsp.decode("utf-8") if isinstance(rsp, bytes) else rsp
127 reply = RPCReply(rsp, huge_tree=self._tty._huge_tree)
128 errors = reply.errors
129 if len(errors) > 1:
130 raise RPCError(to_ele(reply._raw), errs=errors)
131 elif len(errors) == 1:
132 raise reply.error
133 return rsp
134
135 # -------------------------------------------------------------------------
136 # LOW-LEVEL I/O for reading back XML response
137 # -------------------------------------------------------------------------
138
139 def _receive(self):
140 # On windows select.select throws io.UnsupportedOperation: fileno
141 # so use read function for windows serial COM ports
142 if hasattr(self._tty, "port") and str(self._tty.port).startswith("COM"):
143 return self._receive_serial_win()
144 else:
145 return self._receive_serial()
146
147 def _receive_serial(self):
148 """process the XML response into an XML object"""
149 rxbuf = PY6.EMPTY_STR
150 line = PY6.EMPTY_STR
151 while True:
152 try:
153 rd, wt, err = select.select([self._tty._rx], [], [], 0.1)
154 except select.error as err:
155 raise err
156 except socket.error as err:
157 raise err
158 if rd:
159 line, lastline = rd[0].read_until(PY6.NETCONF_EOM, 0.1), line
160 if not line:
161 continue
162 if _NETCONF_EOM in line or _NETCONF_EOM in lastline + line:
163 rxbuf = rxbuf + line
164 break
165 else:
166 rxbuf = rxbuf + line
167 if _NETCONF_EOM in rxbuf:
168 break
169 return self._parse_buffer(rxbuf)
170
171 # -------------------------------------------------------------------------
172 # Read message from windows COM ports
173 # -------------------------------------------------------------------------
174
175 def _receive_serial_win(self):
176 """process incoming data from windows port"""
177 rxbuf = PY6.EMPTY_STR
178 line = PY6.EMPTY_STR
179 while True:
180 line, lastline = self._tty.read().strip(), line
181 if not line:
182 continue
183 if _NETCONF_EOM in line or _NETCONF_EOM in lastline + line:
184 rxbuf = rxbuf + line
185 break
186 else:
187 rxbuf = rxbuf + line
188 if _NETCONF_EOM in rxbuf:
189 break
190 return self._parse_buffer(rxbuf)
191
192 def _parse_buffer(self, rxbuf):
193 rxbuf = rxbuf.splitlines()
194 if _NETCONF_EOM in rxbuf[-1]:
195 if rxbuf[-1] == _NETCONF_EOM:
196 rxbuf.pop()
197 else:
198 rxbuf[-1] = rxbuf[-1].split(_NETCONF_EOM)[0]
199 try:
200 rxbuf = [i.strip() for i in rxbuf if i.strip() != PY6.EMPTY_STR]
201 rcvd_data = PY6.NEW_LINE.join(rxbuf)
202 logger.debug("Received: \n%s" % rcvd_data)
203 parser = etree.XMLParser(
204 remove_blank_text=True, huge_tree=self._tty._huge_tree
205 )
206 try:
207 etree.XML(rcvd_data, parser)
208 except XMLSyntaxError:
209 if _NETCONF_EOM in rcvd_data:
210 rcvd_data = rcvd_data[: rcvd_data.index(_NETCONF_EOM)]
211 etree.XML(rcvd_data) # just to recheck
212 else:
213 parser = etree.XMLParser(recover=True)
214 rcvd_data = etree.tostring(etree.XML(rcvd_data, parser=parser))
215 return rcvd_data
216 except:
217 if "</xnm:error>" in rxbuf:
218 for x in rxbuf:
219 if "<message>" in x:
220 return etree.XML(
221 "<error-in-receive>" + x + "</error-in-receive>"
222 )
223 else:
224 return etree.XML("<error-in-receive/>")