Make pep8 tests run against the library directory as well, and associated tweaks (mostly to indentation) in the library

directory.
This commit is contained in:
Michael DeHaan 2012-08-11 12:35:58 -04:00
parent 61d10cd773
commit 3c2eba57fd
12 changed files with 126 additions and 132 deletions

8
apt
View file

@ -21,7 +21,7 @@
import traceback import traceback
# added to stave off future warnings about apt api # added to stave off future warnings about apt api
import warnings; import warnings
warnings.filterwarnings('ignore', "apt API not stable yet", FutureWarning) warnings.filterwarnings('ignore', "apt API not stable yet", FutureWarning)
# APT related constants # APT related constants
@ -30,8 +30,7 @@ APT = "DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical %s" % APT_PATH
def run_apt(command): def run_apt(command):
try: try:
cmd = subprocess.Popen(command, shell=True, cmd = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate() out, err = cmd.communicate()
except (OSError, IOError), e: except (OSError, IOError), e:
rc = 1 rc = 1
@ -131,7 +130,8 @@ def main():
) )
try: try:
import apt, apt_pkg import apt
import apt_pkg
except: except:
module.fail_json("Could not import python modules: apt, apt_pkg. Please install python-apt package.") module.fail_json("Could not import python modules: apt, apt_pkg. Please install python-apt package.")

View file

@ -58,7 +58,7 @@ def main():
module_fail_json(ansible_job_id=jid, results_file=log_path, module_fail_json(ansible_job_id=jid, results_file=log_path,
msg="Could not parse job output: %s" % data) msg="Could not parse job output: %s" % data)
if not data.has_key("started"): if not 'started' in data:
data['finished'] = 1 data['finished'] = 1
data['ansible_job_id'] = jid data['ansible_job_id'] = jid
module.exit_json(**data) module.exit_json(**data)

View file

@ -54,9 +54,9 @@ def main():
delta = endd - startd delta = endd - startd
if out is None: if out is None:
out = '' out = ''
if err is None: if err is None:
err = '' err = ''
module.exit_json( module.exit_json(
cmd = args, cmd = args,

24
facter
View file

@ -26,22 +26,22 @@
import subprocess import subprocess
def get_facter_data(): def get_facter_data():
p = subprocess.Popen(["/usr/bin/env", "facter", "--json"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p = subprocess.Popen(["/usr/bin/env", "facter", "--json"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate() (out, err) = p.communicate()
rc = p.returncode rc = p.returncode
return rc, out, err return rc, out, err
def main(): def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec = dict() argument_spec = dict()
) )
rc, out, err = get_facter_data() rc, out, err = get_facter_data()
if rc != 0: if rc != 0:
module.fail_json(msg=err) module.fail_json(msg=err)
else: else:
module.exit_json(**json.loads(out)) module.exit_json(**json.loads(out))
# this is magic, see lib/ansible/module_common.py # this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>> #<<INCLUDE_ANSIBLE_MODULE_COMMON>>

107
file
View file

@ -112,13 +112,6 @@ def selinux_context(path):
context = ret[1].split(':') context = ret[1].split(':')
return context return context
# ===========================================
# =========================================== # ===========================================
# support functions # support functions
@ -157,64 +150,64 @@ def set_context_if_different(path, context, changed):
return changed return changed
def set_owner_if_different(path, owner, changed): def set_owner_if_different(path, owner, changed):
if owner is None: if owner is None:
return changed return changed
user, group = user_and_group(path) user, group = user_and_group(path)
if owner != user: if owner != user:
try: try:
uid = pwd.getpwnam(owner).pw_uid uid = pwd.getpwnam(owner).pw_uid
except KeyError: except KeyError:
module_fail_json(path=path, msg='chown failed: failed to look up user %s' % owner) module_fail_json(path=path, msg='chown failed: failed to look up user %s' % owner)
try: try:
os.chown(path, uid, -1) os.chown(path, uid, -1)
except OSError: except OSError:
module_fail_json(path=path, msg='chown failed') module_fail_json(path=path, msg='chown failed')
return True return True
return changed return changed
def set_group_if_different(path, group, changed): def set_group_if_different(path, group, changed):
if group is None: if group is None:
return changed return changed
old_user, old_group = user_and_group(path) old_user, old_group = user_and_group(path)
if old_group != group: if old_group != group:
try: try:
gid = grp.getgrnam(group).gr_gid gid = grp.getgrnam(group).gr_gid
except KeyError: except KeyError:
module_fail_json(path=path, msg='chgrp failed: failed to look up group %s' % group) module_fail_json(path=path, msg='chgrp failed: failed to look up group %s' % group)
try: try:
os.chown(path, -1, gid) os.chown(path, -1, gid)
except OSError: except OSError:
module_fail_json(path=path, msg='chgrp failed') module_fail_json(path=path, msg='chgrp failed')
return True return True
return changed return changed
def set_mode_if_different(path, mode, changed): def set_mode_if_different(path, mode, changed):
if mode is None: if mode is None:
return changed return changed
try: try:
# FIXME: support English modes # FIXME: support English modes
mode = int(mode, 8) mode = int(mode, 8)
except Exception, e: except Exception, e:
module_fail_json(path=path, msg='mode needs to be something octalish', details=str(e)) module_fail_json(path=path, msg='mode needs to be something octalish', details=str(e))
st = os.stat(path) st = os.stat(path)
prev_mode = stat.S_IMODE(st[stat.ST_MODE]) prev_mode = stat.S_IMODE(st[stat.ST_MODE])
if prev_mode != mode: if prev_mode != mode:
# FIXME: comparison against string above will cause this to be executed # FIXME: comparison against string above will cause this to be executed
# every time # every time
try: try:
os.chmod(path, mode) os.chmod(path, mode)
except Exception, e: except Exception, e:
module_fail_json(path=path, msg='chmod failed', details=str(e)) module_fail_json(path=path, msg='chmod failed', details=str(e))
st = os.stat(path)
new_mode = stat.S_IMODE(st[stat.ST_MODE])
st = os.stat(path) if new_mode != prev_mode:
new_mode = stat.S_IMODE(st[stat.ST_MODE]) return True
return changed
if new_mode != prev_mode:
return True
return changed
def rmtree_error(func, path, exc_info): def rmtree_error(func, path, exc_info):
@ -222,7 +215,9 @@ def rmtree_error(func, path, exc_info):
def main(): def main():
# FIXME: pass this around, should not use global
global module global module
module = AnsibleModule( module = AnsibleModule(
check_invalid_arguments = False, check_invalid_arguments = False,
argument_spec = dict( argument_spec = dict(

16
mount
View file

@ -59,8 +59,8 @@ def set_mount(**kwargs):
changed = False changed = False
for line in open(args['fstab'], 'r').readlines(): for line in open(args['fstab'], 'r').readlines():
if not line.strip(): if not line.strip():
to_write.append(line) to_write.append(line)
continue continue
if line.strip().startswith('#'): if line.strip().startswith('#'):
to_write.append(line) to_write.append(line)
continue continue
@ -85,9 +85,9 @@ def set_mount(**kwargs):
ld[t] = args[t] ld[t] = args[t]
if changed: if changed:
to_write.append(new_line % ld) to_write.append(new_line % ld)
else: else:
to_write.append(line) to_write.append(line)
if not exists: if not exists:
to_write.append(new_line % args) to_write.append(new_line % args)
@ -115,8 +115,8 @@ def unset_mount(**kwargs):
changed = False changed = False
for line in open(args['fstab'], 'r').readlines(): for line in open(args['fstab'], 'r').readlines():
if not line.strip(): if not line.strip():
to_write.append(line) to_write.append(line)
continue continue
if line.strip().startswith('#'): if line.strip().startswith('#'):
to_write.append(line) to_write.append(line)
continue continue
@ -147,9 +147,9 @@ def mount(**kwargs):
name = kwargs['name'] name = kwargs['name']
if os.path.ismount(name): if os.path.ismount(name):
cmd = ['/bin/mount', '-o', 'remount', name] cmd = [ '/bin/mount', '-o', 'remount', name ]
else: else:
cmd = ['/bin/mount', name ] cmd = [ '/bin/mount', name ]
call = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) call = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = call.communicate() out, err = call.communicate()

4
ohai
View file

@ -31,9 +31,9 @@ def main():
) )
rc, out, err = get_ohai_data() rc, out, err = get_ohai_data()
if rc != 0: if rc != 0:
module.fail_json(msg=err) module.fail_json(msg=err)
else: else:
module.exit_json(**json.loads(out)) module.exit_json(**json.loads(out))
# this is magic, see lib/ansible/module_common.py # this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>> #<<INCLUDE_ANSIBLE_MODULE_COMMON>>

View file

@ -207,11 +207,9 @@ def main():
if state: if state:
result['state'] = state result['state'] = state
rc, stdout, stderr = _run("%s %s status" % (SERVICE, name)) rc, stdout, stderr = _run("%s %s status" % (SERVICE, name))
module.exit_json(**result); module.exit_json(**result)
# this is magic, see lib/ansible/module_common.py # this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>> #<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main() main()

75
setup
View file

@ -130,7 +130,7 @@ class Facts(object):
self.facts['selinux']['policyvers'] = 'unknown' self.facts['selinux']['policyvers'] = 'unknown'
try: try:
(rc, configmode) = selinux.selinux_getenforcemode() (rc, configmode) = selinux.selinux_getenforcemode()
if rc == 0 and Facts.SELINUX_MODE_DICT.has_key(configmode): if rc == 0 and configmode in Facts.SELINUX_MODE_DICT:
self.facts['selinux']['config_mode'] = Facts.SELINUX_MODE_DICT[configmode] self.facts['selinux']['config_mode'] = Facts.SELINUX_MODE_DICT[configmode]
else: else:
self.facts['selinux']['config_mode'] = 'unknown' self.facts['selinux']['config_mode'] = 'unknown'
@ -138,7 +138,7 @@ class Facts(object):
self.facts['selinux']['config_mode'] = 'unknown' self.facts['selinux']['config_mode'] = 'unknown'
try: try:
mode = selinux.security_getenforce() mode = selinux.security_getenforce()
if Facts.SELINUX_MODE_DICT.has_key(mode): if mode in Facts.SELINUX_MODE_DICT:
self.facts['selinux']['mode'] = Facts.SELINUX_MODE_DICT[mode] self.facts['selinux']['mode'] = Facts.SELINUX_MODE_DICT[mode]
else: else:
self.facts['selinux']['mode'] = 'unknown' self.facts['selinux']['mode'] = 'unknown'
@ -196,19 +196,21 @@ class LinuxHardware(Hardware):
In addition, it also defines number of DMI facts. In addition, it also defines number of DMI facts.
""" """
platform = 'Linux' platform = 'Linux'
MEMORY_FACTS = ['MemTotal', 'SwapTotal', 'MemFree', 'SwapFree'] MEMORY_FACTS = ['MemTotal', 'SwapTotal', 'MemFree', 'SwapFree']
# DMI bits # DMI bits
DMI_DICT = { 'form_factor': '/sys/devices/virtual/dmi/id/chassis_type', DMI_DICT = dict(
'product_name': '/sys/devices/virtual/dmi/id/product_name', form_factor = '/sys/devices/virtual/dmi/id/chassis_type',
'product_serial': '/sys/devices/virtual/dmi/id/product_serial', product_name = '/sys/devices/virtual/dmi/id/product_name',
'product_uuid': '/sys/devices/virtual/dmi/id/product_uuid', product_serial = '/sys/devices/virtual/dmi/id/product_serial',
'product_version': '/sys/devices/virtual/dmi/id/product_version', product_uuid = '/sys/devices/virtual/dmi/id/product_uuid',
'system_vendor': '/sys/devices/virtual/dmi/id/sys_vendor', product_version = '/sys/devices/virtual/dmi/id/product_version',
'bios_date': '/sys/devices/virtual/dmi/id/bios_date', system_vendor = '/sys/devices/virtual/dmi/id/sys_vendor',
'bios_version': '/sys/devices/virtual/dmi/id/bios_version' } bios_date = '/sys/devices/virtual/dmi/id/bios_date',
# From smolt and DMI spec bios_version = '/sys/devices/virtual/dmi/id/bios_version'
# See http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_2.7.0.pdf )
# DMI SPEC -- http://www.dmtf.org/sites/default/files/standards/documents/DSP0134_2.7.0.pdf
FORM_FACTOR = [ "Unknown", "Other", "Unknown", "Desktop", FORM_FACTOR = [ "Unknown", "Other", "Unknown", "Desktop",
"Low Profile Desktop", "Pizza Box", "Mini Tower", "Tower", "Low Profile Desktop", "Pizza Box", "Mini Tower", "Tower",
"Portable", "Laptop", "Notebook", "Hand Held", "Docking Station", "Portable", "Laptop", "Notebook", "Hand Held", "Docking Station",
@ -634,36 +636,36 @@ def run_setup(module):
# ruby-json is ALSO installed, include facter data in the JSON # ruby-json is ALSO installed, include facter data in the JSON
if os.path.exists("/usr/bin/facter"): if os.path.exists("/usr/bin/facter"):
cmd = subprocess.Popen("/usr/bin/facter --json", shell=True, cmd = subprocess.Popen("/usr/bin/facter --json", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate() out, err = cmd.communicate()
facter = True facter = True
try: try:
facter_ds = json.loads(out) facter_ds = json.loads(out)
except: except:
facter = False facter = False
if facter: if facter:
for (k,v) in facter_ds.items(): for (k,v) in facter_ds.items():
setup_options["facter_%s" % k] = v setup_options["facter_%s" % k] = v
# ditto for ohai, but just top level string keys # ditto for ohai, but just top level string keys
# because it contains a lot of nested stuff we can't use for # because it contains a lot of nested stuff we can't use for
# templating w/o making a nicer key for it (TODO) # templating w/o making a nicer key for it (TODO)
if os.path.exists("/usr/bin/ohai"): if os.path.exists("/usr/bin/ohai"):
cmd = subprocess.Popen("/usr/bin/ohai", shell=True, cmd = subprocess.Popen("/usr/bin/ohai", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate() out, err = cmd.communicate()
ohai = True ohai = True
try: try:
ohai_ds = json.loads(out) ohai_ds = json.loads(out)
except: except:
ohai = False ohai = False
if ohai: if ohai:
for (k,v) in ohai_ds.items(): for (k,v) in ohai_ds.items():
if type(v) == str or type(v) == unicode: if type(v) == str or type(v) == unicode:
k2 = "ohai_%s" % k k2 = "ohai_%s" % k
setup_options[k2] = v setup_options[k2] = v
setup_result = {} setup_result = {}
setup_result['ansible_facts'] = setup_options setup_result['ansible_facts'] = setup_options
@ -683,4 +685,3 @@ def main():
# this is magic, see lib/ansible/module_common.py # this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>> #<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main() main()

2
user
View file

@ -134,7 +134,7 @@ def user_mod(module, user, **kwargs):
cmd.append('-a') cmd.append('-a')
groups_need_mod = True groups_need_mod = True
else: else:
groups_need_mod = True groups_need_mod = True
if groups_need_mod: if groups_need_mod:
cmd.append('-G') cmd.append('-G')

2
virt
View file

@ -183,7 +183,7 @@ class Virt(object):
"nrVirtCpu" : data[3], "nrVirtCpu" : data[3],
"cpuTime" : str(data[4]), "cpuTime" : str(data[4]),
} }
info[vm]["autostart"] = self.conn.get_autostart(vm) info[vm]["autostart"] = self.conn.get_autostart(vm)
return info return info

10
yum
View file

@ -130,9 +130,9 @@ def run(command):
out = '' out = ''
if out is None: if out is None:
out = '' out = ''
if err is None: if err is None:
err = '' err = ''
else: else:
rc = cmd.returncode rc = cmd.returncode
@ -144,7 +144,7 @@ def install_no_repoq(module, items, yum_basecmd, latest=False):
to_install = [] to_install = []
if not latest: if not latest:
for item in items: for item in items:
rc, out, err = run([rpmbin, "-q", "--whatprovides", item]) rc, out, err = run([rpmbin, "-q", "--whatprovides", item])
if rc != 0: if rc != 0:
to_install.append(item) to_install.append(item)
if len(to_install) > 0: if len(to_install) > 0:
@ -163,7 +163,7 @@ def install_no_repoq(module, items, yum_basecmd, latest=False):
if rc != 0: if rc != 0:
module.fail_json(msg=err) module.fail_json(msg=err)
for item in to_install: for item in to_install:
rc, out, err = run([rpmbin, "-q", "--whatprovides", item]) rc, out, err = run([rpmbin, "-q", "--whatprovides", item])
if rc != 0: if rc != 0:
module.fail_json(msg="%s could not be installed" % item) module.fail_json(msg="%s could not be installed" % item)
@ -174,7 +174,7 @@ def remove_no_repoq(module, items, yum_basecmd):
to_remove = [] to_remove = []
for item in items: for item in items:
rc, out, err = run([rpmbin, "-q", "--whatprovides", "--qf", "%{NAME}\n", item]) rc, out, err = run([rpmbin, "-q", "--whatprovides", "--qf", "%{NAME}\n", item])
if rc == 0: if rc == 0:
to_remove.append(out.strip()) to_remove.append(out.strip())
if len(to_remove) > 0: if len(to_remove) > 0: