示例#1
0
	def run(self):
		self.debug_print(' runs on %s.' % currentThread(), 0)
		
		# Create one-and-only poll object:
		self._poll_obj = select.poll()
		poll_obj = self._poll_obj
		
		# Register each port's fd to correlate with incoming bytes for poll() triggering:
		poll_obj.register(self._com1_file, select.POLLIN)
		poll_obj.register(self._com2_file, select.POLLIN)
		
		# Enter thread's main loop:
		self.go = 1 # set to '0' only by other threads that want to stop this thread
		while self.go:
			# Enter the one-and-only wait state used by this RouterThread:
			evt_pairs = poll_obj.poll()
			self.debug_print('Event pairs received = %s' % evt_pairs, 0)
			
			buffer = array.array('B')
			for evt_pair in evt_pairs:
				if evt_pair[0] == self._com1_fd:
					buffer.fromstring(self._com1_file.read())
					buffer.tofile(self._com2_file)
				else:
					buffer.fromstring(self._com2_file.read())
					buffer.tofile(self._com1_file)
	
		# Unregister all of the fd's in the local dict from the poll() machinery:
		poll_obj.register(self._com1_file)
		poll_obj.register(self._com2_file)

		self.debug_print('on %s is ending run()...' % currentThread(), 0)
示例#2
0
    def run(self):
        self.debug_print(' runs on %s.' % currentThread(), 0)

        # Create one-and-only poll object:
        self._poll_obj = select.poll()
        poll_obj = self._poll_obj

        # Register each port's fd to correlate with incoming bytes for poll() triggering:
        poll_obj.register(self._com1_file, select.POLLIN)
        poll_obj.register(self._com2_file, select.POLLIN)

        # Enter thread's main loop:
        self.go = 1  # set to '0' only by other threads that want to stop this thread
        while self.go:
            # Enter the one-and-only wait state used by this RouterThread:
            evt_pairs = poll_obj.poll()
            self.debug_print('Event pairs received = %s' % evt_pairs, 0)

            buffer = array.array('B')
            for evt_pair in evt_pairs:
                if evt_pair[0] == self._com1_fd:
                    buffer.fromstring(self._com1_file.read())
                    buffer.tofile(self._com2_file)
                else:
                    buffer.fromstring(self._com2_file.read())
                    buffer.tofile(self._com1_file)

        # Unregister all of the fd's in the local dict from the poll() machinery:
        poll_obj.register(self._com1_file)
        poll_obj.register(self._com2_file)

        self.debug_print('on %s is ending run()...' % currentThread(), 0)
示例#3
0
 def start_tunnel(self):
     if self is not currentThread():
         self._send_cmd('start')
         return
     self._op_lock.acquire()
     try:
         self.is_active = 1
         # set up Port object for the tunnel that reads\writes to the 
         # slave device file of the pseudo-terminal pair. 
         if not self._serial_port:
             self._serial_port = Port()
         cfg = self._vcp.configuration()
         cfg['dev'] = self.tty
         cfg['name'] = '_slave'
         cfg['parent'] = self._vcp
         self._serial_port.configure(cfg)
         self._op_lock.release()
     except:
         self._op_lock.release()
     while self.is_active:
         if not self._serial_port.is_open():
             self._serial_port.open()
             self._serial_port.drain()
         try:
             if self.is_server:
                 self._do_listen()
             else:
                 self._do_connect()
         except:
             msglog.exception()
             if self._serial_port and not self._serial_port.is_open():
                 self._serial_port.close()
示例#4
0
 def user_from_current_thread(self):
     current_thread = threading.currentThread()
     active_request = getattr(current_thread, 'active_request', None)
     if active_request is None:
         raise TypeError('Current thread must be HTTP(S) request.')
     userobject = active_request.user_object()
     return self.user_from_object(userobject)
示例#5
0
 def test_1_debug_on(self):
     l = allocate1()
     if l.owner is not None:
         raise 'Broken debugging code.'
     if l in l.locked_list:
         raise 'Broken debugging code.'
     l.acquire()
     if l not in l.locked_list:
         raise 'Broken debugging code.'
     if l.owner != currentThread():
         raise 'Broken debugging code.'
     return
示例#6
0
 def stop_tunnel(self):
     self.is_active = 0
     if self is not currentThread():
         self._send_cmd('stop')
         if self._is_in_accept():
             self._clear_accept()
     else:
         self._op_lock.acquire()
         try:
             self._tear_down_fds()
         finally:
             self._op_lock.release()
示例#7
0
 def test_1_debug_on(self):
     l = allocate1()
     if l.owner is not None:
         raise "Broken debugging code."
     if l in l.locked_list:
         raise "Broken debugging code."
     l.acquire()
     if l not in l.locked_list:
         raise "Broken debugging code."
     if l.owner != currentThread():
         raise "Broken debugging code."
     return
示例#8
0
文件: feu.py 项目: mcruse/monotone
 def _get_next_feu_to_scan(self):
     thread_name = threading.currentThread().getName()
     feu = None
     self._lock.acquire()
     try:
         # Release existing FEU from this thread, back into scan_list:
         if self._FEU_active_map.has_key(thread_name):
             feu_old = self._FEU_active_map[thread_name]
             self._FEU_scan_list.append(feu_old)
             self._poll_obj.register(feu_old.parent.file.fileno(), select.POLLIN)
             del self._FEU_active_map[thread_name]
         # Remove head FEU from scan_list, into care of this thread:
         try:
             feu = self._FEU_scan_list.pop(0)
             if isinstance(feu, FEU): # could be string ("End")...
                 self._FEU_active_map[thread_name] = feu
                 self._poll_obj.unregister(feu.parent.file.fileno())
         except IndexError, e:
             pass
     finally:
         self._lock.release()
     return feu
示例#9
0
 def _prime_process_alarm_queue(self):
     # @todo Save queue in a PDO?
     thread = currentThread()
     self.__current_thread = thread
     self._process_alarm_queue(thread)
示例#10
0
	def run(self):
		self.debug_print(' runs on %s.' % currentThread(), 0)
		
		# Create one-and-only poll object:
		self._poll_obj = select.poll()
		
		# Register one-and-only fd for input events:
		self._fd = self._ir_node._file.fileno() # in case it changed without de/reconstruction of this thread obj
		self._poll_obj.register(self._fd, select.POLLIN)
		
		# Enter thread's main loop:
		total_bytes = 0
		avg_bytes_per_loop = 0
		loop_count = 0
		total_loop_time = 0
		avg_loop_time = 0
		macro_cnt = 500
		byte_threshold = 1000
		self.go = 1 # set to '0' only by other threads that want to stop this thread
		start_time = time.clock()
		
		while self.go:
			loop_count = loop_count + 1
			if (total_bytes > byte_threshold):
				temp_time = time.clock()
				macro_loop_time = temp_time - start_time
				#print 'macro_loop_time = ', macro_loop_time, 'temp_time = ', temp_time, 'start_time = ', start_time
				start_time = temp_time
				avg_loop_time = macro_loop_time / loop_count
				avg_bytes_per_loop = total_bytes / loop_count
				loop_count = 0 # reset
				total_bytes = 0 # reset
				burden = avg_loop_time / avg_bytes_per_loop
				#print 'avg_loop_time = ', avg_loop_time, 'avg_bytes_per_loop = ', avg_bytes_per_loop, 'burden per byte = ', burden
			
			# Enter the one-and-only wait state used by this RouterThread:
			evt_pairs = self._poll_obj.poll()
			self.debug_print('Event pairs received = %s' % evt_pairs, 1)
			
			# If no event pairs are returned by poll(), then an error must have occurred:
			if len(evt_pairs) == 0:
				self.debug_print('Timeout error detected for fd %d, %s.' % self._fd, 1)
			# Else, process event pairs:
			else:
				for evt_pair in evt_pairs:
					# Submit the kernel event(s) to the generating IW for processing, 
					# and act on the result:
					if evt_pair[1] == select.POLLIN:
						rd_str = self._file.read()
						total_bytes = total_bytes + len(rd_str)
						self._bytes_read = len(rd_str)
						for i in range(self._bytes_read):
							self._rd_buf[self._rd_buf_end_idx] = ord(rd_str[i])
							self._rd_buf_end_idx = (self._rd_buf_end_idx + 1) & 0xFF
						self.process_byte_rd()
					else:
						raise EInvalidValue('Event Type', evt_pair[1])

		self._poll_obj.unregister(self._fd)

		self.debug_print('on %s is ending run()...' % currentThread(), 0)
示例#11
0
    def run(self):
        self.debug_print(' runs on %s.' % currentThread(), 0)

        # Create one-and-only poll object:
        self._poll_obj = select.poll()
        poll_obj = self._poll_obj

        # Register each port's fd to correlate with incoming bytes for poll() triggering:
        iws_list = self._iws.values(
        )  # extract list of values from local IW dict
        for iw in iws_list:
            poll_obj.register(iw._file.fileno(), select.POLLIN)

        # Enter thread's main loop:
        total_bytes = 0
        avg_bytes_per_loop = 0
        loop_count = 0
        total_loop_time = 0
        avg_loop_time = 0
        macro_cnt = 2000
        self.go = 1  # set to '0' only by other threads that want to stop this thread
        start_time = time.clock()

        while self.go:
            loop_count = loop_count + 1
            if ((loop_count % macro_cnt) == 0):
                temp_time = time.clock()
                macro_loop_time = temp_time - start_time
                print 'macro_loop_time = ', macro_loop_time, 'temp_time = ', temp_time, 'start_time = ', start_time
                start_time = temp_time
                avg_loop_time = macro_loop_time / macro_cnt
                burden = avg_loop_time / avg_bytes_per_loop
                print 'avg_loop_time = ', avg_loop_time, 'avg_bytes_per_loop = ', avg_bytes_per_loop, 'burden per byte = ', burden

            #@fixme: Set timeouts:
            timeout_msec = -1

            # Enter the one-and-only wait state used by this RouterThread:
            self.debug_print('timeout_msec = %d' % timeout_msec, 0)
            evt_pairs = poll_obj.poll(timeout_msec)
            self.debug_print('Event pairs received = %s' % evt_pairs, 0)

            # If no event pairs are returned by poll(), then a timeout must have occurred:
            if len(evt_pairs) == 0:
                if not self._timeout_iw:
                    self.debug_print(
                        'Programming Error. poll() timed out without any responsible InterfaceWrapper!',
                        0)
                    raise EInvalidValue
                self.debug_print(
                    'Timeout detected for fd %d, %s.' %
                    (self._timeout_iw._file.fileno(), self._timeout_iw), 1)
                result = self._timeout_iw.handle_timeout(self._timeout_param)
                if result == 'erase':
                    self._erase(
                        self._timeout_iw,
                        'Timeout caused scan of data_skt %d, and it looks dead.'
                    )
                self._timeout_iw = None
                self._timeout_param = None
            # Else, process event pairs:
            else:
                for evt_pair in evt_pairs:
                    # Obtain the signaled IW from the local dict:
                    try:
                        iw_rd = self._iws[evt_pair[0]]
                    except KeyError:  # erasure ops below may have removed IW responsible for given evt_pair
                        self.debug_print(
                            'Ignoring event pair for closed fd %d' %
                            evt_pair[0], 0)
                        continue

                    # Submit the kernel event(s) to the generating IW for processing,
                    # and act on the result:
                    result = iw_rd.process_kernel_evt(evt_pair[1])
                    cmd = result[0]
                    if not cmd:
                        continue
                    elif cmd == 'send':
                        # Give iw_rd ref to Router, get back list of IWs to which to send
                        # reading IW's buffer:
                        iws_dest = self._router.send(iw_rd)
                        wr_buf = result[1]
                        total_bytes = total_bytes + len(wr_buf)
                        avg_bytes_per_loop = total_bytes / loop_count
                        if len(iws_dest) == 0:
                            continue
                        for iw_dest in iws_dest:
                            if iw_dest._file.fileno() < 0:
                                print 'Program error: IW %s has fd %d! Already closed/deleted!' % (
                                    iw_dest, iw_dest._file.fileno())
                                continue
                            try:
                                iw_dest.write(wr_buf)
                                print 'Sent pkt to %d' % iw_dest._file.fileno()
                            except:  # destination IW may have been closed already...
                                print 'Failed to write to fd %d: %s, %s' % (
                                    iw_dest._file.fileno(), sys.exc_type,
                                    sys.exc_value)
                                #self._erase(iw_dest, 'Failed to write to fd %d.')
                                continue
                        # If debugging, send notification of xmitted bytes to console:
                        self.debug_print(
                            'Xmitted byte array from fd %d:' %
                            iw_rd._file.fileno(), 0)
                        if debug_lvl > 1:
                            print_array_as_hex(iw_rd._rd_buf)
                        iw_rd._rd_buf = array.array(
                            'B')  # clear the read buf of the current IW
                    elif cmd == 'new_iw':
                        # We have another data_skt to poll, so register it and add it into the local dict:
                        new_iw = result[1]
                        data_skt_fd = new_iw._file.fileno()
                        self._iws[data_skt_fd] = new_iw
                        self._router.add_interface_wrap(new_iw)
                        poll_obj.register(data_skt_fd, select.POLLIN)
                        self.debug_print(
                            'Input event on listen_skt %d => data_skt %d.' %
                            (iw_rd._file.fileno(), data_skt_fd), 0)
                        continue  # connection established, but no data to process yet
                    elif cmd == 'mon_iw':
                        # We have a data_skt from which to echo incoming bytes/pkts:
                        self._mon_skt = result[1]
                        data_skt_fd = self._mon_skt._file.fileno()
                        self._iws[data_skt_fd] = self._mon_skt
                        self._router.add_interface_wrap(self._mon_skt)
                        poll_obj.register(
                            data_skt_fd, select.POLLIN
                        )  # no input expected from this mon_skt (yet), but be prepared...
                        self.debug_print(
                            'Input event on listen_skt %d => mon_skt %d.' %
                            (iw_rd._file.fileno(), data_skt_fd), 0)
                        continue  # connection established
                    elif cmd == 'erase':
                        # IW determined it was not worthy of existence, so squish it:
                        self._erase(iw_rd, result[1])
                        continue
                    else:
                        self.debug_print(
                            'Unknown result from InterfaceWrap.process_kernel_evt(): %s'
                            % str(result), 0)
                        raise EInvalidValue(
                            'Result from InterfaceWrap.process_kernel_evt()',
                            str(result))

        # Unregister all of the fd's in the local dict from the poll() machinery:
        iw_fds_list = self._iws.keys()
        for iw_fd in iw_fds_list:
            poll_obj.unregister(iw_fd)

        self.debug_print('on %s is ending run()...' % currentThread(), 0)
示例#12
0
	def run(self):
		self.debug_print(' runs on %s.' % currentThread(), 0)
		
		# Create one-and-only poll object:
		self._poll_obj = select.poll()
		poll_obj = self._poll_obj
		
		# Register each port's fd to correlate with incoming bytes for poll() triggering:
		iws_list = self._iws.values() # extract list of values from local IW dict
		for iw in iws_list:
			poll_obj.register(iw._file.fileno(), select.POLLIN)
		
		# Enter thread's main loop:
		total_bytes = 0
		avg_bytes_per_loop = 0
		loop_count = 0
		total_loop_time = 0
		avg_loop_time = 0
		macro_cnt = 2000
		self.go = 1 # set to '0' only by other threads that want to stop this thread
		start_time = time.clock()
		
		while self.go:
			loop_count = loop_count + 1
			if ((loop_count % macro_cnt) == 0):
				temp_time = time.clock()
				macro_loop_time = temp_time - start_time
				print 'macro_loop_time = ', macro_loop_time, 'temp_time = ', temp_time, 'start_time = ', start_time
				start_time = temp_time
				avg_loop_time = macro_loop_time / macro_cnt
				burden = avg_loop_time / avg_bytes_per_loop
				print 'avg_loop_time = ', avg_loop_time, 'avg_bytes_per_loop = ', avg_bytes_per_loop, 'burden per byte = ', burden
				
			#@fixme: Set timeouts:
			timeout_msec = -1
				
			# Enter the one-and-only wait state used by this RouterThread:
			self.debug_print('timeout_msec = %d' % timeout_msec, 0)
			evt_pairs = poll_obj.poll(timeout_msec)
			self.debug_print('Event pairs received = %s' % evt_pairs, 0)
			
			# If no event pairs are returned by poll(), then a timeout must have occurred:
			if len(evt_pairs) == 0:
				if not self._timeout_iw:
					self.debug_print('Programming Error. poll() timed out without any responsible InterfaceWrapper!', 0)
					raise EInvalidValue
				self.debug_print('Timeout detected for fd %d, %s.' % (self._timeout_iw._file.fileno(), self._timeout_iw), 1)
				result = self._timeout_iw.handle_timeout(self._timeout_param)
				if result == 'erase':
					self._erase(self._timeout_iw, 'Timeout caused scan of data_skt %d, and it looks dead.')
				self._timeout_iw = None
				self._timeout_param = None
			# Else, process event pairs:
			else:
				for evt_pair in evt_pairs:
					# Obtain the signaled IW from the local dict:
					try:
						iw_rd = self._iws[evt_pair[0]]
					except KeyError: # erasure ops below may have removed IW responsible for given evt_pair
						self.debug_print('Ignoring event pair for closed fd %d' % evt_pair[0], 0)
						continue
						
					# Submit the kernel event(s) to the generating IW for processing, 
					# and act on the result:
					result = iw_rd.process_kernel_evt(evt_pair[1])
					cmd = result[0]
					if not cmd:
						continue
					elif cmd == 'send':
						# Give iw_rd ref to Router, get back list of IWs to which to send 
						# reading IW's buffer:
						iws_dest = self._router.send(iw_rd)
						wr_buf = result[1]
						total_bytes = total_bytes + len(wr_buf)
						avg_bytes_per_loop = total_bytes / loop_count
						if len(iws_dest) == 0:
							continue
						for iw_dest in iws_dest:
							if iw_dest._file.fileno() < 0:
								print 'Program error: IW %s has fd %d! Already closed/deleted!' % (iw_dest, iw_dest._file.fileno())
								continue
							try:
								iw_dest.write(wr_buf)
								print 'Sent pkt to %d' % iw_dest._file.fileno()
							except: # destination IW may have been closed already...
								print 'Failed to write to fd %d: %s, %s' % (iw_dest._file.fileno(), sys.exc_type, sys.exc_value)
								#self._erase(iw_dest, 'Failed to write to fd %d.')
								continue
						# If debugging, send notification of xmitted bytes to console:
						self.debug_print('Xmitted byte array from fd %d:' % iw_rd._file.fileno(), 0)
						if debug_lvl > 1:
							print_array_as_hex(iw_rd._rd_buf)
						iw_rd._rd_buf = array.array('B') # clear the read buf of the current IW
					elif cmd == 'new_iw':
						# We have another data_skt to poll, so register it and add it into the local dict:
						new_iw = result[1]
						data_skt_fd = new_iw._file.fileno()
						self._iws[data_skt_fd] = new_iw
						self._router.add_interface_wrap(new_iw)
						poll_obj.register(data_skt_fd, select.POLLIN)
						self.debug_print('Input event on listen_skt %d => data_skt %d.' % (iw_rd._file.fileno(), data_skt_fd), 0)
						continue # connection established, but no data to process yet
					elif cmd == 'mon_iw':
						# We have a data_skt from which to echo incoming bytes/pkts:
						self._mon_skt = result[1]
						data_skt_fd = self._mon_skt._file.fileno()
						self._iws[data_skt_fd] = self._mon_skt
						self._router.add_interface_wrap(self._mon_skt)
						poll_obj.register(data_skt_fd, select.POLLIN) # no input expected from this mon_skt (yet), but be prepared...
						self.debug_print('Input event on listen_skt %d => mon_skt %d.' % (iw_rd._file.fileno(), data_skt_fd), 0)
						continue # connection established
					elif cmd == 'erase':
						# IW determined it was not worthy of existence, so squish it:
						self._erase(iw_rd, result[1])
						continue
					else:
						self.debug_print('Unknown result from InterfaceWrap.process_kernel_evt(): %s' % str(result), 0)
						raise EInvalidValue('Result from InterfaceWrap.process_kernel_evt()', str(result))
		
		# Unregister all of the fd's in the local dict from the poll() machinery:
		iw_fds_list = self._iws.keys()
		for iw_fd in iw_fds_list:
			poll_obj.unregister(iw_fd)

		self.debug_print('on %s is ending run()...' % currentThread(), 0)
示例#13
0
    def run(self):
        self.debug_print(" runs on %s." % currentThread(), 0)

        # Create one-and-only poll object:
        self._poll_obj = select.poll()

        # Register one-and-only fd for input events:
        self._fd = self._ir_node._file.fileno()  # in case it changed without de/reconstruction of this thread obj
        self._poll_obj.register(self._fd, select.POLLIN)

        # Enter thread's main loop:
        total_bytes = 0
        avg_bytes_per_loop = 0
        loop_count = 0
        total_loop_time = 0
        avg_loop_time = 0
        macro_cnt = 500
        byte_threshold = 1000
        self.go = 1  # set to '0' only by other threads that want to stop this thread
        start_time = time.clock()

        while self.go:
            loop_count = loop_count + 1
            if total_bytes > byte_threshold:
                temp_time = time.clock()
                macro_loop_time = temp_time - start_time
                # print 'macro_loop_time = ', macro_loop_time, 'temp_time = ', temp_time, 'start_time = ', start_time
                start_time = temp_time
                avg_loop_time = macro_loop_time / loop_count
                avg_bytes_per_loop = total_bytes / loop_count
                loop_count = 0  # reset
                total_bytes = 0  # reset
                burden = avg_loop_time / avg_bytes_per_loop
                # print 'avg_loop_time = ', avg_loop_time, 'avg_bytes_per_loop = ', avg_bytes_per_loop, 'burden per byte = ', burden

                # Enter the one-and-only wait state used by this RouterThread:
            evt_pairs = self._poll_obj.poll()
            self.debug_print("Event pairs received = %s" % evt_pairs, 1)

            # If no event pairs are returned by poll(), then an error must have occurred:
            if len(evt_pairs) == 0:
                self.debug_print("Timeout error detected for fd %d, %s." % self._fd, 1)
                # Else, process event pairs:
            else:
                for evt_pair in evt_pairs:
                    # Submit the kernel event(s) to the generating IW for processing,
                    # and act on the result:
                    if evt_pair[1] == select.POLLIN:
                        rd_str = self._file.read()
                        total_bytes = total_bytes + len(rd_str)
                        self._bytes_read = len(rd_str)
                        for i in range(self._bytes_read):
                            self._rd_buf[self._rd_buf_end_idx] = ord(rd_str[i])
                            self._rd_buf_end_idx = (self._rd_buf_end_idx + 1) & 0xFF
                        self.process_byte_rd()
                    else:
                        raise EInvalidValue("Event Type", evt_pair[1])

        self._poll_obj.unregister(self._fd)

        self.debug_print("on %s is ending run()..." % currentThread(), 0)
示例#14
0
 def _prime_process_alarm_queue(self):
     # @todo Save queue in a PDO?
     thread = currentThread()
     self.__current_thread = thread
     self._process_alarm_queue(thread)