Merge pull request #476 from sivel/py24-fixes

Fix up modules that have python24 syntax errors
This commit is contained in:
Toshio Kuratomi 2015-05-11 09:02:49 -07:00
commit 6bf4558df8
22 changed files with 108 additions and 46 deletions

View file

@ -7,4 +7,4 @@ addons:
packages: packages:
- python2.4 - python2.4
script: script:
- python2.4 -m compileall -fq -x 'cloud/' . - python2.4 -m compileall -fq -x 'cloud/|monitoring/zabbix.*\.py|/layman.py|/maven_artifact.py|clustering/consul.*\.py' .

View file

@ -233,7 +233,10 @@ def present(user_facts, cursor, user, profile, resource_pool,
changed = False changed = False
query_fragments = ["alter user {0}".format(user)] query_fragments = ["alter user {0}".format(user)]
if locked is not None and locked != (user_facts[user_key]['locked'] == 'True'): if locked is not None and locked != (user_facts[user_key]['locked'] == 'True'):
state = 'lock' if locked else 'unlock' if locked:
state = 'lock'
else:
state = 'unlock'
query_fragments.append("account {0}".format(state)) query_fragments.append("account {0}".format(state))
changed = True changed = True
if password and password != user_facts[user_key]['password']: if password and password != user_facts[user_key]['password']:

View file

@ -110,7 +110,7 @@ def apply_patch(patch_func, patch_file, basedir, dest_file=None, strip=0, dry_ru
(rc, out, err) = patch_func(opts) (rc, out, err) = patch_func(opts)
if rc != 0: if rc != 0:
msg = out if not err else err msg = err or out
raise PatchError(msg) raise PatchError(msg)

View file

@ -162,7 +162,7 @@ def main():
module.exit_json(changed=True, **deployment) module.exit_json(changed=True, **deployment)
else: else:
module.fail_json(msg=json.dumps(info)) module.fail_json(msg=json.dumps(info))
except Exception as e: except Exception, e:
module.fail_json(msg=str(e)) module.fail_json(msg=str(e))
# import module snippets # import module snippets

View file

@ -213,7 +213,7 @@ def download_request(module, name, apiid, apikey, cert_type):
cert_file = open(cert_file_path, 'w') cert_file = open(cert_file_path, 'w')
cert_file.write(body) cert_file.write(body)
cert_file.close cert_file.close
os.chmod(cert_file_path, 0o600) os.chmod(cert_file_path, 0600)
except: except:
module.fail_json("Could not write to certificate file") module.fail_json("Could not write to certificate file")

View file

@ -138,11 +138,11 @@ def post_annotation(module):
headers = {} headers = {}
headers['Content-Type'] = 'application/json' headers['Content-Type'] = 'application/json'
headers['Authorization'] = b"Basic " + base64.b64encode(user + b":" + api_key).strip() headers['Authorization'] = "Basic " + base64.b64encode(user + ":" + api_key).strip()
req = urllib2.Request(url, json_body, headers) req = urllib2.Request(url, json_body, headers)
try: try:
response = urllib2.urlopen(req) response = urllib2.urlopen(req)
except urllib2.HTTPError as e: except urllib2.HTTPError, e:
module.fail_json(msg="Request Failed", reason=e.reason) module.fail_json(msg="Request Failed", reason=e.reason)
response = response.read() response = response.read()
module.exit_json(changed=True, annotation=response) module.exit_json(changed=True, annotation=response)

View file

@ -141,9 +141,9 @@ def build_payload_for_slack(module, text, channel, username, icon_url, icon_emoj
else: else:
payload = dict(attachments=[dict(text=text, color=color)]) payload = dict(attachments=[dict(text=text, color=color)])
if channel is not None: if channel is not None:
if (channel[0] == '#') or (channel[0] == '@') if (channel[0] == '#') or (channel[0] == '@'):
payload['channel'] = channel payload['channel'] = channel
else else:
payload['channel'] = '#'+channel payload['channel'] = '#'+channel
if username is not None: if username is not None:
payload['username'] = username payload['username'] = username

View file

@ -128,13 +128,18 @@ def ensure(module, state, packages, params):
}, },
} }
if params['accept_licenses']:
accept_licenses = ['--accept']
else:
accept_licenses = []
to_modify = filter(behaviour[state]['filter'], packages) to_modify = filter(behaviour[state]['filter'], packages)
if to_modify: if to_modify:
rc, out, err = module.run_command( rc, out, err = module.run_command(
[ [
'pkg', behaviour[state]['subcommand'] 'pkg', behaviour[state]['subcommand']
] ]
+ (['--accept'] if params['accept_licenses'] else []) + accept_licenses
+ [ + [
'-q', '--' '-q', '--'
] + to_modify ] + to_modify
@ -151,12 +156,12 @@ def ensure(module, state, packages, params):
def is_installed(module, package): def is_installed(module, package):
rc, out, err = module.run_command(['pkg', 'list', '--', package]) rc, out, err = module.run_command(['pkg', 'list', '--', package])
return True if rc == 0 else False return not bool(int(rc))
def is_latest(module, package): def is_latest(module, package):
rc, out, err = module.run_command(['pkg', 'list', '-u', '--', package]) rc, out, err = module.run_command(['pkg', 'list', '-u', '--', package])
return True if rc == 1 else False return bool(int(rc))
from ansible.module_utils.basic import * from ansible.module_utils.basic import *

View file

@ -122,10 +122,15 @@ def set_publisher(module, params):
args.append('--remove-mirror=*') args.append('--remove-mirror=*')
args.extend(['--add-mirror=' + u for u in params['mirror']]) args.extend(['--add-mirror=' + u for u in params['mirror']])
if params['sticky'] != None: if params['sticky'] != None and params['sticky']:
args.append('--sticky' if params['sticky'] else '--non-sticky') args.append('--sticky')
if params['enabled'] != None: elif params['sticky'] != None:
args.append('--enable' if params['enabled'] else '--disable') args.append('--non-sticky')
if params['enabled'] != None and params['enabled']:
args.append('--enable')
elif params['enabled'] != None:
args.append('--disable')
rc, out, err = module.run_command( rc, out, err = module.run_command(
["pkg", "set-publisher"] + args + [name], ["pkg", "set-publisher"] + args + [name],

View file

@ -252,9 +252,8 @@ def annotate_packages(module, pkgng_path, packages, annotation):
for package in packages: for package in packages:
for _annotation in annotations: for _annotation in annotations:
annotate_c += ( 1 if operation[_annotation['operation']]( if operation[_annotation['operation']](module, pkgng_path, package, _annotation['tag'], _annotation['value']):
module, pkgng_path, package, annotate_c += 1
_annotation['tag'], _annotation['value']) else 0 )
if annotate_c > 0: if annotate_c > 0:
return (True, "added %s annotations." % annotate_c) return (True, "added %s annotations." % annotate_c)

View file

@ -422,7 +422,9 @@ def main():
if not p['package']: if not p['package']:
module.exit_json(msg='Sync successfully finished.') module.exit_json(msg='Sync successfully finished.')
packages = p['package'].split(',') if p['package'] else [] packages = []
if p['package']:
packages.extend(p['package'].split(','))
if p['depclean']: if p['depclean']:
if packages and p['state'] not in portage_absent_states: if packages and p['state'] not in portage_absent_states:

View file

@ -132,7 +132,7 @@ def main():
) )
module.exit_json(changed=True) module.exit_json(changed=True)
except subprocess.CalledProcessError as cpe: except subprocess.CalledProcessError, cpe:
module.fail_json(msg=str(dir(cpe))) module.fail_json(msg=str(dir(cpe)))
else: else:
module.exit_json(changed=False) module.exit_json(changed=False)

View file

@ -155,8 +155,11 @@ def main():
if changed and not module.check_mode: if changed and not module.check_mode:
with open(path, 'wb') as f: try:
f = open(path, 'wb')
f.write(str(crypttab)) f.write(str(crypttab))
finally:
f.close()
module.exit_json(changed=changed, msg=reason, **module.params) module.exit_json(changed=changed, msg=reason, **module.params)
@ -172,9 +175,12 @@ class Crypttab(object):
os.makedirs(os.path.dirname(path)) os.makedirs(os.path.dirname(path))
open(path,'a').close() open(path,'a').close()
with open(path, 'r') as f: try:
f = open(path, 'r')
for line in f.readlines(): for line in f.readlines():
self._lines.append(Line(line)) self._lines.append(Line(line))
finally:
f.close()
def add(self, line): def add(self, line):
self._lines.append(line) self._lines.append(line)
@ -242,10 +248,19 @@ class Line(object):
def _split_line(self, line): def _split_line(self, line):
fields = line.split() fields = line.split()
try:
field2 = field[2]
except IndexError:
field2 = None
try:
field3 = field[3]
except IndexError:
field3 = None
return (fields[0], return (fields[0],
fields[1], fields[1],
fields[2] if len(fields) >= 3 else None, field2,
fields[3] if len(fields) >= 4 else None) fields3)
def remove(self): def remove(self):
self.line, self.name, self.backing_device = '', None, None self.line, self.name, self.backing_device = '', None, None
@ -260,7 +275,10 @@ class Line(object):
if self.valid(): if self.valid():
fields = [self.name, self.backing_device] fields = [self.name, self.backing_device]
if self.password is not None or self.opts: if self.password is not None or self.opts:
fields.append(self.password if self.password is not None else 'none') if self.password is not None:
fields.append(self.password)
else:
self.password('none')
if self.opts: if self.opts:
fields.append(str(self.opts)) fields.append(str(self.opts))
return ' '.join(fields) return ' '.join(fields)
@ -276,7 +294,10 @@ class Options(dict):
if opts_string is not None: if opts_string is not None:
for opt in opts_string.split(','): for opt in opts_string.split(','):
kv = opt.split('=') kv = opt.split('=')
k, v = (kv[0], kv[1]) if len(kv) > 1 else (kv[0], None) if len(kv) > 1:
k, v = (kv[0], kv[1])
else:
k, v = (kv[0], None)
self[k] = v self[k] = v
def add(self, opts_string): def add(self, opts_string):
@ -324,8 +345,13 @@ class Options(dict):
and sorted(self.items()) == sorted(obj.items())) and sorted(self.items()) == sorted(obj.items()))
def __str__(self): def __str__(self):
return ','.join([k if v is None else '%s=%s' % (k, v) ret = []
for k, v in self.items()]) for k, v in self.items():
if v is None:
ret.append(k)
else:
ret.append('%s=%s' % (k, v))
return ','.join(ret)
# import module snippets # import module snippets
from ansible.module_utils.basic import * from ansible.module_utils.basic import *

View file

@ -145,7 +145,7 @@ def run_gluster(gargs, **kwargs):
try: try:
rc, out, err = module.run_command(args, **kwargs) rc, out, err = module.run_command(args, **kwargs)
if rc != 0: if rc != 0:
module.fail_json(msg='error running gluster (%s) command (rc=%d): %s' % (' '.join(args), rc, out if out != '' else err)) module.fail_json(msg='error running gluster (%s) command (rc=%d): %s' % (' '.join(args), rc, out or err))
except Exception, e: except Exception, e:
module.fail_json(msg='error running gluster (%s) command: %s' % (' '.join(args), str(e))) module.fail_json(msg='error running gluster (%s) command: %s' % (' '.join(args), str(e)))
return out return out
@ -167,7 +167,7 @@ def run_gluster_yes(gargs):
args.extend(gargs) args.extend(gargs)
rc, out, err = module.run_command(args, data='y\n') rc, out, err = module.run_command(args, data='y\n')
if rc != 0: if rc != 0:
module.fail_json(msg='error running gluster (%s) command (rc=%d): %s' % (' '.join(args), rc, out if out != '' else err)) module.fail_json(msg='error running gluster (%s) command (rc=%d): %s' % (' '.join(args), rc, out or err))
return out return out
def get_peers(): def get_peers():

View file

@ -55,11 +55,12 @@ def is_available(name, ubuntuMode):
__locales_available = '/etc/locale.gen' __locales_available = '/etc/locale.gen'
re_compiled = re.compile(__regexp) re_compiled = re.compile(__regexp)
with open(__locales_available, 'r') as fd: fd = open(__locales_available, 'r')
for line in fd: for line in fd:
result = re_compiled.match(line) result = re_compiled.match(line)
if result and result.group('locale') == name: if result and result.group('locale') == name:
return True return True
fd.close()
return False return False
def is_present(name): def is_present(name):
@ -76,10 +77,16 @@ def fix_case(name):
def replace_line(existing_line, new_line): def replace_line(existing_line, new_line):
"""Replaces lines in /etc/locale.gen""" """Replaces lines in /etc/locale.gen"""
with open("/etc/locale.gen", "r") as f: try:
f = open("/etc/locale.gen", "r")
lines = [line.replace(existing_line, new_line) for line in f] lines = [line.replace(existing_line, new_line) for line in f]
with open("/etc/locale.gen", "w") as f: finally:
f.close()
try:
f = open("/etc/locale.gen", "w")
f.write("".join(lines)) f.write("".join(lines))
finally:
f.close()
def set_locale(name, enabled=True): def set_locale(name, enabled=True):
""" Sets the state of the locale. Defaults to enabled. """ """ Sets the state of the locale. Defaults to enabled. """
@ -88,10 +95,16 @@ def set_locale(name, enabled=True):
new_string = '%s \g<charset>' % (name) new_string = '%s \g<charset>' % (name)
else: else:
new_string = '# %s \g<charset>' % (name) new_string = '# %s \g<charset>' % (name)
with open("/etc/locale.gen", "r") as f: try:
f = open("/etc/locale.gen", "r")
lines = [re.sub(search_string, new_string, line) for line in f] lines = [re.sub(search_string, new_string, line) for line in f]
with open("/etc/locale.gen", "w") as f: finally:
f.close()
try:
f = open("/etc/locale.gen", "w")
f.write("".join(lines)) f.write("".join(lines))
finally:
f.close()
def apply_change(targetState, name): def apply_change(targetState, name):
"""Create or remove locale. """Create or remove locale.
@ -124,13 +137,19 @@ def apply_change_ubuntu(targetState, name):
localeGenExitValue = call(["locale-gen", name]) localeGenExitValue = call(["locale-gen", name])
else: else:
# Delete locale involves discarding the locale from /var/lib/locales/supported.d/local and regenerating all locales. # Delete locale involves discarding the locale from /var/lib/locales/supported.d/local and regenerating all locales.
with open("/var/lib/locales/supported.d/local", "r") as f: try:
f = open("/var/lib/locales/supported.d/local", "r")
content = f.readlines() content = f.readlines()
with open("/var/lib/locales/supported.d/local", "w") as f: finally:
f.close()
try:
f = open("/var/lib/locales/supported.d/local", "w")
for line in content: for line in content:
locale, charset = line.split(' ') locale, charset = line.split(' ')
if locale != name: if locale != name:
f.write(line) f.write(line)
finally:
f.close()
# Purge locales and regenerate. # Purge locales and regenerate.
# Please provide a patch if you know how to avoid regenerating the locales to keep! # Please provide a patch if you know how to avoid regenerating the locales to keep!
localeGenExitValue = call(["locale-gen", "--purge"]) localeGenExitValue = call(["locale-gen", "--purge"])
@ -168,7 +187,10 @@ def main():
module.fail_json(msg="The locales you've entered is not available " module.fail_json(msg="The locales you've entered is not available "
"on your system.") "on your system.")
prev_state = "present" if is_present(name) else "absent" if is_present(name):
prev_state = "present"
else:
prev_state = "absent"
changed = (prev_state!=state) changed = (prev_state!=state)
if module.check_mode: if module.check_mode:
@ -180,7 +202,7 @@ def main():
apply_change(state, name) apply_change(state, name)
else: else:
apply_change_ubuntu(state, name) apply_change_ubuntu(state, name)
except EnvironmentError as e: except EnvironmentError, e:
module.fail_json(msg=e.strerror, exitValue=e.errno) module.fail_json(msg=e.strerror, exitValue=e.errno)
module.exit_json(name=name, changed=changed, msg="OK") module.exit_json(name=name, changed=changed, msg="OK")

View file

@ -113,7 +113,7 @@ class EjabberdUser(object):
(rc, out, err) = self.run_command('check_account', options) (rc, out, err) = self.run_command('check_account', options)
except EjabberdUserException, e: except EjabberdUserException, e:
(rc, out, err) = (1, None, "required attribute(s) missing") (rc, out, err) = (1, None, "required attribute(s) missing")
return True if rc == 0 else False return not bool(int(rc))
def log(self, entry): def log(self, entry):
""" This method will log information to the local syslog facility """ """ This method will log information to the local syslog facility """

View file

@ -335,7 +335,7 @@ def main():
ret = method(restbase, user, passwd, module.params) ret = method(restbase, user, passwd, module.params)
except Exception as e: except Exception, e:
return module.fail_json(msg=e.message) return module.fail_json(msg=e.message)