cleaned up apt module style

This commit is contained in:
Matthew Williams 2012-03-26 13:48:02 -07:00
parent 71b503b0c3
commit b4604b2525

156
apt
View file

@ -17,20 +17,34 @@
# along with this software. If not, see <http://www.gnu.org/licenses/>. # along with this software. If not, see <http://www.gnu.org/licenses/>.
# #
try:
import json
except ImportError:
import simplejson as json
import os import os
import sys import sys
import apt import apt
import shlex import shlex
import subprocess import subprocess
import traceback
APT = "/usr/bin/apt-get"
try: def debug(msg):
import json # ansible ignores stderr, so it's safe to use for debug
except ImportError: print >>sys.stderr, msg
import simplejson as json #pass
def exit_json(rc=0, **kwargs):
print json.dumps(kwargs)
sys.exit(rc)
def fail_json(**kwargs):
kwargs['failed'] = True
exit_json(rc=1, **kwargs)
def run_apt(command): def run_apt(command):
debug(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)
@ -51,102 +65,86 @@ def run_apt(command):
else: else:
rc = cmd.returncode rc = cmd.returncode
debug(err)
return rc, out, err return rc, out, err
def ensure(state, pkgspec): def get_cache():
# TODO: Only update the cache if it's old.
cache = apt.Cache() cache = apt.Cache()
cache.update() cache.update()
cache.open(None) cache.open(None)
return cache
def package_installed(pkgspec):
cache = get_cache()
try: try:
pkg = cache[pkgspec] pkg = cache[pkgspec]
except: except:
msg = "No package matching '%s' is available" % pkgsepc fail_json(msg="No package matching '%s' is available" % pkgspec)
return {'changed': False, 'failed': True, 'msg': msg} return bool(pkg.is_installed)
if state == 'installed':
#check if package is installed
if pkg.is_installed:
return {'changed': False, 'failed': False}
cmd = "apt-get -q -y install '%s'" % pkgspec
rc, out, err = run_apt(cmd)
#pkg.mark_install()
#cache.commit(apt.progress.base.OpProgress())
elif state == 'removed': def install(pkgspec):
#check if package is installed installed = package_installed(pkgspec)
if not pkg.is_installed: debug("installed: %d" % installed)
return {'changed': False, 'failed': False} if installed:
cmd = "apt-get -q -y remove '%s'" % pkgspec return False
rc, out, err = run_apt(cmd)
#pkg.mark_delete()
#cache.commit(apt.progress.base.OpProgress())
else: else:
return {'failed': True, 'msg': "Unknown state: %s" % state } cmd = "%s -q -y install '%s'" % (APT, pkgspec)
rc, out, err = run_apt(cmd)
return {'changed': True, 'failed': False} # TODO: Ensure the package was really installed.
return True
def remove(pkgspec):
installed = package_installed(pkgspec)
debug("installed: %d" % installed)
if not installed:
return False
else:
cmd = "%s -q -y remove '%s'" % (APT, pkgspec)
rc, out, err = run_apt(cmd)
# TODO: Ensure the package was really removed.
return True
def update(args): def update(args):
#generic update routine # TODO: generic update routine
pass pass
def remove_only(pkgspec): def remove_only(pkgspec):
# remove this pkg and only this pkg - fail if it will require more to remove # TODO: remove this pkg and only this pkg - fail if it will require more to remove
pass pass
def main(): # ===========================================
# state=installed pkg=pkgspec
# state=removed pkg=pkgspec
if len(sys.argv) == 1:
msg = "the apt module requires arguments (-a)"
return 1, msg
argfile = sys.argv[1] if not os.path.exists(APT):
if not os.path.exists(argfile): fail_json(msg="Cannot find apt-get")
msg = "Argument file not found"
return 1, msg
args = open(argfile, 'r').read() argfile = sys.argv[1]
items = shlex.split(args) args = open(argfile, 'r').read()
items = shlex.split(args)
if not len(items): if not len(items):
msg = "the apt module requires arguments (-a)" fail_json(msg='the module requires arguments -a')
return 1, msg sys.exit(1)
# if nothing else changes - it fails params = {}
results = { 'changed':False, for x in items:
'failed':True, (k, v) = x.split("=")
'results':'', params[k] = v
'errors':'',
'msg':"; ".join(items) }
params = {}
for x in items:
try:
(k, v) = x.split("=", 1)
except ValueError:
msg = "invalid arguments: %s" % args
return 1, msg
params[k] = v
if 'state' in params: state = params.get('state','installed')
if 'pkg' not in params: package = params.get('pkg', None)
results['msg'] = "No pkg specified"
else:
state = params['state']
pkgspec = params['pkg']
devnull = open(os.devnull, 'w') if state not in ['installed', 'removed']:
results = ensure(state, pkgspec) fail_json(msg='invalid state')
print json.dumps(results) if package is None:
return 0, None fail_json(msg='pkg is required')
if __name__ == "__main__": if state == 'installed':
rc, msg = main() changed = install(package)
if rc != 0: # something went wrong emit the msg elif state == 'removed':
print json.dumps({ changed = remove(package)
"failed" : bool(rc), exit_json(changed=changed)
"msg" : msg
})
sys.exit(rc)
fail_json(name=name, msg='Unexpected position reached')
sys.exit(0)