Python/BLIP.py
author morrowa
Tue Jun 23 12:46:40 2009 -0700 (2009-06-23)
changeset 53 e9f209a24d53
parent 51 de59ce19f42e
child 54 6d1392a3e0a6
permissions -rw-r--r--
Connections opened by listeners now close correctly.
jens@11
     1
# encoding: utf-8
jens@11
     2
"""
jens@11
     3
BLIP.py
jens@11
     4
jens@11
     5
Created by Jens Alfke on 2008-06-03.
jens@13
     6
Copyright notice and BSD license at end of file.
jens@11
     7
"""
jens@11
     8
jens@11
     9
import asynchat
jens@11
    10
import asyncore
jens@11
    11
from cStringIO import StringIO
jens@11
    12
import logging
jens@11
    13
import socket
jens@11
    14
import struct
jens@11
    15
import sys
jens@11
    16
import traceback
jens@11
    17
import zlib
jens@11
    18
jens@11
    19
jens@13
    20
# Connection status enumeration:
jens@13
    21
kDisconnected = -1
jens@13
    22
kClosed  = 0
jens@13
    23
kOpening = 1
jens@13
    24
kOpen    = 2
jens@13
    25
kClosing = 3
jens@13
    26
jens@13
    27
jens@12
    28
# INTERNAL CONSTANTS -- NO TOUCHIES!
jens@12
    29
morrowa@51
    30
kFrameMagicNumber   = 0x9B34F206
jens@11
    31
kFrameHeaderFormat  = '!LLHH'
jens@11
    32
kFrameHeaderSize    = 12
jens@11
    33
jens@11
    34
kMsgFlag_TypeMask   = 0x000F
jens@11
    35
kMsgFlag_Compressed = 0x0010
jens@11
    36
kMsgFlag_Urgent     = 0x0020
jens@11
    37
kMsgFlag_NoReply    = 0x0040
jens@11
    38
kMsgFlag_MoreComing = 0x0080
morrowa@51
    39
kMsgFlag_Meta       = 0x0100
jens@11
    40
jens@11
    41
kMsgType_Request    = 0
jens@11
    42
kMsgType_Response   = 1
jens@11
    43
kMsgType_Error      = 2
jens@11
    44
morrowa@51
    45
kMsgProfile_Hi      = "Hi"
morrowa@51
    46
kMsgProfile_Bye     = "Bye"
morrowa@51
    47
jens@11
    48
jens@11
    49
log = logging.getLogger('BLIP')
jens@11
    50
log.propagate = True
jens@11
    51
jens@12
    52
jens@11
    53
class MessageException(Exception):
jens@11
    54
    pass
jens@11
    55
jens@11
    56
class ConnectionException(Exception):
jens@11
    57
    pass
jens@11
    58
jens@11
    59
jens@13
    60
### LISTENER AND CONNECTION CLASSES:
jens@13
    61
jens@13
    62
jens@11
    63
class Listener (asyncore.dispatcher):
jens@12
    64
    "BLIP listener/server class"
jens@12
    65
    
jens@13
    66
    def __init__(self, port, sslKeyFile=None, sslCertFile=None):
jens@12
    67
        "Create a listener on a port"
jens@11
    68
        asyncore.dispatcher.__init__(self)
jens@12
    69
        self.onConnected = self.onRequest = None
jens@11
    70
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
jens@11
    71
        self.bind( ('',port) )
jens@11
    72
        self.listen(5)
jens@13
    73
        self.sslKeyFile=sslKeyFile
jens@13
    74
        self.sslCertFile=sslCertFile
jens@11
    75
        log.info("Listening on port %u", port)
jens@11
    76
    
jens@11
    77
    def handle_accept( self ):
jens@13
    78
        socket,address = self.accept()
jens@13
    79
        if self.sslKeyFile:
jens@13
    80
            socket.ssl(socket,self.sslKeyFile,self.sslCertFile)
jens@13
    81
        conn = Connection(address, sock=socket, listener=self)
jens@11
    82
        conn.onRequest = self.onRequest
jens@11
    83
        if self.onConnected:
jens@11
    84
            self.onConnected(conn)
jens@11
    85
jens@13
    86
    def handle_error(self):
jens@13
    87
        (typ,val,trace) = sys.exc_info()
jens@13
    88
        log.error("Listener caught: %s %s\n%s", typ,val,traceback.format_exc())
jens@13
    89
        self.close()
jens@13
    90
    
jens@13
    91
jens@11
    92
jens@11
    93
class Connection (asynchat.async_chat):
jens@13
    94
    def __init__( self, address, sock=None, listener=None, ssl=None ):
jens@12
    95
        "Opens a connection with the given address. If a connection/socket object is provided it'll use that,"
jens@12
    96
        "otherwise it'll open a new outgoing socket."
jens@13
    97
        if sock:
jens@13
    98
            asynchat.async_chat.__init__(self,sock)
jens@11
    99
            log.info("Accepted connection from %s",address)
jens@13
   100
            self.status = kOpen
jens@11
   101
        else:
jens@13
   102
            asynchat.async_chat.__init__(self)
jens@11
   103
            log.info("Opening connection to %s",address)
jens@11
   104
            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
jens@13
   105
            self.status = kOpening
jens@13
   106
            if ssl:
jens@13
   107
                ssl(self.socket)
jens@11
   108
            self.connect(address)
jens@13
   109
        self.address = address
jens@13
   110
        self.listener = listener
morrowa@51
   111
        self.onRequest = self.onCloseRequest = self.onCloseRefused = None
jens@11
   112
        self.pendingRequests = {}
jens@11
   113
        self.pendingResponses = {}
jens@11
   114
        self.outBox = []
jens@11
   115
        self.inMessage = None
jens@13
   116
        self.inNumRequests = self.outNumRequests = 0
jens@14
   117
        self.sending = False
jens@11
   118
        self._endOfFrame()
morrowa@51
   119
        self._closeWhenPossible = False
jens@11
   120
    
jens@13
   121
    def handle_connect(self):
jens@13
   122
        log.info("Connection open!")
jens@13
   123
        self.status = kOpen
jens@13
   124
    
jens@13
   125
    def handle_error(self):
jens@13
   126
        (typ,val,trace) = sys.exc_info()
jens@13
   127
        log.error("Connection caught: %s %s\n%s", typ,val,traceback.format_exc())
jens@13
   128
        self.discard_buffers()
jens@13
   129
        self.status = kDisconnected
jens@11
   130
        self.close()
jens@11
   131
    
jens@11
   132
    
jens@11
   133
    ### SENDING:
jens@11
   134
    
jens@13
   135
    @property
morrowa@51
   136
    def isOpen(self):
jens@13
   137
        return self.status==kOpening or self.status==kOpen
jens@13
   138
    
morrowa@51
   139
    @property
morrowa@51
   140
    def canSend(self):
morrowa@51
   141
        return self.isOpen and not self._closeWhenPossible
morrowa@51
   142
    
jens@13
   143
    def _sendMessage(self, msg):
morrowa@51
   144
        if self.isOpen:
jens@13
   145
            self._outQueueMessage(msg,True)
jens@14
   146
            if not self.sending:
jens@14
   147
                log.debug("Waking up the output stream")
jens@14
   148
                self.sending = True
jens@14
   149
                self.push_with_producer(self)
jens@13
   150
            return True
jens@13
   151
        else:
jens@13
   152
            return False
jens@13
   153
    
jens@13
   154
    def _sendRequest(self, req):
jens@13
   155
        if self.canSend:
jens@13
   156
            requestNo = req.requestNo = self.outNumRequests = self.outNumRequests + 1
jens@13
   157
            response = req.response
jens@13
   158
            if response:
jens@13
   159
                response.requestNo = requestNo
jens@13
   160
                self.pendingResponses[requestNo] = response
jens@13
   161
                log.debug("pendingResponses[%i] := %s",requestNo,response)
jens@13
   162
            return self._sendMessage(req)
jens@13
   163
        else:
jens@13
   164
            return False
jens@13
   165
    
jens@11
   166
    def _outQueueMessage(self, msg,isNew=True):
jens@12
   167
        n = len(self.outBox)
jens@11
   168
        index = n
jens@11
   169
        if msg.urgent and n>1:
jens@11
   170
            while index > 0:
jens@12
   171
                otherMsg = self.outBox[index-1]
jens@11
   172
                if otherMsg.urgent:
jens@11
   173
                    if index<n:
jens@11
   174
                        index += 1
jens@11
   175
                    break
jens@14
   176
                elif isNew and otherMsg.bytesSent==0:
jens@11
   177
                    break
jens@11
   178
                index -= 1
jens@11
   179
            else:
jens@11
   180
                index = 1
jens@12
   181
        
jens@11
   182
        self.outBox.insert(index,msg)
jens@11
   183
        if isNew:
jens@13
   184
            log.info("Queuing %s at index %i",msg,index)
jens@12
   185
        else:
jens@12
   186
            log.debug("Re-queueing outgoing message at index %i of %i",index,len(self.outBox))
jens@11
   187
    
jens@14
   188
    def more(self):
jens@14
   189
        n = len(self.outBox)
jens@14
   190
        if n > 0:
jens@14
   191
            msg = self.outBox.pop(0)
jens@14
   192
            frameSize = 4096
jens@14
   193
            if msg.urgent or n==1 or not self.outBox[0].urgent:
jens@14
   194
                frameSize *= 4
jens@14
   195
            data = msg._sendNextFrame(frameSize)
jens@14
   196
            if msg._moreComing:
jens@14
   197
                self._outQueueMessage(msg,isNew=False)
jens@14
   198
            else:
jens@14
   199
                log.info("Finished sending %s",msg)
jens@14
   200
            return data
jens@14
   201
        else:
jens@14
   202
            log.debug("Nothing more to send")
jens@14
   203
            self.sending = False
morrowa@51
   204
            self._closeIfReady()
jens@14
   205
            return None
jens@11
   206
    
jens@11
   207
    ### RECEIVING:
jens@11
   208
    
jens@11
   209
    def collect_incoming_data(self, data):
jens@11
   210
        if self.expectingHeader:
jens@11
   211
            if self.inHeader==None:
jens@11
   212
                self.inHeader = data
jens@11
   213
            else:
jens@11
   214
                self.inHeader += data
jens@13
   215
        elif self.inMessage:
jens@11
   216
            self.inMessage._receivedData(data)
jens@12
   217
    
jens@11
   218
    def found_terminator(self):
jens@11
   219
        if self.expectingHeader:
jens@11
   220
            # Got a header:
jens@11
   221
            (magic, requestNo, flags, frameLen) = struct.unpack(kFrameHeaderFormat,self.inHeader)
jens@11
   222
            self.inHeader = None
jens@13
   223
            if magic!=kFrameMagicNumber: raise ConnectionException, "Incorrect frame magic number %x" %magic
jens@13
   224
            if frameLen < kFrameHeaderSize: raise ConnectionException,"Invalid frame length %u" %frameLen
jens@11
   225
            frameLen -= kFrameHeaderSize
jens@11
   226
            log.debug("Incoming frame: type=%i, number=%i, flags=%x, length=%i",
jens@11
   227
                        (flags&kMsgFlag_TypeMask),requestNo,flags,frameLen)
jens@11
   228
            self.inMessage = self._inMessageForFrame(requestNo,flags)
jens@11
   229
            
jens@11
   230
            if frameLen > 0:
jens@11
   231
                self.expectingHeader = False
jens@11
   232
                self.set_terminator(frameLen)
jens@11
   233
            else:
jens@11
   234
                self._endOfFrame()
jens@12
   235
        
jens@11
   236
        else:
jens@11
   237
            # Got the frame's payload:
jens@11
   238
            self._endOfFrame()
jens@11
   239
    
jens@11
   240
    def _inMessageForFrame(self, requestNo,flags):
jens@11
   241
        message = None
jens@11
   242
        msgType = flags & kMsgFlag_TypeMask
jens@11
   243
        if msgType==kMsgType_Request:
jens@11
   244
            message = self.pendingRequests.get(requestNo)
jens@11
   245
            if message==None and requestNo == self.inNumRequests+1:
jens@11
   246
                message = IncomingRequest(self,requestNo,flags)
jens@12
   247
                assert message!=None
jens@11
   248
                self.pendingRequests[requestNo] = message
jens@11
   249
                self.inNumRequests += 1
jens@11
   250
        elif msgType==kMsgType_Response or msgType==kMsgType_Error:
jens@11
   251
            message = self.pendingResponses.get(requestNo)
morrowa@51
   252
            message._updateFlags(flags)
jens@12
   253
        
jens@12
   254
        if message != None:
jens@11
   255
            message._beginFrame(flags)
jens@11
   256
        else:
jens@11
   257
            log.warning("Ignoring unexpected frame with type %u, request #%u", msgType,requestNo)
jens@11
   258
        return message
jens@11
   259
    
jens@11
   260
    def _endOfFrame(self):
jens@11
   261
        msg = self.inMessage
jens@11
   262
        self.inMessage = None
jens@11
   263
        self.expectingHeader = True
jens@11
   264
        self.inHeader = None
jens@11
   265
        self.set_terminator(kFrameHeaderSize) # wait for binary header
jens@11
   266
        if msg:
jens@11
   267
            log.debug("End of frame of %s",msg)
jens@13
   268
            if not msg._moreComing:
jens@11
   269
                self._receivedMessage(msg)
jens@12
   270
    
jens@11
   271
    def _receivedMessage(self, msg):
jens@11
   272
        log.info("Received: %s",msg)
jens@11
   273
        # Remove from pending:
jens@11
   274
        if msg.isResponse:
jens@13
   275
            del self.pendingResponses[msg.requestNo]
jens@11
   276
        else:
jens@11
   277
            del self.pendingRequests[msg.requestNo]
jens@11
   278
        # Decode:
jens@11
   279
        try:
jens@11
   280
            msg._finished()
jens@12
   281
            if not msg.isResponse:
morrowa@51
   282
                if msg._meta:
morrowa@51
   283
                    self._dispatchMetaRequest(msg)
morrowa@51
   284
                else:
morrowa@51
   285
                    self.onRequest(msg)
jens@11
   286
        except Exception, x:
jens@12
   287
            log.error("Exception handling incoming message: %s", traceback.format_exc())
jens@11
   288
            #FIX: Send an error reply
morrowa@51
   289
        # Check to see if we're done and ready to close:
morrowa@51
   290
        self._closeIfReady()
morrowa@51
   291
    
morrowa@51
   292
    def _dispatchMetaRequest(self, request):
morrowa@51
   293
        """Handles dispatching internal meta requests."""
morrowa@51
   294
        if request['Profile'] == kMsgProfile_Bye:
morrowa@51
   295
            shouldClose = True
morrowa@51
   296
            if self.onCloseRequest:
morrowa@51
   297
                shouldClose = self.onCloseRequest()
morrowa@51
   298
            if not shouldClose:
morrowa@51
   299
                log.debug("Sending resfusal to close...")
morrowa@51
   300
                response = request.response
morrowa@51
   301
                response.isError = True
morrowa@51
   302
                response['Error-Domain'] = "BLIP"
morrowa@51
   303
                response['Error-Code'] = 403
morrowa@51
   304
                response.body = "Close request denied"
morrowa@51
   305
                response.send()
morrowa@51
   306
            else:
morrowa@51
   307
                log.debug("Sending permission to close...")
morrowa@51
   308
                response = request.response
morrowa@51
   309
                response.send()
morrowa@51
   310
        else:
morrowa@51
   311
            response = request.response
morrowa@51
   312
            response.isError = True
morrowa@51
   313
            response['Error-Domain'] = "BLIP"
morrowa@51
   314
            response['Error-Code'] = 404
morrowa@51
   315
            response.body = "Unknown meta profile"
morrowa@51
   316
            response.send()
morrowa@51
   317
    
morrowa@51
   318
    ### CLOSING:
morrowa@51
   319
    
morrowa@51
   320
    def close(self):
morrowa@51
   321
        """Publicly callable close method. Sends close request to peer."""
morrowa@51
   322
        if self.status != kOpen:
morrowa@51
   323
            return False
morrowa@51
   324
        log.info("Sending close request...")
morrowa@51
   325
        req = OutgoingRequest(self, None, {'Profile': kMsgProfile_Bye})
morrowa@51
   326
        req._meta = True
morrowa@51
   327
        req.response.onComplete = self._handleCloseResponse
morrowa@51
   328
        if not req.send():
morrowa@51
   329
            log.error("Error sending close request.")
morrowa@51
   330
            return False
morrowa@51
   331
        else:
morrowa@51
   332
            self.status = kClosing
morrowa@51
   333
        return True
morrowa@51
   334
    
morrowa@51
   335
    def _handleCloseResponse(self, response):
morrowa@51
   336
        """Called when we receive a response to a close request."""
morrowa@51
   337
        log.info("Received close response.")
morrowa@51
   338
        if response.isError:
morrowa@51
   339
            # remote refused to close
morrowa@51
   340
            if self.onCloseRefused:
morrowa@51
   341
                self.onCloseRefused(response)
morrowa@51
   342
            self.status = kOpen
morrowa@51
   343
        else:
morrowa@51
   344
            # now wait until everything has finished sending, then actually close
morrowa@51
   345
            log.info("No refusal, actually closing...")
morrowa@51
   346
            self._closeWhenPossible = True
morrowa@51
   347
    
morrowa@51
   348
    def _closeIfReady(self):
morrowa@51
   349
        """Checks if all transmissions are complete and then closes the actual socket."""
morrowa@51
   350
        if self._closeWhenPossible and len(self.outBox) == 0 and len(self.pendingRequests) == 0 and len(self.pendingResponses) == 0:
morrowa@51
   351
            # self._closeWhenPossible = False
morrowa@51
   352
            log.debug("_closeIfReady closing.")
morrowa@51
   353
            asynchat.async_chat.close(self)
morrowa@51
   354
    
morrowa@51
   355
    def handle_close(self):
morrowa@51
   356
        """Called when the socket actually closes."""
morrowa@51
   357
        log.info("Connection closed!")
morrowa@51
   358
        self.pendingRequests = self.pendingResponses = None
morrowa@51
   359
        self.outBox = None
morrowa@51
   360
        if self.status == kClosing:
morrowa@51
   361
            self.status = kClosed
morrowa@51
   362
        else:
morrowa@51
   363
            self.status = kDisconnected
morrowa@53
   364
        asyncore.dispatcher.close(self)
jens@11
   365
jens@12
   366
jens@13
   367
### MESSAGE CLASSES:
jens@11
   368
jens@11
   369
jens@11
   370
class Message (object):
jens@12
   371
    "Abstract superclass of all request/response objects"
jens@12
   372
    
jens@13
   373
    def __init__(self, connection, body=None, properties=None):
jens@11
   374
        self.connection = connection
jens@13
   375
        self.body = body
jens@11
   376
        self.properties = properties or {}
jens@13
   377
        self.requestNo = None
jens@11
   378
    
jens@11
   379
    @property
jens@11
   380
    def flags(self):
jens@12
   381
        if self.isResponse:
morrowa@51
   382
            if self.isError:
morrowa@51
   383
                flags = kMsgType_Error
morrowa@51
   384
            else:
morrowa@51
   385
                flags = kMsgType_Response
jens@12
   386
        else:
jens@12
   387
            flags = kMsgType_Request
jens@11
   388
        if self.urgent:     flags |= kMsgFlag_Urgent
jens@11
   389
        if self.compressed: flags |= kMsgFlag_Compressed
jens@11
   390
        if self.noReply:    flags |= kMsgFlag_NoReply
jens@13
   391
        if self._moreComing:flags |= kMsgFlag_MoreComing
morrowa@51
   392
        if self._meta:      flags |= kMsgFlag_Meta
jens@11
   393
        return flags
jens@11
   394
    
jens@11
   395
    def __str__(self):
jens@13
   396
        s = "%s[" %(type(self).__name__)
jens@13
   397
        if self.requestNo != None:
jens@13
   398
            s += "#%i" %self.requestNo
jens@11
   399
        if self.urgent:     s += " URG"
jens@11
   400
        if self.compressed: s += " CMP"
jens@11
   401
        if self.noReply:    s += " NOR"
jens@13
   402
        if self._moreComing:s += " MOR"
morrowa@51
   403
        if self._meta:      s += " MET"
jens@11
   404
        if self.body:       s += " %i bytes" %len(self.body)
jens@11
   405
        return s+"]"
jens@11
   406
    
jens@11
   407
    def __repr__(self):
jens@11
   408
        s = str(self)
jens@11
   409
        if len(self.properties): s += repr(self.properties)
jens@11
   410
        return s
jens@12
   411
    
jens@13
   412
    @property
jens@11
   413
    def isResponse(self):
jens@12
   414
        "Is this message a response?"
jens@11
   415
        return False
jens@12
   416
    
jens@13
   417
    @property
jens@12
   418
    def contentType(self):
jens@12
   419
        return self.properties.get('Content-Type')
jens@12
   420
    
jens@12
   421
    def __getitem__(self, key):     return self.properties.get(key)
jens@12
   422
    def __contains__(self, key):    return key in self.properties
jens@12
   423
    def __len__(self):              return len(self.properties)
jens@12
   424
    def __nonzero__(self):          return True
jens@12
   425
    def __iter__(self):             return self.properties.__iter__()
jens@11
   426
jens@11
   427
jens@11
   428
class IncomingMessage (Message):
jens@12
   429
    "Abstract superclass of incoming messages."
jens@12
   430
    
jens@11
   431
    def __init__(self, connection, requestNo, flags):
jens@11
   432
        super(IncomingMessage,self).__init__(connection)
jens@11
   433
        self.requestNo  = requestNo
morrowa@51
   434
        self._updateFlags(flags)
morrowa@51
   435
        self.frames     = []
morrowa@51
   436
    
morrowa@51
   437
    def _updateFlags(self, flags):
jens@12
   438
        self.urgent     = (flags & kMsgFlag_Urgent) != 0
jens@11
   439
        self.compressed = (flags & kMsgFlag_Compressed) != 0
jens@11
   440
        self.noReply    = (flags & kMsgFlag_NoReply) != 0
jens@13
   441
        self._moreComing= (flags & kMsgFlag_MoreComing) != 0
morrowa@51
   442
        self._meta      = (flags & kMsgFlag_Meta) != 0
morrowa@51
   443
        self.isError    = (flags & kMsgType_Error) != 0
jens@11
   444
    
jens@11
   445
    def _beginFrame(self, flags):
jens@13
   446
        """Received a frame header."""
jens@13
   447
        self._moreComing = (flags & kMsgFlag_MoreComing)!=0
jens@12
   448
    
jens@11
   449
    def _receivedData(self, data):
jens@13
   450
        """Received data from a frame."""
jens@11
   451
        self.frames.append(data)
jens@11
   452
    
jens@11
   453
    def _finished(self):
jens@13
   454
        """The entire message has been received; now decode it."""
jens@11
   455
        encoded = "".join(self.frames)
jens@11
   456
        self.frames = None
jens@11
   457
        
jens@11
   458
        # Decode the properties:
jens@11
   459
        if len(encoded) < 2: raise MessageException, "missing properties length"
jens@11
   460
        propSize = 2 + struct.unpack('!H',encoded[0:2])[0]
jens@11
   461
        if propSize>len(encoded): raise MessageException, "properties too long to fit"
jens@11
   462
        if propSize>2 and encoded[propSize-1] != '\000': raise MessageException, "properties are not nul-terminated"
jens@11
   463
        
morrowa@51
   464
        if propSize > 2:
morrowa@51
   465
            proplist = encoded[2:propSize-1].split('\000')
morrowa@51
   466
        
morrowa@51
   467
            if len(proplist) & 1: raise MessageException, "odd number of property strings"
morrowa@51
   468
            for i in xrange(0,len(proplist),2):
morrowa@51
   469
                def expand(str):
morrowa@51
   470
                    if len(str)==1:
morrowa@51
   471
                        str = IncomingMessage.__expandDict.get(str,str)
morrowa@51
   472
                    return str
morrowa@51
   473
                self.properties[ expand(proplist[i])] = expand(proplist[i+1])
morrowa@51
   474
        
jens@11
   475
        encoded = encoded[propSize:]
jens@11
   476
        # Decode the body:
jens@11
   477
        if self.compressed and len(encoded)>0:
jens@11
   478
            try:
jens@11
   479
                encoded = zlib.decompress(encoded,31)   # window size of 31 needed for gzip format
jens@11
   480
            except zlib.error:
jens@11
   481
                raise MessageException, sys.exc_info()[1]
jens@11
   482
        self.body = encoded
jens@11
   483
    
jens@11
   484
    __expandDict= {'\x01' : "Content-Type",
jens@11
   485
                   '\x02' : "Profile",
jens@11
   486
                   '\x03' : "application/octet-stream",
jens@11
   487
                   '\x04' : "text/plain; charset=UTF-8",
jens@11
   488
                   '\x05' : "text/xml",
jens@11
   489
                   '\x06' : "text/yaml",
jens@11
   490
                   '\x07' : "Channel",
jens@11
   491
                   '\x08' : "Error-Code",
jens@11
   492
                   '\x09' : "Error-Domain"}
jens@12
   493
jens@11
   494
jens@11
   495
class OutgoingMessage (Message):
jens@12
   496
    "Abstract superclass of outgoing requests/responses."
jens@12
   497
    
jens@13
   498
    def __init__(self, connection, body=None, properties=None):
jens@13
   499
        Message.__init__(self,connection,body,properties)
morrowa@51
   500
        self.urgent = self.compressed = self.noReply = self._meta = self.isError = False
jens@13
   501
        self._moreComing = True
jens@12
   502
    
jens@12
   503
    def __setitem__(self, key,val):
jens@12
   504
        self.properties[key] = val
jens@12
   505
    def __delitem__(self, key):
jens@12
   506
        del self.properties[key]
jens@11
   507
    
jens@13
   508
    @property
jens@13
   509
    def sent(self):
jens@16
   510
        return hasattr(self,'encoded')
jens@13
   511
    
jens@13
   512
    def _encode(self):
jens@13
   513
        "Generates the message's encoded form, prior to sending it."
jens@11
   514
        out = StringIO()
jens@12
   515
        for (key,value) in self.properties.iteritems():
jens@13
   516
            def _writePropString(s):
jens@13
   517
                out.write(str(s))    #FIX: Abbreviate
jens@11
   518
                out.write('\000')
jens@12
   519
            _writePropString(key)
jens@12
   520
            _writePropString(value)
jens@13
   521
        propertiesSize = out.tell()
jens@13
   522
        assert propertiesSize<65536     #FIX: Return an error instead
jens@11
   523
        
morrowa@51
   524
        body = self.body or ""
jens@11
   525
        if self.compressed:
jens@13
   526
            z = zlib.compressobj(6,zlib.DEFLATED,31)   # window size of 31 needed for gzip format
jens@13
   527
            out.write(z.compress(body))
jens@13
   528
            body = z.flush()
jens@13
   529
        out.write(body)
jens@13
   530
        
jens@13
   531
        self.encoded = struct.pack('!H',propertiesSize) + out.getvalue()
jens@13
   532
        out.close()
jens@12
   533
        log.debug("Encoded %s into %u bytes", self,len(self.encoded))
jens@11
   534
        self.bytesSent = 0
jens@11
   535
    
jens@14
   536
    def _sendNextFrame(self, maxLen):
jens@11
   537
        pos = self.bytesSent
jens@11
   538
        payload = self.encoded[pos:pos+maxLen]
jens@11
   539
        pos += len(payload)
jens@13
   540
        self._moreComing = (pos < len(self.encoded))
jens@13
   541
        if not self._moreComing:
jens@13
   542
            self.encoded = None
jens@12
   543
        log.debug("Sending frame of %s; bytes %i--%i", self,pos-len(payload),pos)
jens@12
   544
        
jens@14
   545
        header = struct.pack(kFrameHeaderFormat, kFrameMagicNumber,
jens@12
   546
                                                   self.requestNo,
jens@12
   547
                                                   self.flags,
jens@14
   548
                                                   kFrameHeaderSize+len(payload))
jens@11
   549
        self.bytesSent = pos
jens@14
   550
        return header + payload
jens@11
   551
jens@11
   552
jens@12
   553
class Request (object):
jens@12
   554
    @property
jens@12
   555
    def response(self):
jens@12
   556
        "The response object for this request."
jens@13
   557
        if self.noReply:
jens@13
   558
            return None
jens@12
   559
        r = self.__dict__.get('_response')
jens@12
   560
        if r==None:
jens@12
   561
            r = self._response = self._createResponse()
jens@12
   562
        return r
jens@12
   563
jens@11
   564
jens@11
   565
class Response (Message):
jens@13
   566
    def _setRequest(self, request):
jens@12
   567
        assert not request.noReply
jens@12
   568
        self.request = request
jens@12
   569
        self.requestNo = request.requestNo
jens@12
   570
        self.urgent = request.urgent
jens@12
   571
    
jens@11
   572
    @property
jens@11
   573
    def isResponse(self):
jens@11
   574
        return True
jens@11
   575
jens@11
   576
jens@11
   577
class IncomingRequest (IncomingMessage, Request):
jens@12
   578
    def _createResponse(self):
jens@12
   579
        return OutgoingResponse(self)
jens@11
   580
jens@13
   581
jens@11
   582
class OutgoingRequest (OutgoingMessage, Request):
jens@12
   583
    def _createResponse(self):
jens@12
   584
        return IncomingResponse(self)
jens@13
   585
    
jens@13
   586
    def send(self):
jens@13
   587
        self._encode()
jens@13
   588
        return self.connection._sendRequest(self) and self.response
jens@13
   589
jens@11
   590
jens@11
   591
class IncomingResponse (IncomingMessage, Response):
jens@12
   592
    def __init__(self, request):
jens@13
   593
        IncomingMessage.__init__(self,request.connection,None,0)
jens@13
   594
        self._setRequest(request)
jens@12
   595
        self.onComplete = None
jens@12
   596
    
jens@12
   597
    def _finished(self):
jens@12
   598
        super(IncomingResponse,self)._finished()
jens@12
   599
        if self.onComplete:
jens@12
   600
            try:
jens@12
   601
                self.onComplete(self)
jens@12
   602
            except Exception, x:
jens@12
   603
                log.error("Exception dispatching response: %s", traceback.format_exc())
jens@13
   604
jens@13
   605
jens@11
   606
class OutgoingResponse (OutgoingMessage, Response):
jens@12
   607
    def __init__(self, request):
jens@12
   608
        OutgoingMessage.__init__(self,request.connection)
jens@13
   609
        self._setRequest(request)
jens@13
   610
    
jens@13
   611
    def send(self):
jens@13
   612
        self._encode()
jens@13
   613
        return self.connection._sendMessage(self)
jens@11
   614
jens@11
   615
jens@13
   616
"""
jens@13
   617
 Copyright (c) 2008, Jens Alfke <jens@mooseyard.com>. All rights reserved.
jens@13
   618
 
jens@13
   619
 Redistribution and use in source and binary forms, with or without modification, are permitted
jens@13
   620
 provided that the following conditions are met:
jens@13
   621
 
jens@13
   622
 * Redistributions of source code must retain the above copyright notice, this list of conditions
jens@13
   623
 and the following disclaimer.
jens@13
   624
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
jens@13
   625
 and the following disclaimer in the documentation and/or other materials provided with the
jens@13
   626
 distribution.
jens@13
   627
 
jens@13
   628
 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
jens@13
   629
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
jens@13
   630
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRI-
jens@13
   631
 BUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
jens@13
   632
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
jens@13
   633
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
jens@13
   634
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
jens@13
   635
 THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
jens@13
   636
"""