Esempio n. 1
0
    def set_links(self, p, first_time, kill_exc_type):
        event = _event.Event()
        self.link(p, event)

        proc_flag = []
        def receiver():
            sleep(DELAY)
            proc_flag.append('finished')
        receiver = proc.spawn(receiver)
        self.link(p, receiver)

        queue = coros.queue(1)
        self.link(p, queue)

        try:
            self.link(p)
        except kill_exc_type:
            if first_time:
                raise
        else:
            assert first_time, 'not raising here only first time'

        callback_flag = ['initial']
        self.link(p, lambda *args: callback_flag.remove('initial'))

        for _ in range(10):
            self.link(p, _event.Event())
            self.link(p, coros.queue(1))
        return event, receiver, proc_flag, queue, callback_flag
Esempio n. 2
0
    def set_links(self, p, first_time, kill_exc_type):
        event = _event.Event()
        self.link(p, event)

        proc_flag = []

        def receiver():
            sleep(DELAY)
            proc_flag.append('finished')

        receiver = proc.spawn(receiver)
        self.link(p, receiver)

        queue = coros.queue(1)
        self.link(p, queue)

        try:
            self.link(p)
        except kill_exc_type:
            if first_time:
                raise
        else:
            assert first_time, 'not raising here only first time'

        callback_flag = ['initial']
        self.link(p, lambda *args: callback_flag.remove('initial'))

        for _ in range(10):
            self.link(p, _event.Event())
            self.link(p, coros.queue(1))
        return event, receiver, proc_flag, queue, callback_flag
Esempio n. 3
0
 def test_send_exception(self):
     s = proc.Source()
     q1, q2, q3 = coros.queue(), coros.queue(), coros.queue()
     s.link_exception(q1)
     s.send_exception(OSError('hello'))
     sleep(0)
     assert q1.ready()
     s.link_value(q2)
     s.link(q3)
     assert not q2.ready()
     sleep(0)
     assert q3.ready()
     self.assertRaises(OSError, q1.wait)
     self.assertRaises(OSError, q3.wait)
     self.assertRaises(OSError, s.wait)
Esempio n. 4
0
 def test_send_exception(self):
     s = proc.Source()
     q1, q2, q3 = coros.queue(), coros.queue(), coros.queue()
     s.link_exception(q1)
     s.send_exception(OSError('hello'))
     sleep(0)
     assert q1.ready()
     s.link_value(q2)
     s.link(q3)
     assert not q2.ready()
     sleep(0)
     assert q3.ready()
     self.assertRaises(OSError, q1.wait)
     self.assertRaises(OSError, q3.wait)
     self.assertRaises(OSError, s.wait)
Esempio n. 5
0
    def test_blocks_on_pool(self):
        waiter = coros.queue(0)

        def greedy():
            self.pool.get()
            self.pool.get()
            self.pool.get()
            self.pool.get()
            # No one should be waiting yet.
            self.assertEquals(self.pool.waiting(), 0)
            # The call to the next get will unschedule this routine.
            self.pool.get()
            # So this send should never be called.
            waiter.send('Failed!')

        killable = api.spawn(greedy)

        # no one should be waiting yet.
        self.assertEquals(self.pool.waiting(), 0)

        ## Wait for greedy
        api.sleep(0)

        ## Greedy should be blocking on the last get
        self.assertEquals(self.pool.waiting(), 1)

        ## Send will never be called, so balance should be 0.
        self.assertFalse(waiter.ready())

        api.kill(killable)
Esempio n. 6
0
    def test_wait(self):
        sleep(0.1)
        channel = coros.queue(0)
        events = []

        def another_greenlet():
            events.append('sending hello')
            channel.send('hello')
            events.append('sending world')
            channel.send('world')
            events.append('sent world')

        spawn(another_greenlet)

        events.append('waiting')
        events.append(channel.wait())
        events.append(channel.wait())

        self.assertEqual(
            ['waiting', 'sending hello', 'hello', 'sending world', 'world'],
            events)
        sleep(0)
        self.assertEqual([
            'waiting', 'sending hello', 'hello', 'sending world', 'world',
            'sent world'
        ], events)
Esempio n. 7
0
    def fan(self, block, input_list):
        queue = coros.queue(0)
        results = []
        exceptional_results = 0
        for index, input_item in enumerate(input_list):
            pool_item = self.get()

            ## Fan out
            api.spawn(
                self._invoke, block, pool_item, input_item, index, queue)

        ## Fan back in
        for i in range(len(input_list)):
            ## Wait for all guys to send to the queue
            index, value = queue.wait()
            if isinstance(value, Exception):
                exceptional_results += 1
            results.append((index, value))

        results.sort()
        results = [value for index, value in results]

        if exceptional_results:
            if exceptional_results == len(results):
                raise AllFailed(results)
            raise SomeFailed(results)
        return results
Esempio n. 8
0
    def test_blocks_on_pool(self):
        waiter = coros.queue(0)
        def greedy():
            self.pool.get()
            self.pool.get()
            self.pool.get()
            self.pool.get()
            # No one should be waiting yet.
            self.assertEquals(self.pool.waiting(), 0)
            # The call to the next get will unschedule this routine.
            self.pool.get()
            # So this send should never be called.
            waiter.send('Failed!')

        killable = api.spawn(greedy)

        # no one should be waiting yet.
        self.assertEquals(self.pool.waiting(), 0)

        ## Wait for greedy
        api.sleep(0)

        ## Greedy should be blocking on the last get
        self.assertEquals(self.pool.waiting(), 1)

        ## Send will never be called, so balance should be 0.
        self.assertFalse(waiter.ready())

        api.kill(killable)
    def test_multiple_waiters(self):
        # tests that multiple waiters get their results back
        q = coros.queue()

        def waiter(q, evt):
            evt.send(q.wait())

        sendings = ['1', '2', '3', '4']
        evts = [coros.event() for x in sendings]
        for i, x in enumerate(sendings):
            api.spawn(waiter, q, evts[i])

        api.sleep(0.01) # get 'em all waiting

        results = set()
        def collect_pending_results():
            for i, e in enumerate(evts):
                timer = api.exc_after(0.001, api.TimeoutError)
                try:
                    x = e.wait()
                    results.add(x)
                    timer.cancel()
                except api.TimeoutError:
                    pass  # no pending result at that event
            return len(results)
        q.send(sendings[0])
        self.assertEquals(collect_pending_results(), 1)
        q.send(sendings[1])
        self.assertEquals(collect_pending_results(), 2)
        q.send(sendings[2])
        q.send(sendings[3])
        self.assertEquals(collect_pending_results(), 4)
Esempio n. 10
0
    def test_senders_that_die(self):
        q = coros.queue()

        def do_send(q):
            q.send('sent')

        spawn(do_send, q)
        self.assertEqual(q.wait(), 'sent')
Esempio n. 11
0
 def __init__(self):
     self._stopped = True
     self._files = []
     self._servers = {}
     self._command_channel = coros.queue()
     self._select_proc = None
     self._discover_timer = None
     self._wakeup_timer = None
Esempio n. 12
0
    def test_senders_that_die(self):
        q = coros.queue()

        def do_send(q):
            q.send('sent')

        spawn(do_send, q)
        self.assertEqual(q.wait(), 'sent')
Esempio n. 13
0
 def __init__(self, logger):
     ConnectBase.__init__(self, logger)
     self.ports = {} # maps interface -> port -> (use_tls, listening Port)
     self.queue = coros.queue()
     self.expected_local_uris = {} # maps local_uri -> Logger instance
     self.expected_remote_paths = {} # maps full_remote_path -> event
     self.new_full_remote_path_notifier = Notifier()
     self.factory = SpawnFactory(self._incoming_handler, MSRPTransport, local_uri=None, logger=self.logger)
Esempio n. 14
0
 def __init__(self):
     self._stopped = True
     self._files = []
     self._servers = {}
     self._command_channel = coros.queue()
     self._select_proc = None
     self._discover_timer = None
     self._wakeup_timer = None
Esempio n. 15
0
File: pool.py Progetto: esh/invaders
 def __init__(self, min_size=0, max_size=4, track_events=False):
     if min_size > max_size:
         raise ValueError('min_size cannot be bigger than max_size')
     self.max_size = max_size
     self.sem = coros.Semaphore(max_size)
     self.procs = proc.RunningProcSet()
     if track_events:
         self.results = coros.queue()
     else:
         self.results = None
Esempio n. 16
0
 def __init__(self, min_size=0, max_size=4, track_events=False):
     if min_size > max_size:
         raise ValueError('min_size cannot be bigger than max_size')
     self.max_size = max_size
     self.sem = Semaphore(max_size)
     self.procs = proc.RunningProcSet()
     if track_events:
         self.results = coros.queue()
     else:
         self.results = None
Esempio n. 17
0
 def test_send(self):
     s = proc.Source()
     q1, q2, q3 = coros.queue(), coros.queue(), coros.queue()
     s.link_value(q1)
     self.assertRaises(Timeout, s.wait, 0)
     assert s.wait(0, None) is None
     assert s.wait(0.001, None) is None
     self.assertRaises(Timeout, s.wait, 0.001)
     s.send(1)
     assert not q1.ready()
     assert s.wait() == 1
     sleep(0)
     assert q1.ready()
     s.link_exception(q2)
     s.link(q3)
     assert not q2.ready()
     sleep(0)
     assert q3.ready()
     assert s.wait() == 1
Esempio n. 18
0
 def test_send(self):
     s = proc.Source()
     q1, q2, q3 = coros.queue(), coros.queue(), coros.queue()
     s.link_value(q1)
     self.assertRaises(Timeout, s.wait, 0)
     assert s.wait(0, None) is None
     assert s.wait(0.001, None) is None
     self.assertRaises(Timeout, s.wait, 0.001)
     s.send(1)
     assert not q1.ready()
     assert s.wait()==1
     sleep(0)
     assert q1.ready()
     s.link_exception(q2)
     s.link(q3)
     assert not q2.ready()
     sleep(0)
     assert q3.ready()
     assert s.wait()==1
Esempio n. 19
0
 def __init__(self, msrptransport, accept_types=['*'], on_incoming_cb=None):
     self.msrp = msrptransport
     self.accept_types = accept_types
     if on_incoming_cb is not None:
         self._on_incoming_cb = on_incoming_cb
     self.expected_responses = {}
     self.outgoing = coros.queue()
     self.outgoing_files = coros.queue()
     self.reader_job = proc.spawn(self._reader)
     self.writer_job = proc.spawn(self._writer)
     self.state = 'CONNECTED' # -> 'FLUSHING' -> 'CLOSING' -> 'DONE'
     # in FLUSHING writer sends only while there's something in the outgoing queue
     # then it exits and sets state to 'CLOSING' which makes reader only pay attention
     # to responses and success reports. (XXX it could now discard incoming data chunks
     # with direct write() since writer is dead)
     self.reader_job.link(self.writer_job)
     self.last_expected_response = 0
     if not callable(self._on_incoming_cb):
         raise TypeError('on_incoming_cb must be callable: %r' % (self._on_incoming_cb, ))
Esempio n. 20
0
    def test_send_last(self):
        q = coros.queue()
        def waiter(q):
            timer = eventlet.Timeout(0.1)
            self.assertEqual(q.wait(), 'hi2')
            timer.cancel()

        spawn(waiter, q)
        sleep(0)
        sleep(0)
        q.send('hi2')
    def test_send_last(self):
        q = coros.queue()
        def waiter(q):
            timer = api.exc_after(0.1, api.TimeoutError)
            self.assertEquals(q.wait(), 'hi2')
            timer.cancel()

        api.spawn(waiter, q)
        api.sleep(0)
        api.sleep(0)
        q.send('hi2')
Esempio n. 22
0
    def test_send_last(self):
        q = coros.queue()

        def waiter(q):
            timer = eventlet.Timeout(0.1)
            self.assertEqual(q.wait(), 'hi2')
            timer.cancel()

        spawn(waiter, q)
        sleep(0)
        sleep(0)
        q.send('hi2')
Esempio n. 23
0
 def start(self):
     if self._state != 'stopped':
         return
     self._state = 'started'
     self._channel = coros.queue()
     self._current_loop = 0
     if self.initial_play:
         self._channel.send(Command('play'))
     else:
         from twisted.internet import reactor
         reactor.callLater(self.pause_time, self._channel.send, Command('play'))
     self._run()
Esempio n. 24
0
 def start(self):
     if self._state != 'stopped':
         return
     self._state = 'started'
     self._channel = coros.queue()
     self._current_loop = 0
     if self.initial_play:
         self._channel.send(Command('play'))
     else:
         from twisted.internet import reactor
         reactor.callLater(self.pause_time, self._channel.send,
                           Command('play'))
     self._run()
Esempio n. 25
0
    def test_waiting(self):
        def do_wait(q, evt):
            result = q.wait()
            evt.send(result)

        q = coros.queue()
        e1 = Event()
        spawn(do_wait, q, e1)
        sleep(0)
        self.assertEqual(1, q.waiting())
        q.send('hi')
        sleep(0)
        self.assertEqual(0, q.waiting())
        self.assertEqual('hi', e1.wait())
        self.assertEqual(0, q.waiting())
    def test_waiting(self):
        def do_wait(q, evt):
            result = q.wait()
            evt.send(result)

        q = coros.queue()
        e1 = coros.event()
        api.spawn(do_wait, q, e1)
        api.sleep(0)
        self.assertEquals(1, waiting(q))
        q.send('hi')
        api.sleep(0)
        self.assertEquals(0, waiting(q))
        self.assertEquals('hi', e1.wait())
        self.assertEquals(0, waiting(q))
Esempio n. 27
0
    def test_waiting(self):
        def do_wait(q, evt):
            result = q.wait()
            evt.send(result)

        q = coros.queue()
        e1 = Event()
        spawn(do_wait, q, e1)
        sleep(0)
        self.assertEqual(1, q.waiting())
        q.send('hi')
        sleep(0)
        self.assertEqual(0, q.waiting())
        self.assertEqual('hi', e1.wait())
        self.assertEqual(0, q.waiting())
Esempio n. 28
0
    def set_links_timeout(self, link):
        # stuff that won't be touched
        event = coros.event()
        link(event)

        proc_finished_flag = []
        def myproc():
            sleep(10)
            proc_finished_flag.append('finished')
            return 555
        myproc = proc.spawn(myproc)
        link(myproc)

        queue = coros.queue(0)
        link(queue)
        return event, myproc, proc_finished_flag, queue
Esempio n. 29
0
    def set_links_timeout(self, link):
        # stuff that won't be touched
        event = _event.Event()
        link(event)

        proc_finished_flag = []
        def myproc():
            sleep(10)
            proc_finished_flag.append('finished')
            return 555
        myproc = proc.spawn(myproc)
        link(myproc)

        queue = coros.queue(0)
        link(queue)
        return event, myproc, proc_finished_flag, queue
Esempio n. 30
0
    def test_putting_to_queue(self):
        timer = api.exc_after(0.1, api.TimeoutError)
        size = 2
        self.pool = IntPool(min_size=0, max_size=size)
        queue = coros.queue()
        results = []
        def just_put(pool_item, index):
            self.pool.put(pool_item)
            queue.send(index)
        for index in xrange(size + 1):
            pool_item = self.pool.get()
            api.spawn(just_put, pool_item, index)

        while results != range(size + 1):
            x = queue.wait()
            results.append(x)
        timer.cancel()
    def test_multiple_waiters(self):
        # tests that multiple waiters get their results back
        q = coros.queue()

        sendings = ["1", "2", "3", "4"]
        gts = [eventlet.spawn(q.wait) for x in sendings]

        eventlet.sleep(0.01)  # get 'em all waiting

        q.send(sendings[0])
        q.send(sendings[1])
        q.send(sendings[2])
        q.send(sendings[3])
        results = set()
        for i, gt in enumerate(gts):
            results.add(gt.wait())
        self.assertEquals(results, set(sendings))
Esempio n. 32
0
    def test_multiple_waiters(self):
        # tests that multiple waiters get their results back
        q = coros.queue()

        sendings = ['1', '2', '3', '4']
        gts = [eventlet.spawn(q.wait) for x in sendings]

        eventlet.sleep(0.01)  # get 'em all waiting

        q.send(sendings[0])
        q.send(sendings[1])
        q.send(sendings[2])
        q.send(sendings[3])
        results = set()
        for i, gt in enumerate(gts):
            results.add(gt.wait())
        self.assertEqual(results, set(sendings))
Esempio n. 33
0
    def test_waiters_that_cancel(self):
        q = coros.queue()

        def do_receive(q, evt):
            eventlet.Timeout(0, RuntimeError())
            try:
                result = q.wait()
                evt.send(result)
            except RuntimeError:
                evt.send('timed out')

        evt = Event()
        spawn(do_receive, q, evt)
        self.assertEqual(evt.wait(), 'timed out')

        q.send('hi')
        self.assertEqual(q.wait(), 'hi')
Esempio n. 34
0
    def test_waiters_that_cancel(self):
        q = coros.queue()

        def do_receive(q, evt):
            eventlet.Timeout(0, RuntimeError())
            try:
                result = q.wait()
                evt.send(result)
            except RuntimeError:
                evt.send('timed out')

        evt = Event()
        spawn(do_receive, q, evt)
        self.assertEqual(evt.wait(), 'timed out')

        q.send('hi')
        self.assertEqual(q.wait(), 'hi')
Esempio n. 35
0
    def test_two_bogus_waiters(self):
        def do_receive(q, evt):
            eventlet.Timeout(0, RuntimeError())
            try:
                result = q.wait()
                evt.send(result)
            except RuntimeError:
                evt.send('timed out')

        q = coros.queue()
        e1 = Event()
        e2 = Event()
        spawn(do_receive, q, e1)
        spawn(do_receive, q, e2)
        sleep(0)
        q.send('sent')
        self.assertEqual(e1.wait(), 'timed out')
        self.assertEqual(e2.wait(), 'timed out')
        self.assertEqual(q.wait(), 'sent')
    def test_two_bogus_waiters(self):
        def do_receive(q, evt):
            api.exc_after(0, RuntimeError())
            try:
                result = q.wait()
                evt.send(result)
            except RuntimeError:
                evt.send('timed out')

        q = coros.queue()
        e1 = coros.event()
        e2 = coros.event()
        api.spawn(do_receive, q, e1)
        api.spawn(do_receive, q, e2)
        api.sleep(0)
        q.send('sent')
        self.assertEquals(e1.wait(), 'timed out')
        self.assertEquals(e2.wait(), 'timed out')
        self.assertEquals(q.wait(), 'sent')
Esempio n. 37
0
def waitall(lst, trap_errors=False, queue=None):
    if queue is None:
        queue = coros.queue()
    index = -1
    for (index, linkable) in enumerate(lst):
        linkable.link(decorate_send(queue, index))
    len = index + 1
    results = [None] * len
    count = 0
    while count < len:
        try:
            index, value = queue.wait()
        except Exception:
            if not trap_errors:
                raise
        else:
            results[index] = value
        count += 1
    return results
    def test_zero_max_size(self):
        q = coros.queue(0)
        def sender(evt, q):
            q.send('hi')
            evt.send('done')

        def receiver(evt, q):
            x = q.wait()
            evt.send(x)

        e1 = coros.event()
        e2 = coros.event()

        api.spawn(sender, e1, q)
        api.sleep(0)
        self.assert_(not e1.ready())
        api.spawn(receiver, e2, q)
        self.assertEquals(e2.wait(),'hi')
        self.assertEquals(e1.wait(),'done')
Esempio n. 39
0
def waitall(lst, trap_errors=False, queue=None):
    if queue is None:
        queue = coros.queue()
    index = -1
    for (index, linkable) in enumerate(lst):
        linkable.link(decorate_send(queue, index))
    len = index + 1
    results = [None] * len
    count = 0
    while count < len:
        try:
            index, value = queue.wait()
        except Exception:
            if not trap_errors:
                raise
        else:
            results[index] = value
        count += 1
    return results
    def test_send(self):
        sleep(0.1)
        channel = coros.queue(0)

        events = []

        def another_greenlet():
            events.append(channel.wait())
            events.append(channel.wait())

        spawn(another_greenlet)

        events.append("sending")
        channel.send("hello")
        events.append("sent hello")
        channel.send("world")
        events.append("sent world")

        self.assertEqual(["sending", "hello", "sent hello", "world", "sent world"], events)
Esempio n. 41
0
    def test_putting_to_queue(self):
        timer = api.exc_after(0.1, api.TimeoutError)
        size = 2
        self.pool = IntPool(min_size=0, max_size=size)
        queue = coros.queue()
        results = []

        def just_put(pool_item, index):
            self.pool.put(pool_item)
            queue.send(index)

        for index in xrange(size + 1):
            pool_item = self.pool.get()
            api.spawn(just_put, pool_item, index)

        while results != range(size + 1):
            x = queue.wait()
            results.append(x)
        timer.cancel()
Esempio n. 42
0
    def test_send(self):
        sleep(0.1)
        channel = coros.queue(0)

        events = []

        def another_greenlet():
            events.append(channel.wait())
            events.append(channel.wait())

        spawn(another_greenlet)

        events.append('sending')
        channel.send('hello')
        events.append('sent hello')
        channel.send('world')
        events.append('sent world')

        self.assertEqual(['sending', 'hello', 'sent hello', 'world', 'sent world'], events)
Esempio n. 43
0
    def test_two_bogus_waiters(self):
        def do_receive(q, evt):
            eventlet.Timeout(0, RuntimeError())
            try:
                result = q.wait()
                evt.send(result)
            except RuntimeError:
                evt.send('timed out')

        q = coros.queue()
        e1 = Event()
        e2 = Event()
        spawn(do_receive, q, e1)
        spawn(do_receive, q, e2)
        sleep(0)
        q.send('sent')
        self.assertEqual(e1.wait(), 'timed out')
        self.assertEqual(e2.wait(), 'timed out')
        self.assertEqual(q.wait(), 'sent')
Esempio n. 44
0
    def test_zero_max_size(self):
        q = coros.queue(0)
        def sender(evt, q):
            q.send('hi')
            evt.send('done')

        def receiver(evt, q):
            x = q.wait()
            evt.send(x)

        e1 = Event()
        e2 = Event()

        spawn(sender, e1, q)
        sleep(0)
        self.assert_(not e1.ready())
        spawn(receiver, e2, q)
        self.assertEqual(e2.wait(),'hi')
        self.assertEqual(e1.wait(),'done')
Esempio n. 45
0
    def test_max_size(self):
        q = coros.queue(2)
        results = []

        def putter(q):
            q.send('a')
            results.append('a')
            q.send('b')
            results.append('b')
            q.send('c')
            results.append('c')

        spawn(putter, q)
        sleep(0)
        self.assertEqual(results, ['a', 'b'])
        self.assertEqual(q.wait(), 'a')
        sleep(0)
        self.assertEqual(results, ['a', 'b', 'c'])
        self.assertEqual(q.wait(), 'b')
        self.assertEqual(q.wait(), 'c')
    def test_two_waiters_one_dies(self):
        def waiter(q, evt):
            evt.send(q.wait())
        def do_receive(q, evt):
            api.exc_after(0, RuntimeError())
            try:
                result = q.wait()
                evt.send(result)
            except RuntimeError:
                evt.send('timed out')

        q = coros.queue()
        dying_evt = coros.event()
        waiting_evt = coros.event()
        api.spawn(do_receive, q, dying_evt)
        api.spawn(waiter, q, waiting_evt)
        api.sleep(0)
        q.send('hi')
        self.assertEquals(dying_evt.wait(), 'timed out')
        self.assertEquals(waiting_evt.wait(), 'hi')
    def test_max_size(self):
        q = coros.queue(2)
        results = []

        def putter(q):
            q.send("a")
            results.append("a")
            q.send("b")
            results.append("b")
            q.send("c")
            results.append("c")

        spawn(putter, q)
        sleep(0)
        self.assertEquals(results, ["a", "b"])
        self.assertEquals(q.wait(), "a")
        sleep(0)
        self.assertEquals(results, ["a", "b", "c"])
        self.assertEquals(q.wait(), "b")
        self.assertEquals(q.wait(), "c")
Esempio n. 48
0
    def test_max_size(self):
        q = coros.queue(2)
        results = []

        def putter(q):
            q.send('a')
            results.append('a')
            q.send('b')
            results.append('b')
            q.send('c')
            results.append('c')

        spawn(putter, q)
        sleep(0)
        self.assertEqual(results, ['a', 'b'])
        self.assertEqual(q.wait(), 'a')
        sleep(0)
        self.assertEqual(results, ['a', 'b', 'c'])
        self.assertEqual(q.wait(), 'b')
        self.assertEqual(q.wait(), 'c')
Esempio n. 49
0
    def test_two_waiters_one_dies(self):
        def waiter(q, evt):
            evt.send(q.wait())
        def do_receive(q, evt):
            eventlet.Timeout(0, RuntimeError())
            try:
                result = q.wait()
                evt.send(result)
            except RuntimeError:
                evt.send('timed out')

        q = coros.queue()
        dying_evt = Event()
        waiting_evt = Event()
        spawn(do_receive, q, dying_evt)
        spawn(waiter, q, waiting_evt)
        sleep(0)
        q.send('hi')
        self.assertEqual(dying_evt.wait(), 'timed out')
        self.assertEqual(waiting_evt.wait(), 'hi')
Esempio n. 50
0
    def test_exhaustion(self):
        waiter = coros.queue(0)
        def consumer():
            gotten = None
            try:
                gotten = self.pool.get()
            finally:
                waiter.send(gotten)

        api.spawn(consumer)

        one, two, three, four = (
            self.pool.get(), self.pool.get(), self.pool.get(), self.pool.get())
        self.assertEquals(self.pool.free(), 0)

        # Let consumer run; nothing will be in the pool, so he will wait
        api.sleep(0)

        # Wake consumer
        self.pool.put(one)

        # wait for the consumer
        self.assertEquals(waiter.wait(), one)
Esempio n. 51
0
    def test_exhaustion(self):
        waiter = coros.queue(0)

        def consumer():
            gotten = None
            try:
                gotten = self.pool.get()
            finally:
                waiter.send(gotten)

        api.spawn(consumer)

        one, two, three, four = (self.pool.get(), self.pool.get(),
                                 self.pool.get(), self.pool.get())
        self.assertEquals(self.pool.free(), 0)

        # Let consumer run; nothing will be in the pool, so he will wait
        api.sleep(0)

        # Wake consumer
        self.pool.put(one)

        # wait for the consumer
        self.assertEquals(waiter.wait(), one)
Esempio n. 52
0
 def test_send_exception_first(self):
     q = coros.queue()
     q.send(exc=RuntimeError())
     self.assertRaises(RuntimeError, q.wait)
Esempio n. 53
0
    def generate_results(self, function, iterable, qsize=None):
        """For each tuple (sequence) in *iterable*, launch ``function(*tuple)``
        in its own coroutine -- like ``itertools.starmap()``, but in parallel.
        Yield each of the values returned by ``function()``, in the order
        they're completed rather than the order the coroutines were launched.

        Iteration stops when we've yielded results for each arguments tuple in
        *iterable*. Unlike :meth:`wait_all` and :meth:`process_all`, this
        function does not wait for any previously-submitted :meth:`execute` or
        :meth:`execute_async` calls.

        Results are temporarily buffered in a queue. If you pass *qsize=*, this
        value is used to limit the max size of the queue: an attempt to buffer
        too many results will suspend the completed :class:`CoroutinePool`
        coroutine until the requesting coroutine (the caller of
        :meth:`generate_results`) has retrieved one or more results by calling
        this generator-iterator's ``next()``.

        If any coroutine raises an uncaught exception, that exception will
        propagate to the requesting coroutine via the corresponding ``next()``
        call.

        What I particularly want these tests to illustrate is that using this
        generator function::

            for result in generate_results(function, iterable):
                # ... do something with result ...
                pass

        executes coroutines at least as aggressively as the classic eventlet
        idiom::

            events = [pool.execute(function, *args) for args in iterable]
            for event in events:
                result = event.wait()
                # ... do something with result ...

        even without a distinct event object for every arg tuple in *iterable*,
        and despite the funny flow control from interleaving launches of new
        coroutines with yields of completed coroutines' results.

        (The use case that makes this function preferable to the classic idiom
        above is when the *iterable*, which may itself be a generator, produces
        millions of items.)

        >>> from eventlet import coros
        >>> import string
        >>> pool = coros.CoroutinePool(max_size=5)
        >>> pausers = [coros.Event() for x in xrange(2)]
        >>> def longtask(evt, desc):
        ...     print "%s woke up with %s" % (desc, evt.wait())
        ...
        >>> pool.launch_all(longtask, zip(pausers, "AB"))
        >>> def quicktask(desc):
        ...     print "returning %s" % desc
        ...     return desc
        ...

        (Instead of using a ``for`` loop, step through :meth:`generate_results`
        items individually to illustrate timing)

        >>> step = iter(pool.generate_results(quicktask, string.ascii_lowercase))
        >>> print step.next()
        returning a
        returning b
        returning c
        a
        >>> print step.next()
        b
        >>> print step.next()
        c
        >>> print step.next()
        returning d
        returning e
        returning f
        d
        >>> pausers[0].send("A")
        >>> print step.next()
        e
        >>> print step.next()
        f
        >>> print step.next()
        A woke up with A
        returning g
        returning h
        returning i
        g
        >>> print "".join([step.next() for x in xrange(3)])
        returning j
        returning k
        returning l
        returning m
        hij
        >>> pausers[1].send("B")
        >>> print "".join([step.next() for x in xrange(4)])
        B woke up with B
        returning n
        returning o
        returning p
        returning q
        klmn
        """
        # Get an iterator because of our funny nested loop below. Wrap the
        # iterable in enumerate() so we count items that come through.
        tuples = iter(enumerate(iterable))
        # If the iterable is empty, this whole function is a no-op, and we can
        # save ourselves some grief by just quitting out. In particular, once
        # we enter the outer loop below, we're going to wait on the queue --
        # but if we launched no coroutines with that queue as the destination,
        # we could end up waiting a very long time.
        try:
            index, args = tuples.next()
        except StopIteration:
            return
        # From this point forward, 'args' is the current arguments tuple and
        # 'index+1' counts how many such tuples we've seen.
        # This implementation relies on the fact that _execute() accepts an
        # event-like object, and -- unless it's None -- the completed
        # coroutine calls send(result). We slyly pass a queue rather than an
        # event -- the same queue instance for all coroutines. This is why our
        # queue interface intentionally resembles the event interface.
        q = coros.queue(max_size=qsize)
        # How many results have we yielded so far?
        finished = 0
        # This first loop is only until we've launched all the coroutines. Its
        # complexity is because if iterable contains more args tuples than the
        # size of our pool, attempting to _execute() the (poolsize+1)th
        # coroutine would suspend until something completes and send()s its
        # result to our queue. But to keep down queue overhead and to maximize
        # responsiveness to our caller, we'd rather suspend on reading the
        # queue. So we stuff the pool as full as we can, then wait for
        # something to finish, then stuff more coroutines into the pool.
        try:
            while True:
                # Before each yield, start as many new coroutines as we can fit.
                # (The self.free() test isn't 100% accurate: if we happen to be
                # executing in one of the pool's coroutines, we could _execute()
                # without waiting even if self.free() reports 0. See _execute().)
                # The point is that we don't want to wait in the _execute() call,
                # we want to wait in the q.wait() call.
                # IMPORTANT: at start, and whenever we've caught up with all
                # coroutines we've launched so far, we MUST iterate this inner
                # loop at least once, regardless of self.free() -- otherwise the
                # q.wait() call below will deadlock!
                # Recall that index is the index of the NEXT args tuple that we
                # haven't yet launched. Therefore it counts how many args tuples
                # we've launched so far.
                while self.free() > 0 or finished == index:
                    # Just like the implementation of execute_async(), save that
                    # we're passing our queue instead of None as the "event" to
                    # which to send() the result.
                    self._execute(q, function, args, {})
                    # We've consumed that args tuple, advance to next.
                    index, args = tuples.next()
                # Okay, we've filled up the pool again, yield a result -- which
                # will probably wait for a coroutine to complete. Although we do
                # have q.ready(), so we could iterate without waiting, we avoid
                # that because every yield could involve considerable real time.
                # We don't know how long it takes to return from yield, so every
                # time we do, take the opportunity to stuff more requests into the
                # pool before yielding again.
                yield q.wait()
                # Be sure to count results so we know when to stop!
                finished += 1
        except StopIteration:
            pass
        # Here we've exhausted the input iterable. index+1 is the total number
        # of coroutines we've launched. We probably haven't yielded that many
        # results yet. Wait for the rest of the results, yielding them as they
        # arrive.
        while finished < index + 1:
            yield q.wait()
            finished += 1
Esempio n. 54
0
 def test_send_first(self):
     q = coros.queue()
     q.send('hi')
     self.assertEqual(q.wait(), 'hi')