Debian Codegraph @

lib/ClusterShell/Communication.py

raw symbols SCIP
1 #
2 # Copyright (C) 2010-2016 CEA/DAM
3 # Copyright (C) 2010-2011 Henri Doreau <[email protected]>
4 # Copyright (C) 2015-2017 Stephane Thiell <[email protected]>
5 #
6 # This file is part of ClusterShell.
7 #
8 # ClusterShell is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12 #
13 # ClusterShell is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with ClusterShell; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
22 """
23 ClusterShell inter-nodes communication module
24
25 This module contains the required material for nodes to communicate between each
26 others within the propagation tree. At the highest level, messages are instances
27 of several classes. They can be converted into XML to be sent over SSH links
28 through a Channel instance.
29
30 In the other side, XML is parsed and new message objects are instantiated.
31
32 Communication channels have been implemented as ClusterShell events handlers.
33 Whenever a message chunk is read, the data is given to a SAX XML parser, that
34 will use it to create corresponding messages instances as a messages factory.
35
36 As soon as an instance is ready, it is then passed to a recv() method in the
37 channel. The recv() method of the Channel class is a stub, that requires to be
38 implemented in subclass to process incoming messages. So is the start() method
39 too.
40
41 Subclassing the Channel class allows implementing whatever logic you want on the
42 top of a communication channel.
43 """
44
45 try:
46 import _pickle as cPickle
47 except ImportError: # Python 2 compat
48 import cPickle
49
50 from pickle import HIGHEST_PROTOCOL
51
52 import base64
53 import binascii
54 import logging
55 import os
56 import xml.sax
57
58 from xml.sax.handler import ContentHandler
59 from xml.sax.saxutils import XMLGenerator
60 from xml.sax import SAXParseException
61
62 from collections import deque
63
64 try:
65 # Use cStringIO by default as it is faster
66 from cStringIO import StringIO as BytesIO
67 except ImportError: # Python 3 compat
68 from io import BytesIO
69
70 from ClusterShell import __version__
71 from ClusterShell.Event import EventHandler
72
73
74 # XML character encoding
75 ENCODING = 'utf-8'
76
77 # See Message.data_encode()
78 DEFAULT_B64_LINE_LENGTH = 65536
79
80 # Gateway messages may cross Python versions within a tree: cap the pickle
81 # protocol at 4, readable since Python 3.4 (Python 2 writes protocol 2)
82 GW_PICKLE_PROTOCOL = min(HIGHEST_PROTOCOL, 4)
83
84
85 class MessageProcessingError(Exception):
86 """base exception raised when an error occurs while processing incoming or
87 outgoing messages.
88 """
89
90
91 class XMLReader(ContentHandler):
92 """SAX handler for XML -> Messages instances conversion"""
93 def __init__(self):
94 """XMLReader initializer"""
95 ContentHandler.__init__(self)
96 self.msg_queue = deque()
97 self.version = None
98 # current packet under construction
99 self._draft = None
100 self._sections_map = None
101
102 def startElement(self, name, attrs):
103 """read a starting xml tag"""
104 if name == 'channel':
105 self.version = attrs.get('version')
106 self.msg_queue.appendleft(StartMessage())
107 elif name == 'message':
108 self._draft_new(attrs)
109 else:
110 raise MessageProcessingError('Invalid starting tag %s' % name)
111
112 def endElement(self, name):
113 """read an ending xml tag"""
114 # end of message
115 if name == 'message':
116 self.msg_queue.appendleft(self._draft)
117 self._draft = None
118 elif name == 'channel':
119 self.msg_queue.appendleft(EndMessage())
120
121 def characters(self, content):
122 """read content characters (always decoded string)"""
123 if self._draft is not None:
124 self._draft.data_update(content.encode(ENCODING))
125
126 def msg_available(self):
127 """return whether a message is available for delivery or not"""
128 return len(self.msg_queue) > 0
129
130 def pop_msg(self):
131 """pop and return the oldest message queued"""
132 if self.msg_available():
133 return self.msg_queue.pop()
134
135 def _draft_new(self, attributes):
136 """start a new packet construction"""
137 # associative array to select to correct constructor according to the
138 # message type field contained in the serialized representation
139 ctors_map = {
140 ConfigurationMessage.ident: ConfigurationMessage,
141 ControlMessage.ident: ControlMessage,
142 ACKMessage.ident: ACKMessage,
143 ErrorMessage.ident: ErrorMessage,
144 StdOutMessage.ident: StdOutMessage,
145 StdErrMessage.ident: StdErrMessage,
146 RetcodeMessage.ident: RetcodeMessage,
147 TimeoutMessage.ident: TimeoutMessage,
148 RoutingMessage.ident: RoutingMessage,
149 }
150 try:
151 msg_type = attributes.get('type')
152 # select the good constructor
153 ctor = ctors_map[msg_type]
154 except KeyError:
155 if msg_type:
156 ex_msg = "Unknown message type %s" % msg_type
157 else:
158 ex_msg = "Unknown message with no type"
159 raise MessageProcessingError(ex_msg)
160 # build message with its attributes
161 self._draft = ctor()
162 self._draft.selfbuild(attributes)
163
164
165 class Channel(EventHandler):
166 """Use this event handler to establish a communication channel between to
167 hosts within the propagation tree.
168
169 The endpoint's logic has to be implemented by subclassing the Channel class
170 and overriding the start() and recv() methods.
171
172 There is no default behavior for these methods apart raising a
173 NotImplementedError.
174
175 Usage:
176 >> chan = MyChannel() # inherits Channel
177 >> task = task_self()
178 >> task.shell("uname -a", node="host2", handler=chan)
179 >> task.resume()
180 """
181
182 # Common channel stream names
183 SNAME_WRITER = 'ch-writer'
184 SNAME_READER = 'ch-reader'
185 SNAME_ERROR = 'ch-error'
186
187 def __init__(self, initiator=False):
188 """
189 """
190 EventHandler.__init__(self)
191
192 self.worker = None
193
194 # channel state flags
195 self.opened = False
196 self.setup = False
197 # Are we initiating the Channel? False on the receiving Gateway.
198 # if True, this Channel will report errors to subclass as StdErrMessage
199 # if False, this Channel will send communication error responses
200 self.initiator = initiator
201
202 self._xml_reader = XMLReader()
203 self._parser = xml.sax.make_parser(["IncrementalParser"])
204 self._parser.setContentHandler(self._xml_reader)
205
206 self.logger = logging.getLogger(__name__)
207
208 def _init(self):
209 """start xml document for communication"""
210 XMLGenerator(self.worker, encoding=ENCODING).startDocument()
211
212 def _open(self):
213 """open a new communication channel from src to dst"""
214 xmlgen = XMLGenerator(self.worker, encoding=ENCODING)
215 xmlgen.startElement('channel', {'version': __version__})
216
217 def _close(self, abort=False):
218 """close an already opened channel"""
219 if self.opened and not abort:
220 XMLGenerator(self.worker, encoding=ENCODING).endElement('channel')
221 self.worker.abort()
222 self.opened = self.setup = False
223
224 def ev_start(self, worker):
225 """connection established. Open higher level channel"""
226 self.worker = worker
227 self.start()
228
229 def ev_read(self, worker, node, sname, msg):
230 """channel has data to read"""
231 # sname can be either SNAME_READER or self.SNAME_ERROR
232 if sname == self.SNAME_ERROR:
233 if self.initiator:
234 self.recv(StdErrMessage(node, msg))
235 # This is not considered fatal from our side, so we choose to not
236 # close the channel on stderr message.
237 return
238
239 try:
240 self._parser.feed(msg + b'\n')
241 if hasattr(self._parser, 'flush'): # GH#556
242 self._parser.flush()
243 except SAXParseException as ex:
244 self.logger.error("SAXParseException: %s: %s", ex.getMessage(), msg)
245 # Warning: do not send malformed raw message back
246 if self.initiator:
247 self.recv(StdErrMessage(node, ex.getMessage().encode(ENCODING)))
248 else:
249 # target, not initiator: we can send an error message back
250 self.send(ErrorMessage('Parse error: %s' % ex.getMessage()))
251 # This constitutes a fatal channel error, close it now.
252 self._close()
253 return
254 except MessageProcessingError as ex:
255 self.logger.error("MessageProcessingError: %s (initiator=%s)",
256 ex, self.initiator)
257 if self.initiator:
258 self.recv(StdErrMessage(node, str(ex).encode(ENCODING)))
259 else:
260 # target, not initiator: we can send an error message back
261 self.send(ErrorMessage(str(ex)))
262 # This constitutes a fatal channel error, close it now.
263 self._close()
264 return
265
266 # pass messages to the driver if ready
267 while self._xml_reader.msg_available():
268 msg = self._xml_reader.pop_msg()
269 assert msg is not None
270 self.recv(msg)
271
272 def send(self, msg):
273 """write an outgoing message as its XML representation"""
274 #self.logger.debug('SENDING to worker %s: "%s"', id(self.worker),
275 # msg.xml())
276 self.worker.write(msg.xml() + b'\n', sname=self.SNAME_WRITER)
277
278 def start(self):
279 """initialization logic"""
280 raise NotImplementedError('Abstract method: subclasses must implement')
281
282 def recv(self, msg):
283 """callback: process incoming message"""
284 raise NotImplementedError('Abstract method: subclasses must implement')
285
286
287 class Message(object):
288 """base message class"""
289 _inst_counter = 0
290 ident = 'GEN'
291 has_payload = False
292
293 def __init__(self):
294 """
295 """
296 self.attr = {'type': str, 'msgid': int}
297 self.type = self.__class__.ident
298 self.msgid = Message._inst_counter
299 self.data = None
300 Message._inst_counter += 1
301
302 def data_encode(self, inst):
303 """serialize an instance and store the result"""
304 # Base64 transfer encoding for MIME mandates a fixed line length
305 # of 76 characters, which is way too small for our per-line ev_read
306 # mechanism. So use b64encode() here instead of encodestring().
307 encoded = base64.b64encode(cPickle.dumps(inst, GW_PICKLE_PROTOCOL))
308
309 # We now follow relaxed RFC-4648 for base64, but we still add some
310 # newlines to very long lines to avoid memory pressure (eg. --rcopy).
311 # In RFC-4648, CRLF characters constitute "non-alphabet characters"
312 # and are ignored.
313 line_length = int(os.environ.get('CLUSTERSHELL_GW_B64_LINE_LENGTH',
314 DEFAULT_B64_LINE_LENGTH))
315 self.data = b'\n'.join(encoded[pos:pos+line_length]
316 for pos in range(0, len(encoded), line_length))
317
318 def data_decode(self):
319 """deserialize a previously encoded instance and return it"""
320 # NOTE: name is confusing, data_decode() returns pickle-decoded bytes
321 # (encoded string) and not (decoded) string...
322 # if self.data is None then an exception is raised here
323 try:
324 return cPickle.loads(base64.b64decode(self.data))
325 except (EOFError, TypeError, ValueError, cPickle.UnpicklingError,
326 binascii.Error) as exc:
327 # raised by cPickle.loads() if self.data is not valid
328 raise MessageProcessingError('Message %s has an invalid payload'
329 ' (%s)' % (self.ident, exc))
330
331 def data_update(self, raw):
332 """append data to the instance (used for deserialization)"""
333 if self.has_payload:
334 if self.data is None:
335 self.data = raw # first encoded packet
336 else:
337 self.data += raw
338 else:
339 # ensure that incoming messages don't contain unexpected payloads
340 raise MessageProcessingError('Got unexpected payload for Message %s'
341 % self.ident)
342
343 def selfbuild(self, attributes):
344 """self construction from a table of attributes"""
345 for k, fmt in self.attr.items():
346 try:
347 setattr(self, k, fmt(attributes[k]))
348 except KeyError:
349 raise MessageProcessingError(
350 'Invalid "message" attributes: missing key "%s"' % k)
351
352 def __str__(self):
353 """printable representation"""
354 elts = ['%s: %s' % (k, str(self.__dict__[k])) for k in self.attr.keys()]
355 attributes = ', '.join(elts)
356 return "Message %s (%s)" % (self.type, attributes)
357
358 def xml(self):
359 """generate XML version of a configuration message"""
360 out = BytesIO()
361 generator = XMLGenerator(out, encoding=ENCODING)
362
363 # "stringify" entries for XML conversion
364 state = {}
365 for k in self.attr:
366 state[k] = str(getattr(self, k))
367
368 generator.startElement('message', state)
369 if self.data:
370 generator.characters(self.data)
371 generator.endElement('message')
372 xml_msg = out.getvalue()
373 out.close()
374 return xml_msg
375
376 class ConfigurationMessage(Message):
377 """configuration propagation container"""
378 ident = 'CFG'
379 has_payload = True
380
381 def __init__(self, gateway=''):
382 """initialize with gateway node name"""
383 Message.__init__(self)
384 self.attr.update({'gateway': str})
385 self.gateway = gateway
386
387 class RoutedMessageBase(Message):
388 """abstract class for routed message (with worker source id)"""
389 def __init__(self, srcid):
390 Message.__init__(self)
391 self.attr.update({'srcid': int})
392 self.srcid = srcid
393
394 class ControlMessage(RoutedMessageBase):
395 """action request"""
396 ident = 'CTL'
397 has_payload = True
398
399 def __init__(self, srcid=0):
400 """
401 """
402 RoutedMessageBase.__init__(self, srcid)
403 self.attr.update({'action': str, 'target': str})
404 self.action = ''
405 self.target = ''
406
407 class ACKMessage(Message):
408 """acknowledgement message"""
409 ident = 'ACK'
410
411 def __init__(self, ackid=0):
412 """
413 """
414 Message.__init__(self)
415 self.attr.update({'ack': int})
416 self.ack = ackid
417
418 class ErrorMessage(Message):
419 """error message"""
420 ident = 'ERR'
421
422 def __init__(self, err=''):
423 """
424 """
425 Message.__init__(self)
426 self.attr.update({'reason': str})
427 self.reason = err
428
429 class StdOutMessage(RoutedMessageBase):
430 """container message for standard output"""
431 ident = 'OUT'
432 has_payload = True
433
434 def __init__(self, nodes='', output=None, srcid=0):
435 """
436 Initialized either with empty payload (to be loaded, already encoded),
437 or with payload provided (via output to encode here).
438 """
439 RoutedMessageBase.__init__(self, srcid)
440 self.attr.update({'nodes': str})
441 self.nodes = nodes
442 self.data = None # something encoded or None
443 if output is not None:
444 self.data_encode(output)
445
446 class StdErrMessage(StdOutMessage):
447 """container message for stderr output"""
448 ident = 'SER'
449
450 class RetcodeMessage(RoutedMessageBase):
451 """container message for return code"""
452 ident = 'RET'
453
454 def __init__(self, nodes='', retcode=0, srcid=0):
455 """
456 """
457 RoutedMessageBase.__init__(self, srcid)
458 self.attr.update({'retcode': int, 'nodes': str})
459 self.retcode = retcode
460 self.nodes = nodes
461
462 class TimeoutMessage(RoutedMessageBase):
463 """container message for timeout notification"""
464 ident = 'TIM'
465
466 def __init__(self, nodes='', srcid=0):
467 """
468 """
469 RoutedMessageBase.__init__(self, srcid)
470 self.attr.update({'nodes': str})
471 self.nodes = nodes
472
473 class RoutingMessage(RoutedMessageBase):
474 """container message for routing notification"""
475 ident = 'RTR'
476
477 def __init__(self, event='', gateway='', targets='', srcid=0):
478 """
479 """
480 RoutedMessageBase.__init__(self, srcid)
481 self.attr.update({'event': str, 'gateway': str, 'targets': str})
482 self.event = event
483 self.gateway = gateway
484 self.targets = targets
485
486 class StartMessage(Message):
487 """message indicating the start of a channel communication"""
488 ident = 'CHA'
489
490 class EndMessage(Message):
491 """end of channel message"""
492 ident = 'END'