Debian Codegraph @

lib/ClusterShell/Worker/EngineClient.py

raw symbols SCIP
1 #
2 # Copyright (C) 2009-2016 CEA/DAM
3 # Copyright (C) 2016-2017 Stephane Thiell <[email protected]>
4 #
5 # This file is part of ClusterShell.
6 #
7 # ClusterShell is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # ClusterShell is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with ClusterShell; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
21 """
22 EngineClient
23
24 ClusterShell engine's client interface.
25
26 An engine client is similar to a process, you can start/stop it, read data from
27 it and write data to it. Multiple data channels are supported (eg. stdin, stdout
28 and stderr, or even more...)
29 """
30
31 import errno
32 import logging
33 import os
34
35 try:
36 import queue
37 except ImportError:
38 # Python 2 compatibility
39 import Queue as queue
40
41 import threading
42
43 from ClusterShell.Defaults import DEFAULTS
44 from ClusterShell.Worker.fastsubprocess import Popen, PIPE, STDOUT, \
45 set_nonblock_flag
46 from ClusterShell.Engine.Engine import EngineBaseTimer, E_READ, E_WRITE
47
48
49 LOGGER = logging.getLogger(__name__)
50
51
52 class EngineClientException(Exception):
53 """Generic EngineClient exception."""
54
55 class EngineClientEOF(EngineClientException):
56 """EOF from client."""
57
58 class EngineClientError(EngineClientException):
59 """Base EngineClient error exception."""
60
61 class EngineClientNotSupportedError(EngineClientError):
62 """Operation not supported by EngineClient."""
63
64
65 class EngineClientStream(object):
66 """EngineClient I/O stream object.
67
68 Internal object used by EngineClient to manage its Engine-registered I/O
69 streams. Each EngineClientStream is bound to a file object (file
70 descriptor). It can be either an input, an output or a bidirectional
71 stream (not used for now)."""
72
73 def __init__(self, name, sfile=None, evmask=0):
74 """Initialize an EngineClientStream object.
75
76 @param name: Name of stream.
77 @param sfile: File object or file descriptor.
78 @param evmask: Config I/O event bitmask.
79 """
80 self.name = name
81 self.fd = None
82 self.rbuf = bytes()
83 self.wbuf = bytes()
84 self.eof = False
85 self.evmask = evmask
86 self.events = 0
87 self.new_events = 0
88 self.retain = False
89 self.closefd = False
90 self.set_file(sfile)
91
92 def set_file(self, sfile, evmask=0, retain=True, closefd=True):
93 """
94 Set the stream file and event mask for this object.
95 sfile should be a file object or a file descriptor.
96 Event mask can be either E_READ, E_WRITE or both.
97 Currently does NOT retain file object.
98 """
99 try:
100 # file descriptor
101 self.fd = sfile.fileno()
102 except AttributeError:
103 self.fd = sfile
104 # Set I/O event mask
105 self.evmask = evmask
106 # Set retain flag
107 self.retain = retain
108 # Set closefd flag
109 self.closefd = closefd
110
111 def __repr__(self):
112 return "<%s at 0x%s (name=%s fd=%s rbuflen=%d wbuflen=%d eof=%d " \
113 "evmask=0x%x)>" % (self.__class__.__name__, id(self), self.name,
114 self.fd, len(self.rbuf), len(self.wbuf), self.eof, self.evmask)
115
116 def close(self):
117 """Close stream."""
118 if self.closefd and self.fd is not None:
119 os.close(self.fd)
120
121 def readable(self):
122 """Return whether the stream is setup as readable."""
123 return self.evmask & E_READ
124
125 def writable(self):
126 """Return whether the stream is setup as writable."""
127 return self.evmask & E_WRITE
128
129
130 class EngineClientStreamDict(dict):
131 """EngineClient's named stream dictionary."""
132
133 def set_stream(self, sname, sfile=None, evmask=0, retain=True,
134 closefd=True):
135 """Set stream based on file object or file descriptor.
136
137 This method can be used to add a stream or update its
138 parameters.
139 """
140 engfile = dict.setdefault(self, sname, EngineClientStream(sname))
141 engfile.set_file(sfile, evmask, retain, closefd)
142 return engfile
143
144 def set_reader(self, sname, sfile=None, retain=True, closefd=True):
145 """Set readable stream based on file object or file descriptor."""
146 self.set_stream(sname, sfile, E_READ, retain, closefd)
147
148 def set_writer(self, sname, sfile=None, retain=True, closefd=True):
149 """Set writable stream based on file object or file descriptor."""
150 self.set_stream(sname, sfile, E_WRITE, retain, closefd)
151
152 def destroy(self, key):
153 """Close file object and remove it from this pool."""
154 self[key].close()
155 dict.pop(self, key)
156
157 def __delitem__(self, key):
158 self.destroy(key)
159
160 def clear(self):
161 """Clear File Pool"""
162 for stream in self.values():
163 stream.close()
164 dict.clear(self)
165
166 def active_readers(self):
167 """Get an iterator on readable streams (with fd set)."""
168 return (s for s in self.readers() if s.fd is not None)
169
170 def readers(self):
171 """Get an iterator on all streams setup as readable."""
172 return (s for s in list(self.values()) if s.evmask & E_READ)
173
174 def active_writers(self):
175 """Get an iterator on writable streams (with fd set)."""
176 return (s for s in self.writers() if s.fd is not None)
177
178 def writers(self):
179 """Get an iterator on all streams setup as writable."""
180 return (s for s in list(self.values()) if s.evmask & E_WRITE)
181
182 def retained(self):
183 """Check whether this set of streams is retained.
184
185 Note on retain: an active stream with retain=True keeps the
186 engine client alive. When only streams with retain=False
187 remain, the engine client terminates.
188
189 Return:
190 True -- when at least one stream is retained
191 False -- when no retainable stream remain
192 """
193 for stream in self.values():
194 if stream.fd is not None and stream.retain:
195 return True
196 return False
197
198
199 class EngineClient(EngineBaseTimer):
200 """
201 Abstract class EngineClient.
202 """
203
204 def __init__(self, worker, key, stderr, timeout, autoclose):
205 """EngineClient initializer.
206
207 Should be called from derived classes.
208
209 Arguments:
210 worker -- parent worker instance
211 key -- client key used by MsgTree (eg. node name)
212 stderr -- boolean set if stderr is on a separate stream
213 timeout -- client execution timeout value (float)
214 autoclose -- boolean set to indicate whether this engine
215 client should be aborted as soon as all other
216 non-autoclosing clients have finished.
217 """
218
219 EngineBaseTimer.__init__(self, timeout, -1, autoclose)
220
221 self._reg_epoch = 0 # registration generation number
222
223 # read-only public
224 self.registered = False # registered on engine or not
225 self.delayable = True # subject to fanout limit
226
227 self.worker = worker
228 if key is None:
229 key = id(worker)
230 self.key = key
231
232 # boolean indicating whether stderr is on a separate fd
233 self._stderr = stderr
234
235 # streams associated with this client
236 self.streams = EngineClientStreamDict()
237
238 def __repr__(self):
239 # added repr(self.key)
240 return '<%s.%s instance at 0x%x key %r>' % (self.__module__,
241 self.__class__.__name__,
242 id(self), self.key)
243
244 def _fire(self):
245 """
246 Fire timeout timer.
247 """
248 if self._engine:
249 self._engine.remove(self, abort=True, did_timeout=True)
250
251 def _start(self):
252 """
253 Starts client and returns client instance as a convenience.
254 Derived classes must implement.
255 """
256 raise NotImplementedError("Derived classes must implement.")
257
258 def _close(self, abort, timeout):
259 """
260 Close client. Called by the engine after client has been unregistered.
261 This method should handle both termination types (normal or aborted)
262 and should set timeout status accordingly.
263
264 Derived classes should implement.
265 """
266 for sname in list(self.streams):
267 # for engine-induced timeout with abort, do not actually abort
268 # the stream so we can flush buffers (original behavior)
269 self._close_stream(sname, abort and not timeout)
270
271 self.invalidate() # set self._engine to None
272
273 def _close_stream(self, sname, abort=False):
274 """
275 Close specific stream by name (internal, called by engine). This method
276 is the regular way to close a stream flushing read buffers accordingly,
277 unless we are closing the stream with the abort flag set to True.
278 """
279 # flush_read() is useful but may generate user events (ev_read) that
280 # could lead to worker abort and then ev_close. Be careful there.
281 # If we are doing a close with abort, skip the flush (this is newer).
282 if not abort:
283 self._flush_read(sname)
284 if sname in self.streams:
285 del self.streams[sname]
286
287 def _set_reading(self, sname):
288 """
289 Set reading state.
290 """
291 self._engine.set_reading(self, sname)
292
293 def _set_writing(self, sname):
294 """
295 Set writing state.
296 """
297 self._engine.set_writing(self, sname)
298
299 def _read(self, sname, size=65536):
300 """
301 Read data from process.
302 """
303 result = os.read(self.streams[sname].fd, size)
304 if len(result) == 0:
305 raise EngineClientEOF()
306 self._set_reading(sname)
307 return result
308
309 def _flush_read(self, sname):
310 """Called when stream is closing to flush read buffers."""
311 pass # derived classes may implement
312
313 def _handle_read(self, sname):
314 """
315 Handle a read notification. Called by the engine as the result of an
316 event indicating that a read is available.
317 """
318 raise NotImplementedError("Derived classes must implement.")
319
320 def _handle_write(self, sname):
321 """
322 Handle a write notification. Called by the engine as the result of an
323 event indicating that a write can be performed now.
324 """
325 wfile = self.streams[sname]
326 if not wfile.wbuf and wfile.eof:
327 # remove stream from engine (not directly)
328 if self._engine:
329 self._engine.remove_stream(self, wfile)
330 elif len(wfile.wbuf) > 0:
331 try:
332 wcnt = os.write(wfile.fd, wfile.wbuf)
333 except OSError as exc:
334 if exc.errno == errno.EAGAIN:
335 # _handle_write() is not only called by the engine but also
336 # by _write(), so this is legit: we just try again later
337 self._set_writing(sname)
338 return
339 if exc.errno == errno.EPIPE:
340 # broken pipe: log warning message and do NOT retry
341 LOGGER.warning('%r: %s', self, exc)
342 # remove stream now; select engine has no POLLERR
343 if self._engine:
344 self._engine.remove_stream(self, wfile)
345 return
346 raise
347 if wcnt > 0:
348 # dequeue written buffer
349 wfile.wbuf = wfile.wbuf[wcnt:]
350 # check for possible ending
351 if wfile.eof and not wfile.wbuf:
352 self.worker._on_written(self.key, wcnt, sname)
353 # remove stream from engine (not directly)
354 if self._engine:
355 self._engine.remove_stream(self, wfile)
356 else:
357 self._set_writing(sname)
358 self.worker._on_written(self.key, wcnt, sname)
359
360 def _exec_nonblock(self, commandlist, shell=False, env=None):
361 """
362 Utility method to launch a command with stdin/stdout file
363 descriptors configured in non-blocking mode.
364 """
365 full_env = None
366 if env:
367 full_env = os.environ.copy()
368 full_env.update(env)
369
370 if self._stderr:
371 stderr_setup = PIPE
372 else:
373 stderr_setup = STDOUT
374
375 # Launch process in non-blocking mode
376 proc = Popen(commandlist, bufsize=0, stdin=PIPE, stdout=PIPE,
377 stderr=stderr_setup, shell=shell, env=full_env)
378
379 if self._stderr:
380 self.streams.set_stream(self.worker.SNAME_STDERR, proc.stderr,
381 E_READ)
382 self.streams.set_stream(self.worker.SNAME_STDOUT, proc.stdout, E_READ)
383 self.streams.set_stream(self.worker.SNAME_STDIN, proc.stdin, E_WRITE,
384 retain=False)
385
386 return proc
387
388 def _readlines(self, sname):
389 """Utility method to read client lines."""
390 # read a chunk of data, may raise eof
391 readbuf = self._read(sname)
392 assert len(readbuf) > 0, "assertion failed: len(readbuf) > 0"
393
394 # Current version implements line-buffered reads. If needed, we could
395 # easily provide direct, non-buffered, data reads in the future.
396
397 rfile = self.streams[sname]
398
399 buf = rfile.rbuf + readbuf
400 lines = buf.splitlines(True)
401 rfile.rbuf = bytes()
402 for line in lines:
403 if line.endswith(b'\n'):
404 if line.endswith(b'\r\n'):
405 yield line[:-2] # trim CRLF
406 else:
407 # trim LF
408 yield line[:-1] # trim LF
409 else:
410 # keep partial line in buffer
411 rfile.rbuf = line
412 # breaking here
413
414 def _write(self, sname, buf):
415 """Add some data to be written to the client."""
416 if sname not in self.streams:
417 LOGGER.debug("dropping write to unknown or closed stream %s on "
418 "client %s", sname, self.key)
419 return
420
421 wfile = self.streams[sname]
422 if self._engine and wfile.fd:
423 wfile.wbuf += buf
424 # give it a try now (will set writing flag anyhow)
425 self._handle_write(sname)
426 else:
427 # bufferize until pipe is ready
428 wfile.wbuf += buf
429
430 def _set_write_eof(self, sname):
431 """Set EOF on specific writable stream."""
432 if sname not in self.streams:
433 LOGGER.debug("stream %s was already closed on client %s, skipping",
434 sname, self.key)
435 return
436
437 wfile = self.streams[sname]
438 wfile.eof = True
439 if self._engine and wfile.fd and not wfile.wbuf:
440 # sendq empty, remove stream now
441 self._engine.remove_stream(self, wfile)
442
443 def abort(self):
444 """Abort processing any action by this client.
445
446 Safe to call on an already closing or aborting client.
447 """
448 engine = self._engine
449 if engine:
450 self.invalidate() # set self._engine to None
451 engine.remove(self, abort=True)
452
453
454 class EnginePort(EngineClient):
455 """
456 An EnginePort is an abstraction object to deliver messages
457 reliably between tasks.
458 """
459
460 class _Msg(object):
461 """Private class representing a port message.
462
463 A port message may be any Python object.
464 """
465
466 def __init__(self, user_msg, sync):
467 self._user_msg = user_msg
468 self._sync_msg = sync
469 self.reply_lock = threading.Lock()
470 self.reply_lock.acquire()
471
472 def get(self):
473 """
474 Get and acknowledge message.
475 """
476 self.reply_lock.release()
477 return self._user_msg
478
479 def sync(self):
480 """
481 Wait for message acknowledgment if needed.
482 """
483 if self._sync_msg:
484 self.reply_lock.acquire()
485
486 def __init__(self, handler=None, autoclose=False):
487 """
488 Initialize EnginePort object.
489 """
490 EngineClient.__init__(self, None, None, False, -1, autoclose)
491 self.eh = handler
492 # ports are no subject to fanout
493 self.delayable = False
494
495 # Port messages queue
496 self._msgq = queue.Queue(DEFAULTS.port_qlimit)
497
498 # Request pipe
499 (readfd, writefd) = os.pipe()
500 # Set nonblocking flag
501 set_nonblock_flag(readfd)
502 set_nonblock_flag(writefd)
503 self.streams.set_stream('in', readfd, E_READ)
504 self.streams.set_stream('out', writefd, E_WRITE)
505
506 def __repr__(self):
507 try:
508 fd_in = self.streams['in'].fd
509 except KeyError:
510 fd_in = None
511 try:
512 fd_out = self.streams['out'].fd
513 except KeyError:
514 fd_out = None
515 return "<%s at 0x%s (streams=(%s, %s))>" % (self.__class__.__name__,
516 id(self), fd_in, fd_out)
517
518 def _start(self):
519 """Start port."""
520 if self.eh is not None:
521 self.eh.ev_port_start(self)
522 return self
523
524 def _close(self, abort, timeout):
525 """Close port."""
526 if not self._msgq.empty():
527 # purge msgq
528 try:
529 while not self._msgq.empty():
530 pmsg = self._msgq.get(block=False)
531 LOGGER.debug('%r: dropped msg: %s', self, pmsg.get())
532 except queue.Empty:
533 pass
534 self._msgq = None
535 del self.streams['out']
536 del self.streams['in']
537 self.invalidate()
538
539 def _handle_read(self, sname):
540 """
541 Handle a read notification. Called by the engine as the result of an
542 event indicating that a read is available.
543 """
544 readbuf = self._read(sname, 4096)
545 for dummy_char in readbuf:
546 # raise Empty if empty (should never happen)
547 pmsg = self._msgq.get(block=False)
548 self.eh.ev_msg(self, pmsg.get())
549
550 def msg(self, send_msg, send_once=False):
551 """
552 Port message send method that will wait for acknowledgement
553 unless the send_once parameter if set.
554
555 May be called from another thread. Will generate ev_msg() on
556 Port event handler (in Port task/thread).
557
558 Return False if the message cannot be sent (eg. port closed).
559 """
560 if self._msgq is None: # called after port closed?
561 return False
562
563 pmsg = EnginePort._Msg(send_msg, not send_once)
564 self._msgq.put(pmsg, block=True, timeout=None)
565 try:
566 ret = os.write(self.streams['out'].fd, b'M')
567 except OSError:
568 raise
569 pmsg.sync()
570 return ret == 1
571
572 def msg_send(self, send_msg):
573 """
574 Port message send-once method (no acknowledgement). See msg().
575
576 Return False if the message cannot be sent (eg. port closed).
577 """
578 return self.msg(send_msg, send_once=True)