def str2device(ns, device): """ Convert string with name of device to LMIInstance of the device. If LMIInstance is provided, nothing is done and the instance is just returned. If string is given, appropriate LMIInstance is looked up and returned. This functions throws an error when the device cannot be found. The main purpose of this function is to convert parameters in functions, where both string and LMIInstance is allowed. :type device: LMIInstance/CIM_StorageExtent or string with name of device :param device: Device to convert. :rtype: LMIInstance/CIM_StorageExtent """ if isinstance(device, LMIInstance): return device if not isinstance(device, str): raise TypeError("string or LMIInstance expected, got %s" % device.__class__.__name__) query = 'SELECT * FROM CIM_StorageExtent WHERE ' \ 'DeviceID="%(device)s" ' \ 'OR Name="%(device)s" ' \ 'OR ElementName="%(device)s"' % {'device': escape_cql(device)} devices = ns.wql(query) if not devices: raise LmiFailed("Device '%s' not found" % (device, )) if len(devices) > 1: raise LmiFailed("Too many devices with name '%s' found" % (device, )) LOG().debug("String %s translated to device '%s'.", device, devices[0].DeviceID) return devices[0]
def create_raid(ns, devices, level, name=None): """ Create new MD RAID device. :type devices: list of LMIInstance/CIM_StorageExtent or list of strings :param device: Devices to add to the RAID. :type level: int :param level: RAID level. :type name: string :param name: RAID name. :rtype: LMIInstance/LMI_MDRAIDStorageExtent """ devs = [common.str2device(ns, device) for device in devices] args = {'InExtents': devs, 'Level': level} if name: args['ElementName'] = name service = ns.LMI_StorageConfigurationService.first_instance() (ret, outparams, err) = service.SyncCreateOrModifyMDRAID(**args) if ret != 0: if err: raise LmiFailed("Cannot create the partition: %s." % err) values = service.CreateOrModifyMDRAID.CreateOrModifyMDRAIDValues raise LmiFailed("Cannot create the partition: %s." % (values.value_name(ret), )) return outparams['TheElement']
def str2vg(ns, vg): """ Convert string with name of volume group to LMIInstance of the LMI_VGStoragePool. If LMIInstance is provided, nothing is done and the instance is just returned. If string is provided, appropriate LMIInstance is looked up and returned. This functions throws an error when the device cannot be found. The main purpose of this function is to convert parameters in functions, where both string and LMIInstance is allowed. :type vg: LMIInstance/LMI_VGStoragePool or string :param vg: VG to retrieve. :rtype: LMIInstance/LMI_VGStoragePool """ if isinstance(vg, LMIInstance): return vg if not isinstance(vg, str): raise TypeError("string or LMIInstance expected, got %s" % vg.__class__.__name__) query = 'SELECT * FROM LMI_VGStoragePool WHERE ElementName="%(vg)s"' \ % {'vg': escape_cql(vg)} vgs = ns.wql(query) if not vgs: raise LmiFailed("Volume Group '%s' not found" % (vg, )) if len(vgs) > 1: raise LmiFailed("Too many volume groups with name '%s' found" % (vg, )) LOG().debug("String %s translated to Volume Group '%s'", vg, vgs[0].InstanceID) return vgs[0]
def set_local_rtc(ns, value, fix_system): """ Set whether the RTC is maintained in local time/UTC. :param bool value: True/False for RTC maintained in localtime/UTC. :param bool fix_system: If set, the time is read again from the RTC and the system clock adjusted according to the new setting. """ inst = get_locale(ns) (rval, _, errorstr) = inst.SetLocalRTC( LocalRTC=value, FixSystem=fix_system, ) if rval != 0: if errorstr: raise LmiFailed("Cannot enable/disable NTP: %s.", errorstr) raise LmiFailed("Cannot enable/disable NTP.") if value: LOG().info("RTC is maintained in local time.") else: LOG().info("RTC is maintained in UTC.") if fix_system: LOG().info("The time was read again from the RTC and the system " "clock adjusted according to the new setting.")
def watch(ns): """ Sets up a new indication listener and waits for events. """ indication_port = random.randint(12000, 13000) listener = LMIIndicationListener("0.0.0.0", indication_port) uniquename = listener.add_handler("lmiscript_journald_watch-XXXXXXXX", ind_handler) ret = listener.start() if not ret: raise LmiFailed("Cannot initialize indication listener on port %d" % indication_port) ret = ns.connection.subscribe_indication( Name=uniquename, Query= "SELECT * FROM LMI_JournalLogRecordInstanceCreationIndication WHERE SOURCEINSTANCE ISA LMI_JournalLogRecord", Destination="http://%s:%d" % (socket.gethostname(), indication_port)) if not ret or not ret.rval: raise LmiFailed("Failed to register indication: %s\n" % retval.errorstr) try: LOG().info("Watching journal, press Ctrl+C to abort\n") while True: time.sleep(1) pass except KeyboardInterrupt: pass ns.connection.unsubscribe_indication(uniquename) return 0
def list_services(ns, kind='enabled'): """ List services. Yields service instances. :param string kind: What kind of services to list. Possible options are: * 'enabled' - list only enabled services * 'disabled' - list only disabled services * 'all' - list all services :returns: Instances of ``LMI_Service``. :rtype: generator over :py:class:`lmi.shell.LMIInstance`. """ if not isinstance(kind, basestring): raise TypeError("kind must be a string") if not kind in SERVICE_KINDS: raise ValueError("kind must be one of %s" % SERVICE_KINDS) try: for service in sorted(ns.LMI_Service.instances(client_filtering=True), key=lambda i: i.Name): if kind == 'disabled' and service.EnabledDefault != \ ns.LMI_Service.EnabledDefaultValues.Disabled: continue if kind == 'enabled' and service.EnabledDefault != \ ns.LMI_Service.EnabledDefaultValues.Enabled: # list only enabled continue yield service except wbem.CIMError as err: if err.args[0] == wbem.CIM_ERR_NOT_SUPPORTED: raise LmiFailed('Service provider is not installed or registered.') raise LmiFailed('Failed to list services: %s' % err.args[1])
def create_lv(ns, vg, name, size): """ Create new Logical Volume on given Volume Group. :type vg: LMIInstance/LMI_VGStoragePool or string :param vg: Volume Group to allocate the volume from. :type name: string :param name: Name of the logical volume. :type size: int :param size: Size of the logical volume in bytes. :rtype: LMIInstance/LMI_LVStorageExtent """ vg = common.str2vg(ns, vg) service = ns.LMI_StorageConfigurationService.first_instance() (ret, outparams, err) = service.SyncCreateOrModifyLV(ElementName=name, Size=size, InPool=vg) if ret != 0: if err: raise LmiFailed("Cannot create the logical volume: %s." % err) values = service.CreateOrModifyLV.CreateOrModifyLVValues raise LmiFailed("Cannot create the logical volume: %s." % (values.value_name(ret), )) lv = outparams['TheElement'].to_instance() LOG().info("Created logical volume %s", lv.Name) return lv
def mount_delete(ns, target): """ Unmount filesystem. :type target: string :param target: device path or mountpoint """ # Try to convert device name to full device path try: device_inst = common.str2device(ns, target) if device_inst: target = device_inst.Name except LmiFailed: # we did not find CIM_StorageExtent for the device, it must be non # device filesystem specification pass mnt = ns.LMI_MountedFileSystem.first_instance({'FileSystemSpec':target}) or \ ns.LMI_MountedFileSystem.first_instance({'MountPointPath':target}) if mnt is None: raise LmiFailed('Target is not mounted: %s.' % target) service = ns.LMI_MountConfigurationService.first_instance() # TODO for now # Mode 32769 == only unmount (don't remove any persistent info) (ret, _outparams, _err) = service.SyncDeleteMount(Mount=mnt, Mode=32769) if ret != 0: raise LmiFailed('Cannot delete mount: %s.' % target) LOG().info('Successfully deleted mount: %s', target)
def create_luks(ns, device, passphrase): """ Format given device with LUKS encryption format. All data on the device will be deleted! Encryption key and algorithm will be chosen automatically. :type device: LMIInstance/CIM_StorageExtent or string :param device: Device to format with LUKS data :type passphrase: string :param passphrase: Password to open the encrypted data. This is not the encryption key. :rtype: LMIInstance/LMI_EncryptionFormat """ device = common.str2device(ns, device) service = ns.LMI_ExtentEncryptionConfigurationService.first_instance() (ret, outparams, err) = service.SyncCreateEncryptionFormat(InExtent=device, Passphrase=passphrase) if ret != 0: if err: raise LmiFailed("Cannot create LUKS format: %s." % err) values = service.CreateEncryptionFormat.CreateEncryptionFormatValues raise LmiFailed("Cannot create LUKS format: %s." % (values.value_name(ret), )) LOG().info("Created LUKS on %s", device.Name) return outparams['Format']
def open_luks(ns, fmt, name, passphrase): """ Open encrypted LUKS format and expose it as a clear-text block device. :type fmt: LMIInstance/LMI_EncryptionFormat or string :param fmt: The LUKS format to open. :type name: string :param name: Requested name of the clear-text block device. It will be available as /dev/mapper/<name>. :type passphrase: string :param passphrase: Password to open the encrypted data. :rtype: LMIInstance/LMI_LUKSStorageExtent :returns: The block device with clear-text data. """ fmt = fs.str2format(ns, fmt) service = ns.LMI_ExtentEncryptionConfigurationService.first_instance() (ret, outparams, err) = service.SyncOpenEncryptionFormat(Format=fmt, ElementName=name, Passphrase=passphrase) if ret != 0: if err: raise LmiFailed("Cannot open LUKS format: %s." % err) values = service.OpenEncryptionFormat.OpenEncryptionFormatValues raise LmiFailed("Cannot open LUKS format: %s." % (values.value_name(ret), )) opened = outparams['Extent'].to_instance() LOG().info("Opened LUKS on %s as %s", fmt.ElementName, opened.Name) return opened
def add_luks_passphrase(ns, fmt, passphrase, new_passphrase): """ Adds new password to LUKS format. Each format can have up to 8 separate passwords and any of them can be used to open(decrypt) the format. Any existing passphrase must be provided to add a new one. This proves the caller is authorized to add new passphrase (because it already knows one) and also this 'old' passphrase is used to retrieve encryption keys. This 'old' passphrase is not removed nor replaced when adding new passphrase! :type fmt: LMIInstance/LMI_EncryptionFormat or string :param fmt: The LUKS format to modify. :type passphrase: string :param passphrase: Existing LUKS passphrase. :type new_passphrase: string :param new_passphrase: New passphrase to add to the format. """ fmt = fs.str2format(ns, fmt) service = ns.LMI_ExtentEncryptionConfigurationService.first_instance() (ret, outparams, err) = service.AddPassphrase(Format=fmt, Passphrase=passphrase, NewPassphrase=new_passphrase) if ret != 0: if err: raise LmiFailed("Cannot add new passphrase: %s." % err) values = service.AddPassphrase.AddPassphraseValues raise LmiFailed("Cannot add new passphrase: %s." % (values.value_name(ret), )) LOG().info("Added passphrase to %s", fmt.ElementName)
def create_group(ns, group, reserved=False, gid=None): """ Create a new group on the system. :type group: string :param group: Name of the group. :type reserved: boolean :param reserved: Whether the group is a system one (its GID will be allocated lower than system-defined threshold). :type gid: int :param gid: Required GID. It will be allocated automatically if it's None. :rtype: LMIInstanceName of the created group. :returns: Created group. """ cs = lmi.scripts.common.get_computer_system(ns) lams = ns.LMI_AccountManagementService.first_instance() params = {"Name": group, "System": cs} if reserved: params["SystemAccount"] = True if gid is not None: params["GID"] = int(gid) LOG().debug("Creating group %s with arguments %s", group, str(params)) (ret, outparams, err) = lams.CreateGroup(**params) if ret != 0: if err: raise LmiFailed("Cannot create the group: %s." % err) values = lams.CreateGroup.CreateGroupValues raise LmiFailed("Cannot create the group: %s." % (values.value_name(ret), )) return outparams['Group']
def deactivate(ns, setting, device=None): ''' Deactivate network setting. :param LMI_IPAssignmentSettingData setting: Setting to deactivate. :param device: Device to deactivate the setting on :type device: LMI_IPNetworkConnection or None ''' service = ns.LMI_IPConfigurationService.first_instance() if device is not None: LOG().debug('Deactivating setting %s on device %s', setting.Caption, device.ElementName) result = service.SyncApplySettingToIPNetworkConnection( SettingData=setting, IPNetworkConnection=device, Mode=service.ApplySettingToIPNetworkConnection.ModeValues.Mode32769 ) if result.errorstr: raise LmiFailed("Unable to deactivate setting: %s" % result.errorstr) else: result = service.SyncApplySettingToIPNetworkConnection( SettingData=setting, Mode=service.ApplySettingToIPNetworkConnection.ModeValues.Mode32769 ) if result.errorstr: raise LmiFailed("Unable to deactivate setting: %s" % result.errorstr) return 0
def create_partition_table(ns, device, table_type): """ Create new partition table on a device. The device must be empty, i.e. must not have any partitions on it. :type device: LMIInstance/CIM_StorageExtent :param device: Device where the partition table should be created. :type table_type: int :param table_type: Requested partition table type. See PARTITION_TABLE_TYPE_xxx variables. """ device = common.str2device(ns, device) query = "SELECT * FROM LMI_DiskPartitionConfigurationCapabilities WHERE " \ "PartitionStyle=%d" % table_type caps = ns.wql(query) if not caps: raise LmiFailed("Unsupported partition table type: %d" % table_type) cap = caps[0] service = ns.LMI_DiskPartitionConfigurationService.first_instance() (ret, _outparams, err) = service.SetPartitionStyle(Extent=device, PartitionStyle=cap) if ret != 0: if err: raise LmiFailed("Cannot create partition table: %s." % err) values = service.SetPartitionStyle.SetPartitionStyleValues raise LmiFailed("Cannot create partition table: %s." % (values.value_name(ret))) LOG().info("Created partition table on %s", device.Name)
def lf_list(ns, directory, depth=None): """ List all files in a directory. If depth is positive, directory is walked recursively up to the given depth. :type directory: string :param directory: Full path to the directory. :type depth: integer :param depth: Maximum depth to be recursed to. """ if directory != '/': directory = directory.rstrip('/') try: d = get_directory_instance(ns, directory) except: raise LmiFailed("Can't list directory: %s" % directory) if depth: try: depth = int(depth) except ValueError: raise LmiFailed("Depth must be integer.") else: depth = 0 for (f, lvl) in walk_cim_directory(d, depth): rwx = '' rwx += 'r' if f.Readable else '-' rwx += 'w' if f.Writeable else '-' rwx += 'x' if f.Executable else '-' prefix = ' ' * (depth-lvl) ident = f.associators(AssocClass='LMI_FileIdentity')[0] yield(get_file_identification(f), prefix+f.Name, rwx, ident.SELinuxCurrentContext)
def get_setting_from_opts(ns, options, other_options): """ Create a setting instance from option strings. :type options: string of comma-separated options :type other_options: string of comma-separated options :rtype: an instance of LMI_MountedFileSystemSetting """ cap = ns.LMI_MountedFileSystemCapabilities.first_instance() (ret, outparams, _err) = cap.CreateSetting() if ret != 0: raise LmiFailed('Could not create setting') setting = outparams['setting'].to_instance() if other_options is not None: setting.OtherOptions = other_options.split(',') if options is None: return setting for opt_pair in options.split(','): opts = map(lambda o: o.strip(), opt_pair.split(':')) # bail out if the option is not in 'Option:Value' format # or if the Option is not in supported options if len(opts) != 2 or opts[0] not in _OPTS: raise LmiFailed('Invalid option: %s' % opt_pair) # ignore OtherOptions, there is a separate cmdline option for it if opts[0] == 'OtherOptions': continue # insist on using a number with FileSystemCheckOrder if opts[0] == 'FileSystemCheckOrder': if not opts[1].isdigit(): raise LmiFailed( 'Value of FileSystemCheckOrder must be a number') opts[1] = int(opts[1]) else: # otherwise check for true/false possibilities opts[1] = opts[1].lower() if opts[1] not in ['t', 'true', 'f', 'false']: raise LmiFailed('Invalid option value: %s' % opts[1]) # sanitize the boolean option values if opts[1] in ['t', 'true']: opts[1] = True else: opts[1] = False setattr(setting, opts[0], opts[1]) return setting
def create_vg(ns, devices, name, extent_size=None): """ Create new Volume Group from given devices. :type devices: list of LMIInstance/CIM_StorageExtent or list of strings :param device: Devices to add to the Volume Group. :type name: string :param name: Name of the Volume gGoup. :type extent_size: int :param extent_size: Extent size in bytes. :rtype: LMIInstance/LMI_VGStoragePool """ devs = [common.str2device(ns, device) for device in devices] args = {'InExtents': devs, 'ElementName': name} goal = None try: if extent_size: # create (and use) VGStorageSetting caps = ns.LMI_VGStorageCapabilities.first_instance() (ret, outparams, err) = caps.CreateVGStorageSetting(InExtents=devs) if ret != 0: if err: raise LmiFailed("Cannot create setting for the volume " \ "group: %s." % err) vals = caps.CreateVGStorageSetting.CreateVGStorageSettingValues raise LmiFailed("Cannot create setting for the volume group:" \ " %s." % (vals.value_name(ret),)) goal = outparams['Setting'] goal = goal.to_instance() goal.ExtentSize = extent_size (ret, outparams, err) = goal.push() if ret != 0: if err: raise LmiFailed("Cannot modify setting for the volume " \ "group: %s." % err) raise LmiFailed("Cannot modify setting for the volume group:" \ " %d." % ret) args['Goal'] = goal service = ns.LMI_StorageConfigurationService.first_instance() (ret, outparams, err) = service.SyncCreateOrModifyVG(**args) if ret != 0: values = service.CreateOrModifyVG.CreateOrModifyVGValues raise LmiFailed("Cannot create the volume group: %s." % (values.value_name(ret), )) finally: if goal: goal.delete() pool = outparams['Pool'].to_instance() LOG().info("Created volume group %s", pool.Name) return pool
def list_messages(ns, reverse=False, tail=False): """ List messages from the journal. :param boolean reverse: List messages from newest to oldest. :param boolean tail: List only the last 50 messages """ inst = ns.LMI_JournalMessageLog.first_instance() if not inst: raise LmiFailed( "Cannot initialize Journald provider. (hint: check if it's installed)" ) if reverse or tail: r = inst.PositionToLastRecord() else: r = inst.PositionToFirstRecord() if not 'IterationIdentifier' in r.rparams: raise LmiFailed( "Cannot initialize Journald iteration. (hint: check SELinux AVCs)") iter_id = r.rparams['IterationIdentifier'] if tail: r = inst.PositionAtRecord(IterationIdentifier=iter_id, MoveAbsolute=False, RecordNumber=-NUM_TAIL) iter_id = r.rparams['IterationIdentifier'] try: while True: r = inst.GetRecord(IterationIdentifier=iter_id, PositionToNext=(not reverse)) if r.rval != 0: break iter_id = r.rparams['IterationIdentifier'] if reverse: x = inst.PositionAtRecord(IterationIdentifier=iter_id, MoveAbsolute=False, RecordNumber=-1) iter_id = x.rparams['IterationIdentifier'] print "".join(map(chr, r.rparams['RecordData'])) except KeyboardInterrupt: pass inst.CancelIteration(IterationIdentifier=iter_id) return 0
def mount_create(ns, device, mountpoint, fs_type=None, options=None): """ Create a mounted filesystem. :type device: string or LMIInstance/CIM_StorageExtent :param device: Device to mount or a mount specifier (like '//server/share' for CIFS). :type mountpoint: string :param mountpoint: path where device should be mounted :type fs_type: string :param fs_type: filesystem type :type options: string :param options: comma-separated string of mount options """ # Try to convert device name to full device path try: device_inst = common.str2device(ns, device) if device_inst: device = device_inst.Name except LmiFailed: # we did not find CIM_StorageExtent for the device, it must be non # device filesystem specification pass fs_setting = ns.LMI_FileSystemSetting.first_instance( {'InstanceID': 'LMI:LMI_FileSystemSetting:' + device}) if fs_setting is None: raise LmiFailed('Wrong device: %s' % device) filesystem = fs_setting.associators()[0] if fs_type is None: fs_type = filesystem.FileSystemType service = ns.LMI_MountConfigurationService.first_instance() setting = get_setting_from_opts(ns, options) setting.push() # TODO for now # Mode 32768 == only mount (don't create any persistent info) (ret, _outparams, _err) = service.SyncCreateMount(Goal=setting.path, FileSystemType=fs_type, Mode=32768, FileSystem=filesystem.path, MountPoint=mountpoint, FileSystemSpec=device) msg = '%s on %s' % (device, mountpoint) if ret != 0: raise LmiFailed('Cannot create mount: %s: %s' % (msg, _err)) LOG().info('Successfully created mount: %s', msg)
def get_service(ns, service): """ Return :py:class:`lmi.shell.LMIInstance` object matching the given service name. :param string service: Service name. """ try: if isinstance(service, basestring): if not service.endswith('.service'): service += '.service' cs = get_computer_system(ns) iname = ns.LMI_Service.new_instance_name({ "Name": service, "CreationClassName": "LMI_Service", "SystemName": cs.Name, "SystemCreationClassName": cs.CreationClassName }) inst = iname.to_instance() elif isinstance(service, (LMIInstance, LMIInstanceName)): try: inst = service service = inst.Name if isinstance(inst, LMIInstanceName): inst = inst.to_instance() except AttributeError: raise ValueError('Invalid service instance name. It\'s missing' ' Name property.') else: raise TypeError( "service must be either string or ``LMIInstanceName``") except wbem.CIMError as err: if err.args[0] == wbem.CIM_ERR_NOT_FOUND: raise LmiFailed('No such service "%s".' % service) else: raise LmiFailed('Failed to get service "%s": %s' % (service, err.args[1])) if inst is None: raise LmiFailed('No such service "%s".' % service) return inst
def delete_vg(ns, vg): """ Destroy given Volume Group. :type vg: LMIInstance/LMI_VGStoragePool or string :param vg: Volume Group to delete. """ vg = common.str2vg(ns, vg) service = ns.LMI_StorageConfigurationService.first_instance() (ret, _outparams, err) = service.SyncDeleteVG(Pool=vg) if ret != 0: if err: raise LmiFailed("Cannot delete the VG: %s." % err) raise LmiFailed("Cannot delete the VG: %s." % (service.DeleteVG.DeleteVGValues.value_name(ret), ))
def delete_lv(ns, lv): """ Destroy given Logical Volume. :type lv: LMIInstance/LMI_LVStorageExtent or string :param lv: Logical Volume to destroy. """ lv = common.str2device(ns, lv) service = ns.LMI_StorageConfigurationService.first_instance() (ret, _outparams, err) = service.SyncDeleteLV(TheElement=lv) if ret != 0: if err: raise LmiFailed("Cannot delete the LV: %s." % err) raise LmiFailed("Cannot delete the LV: %s." % (service.DeleteLV.DeleteLVValues.value_name(ret), ))
def remove_from_group(ns, group, users): group_inst = ns.LMI_Group.first_instance({"Name": group}) if group_inst is None: raise LmiFailed('No such group "%s"' % group) for user in users: user_inst = ns.LMI_Account.first_instance({"Name": user}) if user_inst is None: raise LmiFailed('No such user "%s"' % user) # get identity identity = user_inst.first_associator(ResultClass="LMI_Identity") # get MemberOfGroup for mog in identity.references(ResultClass="LMI_MemberOfGroup"): if mog.Collection.Name == group: mog.delete()
def install_from_uri(ns, uri, force=False, update=False): """ Install package from *URI* on remote system. :param string uri: Identifier of *RPM* package available via http, https, or ftp service. :param boolean force: Whether the installation shall be done even if installing the same (reinstalling) or older version than already installed. :param boolean update: Whether this is an update. Update fails if package is not already installed on system. """ if not isinstance(uri, basestring): raise TypeError("uri must be a string") service = ns.LMI_SoftwareInstallationService.first_instance() options = [4 if not update else 5] # Install (4) or Update (5) if force: options.append(3) # Force Installation results = service.SyncInstallFromURI(URI=uri, Target=get_computer_system(ns).path, InstallOptions=options) if results.rval != 0: msg = 'Failed to %s package from uri (rval=%d).' % ( 'update' if update else 'install', results.rval) if results.errorstr: msg += ': ' + results.errorstr raise LmiFailed(msg) else: LOG().info('Installed package from uri %s.', uri)
def get_service(ns, service): """ Return :py:class:`lmi.shell.LMIInstance` object matching the given service name. :param string service: Service name. """ if isinstance(service, basestring): cs = ns.Linux_ComputerSystem.first_instance_name() iname = ns.LMI_Service.new_instance_name({ "Name": service, "CreationClassName": "LMI_Service", "SystemName": cs.path['Name'], "SystemCreationClassName": cs.path['CreationClassName'] }) inst = iname.to_instance() if inst is None: raise LmiFailed('No such service "%s"' % service) elif isinstance(service, (LMIInstance, LMIInstanceName)): inst = service service = inst.Name if isinstance(inst, LMIInstanceName): inst = inst.to_instance() else: raise TypeError("service must be either string or ``LMIInstanceName``") return inst
def delete_raid(ns, raid): """ Destroy given RAID device :type raid: LMIInstance/LMI_MDRAIDStorageExtent :param raid: MD RAID to destroy. """ raid = common.str2device(ns, raid) service = ns.LMI_StorageConfigurationService.first_instance() (ret, _outparams, err) = service.SyncDeleteMDRAID(TheElement=raid) if ret != 0: if err: raise LmiFailed("Cannot create the partition: %s." % err) raise LmiFailed( "Cannot delete the raid: %s." % (service.DeleteMDRAID.DeleteMDRAIDValues.value_name(ret), ))
def restore(ns, target, action, recursively): """ Restore default SELinux security contexts on files. :param target: SELinux file to change. :param action: Action to take on mislabeled files. :param recursively: Restore labels recursively in case Target is a directory. """ uf_name = get_uf_name(ns, target) service = get_service(ns) try: (rval, params, errorstr) = service.SyncRestoreLabels( Target=uf_name, Action=action, Recursively=recursively, ) except LMIExceptions.CIMError as err: msg = 'Failed to restore default SELinux security context' if err[1]: if err[0] == 4: msg += err[1][err[1].index(':'):] else: msg += ": " + err[1] raise LmiFailed(msg) else: LOG().info('SELinux security contexts on "%s" restored.', target)
def set_repository_enabled(ns, repository, enable=True): """ Enable or disable repository. :param repository: Instance of ``LMI_SoftwareIdentityResource``. :type repository: :py:class:`lmi.shell.LMIInstance` or :py:class:`lmi.shell.LMIInstanceName` :param boolean enable: New value of ``EnabledState`` property. :returns: Previous value of repository's ``EnabledState``. :rtype: boolean """ if not isinstance(repository, (LMIInstance, LMIInstanceName)): raise TypeError("repository must be an LMIInstance") cls = ns.LMI_SoftwareIdentityResource if not LMIUtil.lmi_isinstance(repository, cls): raise ValueError("repository must be an instance of" " LMI_SoftwareIdentityResource") requested_state = cls.EnabledStateValues.Enabled if enable else \ cls.EnabledStateValues.Disabled if repository.EnabledState != requested_state: results = repository.RequestStateChange(RequestedState=requested_state) if results.rval != 0: msg = 'Failed to enable repository "%s" (rval=%d).' % ( repository.Name, results.rval) if results.errorstr: msg += ': ' + results.errorstr raise LmiFailed(msg) LOG().info('Repository "%s" %s.', repository.Name, "enabled" if enable else "disabled") else: LOG().info('Repository "%s" is already %s.', repository.Name, "enabled" if enable else "disabled") return repository.EnabledState
def remove_package(ns, package): """ Uninstall given package from system. :raises: :py:exc:`LmiFailed`` will be raised on failure. :param package: Instance or instance name of ``LMI_SoftwareIdentity`` representing package to remove. :type package: :py:class:`lmi.shell.LMIInstance` or :py:class:`lmi.shell.LMIInstanceName` """ if not isinstance(package, (LMIInstance, LMIInstanceName)): raise TypeError("package must be an LMIInstance or LMIInstanceName") try: if isinstance(package, LMIInstanceName): package = package.to_instance() except LmiFailed: package = None else: installed_assocs = package.reference_names( Role="InstalledSoftware", ResultClass="LMI_InstalledSoftwareIdentity") if not package or len(installed_assocs) < 1: raise LmiFailed('Given package "%s" is not installed!' % get_package_nevra(package)) for assoc in installed_assocs: nevra = get_package_nevra(assoc.InstalledSoftware) assoc.to_instance().delete() LOG().info('Removed package %s.', nevra)
def get_largest_partition_size(ns, device): """ Returns size of the largest free region (in blocks), which can accommodate a partition on given device. There must be partition table present on this device. :type device: LMIInstance/CIM_StorageExtent or string :param device: Device which should be examined. :rtype: int """ device = common.str2device(ns, device) # find the partition table (=LMI_DiskPartitionConfigurationCapabilities) cap = device.first_associator( ResultClass="LMI_DiskPartitionConfigurationCapabilities") if not cap: raise LmiFailed("Cannot find partition table on %s" % device.name) (ret, outparams, err) = cap.FindPartitionLocation(Extent=device) if ret == cap.FindPartitionLocation.FindPartitionLocationValues\ .NotEnoughFreeSpace: return 0 if ret != 0: if err: LOG().warning("Cannot find largest partition size: %s." % err) else: LOG().warning("Cannot find largest partition size: %d." % ret) return 0 blocks = outparams['EndingAddress'] - outparams['StartingAddress'] size = blocks * device.BlockSize return size