def add_reaction(self, state, event, reaction, *args, **kwargs):
        """Adds a reaction that may get triggered by the given event & state.

        Reaction callbacks may (depending on how the state machine is ran) be
        used after an event is processed (and a transition occurs) to cause the
        machine to react to the newly arrived at stable state.

        These callbacks are expected to accept three default positional
        parameters (although more can be passed in via *args and **kwargs,
        these will automatically get provided to the callback when it is
        activated *ontop* of the three default). The three default parameters
        are the last stable state, the new stable state and the event that
        caused the transition to this new stable state to be arrived at.

        The expected result of a callback is expected to be a new event that
        the callback wants the state machine to react to. This new event
        may (depending on how the state machine is ran) get processed (and
        this process typically repeats) until the state machine reaches a
        terminal state.
        """
        if self.frozen:
            raise excp.FrozenMachine()
        if state not in self._states:
            raise excp.NotFound("Can not add a reaction to event '%s' for an"
                                " undefined state '%s'" % (event, state))
        if not six.callable(reaction):
            raise ValueError("Reaction callback must be callable")
        if event not in self._states[state]['reactions']:
            self._states[state]['reactions'][event] = (reaction, args, kwargs)
        else:
            raise excp.Duplicate("State '%s' reaction to event '%s'"
                                 " already defined" % (state, event))
 def default_start_state(self, state):
     if self.frozen:
         raise excp.FrozenMachine()
     if state not in self._states:
         raise excp.NotFound("Can not set the default start state to"
                             " undefined state '%s'" % (state))
     self._default_start_state = state
    def add_transition(self, start, end, event, replace=False):
        """Adds an allowed transition from start -> end for the given event.

        :param start: starting state
        :param end: ending state
        :param event: event that causes start state to
                      transition to end state
        :param replace: replace existing event instead of raising a
                        :py:class:`~automaton.exceptions.Duplicate` exception
                        when the transition already exists.
        """
        if self.frozen:
            raise excp.FrozenMachine()
        if start not in self._states:
            raise excp.NotFound("Can not add a transition on event '%s' that"
                                " starts in a undefined state '%s'" %
                                (event, start))
        if end not in self._states:
            raise excp.NotFound("Can not add a transition on event '%s' that"
                                " ends in a undefined state '%s'" %
                                (event, end))
        if self._states[start]['terminal']:
            raise excp.InvalidState("Can not add a transition on event '%s'"
                                    " that starts in the terminal state '%s'" %
                                    (event, start))
        if event in self._transitions[start] and not replace:
            target = self._transitions[start][event]
            if target.name != end:
                raise excp.Duplicate(
                    "Cannot add transition from"
                    " '%(start_state)s' to '%(end_state)s'"
                    " on event '%(event)s' because a"
                    " transition from '%(start_state)s'"
                    " to '%(existing_end_state)s' on"
                    " event '%(event)s' already exists." % {
                        'existing_end_state': target.name,
                        'end_state': end,
                        'event': event,
                        'start_state': start
                    })
        else:
            target = _Jump(end, self._states[end]['on_enter'],
                           self._states[start]['on_exit'])
            self._transitions[start][event] = target
Exemplo n.º 4
0
    def default_start_state(self, state):
        """Sets the *default* start state that the machine should use.

        NOTE(harlowja): this will be used by ``initialize`` but only if that
        function is not given its own ``start_state`` that overrides this
        default.
        """
        if self.frozen:
            raise excp.FrozenMachine()
        if state not in self._states:
            raise excp.NotFound("Can not set the default start state to"
                                " undefined state '%s'" % (state))
        self._default_start_state = state
 def _pre_process_event(self, event):
     current = self._current
     if current is None:
         raise excp.NotInitialized("Can not process event '%s'; the state"
                                   " machine hasn't been initialized" %
                                   event)
     if self._states[current.name]['terminal']:
         raise excp.InvalidState("Can not transition from terminal"
                                 " state '%s' on event '%s'" %
                                 (current.name, event))
     if event not in self._transitions[current.name]:
         raise excp.NotFound("Can not transition from state '%s' on"
                             " event '%s' (no defined transition)" %
                             (current.name, event))
Exemplo n.º 6
0
    def run_iter(self, event, initialize=True):
        """Returns a iterator/generator that will run the state machine.

        This will keep a stack (hierarchy) of machines active and jumps through
        them as needed (depending on which machine handles which event) during
        the running lifecycle.

        NOTE(harlowja): only one runner iterator/generator should be active for
        a machine hierarchy, if this is not observed then it is possible for
        initialization and other local state to be corrupted and causes issues
        when running...
        """
        machines = [self._machine]
        if initialize:
            machines[-1].initialize()
        while True:
            old_state = machines[-1].current_state
            effect = self._process_event(machines, event)
            new_state = machines[-1].current_state
            try:
                machine = effect.machine
            except AttributeError:
                pass
            else:
                if machine is not None and machine is not machines[-1]:
                    machine.initialize()
                    machines.append(machine)
            try:
                sent_event = yield (old_state, new_state)
            except GeneratorExit:
                break
            if len(machines) == 1 and effect.terminal:
                # Only allow the top level machine to actually terminate the
                # execution, the rest of the nested machines must not handle
                # events if they wish to have the root machine terminate...
                break
            if effect.reaction is None and sent_event is None:
                raise excp.NotFound(_JUMPER_NOT_FOUND_TPL %
                                    (new_state, old_state, event))
            elif sent_event is not None:
                event = sent_event
            else:
                cb, args, kwargs = effect.reaction
                event = cb(old_state, new_state, event, *args, **kwargs)
Exemplo n.º 7
0
 def run_iter(self, event, initialize=True):
     if initialize:
         self._machine.initialize()
     while True:
         old_state = self._machine.current_state
         reaction, terminal = self._machine.process_event(event)
         new_state = self._machine.current_state
         try:
             sent_event = yield (old_state, new_state)
         except GeneratorExit:
             break
         if terminal:
             break
         if reaction is None and sent_event is None:
             raise excp.NotFound(_JUMPER_NOT_FOUND_TPL %
                                 (new_state, old_state, event))
         elif sent_event is not None:
             event = sent_event
         else:
             cb, args, kwargs = reaction
             event = cb(old_state, new_state, event, *args, **kwargs)
    def initialize(self, start_state=None):
        """Sets up the state machine (sets current state to start state...).

        :param start_state: explicit start state to use to initialize the
                            state machine to. If ``None`` is provided then
                            the machine's default start state will be used
                            instead.
        """
        if start_state is None:
            start_state = self._default_start_state
        if start_state not in self._states:
            raise excp.NotFound("Can not start from a undefined"
                                " state '%s'" % (start_state))
        if self._states[start_state]['terminal']:
            raise excp.InvalidState("Can not start from a terminal"
                                    " state '%s'" % (start_state))
        # No on enter will be called, since we are priming the state machine
        # and have not really transitioned from anything to get here, we will
        # though allow on_exit to be called on the event that causes this
        # to be moved from...
        self._current = _Jump(start_state, None,
                              self._states[start_state]['on_exit'])
Exemplo n.º 9
0
 def fun():
     with self.driver.fsm_reset_on_error():
         raise automaton_errors.NotFound('Oops!')