Skip to content

Commit

Permalink
fixup! chore: Make exception handling more explicit
Browse files Browse the repository at this point in the history
  • Loading branch information
holmanb committed May 3, 2024
1 parent 2864b51 commit 4a24b71
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 29 deletions.
7 changes: 2 additions & 5 deletions cloudinit/config/cc_mounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,13 +406,9 @@ def handle_swapcfg(swapcfg):
LOG.warning(
"swap file %s exists. Error reading /proc/swaps", fname
)
return fname
except Exception as e:
LOG.warning("Unhandled exception: %s", e)
LOG.warning(
"swap file %s exists. Error reading /proc/swaps", fname
)
return fname
return fname

try:
if isinstance(size, str) and size != "auto":
Expand Down Expand Up @@ -472,6 +468,7 @@ def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:
util.logexc(
LOG, "Failed to parse devs from file %s", FSTAB_PATH
)
raise

device_aliases = cfg.get("device_aliases", {})

Expand Down
10 changes: 0 additions & 10 deletions cloudinit/config/cc_ssh_import_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,6 @@ def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:
try:
import_ids = util.uniq_merge(import_ids)
import_ids = [str(i) for i in import_ids]
except (AttributeError, TypeError):
LOG.warning(
"User %s is not correctly configured for ssh_import_id", user
)
continue
except Exception:
util.logexc(LOG, "Unhandled configuration for user %s", user)
continue
Expand All @@ -108,11 +103,6 @@ def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:

try:
import_ssh_ids(import_ids, user)
except subp.ProcessExecutionError as exc:
util.logexc(
LOG, "ssh-import-id failed for: %s %s", user, import_ids
)
elist.append(exc)
except Exception as exc:
util.logexc(
LOG, "ssh-import-id failed for: %s %s", user, import_ids
Expand Down
8 changes: 5 additions & 3 deletions cloudinit/config/modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
"cc_ubuntu_advantage": "cc_ubuntu_pro", # Renamed 24.1
}

RunOutput = Tuple[List[str], List[Tuple[str, Exception]]]


class ModuleDetails(NamedTuple):
module: ModuleType
Expand Down Expand Up @@ -248,7 +250,7 @@ def _fixup_modules(self, raw_mods) -> List[ModuleDetails]:

def _run_modules(
self, mostly_mods: List[ModuleDetails]
) -> Tuple[List[str], List[Tuple[str, Exception]]]:
) -> RunOutput:
cc = self.init.cloudify()
# Return which ones ran
# and which ones failed + the exception of why it failed
Expand Down Expand Up @@ -300,7 +302,7 @@ def _run_modules(

def run_single(
self, mod_name: str, args=None, freq=None
) -> Tuple[List[str], List[Tuple[str, Exception]]]:
) -> RunOutput:
"""Run a single module
return: a tuple containing two lists:
Expand All @@ -321,7 +323,7 @@ def run_single(

def run_section(
self, section_name: str
) -> Tuple[List[str], List[Tuple[str, Exception]]]:
) -> RunOutput:
"""Runs all modules in the given section.
section_name - One of the modules lists as defined in
Expand Down
5 changes: 4 additions & 1 deletion cloudinit/handlers/jinja_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,10 @@ def render_jinja_payload_from_file(
" '%s'. Try sudo" % instance_data_file
)
raise JinjaLoadError(msg) from e
except (OSError, ValueError) as e:
except (OSError, ValueError, TypeError) as e:
raise JinjaLoadError("Loading Jinja instance data failed") from e
except Exception as e:
LOG.warning("Unhandled exception: %s", e)
raise JinjaLoadError("Loading Jinja instance data failed") from e

rendered_payload = render_jinja_payload(
Expand Down
14 changes: 12 additions & 2 deletions cloudinit/sources/helpers/openstack.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def _find_working_version(self):
e,
)
except Exception as e:
LOG.warning("Unhandled exception")
LOG.warning("Unhandled exception: %s", e)
LOG.debug(
"Unable to read openstack versions from %s due to: %s",
self.base_path,
Expand Down Expand Up @@ -317,6 +317,11 @@ def datafiles(version):
raise BrokenMetadata(
"Badly formatted metadata random_seed entry: %s" % e
) from e
except Exception as e:
LOG.warning("Unhandled exception: %s", e)
raise BrokenMetadata(
"Badly formatted metadata random_seed entry: %s" % e
) from e

# load any files that were provided
files = {}
Expand Down Expand Up @@ -403,7 +408,12 @@ def _read_ec2_metadata(self):
else:
try:
return util.load_json(self._path_read(path))
except OSError as e:
except (OSError, ValueError) as e:
raise BrokenMetadata(
"Failed to process path %s: %s" % (path, e)
) from e
except Exception as e:
LOG.warning("Unhandled exception: %s", e)
raise BrokenMetadata(
"Failed to process path %s: %s" % (path, e)
) from e
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
LOG = logging.getLogger(__name__)


class CustomScriptNotFound(OSError):
class CustomScriptNotFound(Exception):
pass


Expand Down
2 changes: 1 addition & 1 deletion cloudinit/sources/helpers/vmware/imc/guestcust_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def send_rpc(rpc):
# Remove the trailing newline in the output.
if out:
out = out.rstrip()
except OSError as e:
except subp.ProcessExecutionError as e:
logger.debug("Failed to send RPC command")
logger.exception(e)

Expand Down
14 changes: 11 additions & 3 deletions cloudinit/stages.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,11 @@ def _reflect_cur_instance(self):
try:
previous_ds = util.load_text_file(ds_fn, quiet=True).strip()
except OSError:
LOG.info("Couldn't load file %s", previous_ds)
pass
except UnicodeDecodeError:
LOG.warning("Invalid previous datasource in file: %s", previous_ds)
except Exception as e:
LOG.warning("Unhandled exception: %s", e)
if not previous_ds:
previous_ds = ds
util.write_file(ds_fn, "%s\n" % ds)
Expand Down Expand Up @@ -509,11 +513,15 @@ def previous_iid(self):

dp = self.paths.get_cpath("data")
iid_fn = os.path.join(dp, "instance-id")
self._previous_iid = NO_PREVIOUS_INSTANCE_ID
try:
self._previous_iid = util.load_text_file(iid_fn).strip()
except OSError:
LOG.info("Couldn't load file %s", iid_fn)
self._previous_iid = NO_PREVIOUS_INSTANCE_ID
pass
except UnicodeDecodeError:
LOG.warning("Invalid instance id in file: %s", iid_fn)
except Exception as e:
LOG.warning("Unhandled exception: %s", e)

LOG.debug("previous iid found to be %s", self._previous_iid)
return self._previous_iid
Expand Down
10 changes: 7 additions & 3 deletions cloudinit/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -1391,10 +1391,14 @@ def search_for_mirror(candidates):

LOG.debug("search for mirror in candidates: '%s'", candidates)
for cand in candidates:
with suppress(ValueError):
try:
if is_resolvable_url(cand):
LOG.debug("found working mirror: '%s'", cand)
return cand
except ValueError:
LOG.debug("Failed to parse url: %s", cand)
except Exception as e:
LOG.warning("Unhandled exception: %s", e)
return None


Expand Down Expand Up @@ -3309,11 +3313,11 @@ def read_hotplug_enabled_file(paths: "Paths") -> dict:
content: dict = {"scopes": []}
try:
content = json.loads(
load_binary_file(paths.get_cpath("hotplug.enabled"), quiet=False)
load_text_file(paths.get_cpath("hotplug.enabled"), quiet=False)
)
except FileNotFoundError:
LOG.debug("File not found: %s", paths.get_cpath("hotplug.enabled"))
except json.JSONDecodeError as e:
except (json.JSONDecodeError, UnicodeDecodeError) as e:
LOG.warning(
"Ignoring contents of %s because it is not decodable. Error: %s",
settings.HOTPLUG_ENABLED_FILE,
Expand Down

0 comments on commit 4a24b71

Please sign in to comment.