# Software Management Providers # # Copyright (C) 2012 Red Hat, Inc. All rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """Python Provider for LMI_YumPackage Instruments the CIM class LMI_YumPackage """ import itertools import datetime #import yum import pywbem from pywbem.cim_provider2 import CIMProvider2 from util.common import * pkg2model = YumPackage.pkg2model_wrapper('root/cimv2', "LMI_YumPackage") class LMI_YumPackage(CIMProvider2): """Instrument the CIM class LMI_YumPackage RPM package installed on particular computer system with YUM (The Yellowdog Updated, Modified) package manager. """ def __init__ (self, env): logger = env.get_logger() logger.log_debug('Initializing provider %s from %s' \ % (self.__class__.__name__, __file__)) def get_instance(self, env, model): """Return an instance. Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) model -- A template of the pywbem.CIMInstance to be returned. The key properties are set on this instance to correspond to the instanceName that was requested. The properties of the model are already filtered according to the PropertyList from the request. Only properties present in the model need to be given values. If you prefer, you can set all of the values, and the instance will be filtered for you. Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM Instance does not exist in the specified namespace) CIM_ERR_FAILED (some other unspecified error occurred) """ logger = env.get_logger() logger.log_debug('Entering %s.get_instance()' \ % self.__class__.__name__) pkg = YumPackage.object_path2pkg(env, model.path) return pkg2model(pkg, env, keys_only=False, model=model) def enum_instances(self, env, model, keys_only): """Enumerate instances. The WBEM operations EnumerateInstances and EnumerateInstanceNames are both mapped to this method. This method is a python generator Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) model -- A template of the pywbem.CIMInstances to be generated. The properties of the model are already filtered according to the PropertyList from the request. Only properties present in the model need to be given values. If you prefer, you can always set all of the values, and the instance will be filtered for you. keys_only -- A boolean. True if only the key properties should be set on the generated instances. Possible Errors: CIM_ERR_FAILED (some other unspecified error occurred) """ logger = env.get_logger() logger.log_debug('Entering %s.enum_instances()' \ % self.__class__.__name__) # Prime model.path with knowledge of the keys, so key values on # the CIMInstanceName (model.path) will automatically be set when # we set property values on the model. model.path.update({'TargetOperatingSystem': None, 'Version': None, 'SoftwareElementState': None, 'Name': None, 'SoftwareElementID': None}) with YumDB.getInstance(env) as yb: for pkg in yb.rpmdb: yield pkg2model(pkg, env, keys_only, model) def set_instance(self, env, instance, modify_existing): """Return a newly created or modified instance. Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) instance -- The new pywbem.CIMInstance. If modifying an existing instance, the properties on this instance have been filtered by the PropertyList from the request. modify_existing -- True if ModifyInstance, False if CreateInstance Return the new instance. The keys must be set on the new instance. Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_NOT_SUPPORTED CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only valid if modify_existing is False, indicating that the operation was CreateInstance) CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid if modify_existing is True, indicating that the operation was ModifyInstance) CIM_ERR_FAILED (some other unspecified error occurred) """ logger = env.get_logger() logger.log_debug('Entering %s.set_instance()' \ % self.__class__.__name__) _has_key = lambda k: k in instance.properties or ( instance.path is not None and k in instance.path) def _get_key(k): v = instance.properties.get(k, None) if isinstance(v, pywbem.CIMProperty): return v.value if v is not None: return v logger.log_error('missing key "{}" in inst.props'.format(k)) return instance.path[k] if k in instance.path else None # parse and check arguments if modify_existing is True: raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND, "MofifyInstance is not supported") match_props = {} # args for match_pkg installed_kwargs = {} # args for rpmdb.installed if instance['SoftwareElementID']: m = re_nevra.match(instance['SoftwareElementID']) if not m: raise pywbem.CIMError(pywbem.CIM_ERR_INVALID_PARAMETER, "SoftwareElementID could not be parsed.") match_props['nevra'] = instance['SoftwareElementID'] match_props['name'] = m.group('name') for a in ('name', 'epoch', 'ver', 'rel', 'arch'): installed_kwargs[a] = m.group(a) else: for matchattr, instattr in ( ('name', 'name'), ('epoch', 'epoch'), ('version', 'ver'), ('release', 'rel'), ('arch', 'arch')): if _has_key(matchattr) and _get_key(matchattr): match_props[matchattr] = installed_kwargs[instattr] = \ _get_key(matchattr) if not match_props: raise pywbem.CIMError(pywbem.CIM_ERR_FAILED, "Too few key values given (give at least a Name).") if not 'name' in match_props and not 'nevra' in match_props: raise pywbem.CIMError(pywbem.CIM_ERR_FAILED, "Missing either Name or SoftwareElementID property.") with YumDB.getInstance(env) as yb: # check already installed if yb.rpmdb.installed(**installed_kwargs): raise pywbem.CIMError(pywbem.CIM_ERR_ALREADY_EXISTS, "Package is already installed.") # get available packages pl = yb.doPackageLists('available', showdups=True) exact, matched, unmatched = yum.packages.parsePackages( pl.available, [match_props['name']]) exact_orig = exact exact = sorted( [ p for p in exact if match_pkg(p, **match_props) ] , key=lambda a: a.evra) if len(exact) == 0: logger.log_error('could not find any package for query: {}' ' in list: {}' .format(match_props, [p.nevra for p in exact_orig])) raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND, "No matching package found.") if len(exact) > 1: logger.log_info('found multiple matching packages' ' for query: {}'.format(match_props)) pkg = exact[-1] # select highest version else: logger.log_debug('exact match found for query: {}' .format(match_props)) pkg = exact[0] logger.log_info('installing package {}'.format(pkg.nevra)) # install yb.install(pkg) yb.buildTransaction() yb.processTransaction() logger.log_info('package installed'.format(pkg.nevra)) # return instance instance = pkg2model(pkg, env, True, instance) return self.get_instance(env, instance) def delete_instance(self, env, instance_name): """Delete an instance. Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) instance_name -- A pywbem.CIMInstanceName specifying the instance to delete. Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_NOT_SUPPORTED CIM_ERR_INVALID_NAMESPACE CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_INVALID_CLASS (the CIM Class does not exist in the specified namespace) CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM Instance does not exist in the specified namespace) CIM_ERR_FAILED (some other unspecified error occurred) """ logger = env.get_logger() logger.log_debug('Entering %s.delete_instance()' \ % self.__class__.__name__) with YumDB.getInstance(env) as yb: pkg = YumPackage.object_path2pkg(env, instance_name) logger.log_info('removing package "%s"' % pkg.nevra) yb.remove(pkg) yb.buildTransaction() yb.processTransaction() logger.log_info('package "%s" removed' % pkg.nevra) def cim_method_checkintegrity(self, env, object_name): """Implements LMI_YumPackage.CheckIntegrity() Verify existence and attributes of files installed from RPM package. If all files installed exist and their attributes matches, method returns "Pass". "Not passed" is returned when arbitrary file differs in its attributes. And "Error" if verification could not be done. Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName specifying the object on which the method CheckIntegrity() should be invoked. Returns a two-tuple containing the return value (type pywbem.Uint32 self.Values.CheckIntegrity) and a list of CIMParameter objects representing the output parameters Output parameters: Failed -- (type REF (pywbem.CIMInstanceName(classname='LMI_YumFileCheck', ...)) Array of references to LMI_YumFileCheck, that did not pass verification. Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_NOT_FOUND (the target CIM Class or instance does not exist in the specified namespace) CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor the invocation request) CIM_ERR_FAILED (some other unspecified error occurred) """ logger = env.get_logger() logger.log_debug('Entering %s.cim_method_checkintegrity()' \ % self.__class__.__name__) # TODO do something raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented out_params = [] #out_params+= [pywbem.CIMParameter('failed', type='reference', # value=[pywbem.CIMInstanceName(classname='LMI_YumFileCheck', ...),])] # TODO #rval = # TODO (type pywbem.Uint32 self.Values.CheckIntegrity) return (rval, out_params) def cim_method_update(self, env, object_name, param_epoch=None, param_release=None, param_version=None): """Implements LMI_YumPackage.Update() Updates the package to latest version. When any of "version" or "release" argument is given, install only matching available package. Otherwise try to update to newest package available. Keyword arguments: env -- Provider Environment (pycimmb.ProviderEnvironment) object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName specifying the object on which the method Update() should be invoked. param_release -- The input parameter release (type unicode) Specify particular release of package to update to. Update to newest, when empty param_version -- The input parameter version (type unicode) Specify particular version of package to update to. Update to newest, when empty Returns a two-tuple containing the return value (type pywbem.Uint16 self.Values.Update) and a list of CIMParameter objects representing the output parameters Output parameters: Installed -- (type REF (pywbem.CIMInstanceName(classname='LMI_YumPackage', ...)) The reference to newly installed package, if installation was successful. Otherwise reference to current package. Possible Errors: CIM_ERR_ACCESS_DENIED CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized or otherwise incorrect parameters) CIM_ERR_NOT_FOUND (the target CIM Class or instance does not exist in the specified namespace) CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor the invocation request) CIM_ERR_FAILED (some other unspecified error occurred) """ logger = env.get_logger() logger.log_debug('Entering %s.cim_method_update()' \ % self.__class__.__name__) with YumDB.getInstance(env) as yb: orig = YumPackage.object_path2pkg(env, object_name) evr_str = [] for name, param in ( ('epoch', param_epoch), ('version', param_version), ('release', param_release)): evr_str.append("%s(%s)"%(name,param)) if len(evr_str): evr_str = "specific "+'-'.join(evr_str) else: evr_str = "the newest version-release" logger.log_info('trying to update to %s of package \"%s\"' % (evr_str, object_name["Name"])) pl = yb.doPackageLists('all', showdups=True) exact, matched, unmatched = yum.packages.parsePackages( itertools.chain(pl.available, pl.installed), [orig.name]) exact = sorted(exact, key=lambda a:a.evra) try: pkg = [p for p in exact if (not param_epoch or param_epoch == p.epoch) and (not param_version or param_version == p.ver) and (not param_release or param_release == p.rel)] [-1] except IndexError: logger.log_error( 'could not find any matching available package') raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND) out_params = [pywbem.CIMParameter('Installed', type='reference', value=pkg2model(pkg, env, True))] if orig.evra == pkg.evra: logger.log_info('already up to date') return (self.Values.Update.Already_newest, out_params) yb.update(update_to=True, name=pkg.name, epoch=pkg.epoch, version=pkg.version, release=pkg.release) yb.buildTransaction() yb.processTransaction() logger.log_info('package {} updated to: {}'.format( orig.name, pkg.evra)) return (self.Values.Update.Successful_installation, out_params) class Values(object): class DetailedStatus(object): Not_Available = pywbem.Uint16(0) No_Additional_Information = pywbem.Uint16(1) Stressed = pywbem.Uint16(2) Predictive_Failure = pywbem.Uint16(3) Non_Recoverable_Error = pywbem.Uint16(4) Supporting_Entity_in_Error = pywbem.Uint16(5) # DMTF_Reserved = .. # Vendor_Reserved = 0x8000.. class Status(object): OK = 'OK' Error = 'Error' Degraded = 'Degraded' Unknown = 'Unknown' Pred_Fail = 'Pred Fail' Starting = 'Starting' Stopping = 'Stopping' Service = 'Service' Stressed = 'Stressed' NonRecover = 'NonRecover' No_Contact = 'No Contact' Lost_Comm = 'Lost Comm' Stopped = 'Stopped' class HealthState(object): Unknown = pywbem.Uint16(0) OK = pywbem.Uint16(5) Degraded_Warning = pywbem.Uint16(10) Minor_failure = pywbem.Uint16(15) Major_failure = pywbem.Uint16(20) Critical_failure = pywbem.Uint16(25) Non_recoverable_error = pywbem.Uint16(30) # DMTF_Reserved = .. # Vendor_Specific = 32768..65535 class TargetOperatingSystem(object): Unknown = pywbem.Uint16(0) Other = pywbem.Uint16(1) MACOS = pywbem.Uint16(2) ATTUNIX = pywbem.Uint16(3) DGUX = pywbem.Uint16(4) DECNT = pywbem.Uint16(5) Tru64_UNIX = pywbem.Uint16(6) OpenVMS = pywbem.Uint16(7) HPUX = pywbem.Uint16(8) AIX = pywbem.Uint16(9) MVS = pywbem.Uint16(10) OS400 = pywbem.Uint16(11) OS_2 = pywbem.Uint16(12) JavaVM = pywbem.Uint16(13) MSDOS = pywbem.Uint16(14) WIN3x = pywbem.Uint16(15) WIN95 = pywbem.Uint16(16) WIN98 = pywbem.Uint16(17) WINNT = pywbem.Uint16(18) WINCE = pywbem.Uint16(19) NCR3000 = pywbem.Uint16(20) NetWare = pywbem.Uint16(21) OSF = pywbem.Uint16(22) DC_OS = pywbem.Uint16(23) Reliant_UNIX = pywbem.Uint16(24) SCO_UnixWare = pywbem.Uint16(25) SCO_OpenServer = pywbem.Uint16(26) Sequent = pywbem.Uint16(27) IRIX = pywbem.Uint16(28) Solaris = pywbem.Uint16(29) SunOS = pywbem.Uint16(30) U6000 = pywbem.Uint16(31) ASERIES = pywbem.Uint16(32) HP_NonStop_OS = pywbem.Uint16(33) HP_NonStop_OSS = pywbem.Uint16(34) BS2000 = pywbem.Uint16(35) LINUX = pywbem.Uint16(36) Lynx = pywbem.Uint16(37) XENIX = pywbem.Uint16(38) VM = pywbem.Uint16(39) Interactive_UNIX = pywbem.Uint16(40) BSDUNIX = pywbem.Uint16(41) FreeBSD = pywbem.Uint16(42) NetBSD = pywbem.Uint16(43) GNU_Hurd = pywbem.Uint16(44) OS9 = pywbem.Uint16(45) MACH_Kernel = pywbem.Uint16(46) Inferno = pywbem.Uint16(47) QNX = pywbem.Uint16(48) EPOC = pywbem.Uint16(49) IxWorks = pywbem.Uint16(50) VxWorks = pywbem.Uint16(51) MiNT = pywbem.Uint16(52) BeOS = pywbem.Uint16(53) HP_MPE = pywbem.Uint16(54) NextStep = pywbem.Uint16(55) PalmPilot = pywbem.Uint16(56) Rhapsody = pywbem.Uint16(57) Windows_2000 = pywbem.Uint16(58) Dedicated = pywbem.Uint16(59) OS_390 = pywbem.Uint16(60) VSE = pywbem.Uint16(61) TPF = pywbem.Uint16(62) Windows__R__Me = pywbem.Uint16(63) Caldera_Open_UNIX = pywbem.Uint16(64) OpenBSD = pywbem.Uint16(65) Not_Applicable = pywbem.Uint16(66) Windows_XP = pywbem.Uint16(67) z_OS = pywbem.Uint16(68) Microsoft_Windows_Server_2003 = pywbem.Uint16(69) Microsoft_Windows_Server_2003_64_Bit = pywbem.Uint16(70) Windows_XP_64_Bit = pywbem.Uint16(71) Windows_XP_Embedded = pywbem.Uint16(72) Windows_Vista = pywbem.Uint16(73) Windows_Vista_64_Bit = pywbem.Uint16(74) Windows_Embedded_for_Point_of_Service = pywbem.Uint16(75) Microsoft_Windows_Server_2008 = pywbem.Uint16(76) Microsoft_Windows_Server_2008_64_Bit = pywbem.Uint16(77) FreeBSD_64_Bit = pywbem.Uint16(78) RedHat_Enterprise_Linux = pywbem.Uint16(79) RedHat_Enterprise_Linux_64_Bit = pywbem.Uint16(80) Solaris_64_Bit = pywbem.Uint16(81) SUSE = pywbem.Uint16(82) SUSE_64_Bit = pywbem.Uint16(83) SLES = pywbem.Uint16(84) SLES_64_Bit = pywbem.Uint16(85) Novell_OES = pywbem.Uint16(86) Novell_Linux_Desktop = pywbem.Uint16(87) Sun_Java_Desktop_System = pywbem.Uint16(88) Mandriva = pywbem.Uint16(89) Mandriva_64_Bit = pywbem.Uint16(90) TurboLinux = pywbem.Uint16(91) TurboLinux_64_Bit = pywbem.Uint16(92) Ubuntu = pywbem.Uint16(93) Ubuntu_64_Bit = pywbem.Uint16(94) Debian = pywbem.Uint16(95) Debian_64_Bit = pywbem.Uint16(96) Linux_2_4_x = pywbem.Uint16(97) Linux_2_4_x_64_Bit = pywbem.Uint16(98) Linux_2_6_x = pywbem.Uint16(99) Linux_2_6_x_64_Bit = pywbem.Uint16(100) Linux_64_Bit = pywbem.Uint16(101) Other_64_Bit = pywbem.Uint16(102) Microsoft_Windows_Server_2008_R2 = pywbem.Uint16(103) VMware_ESXi = pywbem.Uint16(104) Microsoft_Windows_7 = pywbem.Uint16(105) CentOS_32_bit = pywbem.Uint16(106) CentOS_64_bit = pywbem.Uint16(107) Oracle_Enterprise_Linux_32_bit = pywbem.Uint16(108) Oracle_Enterprise_Linux_64_bit = pywbem.Uint16(109) eComStation_32_bitx = pywbem.Uint16(110) class Update(object): Already_newest = pywbem.Uint16(0) Successful_installation = pywbem.Uint16(1) Failed = pywbem.Uint16(2) class CommunicationStatus(object): Unknown = pywbem.Uint16(0) Not_Available = pywbem.Uint16(1) Communication_OK = pywbem.Uint16(2) Lost_Communication = pywbem.Uint16(3) No_Contact = pywbem.Uint16(4) # DMTF_Reserved = .. # Vendor_Reserved = 0x8000.. class OperationalStatus(object): Unknown = pywbem.Uint16(0) Other = pywbem.Uint16(1) OK = pywbem.Uint16(2) Degraded = pywbem.Uint16(3) Stressed = pywbem.Uint16(4) Predictive_Failure = pywbem.Uint16(5) Error = pywbem.Uint16(6) Non_Recoverable_Error = pywbem.Uint16(7) Starting = pywbem.Uint16(8) Stopping = pywbem.Uint16(9) Stopped = pywbem.Uint16(10) In_Service = pywbem.Uint16(11) No_Contact = pywbem.Uint16(12) Lost_Communication = pywbem.Uint16(13) Aborted = pywbem.Uint16(14) Dormant = pywbem.Uint16(15) Supporting_Entity_in_Error = pywbem.Uint16(16) Completed = pywbem.Uint16(17) Power_Mode = pywbem.Uint16(18) Relocating = pywbem.Uint16(19) # DMTF_Reserved = .. # Vendor_Reserved = 0x8000.. class OperatingStatus(object): Unknown = pywbem.Uint16(0) Not_Available = pywbem.Uint16(1) Servicing = pywbem.Uint16(2) Starting = pywbem.Uint16(3) Stopping = pywbem.Uint16(4) Stopped = pywbem.Uint16(5) Aborted = pywbem.Uint16(6) Dormant = pywbem.Uint16(7) Completed = pywbem.Uint16(8) Migrating = pywbem.Uint16(9) Emigrating = pywbem.Uint16(10) Immigrating = pywbem.Uint16(11) Snapshotting = pywbem.Uint16(12) Shutting_Down = pywbem.Uint16(13) In_Test = pywbem.Uint16(14) Transitioning = pywbem.Uint16(15) In_Service = pywbem.Uint16(16) # DMTF_Reserved = .. # Vendor_Reserved = 0x8000.. class SoftwareElementState(object): Deployable = pywbem.Uint16(0) Installable = pywbem.Uint16(1) Executable = pywbem.Uint16(2) Running = pywbem.Uint16(3) class PrimaryStatus(object): Unknown = pywbem.Uint16(0) OK = pywbem.Uint16(1) Degraded = pywbem.Uint16(2) Error = pywbem.Uint16(3) # DMTF_Reserved = .. # Vendor_Reserved = 0x8000.. class CheckIntegrity(object): Pass = pywbem.Uint32(0) Not_passed = pywbem.Uint32(1) Error = pywbem.Uint32(2) ## end of class LMI_YumPackageProvider ## get_providers() for associating CIM Class Name to python provider class name def get_providers(env): lmi_yumpackage_prov = LMI_YumPackage(env) return {'LMI_YumPackage': lmi_yumpackage_prov}