Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Mar 7, 2024
1 parent de36b05 commit c70e1b2
Show file tree
Hide file tree
Showing 217 changed files with 5,072 additions and 1,644 deletions.
22 changes: 15 additions & 7 deletions clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@
"""A test files updater."""

import logging
import ruamel.yaml

from pathlib import Path
from typing import OrderedDict

import ruamel.yaml

from ansiblelint.yaml_utils import FormattedYAML
from ruamel.yaml import CommentedSeq
from ruamel.yaml.comments import CommentedMap
from ruamel.yaml.tokens import CommentToken
from ruamel.yaml.error import CommentMark
from ruamel.yaml.tokens import CommentToken


logging.basicConfig(level=logging.INFO)
LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -192,14 +194,16 @@ def update_include_test_case(list_of_tasks) -> bool:
for idx, item in enumerate(list_of_tasks)
if item.get("include", "").startswith("{{ test_case_to_run }}")
or item.get("ansible.builtin.include_tasks", "").startswith(
"{{ test_case_to_run }}"
"{{ test_case_to_run }}",
)
]
if not match:
return False
for entry in match:
change_key(
list_of_tasks[entry], "include", "ansible.builtin.include_tasks"
list_of_tasks[entry],
"include",
"ansible.builtin.include_tasks",
)
values = (
list_of_tasks[entry]
Expand All @@ -209,13 +213,15 @@ def update_include_test_case(list_of_tasks) -> bool:
)
first, var_pairs = values.split(" ", 1)
list_of_tasks[entry]["ansible.builtin.include_tasks"] = first.replace(
"{{", "{{ "
"{{",
"{{ ",
).replace("}}", " }}")
list_of_tasks[entry]["vars"] = {}
for var_pair in var_pairs.split(" "):
key, value = var_pair.split("=")
list_of_tasks[entry]["vars"][key] = value.replace(
"{{", "{{ "
"{{",
"{{ ",
).replace("}}", " }}")

return True
Expand Down Expand Up @@ -294,7 +300,9 @@ def undo_set_fact_equal(list_of_tasks) -> bool:
commented = True

change_key(
list_of_tasks[entry], "set_fact", "ansible.builtin.set_fact"
list_of_tasks[entry],
"set_fact",
"ansible.builtin.set_fact",
)

if commented:
Expand Down
21 changes: 16 additions & 5 deletions plugins/action/nxos.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ def run(self, tmp=None, task_vars=None):
del tmp # tmp no longer has any effect

module_name = self._task.action.split(".")[-1]
self._config_module = True if module_name in ["nxos_config", "config"] else False
self._config_module = (
True if module_name in ["nxos_config", "config"] else False
)
persistent_connection = self._play_context.connection.split(".")[-1]

warnings = []
Expand Down Expand Up @@ -65,15 +67,19 @@ def run(self, tmp=None, task_vars=None):
}

conn = Connection(self._connection.socket_path)
persistent_command_timeout = conn.get_option("persistent_command_timeout")
persistent_command_timeout = conn.get_option(
"persistent_command_timeout"
)
file_pull = self._task.args.get("file_pull", False)
file_pull_timeout = self._task.args.get("file_pull_timeout")
connect_ssh_port = self._task.args.get("connect_ssh_port", 22)

if file_pull:
# if file_pull_timeout is explicitly set, use that
if file_pull_timeout:
conn.set_option("persistent_command_timeout", file_pull_timeout)
conn.set_option(
"persistent_command_timeout", file_pull_timeout
)
# if file_pull_timeout is not set and command_timeout < 300s, bump to 300s.
elif persistent_command_timeout < 300:
conn.set_option("persistent_command_timeout", 300)
Expand All @@ -96,8 +102,13 @@ def run(self, tmp=None, task_vars=None):
f"PERSISTENT_CONNECT_TIMEOUT is %s {persistent_connect_timeout}",
self._play_context.remote_addr,
)
if persistent_command_timeout < 600 or persistent_connect_timeout < 600:
msg = "PERSISTENT_COMMAND_TIMEOUT and PERSISTENT_CONNECT_TIMEOUT"
if (
persistent_command_timeout < 600
or persistent_connect_timeout < 600
):
msg = (
"PERSISTENT_COMMAND_TIMEOUT and PERSISTENT_CONNECT_TIMEOUT"
)
msg += " must be set to 600 seconds or higher when using nxos_install_os module."
msg += " Current persistent_command_timeout setting:" + str(
persistent_command_timeout,
Expand Down
114 changes: 85 additions & 29 deletions plugins/cliconf/nxos.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,12 @@
NetworkConfig,
dumps,
)
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import to_list
from ansible_collections.ansible.netcommon.plugins.plugin_utils.cliconf_base import CliconfBase
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
to_list,
)
from ansible_collections.ansible.netcommon.plugins.plugin_utils.cliconf_base import (
CliconfBase,
)


class Cliconf(CliconfBase):
Expand Down Expand Up @@ -84,28 +88,42 @@ def get_device_info(self):
reply = self.get("show version")
platform_reply = self.get("show inventory")

match_sys_ver = re.search(r"\s+system:\s+version\s*(\S+)", reply, re.M)
match_sys_ver = re.search(
r"\s+system:\s+version\s*(\S+)", reply, re.M
)
if match_sys_ver:
device_info["network_os_version"] = match_sys_ver.group(1)
else:
match_kick_ver = re.search(r"\s+kickstart:\s+version\s*(\S+)", reply, re.M)
match_kick_ver = re.search(
r"\s+kickstart:\s+version\s*(\S+)", reply, re.M
)
if match_kick_ver:
device_info["network_os_version"] = match_kick_ver.group(1)

if "network_os_version" not in device_info:
match_sys_ver = re.search(r"\s+NXOS:\s+version\s*(\S+)", reply, re.M)
match_sys_ver = re.search(
r"\s+NXOS:\s+version\s*(\S+)", reply, re.M
)
if match_sys_ver:
device_info["network_os_version"] = match_sys_ver.group(1)

match_chassis_id = re.search(r"Hardware\n\s+cisco(.+)$", reply, re.M)
match_chassis_id = re.search(
r"Hardware\n\s+cisco(.+)$", reply, re.M
)
if match_chassis_id:
device_info["network_os_model"] = match_chassis_id.group(1).strip()
device_info["network_os_model"] = match_chassis_id.group(
1
).strip()

match_host_name = re.search(r"\s+Device name:\s*(\S+)", reply, re.M)
match_host_name = re.search(
r"\s+Device name:\s*(\S+)", reply, re.M
)
if match_host_name:
device_info["network_os_hostname"] = match_host_name.group(1)

match_isan_file_name = re.search(r"\s+system image file is:\s*(\S+)", reply, re.M)
match_isan_file_name = re.search(
r"\s+system image file is:\s*(\S+)", reply, re.M
)
if match_isan_file_name:
device_info["network_os_image"] = match_isan_file_name.group(1)
else:
Expand All @@ -115,12 +133,18 @@ def get_device_info(self):
re.M,
)
if match_kick_file_name:
device_info["network_os_image"] = match_kick_file_name.group(1)
device_info[
"network_os_image"
] = match_kick_file_name.group(1)

if "network_os_image" not in device_info:
match_isan_file_name = re.search(r"\s+NXOS image file is:\s*(\S+)", reply, re.M)
match_isan_file_name = re.search(
r"\s+NXOS image file is:\s*(\S+)", reply, re.M
)
if match_isan_file_name:
device_info["network_os_image"] = match_isan_file_name.group(1)
device_info[
"network_os_image"
] = match_isan_file_name.group(1)

match_os_platform = re.search(
r'NAME: "Chassis",\s*DESCR:.*\nPID:\s*(\S+)',
Expand Down Expand Up @@ -148,7 +172,9 @@ def get_diff(
option_values = self.get_option_values()

if candidate is None and device_operations["supports_generate_diff"]:
raise ValueError("candidate configuration is required to generate diff")
raise ValueError(
"candidate configuration is required to generate diff"
)

if diff_match not in option_values["diff_match"]:
raise ValueError(
Expand All @@ -168,7 +194,9 @@ def get_diff(

if running and diff_match != "none" and diff_replace != "config":
# running configuration
running_obj = NetworkConfig(indent=2, contents=running, ignore_lines=diff_ignore_lines)
running_obj = NetworkConfig(
indent=2, contents=running, ignore_lines=diff_ignore_lines
)
configdiffobjs = candidate_obj.difference(
running_obj,
path=path,
Expand All @@ -179,7 +207,9 @@ def get_diff(
else:
configdiffobjs = candidate_obj.items

diff["config_diff"] = dumps(configdiffobjs, "commands") if configdiffobjs else ""
diff["config_diff"] = (
dumps(configdiffobjs, "commands") if configdiffobjs else ""
)
return diff

def get_config(self, source="running", flags=None, format="text"):
Expand All @@ -192,7 +222,9 @@ def get_config(self, source="running", flags=None, format="text"):

lookup = {"running": "running-config", "startup": "startup-config"}
if source not in lookup:
raise ValueError("fetching configuration from %s is not supported" % source)
raise ValueError(
"fetching configuration from %s is not supported" % source
)

cmd = "show {0} ".format(lookup[source])
if format and format != "text":
Expand All @@ -204,10 +236,14 @@ def get_config(self, source="running", flags=None, format="text"):

return self.send_command(cmd)

def edit_config(self, candidate=None, commit=True, replace=None, comment=None):
def edit_config(
self, candidate=None, commit=True, replace=None, comment=None
):
resp = {}
operations = self.get_device_operations()
self.check_edit_config_capability(operations, candidate, commit, replace, comment)
self.check_edit_config_capability(
operations, candidate, commit, replace, comment
)
results = []
requests = []

Expand Down Expand Up @@ -269,7 +305,9 @@ def run_commands(self, commands=None, check_rc=True):

output = cmd.pop("output", None)
if output:
cmd["command"] = self._get_command_with_output(cmd["command"], output)
cmd["command"] = self._get_command_with_output(
cmd["command"], output
)

try:
out = self.send_command(**cmd)
Expand All @@ -283,7 +321,8 @@ def run_commands(self, commands=None, check_rc=True):
out = to_text(out, errors="surrogate_or_strict").strip()
except UnicodeError:
raise ConnectionError(
message="Failed to decode output from %s: %s" % (cmd, to_text(out)),
message="Failed to decode output from %s: %s"
% (cmd, to_text(out)),
)

try:
Expand Down Expand Up @@ -336,11 +375,15 @@ def pull_file(self, command, remotepassword=None):
re.compile(rb"(?i)Could not resolve hostname"),
re.compile(rb"(?i)Too many authentication failures"),
re.compile(rb"Access Denied"),
re.compile(rb"(?i)Copying to\/from this server name is not permitted"),
re.compile(
rb"(?i)Copying to\/from this server name is not permitted"
),
]

# set error regex for copy command
current_stderr_re = self._connection._get_terminal_std_re("terminal_stderr_re")
current_stderr_re = self._connection._get_terminal_std_re(
"terminal_stderr_re"
)
current_stderr_re.extend(possible_errors_re)

# do not change the ordering of this list
Expand All @@ -352,7 +395,9 @@ def pull_file(self, command, remotepassword=None):

# set stdout regex for copy command to handle optional user prompts
# based on different match conditions
current_stdout_re = self._connection._get_terminal_std_re("terminal_stdout_re")
current_stdout_re = self._connection._get_terminal_std_re(
"terminal_stdout_re"
)
current_stdout_re.extend(possible_prompts_re)

retry = 1
Expand All @@ -367,10 +412,14 @@ def pull_file(self, command, remotepassword=None):
output = self.send_command(command="y", strip_prompt=False)

if possible_prompts_re[1].search(to_bytes(output)):
output = self.send_command(command="yes", strip_prompt=False)
output = self.send_command(
command="yes", strip_prompt=False
)

if possible_prompts_re[2].search(to_bytes(output)):
output = self.send_command(command=remotepassword, strip_prompt=False)
output = self.send_command(
command=remotepassword, strip_prompt=False
)
if "Copy complete" in output:
file_pulled = True
return file_pulled
Expand All @@ -391,13 +440,18 @@ def set_cli_prompt_context(self):
if out is None:
raise AnsibleConnectionFailure(
message="cli prompt is not identified from the last received"
" response window: %s" % self._connection._last_recv_window,
" response window: %s"
% self._connection._last_recv_window,
)
# Match prompts ending in )# except those with (maint-mode)#
config_prompt = re.compile(r"^.*\((?!maint-mode).*\)#$")

while config_prompt.match(to_text(out, errors="surrogate_then_replace").strip()):
self._connection.queue_message("vvvv", "wrong context, sending exit to device")
while config_prompt.match(
to_text(out, errors="surrogate_then_replace").strip()
):
self._connection.queue_message(
"vvvv", "wrong context, sending exit to device"
)
self._connection.send_command("exit")
out = self._connection.get_prompt()

Expand All @@ -410,7 +464,9 @@ def _get_command_with_output(self, command, output):
% (output, ",".join(options_values["output"])),
)

if output in ["json", "json-pretty"] and not re.search(output_re, command):
if output in ["json", "json-pretty"] and not re.search(
output_re, command
):
device_info = self.get_device_info()
model = device_info.get("network_os_model", "")
platform = device_info.get("network_os_platform", "")
Expand Down
Loading

0 comments on commit c70e1b2

Please sign in to comment.