Skip to content

Commit

Permalink
added context-manager to session-class
Browse files Browse the repository at this point in the history
  • Loading branch information
ansibleguy committed Jan 1, 2024
1 parent 16e4685 commit ecaca16
Show file tree
Hide file tree
Showing 6 changed files with 118 additions and 104 deletions.
10 changes: 10 additions & 0 deletions docs/source/usage/4_develop.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 12 additions & 6 deletions plugins/module_utils/base/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 6 additions & 0 deletions plugins/module_utils/base/api_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
92 changes: 44 additions & 48 deletions plugins/modules/_tmpl_direct.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
48 changes: 23 additions & 25 deletions plugins/modules/frr_bfd_general.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
48 changes: 23 additions & 25 deletions plugins/modules/wireguard_general.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down

0 comments on commit ecaca16

Please sign in to comment.