2010-03-26 21:32:16 +00:00
|
|
|
"""
|
|
|
|
SleekXMPP: The Sleek XMPP Library
|
|
|
|
Copyright (C) 2010 Nathanael C. Fritz
|
|
|
|
This file is part of SleekXMPP.
|
|
|
|
|
|
|
|
See the file license.txt for copying permission.
|
|
|
|
"""
|
2009-06-03 22:56:51 +00:00
|
|
|
import threading
|
2010-06-02 16:39:54 +00:00
|
|
|
import time
|
|
|
|
import logging
|
2009-06-03 22:56:51 +00:00
|
|
|
|
2010-06-03 18:12:06 +00:00
|
|
|
|
2009-06-03 22:56:51 +00:00
|
|
|
class StateMachine(object):
|
|
|
|
|
2010-06-02 16:39:54 +00:00
|
|
|
def __init__(self, states=[]):
|
2010-07-01 19:10:22 +00:00
|
|
|
self.lock = threading.Lock()
|
|
|
|
self.notifier = threading.Event()
|
2010-06-02 16:39:54 +00:00
|
|
|
self.__states= []
|
2009-06-03 22:56:51 +00:00
|
|
|
self.addStates(states)
|
2010-06-02 16:39:54 +00:00
|
|
|
self.__default_state = self.__states[0]
|
|
|
|
self.__current_state = self.__default_state
|
2009-06-03 22:56:51 +00:00
|
|
|
|
|
|
|
def addStates(self, states):
|
2010-07-01 19:10:22 +00:00
|
|
|
self.lock.acquire()
|
|
|
|
try:
|
2009-06-03 22:56:51 +00:00
|
|
|
for state in states:
|
2010-06-02 16:39:54 +00:00
|
|
|
if state in self.__states:
|
|
|
|
raise IndexError("The state '%s' is already in the StateMachine." % state)
|
|
|
|
self.__states.append( state )
|
2010-07-01 19:10:22 +00:00
|
|
|
finally: self.lock.release()
|
2009-06-03 22:56:51 +00:00
|
|
|
|
|
|
|
|
2010-06-03 18:12:06 +00:00
|
|
|
def transition(self, from_state, to_state, wait=0.0, func=None, args=[], kwargs={} ):
|
2010-06-02 16:39:54 +00:00
|
|
|
'''
|
|
|
|
Transition from the given `from_state` to the given `to_state`.
|
|
|
|
This method will return `True` if the state machine is now in `to_state`. It
|
|
|
|
will return `False` if a timeout occurred the transition did not occur.
|
|
|
|
If `wait` is 0 (the default,) this method returns immediately if the state machine
|
|
|
|
is not in `from_state`.
|
|
|
|
|
|
|
|
If you want the thread to block and transition once the state machine to enters
|
|
|
|
`from_state`, set `wait` to a non-negative value. Note there is no 'block
|
|
|
|
indefinitely' flag since this leads to deadlock. If you want to wait indefinitely,
|
|
|
|
choose a reasonable value for `wait` (e.g. 20 seconds) and do so in a while loop like so:
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
while not thread_should_exit and not state_machine.transition('disconnected', 'connecting', wait=20 ):
|
|
|
|
pass # timeout will occur every 20s unless transition occurs
|
|
|
|
if thread_should_exit: return
|
|
|
|
# perform actions here after successful transition
|
|
|
|
|
2010-06-03 18:12:06 +00:00
|
|
|
This allows the thread to be responsive by setting `thread_should_exit=True`.
|
|
|
|
|
|
|
|
The optional `func` argument allows the user to pass a callable operation which occurs
|
|
|
|
within the context of the state transition (e.g. while the state machine is locked.)
|
|
|
|
If `func` returns a True value, the transition will occur. If `func` returns a non-
|
|
|
|
True value or if an exception is thrown, the transition will not occur. Any thrown
|
|
|
|
exception is not caught by the state machine and is the caller's responsibility to handle.
|
|
|
|
If `func` completes normally, this method will return the value returned by `func.` If
|
|
|
|
values for `args` and `kwargs` are provided, they are expanded and passed like so:
|
|
|
|
`func( *args, **kwargs )`.
|
2010-06-02 16:39:54 +00:00
|
|
|
'''
|
|
|
|
|
2010-06-03 18:12:06 +00:00
|
|
|
return self.transition_any( (from_state,), to_state, wait=wait,
|
|
|
|
func=func, args=args, kwargs=kwargs )
|
2010-06-02 16:39:54 +00:00
|
|
|
|
2010-06-07 17:16:02 +00:00
|
|
|
|
2010-06-03 18:12:06 +00:00
|
|
|
def transition_any(self, from_states, to_state, wait=0.0, func=None, args=[], kwargs={} ):
|
2010-06-02 16:39:54 +00:00
|
|
|
'''
|
|
|
|
Transition from any of the given `from_states` to the given `to_state`.
|
|
|
|
'''
|
|
|
|
|
2010-06-07 17:16:02 +00:00
|
|
|
if not (isinstance(from_states,tuple) or isinstance(from_states,list)):
|
|
|
|
raise ValueError( "from_states should be a list or tuple" )
|
|
|
|
|
|
|
|
for state in from_states:
|
|
|
|
if not state in self.__states:
|
|
|
|
raise ValueError( "StateMachine does not contain from_state %s." % state )
|
|
|
|
if not to_state in self.__states:
|
|
|
|
raise ValueError( "StateMachine does not contain to_state %s." % to_state )
|
2010-06-02 16:39:54 +00:00
|
|
|
|
2010-07-01 19:10:22 +00:00
|
|
|
|
|
|
|
start = time.time()
|
|
|
|
while not self.__current_state in from_states or not self.lock.acquire(False):
|
|
|
|
# detect timeout:
|
|
|
|
if time.time() >= start + wait: return False
|
|
|
|
self.notifier.wait(wait)
|
|
|
|
|
|
|
|
try: # lock is acquired; all other threads will return false or wait until notify/timeout
|
|
|
|
self.notifier.clear()
|
2010-06-02 16:39:54 +00:00
|
|
|
if self.__current_state in from_states: # should always be True due to lock
|
2010-07-01 19:10:22 +00:00
|
|
|
|
2010-06-03 18:12:06 +00:00
|
|
|
# Note that func might throw an exception, but that's OK, it aborts the transition
|
2010-07-01 19:10:22 +00:00
|
|
|
return_val = func(*args,**kwargs) if func is not None else True
|
2010-06-03 18:12:06 +00:00
|
|
|
|
|
|
|
# some 'false' value returned from func,
|
|
|
|
# indicating that transition should not occur:
|
|
|
|
if not return_val: return return_val
|
|
|
|
|
2010-06-02 16:39:54 +00:00
|
|
|
logging.debug(' ==== TRANSITION %s -> %s', self.__current_state, to_state)
|
2010-07-01 19:10:22 +00:00
|
|
|
self._set_state( to_state )
|
2010-06-03 18:12:06 +00:00
|
|
|
return return_val # some 'true' value returned by func or True if func was None
|
2009-06-03 22:56:51 +00:00
|
|
|
else:
|
2010-06-02 16:39:54 +00:00
|
|
|
logging.error( "StateMachine bug!! The lock should ensure this doesn't happen!" )
|
|
|
|
return False
|
2010-07-01 19:10:22 +00:00
|
|
|
finally:
|
|
|
|
self.notifier.set()
|
|
|
|
self.lock.release()
|
2010-06-02 16:39:54 +00:00
|
|
|
|
|
|
|
|
2010-06-07 17:16:02 +00:00
|
|
|
def transition_ctx(self, from_state, to_state, wait=0.0):
|
2010-06-07 18:41:42 +00:00
|
|
|
'''
|
|
|
|
Use the state machine as a context manager. The transition occurs on /exit/ from
|
|
|
|
the `with` context, so long as no exception is thrown. For example:
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
with state_machine.transition_ctx('one','two', wait=5) as locked:
|
|
|
|
if locked:
|
|
|
|
# the state machine is currently locked in state 'one', and will
|
|
|
|
# transition to 'two' when the 'with' statement ends, so long as
|
|
|
|
# no exception is thrown.
|
|
|
|
print 'Currently locked in state one: %s' % state_machine['one']
|
|
|
|
|
|
|
|
else:
|
|
|
|
# The 'wait' timed out, and no lock has been acquired
|
|
|
|
print 'Timed out before entering state "one"'
|
|
|
|
|
|
|
|
print 'Since no exception was thrown, we are now in state "two": %s' % state_machine['two']
|
|
|
|
|
|
|
|
|
|
|
|
The other main difference between this method and `transition()` is that the
|
2010-06-08 13:02:51 +00:00
|
|
|
state machine is locked for the duration of the `with` statement. Normally,
|
|
|
|
after a `transition()` occurs, the state machine is immediately unlocked and
|
2010-06-07 18:41:42 +00:00
|
|
|
available to another thread to call `transition()` again.
|
|
|
|
'''
|
|
|
|
|
2010-06-07 17:16:02 +00:00
|
|
|
if not from_state in self.__states:
|
2010-06-08 13:02:51 +00:00
|
|
|
raise ValueError( "StateMachine does not contain from_state %s." % from_state )
|
2010-06-07 17:16:02 +00:00
|
|
|
if not to_state in self.__states:
|
|
|
|
raise ValueError( "StateMachine does not contain to_state %s." % to_state )
|
|
|
|
|
|
|
|
return _StateCtx(self, from_state, to_state, wait)
|
|
|
|
|
|
|
|
|
2010-06-02 16:39:54 +00:00
|
|
|
def ensure(self, state, wait=0.0):
|
|
|
|
'''
|
|
|
|
Ensure the state machine is currently in `state`, or wait until it enters `state`.
|
|
|
|
'''
|
|
|
|
return self.ensure_any( (state,), wait=wait )
|
|
|
|
|
2010-06-07 17:16:02 +00:00
|
|
|
|
2010-06-02 16:39:54 +00:00
|
|
|
def ensure_any(self, states, wait=0.0):
|
|
|
|
'''
|
2010-07-01 19:10:22 +00:00
|
|
|
Ensure we are currently in one of the given `states` or wait until
|
|
|
|
we enter one of those states.
|
|
|
|
|
|
|
|
Note that due to the nature of the function, you cannot guarantee that
|
|
|
|
the entirety of some operation completes while you remain in a given
|
|
|
|
state. That would require acquiring and holding a lock, which
|
|
|
|
would mean no other threads could do the same. (You'd essentially
|
|
|
|
be serializing all of the threads that are 'ensuring' their tasks
|
|
|
|
occurred in some state.
|
2010-06-02 16:39:54 +00:00
|
|
|
'''
|
2010-06-07 17:16:02 +00:00
|
|
|
if not (isinstance(states,tuple) or isinstance(states,list)):
|
|
|
|
raise ValueError('states arg should be a tuple or list')
|
|
|
|
|
|
|
|
for state in states:
|
|
|
|
if not state in self.__states:
|
|
|
|
raise ValueError( "StateMachine does not contain state '%s'" % state )
|
2010-06-02 16:39:54 +00:00
|
|
|
|
2010-07-01 19:10:22 +00:00
|
|
|
# Locking never really gained us anything here, since the lock was released
|
|
|
|
# before the function returned anyways. The only thing it _did_ do was
|
|
|
|
# increase the probability that this function would block for longer than
|
|
|
|
# intended if a `transition` function or context was running while holding
|
|
|
|
# the lock.
|
|
|
|
start = time.time()
|
|
|
|
while not self.__current_state in states:
|
|
|
|
# detect timeout:
|
|
|
|
if time.time() >= start + wait: return False
|
|
|
|
self.notifier.wait(wait)
|
|
|
|
return True
|
2010-06-02 16:39:54 +00:00
|
|
|
|
2009-06-03 22:56:51 +00:00
|
|
|
|
2010-06-02 16:39:54 +00:00
|
|
|
def reset(self):
|
|
|
|
# TODO need to lock before calling this?
|
|
|
|
self.transition(self.__current_state, self._default_state)
|
2010-06-03 12:07:56 +00:00
|
|
|
|
|
|
|
|
2010-06-07 17:16:02 +00:00
|
|
|
def _set_state(self, state): #unsynchronized, only call internally after lock is acquired
|
|
|
|
self.__current_state = state
|
|
|
|
return state
|
|
|
|
|
|
|
|
|
2010-06-03 12:07:56 +00:00
|
|
|
def current_state(self):
|
|
|
|
'''
|
|
|
|
Return the current state name.
|
|
|
|
'''
|
|
|
|
return self.__current_state
|
|
|
|
|
2010-06-02 16:39:54 +00:00
|
|
|
|
|
|
|
def __getitem__(self, state):
|
|
|
|
'''
|
|
|
|
Non-blocking, non-synchronized test to determine if we are in the given state.
|
|
|
|
Use `StateMachine.ensure(state)` to wait until the machine enters a certain state.
|
|
|
|
'''
|
|
|
|
return self.__current_state == state
|
2010-06-07 17:58:15 +00:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return "".join(( "StateMachine(", ','.join(self.__states), "): ", self.__current_state ))
|
|
|
|
|
2009-06-03 22:56:51 +00:00
|
|
|
|
2010-06-07 17:16:02 +00:00
|
|
|
|
|
|
|
class _StateCtx:
|
|
|
|
|
|
|
|
def __init__( self, state_machine, from_state, to_state, wait ):
|
|
|
|
self.state_machine = state_machine
|
|
|
|
self.from_state = from_state
|
|
|
|
self.to_state = to_state
|
|
|
|
self.wait = wait
|
2010-07-01 19:10:22 +00:00
|
|
|
self._locked = False
|
2010-06-07 17:16:02 +00:00
|
|
|
|
2010-06-02 16:39:54 +00:00
|
|
|
def __enter__(self):
|
2010-06-07 17:16:02 +00:00
|
|
|
start = time.time()
|
2010-07-01 19:10:22 +00:00
|
|
|
while not self.state_machine[ self.from_state ] or not self.state_machine.lock.acquire(False):
|
2010-06-07 17:16:02 +00:00
|
|
|
# detect timeout:
|
|
|
|
if time.time() >= start + self.wait:
|
|
|
|
logging.debug('StateMachine timeout while waiting for state: %s', self.from_state )
|
2010-06-07 17:43:37 +00:00
|
|
|
return False
|
2010-07-01 19:10:22 +00:00
|
|
|
self.state_machine.notifier.wait(self.wait)
|
2010-06-07 17:16:02 +00:00
|
|
|
|
2010-07-01 19:10:22 +00:00
|
|
|
self._locked = True # lock has been acquired at this point
|
|
|
|
self.state_machine.notifier.clear()
|
2010-06-07 17:16:02 +00:00
|
|
|
logging.debug('StateMachine entered context in state: %s',
|
|
|
|
self.state_machine.current_state() )
|
2010-06-07 17:43:37 +00:00
|
|
|
return True
|
2010-06-02 16:39:54 +00:00
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
2010-06-07 17:16:02 +00:00
|
|
|
if exc_val is not None:
|
|
|
|
logging.exception( "StateMachine exception in context, remaining in state: %s\n%s:%s",
|
2010-07-01 19:10:22 +00:00
|
|
|
self.state_machine.current_state(), exc_type.__name__, exc_val )
|
|
|
|
|
|
|
|
if self._locked:
|
|
|
|
if exc_val is None:
|
|
|
|
logging.debug(' ==== TRANSITION %s -> %s',
|
|
|
|
self.state_machine.current_state(), self.to_state)
|
|
|
|
self.state_machine._set_state( self.to_state )
|
|
|
|
|
|
|
|
self.state_machine.notifier.set()
|
|
|
|
self.state_machine.lock.release()
|
|
|
|
|
2010-06-02 16:39:54 +00:00
|
|
|
return False # re-raise any exception
|
2009-06-03 22:56:51 +00:00
|
|
|
|