def _run(self, context_connection, bsd_socket): """ The main loop. Get package from socket, deposit package in queue(s). """ # Short names in local namespace avoid dictionary lookups socket_recv = bsd_socket.recv recv_package = context_connection._context._recv_package package_from_header = Package.from_header HS = HEADER_SIZE # Variable to keep track if we emitted a timedout signal timedOut = False while True: time.sleep(0) # Be nice # Use select call on a timeout to test if data is available while True: try: ok = can_recv(bsd_socket, context_connection._timeout) except Exception: # select() has it's share of weird errors raise socket.error('select(): ' + getErrorMsg()) if ok: # Set timedout ex? if timedOut: timedOut = False context_connection.timedout.emit( context_connection, False) # Exit from loop break else: # Should we stop? if not context_connection.is_connected: return # No need for a stop message # Should we do a timeout? if not timedOut: timedOut = True context_connection.timedout.emit( context_connection, True) # Continue in loop continue # Get package package = self._getPackage(socket_recv, HS, package_from_header) if package is None: continue elif isinstance(package, basestring): return package # error msg # Let context handle package further (but happens in this thread) try: recv_package(package, context_connection) except Exception: print("Error depositing package in ReceivingThread.") print(getErrorMsg())
def _run(self, context_connection, bsd_socket): """ The main loop. Get package from socket, deposit package in queue(s). """ # Short names in local namespace avoid dictionary lookups socket_recv = bsd_socket.recv recv_package = context_connection._context._recv_package package_from_header = Package.from_header HS = HEADER_SIZE # Variable to keep track if we emitted a timedout signal timedOut = False while True: time.sleep(0) # Be nice # Use select call on a timeout to test if data is available while True: try: ok = can_recv(bsd_socket, context_connection._timeout) except Exception: # select() has it's share of weird errors raise socket.error('select(): ' + getErrorMsg()) if ok: # Set timedout ex? if timedOut: timedOut = False context_connection.timedout.emit(context_connection, False) # Exit from loop break else: # Should we stop? if not context_connection.is_connected: return # No need for a stop message # Should we do a timeout? if not timedOut: timedOut = True context_connection.timedout.emit(context_connection, True) # Continue in loop continue # Get package package = self._getPackage(socket_recv, HS, package_from_header) if package is None: continue elif isinstance(package, basestring): return package # error msg # Let context handle package further (but happens in this thread) try: recv_package(package, context_connection) except Exception: print("Error depositing package in ReceivingThread.") print(getErrorMsg())
def _handle_connection(self, s): """ _handle_connection(s) Handle an incoming connection. """ try: self._really_handle_connection(s) except Exception: print('Error handling request:') print(getErrorMsg())
def _handle_connection(self, s): """ _handle_connection(s) Handle an incoming connection. """ try: self._really_handle_connection(s) except Exception: print("Error handling request:") print(getErrorMsg())
def run2(self, context_connection, bsd_socket): """Method to enter main loop. There is a try-except here to catch exceptions in the main loop (such as socket errors and errors due to bugs in the code. """ # Get classname to use in messages className = "yoton." + self.__class__.__name__ # Define function to write errors def writeErr(err): sys.__stderr__.write(str(err) + "\n") sys.__stderr__.flush() try: # Enter mainloop stop_reason = self._run(context_connection, bsd_socket) # Was there a specific reason to stop? if stop_reason: context_connection.close_on_problem(stop_reason) else: pass # Stopped because the connection is gone (already stopped) except socket.error: # Socket error. Can happen if the other end closed not so nice # Do get the socket error message and pass it on. msg = STOP_SOCKET_ERROR + getErrorMsg() context_connection.close_on_problem("%s, %s" % (className, msg)) except Exception: # Else: woops, an error! errmsg = getErrorMsg() msg = STOP_THREAD_ERROR + errmsg context_connection.close_on_problem("%s, %s" % (className, msg)) writeErr("Exception in %s." % className) writeErr(errmsg)
def run2(self, context_connection, bsd_socket): """ Method to enter main loop. There is a try-except here to catch exceptions in the main loop (such as socket errors and errors due to bugs in the code. """ # Get classname to use in messages className = 'yoton.' + self.__class__.__name__ # Define function to write errors def writeErr(err): sys.__stderr__.write(str(err)+'\n') sys.__stderr__.flush() try: # Enter mainloop stop_reason = self._run(context_connection, bsd_socket) # Was there a specific reason to stop? if stop_reason: context_connection.close_on_problem(stop_reason) else: pass # Stopped because the connection is gone (already stopped) except socket.error: # Socket error. Can happen if the other end closed not so nice # Do get the socket error message and pass it on. msg = STOP_SOCKET_ERROR + getErrorMsg() context_connection.close_on_problem('%s, %s' % (className, msg)) except Exception: # Else: woops, an error! errmsg = getErrorMsg() msg = STOP_THREAD_ERROR + errmsg context_connection.close_on_problem('%s, %s' % (className, msg)) writeErr('Exception in %s.' % className) writeErr(errmsg)
def call(self, *args, **kwargs): """ call(*args, **kwargs) Call the callable. Exceptions are caught and printed. """ if self.isdead(): return # Get function try: if self._ob: func = getattr(self._ob(), self._func) else: func = self._func except Exception: return # Call it try: return func(*args, **kwargs) except Exception: print('Exception while handling event:') print(getErrorMsg())
def _replier_iteration(self, package): """ _replier_iteration() Do one iteration: process one request. """ # Get request id request_id = package._dest_seq if request_id > REQREP_SEQ_REF: # Pre-request stuff # Remove offset request_id -= REQREP_SEQ_REF # Get action and pre request id action = package._data.decode('utf-8') # Remove pre-request from pending requests in case of both actions: # Cancel pending pre-request, prevent stacking of the same request. for prereq in [prereq for prereq in self._pre_requests]: if (package._source_id == prereq._source_id and package._dest_seq == prereq._dest_seq): self._pre_requests.remove(prereq) if action == 'req-': # Cancel current pre-request if (self._pre_request and package._source_id == self._pre_request._source_id and package._dest_seq == self._pre_request._dest_seq): self._pre_request = None elif action == 'req?': # New pre-request self._pre_requests.append(package) else: # We are asked to handle an actual request # We can reset the state self._pre_request = None # Get request request = self.message_from_bytes(package._data) # Get reply try: reply = self._handle_request(request) except Exception: reply = ERROR_OBJECT, getErrorMsg() print('yoton.RepChannel: error handling request:') print(reply[1]) # Send reply if True: try: bb = self.message_to_bytes(reply) self._send(bb, package._source_id, request_id) except IOError: pass # Channel is closed except Exception: # Probably wrong type of reply returned by handle_request() print('Warning: request could not be send:') print(getErrorMsg())
def _replier_iteration(self, package): """ _replier_iteration() Do one iteration: process one request. """ # Get request id request_id = package._dest_seq if request_id > REQREP_SEQ_REF: # Pre-request stuff # Remove offset request_id -= REQREP_SEQ_REF # Get action and pre request id action = package._data.decode('utf-8') # Remove pre-request from pending requests in case of both actions: # Cancel pending pre-request, prevent stacking of the same request. for prereq in [prereq for prereq in self._pre_requests]: if ( package._source_id == prereq._source_id and package._dest_seq == prereq._dest_seq): self._pre_requests.remove(prereq) if action == 'req-': # Cancel current pre-request if ( self._pre_request and package._source_id == self._pre_request._source_id and package._dest_seq == self._pre_request._dest_seq): self._pre_request = None elif action == 'req?': # New pre-request self._pre_requests.append(package) else: # We are asked to handle an actual request # We can reset the state self._pre_request = None # Get request request = self.message_from_bytes(package._data) # Get reply try: reply = self._handle_request(request) except Exception: reply = ERROR_OBJECT, getErrorMsg() print('yoton.RepChannel: error handling request:') print(reply[1]) # Send reply if True: try: bb = self.message_to_bytes(reply) self._send(bb, package._source_id, request_id) except IOError: pass # Channel is closed except Exception: # Probably wrong type of reply returned by handle_request() print('Warning: request could not be send:') print(getErrorMsg())