Address broad-exception-caught.

This commit is contained in:
Felix Fontein 2025-10-11 14:27:10 +02:00
parent 451e235c2a
commit 1d30856e67
25 changed files with 69 additions and 72 deletions

View File

@ -381,7 +381,6 @@ disable=raw-checker-failed,
# To clean up:
abstract-method,
arguments-differ,
broad-exception-caught,
consider-iterating-dictionary,
consider-using-dict-comprehension,
consider-using-f-string,

View File

@ -368,7 +368,7 @@ def _load_legacy_config(config_file):
}
}
}
except Exception as e:
except Exception as e: # pylint: disable=broad-exception-caught
log.debug(e)
pass

View File

@ -36,7 +36,7 @@ def get_current_context_name_with_source():
json.load(f).get("currentContext", "default"),
f"configuration file {docker_cfg_path}",
)
except Exception:
except Exception: # pylint: disable=broad-exception-caught
pass
return "default", "fallback value"
@ -54,7 +54,7 @@ def write_context_name_to_docker_config(name=None):
try:
with open(docker_cfg_path, "rt", encoding="utf-8") as f:
config = json.load(f)
except Exception as e:
except Exception as e: # pylint: disable=broad-exception-caught
return e
current_context = config.get("currentContext", None)
if current_context and not name:
@ -68,7 +68,7 @@ def write_context_name_to_docker_config(name=None):
try:
with open(docker_cfg_path, "wt", encoding="utf-8") as f:
json.dump(config, f, indent=4)
except Exception as e:
except Exception as e: # pylint: disable=broad-exception-caught
return e

View File

@ -237,7 +237,7 @@ class AnsibleDockerClientBase(Client):
self.docker_api_version_str = self.api_version
except APIError as exc:
self.fail(f"Docker API error: {exc}")
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error connecting: {exc}")
self.docker_api_version = LooseVersion(self.docker_api_version_str)
@ -409,7 +409,7 @@ class AnsibleDockerClientBase(Client):
return result
except NotFound:
return None
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting container: {exc}")
def get_container(self, name=None):
@ -441,7 +441,7 @@ class AnsibleDockerClientBase(Client):
break
except SSLError as exc:
self._handle_ssl_error(exc)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error retrieving container list: {exc}")
if result is None:
@ -470,7 +470,7 @@ class AnsibleDockerClientBase(Client):
break
except SSLError as exc:
self._handle_ssl_error(exc)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error retrieving network list: {exc}")
if result is not None:
@ -483,7 +483,7 @@ class AnsibleDockerClientBase(Client):
self.log("Completed network inspection")
except NotFound:
return None
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting network: {exc}")
return result
@ -533,7 +533,7 @@ class AnsibleDockerClientBase(Client):
except NotFound:
self.log(f"Image {name}:{tag} not found.")
return None
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting image {name}:{tag} - {exc}")
return inspection
@ -555,7 +555,7 @@ class AnsibleDockerClientBase(Client):
self.fail(f"Error inspecting image ID {image_id} - {exc}")
self.log(f"Image {image_id} not found.")
return None
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting image ID {image_id} - {exc}")
return inspection
@ -567,7 +567,7 @@ class AnsibleDockerClientBase(Client):
"""
try:
response = self.images(name=name)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error searching for image {name} - {exc}")
images = response
if tag:
@ -606,7 +606,7 @@ class AnsibleDockerClientBase(Client):
)
else:
self.fail(f"Error pulling {name} - {line.get('error')}")
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error pulling image {name}:{tag} - {exc}")
new_tag = self.find_image(name, tag)

View File

@ -128,7 +128,7 @@ class AnsibleDockerClientBase(Client):
)
except APIError as exc:
self.fail(f"Docker API error: {exc}")
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error connecting: {exc}")
self.docker_api_version = LooseVersion(self.docker_api_version_str)
@ -308,7 +308,7 @@ class AnsibleDockerClientBase(Client):
return result
except NotFound:
return None
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting container: {exc}")
def get_container(self, name=None):
@ -347,7 +347,7 @@ class AnsibleDockerClientBase(Client):
break
except SSLError as exc:
self._handle_ssl_error(exc)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error retrieving container list: {exc}")
if result is None:
@ -377,7 +377,7 @@ class AnsibleDockerClientBase(Client):
break
except SSLError as exc:
self._handle_ssl_error(exc)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error retrieving network list: {exc}")
if result is not None:
@ -390,7 +390,7 @@ class AnsibleDockerClientBase(Client):
self.log("Completed network inspection")
except NotFound:
return None
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting network: {exc}")
return result
@ -412,7 +412,7 @@ class AnsibleDockerClientBase(Client):
else:
params["filters"] = convert_filters({"reference": name})
images = self.get_json("/images/json", params=params)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error searching for image {name} - {exc}")
if tag:
lookup = f"{name}:{tag}"
@ -472,7 +472,7 @@ class AnsibleDockerClientBase(Client):
except NotFound:
self.log(f"Image {name}:{tag} not found.")
return None
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting image {name}:{tag} - {exc}")
self.log(f"Image {name}:{tag} not found.")
@ -493,7 +493,7 @@ class AnsibleDockerClientBase(Client):
self.fail(f"Error inspecting image ID {image_id} - {exc}")
self.log(f"Image {image_id} not found.")
return None
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting image ID {image_id} - {exc}")
def pull_image(self, name, tag="latest", image_platform=None):
@ -535,7 +535,7 @@ class AnsibleDockerClientBase(Client):
)
else:
self.fail(f"Error pulling {name} - {line.get('error')}")
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error pulling image {name}:{tag} - {exc}")
new_tag = self.find_image(name, tag)

View File

@ -159,7 +159,7 @@ class AnsibleDockerClientBase:
self.warn(to_native(stderr))
try:
data = json.loads(stdout)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(
f"Error while parsing JSON output of {self._compose_cmd_str(args)}: {exc}\nJSON output: {to_native(stdout)}"
)
@ -177,7 +177,7 @@ class AnsibleDockerClientBase:
line = line.strip()
if line.startswith(b"{"):
result.append(json.loads(line))
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(
f"Error while parsing JSON output of {self._compose_cmd_str(args)}: {exc}\nJSON output: {to_native(stdout)}"
)

View File

@ -405,7 +405,7 @@ def parse_json_events(stderr, warn_function=None):
continue
try:
line_data = json.loads(line)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
if warn_function:
warn_function(
f"Cannot parse event from line: {line!r}: {exc}. Please report this at "
@ -748,7 +748,7 @@ class BaseComposeManager(DockerBaseClass):
encoding="utf-8",
Dumper=_SafeDumper,
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error writing to {compose_file} - {exc}")
else:
self.project_src = os.path.abspath(parameters["project_src"])
@ -804,7 +804,7 @@ class BaseComposeManager(DockerBaseClass):
if version == "dev":
return None
return version.lstrip("v")
except Exception:
except Exception: # pylint: disable=broad-exception-caught
return None
def get_compose_version_from_api(self):
@ -946,6 +946,6 @@ class BaseComposeManager(DockerBaseClass):
for directory in self.cleanup_dirs:
try:
shutil.rmtree(directory, True)
except Exception:
except Exception: # pylint: disable=broad-exception-caught
# should not happen, but simply ignore to be on the safe side
pass

View File

@ -431,7 +431,7 @@ def _parse_port_range(range_or_port, module):
if "-" in range_or_port:
try:
start, end = [int(port) for port in range_or_port.split("-")]
except Exception:
except ValueError:
module.fail_json(msg=f'Invalid port range: "{range_or_port}"')
if end < start:
module.fail_json(msg=f'Invalid port range: "{range_or_port}"')
@ -439,7 +439,7 @@ def _parse_port_range(range_or_port, module):
else:
try:
return [int(range_or_port)]
except Exception:
except ValueError:
module.fail_json(msg=f'Invalid port: "{range_or_port}"')
@ -707,7 +707,7 @@ def _preprocess_mounts(module, values):
if mount_dict["tmpfs_mode"] is not None:
try:
mount_dict["tmpfs_mode"] = int(mount_dict["tmpfs_mode"], 8)
except Exception:
except ValueError:
module.fail_json(
msg=f'tmp_fs mode of mount "{target}" is not an octal string!'
)

View File

@ -1060,7 +1060,7 @@ def _get_network_id(module, client, network_name):
network_id = network["Id"]
break
return network_id
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
client.fail(f"Error getting network id for {network_name} - {exc}")

View File

@ -481,7 +481,7 @@ class ContainerManager(DockerBaseClass):
self.engine_driver.unpause_container(
self.client, container.id
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(
f"Error {'pausing' if self.param_paused else 'unpausing'} container {container.id}: {exc}"
)
@ -951,7 +951,7 @@ class ContainerManager(DockerBaseClass):
self.engine_driver.disconnect_container_from_network(
self.client, container.id, diff["parameter"]["id"]
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(
f"Error disconnecting container from network {diff['parameter']['name']} - {exc}"
)
@ -976,7 +976,7 @@ class ContainerManager(DockerBaseClass):
self.engine_driver.connect_container_to_network(
self.client, container.id, diff["parameter"]["id"], params
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(
f"Error connecting container to network {diff['parameter']['name']} - {exc}"
)
@ -990,7 +990,7 @@ class ContainerManager(DockerBaseClass):
self.engine_driver.disconnect_container_from_network(
self.client, container.id, network["name"]
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(
f"Error disconnecting container from network {network['name']} - {exc}"
)
@ -1028,7 +1028,7 @@ class ContainerManager(DockerBaseClass):
container_id = self.engine_driver.create_container(
self.client, self.param_name, create_parameters, networks=networks
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error creating container: {exc}")
return self._get_container(container_id)
return new_container
@ -1040,7 +1040,7 @@ class ContainerManager(DockerBaseClass):
if not self.check_mode:
try:
self.engine_driver.start_container(self.client, container_id)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error starting container {container_id}: {exc}")
if self.module.params["detach"] is False:
@ -1097,7 +1097,7 @@ class ContainerManager(DockerBaseClass):
link=link,
force=force,
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.client.fail(f"Error removing container {container_id}: {exc}")
def container_update(self, container_id, update_parameters):
@ -1113,7 +1113,7 @@ class ContainerManager(DockerBaseClass):
self.engine_driver.update_container(
self.client, container_id, update_parameters
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error updating container {container_id}: {exc}")
return self._get_container(container_id)
@ -1127,7 +1127,7 @@ class ContainerManager(DockerBaseClass):
self.engine_driver.kill_container(
self.client, container_id, kill_signal=self.param_kill_signal
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error killing container {container_id}: {exc}")
def container_restart(self, container_id):
@ -1140,7 +1140,7 @@ class ContainerManager(DockerBaseClass):
self.engine_driver.restart_container(
self.client, container_id, self.module.params["stop_timeout"] or 10
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error restarting container {container_id}: {exc}")
return self._get_container(container_id)
@ -1157,7 +1157,7 @@ class ContainerManager(DockerBaseClass):
self.engine_driver.stop_container(
self.client, container_id, self.module.params["stop_timeout"]
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error stopping container {container_id}: {exc}")

View File

@ -78,7 +78,7 @@ class DockerSocketHandlerBase:
if hasattr(self._sock, "recv"):
try:
data = self._sock.recv(262144)
except Exception as e:
except Exception as e: # pylint: disable=broad-exception-caught
# After calling self._sock.shutdown(), OpenSSL's/urllib3's
# WrappedSocket seems to eventually raise ZeroReturnError in
# case of EOF

View File

@ -179,7 +179,7 @@ class AnsibleDockerSwarmClient(AnsibleDockerClient):
if skip_missing:
return None
self.fail(f"Error while reading from Swarm manager: {exc}")
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting swarm node: {exc}")
json_str = json.dumps(node_info, ensure_ascii=False)
@ -215,7 +215,7 @@ class AnsibleDockerSwarmClient(AnsibleDockerClient):
"Cannot inspect node: To inspect node execute module on Swarm Manager"
)
self.fail(f"Error while reading from Swarm manager: {exc}")
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting swarm node: {exc}")
json_str = json.dumps(node_info, ensure_ascii=False)
@ -295,7 +295,7 @@ class AnsibleDockerSwarmClient(AnsibleDockerClient):
"Cannot inspect service: To inspect service execute module on Swarm Manager"
)
self.fail(f"Error inspecting swarm service: {exc}")
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting swarm service: {exc}")
json_str = json.dumps(service_info, ensure_ascii=False)

View File

@ -243,7 +243,7 @@ class ConfigManager(DockerBaseClass):
try:
with open(data_src, "rb") as f:
self.data = f.read()
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.client.fail(f"Error while reading {data_src}: {exc}")
self.labels = parameters.get("labels")
self.force = parameters.get("force")

View File

@ -1084,9 +1084,7 @@ def main():
if client.module.params["content_is_b64"]:
try:
content = base64.b64decode(content)
except (
Exception
) as e: # depending on Python version and error, multiple different exceptions can be raised
except Exception as e: # pylint: disable=broad-exception-caught
client.fail(f"Cannot Base64 decode the content option: {e}")
else:
content = to_bytes(content)

View File

@ -618,7 +618,7 @@ class ImageManager(DockerBaseClass):
except NotFound:
# If the image vanished while we were trying to remove it, do not fail
pass
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error removing image {name} - {exc}")
self.results["changed"] = True
@ -714,14 +714,14 @@ class ImageManager(DockerBaseClass):
DEFAULT_DATA_CHUNK_SIZE,
False,
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error getting image {image_name} - {exc}")
try:
with open(self.archive_path, "wb") as fd:
for chunk in saved_image:
fd.write(chunk)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error writing image archive {self.archive_path} - {exc}")
self.results["image"] = image
@ -784,7 +784,7 @@ class ImageManager(DockerBaseClass):
if status == "Pushing":
changed = True
self.results["changed"] = changed
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
if "unauthorized" in str(exc):
if "authentication required" in str(exc):
self.fail(
@ -843,7 +843,7 @@ class ImageManager(DockerBaseClass):
self.client._raise_for_status(res)
if res.status_code != 201:
raise RuntimeError("Tag operation failed.")
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error: failed to tag image - {exc}")
self.results["image"] = self.client.find_image(name=repo, tag=repo_tag)
if image and image["Id"] == self.results["image"]["Id"]:
@ -1019,7 +1019,7 @@ class ImageManager(DockerBaseClass):
f"Error loading image {self.name} - {exc}",
stdout="\n".join(load_output),
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.client.fail(
f"Error loading image {self.name} - {exc}",
stdout="\n".join(load_output),

View File

@ -189,7 +189,7 @@ class ImageExportManager(DockerBaseClass):
with open(self.path, "wb") as fd:
for chunk in chunks:
fd.write(chunk)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error writing image archive {self.path} - {exc}")
def export_images(self):
@ -205,7 +205,7 @@ class ImageExportManager(DockerBaseClass):
DEFAULT_DATA_CHUNK_SIZE,
False,
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error getting image {image_names[0]} - {exc}")
else:
self.log(f"Getting archive of images {image_names_str}")
@ -219,7 +219,7 @@ class ImageExportManager(DockerBaseClass):
DEFAULT_DATA_CHUNK_SIZE,
False,
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error getting images {image_names_str} - {exc}")
self.write_chunks(chunks)

View File

@ -212,7 +212,7 @@ class ImageManager(DockerBaseClass):
inspection = self.client.get_json("/images/{0}/json", image["Id"])
except NotFound:
inspection = None
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error inspecting image {image['Id']} - {exc}")
results.append(inspection)
return results

View File

@ -141,7 +141,7 @@ class ImageManager(DockerBaseClass):
f"Error loading archive {self.path} - {exc}",
stdout="\n".join(load_output),
)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.client.fail(
f"Error loading archive {self.path} - {exc}",
stdout="\n".join(load_output),

View File

@ -159,7 +159,7 @@ class ImagePusher(DockerBaseClass):
status = line.get("status")
if status == "Pushing":
results["changed"] = True
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
if "unauthorized" in str(exc):
if "authentication required" in str(exc):
self.client.fail(

View File

@ -194,7 +194,7 @@ class ImageRemover(DockerBaseClass):
except NotFound:
# If the image vanished while we were trying to remove it, do not fail
res = []
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error removing image {name} - {exc}")
for entry in res:

View File

@ -215,7 +215,7 @@ class ImageTagger(DockerBaseClass):
self.client._raise_for_status(res)
if res.status_code != 201:
raise RuntimeError("Tag operation failed.")
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(f"Error: failed to tag image as {name}:{tag} - {exc}")
return True, msg, tagged_image

View File

@ -309,7 +309,7 @@ class LoginManager(DockerBaseClass):
self.log(f"Log into {self.registry_url} with username {self.username}")
try:
response = self._login(self.reauthorize)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(
f"Logging into {self.registry_url} for user {self.username} failed - {exc}"
)
@ -322,7 +322,7 @@ class LoginManager(DockerBaseClass):
if not self.reauthorize and response["password"] != self.password:
try:
response = self._login(True)
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.fail(
f"Logging into {self.registry_url} for user {self.username} failed - {exc}"
)

View File

@ -235,7 +235,7 @@ class SecretManager(DockerBaseClass):
try:
with open(data_src, "rb") as f:
self.data = f.read()
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
self.client.fail(f"Error while reading {data_src}: {exc}")
self.labels = parameters.get("labels")
self.force = parameters.get("force")

View File

@ -2510,7 +2510,7 @@ class DockerServiceManager:
try:
current_service = self.get_service(module.params["name"])
except Exception as e:
except Exception as e: # pylint: disable=broad-exception-caught
self.client.fail(
f"Error looking for service named {module.params['name']}: {e}"
)
@ -2527,7 +2527,7 @@ class DockerServiceManager:
network_ids,
self.client,
)
except Exception as e:
except Exception as e: # pylint: disable=broad-exception-caught
return self.client.fail(f"Error parsing module parameters: {e}")
changed = False

View File

@ -87,7 +87,7 @@ def get_existing_volume(client, volume_name):
return client.get_json("/volumes/{0}", volume_name)
except NotFound:
return None
except Exception as exc:
except Exception as exc: # pylint: disable=broad-exception-caught
client.fail(f"Error inspecting volume: {exc}")