From 3beb55caaeab00bd43e120ee694e03d2f3c0b405 Mon Sep 17 00:00:00 2001 From: hygienic-books Date: Tue, 5 Jul 2022 16:59:49 +0200 Subject: [PATCH] feat(xml): Diff XML with active config, only store if changed Fixes #1 --- update-firewall-source.py | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/update-firewall-source.py b/update-firewall-source.py index 9f36171..46662f7 100644 --- a/update-firewall-source.py +++ b/update-firewall-source.py @@ -22,6 +22,8 @@ import inflect import dbus # Find physical network interface via 'find' command import subprocess +# Diff new and existing firewalld direct rules XML structure +import difflib # Exit codes @@ -553,6 +555,29 @@ def add_firewall_shim(arg_phy_nics: list) -> None: ) +def has_xml_changed( + config_obj: configparser.ConfigParser()) -> bool: + arg_fwd_file_abs = os.path.abspath(config_obj.get(configparser.DEFAULTSECT, "firewalld_direct_file_abs")) + + try: + with open(arg_fwd_file_abs, "r") as fwd_file_abs_handle: + fwd_file_abs_content = fwd_file_abs_handle.read() + fwd_direct_xml_str = get_xml_str_repr() + diff_result = difflib.Differ().compare(fwd_file_abs_content.splitlines(), fwd_direct_xml_str.splitlines()) + s = difflib.SequenceMatcher(isjunk=None, a=fwd_file_abs_content, b=fwd_direct_xml_str, autojunk=False) + except OSError as ose: + ose_handler(os_error=ose, exit_code=5) + sys.exit(5) + else: + if s.ratio() < 1: + nl = "\n" + log.info(f"Changing firewalld rules. Diff as follows:\n" + f"""{nl.join(diff_result)}""") + return True + else: + return False + + if __name__ == '__main__': validate_default_section(config) if config_has_valid_section(config): @@ -589,6 +614,7 @@ if __name__ == '__main__': arg_state="ESTABLISHED,RELATED") add_firewall_shim(get_phy_nics()) - write_new_fwd_direct_xml(config) - if config.getboolean(configparser.DEFAULTSECT, "restart_firewalld_after_change"): - restart_systemd_firewalld() + if has_xml_changed(config): + write_new_fwd_direct_xml(config) + if config.getboolean(configparser.DEFAULTSECT, "restart_firewalld_after_change"): + restart_systemd_firewalld() -- 2.47.2