Skip to content

Commit

Permalink
refactor: update exception handling for Python 2/3 compatibility
Browse files Browse the repository at this point in the history
Signed-off-by: Martin Styk <[email protected]>
  • Loading branch information
StykMartin committed Oct 28, 2024
1 parent b11388a commit e1f7f30
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 43 deletions.
6 changes: 3 additions & 3 deletions LabController/src/bkr/labcontroller/concurrency.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def _read_from_pipe(f):
'child process is running amok?!', f.fileno())
chunks.append('+++ DISCARDED')
discarding = True
except IOError, e:
except IOError as e:
if e.errno != errno.EAGAIN:
raise
sys.exc_clear()
Expand All @@ -54,14 +54,14 @@ def _kill_process_group(pgid):
# Try SIGTERM first, then SIGKILL just to be safe
try:
os.killpg(pgid, signal.SIGTERM)
except OSError, e:
except OSError as e:
if e.errno != errno.ESRCH:
raise
else:
gevent.sleep(1)
try:
os.killpg(pgid, signal.SIGKILL)
except OSError, e:
except OSError as e:
if e.errno != errno.ESRCH:
raise

Expand Down
36 changes: 18 additions & 18 deletions LabController/src/bkr/labcontroller/distro_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def url_exists(url):
urllib2.urlopen(url)
except urllib2.URLError:
return False
except IOError, e:
except IOError as e:
# errno 21 is you tried to retrieve a directory. Thats ok. We just
# want to ensure the path is valid so far.
if e.errno == 21:
Expand Down Expand Up @@ -156,7 +156,7 @@ def parse(self, url):
f.close()
except urllib2.URLError:
return False
except ConfigParser.MissingSectionHeaderError, e:
except ConfigParser.MissingSectionHeaderError as e:
raise BX('%s/%s is not parsable: %s' % (self.url,
self.infofile,
e))
Expand All @@ -174,7 +174,7 @@ def get(self, section, key, default=None):
if self.parser:
try:
default = self.parser.get(section, key)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError), e:
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e:
if default is None:
raise
return default
Expand Down Expand Up @@ -304,7 +304,7 @@ def get_os_dir(self, arch):
try:
os_dir = filter(lambda x: url_exists(os.path.join(base_path, x)) \
and x, self.os_dirs)[0]
except IndexError, e:
except IndexError as e:
raise BX('%s no os_dir found: %s' % (base_path, e))
return os.path.join(arch, os_dir)

Expand All @@ -330,7 +330,7 @@ def process(self, urls, options):
build = Build(full_os_dir)
build.process(urls_arch, options)
self.distro_trees.append(build.tree)
except BX, err:
except BX as err:
if not options.ignore_missing:
exit_status = 1
logging.warn(err)
Expand Down Expand Up @@ -767,7 +767,7 @@ def process(self, urls, options):
build.process(urls_variant_arch, options, repos=repos,
tags=tags, isos_path=isos_path)
self.distro_trees.append(build.tree)
except BX, err:
except BX as err:
if not options.ignore_missing:
exit_status = 1
logging.warn(err)
Expand Down Expand Up @@ -800,7 +800,7 @@ def get_os_dir(self):
try:
os_dir = filter(lambda x: url_exists(x) \
and x, [self.parser.url])[0]
except IndexError, e:
except IndexError as e:
raise BX('%s no os_dir found: %s' % (self.parser.url, e))
return os_dir

Expand Down Expand Up @@ -924,7 +924,7 @@ def process(self, urls, options, repos=None, tags=None, isos_path=None):
if nfs_url:
try:
nfs_isos_url = self._installable_isos_url(nfs_url, isos_path)
except IncompleteTree, e:
except IncompleteTree as e:
logging.warn(str(e))
else:
if nfs_isos_url:
Expand All @@ -937,7 +937,7 @@ def process(self, urls, options, repos=None, tags=None, isos_path=None):
try:
self.add_to_beaker()
logging.info('%s %s %s added to beaker.' % (self.tree['name'], self.tree['variant'], self.tree['arch']))
except (xmlrpclib.Fault, socket.error), e:
except (xmlrpclib.Fault, socket.error) as e:
raise BX('failed to add %s %s %s to beaker: %s' % (self.tree['name'], self.tree['variant'], self.tree['arch'], e))

def extend_tree(self):
Expand Down Expand Up @@ -1038,14 +1038,14 @@ def get_kernel_path(self):
try:
return filter(lambda x: url_exists(os.path.join(self.parser.url,x)) \
and x, [kernel for kernel in self.kernels])[0]
except IndexError, e:
except IndexError as e:
raise BX('%s no kernel found: %s' % (self.parser.url, e))

def get_initrd_path(self):
try:
return filter(lambda x: url_exists(os.path.join(self.parser.url,x)) \
and x, [initrd for initrd in self.initrds])[0]
except IndexError, e:
except IndexError as e:
raise BX('%s no kernel found: %s' % (self.parser.url, e))

def find_repos(self, *args, **kw):
Expand Down Expand Up @@ -1508,7 +1508,7 @@ def find_repos(self):
path=repopath,
)
)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError), e:
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e:
logging.debug('.treeinfo has no repository for variant %s, %s' % (self.parser.url,e))
try:
addons = self.parser.get('variant-%s' % self.tree['variant'],
Expand All @@ -1523,7 +1523,7 @@ def find_repos(self):
path=repopath,
)
)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError), e:
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e:
logging.debug('.treeinfo has no addon repos for %s, %s' % (self.parser.url,e))
return repos

Expand Down Expand Up @@ -1606,7 +1606,7 @@ def find_repos(self):
type='addon',
path=repopath,)
)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError), e:
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e:
logging.debug('no addon repos for %s, %s' % (self.parser.url, e))
return repos

Expand Down Expand Up @@ -1708,7 +1708,7 @@ def find_repos(self):
path=repopath,
)
)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError), e:
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e:
logging.debug('no addon repos for %s, %s' % (self.parser.url,e))
return repos

Expand Down Expand Up @@ -1939,7 +1939,7 @@ def process(self, urls, options, repos=[]):
try:
self.add_to_beaker()
logging.info('%s added to beaker.' % self.tree['name'])
except (xmlrpclib.Fault, socket.error), e:
except (xmlrpclib.Fault, socket.error) as e:
raise BX('failed to add %s to beaker: %s' % (self.tree['name'],e))

def add_to_beaker(self):
Expand Down Expand Up @@ -2102,10 +2102,10 @@ def main():
try:
build.check_input(opts)
exit_status.append(build.process(urls, opts))
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError), e:
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e:
logging.critical(str(e))
sys.exit(3)
except (xmlrpclib.Fault,BX), err:
except (xmlrpclib.Fault,BX) as err:
logging.critical(err)
sys.exit(127)
if opts.run_jobs:
Expand Down
2 changes: 1 addition & 1 deletion LabController/src/bkr/labcontroller/log_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def __enter__(self):
# combination of flags, so we have to use raw os.open :-(
fd = os.open(self.path, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0644)
created = True
except (OSError, IOError), e:
except (OSError, IOError) as e:
if e.errno != errno.EEXIST:
raise
fd = os.open(self.path, os.O_RDWR)
Expand Down
6 changes: 3 additions & 3 deletions LabController/src/bkr/labcontroller/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def __call__(self, req):
return Response(response=repr(result), content_type='text/plain')
else:
return getattr(obj, attr)(req, **args)
except HTTPException, e:
except HTTPException as e:
return e

# Temporary hack to disable keepalive in gevent.wsgi.WSGIServer. This should be easier.
Expand All @@ -167,7 +167,7 @@ def log_failed_requests(func):
def _log_failed_requests(environ, start_response):
try:
return func(environ, start_response)
except Exception, e:
except Exception as e:
logger.exception('Error handling request %s %s',
environ.get('REQUEST_METHOD'), environ.get('PATH_INFO'))
raise
Expand Down Expand Up @@ -229,7 +229,7 @@ def main():
log_to_stream(sys.stderr, level=logging.WARNING)
try:
proxy = Proxy(conf=conf)
except Exception, ex:
except Exception as ex:
sys.stderr.write("Error starting beaker-proxy: %s\n" % ex)
sys.exit(1)

Expand Down
6 changes: 3 additions & 3 deletions LabController/src/bkr/labcontroller/provision.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def handle(self, command, predecessors):
logger.exception('Error processing command %s', command['id'])
# It's not the system's fault so don't mark it as broken
self.mark_command_failed(command['id'], unicode(e), False)
except Exception, e:
except Exception as e:
logger.exception('Error processing command %s', command['id'])
self.mark_command_failed(command['id'],
'%s: %s' % (e.__class__.__name__, e), True)
Expand Down Expand Up @@ -215,7 +215,7 @@ def truncate_logfile(console_log):
logger.debug('Truncating console log %s', console_log)
try:
f = open(console_log, 'r+')
except IOError, e:
except IOError as e:
if e.errno != errno.ENOENT:
raise
else:
Expand Down Expand Up @@ -326,7 +326,7 @@ def main():
log_to_stream(sys.stderr, level=logging.WARNING)
try:
poller = CommandQueuePoller(conf=conf)
except Exception, ex:
except Exception as ex:
sys.stderr.write('Error starting beaker-provision: %s\n' % ex)
sys.exit(1)

Expand Down
24 changes: 12 additions & 12 deletions LabController/src/bkr/labcontroller/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def process_log(self, block):
self.logfile_name, create=(self.where == 0))
with log_file:
log_file.update_chunk(block, self.where)
except (OSError, IOError), e:
except (OSError, IOError) as e:
if e.errno == errno.ENOENT:
pass # someone has removed our log, discard the update
else:
Expand Down Expand Up @@ -293,7 +293,7 @@ def update(self):
"""
try:
file = open(self.log, "r")
except (OSError, IOError), e:
except (OSError, IOError) as e:
if e.errno == errno.ENOENT:
return False # doesn't exist
else:
Expand All @@ -313,7 +313,7 @@ def update(self):
def truncate(self):
try:
f = open(self.log, 'r+')
except IOError, e:
except IOError as e:
if e.errno != errno.ENOENT:
raise
else:
Expand Down Expand Up @@ -386,7 +386,7 @@ def _load_patterns(self):
site_dir = '/etc/beaker/install-failure-patterns'
try:
site_patterns = os.listdir(site_dir)
except OSError, e:
except OSError as e:
if e.errno == errno.ENOENT:
site_patterns = []
else:
Expand All @@ -401,7 +401,7 @@ def _load_patterns(self):
for p in site_patterns:
try:
patterns.append(open(os.path.join(site_dir, p), 'r').read().strip())
except OSError, e:
except OSError as e:
if e.errno == errno.ENOENT:
pass # readdir race
else:
Expand Down Expand Up @@ -461,7 +461,7 @@ def transfer_recipe_logs(self, recipe_id):
try:
os.link(mysrc,mydst)
trlogs.append(mylog)
except OSError, e:
except OSError as e:
logger.exception('Error hard-linking %s to %s', mysrc, mydst)
return
else:
Expand Down Expand Up @@ -796,7 +796,7 @@ def post_result(self, req, recipe_id, task_id):
self._result_types[result],
req.form.get('path'), req.form.get('score'),
req.form.get('message'))
except xmlrpclib.Fault, fault:
except xmlrpclib.Fault as fault:
# XXX need to find a less fragile way to do this
if 'Cannot record result for finished task' in fault.faultString:
return Response(status=409, response=fault.faultString,
Expand Down Expand Up @@ -904,7 +904,7 @@ def _put_log(self, log_file, req):
log_file.truncate(req.content_length)
log_file.update_chunk(req.data, 0)
# XXX need to find a less fragile way to do this
except xmlrpclib.Fault, fault:
except xmlrpclib.Fault as fault:
if 'Cannot register file for finished ' in fault.faultString:
return Response(status=409, response=fault.faultString,
content_type='text/plain')
Expand All @@ -918,7 +918,7 @@ def _put_log(self, log_file, req):
def _get_log(self, log_file, req):
try:
f = log_file.open_ro()
except IOError, e:
except IOError as e:
if e.errno == errno.ENOENT:
raise NotFound()
else:
Expand Down Expand Up @@ -980,7 +980,7 @@ def _log_index(self, req, logs):
def list_recipe_logs(self, req, recipe_id):
try:
logs = self.hub.taskactions.files('R:%s' % recipe_id)
except xmlrpclib.Fault, fault:
except xmlrpclib.Fault as fault:
# XXX need to find a less fragile way to do this
if 'is not a valid Recipe id' in fault.faultString:
raise NotFound()
Expand All @@ -993,7 +993,7 @@ def list_recipe_logs(self, req, recipe_id):
def list_task_logs(self, req, recipe_id, task_id):
try:
logs = self.hub.taskactions.files('T:%s' % task_id)
except xmlrpclib.Fault, fault:
except xmlrpclib.Fault as fault:
# XXX need to find a less fragile way to do this
if 'is not a valid RecipeTask id' in fault.faultString:
raise NotFound()
Expand All @@ -1006,7 +1006,7 @@ def list_task_logs(self, req, recipe_id, task_id):
def list_result_logs(self, req, recipe_id, task_id, result_id):
try:
logs = self.hub.taskactions.files('TR:%s' % result_id)
except xmlrpclib.Fault, fault:
except xmlrpclib.Fault as fault:
# XXX need to find a less fragile way to do this
if 'is not a valid RecipeTaskResult id' in fault.faultString:
raise NotFound()
Expand Down
2 changes: 1 addition & 1 deletion LabController/src/bkr/labcontroller/test_concurrency.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def _assert_process_group_is_removed(self, pgid):
os.killpg(pgid, signal.SIGKILL)
sleep(0.5)
self.fail("The process group should've already been removed")
except OSError, e:
except OSError as e:
if e.errno != errno.ESRCH:
self.fail("The process group should've already been removed")

Expand Down
2 changes: 1 addition & 1 deletion LabController/src/bkr/labcontroller/transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def main():
log_to_stream(sys.stderr, level=logging.WARNING)
try:
logarchiver = LogArchiver(conf=conf)
except Exception, ex:
except Exception as ex:
sys.stderr.write("Error starting beaker-transfer: %s\n" % ex)
sys.exit(1)

Expand Down
2 changes: 1 addition & 1 deletion LabController/src/bkr/labcontroller/watchdog.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ def main():
log_to_stream(sys.stderr, level=logging.WARNING)
try:
watchdog = Watchdog(conf=conf)
except Exception, ex:
except Exception as ex:
sys.stderr.write("Error starting beaker-watchdog: %s\n" % ex)
sys.exit(1)

Expand Down

0 comments on commit e1f7f30

Please sign in to comment.