Skip to content

Commit

Permalink
Add wrapper for all functions. Easier to debug runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
juztas committed Apr 25, 2024
1 parent 1cfe44e commit 33f5080
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 32 deletions.
19 changes: 10 additions & 9 deletions plugins/module_utils/network/dellos10.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@

__metaclass__ = type

import re
from ipaddress import ip_address
from ansible.utils.display import Display
from ansible.module_utils._text import to_text
from ansible.module_utils.basic import env_fallback
from ansible.module_utils.connection import exec_command
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list, ComplexList
from ansible_collections.sense.dellos9.plugins.module_utils.runwrapper import functionwrapper

display = Display()

Expand All @@ -38,12 +38,11 @@
'provider': {'type': 'dict', 'options': dellos10_provider_spec}
}


@functionwrapper
def check_args(module, warnings):
"""Check args pass"""
pass


@functionwrapper
def get_config(module, flags=None):
"""Get running config"""
flags = [] if flags is None else flags
Expand All @@ -61,7 +60,7 @@ def get_config(module, flags=None):
_DEVICE_CONFIGS[cmd] = cfg
return cfg


@functionwrapper
def to_commands(module, commands):
"""Transform commands"""
spec = {
Expand All @@ -72,7 +71,7 @@ def to_commands(module, commands):
transform = ComplexList(spec, module)
return transform(commands)


@functionwrapper
def run_commands(module, commands, check_rc=True):
"""Run Commands"""
responses = []
Expand All @@ -85,7 +84,7 @@ def run_commands(module, commands, check_rc=True):
responses.append(to_text(out, errors='surrogate_or_strict'))
return responses


@functionwrapper
def load_config(module, commands):
"""Load config"""
ret, _out, err = exec_command(module, 'configure terminal')
Expand All @@ -101,7 +100,7 @@ def load_config(module, commands):

exec_command(module, 'end')


@functionwrapper
def normalizedip(ipInput):
"""
Normalize IPv6 address. It can have leading 0 or not and both are valid.
Expand All @@ -120,8 +119,10 @@ def normalizedip(ipInput):
# We return what we get here, because it had multiple / (which is not really valid)
return ipInput

@functionwrapper
def normalizeIntfName(intfName):
"""Normalize interface name"""
intfName = intfName.replace('port-channel', 'Port-channel ')
intfName = intfName.replace('ethernet', 'Ethernet ')
intfName = intfName.replace('mgmt', 'Management ')
return intfName
return intfName
19 changes: 9 additions & 10 deletions plugins/modules/dellos10_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from ansible_collections.sense.dellos10.plugins.module_utils.network.dellos10 import dellos10_argument_spec, check_args
from ansible_collections.sense.dellos10.plugins.module_utils.network.dellos10 import load_config, run_commands
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import NetworkConfig, dumps
from ansible_collections.sense.dellos9.plugins.module_utils.runwrapper import functionwrapper
__metaclass__ = type


Expand All @@ -25,13 +26,13 @@

display = Display()


@functionwrapper
def get_candidate(module):
candidate = NetworkConfig(indent=1)
if module.params['src']:
candidate.load(module.params['src'])
elif module.params['lines']:
parents = module.params['parents'] or list()
parents = module.params['parents'] or []
commands = module.params['lines'][0]
if (isinstance(commands, dict)) and (isinstance(commands['command'], list)):
candidate.add(commands['command'], parents=parents)
Expand All @@ -41,17 +42,17 @@ def get_candidate(module):
candidate.add(module.params['lines'], parents=parents)
return candidate


@functionwrapper
def get_running_config(module):
contents = module.params['config']
if not contents:
contents = get_config(module)
return contents


@functionwrapper
def main():
backup_spec = dict(
filename=dict(),
filename={},
dir_path=dict(type='path')
)
argument_spec = dict(
Expand All @@ -69,7 +70,7 @@ def main():

update=dict(choices=['merge', 'check'], default='merge'),
save=dict(type='bool', default=False),
config=dict(),
config={},
backup=dict(type='bool', default=False),
backup_options=dict(type='dict', options=backup_spec)
)
Expand All @@ -82,12 +83,10 @@ def main():
mutually_exclusive=mutually_exclusive,
supports_check_mode=True)

parents = module.params['parents'] or list()

match = module.params['match']
replace = module.params['replace']

warnings = list()
warnings = []
check_args(module, warnings)

result = dict(changed=False, saved=False, warnings=warnings)
Expand All @@ -97,7 +96,7 @@ def main():
if module.params['backup']:
if not module.check_mode:
result['__backup__'] = get_config(module)
commands = list()
commands = []

if any((module.params['lines'], module.params['src'])):
if match != 'none':
Expand Down
27 changes: 14 additions & 13 deletions plugins/modules/dellos10_facts.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@
from ansible_collections.sense.dellos10.plugins.module_utils.network.dellos10 import (
check_args, dellos10_argument_spec, normalizedip, normalizeIntfName,
run_commands)
from ansible_collections.sense.dellos9.plugins.module_utils.runwrapper import (
classwrapper, functionwrapper)

display = Display()


@classwrapper
class FactsBase:
"""Base class for Facts"""

Expand All @@ -37,7 +39,7 @@ def run(self, cmd):
"""Run commands"""
return run_commands(self.module, cmd, check_rc=False)


@classwrapper
class Routing(FactsBase):
"""Routing Information"""

Expand Down Expand Up @@ -169,7 +171,7 @@ def getIPv6Routing(self, data):
}
)


@classwrapper
class LLDPInfo(FactsBase):
"""LLDP Information and link mapping"""

Expand Down Expand Up @@ -226,7 +228,7 @@ def getlldpneighbors(self, data):
if "local_port_id" in entryOut:
self.facts["lldp"][entryOut["local_port_id"]] = entryOut


@classwrapper
class Default(FactsBase):
"""All Interfaces Class"""

Expand Down Expand Up @@ -307,10 +309,7 @@ def parseRunningConfig(self, data):
intfKey = normalizeIntfName(line[10:])
elif interfaceSt and intfKey in self.facts["interfaces"]:
for key, call in calls.items():
if key in ["tagged", "untagged"]:
call(line, intfKey)
continue
tmpOut = call(line)
tmpOut = call(line, intfKey)
if tmpOut and isinstance(tmpOut, list):
self.facts["interfaces"][intfKey].setdefault(key, [])
self.facts["interfaces"][intfKey][key] += tmpOut
Expand Down Expand Up @@ -361,6 +360,7 @@ def parse_tagged(self, line, intfKey):
self.facts["interfaces"][f"Vlan {val}"]["tagged"].append(
intfKey
)
return []

def parse_untagged(self, line, intfKey):
"""Parse Untagged Vlans"""
Expand All @@ -369,9 +369,10 @@ def parse_untagged(self, line, intfKey):
self.facts["interfaces"].setdefault(f"Vlan {untaggedVlan}", {})
self.facts["interfaces"][f"Vlan {untaggedVlan}"].setdefault("untagged", [])
self.facts["interfaces"][f"Vlan {untaggedVlan}"]["untagged"].append(intfKey)
return []

@staticmethod
def parse_portmode(data):
def parse_portmode(data, _intfKey):
"""Parse Portmode"""
tmpOut = ""
if data.startswith("switchport access vlan "):
Expand All @@ -381,7 +382,7 @@ def parse_portmode(data):
return tmpOut

@staticmethod
def parse_switchport(data):
def parse_switchport(data, _intfKey):
"""Parse Switchport"""
tmpOut = ""
if data == "switchport mode trunk":
Expand All @@ -391,7 +392,7 @@ def parse_switchport(data):
return tmpOut

@staticmethod
def parse_spanning_tree(data):
def parse_spanning_tree(data, _intfKey):
"""Parse spanning tree"""
tmpOut = []
if data.startswith("no spanning-tree"):
Expand All @@ -401,7 +402,7 @@ def parse_spanning_tree(data):
return tmpOut

@staticmethod
def parse_ip_vrf(data):
def parse_ip_vrf(data, _intfKey):
"""Parse ip vrf"""
tmpOut = ""
if data.startswith("ip vrf"):
Expand Down Expand Up @@ -559,7 +560,7 @@ def parse_members(data):

VALID_SUBSETS = frozenset(FACT_SUBSETS.keys())


@functionwrapper
def main():
"""main entry point for module execution"""
argument_spec = {"gather_subset": {"default": [], "type": "list"}}
Expand Down

0 comments on commit 33f5080

Please sign in to comment.