Example #1
0
def test_all_actors_can_be_stopped_through_registry(a_actor_refs,
                                                    b_actor_refs):
    assert len(ActorRegistry.get_all()) == 8

    ActorRegistry.stop_all(block=True)

    assert len(ActorRegistry.get_all()) == 0
Example #2
0
 def test_broadcast_sends_message_to_all_actors_of_given_class(self):
     ActorRegistry.broadcast({'command': 'foo'}, target_class=self.AnActor)
     for actor_ref in ActorRegistry.get_by_class(self.AnActor):
         received_messages = actor_ref.proxy().received_messages.get()
         self.assert_({'command': 'foo'} in received_messages)
     for actor_ref in ActorRegistry.get_by_class(self.BeeActor):
         received_messages = actor_ref.proxy().received_messages.get()
         self.assert_({'command': 'foo'} not in received_messages)
Example #3
0
 def _handle_failure(self, exception_type, exception_value, traceback):
     """Logs unexpected failures, unregisters and stops the actor."""
     logger.error(
         'Unhandled exception in {}:'.format(self),
         exc_info=(exception_type, exception_value, traceback),
     )
     ActorRegistry.unregister(self.actor_ref)
     self.actor_stopped.set()
Example #4
0
 def test_broadcast_sends_message_to_all_actors_of_given_class_name(self):
     ActorRegistry.broadcast({'command': 'foo'}, target_class='AnActor')
     for actor_ref in ActorRegistry.get_by_class(self.AnActor):
         received_messages = actor_ref.proxy().received_messages.get()
         self.assertTrue({'command': 'foo'} in received_messages)
     for actor_ref in ActorRegistry.get_by_class(self.BeeActor):
         received_messages = actor_ref.proxy().received_messages.get()
         self.assertTrue({'command': 'foo'} not in received_messages)
Example #5
0
 def _handle_failure(self, exception_type, exception_value, traceback):
     """Logs unexpected failures, unregisters and stops the actor."""
     logger.error(
         'Unhandled exception in {}:'.format(self),
         exc_info=(exception_type, exception_value, traceback),
     )
     ActorRegistry.unregister(self.actor_ref)
     self.actor_stopped.set()
Example #6
0
    def _actor_loop(self):
        """
        The actor's event loop.

        This is the method that will be executed by the thread or greenlet.
        """
        try:
            self.on_start()
        except Exception:
            self._handle_failure(*sys.exc_info())

        while not self.actor_stopped.is_set():
            envelope = self.actor_inbox.get()
            try:
                response = self._handle_receive(envelope.message)
                if envelope.reply_to is not None:
                    envelope.reply_to.set(response)
            except Exception:
                if envelope.reply_to is not None:
                    logger.info(
                        'Exception returned from {} to caller:'.format(self),
                        exc_info=sys.exc_info(),
                    )
                    envelope.reply_to.set_exception()
                else:
                    self._handle_failure(*sys.exc_info())
                    try:
                        self.on_failure(*sys.exc_info())
                    except Exception:
                        self._handle_failure(*sys.exc_info())
            except BaseException:
                exception_value = sys.exc_info()[1]
                logger.debug(
                    '{!r} in {}. Stopping all actors.'.format(
                        exception_value, self
                    )
                )
                self._stop()
                ActorRegistry.stop_all()

        while not self.actor_inbox.empty():
            envelope = self.actor_inbox.get()
            if envelope.reply_to is not None:
                if isinstance(envelope.message, messages._ActorStop):
                    envelope.reply_to.set(None)
                else:
                    envelope.reply_to.set_exception(
                        exc_info=(
                            ActorDeadError,
                            ActorDeadError(
                                '{} stopped before handling the message'.format(
                                    self.actor_ref
                                )
                            ),
                            None,
                        )
                    )
Example #7
0
def test_broadcast_sends_message_to_all_actors_if_no_target(
        a_actor_refs, b_actor_refs):
    ActorRegistry.broadcast({'command': 'foo'})

    running_actors = ActorRegistry.get_all()
    assert running_actors

    for actor_ref in running_actors:
        received_messages = actor_ref.proxy().received_messages.get()
        assert {'command': 'foo'} in received_messages
Example #8
0
 def test_actor_may_be_unregistered_multiple_times_without_error(self):
     ActorRegistry.unregister(self.ref)
     self.assert_(self.ref not in ActorRegistry.get_all())
     ActorRegistry.unregister(self.ref)
     self.assert_(self.ref not in ActorRegistry.get_all())
     ActorRegistry.register(self.ref)
     self.assert_(self.ref in ActorRegistry.get_all())
Example #9
0
 def test_actor_may_be_unregistered_multiple_times_without_error(self):
     ActorRegistry.unregister(self.ref)
     self.assertTrue(self.ref not in ActorRegistry.get_all())
     ActorRegistry.unregister(self.ref)
     self.assertTrue(self.ref not in ActorRegistry.get_all())
     ActorRegistry.register(self.ref)
     self.assertTrue(self.ref in ActorRegistry.get_all())
Example #10
0
    def test_fail(self):   # pylint: disable=R0201
        """ Test closing stream when fail. """
        def buggy_write(_):
            """ A buggy writable """
            raise ValueError()
        c = Collector.start(self.controller,
                            flexmock(write=buggy_write)
                            .should_receive('close').once().mock())

        c.tell(Record(None, 'Fail'))
        ActorRegistry.stop_all()
Example #11
0
def test_register_get_by_filter(actor_class):
    actor_ref = actor_class().start()
    # 已经完成注册啦了.
    # step1 测试 urn查询
    assert ActorRegistry.get_by_urn(actor_ref.actor_urn) == actor_ref
    # step2 测试类名查询
    assert ActorRegistry.get_by_class(actor_ref.actor_class)[0] == actor_ref
    # # step3 测试类名字符查询
    assert ActorRegistry.get_by_class_name(
        'CustomThreadingActor')[0] == actor_ref
    ActorRegistry.stop_all()
Example #12
0
def test_broadcast_sends_message_to_all_actors_of_given_class_name(
        actor_a_class, actor_b_class):
    ActorRegistry.broadcast({'command': 'foo'}, target_class='ActorA')

    for actor_ref in ActorRegistry.get_by_class(actor_a_class):
        received_messages = actor_ref.proxy().received_messages.get()
        assert {'command': 'foo'} in received_messages

    for actor_ref in ActorRegistry.get_by_class(actor_b_class):
        received_messages = actor_ref.proxy().received_messages.get()
        assert {'command': 'foo'} not in received_messages
Example #13
0
 def _stop(self):
     """
     Stops the actor immediately without processing the rest of the inbox.
     """
     ActorRegistry.unregister(self.actor_ref)
     self.actor_stopped.set()
     logger.debug('Stopped {}'.format(self))
     try:
         self.on_stop()
     except Exception:
         self._handle_failure(*sys.exc_info())
Example #14
0
 def _stop(self):
     """
     Stops the actor immediately without processing the rest of the inbox.
     """
     ActorRegistry.unregister(self.actor_ref)
     self.actor_stopped.set()
     logger.debug('Stopped {}'.format(self))
     try:
         self.on_stop()
     except Exception:
         self._handle_failure(*sys.exc_info())
Example #15
0
def test_broadcast_sends_message_to_all_actors_if_no_target(
    a_actor_refs, b_actor_refs
):
    ActorRegistry.broadcast({'command': 'foo'})

    running_actors = ActorRegistry.get_all()
    assert running_actors

    for actor_ref in running_actors:
        received_messages = actor_ref.proxy().received_messages.get()
        assert {'command': 'foo'} in received_messages
Example #16
0
def test_broadcast_sends_message_to_all_actors_of_given_class_name(
    actor_a_class, actor_b_class
):
    ActorRegistry.broadcast({'command': 'foo'}, target_class='ActorA')

    for actor_ref in ActorRegistry.get_by_class(actor_a_class):
        received_messages = actor_ref.proxy().received_messages.get()
        assert {'command': 'foo'} in received_messages

    for actor_ref in ActorRegistry.get_by_class(actor_b_class):
        received_messages = actor_ref.proxy().received_messages.get()
        assert {'command': 'foo'} not in received_messages
Example #17
0
def test_actor_may_be_unregistered_multiple_times_without_error(actor_ref):
    ActorRegistry.unregister(actor_ref)
    assert actor_ref not in ActorRegistry.get_all()

    ActorRegistry.unregister(actor_ref)
    assert actor_ref not in ActorRegistry.get_all()

    ActorRegistry.register(actor_ref)
    assert actor_ref in ActorRegistry.get_all()
Example #18
0
def test_all_actors_are_stopped_on_base_exception(events, actor_ref):
    assert len(ActorRegistry.get_all()) == 1
    assert not events.on_stop_was_called.is_set()

    actor_ref.tell({'command': 'raise base exception'})

    events.on_stop_was_called.wait(5)
    assert events.on_stop_was_called.is_set()
    assert len(ActorRegistry.get_all()) == 0

    events.on_stop_was_called.wait(5)
    assert events.on_stop_was_called.is_set()
    assert len(ActorRegistry.get_all()) == 0
Example #19
0
def test_all_actors_are_stopped_on_base_exception(events, actor_ref):
    assert len(ActorRegistry.get_all()) == 1
    assert not events.on_stop_was_called.is_set()

    actor_ref.tell({'command': 'raise base exception'})

    events.on_stop_was_called.wait(5)
    assert events.on_stop_was_called.is_set()
    assert len(ActorRegistry.get_all()) == 0

    events.on_stop_was_called.wait(5)
    assert events.on_stop_was_called.is_set()
    assert len(ActorRegistry.get_all()) == 0
Example #20
0
    def _actor_loop(self):
        """
        The actor's event loop.

        This is the method that will be executed by the thread or greenlet.
        """
        try:
            self.on_start()
        except Exception:
            self._handle_failure(*sys.exc_info())

        while not self.actor_stopped.is_set():
            envelope = self.actor_inbox.get()
            try:
                response = self._handle_receive(envelope.message)
                if envelope.reply_to is not None:
                    envelope.reply_to.set(response)
            except Exception:
                if envelope.reply_to is not None:
                    logger.info(
                        'Exception returned from {} to caller:'.format(self),
                        exc_info=sys.exc_info(),
                    )
                    envelope.reply_to.set_exception()
                else:
                    self._handle_failure(*sys.exc_info())
                    try:
                        self.on_failure(*sys.exc_info())
                    except Exception:
                        self._handle_failure(*sys.exc_info())
            except BaseException:
                exception_value = sys.exc_info()[1]
                logger.debug('{!r} in {}. Stopping all actors.'.format(
                    exception_value, self))
                self._stop()
                ActorRegistry.stop_all()

        while not self.actor_inbox.empty():
            envelope = self.actor_inbox.get()
            if envelope.reply_to is not None:
                if isinstance(envelope.message, messages._ActorStop):
                    envelope.reply_to.set(None)
                else:
                    envelope.reply_to.set_exception(exc_info=(
                        ActorDeadError,
                        ActorDeadError('{} stopped before handling the message'
                                       .format(self.actor_ref)),
                        None,
                    ))
Example #21
0
    def test_registration(self):
        f1 = FunctionalUnit((0, 0))
        f2 = FunctionalUnit((0, 1))
        f3 = FunctionalUnit((0, 2))

        a1 = OperatorActor.start(f1)
        time.sleep(.1)
        a2 = OperatorActor.start(f2)
        time.sleep(.1)
        a3 = OperatorActor.start(f3)
        time.sleep(.1)

        registry = ActorRegistry()
        for ref in [registry.get_by_urn(ref.actor_urn) for ref in [a1, a2, a3]]:
            a = ref._actor
Example #22
0
    def test_work(self):
        class Worker(object):
            def __init__(self, arg):
                self.arg = arg

            def work_on(self, task):
                print task
                return task

        flexmock(Worker).should_call('work_on').once().with_args(1)
        cr = Crawler.start(self.controller, self.tasksource, self.collector,
                           Worker, self.initargs)
        cr.tell(Task(None, 1))
        cr.stop()
        ActorRegistry.stop_all()
Example #23
0
def solve(study: Study) -> Study:
    waiter = Waiter(wait_ms=2)

    dispatcher = [create_dispatcher(name, node) for name, node in study.nodes.items()]
    for d in dispatcher:
        d.tell(Start())

    waiter.wait()

    nodes = {}
    for d in dispatcher:
        name, (cons, prod, borders) = d.ask(Next())
        nodes[name] = NodeQuantity(consumptions=cons, productions=prod, borders=borders)

    ActorRegistry.stop_all()
    return Study(nodes=nodes)
Example #24
0
 def send_event(self, event_name, data, player=None, client=None):
     if player:
         data['player'].update(player.get_stats_data())
     if client:
         c = data.get('client', {})
         c['device_type'] = client.device_type
         c['conn_type'] = client.conn_type
         c['client_timestamp'] = client.client_timestamp
         c['client_version'] = client.client_version
         c['device_os'] = client.device_os
         c['device_os_version'] = client.device_os_version
         c['openudid'] = client.openudid
         c['odin'] = client.odin
         c['mac_address'] = client.mac_address
         c['ios_ifa'] = client.ios_ifa
         c['android_id'] = client.android_id
         c['imei'] = client.imei
         c['android_ifa'] = client.android_ifa
         data['client'] = c
     msg = {"event_name": event_name,
            "timestamp": time.time(),
            "data": data}
     actor = ActorRegistry.get_by_class(StatsActor)
     actor = actor and actor[0] or StatsActor.start()
     actor.tell(msg)
Example #25
0
    def test_stop_all_stops_last_started_actor_first_if_blocking(
            self, mock_method):
        stopped_actors = []
        started_actors = [mock.Mock(name=i) for i in range(3)]
        started_actors[0].stop.side_effect = lambda *a, **kw: \
            stopped_actors.append(started_actors[0])
        started_actors[1].stop.side_effect = lambda *a, **kw: \
            stopped_actors.append(started_actors[1])
        started_actors[2].stop.side_effect = lambda *a, **kw: \
            stopped_actors.append(started_actors[2])
        ActorRegistry.get_all.return_value = started_actors

        ActorRegistry.stop_all(block=True)

        self.assertEqual(stopped_actors[0], started_actors[2])
        self.assertEqual(stopped_actors[1], started_actors[1])
        self.assertEqual(stopped_actors[2], started_actors[0])
Example #26
0
def test_register_stop_all(actor_class):
    """
    终止所有的actor
    :param actor_class:
    :return:
    """
    actor_class().start()
    assert ActorRegistry.stop_all()
Example #27
0
 def __init__(self):
     super(SleepyElder, self).__init__()
     self._lair = ActorRegistry.get_by_class_name('SpiderLair')[0]
     self._lair_command = {
         'command': 'kick_all',
         'data': None
     }
     self._work = True
Example #28
0
 def get_pactor_ref(self):
     """Get a reference to a pykka actor for this."""
     if not self.is_active():
         raise NotRunningError("This game is not active.")
     else:
         actor_urn = cache.get(str(self.uuid))
         actor_ref = ActorRegistry.get_by_urn(actor_urn)
     return actor_ref
Example #29
0
 def test_write(self):  # pylint: disable=R0201
     """ Test writing to a writable.  """
     mock_open = flexmock(sys.modules['__builtin__'])
     mock_open.should_call('open')
     (mock_open.should_receive('open')
      .with_args('newfile', 'wb')
      .and_return(
          flexmock(write=lambda x: None)
          .should_receive('write').with_args('READY').once().mock()
          .should_receive('flush').once().mock()
          .should_receive('close').once().mock()
          )
      )
     wr = FileWriter('newfile')
     c = Collector.start(self.controller, wr)
     c.tell(Record(None, 'READY'))
     ActorRegistry.stop_all()
Example #30
0
def test_actors_may_be_looked_up_by_class_name(actor_a_class, a_actor_refs,
                                               b_actor_refs):
    result = ActorRegistry.get_by_class_name('ActorA')

    for a_actor in a_actor_refs:
        assert a_actor in result
    for b_actor in b_actor_refs:
        assert b_actor not in result
Example #31
0
    def test_stop_all_stops_last_started_actor_first_if_blocking(
            self, mock_method):
        stopped_actors = []
        started_actors = [mock.Mock(name=i) for i in range(3)]
        started_actors[0].stop.side_effect = lambda *a, **kw: \
            stopped_actors.append(started_actors[0])
        started_actors[1].stop.side_effect = lambda *a, **kw: \
            stopped_actors.append(started_actors[1])
        started_actors[2].stop.side_effect = lambda *a, **kw: \
            stopped_actors.append(started_actors[2])
        ActorRegistry.get_all.return_value = started_actors

        ActorRegistry.stop_all(block=True)

        self.assertEqual(stopped_actors[0], started_actors[2])
        self.assertEqual(stopped_actors[1], started_actors[1])
        self.assertEqual(stopped_actors[2], started_actors[0])
Example #32
0
    def test_actor_processes_all_messages_before_stop_on_self_stops_it(self):
        self.actor_ref.ask({'command': 'message self then stop'})

        self.greetings_was_received.wait(5)
        self.assertTrue(self.greetings_was_received.is_set())

        self.on_stop_was_called.wait(5)

        self.assertEqual(0, len(ActorRegistry.get_all()))
Example #33
0
def test_actor_is_stopped_when_unhandled_exceptions_are_raised(
        actor_ref, events):
    assert not events.on_failure_was_called.is_set()

    actor_ref.tell({'command': 'raise exception'})

    events.on_failure_was_called.wait(5)
    assert events.on_failure_was_called.is_set()
    assert len(ActorRegistry.get_all()) == 0
Example #34
0
def test_actor_processes_all_messages_before_stop_on_self_stops_it(
        actor_ref, events):
    actor_ref.ask({'command': 'message self then stop'})

    events.greetings_was_received.wait(5)
    assert events.greetings_was_received.is_set()

    events.on_stop_was_called.wait(5)
    assert len(ActorRegistry.get_all()) == 0
Example #35
0
    def test_actor_processes_all_messages_before_stop_on_self_stops_it(self):
        self.actor_ref.ask({'command': 'message self then stop'})

        self.greetings_was_received.wait(5)
        self.assertTrue(self.greetings_was_received.is_set())

        self.on_stop_was_called.wait(5)

        self.assertEqual(0, len(ActorRegistry.get_all()))
Example #36
0
def test_actors_may_be_looked_up_by_class_name(
    actor_a_class, a_actor_refs, b_actor_refs
):
    result = ActorRegistry.get_by_class_name('ActorA')

    for a_actor in a_actor_refs:
        assert a_actor in result
    for b_actor in b_actor_refs:
        assert b_actor not in result
Example #37
0
def test_actor_processes_all_messages_before_stop_on_self_stops_it(
    actor_ref, events
):
    actor_ref.ask({'command': 'message self then stop'})

    events.greetings_was_received.wait(5)
    assert events.greetings_was_received.is_set()

    events.on_stop_was_called.wait(5)
    assert len(ActorRegistry.get_all()) == 0
Example #38
0
def test_actor_is_stopped_when_unhandled_exceptions_are_raised(
    actor_ref, events
):
    assert not events.on_failure_was_called.is_set()

    actor_ref.tell({'command': 'raise exception'})

    events.on_failure_was_called.wait(5)
    assert events.on_failure_was_called.is_set()
    assert len(ActorRegistry.get_all()) == 0
Example #39
0
    def on_receive(self, msg):
        if msg['type'] == 'config':
            # Set the sixteenth note period for this Actor
            self.period = 1.0/msg['bpm']*60.0 / 4.0

            # Get NoteActor URN
            self.target = ActorRegistry.get_by_urn(msg['target'])
            self.tick(0)
        elif msg['type'] == 'play': self.playing = True; self.tick(0)
        elif msg['type'] == 'stop': self.playing = False
Example #40
0
def main():
    parser = argparse.ArgumentParser(
        description='Akka Spider')
    parser.add_argument('url',
                        help='URL seed, main url')

    parser.add_argument('-R', '--recursive-out-domain', action="store_true",
                        help='Continue recursion out of the domain')
    parser.add_argument('--ndownloaders', type=int, default=4, help='Number of downloaders')
    parser.add_argument('-w', '--write',  default='output.dot', help='Output file')
    args = parser.parse_args()

    if urlparse(args.url).scheme == '':
        raise Exception('Input url should contain scheme')
        return
    else:
        seed = [(args.url, args.url)]


    # Start actors
    queue = Queue.start().proxy()
    downloaders = map(
        lambda x: Downloader.start(queue).proxy()
        , range(args.ndownloaders))

    for url in seed:
        queue.push(url).get()

    if args.recursive_out_domain:
        exclusion_filter = lambda url: True
    else:
        exclusion_filter = lambda url: urlparse(url).netloc.endswith(urlparse(args.url).netloc)

    dot = scheduler(queue,
                    downloaders,
                    lambda: random.randrange(len(downloaders)),
                    exclusion_filter)

    with open(args.write, 'w') as f:
        f.write(dot.source)

    # Clean up
    ActorRegistry.stop_all()
Example #41
0
 def is_active(self):
     actor_urn = cache.get(str(self.uuid))
     if actor_urn:
         if ActorRegistry.get_by_urn(actor_urn):
             return True
         else:
             cache.delete(str(self.uuid))
             return False
     else:
         return False
Example #42
0
def test_stop_all_stops_last_started_actor_first_if_blocking(mocker):
    mocker.patch.object(ActorRegistry, 'get_all')

    stopped_actors = []
    started_actors = [mocker.Mock(name=i) for i in range(3)]
    started_actors[0].stop.side_effect = lambda *a, **kw: stopped_actors.append(
        started_actors[0]
    )
    started_actors[1].stop.side_effect = lambda *a, **kw: stopped_actors.append(
        started_actors[1]
    )
    started_actors[2].stop.side_effect = lambda *a, **kw: stopped_actors.append(
        started_actors[2]
    )
    ActorRegistry.get_all.return_value = started_actors

    ActorRegistry.stop_all(block=True)

    assert stopped_actors[0] == started_actors[2]
    assert stopped_actors[1] == started_actors[1]
    assert stopped_actors[2] == started_actors[0]
Example #43
0
def test_stop_all_stops_last_started_actor_first_if_blocking(mocker):
    mocker.patch.object(ActorRegistry, 'get_all')

    stopped_actors = []
    started_actors = [mocker.Mock(name=i) for i in range(3)]
    started_actors[
        0].stop.side_effect = lambda *a, **kw: stopped_actors.append(
            started_actors[0])
    started_actors[
        1].stop.side_effect = lambda *a, **kw: stopped_actors.append(
            started_actors[1])
    started_actors[
        2].stop.side_effect = lambda *a, **kw: stopped_actors.append(
            started_actors[2])
    ActorRegistry.get_all.return_value = started_actors

    ActorRegistry.stop_all(block=True)

    assert stopped_actors[0] == started_actors[2]
    assert stopped_actors[1] == started_actors[1]
    assert stopped_actors[2] == started_actors[0]
Example #44
0
    def test_fatalfailwork(self):
        class Worker(object):
            def __init__(self, arg):
                self.arg = arg

            def work_on(self, task):
                pass

        ctl = (flexmock(tell=lambda x: None)
               .should_receive('tell').once()
               .with_args(Resignition).mock())

        (flexmock(Worker, work_on=lambda x: None)
         .should_receive('work_on').once()
         .with_args(1).and_raise(ValueError()))

        cr = Crawler.start(ctl, self.tasksource, self.collector,
                           Worker, self.initargs)
        cr.tell(Task(None, 1))
        cr.stop()
        ActorRegistry.stop_all()
Example #45
0
def test_actor_may_be_registered_manually(actor_ref):
    ActorRegistry.unregister(actor_ref)
    assert actor_ref not in ActorRegistry.get_all()

    ActorRegistry.register(actor_ref)

    assert actor_ref in ActorRegistry.get_all()
Example #46
0
def test_actor_may_be_registered_manually(actor_ref):
    ActorRegistry.unregister(actor_ref)
    assert actor_ref not in ActorRegistry.get_all()

    ActorRegistry.register(actor_ref)

    assert actor_ref in ActorRegistry.get_all()
Example #47
0
    def start(cls, *args, **kwargs):
        """
        Start an actor and register it in the
        :class:`ActorRegistry <pykka.ActorRegistry>`.

        Any arguments passed to :meth:`start` will be passed on to the class
        constructor.

        Behind the scenes, the following is happening when you call
        :meth:`start`:

        1. The actor is created:

           1. :attr:`actor_urn` is initialized with the assigned URN.

           2. :attr:`actor_inbox` is initialized with a new actor inbox.

           3. :attr:`actor_ref` is initialized with a :class:`pykka.ActorRef`
              object for safely communicating with the actor.

           4. At this point, your :meth:`__init__()` code can run.

        2. The actor is registered in :class:`pykka.ActorRegistry`.

        3. The actor receive loop is started by the actor's associated
           thread/greenlet.

        :returns: a :class:`ActorRef` which can be used to access the actor in
            a safe manner
        """
        obj = cls(*args, **kwargs)
        assert obj.actor_ref is not None, (
            'Actor.__init__() have not been called. '
            'Did you forget to call super() in your override?'
        )
        ActorRegistry.register(obj.actor_ref)
        logger.debug('Starting {}'.format(obj))
        obj._start_actor_loop()
        return obj.actor_ref
Example #48
0
    def test_all_actors_are_stopped_on_base_exception(self):
        start_event = self.event_class()
        stop_event = self.event_class()
        fail_event = self.event_class()
        registered_event = self.event_class()
        greetings_event = self.event_class()
        self.AnActor.start(
            on_start_was_called=start_event,
            on_stop_was_called=stop_event,
            on_failure_was_called=fail_event,
            actor_was_registered_before_on_start_was_called=registered_event,
            greetings_was_received=greetings_event)

        self.assertEqual(2, len(ActorRegistry.get_all()))
        self.assertFalse(self.on_stop_was_called.is_set())
        self.actor_ref.tell({'command': 'raise base exception'})
        self.on_stop_was_called.wait(5)
        self.assertTrue(self.on_stop_was_called.is_set())
        self.assert_(1 >= len(ActorRegistry.get_all()))
        stop_event.wait(5)
        self.assertTrue(stop_event.is_set())
        self.assertEqual(0, len(ActorRegistry.get_all()))
Example #49
0
    def test_all_actors_are_stopped_on_base_exception(self):
        start_event = self.event_class()
        stop_event = self.event_class()
        fail_event = self.event_class()
        registered_event = self.event_class()
        greetings_event = self.event_class()
        self.AnActor.start(
            on_start_was_called=start_event,
            on_stop_was_called=stop_event,
            on_failure_was_called=fail_event,
            actor_was_registered_before_on_start_was_called=registered_event,
            greetings_was_received=greetings_event)

        self.assertEqual(2, len(ActorRegistry.get_all()))
        self.assertFalse(self.on_stop_was_called.is_set())
        self.actor_ref.tell({'command': 'raise base exception'})
        self.on_stop_was_called.wait(5)
        self.assertTrue(self.on_stop_was_called.is_set())
        self.assert_(1 >= len(ActorRegistry.get_all()))
        stop_event.wait(5)
        self.assertTrue(stop_event.is_set())
        self.assertEqual(0, len(ActorRegistry.get_all()))
 def test_setup_1(self):  # check nothing crashes
     sys = UnitSystem()
     supervisor = SupervisorActor.start()
     InputActor.start(sys.create_input_paper_stack((0, 1))),
     OutputActor.start(sys.create_output_paper_stack((3, 1))),
     ConveyorActor.start(sys.create_conveyor((1, 1))),
     ConveyorActor.start(sys.create_conveyor((2, 1))),
     PlotterActor.start(sys.create_plotter((1, 0), color=Color.Red)),
     PlotterActor.start(sys.create_plotter((2, 0), color=Color.Green)),
     PlotterActor.start(sys.create_plotter((1, 3), color=Color.Yellow)),
     PlotterActor.start(sys.create_plotter((2, 3), color=Color.Blue))
     time.sleep(10)
     ActorRegistry().stop_all(block=True)
Example #51
0
    def __init__(self,
                 name,
                 min_exchange: int = 1,
                 consumptions: List[Consumption] = [],
                 productions: List[Production] = [],
                 borders: List[Border] = []):
        super().__init__()

        self.name = name
        self.broker = Broker(name=name,
                             tell=self.tell_to,
                             ask=self.ask_to,
                             min_exchange=min_exchange,
                             consumptions=consumptions,
                             productions=productions,
                             borders=borders)

        self.waiter = Waiter()
        self.events = []

        self.actor_ref.actor_urn = name
        ActorRegistry.register(self.actor_ref)
Example #52
0
    def start(cls, *args, **kwargs):
        """
        Start an actor and register it in the
        :class:`ActorRegistry <pykka.ActorRegistry>`.

        Any arguments passed to :meth:`start` will be passed on to the class
        constructor.

        Behind the scenes, the following is happening when you call
        :meth:`start`:

        1. The actor is created:

           1. :attr:`actor_urn` is initialized with the assigned URN.

           2. :attr:`actor_inbox` is initialized with a new actor inbox.

           3. :attr:`actor_ref` is initialized with a :class:`pykka.ActorRef`
              object for safely communicating with the actor.

           4. At this point, your :meth:`__init__()` code can run.

        2. The actor is registered in :class:`pykka.ActorRegistry`.

        3. The actor receive loop is started by the actor's associated
           thread/greenlet.

        :returns: a :class:`ActorRef` which can be used to access the actor in
            a safe manner
        """
        obj = cls(*args, **kwargs)
        assert obj.actor_ref is not None, (
            'Actor.__init__() have not been called. '
            'Did you forget to call super() in your override?')
        ActorRegistry.register(obj.actor_ref)
        logger.debug('Starting {}'.format(obj))
        obj._start_actor_loop()
        return obj.actor_ref
Example #53
0
def spider_info(spider_name):
    spider = ActorRegistry.get_by_class_name('SpiderLair')[0].ask({
        'command': 'get_spider_by_name',
        'data': spider_name
    })
    if spider:
        spider_info_result = spider.ask({
            'command': 'get_settings_and_info'
        })
        return jsonify(spider_info_result)
    return jsonify({
        'result': '500',
        'message': 'No spider with this name'
    })
Example #54
0
 def on_receive(self, msg):
     if msg['type'] == 'config':
         self.gui_target = ActorRegistry.get_by_urn(msg['gui_target'])
     elif msg['type'] == 'seq-config':
         # Reset the Euclidean rhythm at seq_num using the parameters k and n
         self.seq[msg['seq_num']] = {'i': msg['seq_num'],
                                     'r': euclidean_rhythm(msg['k'], msg['n']), 
                                     'n': self.seq[msg['seq_num']]['n']}
     elif msg['type'] == 'seq-mute':
         self.mutes[msg['seq_num']] = not self.mutes[msg['seq_num']]
         self.gui_target.tell({'type': 'show-mute', 
                               'seq_num': msg['seq_num'], 
                               'muted': self.mutes[msg['seq_num']]})
     elif msg['type'] == 'tick': 
         map(self.send, self.seq)
 def test_setup_2(self):  # smaller setup
     sys = UnitSystem()
     supervisor = SupervisorActor.start()
     InputActor.start(sys.create_input_paper_stack((0, 1))),
     ops = sys.create_output_paper_stack((2, 1))
     OutputActor.start(ops),
     ConveyorActor.start(sys.create_conveyor((1, 1))),
     PlotterActor.start(sys.create_plotter((1, 0), color=Color.Red)),
     PlotterActor.start(sys.create_plotter((1, 2), color=Color.Blue)),
     sheet_orders = [SheetOrder({Color.Red: 1})]
     for order in sheet_orders:
         supervisor.tell(SheetOrderMessage(order))
     SleepyActor.start(20).stop(True)
     for order in sheet_orders:
         self.assertIn(order, ops.received_sheets)
     ActorRegistry().stop_all(block=True)
Example #56
0
def spider_list():
    spiders = ActorRegistry.get_by_class_name('SpiderLair')[0].ask({
        'command': 'get_all_spiders'
    })
    result = []
    for spider in spiders:
        info = spider.ask({
            'command': 'get_info'
        })
        if info:
            if info.get('image_url'):
                info['image_url'] = url_for('static', filename=info['image_url'])
            result.append(info)
    return jsonify({
        'spiders_info': result
    })
Example #57
0
    def reply(self, message, text, opts=None):
        """Reply to the sender of the message with a containing the text

        :param message: the message to reply to
        :param text: the text to reply with
        :param opts: A dictionary of additional values to add to metadata
        :return: None
        """
        metadata = Metadata(source=self.actor_urn,
                            dest=message['metadata']['source']).__dict__
        metadata['opts'] = opts
        message = Message(text=text, metadata=metadata,
                          should_log=message['should_log']).__dict__
        dest_actor = ActorRegistry.get_by_urn(message['metadata']['dest'])
        if dest_actor is not None:
            dest_actor.tell(message)
        else:
            raise("Tried to send message to nonexistent actor")
Example #58
0
def iap(pid):
    g = Greeter.start()
    g.actor_urn = pid
    ActorRegistry.unregister(g)
    ActorRegistry.register(g)

    #greeter2 = Greeter.start(1).proxy()
    #greeter3 = Greeter.start(2).proxy()
    #greeter4 = Greeter.start(3).proxy()
    #greeter5 = Greeter.start(4).proxy()
    #a = ActorRegistry.get_all()
    #for i in a:
    #    ppid = i.proxy().pid.get()
    #    print (ppid, type(ppid))
    #    if ppid == '123':
    #        print('haha, got you')
    #    else:
    #        print(ppid)

    for i in ActorRegistry.get_all():
        print ('here')
        print(i.proxy().actor_urn.get(), type(i.proxy().actor_urn.get()))
        if i.proxy().actor_urn.get() == pid:
            print ('haha, got you')

    print ('=============')
    a = ActorRegistry.get_by_urn(pid)
    print (a)
    print ('=============')

    for i in ActorRegistry.get_all():
        print(i)
        print (i.__dict__)
        print ('here')
        print(i.proxy().actor_urn.get(), type(i.proxy().actor_urn.get()))
        if i.proxy().actor_urn.get() == 'asdf':
            print ('haha, got you')

    #future = greeter.pprint({'message':'%s' % pid})
    return 'as'
Example #59
0
from pykka import ThreadingActor
from pykka import ActorRegistry

class Adder(ThreadingActor):
  def add_one(self, i):
    return i + 1

class Greeter(ThreadingActor):
  def on_receive(self, message):
    print(repr(message))
    print("Hi there!")

if __name__ == '__main__':
  actor_ref = Greeter.start()
  actor_ref.tell({'msg': 'herp'})
#  data = [1,2,3,4]
#  adder = Adder.start().proxy()
#  for datum in data:
#    print(adder.add_one(datum))
  _ = input("press anything to stop")
  ActorRegistry.stop_all()
Example #60
0
 def on_failure(self, exception_type, exception_value, traceback):
     ref = ActorRegistry.get_by_urn(self.actor_urn)
     logger.exception('Lego crashed: ' + str(ref))
     logger.exception(exception_type)
     logger.exception(exception_value)