cleaned up apt module style

pull/75/head
Matthew Williams 13 years ago
parent 90ba14d60e
commit e85355f054

@ -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 def install(pkgspec):
if pkg.is_installed: installed = package_installed(pkgspec)
return {'changed': False, 'failed': False} debug("installed: %d" % installed)
cmd = "apt-get -q -y install '%s'" % pkgspec if installed:
rc, out, err = run_apt(cmd) return False
#pkg.mark_install() else:
#cache.commit(apt.progress.base.OpProgress()) cmd = "%s -q -y install '%s'" % (APT, pkgspec)
elif state == 'removed':
#check if package is installed
if not pkg.is_installed:
return {'changed': False, 'failed': False}
cmd = "apt-get -q -y remove '%s'" % pkgspec
rc, out, err = run_apt(cmd) rc, out, err = run_apt(cmd)
#pkg.mark_delete() # TODO: Ensure the package was really installed.
#cache.commit(apt.progress.base.OpProgress()) return True
def remove(pkgspec):
installed = package_installed(pkgspec)
debug("installed: %d" % installed)
if not installed:
return False
else: else:
return {'failed': True, 'msg': "Unknown state: %s" % state } cmd = "%s -q -y remove '%s'" % (APT, pkgspec)
rc, out, err = run_apt(cmd)
return {'changed': True, 'failed': False} # 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: if not os.path.exists(APT):
msg = "the apt module requires arguments (-a)" fail_json(msg="Cannot find apt-get")
return 1, msg
argfile = sys.argv[1] argfile = sys.argv[1]
if not os.path.exists(argfile):
msg = "Argument file not found"
return 1, msg
args = open(argfile, 'r').read() args = open(argfile, 'r').read()
items = shlex.split(args) 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
results = { 'changed':False,
'failed':True,
'results':'',
'errors':'',
'msg':"; ".join(items) }
params = {} params = {}
for x in items: for x in items:
try: (k, v) = x.split("=")
(k, v) = x.split("=", 1)
except ValueError:
msg = "invalid arguments: %s" % args
return 1, msg
params[k] = v 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: if state not in ['installed', 'removed']:
state = params['state'] fail_json(msg='invalid state')
pkgspec = params['pkg'] if package is None:
fail_json(msg='pkg is required')
devnull = open(os.devnull, 'w')
results = ensure(state, pkgspec) if state == 'installed':
print json.dumps(results) changed = install(package)
return 0, None elif state == 'removed':
changed = remove(package)
if __name__ == "__main__": exit_json(changed=changed)
rc, msg = main()
if rc != 0: # something went wrong emit the msg
print json.dumps({
"failed" : bool(rc),
"msg" : msg
})
sys.exit(rc)
fail_json(name=name, msg='Unexpected position reached')
sys.exit(0)

Loading…
Cancel
Save