diff --git a/lib/tfw/yaml_fsm.py b/lib/tfw/yaml_fsm.py index fe854ba..4b09d5c 100644 --- a/lib/tfw/yaml_fsm.py +++ b/lib/tfw/yaml_fsm.py @@ -1,5 +1,6 @@ -from subprocess import Popen +from subprocess import Popen, run from functools import partial +from contextlib import suppress import yaml from transitions import State @@ -13,6 +14,7 @@ class YamlFSM(FSMBase): self.for_config_states_and_transitions_do(self.patch_config_callbacks) self.setup_states() super().__init__() # FSMBase.__init__() requires states + self.for_config_states_and_transitions_do(self.subscribe_and_remove_predicates) self.setup_transitions() @staticmethod @@ -38,6 +40,24 @@ class YamlFSM(FSMBase): if key in topatch: json_obj[key] = partial(self.run, json_obj[key]) + def subscribe_and_remove_predicates(self, json_obj): + for key in json_obj: + if key == 'predicates': + for predicate in json_obj[key]: + self.subscribe_predicate( + json_obj['trigger'], + partial( + self.statuscode_is_zero, + predicate + ) + ) + with suppress(KeyError): + json_obj.pop('predicates') + @staticmethod def run(command, event): Popen(command, shell=True) + + @staticmethod + def statuscode_is_zero(command): + return run(command, shell=True).returncode == 0