我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用twisted.python.log.callWithLogger()。
def ssh_CHANNEL_DATA(self, packet): localChannel, dataLength = struct.unpack('>2L', packet[: 8]) channel = self.channels[localChannel] # XXX should this move to dataReceived to put client in charge? if dataLength > channel.localWindowLeft or \ dataLength > channel.localMaxPacket: # more data than we want log.callWithLogger(channel, lambda s=self,c=channel: log.msg('too much data') and s.sendClose(c)) return #packet = packet[:channel.localWindowLeft+4] data = common.getNS(packet[4:])[0] channel.localWindowLeft-=dataLength if channel.localWindowLeft < channel.localWindowSize/2: self.adjustWindow(channel, channel.localWindowSize - \ channel.localWindowLeft) #log.msg('local window left: %s/%s' % (channel.localWindowLeft, # channel.localWindowSize)) log.callWithLogger(channel, channel.dataReceived, data)
def read(self, sock): w = self.watcher #self.setEnabled(False) # ??? do I need this? def _read(): why = None try: why = w.doRead() except: log.err() why = sys.exc_info()[1] if why: self.reactor._disconnectSelectable(w, why, True) elif self.watcher: pass #self.setEnabled(True) log.callWithLogger(w, _read) self.reactor.reactorInvocation()
def write(self, sock): w = self.watcher self.setEnabled(False) def _write(): why = None try: why = w.doWrite() except: log.err() why = sys.exc_info()[1] if why: self.reactor._disconnectSelectable(w, why, False) elif self.watcher: self.setEnabled(True) log.callWithLogger(w, _write) self.reactor.reactorInvocation()
def ssh_CHANNEL_OPEN_CONFIRMATION(self, packet): """ The other side accepted our MSG_CHANNEL_OPEN request. Payload:: uint32 local channel number uint32 remote channel number uint32 remote window size uint32 remote maximum packet size <channel specific data> Find the channel using the local channel number and notify its channelOpen method. """ (localChannel, remoteChannel, windowSize, maxPacket) = struct.unpack('>4L', packet[: 16]) specificData = packet[16:] channel = self.channels[localChannel] channel.conn = self self.localToRemoteChannel[localChannel] = remoteChannel self.channelsToRemoteChannel[channel] = remoteChannel channel.remoteWindowLeft = windowSize channel.remoteMaxPacket = maxPacket log.callWithLogger(channel, channel.channelOpen, specificData)
def ssh_CHANNEL_OPEN_FAILURE(self, packet): """ The other side did not accept our MSG_CHANNEL_OPEN request. Payload:: uint32 local channel number uint32 reason code string reason description Find the channel using the local channel number and notify it by calling its openFailed() method. """ localChannel, reasonCode = struct.unpack('>2L', packet[:8]) reasonDesc = common.getNS(packet[8:])[0] channel = self.channels[localChannel] del self.channels[localChannel] channel.conn = self reason = error.ConchError(reasonDesc, reasonCode) log.callWithLogger(channel, channel.openFailed, reason)
def ssh_CHANNEL_REQUEST(self, packet): """ The other side is sending a request to a channel. Payload:: uint32 local channel number string request name bool want reply <request specific data> Pass the message to the channel's requestReceived method. If the other side wants a reply, add callbacks which will send the reply. """ localChannel = struct.unpack('>L', packet[:4])[0] requestType, rest = common.getNS(packet[4:]) wantReply = ord(rest[0:1]) channel = self.channels[localChannel] d = defer.maybeDeferred(log.callWithLogger, channel, channel.requestReceived, requestType, rest[1:]) if wantReply: d.addCallback(self._cbChannelRequest, localChannel) d.addErrback(self._ebChannelRequest, localChannel) return d
def ssh_CHANNEL_FAILURE(self, packet): """ Our channel request to the other side failed. Payload:: uint32 local channel number Get the C{Deferred} out of self.deferreds and errback it with a C{error.ConchError}. """ localChannel = struct.unpack('>L', packet[:4])[0] if self.deferreds.get(localChannel): d = self.deferreds[localChannel].pop(0) log.callWithLogger(self.channels[localChannel], d.errback, error.ConchError('channel request failed')) # methods for users of the connection to call
def addReader(self, reader): if reader in self._readers.keys() or \ reader in self._continuousPolling._readers: return fd = reader.fileno() try: self._asyncioEventloop.add_reader(fd, callWithLogger, reader, self._readOrWrite, reader, True) self._readers[reader] = fd except IOError as e: self._unregisterFDInAsyncio(fd) if e.errno == errno.EPERM: # epoll(7) doesn't support certain file descriptors, # e.g. filesystem files, so for those we just poll # continuously: self._continuousPolling.addReader(reader) else: raise
def addWriter(self, writer): if writer in self._writers.keys() or \ writer in self._continuousPolling._writers: return fd = writer.fileno() try: self._asyncioEventloop.add_writer(fd, callWithLogger, writer, self._readOrWrite, writer, False) self._writers[writer] = fd except PermissionError: self._unregisterFDInAsyncio(fd) # epoll(7) doesn't support certain file descriptors, # e.g. filesystem files, so for those we just poll # continuously: self._continuousPolling.addWriter(writer) except BrokenPipeError: # The kqueuereactor will raise this if there is a broken pipe self._unregisterFDInAsyncio(fd) except: self._unregisterFDInAsyncio(fd) raise
def _invoke_callback(self, fd, events): if fd not in self._fds: return (reader, writer) = self._fds[fd] if reader: err = None if reader.fileno() == -1: err = error.ConnectionLost() elif events & IOLoop.READ: err = log.callWithLogger(reader, reader.doRead) if err is None and events & IOLoop.ERROR: err = error.ConnectionLost() if err is not None: self.removeReader(reader) reader.readConnectionLost(failure.Failure(err)) if writer: err = None if writer.fileno() == -1: err = error.ConnectionLost() elif events & IOLoop.WRITE: err = log.callWithLogger(writer, writer.doWrite) if err is None and events & IOLoop.ERROR: err = error.ConnectionLost() if err is not None: self.removeWriter(writer) writer.writeConnectionLost(failure.Failure(err))
def ssh_CHANNEL_OPEN(self, packet): channelType, rest = common.getNS(packet) senderChannel, windowSize, maxPacket = struct.unpack('>3L', rest[: 12]) packet = rest[12:] try: channel = self.getChannel(channelType, windowSize, maxPacket, packet) localChannel = self.localChannelID self.localChannelID+=1 channel.id = localChannel self.channels[localChannel] = channel self.channelsToRemoteChannel[channel] = senderChannel self.localToRemoteChannel[localChannel] = senderChannel self.transport.sendPacket(MSG_CHANNEL_OPEN_CONFIRMATION, struct.pack('>4L', senderChannel, localChannel, channel.localWindowSize, channel.localMaxPacket)+channel.specificData) log.callWithLogger(channel, channel.channelOpen, '') except Exception, e: log.msg('channel open failed') log.err(e) if isinstance(e, error.ConchError): reason, textualInfo = e.args[0], e.data else: reason = OPEN_CONNECT_FAILED textualInfo = "unknown failure" self.transport.sendPacket(MSG_CHANNEL_OPEN_FAILURE, struct.pack('>2L', senderChannel, reason)+ \ common.NS(textualInfo)+common.NS(''))
def ssh_CHANNEL_OPEN_CONFIRMATION(self, packet): localChannel, remoteChannel, windowSize, maxPacket = struct.unpack('>4L', packet[: 16]) specificData = packet[16:] channel = self.channels[localChannel] channel.conn = self self.localToRemoteChannel[localChannel] = remoteChannel self.channelsToRemoteChannel[channel] = remoteChannel channel.remoteWindowLeft = windowSize channel.remoteMaxPacket = maxPacket log.callWithLogger(channel, channel.channelOpen, specificData)
def ssh_CHANNEL_OPEN_FAILURE(self, packet): localChannel, reasonCode = struct.unpack('>2L', packet[: 8]) reasonDesc = common.getNS(packet[8:])[0] channel = self.channels[localChannel] del self.channels[localChannel] channel.conn = self reason = error.ConchError(reasonDesc, reasonCode) log.callWithLogger(channel, channel.openFailed, reason)
def ssh_CHANNEL_WINDOW_ADJUST(self, packet): localChannel, bytesToAdd = struct.unpack('>2L', packet[: 8]) channel = self.channels[localChannel] log.callWithLogger(channel, channel.addWindowBytes, bytesToAdd)
def ssh_CHANNEL_EOF(self, packet): localChannel = struct.unpack('>L', packet[: 4])[0] channel = self.channels[localChannel] log.callWithLogger(channel, channel.eofReceived)
def ssh_CHANNEL_CLOSE(self, packet): localChannel = struct.unpack('>L', packet[: 4])[0] channel = self.channels[localChannel] if channel.remoteClosed: return log.callWithLogger(channel, channel.closeReceived) channel.remoteClosed = 1 if channel.localClosed and channel.remoteClosed: self.channelClosed(channel)
def ssh_CHANNEL_REQUEST(self, packet): localChannel = struct.unpack('>L', packet[: 4])[0] requestType, rest = common.getNS(packet[4:]) wantReply = ord(rest[0]) channel = self.channels[localChannel] d = log.callWithLogger(channel, channel.requestReceived, requestType, rest[1:]) if wantReply: if isinstance(d, defer.Deferred): d.addCallback(self._cbChannelRequest, localChannel) d.addErrback(self._ebChannelRequest, localChannel) elif d: self._cbChannelRequest(None, localChannel) else: self._ebChannelRequest(None, localChannel)
def ssh_CHANNEL_SUCCESS(self, packet): localChannel = struct.unpack('>L', packet[: 4])[0] if self.deferreds.get(localChannel): d = self.deferreds[localChannel].pop(0) log.callWithLogger(self.channels[localChannel], d.callback, packet[4:])
def ssh_CHANNEL_FAILURE(self, packet): localChannel = struct.unpack('>L', packet[: 4])[0] if self.deferreds.get(localChannel): d = self.deferreds[localChannel].pop(0) log.callWithLogger(self.channels[localChannel], d.errback, error.ConchError('channel request failed')) # methods for users of the connection to call
def dataReceived(self, data): self.buf = self.buf+data if not self.gotVersion: parts = self.buf.split('\n') for p in parts: if p[: 4] == 'SSH-': self.gotVersion = 1 self.otherVersionString = p.strip() if p.split('-')[1]not in('1.99', '2.0'): # bad version self.sendDisconnect(DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED, 'bad version %s'%p.split('-')[1]) return i = parts.index(p) self.buf = '\n'.join(parts[i+1:]) packet = self.getPacket() while packet: messageNum = ord(packet[0]) if messageNum < 50: messageType = messages[messageNum][4:] f = getattr(self, 'ssh_%s'%messageType, None) if f: f(packet[1:]) else: log.msg("couldn't handle %s"%messageType) log.msg(repr(packet[1:])) self.sendUnimplemented() elif self.service: log.callWithLogger(self.service, self.service.packetReceived, ord(packet[0]), packet[1:]) else: log.msg("couldn't handle %s"%messageNum) log.msg(repr(packet[1:])) self.sendUnimplemented() packet = self.getPacket()
def channelClosed(self, channel): channel.localClosed = channel.remoteClosed = 1 del self.channels[channel.id] log.callWithLogger(channel, channel.closed) # just in case the user doesn't override
def _process_Notify(self, r, w): #print >>sys.stderr, "_process_Notify" reads = self.reads writes = self.writes _drdw = self._doReadOrWrite _logrun = log.callWithLogger for selectables, method, dct in ((r, "doRead", reads), (w, "doWrite", writes)): for selectable in selectables: # if this was disconnected in another thread, kill it. if selectable not in dct: continue # This for pausing input when we're not ready for more. _logrun(selectable, _drdw, selectable, method, dct) #print >>sys.stderr, "done _process_Notify"
def doPoll(self, timeout, reads=reads, writes=writes, selectables=selectables, select=select, log=log, POLLIN=select.POLLIN, POLLOUT=select.POLLOUT): """Poll the poller for new events.""" if timeout is not None: timeout = int(timeout * 1000) # convert seconds to milliseconds try: l = poller.poll(timeout) except select.error, e: if e[0] == errno.EINTR: return else: raise _drdw = self._doReadOrWrite for fd, event in l: try: selectable = selectables[fd] except KeyError: # Handles the infrequent case where one selectable's # handler disconnects another. continue log.callWithLogger(selectable, _drdw, selectable, fd, event, POLLIN, POLLOUT, log)
def doKEvent(self, timeout, reads=reads, writes=writes, selectables=selectables, kq=kq, log=log, OSError=OSError, EVFILT_READ=EVFILT_READ, EVFILT_WRITE=EVFILT_WRITE): """Poll the kqueue for new events.""" if timeout is None: timeout = 1000 else: timeout = int(timeout * 1000) # convert seconds to milliseconds try: l = kq.kevent([], len(selectables), timeout) except OSError, e: if e[0] == errno.EINTR: return else: raise _drdw = self._doWriteOrRead for event in l: why = None fd, filter = event.ident, event.filter selectable = selectables[fd] log.callWithLogger(selectable, _drdw, selectable, fd, filter)
def disconnectAll(self): """Disconnect every reader, and writer in the system. """ selectables = self.removeAll() for reader in selectables: log.callWithLogger(reader, reader.connectionLost, failure.Failure(main.CONNECTION_LOST))
def callback(self, source, condition): log.callWithLogger(source, self._doReadOrWrite, source, condition) self.simulate() # fire Twisted timers return 1 # 1=don't auto-remove the source
def doWaitForMultipleEvents(self, timeout, reads=reads, writes=writes): log.msg(channel='system', event='iteration', reactor=self) if timeout is None: #timeout = INFINITE timeout = 100 else: timeout = int(timeout * 1000) if not (events or writes): # sleep so we don't suck up CPU time time.sleep(timeout / 1000.0) return canDoMoreWrites = 0 for fd in writes.keys(): if log.callWithLogger(fd, self._runWrite, fd): canDoMoreWrites = 1 if canDoMoreWrites: timeout = 0 handles = events.keys() or [self.dummyEvent] val = MsgWaitForMultipleObjects(handles, 0, timeout, QS_ALLINPUT | QS_ALLEVENTS) if val == WAIT_TIMEOUT: return elif val == WAIT_OBJECT_0 + len(handles): exit = win32gui.PumpWaitingMessages() if exit: self.callLater(0, self.stop) return elif val >= WAIT_OBJECT_0 and val < WAIT_OBJECT_0 + len(handles): fd, action = events[handles[val - WAIT_OBJECT_0]] log.callWithLogger(fd, self._runAction, action, fd)
def doPoll(self, timeout, reads=reads, writes=writes, selectables=selectables, wait=poller.wait, log=log): """ Poll the poller for new events. """ if timeout is None: timeout = 1 timeout = int(timeout * 1000) # convert seconds to milliseconds try: # Limit the number of events to the number of io objects we're # currently tracking (because that's maybe a good heuristic) and # the amount of time we block to the value specified by our # caller. l = wait(len(selectables), timeout) except IOError, err: if err.errno == errno.EINTR: return # See epoll_wait(2) for documentation on the other conditions # under which this can fail. They can only be due to a serious # programming error on our part, so let's just announce them # loudly. raise _drdw = self._doReadOrWrite for fd, event in l: try: selectable = selectables[fd] except KeyError: pass else: log.callWithLogger(selectable, _drdw, selectable, fd, event)
def callback(self, source, condition): log.callWithLogger(source, self._readAndWrite, source, condition) self.simulate() # fire Twisted timers return 1 # 1=don't auto-remove the source
def doPoll(self, timeout, reads=reads, writes=writes, selectables=selectables, select=select, log=log, POLLIN=select.POLLIN, POLLOUT=select.POLLOUT): """Poll the poller for new events.""" if timeout is not None: timeout = int(timeout * 1000) # convert seconds to milliseconds try: l = poller.poll(timeout) if l is None: if self.running: self.stop() l = [ ] except select.error, e: if e[0] == errno.EINTR: return else: raise _drdw = self._doReadOrWrite for fd, event in l: try: selectable = selectables[fd] except KeyError: # Handles the infrequent case where one selectable's # handler disconnects another. continue log.callWithLogger(selectable, _drdw, selectable, fd, event, POLLIN, POLLOUT, log)