Debian Codegraph @

pyxs/client.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 pyxs.client
4 ~~~~~~~~~~~
5
6 This module implements XenStore client, which can communicate with
7 XenStore either via: :class:`~pyxs.connection.UnixSocketConnection`
8 or :class:`~pyxs.connection.XenBusConnection`.
9
10 :copyright: (c) 2011 by Selectel.
11 :copyright: (c) 2016 by pyxs authors and contributors, see AUTHORS
12 for more details.
13 :license: LGPL, see LICENSE for more details.
14 """
15
16 from __future__ import absolute_import
17
18 __all__ = ["Router", "Client", "Monitor"]
19
20 import copy
21 import errno
22 import posixpath
23 import re
24 import socket
25 import select
26 import sys
27 import threading
28 from collections import defaultdict
29 from functools import partial
30
31 try:
32 import Queue as queue
33 except ImportError:
34 import queue
35
36 # XXX see ``Router`` docstring for motivation.
37 if sys.version_info[:2] < (3, 2):
38 _condition_wait = partial(threading._Condition.wait, timeout=1)
39 else:
40 _condition_wait = threading.Condition.wait
41
42 from ._internal import NUL, Event, Packet, Op, next_rq_id
43 from .connection import UnixSocketConnection, XenBusConnection
44 from .exceptions import UnexpectedPacket, ConnectionError, PyXSError
45 from .helpers import check_path, check_watch_path, check_perms, error
46
47 _re_7bit_ascii = re.compile(b"^[\x00\x20-\x7f]*$")
48
49
50 class Router(object):
51 """Router.
52
53 The goal of the router is to multiplex XenStore connection between
54 multiple clients and monitors.
55
56 .. versionadded: 0.4.0
57
58 :param connection FileDescriptorConnection:
59 owned by the router. The connection is open when the router is
60 started and remains open until the router is terminated.
61
62 .. note::
63
64 Python lacks API for interrupting a thread from another thread.
65 This means that when a router cannot be stopped when it is blocked
66 in :func:`select.select` or :meth:`~threading.Condition.wait`.
67
68 The following two "hacks" are used to ensure prompt termination.
69
70 1. A router is equipped with a :func:`socket.socketpair`. The
71 reader-end of the pair is selected in the mainloop alongside
72 the XenStore connection, while the writer-end is used in
73 :meth:`~pyxs.client.Router.terminate` to force-stop the mainloop.
74 2. All operations with :class:`threading.Condition` variables user
75 a 1 second timeout. This "hack" is only relevant for Python
76 prior to 3.2 which didn't allow one to interrupt lock acquisitions.
77 See `issue8844`_ on CPython issue tracker for details. On
78 Python 3.2 and later no timeout is used.
79
80 .. _issue8844: https://bugs.python.org/issue8844
81 """
82 def __init__(self, connection):
83 self.r_terminator, self.w_terminator = socket.socketpair()
84 self.connection = connection
85 self.send_lock = threading.Lock()
86 self.rvars = {}
87 self.monitors = defaultdict(list)
88
89 # Router thread is daemonic to prevent blocking in case
90 # the client wasn't finilzed properly, e.g. unhandled
91 # exception outside of ``with``. As a result, we cannot
92 # guarantee data integrity unless either ``close`` or
93 # ``__exit__`` was closed.
94 self.thread = threading.Thread(target=self)
95 self.thread.daemon = True
96
97 def __repr__(self):
98 return "Router({0})".format(self.connection)
99
100 def __call__(self):
101 try:
102 while True:
103 rlist, _wlist, _xlist = select.select(
104 [self.connection, self.r_terminator], [], [])
105 if not rlist:
106 continue
107 elif self.r_terminator in rlist:
108 break
109
110 packet = self.connection.recv()
111 if packet.op == Op.WATCH_EVENT:
112 event = Event(*packet.payload.split(NUL)[:-1])
113 for monitor in self.monitors[event.token]:
114 monitor.events.put(event)
115 else:
116 rvar = self.rvars.pop(packet.rq_id, None)
117 if rvar is None:
118 raise UnexpectedPacket(packet)
119 else:
120 rvar.set(packet)
121 finally:
122 self.connection.close()
123 self.r_terminator.close()
124 self.w_terminator.close()
125
126 @property
127 def is_connected(self):
128 """Checks if the underlying connection is active."""
129 return self.connection.is_connected
130
131 def subscribe(self, token, monitor):
132 """Subscribes a ``monitor`` from events with a given ``token``."""
133 self.monitors[token].append(monitor)
134
135 def unsubscribe(self, token, monitor):
136 """Unsubscribes a ``monitor`` to events with a given ``token``."""
137 self.monitors[token].remove(monitor)
138
139 def send(self, packet):
140 """Sends a packet to XenStore.
141
142 :returns RVar: a reference to the XenStore response.
143 """
144 with self.send_lock:
145 # The order here matters. XenStore might reply to the packet
146 # *before* the ``rvar`` is registered.
147 self.rvars[packet.rq_id] = rvar = RVar()
148 self.connection.send(packet)
149 return rvar
150
151 def start(self):
152 """Starts the router thread.
153
154 Does nothing if the router is already started.
155 """
156 # Connection is deliberately done in the calling thread so that
157 # ``ConnectionError`` could be handled. See issue #8 on GitHub
158 # for details.
159 self.connection.connect()
160
161 if not self.thread.is_alive():
162 self.thread.start()
163
164 while not self.is_connected:
165 if not self.thread.is_alive():
166 raise ConnectionError("router died")
167
168 def terminate(self):
169 """Terminates the router.
170
171 After termination the router can no longer send or receive packets.
172 Does nothing if the router was already terminated.
173 """
174 if self.is_connected:
175 self.w_terminator.sendall(NUL)
176
177 if self.thread.is_alive():
178 self.thread.join()
179
180
181 class RVar(object):
182 """A thread-safe shared mutable reference.
183
184 .. versionadded:: 0.4.0
185 """
186 __slots__ = ["condition", "target"]
187
188 def __init__(self):
189 self.condition = threading.Condition()
190 self.target = None
191
192 def __repr__(self):
193 return "RVar({0})".format(self.target)
194
195 def get(self):
196 """Blocks until the value is :meth:`set`` and then returns the value.
197
198 .. note:: The returned value is guaranteed never to be ``None``.
199 """
200 with self.condition:
201 while self.target is None:
202 _condition_wait(self.condition)
203
204 return self.target
205
206 def set(self, target):
207 """Sets the value, which effectively unblocks all :meth:`get` calls."""
208 with self.condition:
209 self.target = target
210 self.condition.notify_all()
211
212
213 class Client(object):
214 """XenStore client.
215
216 :param str unix_socket_path: path to XenStore Unix domain socket.
217 :param str xen_bus_path: path to XenBus device.
218
219 If ``unix_socket_path`` is given or :class:`~pyxs.client.Client`
220 was created with no arguments, XenStore is accessed via
221 :class:`~pyxs.connection.UnixSocketConnection`; otherwise,
222 :class:`~pyxs.connection.XenBusConnection` is used.
223
224 Each client has a :class:`~pyxs.client.Router` thread running
225 in the background. The goal of the router is to multiplex
226 requests from different transaction through a single XenStore
227 connection.
228
229 .. versionchanged:: 0.4.0
230
231 The constructor no longer accepts ``connection`` argument. If
232 you wan't to force the use of a specific connection class, wrap
233 it in a :class:`~pyxs.client.Router`::
234
235 from pyxs import Router, Client
236 from pyxs.connection import XenBusConnection
237
238 router = Router(XenBusConnection())
239 with Client(router=router) as c:
240 do_something(c)
241
242 .. warning::
243
244 Always finalize the client either explicitly by calling
245 :meth:`~pyxs.client.Client.close` or implicitly via
246 a context manager to prevent data loss.
247
248 .. seealso::
249
250 `Xenstore protocol specification \
251 <http://xenbits.xen.org/docs/4.4-testing/misc/xenstore.txt>`_
252 for a description of the protocol, implemented by ``Client``.
253 """
254 #: A flag, which is ``True`` if we're operating on control domain
255 #: and else otherwise.
256 try:
257 SU = open("/proc/xen/capabilities", "rb").read() == b"control_d\n"
258 except (IOError, OSError):
259 SU = False
260
261 def __init__(self, unix_socket_path=None, xen_bus_path=None, router=None):
262 if router is None:
263 if unix_socket_path or not xen_bus_path:
264 connection = UnixSocketConnection(unix_socket_path)
265 else:
266 connection = XenBusConnection(xen_bus_path)
267
268 router = Router(connection)
269
270 self.router = router
271 self.tx_id = 0
272
273 def __repr__(self):
274 return "Client({0})".format(self.router.connection)
275
276 def __copy__(self):
277 return self.__class__(router=self.router)
278
279 def __enter__(self):
280 self.connect()
281 return self
282
283 def __exit__(self, *exc_info):
284 self.close()
285
286 if self.tx_id and not any(exc_info):
287 raise PyXSError("uncommitted transaction")
288
289 # Private API.
290 # ............
291
292 def execute_command(self, op, *args, **kwargs):
293 if not all(map(_re_7bit_ascii.match, args)):
294 raise ValueError(args)
295
296 kwargs.update(tx_id=self.tx_id, rq_id=next_rq_id())
297 rvar = self.router.send(Packet(op, b"".join(args), **kwargs))
298 packet = rvar.get()
299 if packet.op == Op.ERROR:
300 # Erroneous responses are POSIX error code ending with a
301 # ``NUL`` byte.
302 raise error(packet.payload[:-1])
303 elif packet.op != op or packet.tx_id != self.tx_id:
304 raise UnexpectedPacket(packet)
305
306 return packet.payload.rstrip(NUL)
307
308 def ack(self, *args):
309 payload = self.execute_command(*args)
310 if payload != b"OK":
311 raise PyXSError(payload)
312
313 # Public API.
314 # ...........
315
316 def connect(self):
317 """Connects to the XenStore daemon.
318
319 :raises pyxs.exceptions.ConnectionError: if the connection could
320 not be opened. This could happen either because XenStore is
321 not running on the machine or due to the lack of permissions.
322
323 .. versionadded: 0.4.0
324
325 .. warning:: This method is unsafe. Please use client as a context
326 manager to ensure it is properly finalized.
327 """
328 self.router.start()
329
330 def close(self):
331 """Finalizes the client.
332
333 .. warning:: This method is unsafe. Please use client as a context
334 manager to ensure it is properly finalized.
335 """
336 self.router.terminate()
337
338 def read(self, path, default=None):
339 """Reads data from a given path.
340
341 :param bytes path: a path to read from.
342 :param bytes default: default value, to be used if `path` doesn't
343 exist.
344 """
345 check_path(path)
346 try:
347 return self.execute_command(Op.READ, path + NUL)
348 except PyXSError as e:
349 if e.args[0] == errno.ENOENT and default is not None:
350 return default
351
352 raise
353
354 __getitem__ = read
355
356 def write(self, path, value):
357 """Writes data to a given path.
358
359 :param bytes value: data to write.
360 :param bytes path: a path to write to.
361 """
362 check_path(path)
363 self.ack(Op.WRITE, path + NUL, value)
364
365 __setitem__ = write
366
367 def mkdir(self, path):
368 """Ensures that a given path exists, by creating it and any
369 missing parents with empty values. If `path` or any parent
370 already exist, its value is left unchanged.
371
372 :param bytes path: path to directory to create.
373 """
374 check_path(path)
375 self.ack(Op.MKDIR, path + NUL)
376
377 def delete(self, path):
378 """Ensures that a given does not exist, by deleting it and all
379 of its children. It is not an error if `path` doesn't exist, but
380 it **is** an error if `path`'s immediate parent does not exist
381 either.
382
383 :param bytes path: path to directory to remove.
384 """
385 check_path(path)
386 self.ack(Op.RM, path + NUL)
387
388 __delitem__ = delete
389
390 def list(self, path):
391 """Returns a list of names of the immediate children of `path`.
392
393 :param bytes path: path to list.
394 """
395 check_path(path)
396 payload = self.execute_command(Op.DIRECTORY, path + NUL)
397 return [] if not payload else payload.split(NUL)
398
399 def exists(self, path):
400 """Checks if a given `path` exists.
401
402 :param bytes path: path to check.
403 """
404 try:
405 self.list(path)
406 except PyXSError as e:
407 if e.args[0] == errno.ENOENT:
408 return False
409
410 raise
411 else:
412 return True
413
414 def get_perms(self, path):
415 """Returns a list of permissions for a given `path`, see
416 :exc:`~pyxs.exceptions.InvalidPermission` for details on
417 permission format.
418
419 :param bytes path: path to get permissions for.
420 """
421 check_path(path)
422 payload = self.execute_command(Op.GET_PERMS, path + NUL)
423 return payload.split(NUL)
424
425 def set_perms(self, path, perms):
426 """Sets a access permissions for a given `path`, see
427 :exc:`~pyxs.exceptions.InvalidPermission` for details on
428 permission format.
429
430 :param bytes path: path to set permissions for.
431 :param list perms: a list of permissions to set.
432 """
433 check_path(path)
434 check_perms(perms)
435 self.ack(Op.SET_PERMS, path + NUL, *(perm + NUL for perm in perms))
436
437 def walk(self, top, topdown=True):
438 """Walk XenStore, yielding 3-tuples ``(path, value, children)``
439 for each node in the tree, rooted at node `top`.
440
441 :param bytes top: node to start from.
442 :param bool topdown: see :func:`os.walk` for details.
443 """
444 children = self.list(top)
445
446 try:
447 value = self.read(top)
448 except PyXSError:
449 value = b"" # '/' or no read permissions?
450
451 if topdown:
452 yield top, value, children
453
454 for child in children:
455 for x in self.walk(posixpath.join(top, child)):
456 yield x
457
458 if not topdown:
459 yield top, value, children
460
461 def get_domain_path(self, domid):
462 """Returns the domain's base path, as used for relative
463 requests: e.g. ``b"/local/domain/<domid>"``. If a given
464 `domid` doesn't exists the answer is undefined.
465
466 :param int domid: domain to get base path for.
467 """
468 return self.execute_command(Op.GET_DOMAIN_PATH,
469 str(domid).encode() + NUL)
470
471 def is_domain_introduced(self, domid):
472 """Returns ``True`` if ``xenstored`` is in communication with
473 the domain; that is when `INTRODUCE` for the domain has not
474 yet been followed by domain destruction or explicit
475 `RELEASE`; and ``False`` otherwise.
476
477 :param int domid: domain to check status for.
478 """
479 payload = self.execute_command(Op.IS_DOMAIN_INTRODUCED,
480 str(domid).encode() + NUL)
481 return {b"T": True, b"F": False}[payload]
482
483 def introduce_domain(self, domid, mfn, eventchn):
484 """Tells ``xenstored`` to communicate with this domain.
485
486 :param int domid: a real domain id, (``0`` is forbidden).
487 :param int mfn: address of xenstore page in `domid`.
488 :param int eventchn: an unbound event chanel in `domid`.
489 """
490 if not domid:
491 raise ValueError("domain 0 cannot be introduced.")
492
493 self.ack(Op.INTRODUCE,
494 str(domid).encode() + NUL,
495 str(mfn).encode() + NUL,
496 str(eventchn).encode() + NUL)
497
498 def release_domain(self, domid):
499 """Manually requests ``xenstored`` to disconnect from the
500 domain.
501
502 :param int domid: domain to disconnect.
503
504 .. note:: ``xenstored`` will in any case detect domain
505 destruction and disconnect by itself.
506 """
507 if not self.SU:
508 raise error(errno.EPERM)
509
510 self.ack(Op.RELEASE, str(domid).encode() + NUL)
511
512 def resume_domain(self, domid):
513 """Tells ``xenstored`` to clear its shutdown flag for a
514 domain. This ensures that a subsequent shutdown will fire the
515 appropriate watches.
516
517 :param int domid: domain to resume.
518 """
519 if not self.SU:
520 raise error(errno.EPERM)
521
522 self.ack(Op.RESUME, str(domid).encode() + NUL)
523
524 def set_target(self, domid, target):
525 """Tells ``xenstored`` that a domain is targetting another one,
526 so it should let it tinker with it. This grants domain `domid`
527 full access to paths owned by `target`. Domain `domid` also
528 inherits all permissions granted to `target` on all other
529 paths.
530
531 :param int domid: domain to set target for.
532 :param int target: target domain (yours truly, Captain).
533 """
534 if not self.SU:
535 raise error(errno.EPERM)
536
537 self.ack(Op.SET_TARGET, str(domid).encode() + NUL,
538 str(target).encode() + NUL)
539
540 def transaction(self):
541 """Starts a new transaction.
542
543 :returns int: transaction handle.
544 :raises pyxs.exceptions.PyXSError:
545 with :data:`errno.EALREADY` if this client is already in
546 a transaction.
547
548 .. warning::
549
550 Currently ``xenstored`` has a bug that after 2**32 transactions
551 it will allocate id 0 for an actual transaction.
552 """
553 if self.tx_id:
554 raise error(errno.EALREADY)
555
556 payload = self.execute_command(Op.TRANSACTION_START, NUL)
557 self.tx_id = int(payload)
558 return self.tx_id
559
560 def rollback(self):
561 """Rolls back a transaction currently in progress.
562
563 .. versionchanged: 0.4.0
564
565 In previous versions the method gracefully handled attempts to
566 end a transaction when no transaction was running. This is no
567 longer the case. The method will send the corresponding command
568 to XenStore.
569 """
570 self.ack(Op.TRANSACTION_END, b"F" + NUL)
571 self.tx_id = 0
572
573 def commit(self):
574 """Commits a transaction currently in progress.
575
576 :returns bool: ``False`` if commit failed because of the
577 intervening writes and ``True`` otherwise. In any
578 case transaction is invalidated. The caller is
579 responsible for starting a new transaction, repeating
580 all of the operations a re-committing.
581
582 .. versionchanged: 0.4.0
583
584 In previous versions the method gracefully handled attempts to
585 end a transaction when no transaction was running. This is no
586 longer the case. The method will send the corresponding command
587 to XenStore.
588 """
589 try:
590 self.ack(Op.TRANSACTION_END, b"T" + NUL)
591 except PyXSError as e:
592 if e.args[0] == errno.EAGAIN:
593 return False
594
595 raise
596 else:
597 return True
598 finally:
599 self.tx_id = 0
600
601 def monitor(self):
602 """Returns a new :class:`Monitor` instance, which is currently
603 the only way of doing PUBSUB.
604
605 The monitor shares the router with its parent client. Thus closing
606 the client invalidates the monitor. Closing the monitor, on the
607 other hand, had no effect on the router state.
608
609 .. note::
610
611 Using :meth:`monitor` over
612 :class:`~pyxs.connection.XenBusConnection` is currently
613 unsupported, because XenBus does not obey XenStore protocol
614 specification. See `xen-devel`_ discussion for details.
615
616 .. _xen-devel: \
617 http://lists.xen.org/archives/html/xen-devel/2016-02/msg03737
618 """
619 if isinstance(self.router.connection, XenBusConnection):
620 raise PyXSError("using ``Monitor`` over XenBus is not supported",
621 UserWarning)
622
623 return Monitor(copy.copy(self))
624
625
626 class Monitor(object):
627 """Monitor implements minimal PUBSUB functionality on top of XenStore.
628
629 >>> with Client() as c:
630 ... m = c.monitor():
631 ... m.watch("foo/bar")
632 ... print(next(c.wait()))
633 Event(...)
634
635 :param Client client: a reference to the parent client.
636
637 .. note::
638
639 When used as a context manager the monitor will try to unwatch
640 all watched paths.
641 """
642 def __init__(self, client):
643 self.client = client
644 self.events = queue.Queue()
645 self.unwatch_queue = set()
646
647 def __enter__(self):
648 return self
649
650 def __exit__(self, *exc_info):
651 self.close()
652
653 @property
654 def watched(self):
655 """A set of paths currently watched by the monitor."""
656 return set(wpath for wpath, token in self.unwatch_queue)
657
658 def close(self):
659 """Finalizes the monitor by unwatching all watched paths."""
660 for wpath, token in list(self.unwatch_queue):
661 self.unwatch(wpath, token)
662
663 def watch(self, wpath, token):
664 """Adds a watch.
665
666 Any alteration to the watched path generates an event. This
667 includes path creation, removal, contents change or permission
668 change. An event can also be triggered spuriously.
669
670 Changes made in transactions cause an event only if and when
671 committed.
672
673 :param bytes wpath: path to watch.
674 :param bytes token: watch token, returned in watch notification.
675 """
676 check_watch_path(wpath)
677 self.client.router.subscribe(token, self)
678 self.client.ack(Op.WATCH, wpath + NUL, token + NUL)
679 self.unwatch_queue.add((wpath, token))
680
681 def unwatch(self, wpath, token):
682 """Removes a previously added watch.
683
684 :param bytes wpath: path to unwatch.
685 :param bytes token: watch token, passed to :meth:`watch`.
686 """
687 check_watch_path(wpath)
688 self.client.ack(Op.UNWATCH, wpath + NUL, token + NUL)
689 self.client.router.unsubscribe(token, self)
690 self.unwatch_queue.discard((wpath, token))
691
692 def wait(self, unwatched=False):
693 """Yields events for all of the watched paths.
694
695 An event is a ``(path, token)`` pair, where the first element
696 is event path, i.e. the actual path that was modified, and the
697 second -- a token, passed to :meth:`watch`.
698
699 :param bool unwatched: if ``True`` :meth:`wait` might yield
700 spurious unwatched packets, otherwise
701 these are dropped. Defaults to ``False``.
702 """
703 while True:
704 with self.events.not_empty:
705 while not self.events._qsize():
706 _condition_wait(self.events.not_empty)
707
708 event = wpath, token = self.events.get_nowait()
709
710 # Check that event path or its parent is watched.
711 while wpath and (wpath, token) not in self.unwatch_queue:
712 wpath = posixpath.dirname(wpath)
713
714 if wpath or unwatched:
715 yield event