#!/usr/bin/env python # # Copyright (C) 2012-2013 Red Hat, Inc. All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Authors: Michal Minar # """ Command line tool for simple software management with OpenLMI CIM software providers. """ import argparse from collections import defaultdict import pywbem import socket import sys from lmi.software import util from lmi.software.core import SystemSoftwareCollection CIM_ERROR2TEXT = defaultdict(lambda: "OTHER_ERROR", { 1 : "FAILED", 2 : "ACCESS_DENIED", 3 : "INVALID_NAMESPACE", 4 : "INVALID_PARAMETER", 5 : "INVALID_CLASS", 6 : "NOT_FOUND", 7 : "NOT_SUPPORTED", 8 : "CLASS_HAS_CHILDREN", 9 : "CLASS_HAS_INSTANCES", 10 : "INVALID_SUPERCLASS", 11 : "ALREADY_EXISTS", 12 : "NO_SUCH_PROPERTY", 13 : "TYPE_MISMATCH", 14 : "QUERY_LANGUAGE_NOT_SUPPORTED", 15 : "INVALID_QUERY", 16 : "METHOD_NOT_AVAILABLE", 17 : "METHOD_NOT_FOUND" }) class NotFound(Exception): """ Exception raised, when desired package could not be found. """ def __init__(self, package, details=None): msg = 'Package "%s" not installed!' % package if details is not None: msg += ' : '+details Exception.__init__(self, msg) def get_host_name(): """ @return computer host name """ if not hasattr(get_host_name, '_hostname'): get_host_name._hostname = socket.gethostname() #pylint: disable=W0212 return get_host_name._hostname #pylint: disable=W0212 def make_pkg_path(name, epoch, ver, rel, arch): """ @return instance name for LMI_SoftwareIdentity """ return pywbem.CIMInstanceName( classname="LMI_SoftwareIdentity", namespace=util.Configuration.get_instance().namespace, keybindings={ "InstanceID" : util.make_nevra( name, epoch, ver, rel, arch, "ALWAYS")}) def install(_conn, _nevra): """Install package by nevra.""" raise NotImplementedError("Installation is not yet supported!") def update(_conn, _package, _epoch=None, _version=None, _release=None): """Update to particular evr of package.""" raise NotImplementedError("Update of package is not yet supported!") def remove(_conn, _package): """Remove installed package by its name.""" raise NotImplementedError("Removal is not yet supported!") def verify(_conn, _package): """Verity installed package by its name.""" raise NotImplementedError("Verification is not yet supported!") def list_available(conn): """List nevra strings of available packages.""" inames = conn.AssociatorNames( ObjectName=SystemSoftwareCollection.get_path(), ResultClass='LMI_SoftwareIdentity', AssocClass="LMI_MemberOfSoftwareCollection", Role="Collection", ResultRole="Member") for nevra in (i['InstanceID'] for i in inames): print nevra[len("LMI:LMI_SoftwareIdentity:"):] def list_installed(_conn): """List nevra strings of installed packages.""" raise NotImplementedError( "Listing of installed packages is not yet supported!") def list_files(_conn, _package): """List files of installed package.""" raise NotImplementedError("Listing of package files is not yet supported!") def parse_args(): """ Parse command line arguments and handle related errors. @return Namespace object """ parser = argparse.ArgumentParser(prog='software', description=("CLI tool for testing OpenLMI software providers." " With this tool you are able to install, update," " remove and verify particular package."), conflict_handler="resolve") parser.add_argument('--url', help="Specify schema, hostname and port of broker in one argument." " For user and password, please use provided options.") parser.add_argument('-p', '--port', type=int, default=5989, help="Port of cimom broker. Default is %(default)d.") parser.add_argument('-h', '--hostname', default='localhost', help="Hostname of cimom broker.") parser.add_argument('-s', '--schema', choices=('http', 'https'), default='https', help="Schema part of url (default is %(default)s)") parser.add_argument('-u', '--user', default='', help="Under which user to authenticate.") parser.add_argument('--password', default='', help="User password.") parser.add_argument('-d', '--debug', action='store_true', default=False, help="Print debugging informations.") subpars = parser.add_subparsers(help="Action to make on OpenLMI providers.") parse_install = subpars.add_parser('install', help="Install specific available package.") parse_install.add_argument('nevra', help="Name, epoch, version, release" " and architecture of package to install given as:\n" " name-epoch:version-release.arch") parse_install.set_defaults(command='install') parse_update = subpars.add_parser('update', help="Update a package to specific evra or to the newest available.") parse_update.add_argument('package', help="Name or nevra of installed package.") parse_update.add_argument('-e', '--epoch', type=int, help="Filter available packages for update by epoch.") parse_update.add_argument('-v', '--version', help="Filter available packages for update by version.") parse_update.add_argument('-r', '--release', help="Filter available packages for update by release.") parse_update.set_defaults(command='update') parse_remove = subpars.add_parser('remove', help="Remove installed package.") parse_remove.add_argument('package', help="Name or nevra of installed package.") parse_remove.set_defaults(command='remove') parse_verify = subpars.add_parser('verify', help="Verify installed package.") parse_verify.add_argument('package', help="Name or nevra of installed package to verify.") parse_verify.set_defaults(command='verify') parse_list = subpars.add_parser('list', help="List various information depending on next argument." " See \"%(prog)s list --help\".") parse_list.set_defaults(command='list') list_subpars = parse_list.add_subparsers(help="What should be listed.") parse_list_available = list_subpars.add_parser("available", help="List available packages.") parse_list_available.set_defaults(list_kind='available') parse_list_installed = list_subpars.add_parser("installed", help="List installed packages.") parse_list_installed.set_defaults(list_kind='installed') parse_list_files = list_subpars.add_parser("files", help="List files of installed package.") parse_list_files.set_defaults(list_kind='files') parse_list_files.add_argument('package', help="Name or nevra of installed package.") args = parser.parse_args() if args.url is None: args.url = '%s://%s:%d' % (args.schema, args.hostname, args.port) return args def main(args): """ Main functionality. @return return code of script """ auth = (args.user, args.password) if args.debug: sys.stderr.write('url:\t%s\n'%args.url) conn = pywbem.WBEMConnection(args.url, auth) if args.command == 'list': func, attrs = \ { 'available' : (list_available, tuple()) , 'installed' : (list_installed, tuple()) , 'files' : (list_files, ('package')) }[args.list_kind] else: func, attrs = \ { 'install' : (install, ('nevra',)) , 'update' : (update, ('package', 'epoch', 'version', 'release')) , 'remove' : (remove, ('package',)) , 'verify' : (verify, ('package',)) }[args.command] try: func(conn, *(getattr(args, a) for a in attrs)) return 0 except pywbem.CIMError as exc: sys.stderr.write('Failed: %d (%s) - %s\n' % ( exc.args[0], CIM_ERROR2TEXT[exc.args[0]], exc.args[1].replace('
', '\n'))) return 1 except NotFound as exc: sys.stderr.write(str(exc) + '\n') return 1 if __name__ == '__main__': ARGS = parse_args() sys.exit(main(ARGS))