Beispiel #1
0
def run():
    # have to init the damn display system to use sound, ugh
    pygame.display.init()
    # start the server thread with a timeout value
    # pygame event loop
    while 1:
        # poll asyncore
        asyncore.poll(0.005)
        # look for an event
        event = pygame.event.poll()
        if event.type == pygame.NOEVENT:
            # nothing to read
            continue
        elif event.type == pygame.locals.QUIT:
            # exit the event loop
            return
        else:
            # treat all other events as player completion
            # pass them to channel based on event type 
            # would be much easier if we could specify sound event properties...
            ch = channel.getChannelFromId(event.type)
            try:
                ch.onPlayerComplete()
            except Exception, e:
                print e
Beispiel #2
0
def main():
    import sys
    import threading
    import traceback
    if len(sys.argv) < 3:
        print usage
        return
    HOST = sys.argv[1]
    try:
        PORT = int(sys.argv[2])
    except ValueError:
        print "invalid port"
        print usage
        return
    msg_queue = []
    def printfunc(s): print s
    client = BrokerClient(HOST, PORT)
    client.subscribe(lambda topic, message: printfunc("%s: %s" % (topic, message)))
    client.Connect()
    while True:
        x = raw_input("> ")
        if x:
            try:
                eval(x)
            except KeyboardInterrupt:
                return
            except:
                traceback.print_exc()
        asyncore.poll()
Beispiel #3
0
    def run(self, check_deadlock_fn=None, poll_timeout=1.0, ttl=None):
        """
        Runs the polling loop. This does not create any separate processes or
        threads, and it only returns after all handlers and the server itself
        have been closed. For debugging purposes, we can also specify a time-
        to-live (ttl), which specifies the number of seconds that the server
        and server handlers are allowed to run before they are forcibly closed.

        This is a monkeypatched version of asyncore.loop(). This was the
        cleanest way to add the deadlock detector and ttl.
        """
        if check_deadlock_fn is None:
            check_deadlock_fn = lambda get_count, put_count: True
        start_time = time.time()
        timed_out = False
        while len(asyncore.socket_map) > 0:
            elapsed_time = time.time() - start_time
            if ttl is not None and elapsed_time > ttl:
                timed_out = True
                break
            new_poll_timeout = self.get_poll_timeout(poll_timeout, ttl, elapsed_time)
            # Run select syscall and readable() and writable() on all handlers,
            # then run handle_read() and handle_write() on appropriate handlers
            asyncore.poll(new_poll_timeout, asyncore.socket_map)
            if check_deadlock_fn(self._stats[0], self._stats[1]):
                abort_id = self._coordinator.detect_deadlocks()
                if abort_id is not None:
                    self._txn_map[abort_id].deadlock_abort()
        for fd, obj in asyncore.socket_map.items():
            if obj != self:
                obj.close()
        self.close()
        self._logger.debug('No more open connections')
        if timed_out:
            raise KVStoreError('Server timed out')
Beispiel #4
0
 def go (self, timeout=30.0, granularity=15):
     global socket_map
     last_event_check = 0
     while socket_map:
         now = int(time.time())
         if (now - last_event_check) >= granularity:
             last_event_check = now
             fired = []
             # yuck. i want my lisp.
             i = j = 0
             while i < len(self.events):
                 when, what = self.events[i]
                 if now >= when:
                     fired.append (what)
                     j = i + 1
                 else:
                     break
                 i = i + 1
             if fired:
                 self.events = self.events[j:]
                 for what in fired:
                     what (self, now)
         # sample the number of channels
         n = len(asyncore.socket_map)
         self.num_channels = n
         if n > self.max_channels:
             self.max_channels = n
         asyncore.poll (timeout)
Beispiel #5
0
    def runFuncs(self, tSlice=SLEEP_TIME):
        asyncore.poll(tSlice)
        self.evScheduler.poll()

        # asyncore won't block for timeout if it's not waiting on anything
        if not asyncore.socket_map:
            time.sleep(tSlice)
Beispiel #6
0
 def poll(self):
     """Polls asyncore if serving,
        checks the attribute self.serving, turning on listenning
        if True, or off if false"""
     if not self._engine_available:
         return
     if self._serving:
         # The server is listenning
         if not self.serving:
             # A request has been made to turn off the server
             self.stop_serving()
             return
         # poll asyncore and the connections
         asyncore.poll()
         # Poll each connection to run timers
         connection_list = self.get_connections_list()
         for connection in connection_list:
             connection.poll()
             asyncore.poll()
         return
     # self._serving must be False, but maybe self.serving has been set
     if self.serving:
         # The server is not serving, but the attribute
         # self.serving is True, so a request
         # has been made to turn on the server
         self.start_serving()
	def Pump(self):
		if not self.exitFlag:
			poll()
			self.poller.Pump()
			self.udplistener.Pump()
			PdServer.Pump(self)
		return not self.exitFlag
Beispiel #8
0
 def run(self):
     cfg = self.session.config.sys.smtpd
     if cfg.host and cfg.port:
         server = SMTPServer(self.session, (cfg.host, cfg.port))
         while not self.quitting:
             asyncore.poll(timeout=1.0)
         asyncore.close_all()
Beispiel #9
0
    def run(self):
        """
        Thread main part
        """

##        testlink = threading.Timer(3.0,gprs_source.writeTest)
##        testlink.start()
        while not self.exitEvent.isSet(): 
            asyncore.poll(0.5) # socket IO
            try: ## lower device IO
                for i in self.device: #如果连接网关的本地客户端不为空,那么循环读取数据,发送命令
                    try:
                        pkts = i.readPackets()#返回的就是python字典形式的包
                    except:
                        pass
                    else:
                        if pkts:
                            self.clientMessageSource.setMessage(pkts)
                    command = self.clientMessageSource.getLowerPacket()
                    
                    print "+++++++"+str(command)
                    i.writePackets(command)
 
            except:
                type, value, tb = sys.exc_info()
                print traceback.format_exception(type, value, tb)
                pass
Beispiel #10
0
def server_loop(map):
    while len(map) > 1:
        try:
            asyncore.poll(30.0, map)
        except Exception, v:
            if v.args[0] != errno.EBADF:
                raise
Beispiel #11
0
 def runDispatcher(self, timeout=0.0):
     while ( self.jobsArePending() or self.transportsAreWorking()) and self.thread_stop == False:
         from asyncore import poll
         from time import time
         poll(timeout and timeout or self.timeout, self.getSocketMap())
         self.handleTimerTick(time())
     print 'quit from runDispatcher'
Beispiel #12
0
def main(argv):
    url = argv[1]
    test(url)
    while 1:
        asyncore.poll(scheduler.timeout())
        # print "\n\n asyncore.poll \n"
        scheduler.run()
Beispiel #13
0
def main():
    formatter = optparse.IndentedHelpFormatter(max_help_position=30)
    parser = optparse.OptionParser(
                    version='%prog ' + str(VERSION),
                    usage='usage: python %prog [options] args...',
                    formatter=formatter)
    parser.add_option('-d', '--debug',
            action="store_true", default=False,
            help='enable printing debug information')
    parser.add_option('--conf', type='string', default='.',
            help=('path to vimoir.properties directory (default \'%default\')'))
    (options, sys.argv) = parser.parse_args(args=sys.argv)
    setup_logger(options.debug)
    props_file = os.path.join(options.conf, 'vimoir.properties')
    opts = load_properties(props_file)

    Server(opts.get('vimoir.netbeans.host'), opts.get('vimoir.netbeans.port'),
                                                                    props_file)
    timeout = int(opts.get('vimoir.netbeans.timeout')) / 1000.0
    user_interval = (int(opts.get('vimoir.netbeans.user_interval')) / 1000.0)
    last = time.time()
    while asyncore.socket_map:
        asyncore.poll(timeout=timeout)

        # Send the timer events.
        now = time.time()
        if (now - last >= user_interval):
            last = now
            for obj in asyncore.socket_map.values():
                obj.handle_tick()

    # Terminate all Phonemic threads by exiting.
    sys.exit(0)
Beispiel #14
0
	def test_TCP(self):
		""" Test encoding and decoding of a message through two TCP transports """
		msg = self.newMsg()
		server = TCPServer('127.0.0.1', 10101)
		tx = TestTCPTransport(address='127.0.0.1', port=10101)

		# connect them, socketpair on linux doesn't work with AF_INET
		count = 0
		while True:
			asyncore.poll(0.1, {server.fileno():server, tx.fileno():tx})
			if len(server.inmessages) > 0:
				rx = server.inmessages[0]
				break
			count += 1
			self.assertLess(count, 5, 'connect failed')


		# Try different send/receive sizes to confirm there are no segment boundary issues
		mymap = { rx.fileno():rx, tx.fileno():tx }
		for ii in range(1, 100, 1):
			rx.RXSIZE = ii
			tx.TXSIZE = ii
			rx.inmessages = []
			tx.outmessages.append(msg)
			if not self.runAsync(mymap, rx, msg, 106-ii):
				self.assert_(False, "Poll called too many times for TCP with size %d" % ii)
			self.assertMessageEqual(rx.inmessages[0], msg)

		tx.close()
		rx.close()
Beispiel #15
0
	def test_SSL(self):
		""" Test encoding and decoding of a message through two SSL transports """
		# TCP tests already do the mass of different byte sizing for tx/rx, this is just basic SSL tests
		cafile = os.path.join(os.path.dirname(__file__), 'ca.pem')
		nodefile = os.path.join(os.path.dirname(__file__), 'node.pem')
		msg = self.newMsg()
		server = SSLServer(address='127.0.0.1', port=10102, cafile=cafile, nodefile=nodefile, matchingOU="DeterTest.bwilson-orch")
		tx = SSLTransport(address='127.0.0.1', port=10102, cafile=cafile, nodefile=nodefile, matchingOU="DeterTest.bwilson-orch")
		# match name to pem files in test
		
		# connect them, socketpair on linux doesn't work with AF_INET
		count = 0
		while True:
			asyncore.poll(0.1, {server.fileno():server, tx.fileno():tx})
			if len(server.inmessages) > 0:
				rx = server.inmessages[0]
				break
			count += 1
			self.assertLess(count, 5, 'connect failed')

		# Do a simple one time test, let TCP do the range of sizes
		mymap = { rx.fileno():rx, tx.fileno():tx }
		rx.inmessages = []
		tx.outmessages.append(msg)
		if not self.runAsync(mymap, rx, msg, 10):
			self.assert_(False, "Poll called too many times for SSL")
		self.assertMessageEqual(rx.inmessages[0], msg)

		tx.close()
		rx.close()
Beispiel #16
0
def main(argv, env):
    global USER
    
    USER = None
    
    nick = argv[1]
    host = argv[2]
    port = int(argv[3])
    avatar = argv[4]
    command = string.join(argv[5:])

    # Open a pipe to the command    
    pipe = expect.popen(command, 'b')
    c = BotClient(nick, pipe)
    server = OpenVerse.ServerConnection(host, port, c, nick, avatar)
    c.set_server(server)
    #asyncore.poll(5)
    #asyncore.poll(5)
    #server.chat('Lah hello')
    while 1:
        asyncore.poll(5)
        try:
            data = string.strip(c.pipe.read())
            print data
        except: 
            print 'crashed'
            pipe = expect.popen(command, 'b')
            c.pipe = pipe
        else:
            #print >> sys.stderr, data
            if data and USER:
                for line in string.split(data, '\n'):
                    server.chat('%s: %s' % (USER, line))
            
                USER = None
Beispiel #17
0
 def __call__(self, msg):
     try: self.plugin.reader.sbuffer
     except AttributeError:
        self.plugin.HandleWarning(self.text.acterrormsg)
     else:
        self.plugin.reader.sbuffer = msg + "\n"
        asyncore.poll()
Beispiel #18
0
	def run(self):
#		import cProfile
#		cProfile.runctx('self.runX()', globals(), locals(), '/tmp/cprofile_worker')
#	
#	def runX(self):
		"""
			Run the sockets thread.  Infinite loop:
			- run the scheduler and events, returns the time until the next future event
			- wait for that amount of time (max 1/10th second) for events on any open sockets
		"""
		self.threadId = helpers.getThreadId()
		log.info("Worker started. Thread id: " + str(self.threadId))

		#when = time.time() + 30
		#while time.time() < when:
		self.done = False
		while not self.done:
			try:
				timeout = min(0.2, self.scheduler.run()) # Max 0.2 second sleep, maybe less, we can't wait on Queue.Queue so we have to poll it
				if len(self.pollMap) <= 0:
					time.sleep(timeout)
				else:
					asyncore.poll(timeout, self.pollMap)  # poll appears to be a little faster than poll2
				self.loop()
			except:
				if log is None:
					return  # We shutdown and all my variables are disappearing
				log.error("Failed in router thread: %s", sys.exc_info()[1], exc_info=True)
				time.sleep(0.5) # Don't jump into a super loop on repeatable errors
				
		log.info("Worker stopped")
Beispiel #19
0
    def test_send(self):
        self.evt = threading.Event()
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(3)
        self.port = test_support.bind_port(self.sock)

        cap = StringIO()
        args = (self.evt, cap, self.sock)
        threading.Thread(target=capture_server, args=args).start()

        # wait a little longer for the server to initialize (it sometimes
        # refuses connections on slow machines without this wait)
        time.sleep(0.2)

        data = "Suppose there isn't a 16-ton weight?"
        d = dispatcherwithsend_noread()
        d.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        d.connect((HOST, self.port))

        # give time for socket to connect
        time.sleep(0.1)

        d.send(data)
        d.send(data)
        d.send("\n")

        n = 1000
        while d.out_buffer and n > 0:
            asyncore.poll()
            n -= 1

        self.evt.wait()

        self.assertEqual(cap.getvalue(), data * 2)
Beispiel #20
0
    def OnPoll(self, event):       

        # handle keyboard input
        keys = self.throttleControl.key_mapping.keys()
        for key in keys:
            key_ord = ord(key)

            if self.keypress.get(key_ord, None) == 1:
                self.throttleControl.key_mapping[key]()
                self.leftThrottle.SetValue(self.throttleControl.throttle['left'])
                self.rightThrottle.SetValue(self.throttleControl.throttle['right'])
        
        # socket work
        asyncore.poll(timeout=0)
        if self.proxy_connection != False:
            if self.proxy_connection.is_open() == False:
                if time.clock() - self.clock < 5: return
                self.clock = time.clock()                
                self.proxy_connection = ProxyConnection(robotserver['host'], int(robotserver['port']))  
                                
            if self.proxy_connection.is_open() == True:
                # send and receive socket data
                self.proxy_connection.write(
                    "rpmset," + 
                    str(int(self.throttleControl.throttle['left']) * 100) + "," + 
                    str(int(self.throttleControl.throttle['right']) * 100))
                
                self.counter += 1
                if self.counter < 5: return 
                self.proxy_connection.write('get_status')
                self.counter = 0
Beispiel #21
0
    def setUp(self):
        super(LoopTestMixin, self).setUp()
        td = self.td = ThreadedTaskDispatcher()
        td.setThreadCount(self.task_dispatcher_count)
        if len(asyncore.socket_map) != 1:  # pragma: no cover
            # Let sockets die off.
            # (tests should be more careful to clear the socket map, and they
            # currently do, but let's keep this backstop just in case, to avoid
            # confusing failures).
            gc.collect()
            asyncore.poll(0.1)
        self.orig_map_size = len(asyncore.socket_map)

        self.server = self._makeServer()

        if self.CONNECT_TO_PORT == 0:
            self.port = self.server.socket.getsockname()[1]
        else: # pragma: no cover
            self.port = self.CONNECT_TO_PORT
        self.run_loop = 1
        self.counter = 0
        self.thread_started = Event()
        self.thread = Thread(target=self.loop, name=self.thread_name)
        self.thread.setDaemon(True)
        self.thread.start()
        self.thread_started.wait(10.0)
        self.assertTrue(self.thread_started.isSet())
Beispiel #22
0
 def run(self):
     "Start the loop."
     last_event_check = 0
     self._running = True
     while (self.socket_map or self.events) and self._running:
         self._now = time.time()
         if (self._now - last_event_check) >= self.granularity:
             last_event_check = self._now
             for event in self.events:
                 when, what = event
                 if self._now >= when:
                     try:
                         self.events.remove(event)
                     except ValueError: 
                         # a previous event may have removed this one.
                         continue
                     what()
                 else:
                     break
         # sample the number of channels
         n = len(self.socket_map)
         self.num_channels = n
         if n > self.max_channels:
             self.max_channels = n
         asyncore.poll(self.timeout) # TODO: use poll2 when available
Beispiel #23
0
def run_loop():
  global must_exit
  global in_pipe
  global out_pipe
  global needs_flush
  global flush_pipes
  gc_check_count = 0
  last_activity = time.clock()
  # disable gc to avoid pauses during traffic shaping/proxying
  gc.disable()
  while not must_exit:
    asyncore.poll(0.001, asyncore.socket_map)
    if needs_flush:
      flush_pipes = True
      needs_flush = False
    if in_pipe.tick():
      last_activity = time.clock()
    if out_pipe.tick():
      last_activity = time.clock()
    if flush_pipes:
      PrintMessage('OK')
      flush_pipes = False
    # Every 500 loops (~0.5 second) check to see if it is a good time to do a gc
    if gc_check_count > 1000:
      gc_check_count = 0
      # manually gc after 5 seconds of idle
      if time.clock() - last_activity >= 5:
        last_activity = time.clock()
        logging.debug("Triggering manual GC")
        gc.collect()
    else:
      gc_check_count += 1
Beispiel #24
0
 def loop(self):
     self.thread_started.set()
     import select
     from errno import EBADF
     while self.run_loop:
         self.counter = self.counter + 1
         # Note that it isn't acceptable to fail out of
         # this loop. That will likely make the tests hang.
         try:
             asyncore.poll(0.1)
         except select.error as data: # pragma: no cover
             print("EXCEPTION POLLING IN LOOP(): %s" % data)
             if data.args[0] == EBADF:
                 for key in asyncore.socket_map:
                     print("")
                     try:
                         select.select([], [], [key], 0.0)
                     except select.error as v:
                         print("Bad entry in socket map %s %s" % (key, v))
                         print(asyncore.socket_map[key])
                         print(asyncore.socket_map[key].__class__)
                         del asyncore.socket_map[key]
                     else:
                         print("OK entry in socket map %s" % key)
                         print(asyncore.socket_map[key])
                         print(asyncore.socket_map[key].__class__)
                     print("")
         except: # pragma: no cover pylint:disable=bare-except
             print("WEIRD EXCEPTION IN LOOP")
             traceback.print_exception(*(sys.exc_info()+(100,)))
    def test_snmp_get(self):
        self.simulator.add_walkfile(WALK_FILE)

        def cbFun(sendRequestHandle, errorIndication, errorStatus, errorIndex, varBinds, cbCtx):
            if errorIndication or errorStatus:
                raise Exception('SNMP error!')

            oid, val = varBinds[0]
            assert oid.prettyPrint() == '1.3.6.1.2.1.1.1.0'
            assert val.prettyPrint().startswith('Cisco')

        cmdGen = cmdgen.AsynCommandGenerator()
        cmdGen.getCmd(
            cmdgen.CommunityData('public'),
            cmdgen.UdpTransportTarget(('127.0.0.1', 1161)),
            (cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0),),
            (cbFun, None)
        )
        simulator_snmpEngine = self.simulator.snmp_agent.snmpEngine
        while cmdGen.snmpEngine.transportDispatcher.jobsArePending() or cmdGen.snmpEngine.transportDispatcher.transportsAreWorking():
            asyncore.poll(0.001, cmdGen.snmpEngine.transportDispatcher.getSocketMap())
            cmdGen.snmpEngine.transportDispatcher.handleTimerTick(time.time())

            asyncore.poll(0.001, simulator_snmpEngine.transportDispatcher.getSocketMap())
            simulator_snmpEngine.transportDispatcher.handleTimerTick(time.time())
Beispiel #26
0
def graceful_shutdown_loop():
    # The shutdown loop. Allow various services to shutdown gradually.
    global _shutdown_phase
    timestamp = time.time()
    timeout = 1.0
    map = asyncore.socket_map
    while map and _shutdown_phase < 4:
        time_in_this_phase = time.time()-timestamp 
        veto = 0
        for fd,obj in map.items():
            try:
                fn = getattr(obj,'clean_shutdown_control')
            except AttributeError:
                pass
            else:
                try:
                    veto = veto or fn(_shutdown_phase,time_in_this_phase)
                except:
                    obj.handle_error()
        if veto and time_in_this_phase<_shutdown_timeout:
            # Any open socket handler can veto moving on to the next shutdown
            # phase.  (but not forever)
            asyncore.poll(timeout, map)
        else:
            # No vetos? That is one step closer to shutting down
            _shutdown_phase += 1
            timestamp = time.time()
Beispiel #27
0
    def loop(self):
        self.thread_started.set()
        import select
        from errno import EBADF

        while self.run_loop:
            self.counter = self.counter + 1
            # Note that it isn't acceptable to fail out of
            # this loop. That will likely make the tests hang.
            try:
                asyncore.poll(0.1)
                continue
            except select.error, data:
                print "EXCEPTION POLLING IN LOOP(): ", data
                if data[0] == EBADF:
                    for key in asyncore.socket_map.keys():
                        print
                        try:
                            select.select([], [], [key], 0.0)
                        except select.error, v:
                            print "Bad entry in socket map", key, v
                            print asyncore.socket_map[key]
                            print asyncore.socket_map[key].__class__
                            del asyncore.socket_map[key]
                        else:
                            print "OK entry in socket map", key
                            print asyncore.socket_map[key]
                            print asyncore.socket_map[key].__class__
                        print
def asyncoreListenWait(delay):
    if asyncore.socket_map:
        asyncore.poll(delay)
    else:
        # asyncore.poll() returns immediately if there are no sockets to watch;
        # avoid busy loop
        time.sleep(delay)
Beispiel #29
0
def run(url, requests, concurrency, qg):
    if (concurrency > requests):
        concurrency = requests

    remaining = requests

    conns = []
    queries_durations = {}
    if url.startswith('tcp:'):
        url = url[4:]
        addr = url.split(':')[0]
        port = int(url.split(':')[1])
    else:
        return

    for x in xrange(0, concurrency):
        conns.append(LSAsynConnection(addr=addr, port=port))
        (query_class, query_str) = qg.get()
        q = Query(query_str)
        q.query_class = query_class
        conns[x].stack_query(q)

    print "Start queries"
    t = time.time()
    while remaining > 0:
        asyncore.poll(timeout=1)
        for c in conns:
            if c.is_finished():
                # Store query duration to compute stats
                q = c.results.pop()
                duration = q.duration
                if q.query_class not in queries_durations:
                    queries_durations[q.query_class] = []
                queries_durations[q.query_class].append(q.duration)
                sys.stdout.flush()
                remaining -= 1

                # Print a dot every 10 completed queries
                if (remaining % 10 == 0):
                    print '.',
                    sys.stdout.flush()

                # Run another query
                (query_class, query_str) = qg.get()
                q = Query(query_str)
                q.query_class = query_class
                c.stack_query(q)
    running_time = time.time() - t
    print "End queries"

    print "\n==============="
    print "Execution report"
    print "==============="
    print "Running time is %04f s" % running_time
    print "Query Class          nb  min      max       mean     median"
    for query_class, durations in queries_durations.items():
        print "%s %03d %03f %03f %03f %03f" % (query_class.ljust(20), len(durations),
                                               min(durations), max(durations), mean(durations),
                                               median(durations))
Beispiel #30
0
 def Update(self):
     poll(map=self._map)
     stdin = self.pd.recv()
     stderr = self.pd.recv_err()
     if stdin:
         [self.CheckStart(t) for t in cr.split(stdin) if t]
     if stderr:
         [self.Error(t) for t in cr.split(stderr) if t]
Beispiel #31
0
def server_loop(map):
    while len(map) > 1:
        try:
            asyncore.poll(30.0, map)
        except Exception as v:
            if v.args[0] != errno.EBADF:
                raise

    for o in tuple(map.values()):
        o.close()
def asyncore_loop():
    # Make sure only one invocation is active at any time
    assert asyncore_loop.running == False
    asyncore_loop.running = True
    try:
        while len(asyncore.socket_map):
            asyncore.poll(0.05)
            stackless.schedule()
    finally:
        asyncore_loop.running = False
Beispiel #33
0
def loop():
    while 1:
        while not to_network.empty():
            message = to_network.get()
            #process and handle message
            #
            #remember to validate any possible
            #socket objects recieved from the GUI,
            #they could already be closed
        asyncore.poll(timeout=.01)
Beispiel #34
0
def ManageSockets():
    global managerRunning

    while len(asyncore.socket_map):
        # Check the sockets for activity.
        asyncore.poll(0.05)
        # Yield to give other tasklets a chance to be scheduled.
        Tasklet.sleep(0.01)

    managerRunning = False
Beispiel #35
0
 def looper(self):
     """ looper проверяет не наступил ли таймаут подключения и
     собирает данные с async_chat. Завязан на таймер self.timer
     """
     ex_time = datetime.now() - self.start_time
     ex_time = ex_time.total_seconds()
     if (ex_time > 20) and not self.connected:
         self.logger.error("Connection time out")
         self.disconnect("401")
     asyncore.poll()
Beispiel #36
0
def ManageSockets():
    global poll_interval
    global managerRunning
    try:
        while len(asyncore.socket_map):
            asyncore.poll(poll_interval)
            _schedule_func()

    finally:
        managerRunning = False
Beispiel #37
0
 def go (self, timeout=5.0):
     events = self.events
     while self.socket_map:
         # print 'inner-loop'
         now = int(time.time())
         for k,v in events.items():
             if now >= k:
                 v (self, now)
                 del events[k]
         asyncore.poll (timeout)
Beispiel #38
0
	def main():
	    c = PredictConnection('localhost', 1210)
	    conns = []
	    s = APRSServer(conns)

	    while True:
	        if conns:
	            update(c, conns)
	        t = time.time() + 10.0
	        while time.time() < t:
	            asyncore.poll(t - time.time())
Beispiel #39
0
def run_loop():
    global must_exit
    global in_pipe
    global out_pipe
    global needs_flush
    global flush_pipes
    global last_activity
    winmm = None

    # increase the windows timer resolution to 1ms
    if platform.system() == "Windows":
        try:
            import ctypes
            winmm = ctypes.WinDLL('winmm')
            winmm.timeBeginPeriod(1)
        except:
            pass

    last_activity = time.clock()
    last_check = time.clock()
    # disable gc to avoid pauses during traffic shaping/proxying
    gc.disable()
    while not must_exit:
        # Tick every 1ms if traffic-shaping is enabled and we have data or are doing background dns lookups, every 1 second otherwise
        lock.acquire()
        tick_interval = 0.001
        if background_activity_count == 0:
            if in_pipe.next_message is None and in_pipe.queue.empty(
            ) and out_pipe.next_message is None and out_pipe.queue.empty():
                tick_interval = 1.0
            elif in_pipe.kbps == .0 and in_pipe.latency == 0 and out_pipe.kbps == .0 and out_pipe.latency == 0:
                tick_interval = 1.0
        lock.release()
        asyncore.poll(tick_interval, asyncore.socket_map)
        if needs_flush:
            flush_pipes = True
            needs_flush = False
        out_pipe.tick()
        in_pipe.tick()
        if flush_pipes:
            PrintMessage('OK')
            flush_pipes = False
        # Every 500 ms check to see if it is a good time to do a gc
        now = time.clock()
        if now - last_check > 0.5:
            last_check = now
            # manually gc after 5 seconds of idle
            if now - last_activity >= 5:
                last_activity = now
                logging.debug("Triggering manual GC")
                gc.collect()

    if winmm is not None:
        winmm.timeEndPeriod(1)
Beispiel #40
0
def lifetime_loop():
    # The main loop. Stay in here until we need to shutdown
    map = asyncore.socket_map
    timeout = 30.0
    timestamp = time.time()
    while map and _shutdown_phase == 0:
        if _SD_NOTIFY_WATCHDOG and timestamp + timeout < time.time():
            SystemdNotifier().notify('WATCHDOG=1')
            logger.debug("Notifying systemd we're still alive")
            timestamp = time.time()
        asyncore.poll(timeout, map)
Beispiel #41
0
    def runner(self):
        """Thread runner for the main asyncore loop. This function runs in a
        separate thread.
        """

        import asyncore

        # Poll
        socket_map = asyncore.socket_map
        while socket_map and not self._shutdown:
            asyncore.poll(self.timeout, socket_map)
Beispiel #42
0
 def pollDown(self, timeout=30.0):
     # Poll until we're disconnected.
     now = time.time()
     giveup = now + timeout
     while self._storage.is_connected():
         asyncore.poll(0.1)
         now = time.time()
         if now > giveup:
             self.fail("timed out waiting for storage to disconnect")
         # See pollUp() for why we sleep a little here.
         time.sleep(0.1)
Beispiel #43
0
def main(argv):
    server_url = argv[1]
    if len(argv) > 2:
        topic = argv[2]
    if len(argv) > 3:
        payload_size = argv[3]
    if len(argv) > 4:
        expires = argv[4]
    publisher = publish_payload(server_url, topic, payload_size, expires)
    while publisher.running:
        asyncore.poll(scheduler.timeout())
        scheduler.run()
Beispiel #44
0
def main(pathToWatch):
    wm = pyinotify.WatchManager()  # Watch Manager

    mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MODIFY | pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM  # watched events

    notifier = pyinotify.AsyncNotifier(wm, EventHandler())
    wm.add_watch('/tmp/directorywatch', mask)

    while (True):
        asyncore.poll()
        sleep(2)
    notifier.stop()
Beispiel #45
0
def ManageSockets():
    global managerRunning

    try:
        while len(asyncore.socket_map):
            # Check the sockets for activity.
            #print "POLL"
            asyncore.poll(poll_interval)
            # Yield to give other tasklets a chance to be scheduled.
            _schedule_func()
    finally:
        managerRunning = False
Beispiel #46
0
    def __init__(self, host, port):
        """
        Args:
            host:
            port:
        """
        super().__init__()
        self.create_socket()
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(_N_PLAYERS)
        self.clients = _N_PLAYERS * [None]

        self.tokens_center = []
        for i in range(_N_PLAYERS):
            self.tokens_center.append(
                (425 + 30 * math.cos(2 * i * math.pi / _N_PLAYERS),
                 270 + 30 * math.sin(2 * i * math.pi / _N_PLAYERS)))
            self.tokens_center.append((60 + 30 * (i % (_N_PLAYERS / 2)),
                                       430 + 30 * (i // (_N_PLAYERS / 2))))

        self.dices_val = [random.randint(1, 4), random.randint(1, 6)]

        self.characters = []
        if _N_PLAYERS >= 7:  # Removing Bob for 7 and 8 players
            game.Character.CHARACTERS[1 + 0].pop(4)
        for align in (0, 1, 2):
            n_total = len(game.Character.CHARACTERS[align])
            n_avail = game.Character.CHARACTERS_REPARTITION[_N_PLAYERS][align]
            self.characters += [[align, i, False, []]
                                for i in random.sample(range(n_total), n_avail)
                                ]
        random.shuffle(self.characters)

        self.areas = list(range(6))
        random.shuffle(self.areas)

        self.active_player = 0  # Todo
        # self.active_player = random.randrange(_N_PLAYERS)

        self.cards = [
            list(range(len(card_type.CARDS))) for card_type in card.TYPES
        ]
        for c in self.cards:
            random.shuffle(c)

        try:
            while True:
                asyncore.poll()
                time.sleep(self.DELAY)
        except KeyboardInterrupt:
            pass
Beispiel #47
0
 def _loop(self, map):
     """The main loop. Poll sockets for I/O and run any other functions
     that need to be run every loop.
     """
     try:
         from asyncore import poll
     except ImportError:
         raise Exception("Couldn't find poll function. Cannot start bot.")
 
     while map:
         self.before_poll()
         poll(timeout=30.0, map=map)
         self.after_poll()
def ManageSockets():
    global managerRunning

    t = stackless.getcurrent()
    while len(asyncore.socket_map):
        # Check the sockets for activity.
        t.block_trap = False
        asyncore.poll(0.01)
        t.block_trap = True
        # Yield to give other tasklets a chance to be scheduled.
        stackless.schedule()

    managerRunning = False
Beispiel #49
0
 def stopServer(self):
     self.run_loop = 0
     self.thread.join()
     td.shutdown()
     self._server.close()
     # Make sure all sockets get closed by asyncore normally.
     timeout = time.time() + 5
     while 1:
         if len(asyncore.socket_map) == self.orig_map_size:
             # Clean!
             break
         if time.time() >= timeout:
             self.fail('Leaked a socket: %s' % `asyncore.socket_map`)
         asyncore.poll(0.1)
Beispiel #50
0
    def loop(self, timeout=None):
        self.thread_ident = thread.get_ident()
        if timeout is not None:
            deadline = time.time() + timeout
        else:
            deadline = None
            timeout = 30
        map = self._map
        callbacks = self._callbacks
        logger = logging.getLogger('zc.ngi.async.loop')
        trigger = _Trigger(self._map)
        self.notify_select = trigger.pull_trigger

        try:
            while 1:

                while callbacks:
                    callback = callbacks.pop(0)
                    try:
                        callback()
                    except:
                        self.logger.exception('Calling callback')
                        self.handle_error()

                if deadline:
                    timeout = min(deadline - time.time(), 30)

                try:
                    if (timeout > 0) and (len(map) > 1):
                        asyncore.poll(timeout, map)
                except:
                    logger.exception('loop error')
                    raise

                if trigger._fileno is None:
                    # oops, the trigger got closed.  Recreate it.
                    trigger = _Trigger(self._map)
                    self.notify_select = trigger.pull_trigger

                with self._start_lock:
                    if (len(map) <= 1) and not callbacks:
                        self._thread = None
                        return

                if timeout <= 0:
                    raise zc.ngi.interfaces.Timeout
        finally:
            del self.thread_ident
            del self.notify_select
            trigger.close()
Beispiel #51
0
    def delayFunc(self, delaySecs):
        if (self.stopLoopB):
            raise ExitLoop, "Exiting mainloop from delay"
        if delaySecs == 0:
            #print "DBG: delay of zero"
            pass
        else:
            #print "DBG: delay of %.4f" % delaySecs
            # asyncore.loop(delaySecs, False, None, 1)

            if self.sockMap:
                asyncore.poll(delaySecs, self.sockMap)
            else:
                time.sleep(delaySecs)
Beispiel #52
0
def main(argv):
    server_url = "http://www.mod-pubsub.org:9000/kn"
    if len(argv) > 1:
        server_url = argv[1]
    topic = "/what/apps/blogchatter/pings"
    if len(argv) > 2:
        topic = argv[2]
    do_max_n = "10"
    if len(argv) > 3:
        do_max_n = argv[3]
    sub(server_url, topic, do_max_n)
    while 1:
        asyncore.poll(scheduler.timeout())
        scheduler.run()
Beispiel #53
0
def async_download(pagegetter_list,
                   finish_function=None,
                   datastructure_list=None,
                   timeout=15,
                   print_search_info=True,
                   print_body=True):
    """Download web pages asynchronously with timeout.
    pagegetter_list : list of HTTPAsyncPageGetter objects
    finish_function : function called when a web page is downloaded;
        prototype def funct(pagetter, datastructure, current_time, print_search_info(optional))
    datastructure_list : list (same size as pagegetter_list) with information to pass as datastructure
        to the finish function.
    timeout : float, timeout in seconds.
    print_search_info: boolean, whether to print the search info or not in the finish function"""
    time_start = time.time()
    finished_list = [False] * len(pagegetter_list)

    nb_remaining = 0
    check_redirected(pagegetter_list)
    for pagegetter in pagegetter_list:
        if pagegetter and not pagegetter.done:
            nb_remaining += 1

    while (time.time() - time_start < timeout) and nb_remaining > 0:
        if sys.hexversion < 0x2040000:
            asyncore.poll(0.01)
        else:
            asyncore.loop(0.01, True, None, 1)
        check_redirected(pagegetter_list)
        for i in range(len(pagegetter_list)):
            if pagegetter_list[i] and not finished_list[i] and pagegetter_list[
                    i].done:
                nb_remaining -= 1
                if finish_function:
                    if datastructure_list:
                        datastructure = datastructure_list[i]
                    else:
                        datastructure = None
                    current_time = time.time() - time_start
                    try:
                        finish_function(pagegetter_list[i], datastructure,
                                        current_time, print_search_info,
                                        print_body)
                    except TypeError:
                        finish_function(pagegetter_list[i], datastructure,
                                        current_time)
                finished_list[i] = True

    return finished_list
Beispiel #54
0
 def loop(self):
     try:
         while not self.doneflag.isSet():
             self._pop_externally_added()
             period = 1e9
             if len(self.tasks) > 0:
                 # Poll until the next task is set to execute
                 period = max(0, self.tasks[0][0] - bttime())
             asyncore.poll(period)
             self.do_tasks()
     except KeyboardInterrupt:
         #TODO: cleanup?
         pass
     except:
         log.critical('\n' + traceback.format_exc())
Beispiel #55
0
 def tearDown(self):
     self.run_loop = 0
     self.thread.join()
     td.shutdown()
     self.server.close()
     # Make sure all sockets get closed by asyncore normally.
     timeout = time() + 5
     while 1:
         if len(socket_map) == self.orig_map_size:
             # Clean!
             break
         if time() >= timeout:
             self.fail('Leaked a socket: %s' % ` socket_map `)
         poll(0.1)
     self.unhook_asyncore_error()
Beispiel #56
0
 def jogWithDirectionAndClock(self,dir_gpio,clock_gpio,direction):
     self.command_stopped = False
     if direction == 1: 
         GPIO.output(dir_gpio, GPIO.HIGH)
     elif direction == -1:
         GPIO.output(dir_gpio, GPIO.LOW)
     self.data = ""
     while 1:
         if self.command_stopped:
             return
         GPIO.output(clock_gpio, GPIO.HIGH)
         time.sleep(0.0001)
         GPIO.output(clock_gpio, GPIO.LOW)
         time.sleep(0.0001)
         asyncore.poll()
Beispiel #57
0
 def CheckConnection(self):
     if self.maxretries == 0 or self.retryinterval == 0:
         return True
     time.sleep(0.05)
     if not self.reader:
         return False
     try:
         self.reader.sbuffer = 'VERSION\n'
     except:
         return False
     time.sleep(0.05)
     asyncore.poll()
     if not self.reader.connected:
         return False
     return True
Beispiel #58
0
    def get_portinfo(self):
        """! @brief Get the AGWPE port information
             @param self -
             @returns Nothing. The information will be printed
        """

        while not ports:
            frame = Frame()
            frame.make_header(0, 'G', 0, '', '', 0)
            self.send(frame.header)
            try:
                asyncore.poll(1)
            except KeyboardInterrupt:
                print 'version() kbd interrupt'
                return
Beispiel #59
0
    def get_portcapabilities(self):
        """! @brief Get the AGWPE port capabilities
             @param self -
             @returns Nothing. The information will be printed
        """

        for n in range(ports):
            frame = Frame()
            frame.make_header(n, 'g', 0, '', '', 0)
            self.send(frame.header)
            try:
                asyncore.poll(1)
            except KeyboardInterrupt:
                print 'version() kbd interrupt'
                return
Beispiel #60
0
 def register(self, callsign):
     """Register the given callsign
      @param self -
      @param callsign Callsign to register
      @returns Nothing
     """
     print 'registering %s' % callsign
     frame = Frame()
     frame.make_header(0, 'X', 0, callsign, '', 0)
     self.send(frame.header)
     try:
         asyncore.poll(1)
     except KeyboardInterrupt:
         print 'register() kbd interrupt'
         return