| 1 |
|
| 2 |
""" |
| 3 |
pyxs._internal |
| 4 |
~~~~~~~~~~~~~~ |
| 5 |
|
| 6 |
A place for secret stuff, not available in the public API. |
| 7 |
|
| 8 |
:copyright: (c) 2011 by Selectel. |
| 9 |
:copyright: (c) 2016 by pyxs authors and contributors, see AUTHORS |
| 10 |
for more details. |
| 11 |
:license: LGPL, see LICENSE for more details. |
| 12 |
""" |
| 13 |
|
| 14 |
from __future__ import absolute_import |
| 15 |
|
| 16 |
__all__ = ["NUL", "Event", "Op", "Packet", "next_rq_id"] |
| 17 |
|
| 18 |
import struct |
| 19 |
import sys |
| 20 |
from collections import namedtuple |
| 21 |
|
| 22 |
from .exceptions import InvalidOperation, InvalidPayload |
| 23 |
|
| 24 |
|
| 25 |
NUL = b"\x00" |
| 26 |
|
| 27 |
|
| 28 |
Operations = Op = namedtuple("Operations", [ |
| 29 |
"DEBUG", |
| 30 |
"DIRECTORY", |
| 31 |
"READ", |
| 32 |
"GET_PERMS", |
| 33 |
"WATCH", |
| 34 |
"UNWATCH", |
| 35 |
"TRANSACTION_START", |
| 36 |
"TRANSACTION_END", |
| 37 |
"INTRODUCE", |
| 38 |
"RELEASE", |
| 39 |
"GET_DOMAIN_PATH", |
| 40 |
"WRITE", |
| 41 |
"MKDIR", |
| 42 |
"RM", |
| 43 |
"SET_PERMS", |
| 44 |
"WATCH_EVENT", |
| 45 |
"ERROR", |
| 46 |
"IS_DOMAIN_INTRODUCED", |
| 47 |
"RESUME", |
| 48 |
"SET_TARGET", |
| 49 |
"RESTRICT" |
| 50 |
])(*(list(range(20)) + [128])) |
| 51 |
|
| 52 |
|
| 53 |
Event = namedtuple("Event", "path token") |
| 54 |
|
| 55 |
|
| 56 |
class Packet(namedtuple("_Packet", "op rq_id tx_id size payload")): |
| 57 |
"""A message to or from XenStore. |
| 58 |
|
| 59 |
:param int op: an item from :data:`~pyxs._internal.Op`, representing |
| 60 |
operation, performed by this packet. |
| 61 |
:param bytes payload: packet payload, should be a valid ASCII-string |
| 62 |
with characters between ``[0x20; 0x7f]``. |
| 63 |
:param int rq_id: request id -- hopefully a **unique** identifier |
| 64 |
for this packet, XenStore simply echoes this value |
| 65 |
back in response. |
| 66 |
:param int tx_id: transaction id, defaults to ``0`` , which means |
| 67 |
no transaction is running. |
| 68 |
|
| 69 |
.. versionchanged:: 0.4.0 |
| 70 |
|
| 71 |
``rq_id`` no longer defaults to ``0`` and should be provided |
| 72 |
explicitly. |
| 73 |
""" |
| 74 |
|
| 75 |
|
| 76 |
_struct = struct.Struct(b"IIII") |
| 77 |
|
| 78 |
def __new__(cls, op, payload, rq_id, tx_id=None): |
| 79 |
|
| 80 |
|
| 81 |
if len(payload) > 4096: |
| 82 |
raise InvalidPayload(payload) |
| 83 |
|
| 84 |
if op not in Op: |
| 85 |
raise InvalidOperation(op) |
| 86 |
|
| 87 |
return super(Packet, cls).__new__( |
| 88 |
cls, op, rq_id, tx_id or 0, len(payload), payload) |
| 89 |
|
| 90 |
|
| 91 |
_rq_id = -1 |
| 92 |
|
| 93 |
def next_rq_id(): |
| 94 |
"""Returns the next available request id.""" |
| 95 |
|
| 96 |
global _rq_id |
| 97 |
_rq_id += 1 |
| 98 |
_rq_id %= sys.maxsize |
| 99 |
return _rq_id |