From ecaca16eefc1fd78d9a3e72d9de0b7242cd78199 Mon Sep 17 00:00:00 2001 From: AnsibleGuy Date: Mon, 1 Jan 2024 18:36:44 +0100 Subject: [PATCH] added context-manager to session-class --- docs/source/usage/4_develop.rst | 10 +++ plugins/module_utils/base/api.py | 18 ++++-- plugins/module_utils/base/api_test.py | 6 ++ plugins/modules/_tmpl_direct.py | 92 +++++++++++++-------------- plugins/modules/frr_bfd_general.py | 48 +++++++------- plugins/modules/wireguard_general.py | 48 +++++++------- 6 files changed, 118 insertions(+), 104 deletions(-) diff --git a/docs/source/usage/4_develop.rst b/docs/source/usage/4_develop.rst index 876db591..e87ad68f 100644 --- a/docs/source/usage/4_develop.rst +++ b/docs/source/usage/4_develop.rst @@ -146,6 +146,16 @@ One can choose to either: session.post(cnf={'controller': 'alias', 'command': 'delItem', 'params': [uuid]}) session.close() + or using a context-manager: + + .. code-block:: python3 + + from ansible_collections.ansibleguy.opnsense.plugins.module_utils.base.api import Session + with Session(module=module) as session: + session.get(cnf={'controller': 'alias', 'command': 'addItem', 'data': {'name': 'dummy', ...}}) + session.post(cnf={'controller': 'alias', 'command': 'delItem', 'params': [uuid]}) + + - use a single call - if only one is needed p.e. toggle a cronjob or restart a service diff --git a/plugins/module_utils/base/api.py b/plugins/module_utils/base/api.py index 8d07c34e..594007f9 100644 --- a/plugins/module_utils/base/api.py +++ b/plugins/module_utils/base/api.py @@ -105,16 +105,22 @@ def post(self, cnf: dict, headers: dict = None) -> dict: def close(self) -> None: self.s.close() + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + def single_get(module: AnsibleModule, cnf: dict, timeout: float = DEFAULT_TIMEOUT) -> dict: - s = Session(module=module, timeout=timeout) - response = s.get(cnf=cnf) - s.close() + with Session(module=module, timeout=timeout) as s: + response = s.get(cnf=cnf) + return response def single_post(module: AnsibleModule, cnf: dict, timeout: float = DEFAULT_TIMEOUT, headers: dict = None) -> dict: - s = Session(module=module, timeout=timeout) - response = s.post(cnf=cnf, headers=headers) - s.close() + with Session(module=module, timeout=timeout) as s: + response = s.post(cnf=cnf, headers=headers) + return response diff --git a/plugins/module_utils/base/api_test.py b/plugins/module_utils/base/api_test.py index 05938762..4cf02537 100644 --- a/plugins/module_utils/base/api_test.py +++ b/plugins/module_utils/base/api_test.py @@ -39,6 +39,12 @@ def test_session_creation(): s.close() +def test_session_contextmanager(): + from ansible_collections.ansibleguy.opnsense.plugins.module_utils.base.api import Session + with Session(module=DUMMY_MODULE): + pass + + # todo: to test this we need to create a http-server that's able to abort connections before they are established # @pytest.mark.parametrize('retries', [ # 0, diff --git a/plugins/modules/_tmpl_direct.py b/plugins/modules/_tmpl_direct.py index feb9c8e5..1c53504f 100644 --- a/plugins/modules/_tmpl_direct.py +++ b/plugins/modules/_tmpl_direct.py @@ -47,66 +47,62 @@ def run_module(): supports_check_mode=True, ) - session = Session(module=module) + with Session(module=module) as _: # rename to 'session' + # do api interactions here + exists = True # check via api if the item already exists + # session.get(cnf={ + # 'module': 'API-Module', + # 'controller': 'API-Controller', + # 'command': 'API-info-command', + # 'data': {'tests'} + # }) - # do api interactions here - exists = True # check via api if the item already exists - # session.get(cnf={ - # 'module': 'API-Module', - # 'controller': 'API-Controller', - # 'command': 'API-info-command', - # 'data': {'tests'} - # }) + if exists: + result['diff']['before'] = 'test' # set to current value for diff-mode - if exists: - result['diff']['before'] = 'test' # set to current value for diff-mode + if module.params['state'] == 'absent': + if exists: + result['changed'] = True + if not module.check_mode: + # remove item via api if not in check-mode + # session.post(cnf={ + # 'module': 'API-Module', + # 'controller': 'API-Controller', + # 'command': 'API-delete-command', + # 'params': ['uuid'], + # }) + pass - if module.params['state'] == 'absent': - if exists: - result['changed'] = True - if not module.check_mode: - # remove item via api if not in check-mode - # session.post(cnf={ - # 'module': 'API-Module', - # 'controller': 'API-Controller', - # 'command': 'API-delete-command', - # 'params': ['uuid'], - # }) - pass - - else: - if exists: - value_changed = True # compare existing item config with configured one - if value_changed: + else: + if exists: + value_changed = True # compare existing item config with configured one + if value_changed: + result['diff']['after'] = 'tests' # set to configured value(s) + if not module.check_mode: + # update item via api if not in check-mode + # session.post(cnf={ + # 'module': 'API-Module', + # 'controller': 'API-Controller', + # 'command': 'API-update-command', + # 'data': {'tests'}, + # 'params': ['uuid'], + # }) + pass + + else: result['diff']['after'] = 'tests' # set to configured value(s) if not module.check_mode: - # update item via api if not in check-mode + # create item via api if not in check-mode # session.post(cnf={ # 'module': 'API-Module', # 'controller': 'API-Controller', - # 'command': 'API-update-command', + # 'command': 'API-add-command', # 'data': {'tests'}, - # 'params': ['uuid'], # }) pass - else: - result['diff']['after'] = 'tests' # set to configured value(s) - if not module.check_mode: - # create item via api if not in check-mode - # session.post(cnf={ - # 'module': 'API-Module', - # 'controller': 'API-Controller', - # 'command': 'API-add-command', - # 'data': {'tests'}, - # }) - pass - - # don't forget to call the 'reload' endpoint to activate the changes (if available/needed) - - # cleanup and exit - - session.close() + # don't forget to call the 'reload' endpoint to activate the changes (if available/needed) + result['diff'] = diff_remove_empty(result['diff']) module.exit_json(**result) diff --git a/plugins/modules/frr_bfd_general.py b/plugins/modules/frr_bfd_general.py index ba7e324b..16211157 100644 --- a/plugins/modules/frr_bfd_general.py +++ b/plugins/modules/frr_bfd_general.py @@ -44,34 +44,32 @@ def run_module(): } ) - s = Session(module=module) - - is_enabled = is_true( - s.get(cnf={ - 'module': 'quagga', - 'controller': 'bfd', - 'command': 'get', - })['bfd']['enabled'] - ) - result['diff']['before']['enabled'] = is_enabled - - if is_enabled != module.params['enabled']: - result['changed'] = True - - if not module.check_mode: - s.post(cnf={ + with Session(module=module) as s: + is_enabled = is_true( + s.get(cnf={ 'module': 'quagga', 'controller': 'bfd', - 'command': 'set', - 'data': {'bfd': {'enabled': to_digit(module.params['enabled'])}} - }) - s.post(cnf={ - 'module': 'quagga', - 'controller': 'service', - 'command': 'reconfigure', - }) + 'command': 'get', + })['bfd']['enabled'] + ) + result['diff']['before']['enabled'] = is_enabled + + if is_enabled != module.params['enabled']: + result['changed'] = True + + if not module.check_mode: + s.post(cnf={ + 'module': 'quagga', + 'controller': 'bfd', + 'command': 'set', + 'data': {'bfd': {'enabled': to_digit(module.params['enabled'])}} + }) + s.post(cnf={ + 'module': 'quagga', + 'controller': 'service', + 'command': 'reconfigure', + }) - s.close() module.exit_json(**result) diff --git a/plugins/modules/wireguard_general.py b/plugins/modules/wireguard_general.py index 4f57c020..5846de0a 100644 --- a/plugins/modules/wireguard_general.py +++ b/plugins/modules/wireguard_general.py @@ -44,34 +44,32 @@ def run_module(): } ) - s = Session(module=module) - - is_enabled = is_true( - s.get(cnf={ - 'module': 'wireguard', - 'controller': 'general', - 'command': 'get', - })['general']['enabled'] - ) - result['diff']['before']['enabled'] = is_enabled - - if is_enabled != module.params['enabled']: - result['changed'] = True - - if not module.check_mode: - s.post(cnf={ + with Session(module=module) as s: + is_enabled = is_true( + s.get(cnf={ 'module': 'wireguard', 'controller': 'general', - 'command': 'set', - 'data': {'general': {'enabled': to_digit(module.params['enabled'])}} - }) - s.post(cnf={ - 'module': 'wireguard', - 'controller': 'service', - 'command': 'reconfigure', - }) + 'command': 'get', + })['general']['enabled'] + ) + result['diff']['before']['enabled'] = is_enabled + + if is_enabled != module.params['enabled']: + result['changed'] = True + + if not module.check_mode: + s.post(cnf={ + 'module': 'wireguard', + 'controller': 'general', + 'command': 'set', + 'data': {'general': {'enabled': to_digit(module.params['enabled'])}} + }) + s.post(cnf={ + 'module': 'wireguard', + 'controller': 'service', + 'command': 'reconfigure', + }) - s.close() module.exit_json(**result)