From 1230e04c3e196f6cfd614703dbc7ecf8f62ff74b Mon Sep 17 00:00:00 2001 From: Pim van Pelt Date: Sat, 9 Apr 2022 20:12:21 +0000 Subject: [PATCH] Refactor validators into a list, and add a custom validator function, which is passed the YAML as an argument, and will return (rv,msgs) to signal custom semantic validation results --- config/__init__.py | 56 +++++++++++++++++----------------------------- tests.py | 8 +++++++ 2 files changed, 29 insertions(+), 35 deletions(-) diff --git a/config/__init__.py b/config/__init__.py index 0b4d894..65808d6 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -69,6 +69,13 @@ class Validator(object): self.logger.addHandler(logging.NullHandler()) self.schema = schema + self.validators = [ + validate_bondethernets, + validate_interfaces, + validate_loopbacks, + validate_bridgedomains, + validate_vxlan_tunnels, + validate_taps ] def validate(self, yaml): ret_rv = True @@ -107,41 +114,12 @@ class Validator(object): self.logger.debug("Validating Semantics...") - rv, msgs = validate_bondethernets(yaml) - if msgs: - ret_msgs.extend(msgs) - if not rv: - ret_rv = False - - rv, msgs = validate_interfaces(yaml) - if msgs: - ret_msgs.extend(msgs) - if not rv: - ret_rv = False - - rv, msgs = validate_loopbacks(yaml) - if msgs: - ret_msgs.extend(msgs) - if not rv: - ret_rv = False - - rv, msgs = validate_bridgedomains(yaml) - if msgs: - ret_msgs.extend(msgs) - if not rv: - ret_rv = False - - rv, msgs = validate_vxlan_tunnels(yaml) - if msgs: - ret_msgs.extend(msgs) - if not rv: - ret_rv = False - - rv, msgs = validate_taps(yaml) - if msgs: - ret_msgs.extend(msgs) - if not rv: - ret_rv = False + for v in self.validators: + rv, msgs = v(yaml) + if msgs: + ret_msgs.extend(msgs) + if not rv: + ret_rv = False if ret_rv: self.logger.debug("Semantics correctly validated") @@ -162,3 +140,11 @@ class Validator(object): self.logger.info("Configuration validated successfully") return True + + def add_validator(self, func): + """ Add a validator function, which strictly takes the prototype + rv, msgs = func(yaml) + returning a Boolean success value in rv and a List of strings + in msgs. The function will be passed the configuration YAML and + gets to opine if it's valid or not. """ + self.validators.append(func) diff --git a/tests.py b/tests.py index 215d08e..6b6073b 100755 --- a/tests.py +++ b/tests.py @@ -27,6 +27,14 @@ except ImportError: print("ERROR: install argparse manually: sudo pip install argparse") sys.exit(-2) +def example_validator(yaml): + """ A simple example validator that takes the YAML configuration file as an input, + and returns a tuple of rv (return value, True is success), and a list of string + messages to the validation framework. """ + rv = True + msgs = [] + + return rv, msgs class YAMLTest(unittest.TestCase): def __init__(self, testName, yaml_filename, yaml_schema):