Skip to content

Commit

Permalink
chore(IOError): Update IOError to OSError
Browse files Browse the repository at this point in the history
In Python 3.3+, IOError is an alias of OSError[1]. Some call sites use
one or the other or both. Standardize on the OSError.

[1] https://docs.python.org/3/library/exceptions.html#IOError
  • Loading branch information
holmanb committed Apr 26, 2024
1 parent 7d78df7 commit b1b4c06
Show file tree
Hide file tree
Showing 54 changed files with 112 additions and 114 deletions.
2 changes: 1 addition & 1 deletion cloudinit/apport.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def attach_cloud_info(report, ui=None):
instance_data = json.load(file)
assert instance_data.get("v1", {}).get("cloud_name")
return # Valid instance-data means generic-hooks will report
except (IOError, json.decoder.JSONDecodeError, AssertionError):
except (OSError, json.decoder.JSONDecodeError, AssertionError):
pass

# No valid /run/cloud/instance-data.json on system. Prompt for cloud.
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/cmd/cloud_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def handle_args(name, args):
try:
with open(args.instance_data) as file:
instance_data = json.load(file)
except IOError:
except OSError:
return error(
"File not found '%s'. Provide a path to instance data json file"
" using --instance-data" % args.instance_data
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/cmd/devel/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def render_template(user_data_path, instance_data_path=None, debug=False):
try:
with open(user_data_path) as stream:
user_data = stream.read()
except IOError:
except OSError:
LOG.error("Missing user-data file: %s", user_data_path)
return 1
try:
Expand Down
17 changes: 8 additions & 9 deletions cloudinit/cmd/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import logging
import os
import sys
from errno import EACCES

from cloudinit import atomic_helper, util
from cloudinit.cmd.devel import read_cfg_paths
Expand Down Expand Up @@ -147,7 +146,7 @@ def _read_instance_data(instance_data, user_data, vendor_data) -> dict:
Non-root users will have redacted INSTANCE_JSON_FILE content and redacted
vendordata and userdata values.
:raise: IOError/OSError on absence of instance-data.json file or invalid
:raise: OSError on absence of instance-data.json file or invalid
access perms.
"""
uid = os.getuid()
Expand Down Expand Up @@ -181,19 +180,19 @@ def _read_instance_data(instance_data, user_data, vendor_data) -> dict:

try:
instance_json = util.load_text_file(instance_data_fn)
except (IOError, OSError) as e:
if e.errno == EACCES:
LOG.error("No read permission on '%s'. Try sudo", instance_data_fn)
else:
LOG.error("Missing instance-data file: %s", instance_data_fn)
except PermissionError:
LOG.error("No read permission on '%s'. Try sudo", instance_data_fn)
raise
except OSError:
LOG.error("Missing instance-data file: %s", instance_data_fn)
raise

instance_data = util.load_json(instance_json)
try:
combined_cloud_config = util.load_json(
util.load_text_file(combined_cloud_config_fn)
)
except (IOError, OSError):
except OSError:
# File will not yet be present in init-local stage.
# It's created in `init` when vendor-data and user-data are processed.
combined_cloud_config = None
Expand Down Expand Up @@ -274,7 +273,7 @@ def handle_args(name, args):
instance_data = _read_instance_data(
args.instance_data, args.user_data, args.vendor_data
)
except (IOError, OSError):
except OSError:
return 1
if args.format:
payload = "## template: jinja\n{fmt}".format(fmt=args.format)
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/config/cc_apt_configure.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def apply_apt(cfg, cloud, gpg):

try:
apply_apt_config(cfg, APT_PROXY_FN, APT_CONFIG_FN)
except (IOError, OSError):
except OSError:
LOG.exception("Failed to apply proxy or apt config info:")

# Process 'apt_source -> sources {dict}'
Expand Down Expand Up @@ -852,7 +852,7 @@ def add_apt_sources(
omode = "w"

util.write_file(sourcefn, contents, omode=omode)
except IOError as detail:
except OSError as detail:
LOG.exception("failed write to file %s: %s", sourcefn, detail)
raise

Expand Down
4 changes: 2 additions & 2 deletions cloudinit/config/cc_mcollective.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def configure(
try:
old_contents = util.load_binary_file(server_cfg, quiet=False)
mcollective_config = ConfigObj(io.BytesIO(old_contents))
except IOError as e:
except OSError as e:
if e.errno != errno.ENOENT:
raise
else:
Expand Down Expand Up @@ -137,7 +137,7 @@ def configure(
# We got all our config as wanted we'll copy
# the previous server.cfg and overwrite the old with our new one
util.copy(server_cfg, "%s.old" % (server_cfg))
except IOError as e:
except OSError as e:
if e.errno == errno.ENOENT:
# Doesn't exist to copy...
pass
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/config/cc_mounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ def setup_swapfile(fname, size=None, maxsize=None):
if str(size).lower() == "auto":
try:
memsize = util.read_meminfo()["total"]
except IOError:
except OSError:
LOG.debug("Not creating swap: failed to read meminfo")
return

Expand Down
6 changes: 3 additions & 3 deletions cloudinit/config/cc_power_state_change.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def givecmdline(pid):
return m.group(2)
else:
return util.load_text_file("/proc/%s/cmdline" % pid)
except IOError:
except OSError:
return None


Expand Down Expand Up @@ -242,11 +242,11 @@ def fatal(msg):
msg = "cmdline changed for %s [now: %s]" % (pid, cmdline)
break

except IOError as ioerr:
except OSError as ioerr:
if ioerr.errno in known_errnos:
msg = "pidfile gone [%d]" % ioerr.errno
else:
fatal("IOError during wait: %s" % ioerr)
fatal("OSError during wait: %s" % ioerr)
break

except Exception as e:
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/config/cc_seed_random.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def _decode(data, encoding=None):
elif encoding.lower() in ["gzip", "gz"]:
return util.decomp_gzip(data, quiet=False, decode=None)
else:
raise IOError("Unknown random_seed encoding: %s" % (encoding))
raise OSError("Unknown random_seed encoding: %s" % (encoding))


def handle_random_seed_command(command, required, update_env):
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/config/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -1582,7 +1582,7 @@ def get_schema(schema_type: SchemaType = SchemaType.CLOUD_CONFIG) -> dict:
full_schema = None
try:
full_schema = json.loads(load_text_file(schema_file))
except (IOError, OSError):
except OSError:
LOG.warning(
"Skipping %s schema validation. No JSON schema file found %s.",
schema_type.value,
Expand Down Expand Up @@ -1722,7 +1722,7 @@ def get_processed_or_fallback_path(

try:
paths = read_cfg_paths(fetch_existing_datasource="trust")
except (IOError, OSError) as e:
except OSError as e:
if e.errno == EACCES:
LOG.debug(
"Using default instance-data/user-data paths for non-root user"
Expand Down
16 changes: 8 additions & 8 deletions cloudinit/distros/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ def _write_network_state(self, network_state, renderer: Renderer):
def _find_tz_file(self, tz):
tz_file = os.path.join(self.tz_zone_dir, str(tz))
if not os.path.isfile(tz_file):
raise IOError(
raise OSError(
"Invalid timezone %s, no file found at %s" % (tz, tz_file)
)
return tz_file
Expand Down Expand Up @@ -583,7 +583,7 @@ def update_hostname(self, hostname, fqdn, prev_hostname_fn):
for fn in update_files:
try:
self._write_hostname(hostname, fn)
except IOError:
except OSError:
util.logexc(
LOG, "Failed to write hostname %s to %s", hostname, fn
)
Expand Down Expand Up @@ -998,14 +998,14 @@ def write_doas_rules(self, user, rules, doas_file=None):
contents = [util.make_header(), content]
try:
util.write_file(doas_file, "\n".join(contents), mode=0o440)
except IOError as e:
except OSError as e:
util.logexc(LOG, "Failed to write doas file %s", doas_file)
raise e
else:
if content not in util.load_text_file(doas_file):
try:
util.append_file(doas_file, content)
except IOError as e:
except OSError as e:
util.logexc(
LOG, "Failed to append to doas file %s", doas_file
)
Expand Down Expand Up @@ -1055,7 +1055,7 @@ def ensure_sudo_dir(self, path, sudo_base="/etc/sudoers"):
sudoers_contents = "\n".join(lines)
util.append_file(sudo_base, sudoers_contents)
LOG.debug("Added '#includedir %s' to %s", path, sudo_base)
except IOError as e:
except OSError as e:
util.logexc(LOG, "Failed to write %s", sudo_base)
raise e
util.ensure_dir(path, 0o750)
Expand Down Expand Up @@ -1088,14 +1088,14 @@ def write_sudo_rules(self, user, rules, sudo_file=None):
]
try:
util.write_file(sudo_file, "\n".join(contents), 0o440)
except IOError as e:
except OSError as e:
util.logexc(LOG, "Failed to write sudoers file %s", sudo_file)
raise e
else:
if content not in util.load_text_file(sudo_file):
try:
util.append_file(sudo_file, content)
except IOError as e:
except OSError as e:
util.logexc(
LOG, "Failed to append to sudoers file %s", sudo_file
)
Expand Down Expand Up @@ -1316,7 +1316,7 @@ def _get_proc_stat_by_index(pid: int, field: int) -> Optional[int]:
)
return None
return int(match.group(field))
except IOError as e:
except OSError as e:
LOG.warning("Failed to load /proc/%s/stat. %s", pid, e)
except IndexError:
LOG.warning(
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/distros/alpine.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def _write_hostname(self, hostname, filename):
# Try to update the previous one
# so lets see if we can read it first.
conf = self._read_hostname_conf(filename)
except IOError:
except OSError:
create_hostname_file = util.get_cfg_option_bool(
self._cfg, "create_hostname_file", True
)
Expand Down Expand Up @@ -115,7 +115,7 @@ def _read_hostname(self, filename, default=None):
try:
conf = self._read_hostname_conf(filename)
hostname = conf.hostname
except IOError:
except OSError:
pass
if not hostname:
return default
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/distros/arch.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def _write_hostname(self, hostname, filename):
# Try to update the previous one
# so lets see if we can read it first.
conf = self._read_hostname_conf(filename)
except IOError:
except OSError:
create_hostname_file = util.get_cfg_option_bool(
self._cfg, "create_hostname_file", True
)
Expand Down Expand Up @@ -94,7 +94,7 @@ def _read_hostname(self, filename, default=None):
try:
conf = self._read_hostname_conf(filename)
hostname = conf.hostname
except IOError:
except OSError:
pass
if not hostname:
return default
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/distros/debian.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def _write_hostname(self, hostname, filename):
# Try to update the previous one
# so lets see if we can read it first.
conf = self._read_hostname_conf(filename)
except IOError:
except OSError:
create_hostname_file = util.get_cfg_option_bool(
self._cfg, "create_hostname_file", True
)
Expand Down Expand Up @@ -160,7 +160,7 @@ def _read_hostname(self, filename, default=None):
try:
conf = self._read_hostname_conf(filename)
hostname = conf.hostname
except IOError:
except OSError:
pass
if not hostname:
return default
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/distros/freebsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ def apply_locale(self, locale, out_fn=None):
util.logexc(LOG, "Failed to apply locale %s", locale)
try:
util.copy(self.login_conf_fn_bak, self.login_conf_fn)
except IOError:
except OSError:
util.logexc(
LOG, "Failed to restore %s backup", self.login_conf_fn
)
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/distros/gentoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def _write_hostname(self, hostname, filename):
# Try to update the previous one
# so lets see if we can read it first.
conf = self._read_hostname_conf(filename)
except IOError:
except OSError:
create_hostname_file = util.get_cfg_option_bool(
self._cfg, "create_hostname_file", True
)
Expand Down Expand Up @@ -98,7 +98,7 @@ def _read_hostname(self, filename, default=None):
try:
conf = self._read_hostname_conf(filename)
hostname = conf.hostname
except IOError:
except OSError:
pass
if not hostname:
return default
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/distros/opensuse.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def _read_hostname(self, filename, default=None):
try:
conf = self._read_hostname_conf(filename)
hostname = conf.hostname
except IOError:
except OSError:
pass
if not hostname:
return default
Expand Down Expand Up @@ -244,7 +244,7 @@ def _write_hostname(self, hostname, filename):
# Try to update the previous one
# so lets see if we can read it first.
conf = self._read_hostname_conf(filename)
except IOError:
except OSError:
if create_hostname_file:
pass
else:
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/distros/parsers/hostname.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,5 +71,5 @@ def _parse(self, contents):
entries.append(("hostname", [head, tail]))
hostnames_found.add(head)
if len(hostnames_found) > 1:
raise IOError("Multiple hostnames (%s) found!" % (hostnames_found))
raise OSError("Multiple hostnames (%s) found!" % (hostnames_found))
return entries
4 changes: 2 additions & 2 deletions cloudinit/distros/parsers/resolv_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def _parse(self, contents):
try:
(cfg_opt, cfg_values) = head.split(None, 1)
except (IndexError, ValueError) as e:
raise IOError(
raise OSError(
"Incorrectly formatted resolv.conf line %s" % (i + 1)
) from e
if cfg_opt not in [
Expand All @@ -158,6 +158,6 @@ def _parse(self, contents):
"sortlist",
"options",
]:
raise IOError("Unexpected resolv.conf option %s" % (cfg_opt))
raise OSError("Unexpected resolv.conf option %s" % (cfg_opt))
entries.append(("option", [cfg_opt, cfg_values, tail]))
return entries
2 changes: 1 addition & 1 deletion cloudinit/distros/rhel_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,6 @@ def read_sysconfig_file(fn):
try:
contents = util.load_text_file(fn).splitlines()
exists = True
except IOError:
except OSError:
contents = []
return (exists, SysConf(contents))
4 changes: 2 additions & 2 deletions cloudinit/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def clear(self, name, freq):
sem_file = self._get_path(name, freq)
try:
util.del_file(sem_file)
except (IOError, OSError):
except OSError:
util.logexc(LOG, "Failed deleting semaphore %s", sem_file)
return False
return True
Expand All @@ -86,7 +86,7 @@ def _acquire(self, name, freq):
contents = "%s: %s\n" % (os.getpid(), time())
try:
util.write_file(sem_file, contents)
except (IOError, OSError):
except OSError:
util.logexc(LOG, "Failed writing semaphore file %s", sem_file)
return None
return FileLock(sem_file)
Expand Down
Loading

0 comments on commit b1b4c06

Please sign in to comment.