Skip to content

Commit

Permalink
🐛 FIX: Cleanup process event hooks (#200)
Browse files Browse the repository at this point in the history
On Process close/cleanup event hooks are removed,
in part to not persist cyclic dependencies of hooks <-> Process.
Once a process is closed, it will also not raise an Exception
if a hook tries to unregister itself (but has already been removed).
  • Loading branch information
chrisjsewell authored Feb 2, 2021
1 parent 33f4e9f commit 7004bd9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
3 changes: 3 additions & 0 deletions plumpy/base/state_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,9 @@ def add_state_event_callback(self, hook: Hashable, callback: EVENT_CALLBACK_TYPE
self._event_callbacks.setdefault(hook, []).append(callback)

def remove_state_event_callback(self, hook: Hashable, callback: EVENT_CALLBACK_TYPE) -> None:
if getattr(self, '_closed', False):
# if the process is closed, then all callbacks have already been removed
return None
try:
self._event_callbacks[hook].remove(callback)
except (KeyError, ValueError):
Expand Down
22 changes: 11 additions & 11 deletions plumpy/processes.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,17 +317,16 @@ def try_killing(future: futures.Future) -> None:

def _setup_event_hooks(self) -> None:
"""Set the event hooks to process, when it is created or loaded(recreated)."""
self.add_state_event_callback(
state_machine.StateEventHook.ENTERING_STATE,
lambda _s, _h, state: self.on_entering(cast(process_states.State, state))
)
self.add_state_event_callback(
state_machine.StateEventHook.ENTERED_STATE,
lambda _s, _h, from_state: self.on_entered(cast(Optional[process_states.State], from_state))
)
self.add_state_event_callback(
state_machine.StateEventHook.EXITING_STATE, lambda _s, _h, _state: self.on_exiting()
)
event_hooks = {
state_machine.StateEventHook.ENTERING_STATE:
lambda _s, _h, state: self.on_entering(cast(process_states.State, state)),
state_machine.StateEventHook.ENTERED_STATE:
lambda _s, _h, from_state: self.on_entered(cast(Optional[process_states.State], from_state)),
state_machine.StateEventHook.EXITING_STATE:
lambda _s, _h, _state: self.on_exiting()
}
for hook, callback in event_hooks.items():
self.add_state_event_callback(hook, callback)

@property
def creation_time(self) -> Optional[float]:
Expand Down Expand Up @@ -845,6 +844,7 @@ def on_close(self) -> None:
self.logger.exception('Exception calling cleanup method %s', cleanup)
self._cleanups = None
finally:
self._event_callbacks = {}
self._closed = True

def _fire_event(self, evt: Callable[..., Any], *args: Any, **kwargs: Any) -> None:
Expand Down

0 comments on commit 7004bd9

Please sign in to comment.