Merge pull request #49596 from terminalmage/kill-bare-excepts-with-fire

Kill bare excepts with fire
This commit is contained in:
Nicole Thomas 2018-09-11 09:58:16 -04:00 committed by GitHub
commit e8171de57b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 50 additions and 55 deletions

View File

@ -661,8 +661,6 @@ def _get_properties(path="", method="GET", forced_params=None):
props = sub['info'][method]['parameters']['properties'].keys()
except KeyError as exc:
log.error('method not found: "{0}"'.format(str(exc)))
except:
raise
for prop in props:
numerical = re.match(r'(\w+)\[n\]', prop)
# generate (arbitrarily) 10 properties for duplicatable properties identified by:

View File

@ -201,7 +201,7 @@ def v4_int_to_packed(address):
"""
try:
return _int_to_bytes(address, 4, 'big')
except:
except Exception:
raise ValueError("Address negative or too large for IPv4")
@ -217,7 +217,7 @@ def v6_int_to_packed(address):
"""
try:
return _int_to_bytes(address, 16, 'big')
except:
except Exception:
raise ValueError("Address negative or too large for IPv6")

View File

@ -2686,7 +2686,7 @@ class SyndicManager(MinionBase):
yield tornado.gen.sleep(auth_wait) # TODO: log?
except KeyboardInterrupt:
raise
except: # pylint: disable=W0702
except Exception:
failed = True
log.critical('Unexpected error while connecting to {0}'.format(opts['master']), exc_info=True)
@ -3047,11 +3047,11 @@ class Matcher(object):
try:
# Target is an address?
tgt = ipaddress.ip_address(tgt)
except: # pylint: disable=bare-except
except Exception:
try:
# Target is a network?
tgt = ipaddress.ip_network(tgt)
except: # pylint: disable=bare-except
except Exception:
log.error('Invalid IP/CIDR target: {0}'.format(tgt))
return []
proto = 'ipv{0}'.format(tgt.version)

View File

@ -75,7 +75,7 @@ def uuid(dev=None):
else:
# basename of the /sys/block/{dev}/bcache/cache symlink target
return os.path.basename(_bcsys(dev, 'cache'))
except: # pylint: disable=bare-except
except Exception:
return False
@ -492,7 +492,7 @@ def device(dev, stats=False, config=False, internals=False, superblock=False):
try:
result['dev'] = os.path.basename(_bcsys(dev, 'dev'))
except: # pylint: disable=bare-except
except Exception:
pass
result['bdev'] = _bdev(dev)
@ -604,10 +604,10 @@ def super_(dev):
try:
rval = int(rval)
except: # pylint: disable=bare-except
except Exception:
try:
rval = float(rval)
except: # pylint: disable=bare-except
except Exception:
if rval == 'yes':
rval = True
elif rval == 'no':
@ -800,10 +800,10 @@ def _sysfs_parse(path, base_attr=None, stats=False, config=False, internals=Fals
val = val.strip()
try:
val = int(val)
except: # pylint: disable=bare-except
except Exception:
try:
val = float(val)
except: # pylint: disable=bare-except
except Exception:
pass
listres[key.strip()] = val
result[strlist] = listres
@ -846,7 +846,7 @@ def _size_map(size):
size = 1024**2 * float(re.sub(r'[Mm]', '', size))
size = int(size)
return size
except: # pylint: disable=bare-except
except Exception:
return None

View File

@ -127,7 +127,7 @@ def _delete_resource(name, name_param, desc, res_type, wait=0, status_param=None
'''
try:
wait = int(wait)
except:
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
@ -177,7 +177,7 @@ def _create_resource(name, name_param=None, desc=None, res_type=None, wait=0, st
**args):
try:
wait = int(wait)
except:
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
@ -227,7 +227,7 @@ def _modify_resource(name, name_param=None, desc=None, res_type=None, wait=0, st
**args):
try:
wait = int(wait)
except:
except Exception:
raise SaltInvocationError("Bad value ('{0}') passed for 'wait' param - must be an "
"int or boolean.".format(wait))
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

View File

@ -590,7 +590,7 @@ def hdparms(disks, args=None):
try:
val = int(val)
rvals.append(val)
except: # pylint: disable=bare-except
except Exception:
if '=' in val:
deep_key, val = val.split('=', 1)
deep_key = deep_key.strip()
@ -657,7 +657,7 @@ def hpa(disks, size=None):
for disk, data in hpa_data.items():
try:
size = data['total'] - int(size)
except: # pylint: disable=bare-except
except Exception:
if '%' in size:
size = int(size.strip('%'))
size = (100 - size) * data['total']
@ -722,17 +722,17 @@ def smart_attributes(dev, attributes=None, values=None):
data = dict(zip(fields, line[1:]))
try:
del data['_']
except: # pylint: disable=bare-except
except Exception:
pass
for field in data:
val = data[field]
try:
val = int(val)
except: # pylint: disable=bare-except
except Exception:
try:
val = [int(value) for value in val.split(' ')]
except: # pylint: disable=bare-except
except Exception:
pass
data[field] = val

View File

@ -2225,7 +2225,7 @@ def replace(path,
except OSError:
os.remove(symlink_backup)
os.symlink(target_backup, symlink_backup)
except:
except Exception:
raise CommandExecutionError(
"Unable create backup symlink '{0}'. "
"Target was '{1}'. "
@ -5927,7 +5927,7 @@ def open_files(by_pid=False):
#try:
# fd_.append(os.path.realpath('{0}/task/{1}exe'.format(ppath, tid)))
#except:
#except Exception:
# pass
for fpath in os.listdir('{0}/fd'.format(ppath)):

View File

@ -281,8 +281,7 @@ def _dmi_cast(key, val, clean=True):
else:
try:
val = int(val)
# pylint: disable=bare-except
except:
except Exception:
pass
return val

View File

@ -66,7 +66,7 @@ def write(key, value):
with salt.utils.fopen(key, 'w') as twriter:
twriter.write('{0}\n'.format(value))
return True
except: # pylint: disable=bare-except
except Exception:
return False
@ -125,13 +125,13 @@ def read(key, root=''):
return False
try:
val = int(val)
except: # pylint: disable=bare-except
except Exception:
try:
val = float(val)
except: # pylint: disable=bare-except
except Exception:
pass
return val
except: # pylint: disable=bare-except
except Exception:
return False

View File

@ -5637,7 +5637,7 @@ def set_(computer_policy=None, user_policy=None,
_newModalSetData = dictupdate.update(_existingModalData, _modal_sets[_modal_set])
log.debug('NEW MODAL SET = {0}'.format(_newModalSetData))
_ret = win32net.NetUserModalsSet(None, _modal_set, _newModalSetData)
except:
except Exception:
msg = 'An unhandled exception occurred while attempting to set policy via NetUserModalSet'
raise CommandExecutionError(msg)
if _admTemplateData:

View File

@ -29,7 +29,7 @@ import time
try:
from shlex import quote as _cmd_quote # pylint: disable=E0611
except: # pylint: disable=W0702
except Exception:
from pipes import quote as _cmd_quote
# Import salt libs

View File

@ -123,7 +123,7 @@ def start():
backlog=mod_opts.get('backlog', 128),
)
http_server.start(mod_opts['num_processes'])
except:
except Exception:
logger.error('Rest_tornado unable to bind to port {0}'.format(mod_opts['port']), exc_info=True)
raise SystemExit(1)

View File

@ -112,7 +112,7 @@ class AsyncRemotePillar(object):
load,
dictkey='pillar',
)
except:
except Exception:
log.exception('Exception getting pillar:')
raise SaltClientError('Exception getting pillar.')

View File

@ -188,8 +188,6 @@ def ext_pillar(minion_id,
except boto.exception.AWSConnectionError as exc:
log.error('%s: invalid AWS credentials, %s', __name__, exc)
return {}
except:
raise
if conn is None:
log.error('%s: Could not connect to region %s', __name__, region)

View File

@ -494,7 +494,7 @@ def save_reg(data):
try:
with salt.utils.fopen(regfile, 'a') as fh_:
msgpack.dump(data, fh_)
except:
except Exception:
log.error('Could not write to msgpack file {0}'.format(__opts__['outdir']))
raise
@ -508,6 +508,6 @@ def load_reg():
try:
with salt.utils.fopen(regfile, 'r') as fh_:
return msgpack.load(fh_)
except:
except Exception:
log.error('Could not write to msgpack file {0}'.format(__opts__['outdir']))
raise

View File

@ -328,7 +328,7 @@ def save_load(jid, load, minions=None):
cur.execute(sql, (jid, json.dumps(load)))
except MySQLdb.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try:except: we get tons of duplicate entry errors
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass

View File

@ -297,7 +297,7 @@ def save_load(jid, load, minions=None):
cur.execute(sql, (jid, psycopg2.extras.Json(load)))
except psycopg2.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try:except: we get tons of duplicate entry errors
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass

View File

@ -275,7 +275,7 @@ def save_load(jid, load, minions=None): # pylint: disable=unused-argument
json.dumps(load)))
except psycopg2.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try:except: we get tons of duplicate entry errors
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass

View File

@ -59,7 +59,7 @@ def returner(ret):
try:
with salt.utils.flopen(opts['filename'], 'a') as logfile:
logfile.write(json.dumps(ret)+'\n')
except:
except Exception:
log.error('Could not write to rawdata_json file {0}'.format(opts['filename']))
raise
@ -73,6 +73,6 @@ def event_return(event):
with salt.utils.flopen(opts['filename'], 'a') as logfile:
for e in event:
logfile.write(str(json.dumps(e))+'\n')
except:
except Exception:
log.error('Could not write to rawdata_json file {0}'.format(opts['rawfile']))
raise

View File

@ -271,7 +271,7 @@ class Loader(BaseLoader): # pylint: disable=W0232
def construct_sls_aggregate(self, node):
try:
tag, deep = self.resolve_sls_tag(node)
except:
except Exception:
raise ConstructorError('unable to build reset')
node = copy(node)
@ -288,7 +288,7 @@ class Loader(BaseLoader): # pylint: disable=W0232
def construct_sls_reset(self, node):
try:
tag, deep = self.resolve_sls_tag(node)
except:
except Exception:
raise ConstructorError('unable to build reset')
node = copy(node)

View File

@ -77,7 +77,7 @@ def cert(name,
window = None
try:
window = int(renew)
except: # pylint: disable=bare-except
except Exception:
pass
comment = 'Certificate {0} '.format(name)

View File

@ -805,7 +805,7 @@ class _Swagger(object):
method='')
self._lambda_funcname_format.format(**known_kwargs)
return True
except:
except Exception:
raise ValueError('Invalid lambda_funcname_format {0}. Please review '
'documentation for known substitutable keys'.format(self._lambda_funcname_format))

View File

@ -866,7 +866,7 @@ class SaltEvent(object):
# shutdown-- where globals start going missing
try:
self.destroy()
except: # pylint: disable=W0702
except Exception:
pass

View File

@ -368,11 +368,11 @@ class CkMinions(object):
try:
# Target is an address?
tgt = ipaddress.ip_address(tgt)
except: # pylint: disable=bare-except
except Exception:
try:
# Target is a network?
tgt = ipaddress.ip_network(tgt)
except: # pylint: disable=bare-except
except Exception:
log.error('Invalid IP/CIDR target: {0}'.format(tgt))
return []
proto = 'ipv{0}'.format(tgt.version)

View File

@ -1190,7 +1190,7 @@ def mac2eui64(mac, prefix=None):
net = ipaddress.ip_network(prefix, strict=False)
euil = int('0x{0}'.format(eui64), 16)
return '{0}/{1}'.format(net[euil], net.prefixlen)
except: # pylint: disable=bare-except
except Exception:
return

View File

@ -504,7 +504,7 @@ def render_mako_tmpl(tmplstr, context, tmplpath=None):
uri=context['sls'].replace('.', '/') if 'sls' in context else None,
lookup=lookup
).render(**context)
except:
except Exception:
raise SaltRenderError(mako.exceptions.text_error_template().render())

View File

@ -503,7 +503,7 @@ class Terminal(object):
if tty_fd >= 0:
os.close(tty_fd)
# which exception, shouldn't we catch explicitly .. ?
except: # pylint: disable=W0702
except Exception:
# Already disconnected. This happens if running inside cron
pass
@ -521,7 +521,7 @@ class Terminal(object):
'still possible to open /dev/tty.'
)
# which exception, shouldn't we catch explicitly .. ?
except: # pylint: disable=W0702
except Exception:
# Good! We are disconnected from a controlling tty.
pass

View File

@ -102,7 +102,7 @@ class UseraddModuleTestLinux(ModuleCase):
uid_info = self.run_function('user.info', [name])
self.assertIn(primary_group, uid_info['groups'])
except:
except Exception:
self.run_function('user.delete', [name])
raise