connection.py 26.1 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
#
# Copyright (C) 2006-2015  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/>.

from functools import wraps
from time import time

from . import attributeTracker, logging
from .connector import ConnectorException, ConnectorTryAgainException, \
        ConnectorInProgressException, ConnectorConnectionRefusedException, \
        ConnectorConnectionClosedException, ConnectorDelayedConnection
from .locking import RLock
from .protocol import uuid_str, Errors, \
        PacketMalformedError, Packets, ParserState
from .util import ReadBuffer

CRITICAL_TIMEOUT = 30

class ConnectionClosed(Exception):
    pass

def not_closed(func):
    def decorator(self, *args, **kw):
        if self.connector is None:
            raise ConnectorConnectionClosedException
        return func(self, *args, **kw)
    return wraps(func)(decorator)


class HandlerSwitcher(object):
    _next_timeout = None
    _next_timeout_msg_id = None
    _next_on_timeout = None

    def __init__(self, handler):
        # pending handlers and related requests
        self._pending = []
        self._is_handling = False
        self.setHandler(handler)

    def clear(self):
        self.__init__(self.getLastHandler())
        try:
            del (self._next_timeout,
                 self._next_timeout_msg_id,
                 self._next_on_timeout)
        except AttributeError:
            pass

    def isPending(self):
        return bool(self._pending[0][0])

    def cancelRequests(self, conn, message):
        if self.isPending():
            p = Errors.ProtocolError(message)
            while True:
                request_dict, handler = self._pending[0]
                while request_dict:
                    msg_id, request = request_dict.popitem()
                    p.setId(msg_id)
                    handler.packetReceived(conn, p, request[3])
                if len(self._pending) == 1:
                    break
                del self._pending[0]

    def getHandler(self):
        return self._pending[0][1]

    def getLastHandler(self):
        """ Return the last (may be unapplied) handler registered """
        return self._pending[-1][1]

    def emit(self, request, timeout, on_timeout, kw={}):
        # register the request in the current handler
        _pending = self._pending
        if self._is_handling:
            # If this is called while handling a packet, the response is to
            # be excpected for the current handler...
            (request_dict, _) = _pending[0]
        else:
            # ...otherwise, queue for the latest handler
            assert len(_pending) == 1 or _pending[0][0]
            (request_dict, _) = _pending[-1]
        msg_id = request.getId()
        answer_class = request.getAnswerClass()
        assert answer_class is not None, "Not a request"
        assert msg_id not in request_dict, "Packet id already expected"
        next_timeout = self._next_timeout
        if next_timeout is None or timeout < next_timeout:
            self._next_timeout = timeout
            self._next_timeout_msg_id = msg_id
            self._next_on_timeout = on_timeout
        request_dict[msg_id] = answer_class, timeout, on_timeout, kw

    def getNextTimeout(self):
        return self._next_timeout

    def timeout(self, connection):
        msg_id = self._next_timeout_msg_id
        if self._next_on_timeout is not None:
            self._next_on_timeout(connection, msg_id)
            if self._next_timeout_msg_id != msg_id:
                # on_timeout sent a packet with a smaller timeout
                # so keep the connection open
                return
        # Notify that a timeout occured
        return msg_id

    def handle(self, connection, packet):
        assert not self._is_handling
        self._is_handling = True
        try:
            self._handle(connection, packet)
        finally:
            self._is_handling = False

    def _handle(self, connection, packet):
        assert len(self._pending) == 1 or self._pending[0][0]
        logging.packet(connection, packet, False)
        if connection.isClosed() and packet.ignoreOnClosedConnection():
            logging.debug('Ignoring packet %r on closed connection %r',
                packet, connection)
            return
        msg_id = packet.getId()
        (request_dict, handler) = self._pending[0]
        # notifications are not expected
        if not packet.isResponse():
            handler.packetReceived(connection, packet)
            return
        # checkout the expected answer class
        try:
            klass, _, _, kw = request_dict.pop(msg_id)
        except KeyError:
            klass = None
            kw = {}
        if klass and isinstance(packet, klass) or packet.isError():
            handler.packetReceived(connection, packet, kw)
        else:
            logging.error('Unexpected answer %r in %r', packet, connection)
            if not connection.isClosed():
                notification = Packets.Notify('Unexpected answer: %r' % packet)
                connection.notify(notification)
                connection.abort()
            # handler.peerBroken(connection)
        # apply a pending handler if no more answers are pending
        while len(self._pending) > 1 and not self._pending[0][0]:
            del self._pending[0]
            logging.debug('Apply handler %r on %r', self._pending[0][1],
                    connection)
        if msg_id == self._next_timeout_msg_id:
            self._updateNextTimeout()

    def _updateNextTimeout(self):
        # Find next timeout and its msg_id
        next_timeout = None
        for pending in self._pending:
            for msg_id, (_, timeout, on_timeout, _) in pending[0].iteritems():
                if not next_timeout or timeout < next_timeout[0]:
                    next_timeout = timeout, msg_id, on_timeout
        self._next_timeout, self._next_timeout_msg_id, self._next_on_timeout = \
            next_timeout or (None, None, None)

    def setHandler(self, handler):
        can_apply = len(self._pending) == 1 and not self._pending[0][0]
        if can_apply:
            # nothing is pending, change immediately
            self._pending[0][1] = handler
        else:
            # put the next handler in queue
            self._pending.append([{}, handler])
        return can_apply


class BaseConnection(object):
    """A base connection

    About timeouts:

        Timeout are mainly per-connection instead of per-packet.
        The idea is that most of time, packets are received and processed
        sequentially, so if it takes a long for a peer to process a packet,
        following packets would just be enqueued.
        What really matters is that the peer makes progress in its work.
        As long as we receive an answer, we consider it's still alive and
        it may just have started to process the following request. So we reset
        timeouts.
        There is anyway nothing more we could do, because processing of a packet
        may be delayed in a very unpredictable way depending of previously
        received packets on peer side.
        Even ourself may be slow to receive a packet. We must not timeout for
        an answer that is already in our incoming buffer (read_buf or _queue).
        Timeouts in HandlerSwitcher are only there to prioritize some packets.
    """

    from .connector import SocketConnector as ConnectorClass
    KEEP_ALIVE = 60

    def __init__(self, event_manager, handler, connector, addr=None):
        assert connector is not None, "Need a low-level connector"
        self.em = event_manager
        self.connector = connector
        self.addr = addr
        self._handlers = HandlerSwitcher(handler)

    # XXX: do not use getHandler
    getHandler      = property(lambda self: self._handlers.getHandler)
    getLastHandler  = property(lambda self: self._handlers.getLastHandler)
    isPending       = property(lambda self: self._handlers.isPending)

    def cancelRequests(self, *args, **kw):
        return self._handlers.cancelRequests(self, *args, **kw)

    def getTimeout(self):
        pass

    def lockWrapper(self, func):
        return func

    def getConnector(self):
        return self.connector

    def getAddress(self):
        return self.addr

    def readable(self):
        raise NotImplementedError

    def writable(self):
        raise NotImplementedError

    def close(self):
        """Close the connection."""
        if self.connector is not None:
            self.em.unregister(self)
            self.connector.close()
            self.connector = None
            self.aborted = False

    def _getReprInfo(self):
        r = [
            ('uuid', uuid_str(self.getUUID())),
            ('address', '%s:%u' % self.addr if self.addr else '?'),
            ('handler', self.getHandler()),
        ]
        connector = self.connector
        if connector is None:
            return r, ['closed']
        r.append(('fd', connector.getDescriptor()))
        return r, ['aborted'] if self.isAborted() else []

    def __repr__(self):
        r, flags = self._getReprInfo()
        r = map('%s=%s'.__mod__, r)
        r += flags
        return '<%s(%s) at %x>' % (
            self.__class__.__name__,
            ', '.join(r),
            id(self),
        )

    __del__ = close

    def setHandler(self, handler):
        if self._handlers.setHandler(handler):
            logging.debug('Set handler %r on %r', handler, self)
        else:
            logging.debug('Delay handler %r on %r', handler, self)

    def getUUID(self):
        return None

    def isClosed(self):
        return self.connector is None or self.isAborted()

    def isAborted(self):
        return False

    def isListening(self):
        return False

    def isServer(self):
        return False

    def isClient(self):
        return False

    def hasPendingMessages(self):
        return False

    def whoSetConnector(self):
        """
          Debugging method: call this method to know who set the current
          connector value.
        """
        return attributeTracker.whoSet(self, 'connector')

    def idle(self):
        pass


attributeTracker.track(BaseConnection)

class ListeningConnection(BaseConnection):
    """A listen connection."""

    def __init__(self, event_manager, handler, addr):
        logging.debug('listening to %s:%d', *addr)
        connector = self.ConnectorClass(addr)
        BaseConnection.__init__(self, event_manager, handler, connector, addr)
        connector.makeListeningConnection()
        event_manager.register(self)

    def readable(self):
        try:
            connector, addr = self.connector.accept()
            logging.debug('accepted a connection from %s:%d', *addr)
            handler = self.getHandler()
            new_conn = ServerConnection(self.em, handler, connector, addr)
            handler.connectionAccepted(new_conn)
        except ConnectorTryAgainException:
            pass

    def getAddress(self):
        return self.connector.getAddress()

    def isListening(self):
        return True


class Connection(BaseConnection):
    """A connection."""

    # XXX: rename isPending, hasPendingMessages & pending methods

    connecting = False
    client = False
    server = False
    peer_id = None
    _next_timeout = None
    _timeout = 0

    def __init__(self, event_manager, *args, **kw):
        BaseConnection.__init__(self, event_manager, *args, **kw)
        self.read_buf = ReadBuffer()
        self.write_buf = []
        self.cur_id = 0
        self.aborted = False
        self.uuid = None
        self._queue = []
        self._on_close = None
        self._parser_state = ParserState()

    def _getReprInfo(self):
        r, flags = super(Connection, self)._getReprInfo()
        if self._queue:
            r.append(('len(queue)', len(self._queue)))
        if self._on_close is not None:
            r.append(('on_close', getattr(self._on_close, '__name__', '?')))
        flags.extend(x for x in ('aborted', 'connecting', 'client', 'server')
                       if getattr(self, x))
        return r, flags

    def setOnClose(self, callback):
        self._on_close = callback

    def isClient(self):
        return self.client

    def isServer(self):
        return self.server

    def asClient(self):
        try:
            del self.idle
            assert self.client
        except AttributeError:
            self.client = True

    def asServer(self):
        self.server = True

    def _closeClient(self):
        if self.server:
            del self.idle
            self.client = False
            self.notify(Packets.CloseClient())
        else:
            self.close()

    def closeClient(self):
        if self.connector is not None and self.client:
            self.idle = self._closeClient

    def isAborted(self):
        return self.aborted

    def getUUID(self):
        return self.uuid

    def setUUID(self, uuid):
        self.uuid = uuid

    def setPeerId(self, peer_id):
        assert peer_id is not None
        self.peer_id = peer_id

    def getPeerId(self):
        return self.peer_id

    def _getNextId(self):
        next_id = self.cur_id
        self.cur_id = (next_id + 1) & 0xffffffff
        return next_id

    def updateTimeout(self, t=None):
        if not self._queue:
            if not t:
                t = self._next_timeout - self._timeout
            self._timeout = self._handlers.getNextTimeout() or self.KEEP_ALIVE
            self._next_timeout = t + self._timeout

    def getTimeout(self):
        if not self._queue:
            return self._next_timeout

    def onTimeout(self):
        handlers = self._handlers
        if handlers.isPending():
            msg_id = handlers.timeout(self)
            if msg_id is None:
                self._next_timeout = time() + self._timeout
            else:
                logging.info('timeout for #0x%08x with %r', msg_id, self)
                self.close()
        else:
            self.idle()

    def abort(self):
        """Abort dealing with this connection."""
        logging.debug('aborting a connector for %r', self)
        self.aborted = True
        assert self.write_buf
        if self._on_close is not None:
            self._on_close()
            self._on_close = None

    def writable(self):
        """Called when self is writable."""
        self._send()
        if not self.write_buf and self.connector is not None:
            if self.aborted:
                self.close()
            else:
                self.em.removeWriter(self)

    def readable(self):
        """Called when self is readable."""
        self._recv()
        self._analyse()
        if self.aborted:
            self.em.removeReader(self)
        return not not self._queue

    def _analyse(self):
        """Analyse received data."""
        try:
            while True:
                packet = Packets.parse(self.read_buf, self._parser_state)
                if packet is None:
                    break
                self._queue.append(packet)
        except PacketMalformedError, e:
            logging.error('malformed packet from %r: %s', self, e)
            self._closure()

    def hasPendingMessages(self):
        """
          Returns True if there are messages queued and awaiting processing.
        """
        return not not self._queue

    def process(self):
        """
          Process a pending packet.
        """
        # check out packet and process it with current handler
        self._handlers.handle(self, self._queue.pop(0))
        self.updateTimeout()

    def pending(self):
        return self.connector is not None and self.write_buf

    @property
    def setReconnectionNoDelay(self):
        return self.connector.setReconnectionNoDelay

    def close(self):
        if self.connector is None:
            assert self._on_close is None
            assert not self.read_buf
            assert not self.write_buf
            assert not self.isPending()
            return
        # process the network events with the last registered handler to
        # solve issues where a node is lost with pending handlers and
        # create unexpected side effects.
        handler = self._handlers.getLastHandler()
        super(Connection, self).close()
        if self._on_close is not None:
            self._on_close()
            self._on_close = None
        del self.write_buf[:]
        self.read_buf.clear()
        try:
            if self.connecting:
                handler.connectionFailed(self)
                self.connecting = False
            else:
                handler.connectionClosed(self)
        finally:
            self._handlers.clear()

    def _closure(self):
        assert self.connector is not None, self.whoSetConnector()
        while self._queue:
            self._handlers.handle(self, self._queue.pop(0))
        self.close()

    def _recv(self):
        """Receive data from a connector."""
        try:
            data = self.connector.receive()
        except ConnectorTryAgainException:
            pass
        except ConnectorConnectionRefusedException:
            assert self.connecting
            self._closure()
        except ConnectorConnectionClosedException:
            # connection resetted by peer, according to the man, this error
            # should not occurs but it seems it's false
            logging.debug('Connection reset by peer: %r', self.connector)
            self._closure()
        except:
            logging.debug('Unknown connection error: %r', self.connector)
            self._closure()
            # unhandled connector exception
            raise
        else:
            if not data:
                logging.debug('Connection %r closed in recv', self.connector)
                self._closure()
                return
            # last known remote activity
            self._next_timeout = time() + self._timeout
            self.read_buf.append(data)

    def _send(self):
        """Send data to a connector."""
        if not self.write_buf:
            return
        msg = ''.join(self.write_buf)
        try:
            n = self.connector.send(msg)
        except ConnectorTryAgainException:
            pass
        except ConnectorConnectionClosedException:
            # connection resetted by peer
            logging.debug('Connection reset by peer: %r', self.connector)
            self._closure()
        except:
            logging.debug('Unknown connection error: %r', self.connector)
            # unhandled connector exception
            self._closure()
            raise
        else:
            if not n:
                logging.debug('Connection %r closed in send', self.connector)
                self._closure()
                return
            if n == len(msg):
                del self.write_buf[:]
            else:
                self.write_buf = [msg[n:]]

    def _addPacket(self, packet):
        """Add a packet into the write buffer."""
        if self.connector is None:
            return

        was_empty = not self.write_buf

        self.write_buf.extend(packet.encode())

        if was_empty:
            # enable polling for writing.
            self.em.addWriter(self)
        logging.packet(self, packet, True)

    @not_closed
    def notify(self, packet):
        """ Then a packet with a new ID """
        msg_id = self._getNextId()
        packet.setId(msg_id)
        self._addPacket(packet)
        return msg_id

    @not_closed
    def ask(self, packet, timeout=CRITICAL_TIMEOUT, on_timeout=None, **kw):
        """
        Send a packet with a new ID and register the expectation of an answer
        """
        msg_id = self._getNextId()
        packet.setId(msg_id)
        self._addPacket(packet)
        handlers = self._handlers
        t = None if handlers.isPending() else time()
        handlers.emit(packet, timeout, on_timeout, kw)
        if not self._queue:
            next_timeout = self._next_timeout
            self.updateTimeout(t)
            if self._next_timeout < next_timeout:
                self.em.wakeup()
        return msg_id

    @not_closed
    def answer(self, packet, msg_id=None):
        """ Answer to a packet by re-using its ID for the packet answer """
        if msg_id is None:
            msg_id = self.getPeerId()
        packet.setId(msg_id)
        assert packet.isResponse(), packet
        self._addPacket(packet)

    def idle(self):
        self.ask(Packets.Ping())


class ClientConnection(Connection):
    """A connection from this node to a remote node."""

    connecting = True
    client = True

    def __init__(self, event_manager, handler, node):
        addr = node.getAddress()
        connector = self.ConnectorClass(addr)
        Connection.__init__(self, event_manager, handler, connector, addr)
        node.setConnection(self)
        handler.connectionStarted(self)
        self._connect()

    def convertToMT(self, dispatcher):
        assert self.__class__ is ClientConnection, self
        self.__class__ = MTClientConnection
        self._initMT(dispatcher)

    def _connect(self):
        try:
            self.connector.makeClientConnection()
        except ConnectorInProgressException:
            self.em.register(self)
            self.em.addWriter(self)
        except ConnectorDelayedConnection, c:
            connect_limit, = c.args
            self.getTimeout = lambda: connect_limit
            self.onTimeout = self._delayedConnect
            self.em.register(self, timeout_only=True)
            # Fake _addPacket so that if does not
            # try to reenable polling for writing.
            self.write_buf.insert(0, '')
        except ConnectorConnectionRefusedException:
            self._closure()
        except ConnectorException:
            # unhandled connector exception
            self._closure()
            raise
        else:
            self.em.register(self)
            if self.write_buf:
                self.em.addWriter(self)
            self._connectionCompleted()

    def _delayedConnect(self):
        del self.getTimeout, self.onTimeout, self.write_buf[0]
        self._connect()

    def writable(self):
        """Called when self is writable."""
        if self.connector.getError():
            self._closure()
        else:
            self._connectionCompleted()
            self.writable()

    def _connectionCompleted(self):
        self.writable = self.lockWrapper(super(ClientConnection, self).writable)
        self.connecting = False
        self.updateTimeout(time())
        self.getHandler().connectionCompleted(self)


class ServerConnection(Connection):
    """A connection from a remote node to this node."""

    # Both server and client must check the connection, in case:
    # - the remote crashed brutally (i.e. without closing TCP connections)
    # - or packets sent by the remote are dropped (network failure)
    # Use different timeout so that in normal condition, server never has to
    # ping the client. Otherwise, it would do it about half of the time.
    KEEP_ALIVE = Connection.KEEP_ALIVE + 5

    server = True

    def __init__(self, *args, **kw):
        Connection.__init__(self, *args, **kw)
        self.em.register(self)
        self.updateTimeout(time())


class MTConnectionType(type):

    def __init__(cls, *args):
        if __debug__:
            for name in 'answer',:
                setattr(cls, name, cls.lockCheckWrapper(name))
        for name in ('_delayedConnect', 'close', 'notify', 'onTimeout',
                     'process', 'readable', 'writable'):
            setattr(cls, name, cls.__class__.lockWrapper(cls, name))

    def lockCheckWrapper(cls, name):
        def wrapper(self, *args, **kw):
            # XXX: Unfortunately, RLock does not has any public method
            #      to test whether we own the lock or not.
            assert self.lock._is_owned(), (self, args, kw)
            return getattr(super(cls, self), name)(*args, **kw)
        return wraps(getattr(cls, name).im_func)(wrapper)

    def lockWrapper(cls, name):
        def wrapper(self, *args, **kw):
            with self.lock:
                return getattr(super(cls, self), name)(*args, **kw)
        return wraps(getattr(cls, name).im_func)(wrapper)


class MTClientConnection(ClientConnection):
    """A Multithread-safe version of ClientConnection."""

    __metaclass__ = MTConnectionType

    def lockWrapper(self, func):
        lock = self.lock
        def wrapper(*args, **kw):
            with lock:
                return func(*args, **kw)
        return wrapper

    def __init__(self, *args, **kwargs):
        self._initMT(kwargs.pop('dispatcher'))
        with self.lock:
            super(MTClientConnection, self).__init__(*args, **kwargs)

    def _initMT(self, dispatcher):
        self.lock = RLock()
        self.dispatcher = dispatcher

    def ask(self, packet, timeout=CRITICAL_TIMEOUT, on_timeout=None,
            queue=None, **kw):
        with self.lock:
            if self.isClosed():
                raise ConnectionClosed
            # XXX: Here, we duplicate Connection.ask because we need to call
            # self.dispatcher.register after setId is called and before
            # _addPacket is called.
            msg_id = self._getNextId()
            packet.setId(msg_id)
            if queue is None:
                if type(packet) is not Packets.Ping:
                    raise TypeError, 'Only Ping packet can be asked ' \
                        'without a queue, got a %r.' % (packet, )
            else:
                self.dispatcher.register(self, msg_id, queue)
            self._addPacket(packet)
            handlers = self._handlers
            t = None if handlers.isPending() else time()
            handlers.emit(packet, timeout, on_timeout, kw)
            if not self._queue:
                next_timeout = self._next_timeout
                self.updateTimeout(t)
                if self._next_timeout < next_timeout:
                    self.em.wakeup()
            return msg_id