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: else:
log.error( log.error(
'The Salt Master has cached the public key for this ' 'The Salt Master has cached the public key for this '
'node, this salt minion will wait for %s seconds ' 'node, this salt minion will wait for {0} seconds '
'before attempting to re-authenticate', 'before attempting to re-authenticate'.format(
self.opts['acceptance_wait_time'] self.opts['acceptance_wait_time']
)
) )
return 'retry' return 'retry'
if not self.verify_master(payload['pub_key'], payload['token']): 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' 'The Salt Master server\'s public key did not authenticate!\n'
'If you are confident that you are connecting to a valid Salt ' 'If you are confident that you are connecting to a valid Salt '
'Master, then remove the master public key and restart the ' 'Master, then remove the master public key and restart the '
'Salt Minion.\nThe master public key can be found at:\n%s', 'Salt Minion.\nThe master public key can be found '
m_pub_fn 'at:\n{0}'.format(m_pub_fn)
) )
sys.exit(42) sys.exit(42)
if self.opts.get('master_finger', False): 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'): 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 raise NotImplementedError
@ -138,7 +139,11 @@ class Client(object):
''' '''
ret = [] ret = []
path = self._check_proto(path) 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): for fn_ in self.file_list(env):
if fn_.startswith(path): if fn_.startswith(path):
local = self.cache_file('salt://{0}'.format(fn_), env) local = self.cache_file('salt://{0}'.format(fn_), env)
@ -162,7 +167,7 @@ class Client(object):
'files', 'files',
env env
) )
minion_dir = '%s/%s' % (dest,fn_) minion_dir = '{0}/{1}'.format(dest, fn_)
if not os.path.isdir(minion_dir): if not os.path.isdir(minion_dir):
os.makedirs(minion_dir) os.makedirs(minion_dir)
ret.append(minion_dir) ret.append(minion_dir)
@ -267,16 +272,20 @@ class Client(object):
# Remove the leading directories from path to derive # Remove the leading directories from path to derive
# the relative path on the minion. # the relative path on the minion.
minion_relpath = string.lstrip(fn_[len(prefix):], '/') minion_relpath = string.lstrip(fn_[len(prefix):], '/')
ret.append(self.get_file('salt://{0}'.format(fn_), ret.append(
'%s/%s' % (dest, minion_relpath), self.get_file(
True, env)) 'salt://{0}'.format(fn_),
'{0}/{1}'.format(dest, minion_relpath),
True, env
)
)
# Replicate empty dirs from master # Replicate empty dirs from master
for fn_ in self.file_list_emptydirs(env): for fn_ in self.file_list_emptydirs(env):
if fn_.startswith(path): if fn_.startswith(path):
# Remove the leading directories from path to derive # Remove the leading directories from path to derive
# the relative path on the minion. # the relative path on the minion.
minion_relpath = string.lstrip(fn_[len(prefix):], '/') 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) os.makedirs(minion_mkdir)
ret.append(minion_mkdir) ret.append(minion_mkdir)
ret.sort() ret.sort()
@ -451,9 +460,8 @@ class LocalClient(Client):
path = self._check_proto(path) path = self._check_proto(path)
except MinionError: except MinionError:
if not os.path.isfile(path): if not os.path.isfile(path):
err = ('Specified file {0} is not present to generate ' err = 'Specified file {0} is not present to generate hash'
'hash').format(path) log.warning(err.format(path))
log.warning(err)
return ret return ret
else: else:
with open(path, 'rb') as f: 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 dest is ommited, then the downloaded file will be placed in the minion
cache cache
''' '''
log.info("Fetching file '%s'" % path) log.info('Fetching file \'{0}\''.format(path))
path = self._check_proto(path) path = self._check_proto(path)
load = {'path': path, load = {'path': path,
'env': env, 'env': env,
@ -624,9 +632,8 @@ class RemoteClient(Client):
path = self._check_proto(path) path = self._check_proto(path)
except MinionError: except MinionError:
if not os.path.isfile(path): if not os.path.isfile(path):
err = ('Specified file {0} is not present to generate ' err = 'Specified file {0} is not present to generate hash'
'hash').format(path) log.warning(err.format(path))
log.warning(err)
return {} return {}
else: else:
ret = {} ret = {}

View File

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

View File

@ -36,10 +36,12 @@ def address():
salt '*' bluetooth.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') path = __salt__['cmd.run'](cmd).split('\n')
devname = path[0].split('/') 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') sysfile = open(syspath, 'r')
address = sysfile.read().strip() address = sysfile.read().strip()
sysfile.close() sysfile.close()
@ -84,7 +86,9 @@ def pair(address, key):
to pair with, and 1234 is the passphrase. to pair with, and 1234 is the passphrase.
''' '''
address = address() 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') out = __salt__['cmd.run'](cmd).split('\n')
return out return out
@ -101,7 +105,7 @@ def unpair(address):
to unpair. to unpair.
''' '''
address = address() address = address()
cmd = 'bluez-test-device remove %s' % address cmd = 'bluez-test-device remove {0}'.format(address)
out = __salt__['cmd.run'](cmd).split('\n') out = __salt__['cmd.run'](cmd).split('\n')
return out return out

View File

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

View File

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

View File

@ -119,7 +119,7 @@ def set_host(ip, alias):
if not ovr: if not ovr:
# make sure there is a newline # make sure there is a newline
if lines and not lines[-1].endswith(('\n', '\r')): 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' line = ip + '\t\t' + alias + '\n'
lines.append(line) lines.append(line)
open(hfn, 'w+').writelines(lines) open(hfn, 'w+').writelines(lines)
@ -195,7 +195,7 @@ def add_host(ip, alias):
if not ovr: if not ovr:
# make sure there is a newline # make sure there is a newline
if lines and not lines[-1].endswith(('\n', '\r')): 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' line = ip + '\t\t' + alias + '\n'
lines.append(line) lines.append(line)
open(hfn, 'w+').writelines(lines) open(hfn, 'w+').writelines(lines)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -46,7 +46,7 @@ def version():
version_line = __salt__['cmd.run']('psql --version').split("\n")[0] version_line = __salt__['cmd.run']('psql --version').split("\n")[0]
name = version_line.split(" ")[1] name = version_line.split(" ")[1]
ver = version_line.split(" ")[2] 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): 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)) source = os.path.join('salt://_{0}'.format(form))
mod_dir = os.path.join(__opts__['extension_modules'], '{0}'.format(form)) mod_dir = os.path.join(__opts__['extension_modules'], '{0}'.format(form))
if not os.path.isdir(mod_dir): 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) os.makedirs(mod_dir)
for sub_env in env: 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 = [] 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)) cache.extend(__salt__['cp.cache_dir'](source, sub_env))
local_cache_dir=os.path.join( local_cache_dir=os.path.join(
__opts__['cachedir'], __opts__['cachedir'],
@ -57,13 +57,13 @@ def _sync(form, env=None):
sub_env, sub_env,
'_{0}'.format(form) '_{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: for fn_ in cache:
relpath = os.path.relpath(fn_, local_cache_dir) relpath = os.path.relpath(fn_, local_cache_dir)
relname = os.path.splitext(relpath)[0].replace(os.sep, '.') relname = os.path.splitext(relpath)[0].replace(os.sep, '.')
remote.add(relpath) remote.add(relpath)
dest = os.path.join(mod_dir, 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): if os.path.isfile(dest):
# The file is present, if the sum differs replace it # The file is present, if the sum differs replace it
srch = hashlib.md5(open(fn_, 'r').read()).hexdigest() srch = hashlib.md5(open(fn_, 'r').read()).hexdigest()
@ -154,7 +154,7 @@ def update(version=None):
restarted = {} restarted = {}
for service in __opts__['update_restart_services']: for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service) 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} 'restarted': restarted}
def sync_modules(env=None): def sync_modules(env=None):

View File

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

View File

@ -69,5 +69,7 @@ def signal(signal=None):
if not valid_signals[signal]: if not valid_signals[signal]:
return 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) __salt__['cmd.run'](cmd)

View File

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

View File

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

View File

@ -53,7 +53,7 @@ def returner(ret):
'id': ret['id']} 'id': ret['id']}
if isinstance(ret['return'], dict): if isinstance(ret['return'], dict):
for key, value in ret['return'].items(): for key, value in ret['return'].items():
columns['return.%s' % (key,)] = str(value) columns['return.{0}'.format(key)] = str(value)
else: else:
columns['return'] = str(ret['return']) 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['comment'] = 'File {0} is set to be updated'.format(name)
ret['result'] = None ret['result'] = None
return ret return ret
with open(name, 'rb') as fp_: with open(name, 'rb') as fp_:
slines = fp_.readlines() slines = fp_.readlines()
@ -1818,8 +1818,11 @@ def append(name, text=None, makedirs=False, source=None, source_hash=None):
try: try:
lines = chunk.split('\n') lines = chunk.split('\n')
except AttributeError: except AttributeError:
logger.debug('Error appending text to %s; given object is: %s', logger.debug(
name, type(chunk)) 'Error appending text to {0}; given object is: {1}'.format(
name, type(chunk)
)
)
return _error(ret, 'Given text is not a string') return _error(ret, 'Given text is not a string')
for line in lines: for line in lines:

View File

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

View File

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

View File

@ -47,7 +47,7 @@ class SaltCacheLoader(BaseLoader):
self.env = env self.env = env
self.encoding = encoding self.encoding = encoding
self.searchpath = path.join(opts['cachedir'], 'files', env) 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._file_client = None
self.cached = [] self.cached = []
@ -77,8 +77,10 @@ class SaltCacheLoader(BaseLoader):
def get_source(self, environment, template): def get_source(self, environment, template):
# checks for relative '..' paths # checks for relative '..' paths
if '..' in template: if '..' in template:
log.warning("Discarded template path '%s', relative paths are" log.warning(
"prohibited" % template) 'Discarded template path \'{0}\', relative paths are '
'prohibited'.format(template)
)
raise TemplateNotFound(template) raise TemplateNotFound(template)
self.check_cache(template) self.check_cache(template)
filepath = path.join(self.searchpath, 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 # Gather and run the process_<option> functions in the proper order
process_option_funcs = [] process_option_funcs = []
for option_key in options.__dict__.keys(): 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: if process_option_func is not None:
process_option_funcs.append(process_option_func) 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: if self.config.get('conf_file', None) is not None:
logging.getLogger(__name__).info( 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 # Retain the standard behaviour of optparse to return options and args
return options, args return options, args
@ -433,7 +437,7 @@ class TargetOptionsMixIn(object):
if getattr(self.options, opt.dest): if getattr(self.options, opt.dest):
self.selected_target_option = opt.dest self.selected_target_option = opt.dest
funcname = 'process_%s' % option.dest funcname = 'process_{0}'.format(option.dest)
if not hasattr(self, funcname): if not hasattr(self, funcname):
setattr(self, funcname, partial(process, option)) setattr(self, funcname, partial(process, option))
@ -493,8 +497,12 @@ class TimeoutMixIn(object):
def _mixin_setup(self): def _mixin_setup(self):
if not hasattr(self, 'default_timeout'): if not hasattr(self, 'default_timeout'):
raise RuntimeError("You need to define the 'default_timeout' " raise RuntimeError(
"attribute on %s" % self.__class__.__name__) 'You need to define the \'default_timeout\' attribute '
'on {0}'.format(
self.__class__.__name__
)
)
self.add_option( self.add_option(
'-t', '--timeout', '-t', '--timeout',
type=int, type=int,
@ -557,7 +565,7 @@ class OutputOptionsMixIn(object):
if getattr(self.options, opt.dest): if getattr(self.options, opt.dest):
self.selected_output_option = opt.dest self.selected_output_option = opt.dest
funcname = 'process_%s' % option.dest funcname = 'process_{0}'.format(option.dest)
if not hasattr(self, funcname): if not hasattr(self, funcname):
setattr(self, funcname, partial(process, option)) setattr(self, funcname, partial(process, option))

View File

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