Exemplo n.º 1
0
    def step(self, dt=0):
        '''
        Step through queue'd events scheduled to be released within the next
        dt seconds.
        '''
        # fire any instants (like spawn) before 'waiting'
        # this fixes the case where a spawned function adds a sleep
        self.fastsleep()
        # print('gt:',self.now,self._targets)
        if len(self._targets) == 0:
            # no sleeps, just advance the time
            self._current += dt
            self.fastsleep()
        else:
            # sort targets so we we get the ones to process in front
            self._targets.sort()

            # keep stepping till we hit an end time
            step_to = self.now + dt if dt else self._targets[0]
            while self.now < step_to:
                # step a specific amount of time or to the first target
                new = min(step_to, self._targets[0])
                self._current = new
                # print('gt2:',self.now,self._targets)
                for target in list(self._targets):
                    if target <= new:
                        for event in self._waits[target]:
                            event.set() # does not switch
                    else:
                        break

                # switch to run released events
                self.fastsleep()
Exemplo n.º 2
0
 def do_return(serial, retval):
     if serial in self._pending:
         event = self._pending.pop(serial)
         if event is not None:
             event.set(retval)
     else:
         logger.warning("Returns {0} serial {1} is not found.".format(
             retval, serial))
Exemplo n.º 3
0
def open():
    # Open a new file with the given name.
    global next_id
    path = bottle.request.json['path']
    data = {'id': next_id, 'path': path}
    if not os.path.exists(os.path.join(root, path)):
        bottle.response.status = 404
        return {'status': 'no such file'}

    pending.append(data)
    next_id += 1
    event.set()
    event.clear()
    return data
Exemplo n.º 4
0
    def send_rpc(self, method, params=None, num_results=0, and_discard=False):
        if self._in_channel is None:
            raise RuntimeError('Not connected')

        if params is None:
            params = {}

        id_ = str(uuid.uuid1())

        body = {
            'reply_to': self._in_queue.queue,
            'method': method,
            'id': id_,
            'params': params
        }

        LOG.debug('AMQPRpcFanoutClientChannel - sending %s to %s',
                  body, self.fanout)

        msg = amqp.Message(
            body=json.dumps(body),
            reply_to=self._in_queue.queue,
            exchange=self.fanout
        )

        event = gevent.event.AsyncResult()

        if num_results == 0:
            event.set({
                'answers': {},
                'errors': 0
            })
            return event

        self.active_rpcs[id_] = {
            'cmd': method,
            'answers': {},
            'num_results': num_results,
            'event': event,
            'errors': 0,
            'discard': and_discard
        }

        self._out_channel.basic_publish(msg, exchange=self.fanout)

        gevent.sleep(0)

        return event
Exemplo n.º 5
0
    def send_rpc(self, method, params=None, num_results=0, and_discard=False):
        if self._in_channel is None:
            raise RuntimeError('Not connected')

        if params is None:
            params = {}

        id_ = str(uuid.uuid1())

        body = {
            'reply_to': self._in_queue.queue,
            'method': method,
            'id': id_,
            'params': params
        }

        LOG.debug('AMQPRpcFanoutClientChannel - sending %s to %s', body,
                  self.fanout)

        msg = amqp.Message(body=json.dumps(body),
                           reply_to=self._in_queue.queue,
                           exchange=self.fanout)

        event = gevent.event.AsyncResult()

        if num_results == 0:
            event.set({'answers': {}, 'errors': 0})
            return event

        self.active_rpcs[id_] = {
            'cmd': method,
            'answers': {},
            'num_results': num_results,
            'event': event,
            'errors': 0,
            'discard': and_discard
        }

        self._out_channel.basic_publish(msg, exchange=self.fanout)

        gevent.sleep(0)

        return event
Exemplo n.º 6
0
    def send_rpc(self, method, params=None, num_results=0, and_discard=False):
        if self.socket is None:
            raise RuntimeError('Not connected')

        if params is None:
            params = {}

        id_ = str(uuid.uuid1())

        body = {
            'reply_to': '{}:reply'.format(self.fanout),
            'method': method,
            'id': id_,
            'params': params
        }

        event = gevent.event.AsyncResult()

        if num_results == 0:
            event.set({'answers': {}, 'errors': 0})
            return event

        self.active_rpcs[id_] = {
            'cmd': method,
            'answers': {},
            'num_results': num_results,
            'event': event,
            'errors': 0,
            'discard': and_discard
        }

        LOG.debug('RPC Fanout Client: send multipart to {}: {!r}'.format(
            self.fanout, json.dumps(body)))
        self.socket.send_multipart(
            ['{}'.format(self.fanout),
             json.dumps(body)])
        LOG.debug(
            'RPC Fanout Client: send multipart to {}: {!r} - done'.format(
                self.fanout, json.dumps(body)))

        gevent.sleep(0)

        return event
Exemplo n.º 7
0
        def _get_rpc_agent(self, address):
            if address == self.core.address:
                agent = self
            elif address not in self._vip_channels:
                agent = Agent(address=address)
                event = gevent.event.Event()
                agent.core.onstart.connect(lambda *a, **kw: event.set(), event)
                gevent.spawn(agent.core.run)
                event.wait()
                self._vip_channels[address] = agent

            else:
                agent = self._vip_channels[address]
            return agent
Exemplo n.º 8
0
        def _get_rpc_agent(self, address):
            if address == self.core.address:
                agent = self
            elif address not in self._vip_channels:
                agent = Agent(address=address)
                event = gevent.event.Event()
                agent.core.onstart.connect(lambda *a, **kw: event.set(), event)
                gevent.spawn(agent.core.run)
                event.wait()
                self._vip_channels[address] = agent

            else:
                agent = self._vip_channels[address]
            return agent
Exemplo n.º 9
0
    def _gl_handler(self):
        while True:
            # Get request
            (exp, count, client, messages, event) = self.q.get()
            try:
                # If request is expired, signal it and move on
                if exp < datetime.utcnow():
                    event.set()
                    continue

                # Get all the ready messages, up to the number requested
                for x in range(count):
                    msg = M.HTTPMessage.reserve(client, [self.qname])
                    if msg is None:
                        break
                    messages.append(msg)
                    # Only get 1 message if there are other requests waiting
                    if not self.q.empty():
                        break

                # Found messages, notify caller and get next request
                if messages or exp < datetime.utcnow():
                    event.set()
                    continue

                # No messages, so we must put the request back onto the queue
                # and wait for a channel event
                self.q.put((exp, count, client, messages, event))

                ev = M.Message.channel.await()
                if ev is None:
                    gevent.sleep(self.sleep / 1e3)

            except:
                log.exception('Error in handler greenlet')
                event.set()
Exemplo n.º 10
0
    def _gl_handler(self):
        chan = M.Message.channel.new_channel()
        while True:
            # Get request
            (exp, count, client, messages, event) = self.q.get()
            try:
                # If request is expired, signal it and move on
                if exp < datetime.utcnow():
                    event.set()
                    continue

                # Get all the ready messages, up to the number requested
                for x in range(count):
                    msg = M.HTTPMessage.reserve(client, [self.qname])
                    if msg is None:
                        break
                    messages.append(msg)

                # Found messages, notify caller and get next request
                if messages or exp < datetime.utcnow():
                    event.set()
                    continue

                # No messages, so we must put the request back onto the queue
                # and wait for a channel event
                self.q.put((exp, count, client, messages, event))

                cursor = chan.cursor(True)
                try:
                    cursor.next()
                except StopIteration:
                    gevent.sleep(self.sleep / 1e3)

            except:
                log.exception('Error in handler greenlet')
                event.set()
Exemplo n.º 11
0
    def _gl_handler(self):
        while True:
            # Get request
            (exp, count, client, messages, event) = self.q.get()
            try:
                # If request is expired, signal it and move on
                if exp < datetime.utcnow():
                    event.set()
                    continue

                # Get all the ready messages, up to the number requested
                for x in range(count):
                    msg = M.HTTPMessage.reserve(client, [self.qname])
                    if msg is None:
                        break
                    messages.append(msg)
                    # Only get 1 message if there are other requests waiting
                    if not self.q.empty():
                        break

                # Found messages, notify caller and get next request
                if messages or exp < datetime.utcnow():
                    event.set()
                    continue

                # No messages, so we must put the request back onto the queue
                # and wait for a channel event
                self.q.put((exp, count, client, messages, event))

                ev = M.Message.channel. await ()
                if ev is None:
                    gevent.sleep(self.sleep / 1e3)

            except:
                log.exception('Error in handler greenlet')
                event.set()
Exemplo n.º 12
0
    def _gl_handler(self):
        chan = M.Message.channel.new_channel()
        while True:
            # Get request
            (exp, count, client, messages, event) = self.q.get()
            try:
                # If request is expired, signal it and move on
                if exp < datetime.utcnow():
                    event.set()
                    continue

                # Get all the ready messages, up to the number requested
                for x in range(count):
                    msg = M.HTTPMessage.reserve(client, [self.qname])
                    if msg is None:
                        break
                    messages.append(msg)

                # Found messages, notify caller and get next request
                if messages or exp < datetime.utcnow():
                    event.set()
                    continue

                # No messages, so we must put the request back onto the queue
                # and wait for a channel event
                self.q.put((exp, count, client, messages, event))

                cursor = chan.cursor(True)
                try:
                    cursor.next()
                except StopIteration:
                    gevent.sleep(self.sleep / 1e3)

            except:
                log.exception('Error in handler greenlet')
                event.set()
Exemplo n.º 13
0
 def inner(*args, **kwargs):
     event = gevent.event.Event()
     gevent.spawn(check, event)
     result = fn(*args, **kwargs)
     event.set()
     return result
Exemplo n.º 14
0
 def timer():
     while True:
         event.set()
         gevent.sleep(1)
Exemplo n.º 15
0
 def timeout_cb(event):
     if event.ready():
         return
     event.set()
Exemplo n.º 16
0
 def wakeup_event(fut):
     event.set()
Exemplo n.º 17
0
def _ioloop_failure(event):
    LOG.debug("loop failure")
    event.set()
Exemplo n.º 18
0
 def put(self, frame):
     self.buf.append(frame)
     event = self.event
     self.event = gevent.event.Event()
     event.set()
     gevent.sleep(0)
Exemplo n.º 19
0
def _ioloop_failure(event):
    LOG.debug("loop failure")
    event.set()
Exemplo n.º 20
0
 def put(self, frame):
     self.buf.append(frame)
     event = self.event
     self.event = gevent.event.Event()
     event.set()
     gevent.sleep(0)