def __init__(self, parent, xmms): qt.QObject.__init__(self, parent) fd = xmms.get_fd() self.xmms = xmms self.xmms.set_need_out_fun(self.chkWr) self.rsock = qt.QSocketNotifier(fd, qt.QSocketNotifier.Read, self) self.connect(self.rsock, qt.SIGNAL("activated(int)"), self.do_read) self.rsock.setEnabled(False) self.wsock = qt.QSocketNotifier(fd, qt.QSocketNotifier.Write, self) self.connect(self.wsock, qt.SIGNAL("activated(int)"), self.do_write) self.wsock.setEnabled(False)
def reopenFifo(self): """Close and reopen the FIFO. Setup a QSocketNotifier to get the Qt event loop notifying us when someone is requesting an application start.""" del self.socketNotifier os.close(self.fileno) self.fileno = os.open(self.name, os.O_RDONLY | os.O_NONBLOCK) TDEBUG(self, "created communication fifo '%s'" % self.name) self.socketNotifier = qt.QSocketNotifier(self.fileno, qt.QSocketNotifier.Read) qt.QObject.connect(self.socketNotifier, qt.SIGNAL("activated(int)"), self.slotHandleMessage)
def start(self): """start the server Uses one thread since we are event driven """ try: self.logMessage('started httpserver...') self.notifier = qt.QSocketNotifier(self.socket.fileno(), qt.QSocketNotifier.Read) self.logMessage('listening on %d...' % self.socket.fileno()) self.notifier.connect('activated(int)', self.onServerSocketNotify) except KeyboardInterrupt: self.logMessage('KeyboardInterrupt - stopping') self.stop()
def _parentSetupCommunication(self): """Called right after a (successful) fork on the parent side. This function will do some communications cleanup, like closing the reading end of the "stdin" communication channel. Furthermore, it must also create the "outnot" QSocketNotifiers and connect its Qt slots to the respective member functions. """ os.close(self.out[1]) # fcntl(out[0], F_SETFL, O_NONBLOCK)) self._outnot = qt.QSocketNotifier(self.out[0], qt.QSocketNotifier.Read, self) self.connect(self._outnot, qt.SIGNAL('activated(int)'), self.slotChildOutput) self.suspend()
def __init__(self): super(ProcessController, self).__init__() #global theProcessController #assert theProcessController is None self.old_sigCHLDHandler = None self.handler_set = False self.process_list = [] self.fd = os.pipe() # delayed children cleanup timer self._dcc_timer = qt.QTimer() fcntl.fcntl(self.fd[0], fcntl.F_SETFL, os.O_NONBLOCK) notifier = qt.QSocketNotifier(self.fd[0], qt.QSocketNotifier.Read, self) self.connect(notifier, qt.SIGNAL('activated(int)'), self.slotDoHousekeeping) self.connect(self._dcc_timer, qt.SIGNAL('timeout()'), self.delayedChildrenCleanup) #theProcessController = self self.setupHandlers()
def __init__(self, connectionSocket, requestHandlers, docroot, logMessage): """ :param connectionSocket: socket for this request :param docroot: for handling static pages content :param logMessage: callable """ self.connectionSocket = connectionSocket self.docroot = docroot self.logMessage = logMessage self.bufferSize = 1024 * 1024 self.requestHandlers = [] for requestHandler in requestHandlers: self.registerRequestHandler(requestHandler) self.expectedRequestSize = -1 self.requestSoFar = b"" fileno = self.connectionSocket.fileno() self.readNotifier = qt.QSocketNotifier(fileno, qt.QSocketNotifier.Read) self.readNotifier.connect('activated(int)', self.onReadable) self.logMessage('Waiting on %d...' % fileno)
def onReadable(self, fileno): self.logMessage('Reading...') requestHeader = b"" requestBody = b"" requestComplete = False requestPart = "" try: requestPart = self.connectionSocket.recv(self.bufferSize) self.logMessage('Just received... %d bytes in this part' % len(requestPart)) self.requestSoFar += requestPart endOfHeader = self.requestSoFar.find(b'\r\n\r\n') if self.expectedRequestSize > 0: self.logMessage( 'received... %d of %d expected' % (len(self.requestSoFar), self.expectedRequestSize)) if len(self.requestSoFar) >= self.expectedRequestSize: requestHeader = self.requestSoFar[:endOfHeader + 2] requestBody = self.requestSoFar[4 + endOfHeader:] requestComplete = True else: if endOfHeader != -1: self.logMessage('Looking for content in header...') contentLengthTag = self.requestSoFar.find( b'Content-Length:') if contentLengthTag != -1: tag = self.requestSoFar[contentLengthTag:] numberStartIndex = tag.find(b' ') numberEndIndex = tag.find(b'\r\n') contentLength = int( tag[numberStartIndex:numberEndIndex]) self.expectedRequestSize = 4 + endOfHeader + contentLength self.logMessage( 'Expecting a body of %d, total size %d' % (contentLength, self.expectedRequestSize)) if len(requestPart) == self.expectedRequestSize: requestHeader = requestPart[:endOfHeader + 2] requestBody = requestPart[4 + endOfHeader:] requestComplete = True else: self.logMessage( 'Found end of header with no content, so body is empty' ) requestHeader = self.requestSoFar[:-2] requestComplete = True except socket.error as e: print('Socket error: ', e) print('So far:\n', self.requestSoFar) requestComplete = True if len(requestPart) == 0 or requestComplete: self.logMessage( 'Got complete message of header size %d, body size %d' % (len(requestHeader), len(requestBody))) self.readNotifier.disconnect('activated(int)', self.onReadable) self.readNotifier.setEnabled(False) qt.QTimer.singleShot(0, self.onReadableComplete) if len(self.requestSoFar) == 0: self.logMessage("Ignoring empty request") return method, uri, version = [b'GET', b'/', b'HTTP/1.1'] # defaults requestLines = requestHeader.split(b'\r\n') self.logMessage(requestLines[0]) try: method, uri, version = requestLines[0].split(b' ') except ValueError as e: self.logMessage( "Could not interpret first request lines: ", requestLines) if requestLines == "": self.logMessage( "Assuming empty string is HTTP/1.1 GET of /.") if version != b"HTTP/1.1": self.logMessage("Warning, we don't speak %s", version) return # TODO: methods = ["GET", "POST", "PUT", "DELETE"] methods = [b"GET", b"POST", b"PUT"] if method not in methods: self.logMessage("Warning, we only handle %s" % methods) return parsedURL = urllib.parse.urlparse(uri) request = parsedURL.path if parsedURL.query != b"": request += b'?' + parsedURL.query self.logMessage('Parsing url request: ', parsedURL) self.logMessage(' request is: %s' % request) highestConfidenceHandler = None highestConfidence = 0.0 for handler in self.requestHandlers: confidence = handler.canHandleRequest(uri, requestBody) if confidence > highestConfidence: highestConfidenceHandler = handler highestConfidence = confidence if highestConfidenceHandler is not None and highestConfidence > 0.0: try: contentType, responseBody = highestConfidenceHandler.handleRequest( uri, requestBody) except: etype, value, tb = sys.exc_info() import traceback for frame in traceback.format_tb(tb): self.logMessage(frame) self.logMessage(etype, value) contentType = b'text/plain' responseBody = b'Server error' # TODO: send correct error code in response else: contentType = b'text/plain' responseBody = b'' if responseBody: self.response = b"HTTP/1.1 200 OK\r\n" self.response += b"Access-Control-Allow-Origin: *\r\n" self.response += b"Content-Type: %s\r\n" % contentType self.response += b"Content-Length: %d\r\n" % len( responseBody) self.response += b"Cache-Control: no-cache\r\n" self.response += b"\r\n" self.response += responseBody else: self.response = b"HTTP/1.1 404 Not Found\r\n" self.response += b"\r\n" self.toSend = len(self.response) self.sentSoFar = 0 fileno = self.connectionSocket.fileno() self.writeNotifier = qt.QSocketNotifier( fileno, qt.QSocketNotifier.Write) self.writeNotifier.connect('activated(int)', self.onWritable)