Merge pull request #2055 from s0undt3ch/develop

Source code formatting audit.
This commit is contained in:
Thomas S Hatch 2012-09-21 16:44:07 -07:00
commit 05429b870a
25 changed files with 307 additions and 221 deletions

View File

@ -266,9 +266,10 @@ class Auth(object):
else:
log.error(
'The Salt Master has cached the public key for this '
'node, this salt minion will wait for %s seconds '
'before attempting to re-authenticate',
self.opts['acceptance_wait_time']
'node, this salt minion will wait for {0} seconds '
'before attempting to re-authenticate'.format(
self.opts['acceptance_wait_time']
)
)
return 'retry'
if not self.verify_master(payload['pub_key'], payload['token']):
@ -276,8 +277,8 @@ class Auth(object):
'The Salt Master server\'s public key did not authenticate!\n'
'If you are confident that you are connecting to a valid Salt '
'Master, then remove the master public key and restart the '
'Salt Minion.\nThe master public key can be found at:\n%s',
m_pub_fn
'Salt Minion.\nThe master public key can be found '
'at:\n{0}'.format(m_pub_fn)
)
sys.exit(42)
if self.opts.get('master_finger', False):

View File

@ -96,7 +96,8 @@ class Client(object):
def get_file(self, path, dest='', makedirs=False, env='base'):
'''
Copies a file from the local files or master depending on implementation
Copies a file from the local files or master depending on
implementation
'''
raise NotImplementedError
@ -138,7 +139,11 @@ class Client(object):
'''
ret = []
path = self._check_proto(path)
log.info("Caching directory '%s' for environment '%s'" % (path, env))
log.info(
'Caching directory \'{0}\' for environment \'{1}\''.format(
path, env
)
)
for fn_ in self.file_list(env):
if fn_.startswith(path):
local = self.cache_file('salt://{0}'.format(fn_), env)
@ -162,7 +167,7 @@ class Client(object):
'files',
env
)
minion_dir = '%s/%s' % (dest,fn_)
minion_dir = '{0}/{1}'.format(dest, fn_)
if not os.path.isdir(minion_dir):
os.makedirs(minion_dir)
ret.append(minion_dir)
@ -267,16 +272,20 @@ class Client(object):
# Remove the leading directories from path to derive
# the relative path on the minion.
minion_relpath = string.lstrip(fn_[len(prefix):], '/')
ret.append(self.get_file('salt://{0}'.format(fn_),
'%s/%s' % (dest, minion_relpath),
True, env))
ret.append(
self.get_file(
'salt://{0}'.format(fn_),
'{0}/{1}'.format(dest, minion_relpath),
True, env
)
)
# Replicate empty dirs from master
for fn_ in self.file_list_emptydirs(env):
if fn_.startswith(path):
# Remove the leading directories from path to derive
# the relative path on the minion.
minion_relpath = string.lstrip(fn_[len(prefix):], '/')
minion_mkdir = '%s/%s' % (dest, minion_relpath)
minion_mkdir = '{0}/{1}'.format(dest, minion_relpath)
os.makedirs(minion_mkdir)
ret.append(minion_mkdir)
ret.sort()
@ -451,9 +460,8 @@ class LocalClient(Client):
path = self._check_proto(path)
except MinionError:
if not os.path.isfile(path):
err = ('Specified file {0} is not present to generate '
'hash').format(path)
log.warning(err)
err = 'Specified file {0} is not present to generate hash'
log.warning(err.format(path))
return ret
else:
with open(path, 'rb') as f:
@ -533,7 +541,7 @@ class RemoteClient(Client):
dest is ommited, then the downloaded file will be placed in the minion
cache
'''
log.info("Fetching file '%s'" % path)
log.info('Fetching file \'{0}\''.format(path))
path = self._check_proto(path)
load = {'path': path,
'env': env,
@ -624,9 +632,8 @@ class RemoteClient(Client):
path = self._check_proto(path)
except MinionError:
if not os.path.isfile(path):
err = ('Specified file {0} is not present to generate '
'hash').format(path)
log.warning(err)
err = 'Specified file {0} is not present to generate hash'
log.warning(err.format(path))
return {}
else:
ret = {}

View File

@ -68,9 +68,11 @@ def __write_aliases_file(lines):
if not line_comment:
line_comment = ''
if line_alias and line_target:
out.write('%s: %s%s\n' % (line_alias, line_target, line_comment))
out.write('{0}: {1}{2}\n'.format(
line_alias, line_target, line_comment
))
else:
out.write('%s\n' % line_comment)
out.write('{0}\n'.format(line_comment))
out.close()
os.rename(out.name, afn)

View File

@ -36,10 +36,12 @@ def address():
salt '*' bluetooth.address
'''
cmd = "dbus-send --system --print-reply --dest=org.bluez / org.bluez.Manager.DefaultAdapter|awk '/object path/ {print $3}' | sed 's/\"//g'"
cmd = ('dbus-send --system --print-reply --dest=org.bluez / '
'org.bluez.Manager.DefaultAdapter|awk \'/object path/ '
'{print $3}\' | sed \'s/"//g\'')
path = __salt__['cmd.run'](cmd).split('\n')
devname = path[0].split('/')
syspath = '/sys/class/bluetooth/%s/address' % devname[-1]
syspath = '/sys/class/bluetooth/{0}/address'.format(devname[-1])
sysfile = open(syspath, 'r')
address = sysfile.read().strip()
sysfile.close()
@ -84,7 +86,9 @@ def pair(address, key):
to pair with, and 1234 is the passphrase.
'''
address = address()
cmd = 'echo "%s" | bluez-simple-agent %s %s' % (address['devname'], address, key)
cmd = 'echo "{0}" | bluez-simple-agent {1} {2}'.format(
address['devname'], address, key
)
out = __salt__['cmd.run'](cmd).split('\n')
return out
@ -101,7 +105,7 @@ def unpair(address):
to unpair.
'''
address = address()
cmd = 'bluez-test-device remove %s' % address
cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).split('\n')
return out

View File

@ -246,9 +246,9 @@ def get_sum(path, form='md5'):
with open(path, 'rb') as f:
return getattr(hashlib, form)(f.read()).hexdigest()
except (IOError, OSError) as e:
return 'File Error: %s' % (str(e))
return 'File Error: {0}'.format(e)
except AttributeError as e:
return 'Hash ' + form + ' not supported'
return 'Hash {0} not supported'.format(form)
except NameError as e:
return 'Hashlib unavailable - please fix your python install'
except Exception as e:

View File

@ -4,6 +4,7 @@ Package support for FreeBSD
import os
def _check_pkgng():
'''
Looks to see if pkgng is being used by checking if database exists
@ -23,8 +24,9 @@ def search(pkg_name):
'''
if _check_pkgng():
res = __salt__['cmd.run']('pkg search {0}'.format(pkg_name))
res = [ x for x in res.split('\n') ]
return { "Results" : res }
res = [x for x in res.split('\n')]
return {"Results": res}
def __virtual__():
'''
@ -72,8 +74,8 @@ def version(name):
def refresh_db():
'''
Use pkg update to get latest repo.txz when using pkgng, else update the
ports tree with portsnap otherwise. If the ports tree does not exist it
Use pkg update to get latest repo.txz when using pkgng, else update the
ports tree with portsnap otherwise. If the ports tree does not exist it
will be downloaded and set up.
CLI Example::
@ -139,7 +141,7 @@ def install(name, refresh=False, repo='', **kwargs):
if repo:
env = (('PACKAGEROOT', repo),)
old = list_pkgs()
__salt__['cmd.retcode']('%s {0}'.format(name) % pkg_command, env=env)
__salt__['cmd.retcode']('{0} {1}'.format(pkg_command, name), env=env)
new = list_pkgs()
pkgs = {}
for npkg in new:
@ -215,7 +217,7 @@ def remove(name):
pkg_command = 'pkg delete -y'
else:
pkg_command - 'pkg_delete'
__salt__['cmd.retcode']('%s {0}'.format(name)% pkg_command)
__salt__['cmd.retcode']('{0} {1}'.format(pkg_command, name))
new = list_pkgs()
return _list_removed(old, new)
@ -232,6 +234,7 @@ def purge(name):
'''
return remove(name)
def rehash():
'''
Recomputes internal hash table for the PATH variable.
@ -242,6 +245,6 @@ def rehash():
salt '*' pkg.rehash
'''
shell = __salt__['cmd.run']('echo $SHELL').split('/')
if shell[len(shell)-1] in ["csh","tcsh"]:
shell = __salt__['cmd.run']('echo $SHELL').split('/')
if shell[len(shell)-1] in ["csh", "tcsh"]:
__salt__['cmd.run']('rehash')

View File

@ -119,7 +119,7 @@ def set_host(ip, alias):
if not ovr:
# make sure there is a newline
if lines and not lines[-1].endswith(('\n', '\r')):
lines[-1] = '%s\n' % lines[-1]
lines[-1] = '{0}\n'.format(lines[-1])
line = ip + '\t\t' + alias + '\n'
lines.append(line)
open(hfn, 'w+').writelines(lines)
@ -195,7 +195,7 @@ def add_host(ip, alias):
if not ovr:
# make sure there is a newline
if lines and not lines[-1].endswith(('\n', '\r')):
lines[-1] = '%s\n' % lines[-1]
lines[-1] = '{0}\n'.format(lines[-1])
line = ip + '\t\t' + alias + '\n'
lines.append(line)
open(hfn, 'w+').writelines(lines)

View File

@ -49,7 +49,7 @@ def detail(device='/dev/md0'):
'''
ret = {}
ret['members'] = {}
cmd = 'mdadm --detail %s' % device
cmd = 'mdadm --detail {0}'.format(device)
for line in __salt__['cmd.run_stdout'](cmd).split('\n'):
if line.startswith(device):
continue

View File

@ -37,6 +37,7 @@ except ImportError:
log = logging.getLogger(__name__)
__opts__ = {}
def __virtual__():
'''
Only load this module if the mysql config is set
@ -53,33 +54,33 @@ def __virtual__():
def __check_table(name, table):
db = connect()
cur = db.cursor(MySQLdb.cursors.DictCursor)
query = "CHECK TABLE `%s`.`%s`" % (name, table, )
log.debug("Doing query: {0}".format(query,))
cur.execute( query )
query = 'CHECK TABLE `{0}`.`{1}`'.format(name, table)
log.debug('Doing query: {0}'.format(query))
cur.execute(query)
results = cur.fetchall()
log.debug( results )
log.debug(results)
return results
def __repair_table(name, table):
db = connect()
cur = db.cursor(MySQLdb.cursors.DictCursor)
query = "REPAIR TABLE `%s`.`%s`" % (name, table, )
log.debug("Doing query: {0}".format(query,))
cur.execute( query )
query = 'REPAIR TABLE `{0}`.`{1}`'.format(name, table)
log.debug('Doing query: {0}'.format(query))
cur.execute(query)
results = cur.fetchall()
log.debug( results )
log.debug(results)
return results
def __optimize_table(name, table):
db = connect()
cur = db.cursor(MySQLdb.cursors.DictCursor)
query = "OPTIMIZE TABLE `%s`.`%s`" % (name, table, )
log.debug("Doing query: {0}".format(query,))
cur.execute( query )
query = 'OPTIMIZE TABLE `{0}`.`{1}`'.format(name, table)
log.debug('Doing query: {0}'.format(query))
cur.execute(query)
results = cur.fetchall()
log.debug( results )
log.debug(results)
return results
@ -88,6 +89,7 @@ def connect(**kwargs):
wrap authentication credentials here
'''
connargs = dict()
def _connarg(name, key=None):
'''
Add key to connargs, only if name exists in our
@ -189,7 +191,7 @@ def status():
db = connect()
cur = db.cursor()
cur.execute('SHOW STATUS')
for i in range( cur.rowcount ):
for i in range(cur.rowcount):
row = cur.fetchone()
ret[row[0]] = row[1]
return ret
@ -224,7 +226,7 @@ def slave_lag():
'''
db = connect()
cur = db.cursor(MySQLdb.cursors.DictCursor)
cur.execute("show slave status")
cur.execute('show slave status')
results = cur.fetchone()
if cur.rowcount == 0:
# Server is not a slave if master is not defined. Return empty tuple
@ -312,14 +314,14 @@ def db_tables(name):
ret = []
db = connect()
cur = db.cursor()
query = "SHOW TABLES IN %s" % name
log.debug("Doing query: {0}".format(query,))
query = 'SHOW TABLES IN {0}'.format(name)
log.debug('Doing query: {0}'.format(query))
cur.execute( query )
cur.execute(query)
results = cur.fetchall()
for table in results:
ret.append(table[0])
log.debug( ret )
log.debug(ret)
return ret
@ -333,9 +335,9 @@ def db_exists(name):
'''
db = connect()
cur = db.cursor()
query = "SHOW DATABASES LIKE '%s'" % name
log.debug("Doing query: {0}".format(query,))
cur.execute( query )
query = 'SHOW DATABASES LIKE \'{0}\''.format(name)
log.debug('Doing query: {0}'.format(query))
cur.execute(query)
cur.fetchall()
return cur.rowcount == 1
@ -349,17 +351,17 @@ def db_create(name):
salt '*' mysql.db_create 'dbname'
'''
# check if db exists
if db_exists( name ):
log.info("DB '{0}' already exists".format(name,))
if db_exists(name):
log.info('DB \'{0}\' already exists'.format(name))
return False
# db doesnt exist, proceed
db = connect()
cur = db.cursor()
query = "CREATE DATABASE `%s`;" % name
log.debug("Query: {0}".format(query,))
if cur.execute( query ):
log.info("DB '{0}' created".format(name,))
query = 'CREATE DATABASE `{0}`;'.format(name)
log.debug('Query: {0}'.format(query))
if cur.execute(query):
log.info('DB \'{0}\' created'.format(name))
return True
return False
@ -373,26 +375,26 @@ def db_remove(name):
salt '*' mysql.db_remove 'dbname'
'''
# check if db exists
if not db_exists( name ):
log.info("DB '{0}' does not exist".format(name,))
if not db_exists(name):
log.info('DB \'{0}\' does not exist'.format(name))
return False
if name in ('mysql', 'information_scheme'):
log.info("DB '{0}' may not be removed".format(name,))
log.info('DB \'{0}\' may not be removed'.format(name))
return False
# db doesnt exist, proceed
db = connect()
cur = db.cursor()
query = "DROP DATABASE `%s`;" % name
log.debug("Doing query: {0}".format(query,))
cur.execute( query )
query = 'DROP DATABASE `{0}`;'.format(name)
log.debug('Doing query: {0}'.format(query))
cur.execute(query)
if not db_exists( name ):
log.info("Database '{0}' has been removed".format(name,))
if not db_exists(name):
log.info('Database \'{0}\' has been removed'.format(name))
return True
log.info("Database '{0}' has not been removed".format(name,))
log.info('Database \'{0}\' has not been removed'.format(name))
return False
@ -409,7 +411,7 @@ def user_list():
cur = db.cursor(MySQLdb.cursors.DictCursor)
cur.execute('SELECT User,Host FROM mysql.user')
results = cur.fetchall()
log.debug( results )
log.debug(results)
return results
@ -423,9 +425,10 @@ def user_exists(user, host='localhost'):
'''
db = connect()
cur = db.cursor()
query = "SELECT User,Host FROM mysql.user WHERE User = '%s' AND Host = '%s'" % (user, host,)
log.debug("Doing query: {0}".format(query,))
cur.execute( query )
query = ('SELECT User,Host FROM mysql.user WHERE User = \'{0}\' AND '
'Host = \'{0}\''.format(user, host))
log.debug('Doing query: {0}'.format(query))
cur.execute(query)
return cur.rowcount == 1
@ -438,12 +441,13 @@ def user_info(user, host='localhost'):
salt '*' mysql.user_info root localhost
'''
db = connect()
cur = db.cursor (MySQLdb.cursors.DictCursor)
query = "SELECT * FROM mysql.user WHERE User = '%s' AND Host = '%s'" % (user, host,)
log.debug("Query: {0}".format(query,))
cur.execute( query )
cur = db.cursor(MySQLdb.cursors.DictCursor)
query = ('SELECT * FROM mysql.user WHERE User = \'{0}\' AND '
'Host = \'{1}\''.format(user, host))
log.debug('Query: {0}'.format(query))
cur.execute(query)
result = cur.fetchone()
log.debug( result )
log.debug(result)
return result
@ -460,26 +464,26 @@ def user_create(user,
salt '*' mysql.user_create 'username' 'hostname' password_hash='hash'
'''
if user_exists(user,host):
log.info("User '{0}'@'{1}' already exists".format(user,host,))
return False
if user_exists(user, host):
log.info('User \'{0}\'@\'{1}\' already exists'.format(user, host))
return False
db = connect()
cur = db.cursor ()
query = "CREATE USER '%s'@'%s'" % (user, host,)
cur = db.cursor()
query = 'CREATE USER \'{0}\'@\'{1}\''.format(user, host)
if password is not None:
query = query + " IDENTIFIED BY '%s'" % password
query = query + ' IDENTIFIED BY \'{0}\''.format(password)
elif password_hash is not None:
query = query + " IDENTIFIED BY PASSWORD '%s'" % password_hash
query = query + ' IDENTIFIED BY PASSWORD \'{0}\''.format(password_hash)
log.debug("Query: {0}".format(query,))
cur.execute( query )
log.debug('Query: {0}'.format(query))
cur.execute(query)
if user_exists(user, host):
log.info("User '{0}'@'{1}' has been created".format(user,host,))
log.info('User \'{0}\'@\'{1}\' has been created'.format(user, host))
return True
log.info("User '{0}'@'{1}' is not created".format(user,host,))
log.info('User \'{0}\'@\'{1}\' is not created'.format(user, host))
return False
@ -500,20 +504,27 @@ def user_chpass(user,
log.error('No password provided')
return False
elif password is not None:
password_sql = "PASSWORD(\"%s\")" % password
password_sql = 'PASSWORD("{0}")'.format(password)
elif password_hash is not None:
password_sql = "\"%s\"" % password_hash
password_sql = '"{0}"'.format(password_hash)
db = connect()
cur = db.cursor()
query = "UPDATE mysql.user SET password=%s WHERE User='%s' AND Host = '%s';" % (password_sql, user, host,)
log.debug("Query: {0}".format(query,))
query = ('UPDATE mysql.user SET password={0} WHERE User=\'{1}\' AND '
'Host = \'{2}\';'.format(password_sql, user, host))
log.debug('Query: {0}'.format(query))
if cur.execute(query):
cur.execute('FLUSH PRIVILEGES;')
log.info("Password for user '{0}'@'{1}' has been changed".format(user, host,))
log.info(
'Password for user \'{0}\'@\'{1}\' has been changed'.format(
user, host
)
)
return True
log.info("Password for user '{0}'@'{1}' is not changed".format(user, host,))
log.info(
'Password for user \'{0}\'@\'{1}\' is not changed'.format(user, host)
)
return False
@ -527,21 +538,21 @@ def user_remove(user,
salt '*' mysql.user_remove frank localhost
'''
db = connect()
cur = db.cursor ()
query = "DROP USER '%s'@'%s'" % (user, host,)
log.debug("Query: {0}".format(query,))
cur.execute( query )
cur = db.cursor()
query = 'DROP USER \'{0}\'@\'{1}\''.format(user, host)
log.debug('Query: {0}'.format(query))
cur.execute(query)
if not user_exists(user, host):
log.info("User '{0}'@'{1}' has been removed".format(user,host,))
log.info('User \'{0}\'@\'{1}\' has been removed'.format(user, host))
return True
log.info("User '{0}'@'{1}' has NOT been removed".format(user,host,))
log.info('User \'{0}\'@\'{1}\' has NOT been removed'.format(user, host))
return False
# Maintenance
def db_check(name,
table=None):
table=None):
'''
Repairs the full database or just a given table
@ -552,12 +563,14 @@ def db_check(name,
ret = []
if table is None:
# we need to check all tables
tables = db_tables( name )
tables = db_tables(name)
for table in tables:
log.info("Checking table '%s' in db '%s..'".format(name,table,))
ret.append( __check_table(name, table))
log.info(
'Checking table \'{0}\' in db \'{1}..\''.format(name, table)
)
ret.append(__check_table(name, table))
else:
log.info("Checking table '%s' in db '%s'..".format(name,table,))
log.info('Checking table \'{0}\' in db \'{1}\'..'.format(name, table))
ret = __check_table(name, table)
return ret
@ -574,12 +587,14 @@ def db_repair(name,
ret = []
if table is None:
# we need to repair all tables
tables = db_tables( name )
tables = db_tables(name)
for table in tables:
log.info("Repairing table '%s' in db '%s..'".format(name,table,))
ret.append( __repair_table(name, table))
log.info(
'Repairing table \'{0}\' in db \'{1}..\''.format(name, table)
)
ret.append(__repair_table(name, table))
else:
log.info("Repairing table '%s' in db '%s'..".format(name,table,))
log.info('Repairing table \'{0}\' in db \'{1}\'..'.format(name, table))
ret = __repair_table(name, table)
return ret
@ -598,10 +613,14 @@ def db_optimize(name,
# we need to optimize all tables
tables = db_tables(name)
for table in tables:
log.info("Optimizing table '%s' in db '%s..'".format(name,table,))
ret.append( __optimize_table(name, table))
log.info(
'Optimizing table \'{0}\' in db \'{1}..\''.format(name, table)
)
ret.append(__optimize_table(name, table))
else:
log.info("Optimizing table '%s' in db '%s'..".format(name,table,))
log.info(
'Optimizing table \'{0}\' in db \'{1}\'..'.format(name, table)
)
ret = __optimize_table(name, table)
return ret
@ -613,9 +632,10 @@ def __grant_generate(grant,
host='localhost',
grant_option=False,
escape=True):
# todo: Re-order the grant so it is according to the SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
# TODO: Re-order the grant so it is according to the
# SHOW GRANTS for xxx@yyy query (SELECT comes first, etc)
grant = re.sub(r'\s*,\s*', ', ', grant).upper()
# MySQL normalizes ALL to ALL PRIVILEGES, we do the same so that
# grant_exists and grant_add ALL work correctly
if grant == 'ALL':
@ -627,13 +647,15 @@ def __grant_generate(grant,
if escape:
if db is not '*':
db = "`%s`" % db
db = '`{0}`'.format(db)
if table is not '*':
table = "`%s`" % table
query = "GRANT %s ON %s.%s TO '%s'@'%s'" % (grant, db, table, user, host,)
table = '`{0}`'.format(table)
query = 'GRANT {0} ON {1}.{2} TO \'{3}\'@\'{4}\''.format(
grant, db, table, user, host
)
if grant_option:
query += " WITH GRANT OPTION"
log.debug("Query generated: {0}".format(query,))
query += ' WITH GRANT OPTION'
log.debug('Query generated: {0}'.format(query))
return query
@ -646,17 +668,17 @@ def user_grants(user,
salt '*' mysql.user_grants 'frank' 'localhost'
'''
if not user_exists(user,host):
log.info("User '{0}'@'{1}' does not exist".format(user,host,))
return False
if not user_exists(user, host):
log.info('User \'{0}\'@\'{1}\' does not exist'.format(user, host))
return False
ret = []
db = connect()
cur = db.cursor()
query = "SHOW GRANTS FOR '%s'@'%s'" % (user,host,)
log.debug("Doing query: {0}".format(query,))
query = 'SHOW GRANTS FOR \'{0}\'@\'{1}\''.format(user, host)
log.debug('Doing query: {0}'.format(query))
cur.execute( query )
cur.execute(query)
results = cur.fetchall()
for grant in results:
ret.append(grant[0].split(' IDENTIFIED BY')[0])
@ -670,16 +692,19 @@ def grant_exists(grant,
host='localhost',
grant_option=False,
escape=True):
# todo: This function is a bit tricky, since it requires the ordering to be exactly the same.
# perhaps should be replaced/reworked with a better/cleaner solution.
target = __grant_generate(grant, database, user, host, grant_option, escape)
# TODO: This function is a bit tricky, since it requires the ordering to
# be exactly the same. Perhaps should be replaced/reworked with a
# better/cleaner solution.
target = __grant_generate(
grant, database, user, host, grant_option, escape
)
grants = user_grants(user, host)
if grants is not False and target in grants:
log.debug("Grant exists.")
log.debug('Grant exists.')
return True
log.debug("Grant does not exist, or is perhaps not ordered properly?")
log.debug('Grant does not exist, or is perhaps not ordered properly?')
return False
@ -693,7 +718,7 @@ def grant_add(grant,
Adds a grant to the MySQL server.
For database, make sure you specify database.table or database.*
CLI Example::
salt '*' mysql.grant_add 'SELECT,INSERT,UPDATE,...' 'database.*' 'frank' 'localhost'
@ -703,13 +728,21 @@ def grant_add(grant,
cur = db.cursor()
query = __grant_generate(grant, database, user, host, grant_option, escape)
log.debug("Query: {0}".format(query,))
cur.execute( query )
log.debug('Query: {0}'.format(query))
cur.execute(query)
if grant_exists(grant, database, user, host, grant_option, escape):
log.info("Grant '{0}' on '{1}' for user '{2}' has been added".format(grant,database,user,))
log.info(
'Grant \'{0}\' on \'{1}\' for user \'{2}\' has been added'.format(
grant,database, user
)
)
return True
log.info("Grant '{0}' on '{1}' for user '{2}' has NOT been added".format(grant,database,user,))
log.info(
'Grant \'{0}\' on \'{1}\' for user \'{2}\' has NOT been added'.format(
grant,database, user
)
)
return False
@ -731,13 +764,21 @@ def grant_revoke(grant,
cur = db.cursor()
if grant_option:
grant += ", GRANT OPTION"
query = "REVOKE %s ON %s FROM '%s'@'%s';" % (grant, database, user, host,)
log.debug("Query: {0}".format(query,))
cur.execute( query )
grant += ', GRANT OPTION'
query = 'REVOKE {0} ON {1} FROM \'{2}\'@\'{3}\';'.format(
grant, database, user, host
)
log.debug('Query: {0}'.format(query))
cur.execute(query)
if not grant_exists(grant, database, user, host, grant_option, escape):
log.info("Grant '{0}' on '{1}' for user '{2}' has been revoked".format(grant,database,user,))
log.info(
'Grant \'{0}\' on \'{1}\' for user \'{2}\' has been '
'revoked'.format(grant, database, user)
)
return True
log.info("Grant '{0}' on '{1}' for user '{2}' has NOT been revoked".format(grant,database,user,))
log.info(
'Grant \'{0}\' on \'{1}\' for user \'{2}\' has NOT been '
'revoked'.format(grant, database, user)
)
return False

View File

@ -41,7 +41,7 @@ def _cidr_to_ipv4_netmask(cidr_bits):
netmask += '255'
cidr_bits -= 8
else:
netmask += '%d' % (256-(2**(8-cidr_bits)))
netmask += '{0:d}'.format(256-(2**(8-cidr_bits)))
cidr_bits = 0
return netmask
@ -106,7 +106,7 @@ def _interfaces_ip(out):
continue
m = re.match('^\d*:\s+([\w.]+)(?:@)?(\w+)?:\s+<(.+)>', line)
if m:
iface,parent,attrs = m.groups()
iface, parent, attrs = m.groups()
if 'UP' in attrs.split(','):
data['up'] = True
else:
@ -117,7 +117,7 @@ def _interfaces_ip(out):
cols = line.split()
if len(cols) >= 2:
type,value = tuple(cols[0:2])
type, value = tuple(cols[0:2])
if type in ('inet', 'inet6'):
if 'secondary' not in cols:
ipaddr, netmask, broadcast = parse_network(value, cols)
@ -232,11 +232,11 @@ def interfaces():
return ifaces
def _get_net_start(ipaddr,netmask):
def _get_net_start(ipaddr, netmask):
ipaddr_octets = ipaddr.split('.')
netmask_octets = netmask.split('.')
net_start_octets = [str(int(ipaddr_octets[x]) & int(netmask_octets[x]))
for x in range(0,4)]
for x in range(0, 4)]
return '.'.join(net_start_octets)
@ -247,8 +247,8 @@ def _get_net_size(mask):
return len(binary_str.rstrip('0'))
def _calculate_subnet(ipaddr,netmask):
return '{0}/{1}'.format(_get_net_start(ipaddr,netmask),
def _calculate_subnet(ipaddr, netmask):
return '{0}/{1}'.format(_get_net_start(ipaddr, netmask),
_get_net_size(netmask))
@ -257,7 +257,7 @@ def _ipv4_to_bits(ipaddr):
Accepts an IPv4 dotted quad and returns a string representing its binary
counterpart
'''
return ''.join([bin(int(x))[2:].rjust(8,'0') for x in ipaddr.split('.')])
return ''.join([bin(int(x))[2:].rjust(8, '0') for x in ipaddr.split('.')])
def subnets():
@ -268,9 +268,9 @@ def subnets():
subnets = []
for ipv4_info in ifaces.values():
for ipv4 in ipv4_info.get('inet',[]):
for ipv4 in ipv4_info.get('inet', []):
if ipv4['address'] == '127.0.0.1': continue
network = _calculate_subnet(ipv4['address'],ipv4['netmask'])
network = _calculate_subnet(ipv4['address'], ipv4['netmask'])
subnets.append(network)
return subnets
@ -280,7 +280,7 @@ def in_subnet(cidr):
Returns True if host is within specified subnet, otherwise False
'''
try:
netstart,netsize = cidr.split('/')
netstart, netsize = cidr.split('/')
netsize = int(netsize)
except:
log.error('Invalid CIDR \'{0}\''.format(cidr))
@ -292,12 +292,12 @@ def in_subnet(cidr):
if netsize < 32 and len(netstart_bin.rstrip('0')) > netsize:
log.error('Invalid network starting IP \'{0}\' in CIDR '
'\'{1}\''.format(netstart,cidr))
'\'{1}\''.format(netstart, cidr))
return False
netstart_leftbits = netstart_bin[0:netsize]
for ipv4_info in ifaces.values():
for ipv4 in ipv4_info.get('inet',[]):
for ipv4 in ipv4_info.get('inet', []):
if ipv4['address'] == '127.0.0.1': continue
if netsize == 32:
if netstart == ipv4['address']: return True
@ -316,7 +316,7 @@ def ping(host):
salt '*' network.ping archlinux.org
'''
cmd = 'ping -c 4 %s' % _sanitize_host(host)
cmd = 'ping -c 4 {0}'.format(_sanitize_host(host))
return __salt__['cmd.run'](cmd)
@ -369,7 +369,7 @@ def traceroute(host):
salt '*' network.traceroute archlinux.org
'''
ret = []
cmd = 'traceroute %s' % _sanitize_host(host)
cmd = 'traceroute {0}'.format(_sanitize_host(host))
out = __salt__['cmd.run'](cmd)
for line in out:
@ -400,7 +400,5 @@ def dig(host):
salt '*' network.dig archlinux.org
'''
cmd = 'dig %s' % _sanitize_host(host)
cmd = 'dig {0}'.format(_sanitize_host(host))
return __salt__['cmd.run'](cmd)

View File

@ -72,7 +72,7 @@ def _format_pkgs(split):
pkg = {}
for k, v in split.items():
if v[2]:
name = '%s--%s' % (v[0], v[2])
name = '{0}--{1}'.format(v[0], v[2])
else:
name = v[0]
pkg[name] = v[1]

View File

@ -176,7 +176,7 @@ def install(pkgs=None,
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError("'%s' is not writeable" % log)
raise IOError('\'{0}\' is not writeable'.format(log))
cmd = '{cmd} --log {log} '.format(
cmd=cmd, log=log)
@ -188,7 +188,9 @@ def install(pkgs=None,
try:
int(timeout)
except ValueError:
raise ValueError("'%s' is not a valid integer base 10.")
raise ValueError(
'\'{0}\' is not a valid integer base 10.'.format(timeout)
)
cmd = '{cmd} --timeout={timeout} '.format(
cmd=cmd, timeout=timeout)
@ -200,19 +202,21 @@ def install(pkgs=None,
if find_links:
if not find_links.startswith("http://"):
raise Exception("'%s' must be a valid url" % find_links)
raise Exception('\'{0}\' must be a valid url'.format(find_links))
cmd = '{cmd} --find-links={find_links}'.format(
cmd=cmd, find_links=find_links)
if index_url:
if not index_url.startswith("http://"):
raise Exception("'%s' must be a valid url" % index_url)
raise Exception('\'{0}\' must be a valid url'.format(index_url))
cmd = '{cmd} --index-url="{index_url}" '.format(
cmd=cmd, index_url=index_url)
if extra_index_url:
if not extra_index_url.startswith("http://"):
raise Exception("'%s' must be a valid url" % extra_index_url)
raise Exception(
'\'{0}\' must be a valid url'.format(extra_index_url)
)
cmd = '{cmd} --extra-index_url="{extra_index_url}" '.format(
cmd=cmd, extra_index_url=extra_index_url)
@ -221,7 +225,7 @@ def install(pkgs=None,
if mirrors:
if not mirrors.startswith("http://"):
raise Exception("'%s' must be a valid url" % mirrors)
raise Exception('\'{0}\' must be a valid url'.format(mirrors))
cmd = '{cmd} --use-mirrors --mirrors={mirrors} '.format(
cmd=cmd, mirrors=mirrors)
@ -351,7 +355,7 @@ def uninstall(pkgs=None,
# TODO make this check if writeable
os.path.exists(log)
except IOError:
raise IOError("'%s' is not writeable" % log)
raise IOError('\'{0}\' is not writeable'.format(log))
cmd = '{cmd} --{log} '.format(
cmd=cmd, log=log)
@ -363,7 +367,9 @@ def uninstall(pkgs=None,
try:
int(timeout)
except ValueError:
raise ValueError("'%s' is not a valid integer base 10.")
raise ValueError(
'\'{0}\' is not a valid integer base 10.'.format(timeout)
)
cmd = '{cmd} --timeout={timeout} '.format(
cmd=cmd, timeout=timeout)
@ -430,14 +436,14 @@ def list(prefix='',
if line.startswith('-e'):
line = line.split('-e ')[1]
line, name = line.split('#egg=')
packages[name]=line
packages[name] = line
elif len(line.split("==")) >= 2:
name = line.split("==")[0]
version = line.split("==")[1]
if prefix:
if line.lower().startswith(prefix.lower()):
packages[name]=version
packages[name] = version
else:
packages[name]=version
packages[name] = version
return packages

View File

@ -46,7 +46,7 @@ def version():
version_line = __salt__['cmd.run']('psql --version').split("\n")[0]
name = version_line.split(" ")[1]
ver = version_line.split(" ")[2]
return "%s %s" % (name, ver)
return '{0} {1}'.format(name, ver)
def _connection_defaults(user=None, host=None, port=None):
'''

View File

@ -44,12 +44,12 @@ def _sync(form, env=None):
source = os.path.join('salt://_{0}'.format(form))
mod_dir = os.path.join(__opts__['extension_modules'], '{0}'.format(form))
if not os.path.isdir(mod_dir):
log.info("Creating module dir '%s'" % mod_dir)
log.info('Creating module dir \'{0}\''.format(mod_dir))
os.makedirs(mod_dir)
for sub_env in env:
log.info("Syncing %s for environment '%s'" % (form, sub_env))
log.info('Syncing {0} for environment \'{1}\''.format(form, sub_env))
cache = []
log.info('Loading cache from %s,for %s)' % (source, sub_env))
log.info('Loading cache from {0},for {1})'.format(source, sub_env))
cache.extend(__salt__['cp.cache_dir'](source, sub_env))
local_cache_dir=os.path.join(
__opts__['cachedir'],
@ -57,13 +57,13 @@ def _sync(form, env=None):
sub_env,
'_{0}'.format(form)
)
log.debug("Local cache dir: '%s'" % local_cache_dir)
log.debug('Local cache dir: \'{0}\''.format(local_cache_dir))
for fn_ in cache:
relpath = os.path.relpath(fn_, local_cache_dir)
relname = os.path.splitext(relpath)[0].replace(os.sep, '.')
remote.add(relpath)
dest = os.path.join(mod_dir, relpath)
log.info("Copying '%s' to '%s'" % (fn_, dest))
log.info('Copying \'{0}\' to \'{1}\''.format(fn_, dest))
if os.path.isfile(dest):
# The file is present, if the sum differs replace it
srch = hashlib.md5(open(fn_, 'r').read()).hexdigest()
@ -154,7 +154,7 @@ def update(version=None):
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
return {'comment': "Updated from %s to %s" % (oldversion, version),
return {'comment': 'Updated from {0} to {1}'.format(oldversion, version),
'restarted': restarted}
def sync_modules(env=None):

View File

@ -86,7 +86,7 @@ def custom():
keys = opt.split('.')
if keys[0] != 'status':
continue
func = '%s()' % keys[1]
func = '{0}()'.format(keys[1])
vals = eval(func)
for item in __opts__[opt]:

View File

@ -69,5 +69,7 @@ def signal(signal=None):
if not valid_signals[signal]:
return
cmd = __catalina_home() + '/bin/catalina.sh %s' % valid_signals[signal]
cmd = '{0}/bin/catalina.sh {1}'.format(
__catalina_home, valid_signals[signal]
)
__salt__['cmd.run'](cmd)

View File

@ -230,9 +230,9 @@ def get_sum(path, form='md5'):
try:
return getattr(hashlib, form)(open(path, 'rb').read()).hexdigest()
except (IOError, OSError) as e:
return 'File Error: %s' % (str(e))
return 'File Error: {0}'.format(e)
except AttributeError as e:
return 'Hash ' + form + ' not supported'
return 'Hash {0} not supported'.format(form)
except NameError as e:
return 'Hashlib unavailable - please fix your python install'
except Exception as e:
@ -242,7 +242,7 @@ def get_sum(path, form='md5'):
def find(path, **kwargs):
'''
Approximate the Unix find(1) command and return a list of paths that
meet the specified critera.
meet the specified criteria.
The options include match criteria::

View File

@ -13,6 +13,7 @@ __outputter__ = {
'netstat': 'txt',
}
def __virtual__():
'''
Only works on Windows systems
@ -40,7 +41,7 @@ def ping(host):
salt '*' network.ping archlinux.org
'''
cmd = 'ping -n 4 %s' % _sanitize_host(host)
cmd = 'ping -n 4 {0}'.format(_sanitize_host(host))
return __salt__['cmd.run'](cmd)
@ -81,7 +82,7 @@ def traceroute(host):
salt '*' network.traceroute archlinux.org
'''
ret = []
cmd = 'tracert %s' % _sanitize_host(host)
cmd = 'tracert {0}'.format(_sanitize_host(host))
lines = __salt__['cmd.run'](cmd).split('\n')
for line in lines:
if not ' ' in line:
@ -133,7 +134,7 @@ def nslookup(host):
salt '*' network.nslookup archlinux.org
'''
ret = []
cmd = 'nslookup %s' % _sanitize_host(host)
cmd = 'nslookup {0}'.format(_sanitize_host(host))
lines = __salt__['cmd.run'](cmd).split('\n')
for line in lines:
if line.startswith('Non-authoritative'):
@ -154,7 +155,7 @@ def dig(host):
salt '*' network.dig archlinux.org
'''
cmd = 'dig %s' % _sanitize_host(host)
cmd = 'dig {0}'.format(_sanitize_host(host))
return __salt__['cmd.run'](cmd)
@ -204,7 +205,7 @@ def _interfaces_ipconfig(out):
iface['inet'] = list()
addr = {'address': val.rstrip('(Preferred)'),
'netmask': None,
'broadcast': None} # TODO find the broadcast
'broadcast': None} # TODO find the broadcast
iface['inet'].append(addr)
elif 'IPv6 Address' in key:
if 'inet6' not in iface:

View File

@ -53,7 +53,7 @@ def returner(ret):
'id': ret['id']}
if isinstance(ret['return'], dict):
for key, value in ret['return'].items():
columns['return.%s' % (key,)] = str(value)
columns['return.{0}'.format(key)] = str(value)
else:
columns['return'] = str(ret['return'])

View File

@ -1711,7 +1711,7 @@ def uncomment(name, regex, char='#', backup='.bak'):
ret['comment'] = 'File {0} is set to be updated'.format(name)
ret['result'] = None
return ret
with open(name, 'rb') as fp_:
slines = fp_.readlines()
@ -1818,8 +1818,11 @@ def append(name, text=None, makedirs=False, source=None, source_hash=None):
try:
lines = chunk.split('\n')
except AttributeError:
logger.debug('Error appending text to %s; given object is: %s',
name, type(chunk))
logger.debug(
'Error appending text to {0}; given object is: {1}'.format(
name, type(chunk)
)
)
return _error(ret, 'Given text is not a string')
for line in lines:

View File

@ -11,7 +11,7 @@ import random
can_rename_open_file = False
if os.name == 'nt': # pragma: no cover
if os.name == 'nt': # pragma: no cover
_rename = lambda src, dst: False
_rename_atomic = lambda src, dst: False
@ -79,7 +79,7 @@ if os.name == 'nt': # pragma: no cover
except OSError, e:
if e.errno != errno.EEXIST:
raise
old = "%s-%08x" % (dst, random.randint(0, sys.maxint))
old = '{0}-{1:08x}'.format(dst, random.randint(0, sys.maxint))
os.rename(dst, old)
os.rename(src, dst)
try:
@ -123,7 +123,7 @@ class _AtomicWFile(object):
pass
def __repr__(self):
return '<%s %s%r, mode %r>' % (
return '<{0} {1}{2}, mode {3}>'.format(
self.__class__.__name__,
self._f.closed and 'closed ' or '',
self._filename,

View File

@ -63,7 +63,7 @@ class BufferedReader(object):
multiplier = 1
self.__buffered = self.__buffered[self.__chunk_size:]
data = self.__file.read(self.__chunk_size*multiplier)
data = self.__file.read(self.__chunk_size * multiplier)
if not data:
self.__file.close()
@ -72,7 +72,6 @@ class BufferedReader(object):
self.__buffered += data
return self.__buffered
# Support with statements
def __enter__(self):
return self
@ -90,11 +89,11 @@ if __name__ == '__main__':
return
def sizeof_fmt(num):
for x in ['bytes','KB','MB','GB']:
for x in ['bytes', 'KB', 'MB', 'GB']:
if num < 1024.0:
return "%3.1f%s" % (num, x)
return '{0:3.1f}{1}'.format(num, x)
num /= 1024.0
return "%3.1f%s" % (num, 'TB')
return '{0:3.1f}{1}'.format(num, 'TB')
import os, timeit
fpath = os.path.normpath(os.path.join(
@ -114,13 +113,22 @@ if __name__ == '__main__':
TNUMBER = 1000
print "Running tests against a file with the size of %s" % sizeof_fmt(os.stat(tpath).st_size)
print('Running tests against a file with the size of {0}'.format(
sizeof_fmt(os.stat(tpath).st_size))
)
for idx, multiplier in enumerate([4, 8, 16, 32, 64, 128, 256]):
chunk_size = multiplier * 1024
max_size = chunk_size * 5
t = timeit.Timer("timeit_string('%s', %d, %d)" % (tpath, max_size, chunk_size), "from __main__ import timeit_string")
print "timeit_string ({0: >7} chunks; max: {1: >7}):".format(sizeof_fmt(chunk_size), sizeof_fmt(max_size)),
print u"{0: >6} \u00B5sec/pass".format(u"%.2f" % (TNUMBER * t.timeit(number=TNUMBER)/TNUMBER))
t = timeit.Timer(
"timeit_string('{0}', {1:d}, {2:d})".format(
tpath, max_size, chunk_size
), "from __main__ import timeit_string"
)
print("timeit_string ({0: >7} chunks; max: {1: >7}):".format(
sizeof_fmt(chunk_size), sizeof_fmt(max_size))),
print(u"{0: >6} \u00B5sec/pass".format(u"{0:0.2f}".format(
TNUMBER * t.timeit(number=TNUMBER) / TNUMBER
)))
print

View File

@ -47,7 +47,7 @@ class SaltCacheLoader(BaseLoader):
self.env = env
self.encoding = encoding
self.searchpath = path.join(opts['cachedir'], 'files', env)
log.debug("Jinja search path: '%s'" % self.searchpath)
log.debug('Jinja search path: \'{0}\''.format(self.searchpath))
self._file_client = None
self.cached = []
@ -77,8 +77,10 @@ class SaltCacheLoader(BaseLoader):
def get_source(self, environment, template):
# checks for relative '..' paths
if '..' in template:
log.warning("Discarded template path '%s', relative paths are"
"prohibited" % template)
log.warning(
'Discarded template path \'{0}\', relative paths are '
'prohibited'.format(template)
)
raise TemplateNotFound(template)
self.check_cache(template)
filepath = path.join(self.searchpath, template)

View File

@ -103,7 +103,9 @@ class OptionParser(optparse.OptionParser):
# Gather and run the process_<option> functions in the proper order
process_option_funcs = []
for option_key in options.__dict__.keys():
process_option_func = getattr(self, 'process_%s' % option_key, None)
process_option_func = getattr(
self, 'process_{0}'.format(option_key), None
)
if process_option_func is not None:
process_option_funcs.append(process_option_func)
@ -121,7 +123,9 @@ class OptionParser(optparse.OptionParser):
if self.config.get('conf_file', None) is not None:
logging.getLogger(__name__).info(
'Loaded configuration file: %s', self.config['conf_file']
'Loaded configuration file: {0}'.format(
self.config['conf_file']
)
)
# Retain the standard behaviour of optparse to return options and args
return options, args
@ -433,7 +437,7 @@ class TargetOptionsMixIn(object):
if getattr(self.options, opt.dest):
self.selected_target_option = opt.dest
funcname = 'process_%s' % option.dest
funcname = 'process_{0}'.format(option.dest)
if not hasattr(self, funcname):
setattr(self, funcname, partial(process, option))
@ -493,8 +497,12 @@ class TimeoutMixIn(object):
def _mixin_setup(self):
if not hasattr(self, 'default_timeout'):
raise RuntimeError("You need to define the 'default_timeout' "
"attribute on %s" % self.__class__.__name__)
raise RuntimeError(
'You need to define the \'default_timeout\' attribute '
'on {0}'.format(
self.__class__.__name__
)
)
self.add_option(
'-t', '--timeout',
type=int,
@ -557,7 +565,7 @@ class OutputOptionsMixIn(object):
if getattr(self.options, opt.dest):
self.selected_output_option = opt.dest
funcname = 'process_%s' % option.dest
funcname = 'process_{0}'.format(option.dest)
if not hasattr(self, funcname):
setattr(self, funcname, partial(process, option))

View File

@ -37,7 +37,7 @@ class Service(win32serviceutil.ServiceFramework):
win32event.INFINITE)
self.log('done')
except Exception as x:
self.log('Exception : %s' % x)
self.log('Exception: {0}'.format(x))
self.SvcStop()
def SvcStop(self):
@ -74,7 +74,7 @@ def instart(cls, name, display_name=None, stay_alive=True):
from sys import executable
module_path = executable
module_file = splitext(abspath(module_path))[0]
cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)
cls._svc_reg_class_ = '{0}.{1}'.format(module_file, cls.__name__)
if stay_alive:
win32api.SetConsoleCtrlHandler(lambda x: True, True)
try: