protocol.py 26 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858

# Copyright (C) 2006-2019  Nexedi SA
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import struct, threading
from functools import partial

# The protocol version must be increased whenever upgrading a node may require
# to upgrade other nodes. It is encoded as a 4-bytes big-endian integer and
# the high order byte 0 is different from TLS Handshake (0x16).
PROTOCOL_VERSION = 6
ENCODED_VERSION = struct.pack('!L', PROTOCOL_VERSION)

RESPONSE_MASK = 0x8000

# Avoid some memory errors on corrupted data.
# Before we use msgpack, we limited the size of a whole packet. That's not
# possible anymore because the size is not known in advance. Packets bigger
# than the buffer size are possible (e.g. a huge list of small items) and for
# that we could compare the stream position (Unpacker.tell); it's not worth it.
UNPACK_BUFFER_SIZE = 0x4000000

@apply
def Unpacker():
    global registerExtType, packb
    from msgpack import ExtType, unpackb, Packer, Unpacker
    ext_type_dict = []
    kw = dict(use_bin_type=True)
    pack_ext = Packer(**kw).pack

    def registerExtType(getstate, make):
        code = len(ext_type_dict)
        ext_type_dict.append(lambda data: make(unpackb(data, use_list=False)))
        return lambda obj: ExtType(code, pack_ext(getstate(obj)))

    iterable_types = set, tuple
    def default(obj):
        try:
            pack = obj._pack
        except AttributeError:
            assert type(obj) in iterable_types, type(obj)
            return list(obj)
        return pack()
    lock = threading.Lock()
    pack = Packer(default, strict_types=True, **kw).pack
    def packb(obj):
        with lock: # in case that 'default' is called
            return pack(obj)

    return partial(Unpacker, use_list=False, max_buffer_size=UNPACK_BUFFER_SIZE,
        ext_hook=lambda code, data: ext_type_dict[code](data))

class Enum(tuple):

    class Item(int):
        __slots__ = '_name', '_enum', '_pack'
        def __str__(self):
            return self._name
        def __repr__(self):
            return "<EnumItem %s (%d)>" % (self._name, self)
        def __eq__(self, other):
            if type(other) is self.__class__:
                assert other._enum is self._enum
                return other is self
            return other == int(self)

    def __new__(cls, func):
        names = func.func_code.co_names
        self = tuple.__new__(cls, map(cls.Item, xrange(len(names))))
        self._name = func.__name__
        pack = registerExtType(int, self.__getitem__)
        for item, name in zip(self, names):
            setattr(self, name, item)
            item._name = name
            item._enum = self
            item._pack = (lambda x: lambda: x)(pack(item))
        return self

    def __repr__(self):
        return "<Enum %s>" % self._name

# The order of extension type is important.
# Enum types first, sorted alphabetically.

@Enum
def CellStates():
    # Write-only cell. Last transactions are missing because storage is/was down
    # for a while, or because it is new for the partition. It usually becomes
    # UP_TO_DATE when replication is done.
    OUT_OF_DATE
    # Normal state: cell is writable/readable, and it isn't planned to drop it.
    UP_TO_DATE
    # Same as UP_TO_DATE, except that it will be discarded as soon as another
    # node finishes to replicate it. It means a partition is moved from 1 node
    # to another. It is also discarded immediately if out-of-date.
    FEEDING
    # A check revealed that data differs from other replicas. Cell is neither
    # readable nor writable.
    CORRUPTED
    # Not really a state: only used in network packets to tell storages to drop
    # partitions.
    DISCARDED

@Enum
def ClusterStates():
    # The cluster is initially in the RECOVERING state, and it goes back to
    # this state whenever the partition table becomes non-operational again.
    # An election of the primary master always happens, in case of a network
    # cut between a primary master and all other nodes. The primary master:
    # - first recovers its own data by reading it from storage nodes;
    # - waits for the partition table be operational;
    # - automatically switch to VERIFYING if the cluster can be safely started.
    RECOVERING
    # Transient state, used to:
    # - replay the transaction log, in case of unclean shutdown;
    # - and actually truncate the DB if the user asked to do so.
    # Then, the cluster either goes to RUNNING or STARTING_BACKUP state.
    VERIFYING
    # Normal operation. The DB is read-writable by clients.
    RUNNING
    # Transient state to shutdown the whole cluster.
    STOPPING
    # Transient state, during which the master (re)connect to the upstream
    # master.
    STARTING_BACKUP
    # Backup operation. The master is notified of new transactions thanks to
    # invalidations and orders storage nodes to fetch them from upstream.
    # Because cells are synchronized independently, the DB is often
    # inconsistent.
    BACKINGUP
    # Transient state, when the user decides to go back to RUNNING state.
    # The master stays in this state until the DB is consistent again.
    # In case of failure, the cluster will go back to backup mode.
    STOPPING_BACKUP

@Enum
def ErrorCodes():
    ACK
    NOT_READY
    OID_NOT_FOUND
    TID_NOT_FOUND
    OID_DOES_NOT_EXIST
    PROTOCOL_ERROR
    REPLICATION_ERROR
    CHECKING_ERROR
    BACKEND_NOT_IMPLEMENTED
    NON_READABLE_CELL
    READ_ONLY_ACCESS
    INCOMPLETE_TRANSACTION

@Enum
def NodeStates():
    UNKNOWN
    DOWN
    RUNNING
    PENDING

@Enum
def NodeTypes():
    MASTER
    STORAGE
    CLIENT
    ADMIN

# used for logging
node_state_prefix_dict = {
    NodeStates.RUNNING: 'R',
    NodeStates.DOWN: 'D',
    NodeStates.UNKNOWN: 'U',
    NodeStates.PENDING: 'P',
}

# used for logging
cell_state_prefix_dict = {
    CellStates.UP_TO_DATE: 'U',
    CellStates.OUT_OF_DATE: 'O',
    CellStates.FEEDING: 'F',
    CellStates.DISCARDED: 'D',
    CellStates.CORRUPTED: 'C',
}

# Other constants.
INVALID_TID = \
INVALID_OID = '\xff' * 8
INVALID_PARTITION = 0xffffffff
ZERO_HASH = '\0' * 20
ZERO_TID = \
ZERO_OID = '\0' * 8
MAX_TID = '\x7f' + '\xff' * 7 # SQLite does not accept numbers above 2^63-1

# High-order byte:
# 7 6 5 4 3 2 1 0
# | | | | +-+-+-+-- reserved (0)
# | +-+-+---------- node type
# +---------------- temporary if negative
# UUID namespaces are required to prevent conflicts when the master generate
# new uuid before it knows uuid of existing storage nodes. So only the high
# order bit is really important and the 31 other bits could be random.
# Extra namespace information and non-randomness of 3 LOB help to read logs.
UUID_NAMESPACES = {
    NodeTypes.STORAGE: 0x00,
    NodeTypes.MASTER: -0x10,
    NodeTypes.CLIENT: -0x20,
    NodeTypes.ADMIN: -0x30,
}
uuid_str = (lambda ns: lambda uuid:
    ns[uuid >> 24] + str(uuid & 0xffffff) if uuid else str(uuid)
    )({v: str(k)[0] for k, v in UUID_NAMESPACES.iteritems()})

class ProtocolError(Exception):
    """ Base class for protocol errors, close the connection """

class PacketMalformedError(ProtocolError):
    """Close the connection"""

class UnexpectedPacketError(ProtocolError):
    """Close the connection"""

class NotReadyError(ProtocolError):
    """ Just close the connection """

class BackendNotImplemented(Exception):
    """ Method not implemented by backend storage """

class NonReadableCell(Exception):
    """Read-access to a cell that is actually non-readable

    This happens in case of race condition at processing partition table
    updates: client's PT is older or newer than storage's. The latter case is
    possible because the master must validate any end of replication, which
    means that the storage node can't anticipate the PT update (concurrently,
    there may be a first tweaks that moves the replicated cell to another node,
    and a second one that moves it back).

    On such event, the client must retry, preferably another cell.
    """


class Packet(object):
    """
        Base class for any packet definition.
    """
    _ignore_when_closed = False
    _request = None
    _answer = None
    _code = None
    _id = None
    nodelay = True
    poll_thread = False

    def __init__(self, *args):
        assert self._code is not None, "Packet class not registered"
        self._args = args

    def setId(self, value):
        self._id = value

    def getId(self):
        assert self._id is not None, "No identifier applied on the packet"
        return self._id

    def encode(self, packb=packb):
        """ Encode a packet as a string to send it over the network """
        r = packb((self._id, self._code, self._args))
        self.size = len(r)
        return r

    def __repr__(self):
        return '%s[%r]' % (self.__class__.__name__, self._id)

    def __eq__(self, other):
        """ Compare packets with their code instead of content """
        if other is None:
            return False
        assert isinstance(other, Packet)
        return self._code == other._code

    def isError(self):
        return self._code == RESPONSE_MASK

    def isResponse(self):
        return self._code & RESPONSE_MASK

    def getAnswerClass(self):
        return self._answer

    def ignoreOnClosedConnection(self):
        """
        Tells if this packet must be ignored when its connection is closed
        when it is handled.
        """
        return self._ignore_when_closed


class PacketRegistryFactory(dict):

    def __call__(self, name, base, d):
        for k, v in d.items():
            if isinstance(v, type) and issubclass(v, Packet):
                v.__name__ = k
                v.handler_method_name = k[0].lower() + k[1:]
        # this builds a "singleton"
        return type('PacketRegistry', base, d)(self)

    def register(self, doc, ignore_when_closed=None, request=False, error=False,
                       _base=(Packet,), **kw):
        """ Register a packet in the packet registry """
        code = len(self)
        if doc is None:
            self[code] = None
            return # None registered only to skip a code number (for compatibility)
        if error and not request:
            assert not code
            code = RESPONSE_MASK
        kw.update(__doc__=doc, _code=code)
        packet = type('', _base, kw)
        # register the request
        self[code] = packet
        if request:
            if ignore_when_closed is None:
                # By default, on a closed connection:
                # - request: ignore
                # - answer: keep
                # - notification: keep
                packet._ignore_when_closed = True
            else:
                assert ignore_when_closed is False
            if error:
                packet._answer = self[RESPONSE_MASK]
            else:
                # build a class for the answer
                code |= RESPONSE_MASK
                kw['_code'] = code
                answer = packet._answer = self[code] = type('', _base, kw)
                return packet, answer
        else:
            assert ignore_when_closed is None
        return packet


class Packets(dict):
    """
    Packet registry that checks packet code uniqueness and provides an index
    """
    __metaclass__ = PacketRegistryFactory()
    notify = __metaclass__.register
    request = partial(notify, request=True)

    Error = notify("""
        Error is a special type of message, because this can be sent against
        any other message, even if such a message does not expect a reply
        usually.

        :nodes: * -> *
        """, error=True)

    RequestIdentification, AcceptIdentification = request("""
        Request a node identification. This must be the first packet for any
        connection.

        :nodes: * -> *
        """, poll_thread=True)

    Ping, Pong = request("""
        Empty request used as network barrier.

        :nodes: * -> *
        """)

    CloseClient = notify("""
        Tell peer that it can close the connection if it has finished with us.

        :nodes: * -> *
        """)

    AskPrimary, AnswerPrimary = request("""
        Ask node identier of the current primary master.

        :nodes: ctl -> A
        """)

    NotPrimaryMaster = notify("""
        Notify peer that I'm not the primary master. Attach any extra
        information to help the peer joining the cluster.

        :nodes: SM -> *
        """)

    NotifyNodeInformation = notify("""
        Notify information about one or more nodes.

        :nodes: M -> *
        """)

    AskRecovery, AnswerRecovery = request("""
        Ask storage nodes data needed by master to recover.
        Reused by `neoctl print ids`.

        :nodes: M -> S; ctl -> A -> M
        """)

    AskLastIDs, AnswerLastIDs = request("""
        Ask the last OID/TID so that a master can initialize its
        TransactionManager. Reused by `neoctl print ids`.

        :nodes: M -> S; ctl -> A -> M
        """)

    AskPartitionTable, AnswerPartitionTable = request("""
        Ask storage node the remaining data needed by master to recover.
        This is also how the clients get the full partition table on connection.

        :nodes: M -> S; C -> M
        """)

    SendPartitionTable = notify("""
        Send the full partition table to admin/storage nodes on connection.

        :nodes: M -> A, S
        """)

    NotifyPartitionChanges = notify("""
        Notify about changes in the partition table.

        :nodes: M -> *
        """)

    StartOperation = notify("""
        Tell a storage node to start operation. Before this message,
        it must only communicate with the primary master.

        :nodes: M -> S
        """)

    StopOperation = notify("""
        Notify that the cluster is not operational anymore.
        Any operation between nodes must be aborted.

        :nodes: M -> S, C
        """)

    AskUnfinishedTransactions, AnswerUnfinishedTransactions = request("""
        Ask unfinished transactions, which will be replicated
        when they're finished.

        :nodes: S -> M
        """)

    AskLockedTransactions, AnswerLockedTransactions = request("""
        Ask locked transactions to replay committed transactions
        that haven't been unlocked.

        :nodes: M -> S
        """)

    AskFinalTID, AnswerFinalTID = request("""
        Return final tid if ttid has been committed, to recover from certain
        failures during tpc_finish.

        :nodes: M -> S; C -> M, S
        """)

    ValidateTransaction = notify("""
        Do replay a committed transaction that was not unlocked.

        :nodes: M -> S
        """)

    AskBeginTransaction, AnswerBeginTransaction = request("""
        Ask to begin a new transaction. This maps to `tpc_begin`.

        :nodes: C -> M
        """)

    FailedVote = request("""
        Report storage nodes for which vote failed.
        True is returned if it's still possible to finish the transaction.

        :nodes: C -> M
        """, error=True)

    AskFinishTransaction, AnswerTransactionFinished = request("""
        Finish a transaction. Return the TID of the committed transaction.
        This maps to `tpc_finish`.

        :nodes: C -> M
        """, ignore_when_closed=False, poll_thread=True)

    AskLockInformation, AnswerInformationLocked = request("""
        Commit a transaction. The new data is read-locked.

        :nodes: M -> S
        """, ignore_when_closed=False)

    InvalidateObjects = notify("""
        Notify about a new transaction modifying objects,
        invalidating client caches.

        :nodes: M -> C
        """)

    NotifyUnlockInformation = notify("""
        Notify about a successfully committed transaction. The new data can be
        unlocked.

        :nodes: M -> S
        """)

    AskNewOIDs, AnswerNewOIDs = request("""
        Ask new OIDs to create objects.

        :nodes: C -> M
        """)

    NotifyDeadlock = notify("""
        Ask master to generate a new TTID that will be used by the client to
        solve a deadlock by rebasing the transaction on top of concurrent
        changes.

        :nodes: S -> M -> C
        """)

    AskRebaseTransaction, AnswerRebaseTransaction = request("""
        Rebase a transaction to solve a deadlock.

        :nodes: C -> S
        """)

    AskRebaseObject, AnswerRebaseObject = request("""
        Rebase an object change to solve a deadlock.

        :nodes: C -> S

        XXX: It is a request packet to simplify the implementation. For more
             efficiency, this should be turned into a notification, and the
             RebaseTransaction should answered once all objects are rebased
             (so that the client can still wait on something).
        """, data_path=(1, 0, 2, 0))

    AskStoreObject, AnswerStoreObject = request("""
        Ask to create/modify an object. This maps to `store`.

        As for IStorage, 'serial' is ZERO_TID for new objects.

        :nodes: C -> S
        """, data_path=(0, 2))

    AbortTransaction = notify("""
        Abort a transaction. This maps to `tpc_abort`.

        :nodes: C -> S; C -> M -> S
        """)

    AskStoreTransaction, AnswerStoreTransaction = request("""
        Ask to store a transaction. Implies vote.

        :nodes: C -> S
        """)

    AskVoteTransaction, AnswerVoteTransaction = request("""
        Ask to vote a transaction.

        :nodes: C -> S
        """)

    AskObject, AnswerObject = request("""
        Ask a stored object by its OID, optionally at/before a specific tid.
        This maps to `load/loadBefore/loadSerial`.

        :nodes: C -> S
        """, data_path=(1, 3))

    AskTIDs, AnswerTIDs = request("""
        Ask for TIDs between a range of offsets. The order of TIDs is
        descending, and the range is [first, last). This maps to `undoLog`.

        :nodes: C -> S
        """)

    AskTransactionInformation, AnswerTransactionInformation = request("""
        Ask for transaction metadata.

        :nodes: C -> S
        """)

    AskObjectHistory, AnswerObjectHistory = request("""
        Ask history information for a given object. The order of serials is
        descending, and the range is [first, last]. This maps to `history`.

        :nodes: C -> S
        """)

    AskPartitionList, AnswerPartitionList = request("""
        Ask information about partitions.

        :nodes: ctl -> A
        """)

    AskNodeList, AnswerNodeList = request("""
        Ask information about nodes.

        :nodes: ctl -> A
        """)

    SetNodeState = request("""
        Change the state of a node.

        :nodes: ctl -> A -> M
        """, error=True, ignore_when_closed=False)

    AddPendingNodes = request("""
        Mark given pending nodes as running, for future inclusion when tweaking
        the partition table.

        :nodes: ctl -> A -> M
        """, error=True, ignore_when_closed=False)

    TweakPartitionTable = request("""
        Ask the master to balance the partition table, optionally excluding
        specific nodes in anticipation of removing them.

        :nodes: ctl -> A -> M
        """, error=True, ignore_when_closed=False)

    SetClusterState = request("""
        Set the cluster state.

        :nodes: ctl -> A -> M
        """,  error=True, ignore_when_closed=False)

    Repair = request("""
        Ask storage nodes to repair their databases.

        :nodes: ctl -> A -> M
        """, error=True)

    NotifyRepair = notify("""
        Repair is translated to this message, asking a specific storage node to
        repair its database.

        :nodes: M -> S
        """)

    NotifyClusterInformation = notify("""
        Notify about a cluster state change.

        :nodes: M -> *
        """)

    AskClusterState, AnswerClusterState = request("""
        Ask the state of the cluster

        :nodes: ctl -> A; A -> M
        """)

    AskObjectUndoSerial, AnswerObjectUndoSerial = request("""
        Ask storage the serial where object data is when undoing given
        transaction, for a list of OIDs.

        Answer a dict mapping oids to 3-tuples:
            current_serial (TID)
                The latest serial visible to the undoing transaction.
            undo_serial (TID)
                Where undone data is (tid at which data is before given undo).
            is_current (bool)
                If current_serial's data is current on storage.

        :nodes: C -> S
        """)

    AskTIDsFrom, AnswerTIDsFrom = request("""
        Ask for length TIDs starting at min_tid. The order of TIDs is ascending.
        Used by `iterator`.

        :nodes: C -> S
        """)

    AskPack, AnswerPack = request("""
        Request a pack at given TID.

        :nodes: C -> M -> S
        """, ignore_when_closed=False)

    CheckReplicas = request("""
        Ask the cluster to search for mismatches between replicas, metadata
        only, and optionally within a specific range. Reference nodes can be
        specified.

        :nodes: ctl -> A -> M
        """, error=True)

    CheckPartition = notify("""
        Ask a storage node to compare a partition with all other nodes.
        Like for CheckReplicas, only metadata are checked, optionally within a
        specific range. A reference node can be specified.

        :nodes: M -> S
        """)

    AskCheckTIDRange, AnswerCheckTIDRange = request("""
        Ask some stats about a range of transactions.
        Used to know if there are differences between a replicating node and
        reference node.

        :nodes: S -> S
        """)

    AskCheckSerialRange, AnswerCheckSerialRange = request("""
        Ask some stats about a range of object history.
        Used to know if there are differences between a replicating node and
        reference node.

        :nodes: S -> S
        """)

    NotifyPartitionCorrupted = notify("""
        Notify that mismatches were found while check replicas for a partition.

        :nodes: S -> M
        """)

    NotifyReady = notify("""
        Notify that we're ready to serve requests.

        :nodes: S -> M
        """)

    AskLastTransaction, AnswerLastTransaction = request("""
        Ask last committed TID.

        :nodes: C -> M; ctl -> A -> M
        """, poll_thread=True)

    AskCheckCurrentSerial, AnswerCheckCurrentSerial = request("""
        Check if given serial is current for the given oid, and lock it so that
        this state is not altered until transaction ends.
        This maps to `checkCurrentSerialInTransaction`.

        :nodes: C -> S
        """)

    NotifyTransactionFinished = notify("""
        Notify that a transaction blocking a replication is now finished.

        :nodes: M -> S
        """)

    Replicate = notify("""
        Notify a storage node to replicate partitions up to given 'tid'
        and from given sources.

        args: tid, upstream_name, {partition: address}
        - upstream_name: replicate from an upstream cluster
        - address: address of the source storage node, or None if there's
                   no new data up to 'tid' for the given partition

        :nodes: M -> S
        """)

    NotifyReplicationDone = notify("""
        Notify the master node that a partition has been successfully
        replicated from a storage to another.

        :nodes: S -> M
        """)

    AskFetchTransactions, AnswerFetchTransactions = request("""
        Ask a storage node to send all transaction data we don't have,
        and reply with the list of transactions we should not have.

        :nodes: S -> S
        """)

    AskFetchObjects, AnswerFetchObjects = request("""
        Ask a storage node to send object records we don't have,
        and reply with the list of records we should not have.

        :nodes: S -> S
        """)

    AddTransaction = notify("""
        Send metadata of a transaction to a node that does not have them.

        :nodes: S -> S
        """, nodelay=False)

    AddObject = notify("""
        Send an object record to a node that does not have it.

        :nodes: S -> S
        """, nodelay=False, data_path=(0, 2))

    Truncate = request("""
        Request DB to be truncated. Also used to leave backup mode.

        :nodes: ctl -> A -> M; M -> S
        """, error=True)

    FlushLog = notify("""
        Request all nodes to flush their logs.

        :nodes: ctl -> A -> M -> *
        """)

    del notify, request


def Errors():
    registry_dict = {}
    handler_method_name_dict = {}
    Error = Packets.Error
    def register_error(code):
        return lambda self, message='': Error(code, message)
    for error in ErrorCodes:
        name = ''.join(part.capitalize() for part in str(error).split('_'))
        registry_dict[name] = register_error(int(error))
        handler_method_name_dict[int(error)] = name[0].lower() + name[1:]
    return type('ErrorRegistry', (dict,),
                registry_dict)(handler_method_name_dict)

Errors = Errors()

# Common helpers between the 'neo' module and 'neolog'.

from datetime import datetime
from operator import itemgetter

def formatNodeList(node_list, prefix='', _sort_key=itemgetter(2)):
    if node_list:
        node_list = [(
                uuid_str(uuid), str(node_type),
                ('[%s]:%s' if ':' in addr[0] else '%s:%s')
                % addr if addr else '', str(state),
                str(id_timestamp and datetime.utcfromtimestamp(id_timestamp)))
            for node_type, addr, uuid, state, id_timestamp
                in sorted(node_list, key=_sort_key)]
        t = ''.join('%%-%us | ' % max(len(x[i]) for x in node_list)
                    for i in xrange(len(node_list[0]) - 1))
        return map((prefix + t + '%s').__mod__, node_list)
    return ()

Packets.NotifyNodeInformation._neolog = staticmethod(
    lambda timestamp, node_list:
    ((timestamp,), formatNodeList(node_list, ' ! ')))

Packets.Error._neolog = staticmethod(lambda *args: ((), ("%s (%s)" % args,)))