From d71a25e30a60d2beb5cf4e79dd2f52ead7ee9b8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Wed, 4 Jul 2018 18:11:42 +0200 Subject: [PATCH] Implement subscribing predicates found in yaml --- lib/tfw/yaml_fsm.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) 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