def vmedia_mount_create(handle, volume_name, remote_share, remote_file, map="www", mount_options="noauto", username="", password="", server_id=1, timeout=60): """ This method will setup the vmedia mapping Args: handle (ImcHandle) volume_name (string): Name of the volume or identity of the image map (string): "cifs", "nfs", "www" mount_options (string): Options to be passed while mounting the image remote_share (string): URI of the image remote_file (string): name of the image username (string): username password (string): password server_id (int): Server Id to be specified for C3260 platforms Returns: CommVMediaMap object Examples: vmedia_mount_add( handle, volume_name="c", map="www", mount_options="noauto", "nolock" etc. remote_share="http://1.1.1.1/files", remote_file="ubuntu-14.04.2-server-amd64.iso", username="******", password="******") """ image_type = remote_file.split('.')[-1] vmedia_mount_remove_image(handle, image_type) mo = CommVMediaMap(parent_mo_or_dn=_get_vmedia_mo_dn(handle, server_id), volume_name=volume_name) mo.map = map if mount_options: mo.mount_options = mount_options mo.remote_share = remote_share mo.remote_file = remote_file mo.username = username mo.password = password handle.add_mo(mo, modify_present="True") wait_time = 0 interval = 10 while wait_time < timeout: time.sleep(interval) mo = handle.query_dn(mo.dn) existing_mapping_status = mo.mapping_status if existing_mapping_status == "OK": return mo elif re.match(r"ERROR", existing_mapping_status): raise ImcOperationError("vmedia_mount_create", mo.mapping_status) wait_time += interval raise ImcOperationError("vmedia_mount_create", "ERROR - Mapped image status stuck at %s" % existing_mapping_status)
def _validate_api_prop(prop, value, api, validate_value=False, valid_values=None): if value is None: raise ImcOperationError(api, "Required property '%s' missing." % ( api, prop)) if validate_value and value not in valid_values: raise ImcOperationError( api, "['%s'] Invalid value '%s'. Valid values are %s" % ( prop, value, str(valid_values)))
def _create_vic_object(adaptor_mo, vic_name, vic_type, api_error_msg, **kwargs): from imcsdk.imccoreutils import load_class from imcsdk.imccoreutils import find_class_id_in_mo_meta_ignore_case vic_mo_name = vic_map[vic_type] vic_mo_class = load_class(vic_mo_name) vic_mo = vic_mo_class(parent_mo_or_dn=adaptor_mo, name=vic_name) # process vnic/vhba children vic_children = {} for key, value in kwargs.items(): mo_name, prop_name = _process_mo_prop_str(key, api_error_msg) if not mo_name: raise ImcOperationError(api_error_msg, "MO name is missing.") if not prop_name: raise ImcOperationError(api_error_msg, "Property name is missing.") prop_value = None if value is None else str(value) # VIC 1385 adapter is a multi-pci link adapter and hence just use the pci-link what we have received # For all other adapters, hard-code it to 0 if adaptor_mo.model != "UCSC-PCIE-C40Q-03": if mo_name == "AdaptorEthGenProfile" or mo_name == "AdaptorFcGenProfile": if prop_name == "pci_link": prop_value = "0" # Allow vHBA Type Configuration for Generation4+ adaptor only. Else, set the vhbaType to None as they are not supported. adaptorModel = adaptor_mo.model.split("-") genVersion = adaptorModel[len(adaptorModel) - 1] if genVersion < "04" and mo_name == "AdaptorFcGenProfile" and prop_name == "vhba_type": prop_value = None nmo_name = find_class_id_in_mo_meta_ignore_case(mo_name) if nmo_name is None: log.debug("Ignoring '%s'. MO '%s' does not exist in meta." % (key, mo_name)) continue else: mo_name = nmo_name if mo_name == vic_mo_name: mo = vic_mo elif mo_name not in vic_children: mo = _create_child_mo(vic_mo, mo_name) vic_children[mo_name] = mo else: mo = vic_children[mo_name] setattr(mo, prop_name, prop_value) return vic_mo
def _get_mo(handle, dn=None, **kwargs): if handle is None: raise ImcOperationError("Get Managed Object for dn:%s" % dn, "Handle is None") if dn: mo = handle.query_dn(dn) if mo is None: raise ImcOperationError("Get Managed Object for dn:%s" % dn, "Managed Object doesn't exist") return mo return None
def pd_encryption_enable(handle, controller_type, controller_slot, drive_slot, server_id=1): """ Enables encryption on the physical drive Args: handle (ImcHandle) controller_type (str): Controller type 'SAS' controller_slot (str): Controller slot name/number "MEZZ","0"-"9", "HBA" drive_slot (int): Slot in which the drive resides server_id (int): server_id for UCS 3260 platform Returns: StorageLocalDisk object Examples: pd_encryption_enable(handle, controller_type='SAS', controller_slot='HBA'', drive_slot=4') """ # pre-requisite # 1) disk should be encryption capable capable = pd_encryption_capable(handle, controller_type, controller_slot, drive_slot, server_id) if not capable: raise ImcOperationError( "Enable encryption on the Physical drive: %d" % drive_slot, "Drive is not FDE capable.") # 2) disk should be in JBOD mode. pd = pd_get(handle, controller_type, controller_slot, drive_slot, server_id) if pd.drive_state != "JBOD": raise ImcOperationError( "Enable encryption on the Physical drive: %d" % drive_slot, "Drive is not in JBOD mode") action = StorageLocalDiskConsts.ADMIN_ACTION_ENABLE_SELF_ENCRYPT return _pd_set_action(handle, controller_type=controller_type, controller_slot=controller_slot, drive_slot=drive_slot, action=action, server_id=server_id)
def snmp_user_modify(handle, name, **kwargs): """ Modifies snmp user. Use this after getting the id from snmp_user_exists Args: handle (ImcHandle) name (string) : SNMP user name kwargs: Key-Value paired arguments relevant to CommSnmpUser object Returns: CommSnmpUser: Managed Object Raises: ImcOperationError: If user is not present Example: snmp_user_modify(handle, name="snmpuser", security_level="authpriv", auth_pwd="password", auth="MD5", privacy="AES", privacy_pwd="password") """ mo = snmp_user_get(handle, name) if mo is None: raise ImcOperationError("Modify SNMP User", "User doesn't exist") mo.set_prop_multiple(**kwargs) handle.set_mo(mo) return mo
def vnic_create(handle, server_id=1, **kwargs): """ This method is used to create a new vnic Args: handle (ImcHandle) server_id (int): Server Id for C3260 platforms kwargs: key=value paired arguments for vnic/vhba Examples: Returns: AdaptorHostEthIf object """ vic_type = "vnic" api_error_msg = VicConst.VNIC_ERROR_MSG _validate_vic(vic_type, api_error_msg, kwargs) vic_name = kwargs.pop('name') vic_adaptor_slot = kwargs.pop('adaptor_slot') # Checks if the required adaptor exists at end point adaptor_mo = adaptor_unit_get(handle, vic_adaptor_slot) if adaptor_mo is None: raise ImcOperationError(api_error_msg, "Adaptor is missing at end point.") vic_mo = _create_vic_object(adaptor_mo, vic_name, vic_type, api_error_msg, **kwargs) return handle.add_mo(vic_mo)
def vmedia_mount_remove_all(handle, server_id=1): """ This method will remove all the vmedia mappings Args: handle (ImcHandle) server_id (int): Server Id to be specified for C3260 platforms Raises: Exception if mapping is able to be removed Returns: True Examples: vmedia_mount_remove_all(handle) """ # Get all current virtually mapped ISOs virt_media_maps = handle.query_children(in_dn=_get_vmedia_mo_dn(handle, server_id)) # Loop over each mapped ISO for virt_media in virt_media_maps: # Remove the mapped ISO handle.remove_mo(virt_media) # Raise error if all mappings not removed if len(handle.query_children(in_dn="sys/svc-ext/vmedia-svc")) > 0: raise ImcOperationError('Remove Virtual Media', '{0}: ERROR - Unable remove all virtual' + 'media mappings'.format(handle.ip)) # Return True if all mappings removed return True
def flexutil_controller_get(handle): controller = handle.query_classid( class_id=NamingId.STORAGE_FLEX_UTIL_CONTROLLER) if not controller: raise ImcOperationError("Get Flex Util Controller", "FlexUtil Controller not found") return controller[0]
def local_user_delete(handle, name): """ This method deactivates the user referred to by the username passed Args: handle (ImcHandle) name (string): username Returns: None Raises: ImcOperationError if the user is not found """ from imcsdk.mometa.aaa.AaaUser import AaaUserConsts found_user = _get_local_user(handle, name=name) if found_user is None: raise ImcOperationError("Delete Local User", "User doesn't exist") found_user.account_status = AaaUserConsts.ACCOUNT_STATUS_INACTIVE found_user.priv = AaaUserConsts.PRIV_READ_ONLY found_user.admin_action = AaaUserConsts.ADMIN_ACTION_CLEAR handle.set_mo(found_user)
def server_power_state_get(handle, server_id=1): """ This method will return the oper power status of the rack server Args: handle (ImcHandle) server_id (int): Server Id to be specified for C3260 platforms Examples: For classic or non-C3260 series servers:- server_power_state_get(handle) For modular or C3260 series servers, server_id should also be passed in the params:- server_power_state_get(handle, server_id=1) If server_id is not specified, this will assume server_id="1" Returns: oper power state(string) """ server_dn = get_server_dn(handle, server_id) server_mo = handle.query_dn(server_dn) if server_mo: return server_mo.oper_power raise ImcOperationError("Get Server Power State", "Managed Object not found for dn:%s" % server_dn)
def ip_filtering_enable(handle, ip_filters=None): """ Enables NTP and configures the NTP servers provided Args: handle (ImcHandle) ip_filters (list): List of dictionaries in the format [{"id": 1, "ip_filter": "192.168.1.1"}, {"id": 2, "ip": "192.168.1.2-192.168.1.4"}] Upto 4 ip filters can be specified. Returns: IPFiltering object Example: ip_filtering_enable(handle, ip_filters = [ {"id": 1, "ip_filter": "192.168.1.1"}, {"id": 2, "ip_filter": "192.168.1.2-192.168.1.4"}] """ dn = _get_mgmtif_mo_dn(handle) + "/ip-filter" mo = handle.query_dn(dn) if mo is None: raise ImcOperationError("ip_filtering_enable", "%s does not exist." % dn) mo.enable = 'yes' _set_ip_filters(mo, ip_filters) handle.set_mo(mo) return mo
def _set_ntp_servers(mo, ntp_servers): if len(ntp_servers) > len(_NTP_SERVER_LIST): raise ImcOperationError( "Set NTP Servers", "Cannot specify more than %d servers" % len(_NTP_SERVER_LIST)) args = _get_ntp_servers(ntp_servers) mo.set_prop_multiple(**args)
def physical_drive_set_jbod_mode(handle, controller_type, controller_slot, drive_slot, server_id=1): """ Sets the physical drive in jbod mode Args: handle (ImcHandle) controller_type (str): Controller type 'SAS' controller_slot (str): Controller slot name/number "MEZZ","0"-"9", "HBA" drive_slot (int): Slot in which the drive resides server_id (int): server_id for UCS 3260 platform Returns: StorageLocalDisk object Examples: physical_drive_set_jbod_mode(handle, controller_type='SAS', controller_slot='HBA'', drive_slot=4') """ if not is_controller_jbod_mode_enabled(handle, controller_type, controller_slot, server_id): raise ImcOperationError("Physical Drive: %s JBOD Mode Enable", "Controller JBOD mode is not enabled") return _physical_drive_action_set( handle, controller_type=controller_type, controller_slot=controller_slot, drive_slot=drive_slot, action=StorageLocalDiskConsts.ADMIN_ACTION_MAKE_JBOD, server_id=server_id )
def _set_ip_filters(mo, ip_filters): if len(ip_filters) > len(_IP_FILTERS_LIST): raise ImcOperationError( "Set IP Filters", "Cannot specify more than %d filters" % len(_IP_FILTERS_LIST)) args = _get_ip_filters(ip_filters) mo.set_prop_multiple(**args)
def _get_inventory_csv(inventory, file_name, spec=inventory_spec): import csv if file_name is None: raise ImcOperationError("Inventory collection", "file_name is a required parameter") f = csv.writer(open(file_name, "wb")) x = inventory for comp in spec: f.writerow([comp.upper()]) props = spec[comp]["props"] keys = [y['prop'] for y in props] keys.insert(0, "Host") f.writerow(keys) for ip in x: if comp not in x[ip]: continue host_component = x[ip][comp] if len(host_component) == 0: continue for entry in host_component: row_val = [] for key in keys: if key not in entry: continue row_val.append(entry[key]) row_val.insert(0, ip) f.writerow(row_val) f.writerow([]) f.writerow([])
def _get_vnic_order(vnic): api_error_msg = VicConst.VNIC_ERROR_MSG children = vnic._child for ch in children: if ch.get_class_id() == "AdaptorEthGenProfile": return int(ch.order) raise ImcOperationError(api_error_msg, "Order is missing.")
def _get_expected_vds(virtual_drives={}): vd_types = [vd for vd in dir(VirtualDriveType) if not vd.startswith('_')] expected_vds = {} for vd_type_ in virtual_drives: vd_ = virtual_drives[vd_type_] vd_type = vd_type_.upper() if vd_type not in vd_types: raise ImcOperationError("_prepare_config_set", "Unknown virtual drive'%s'" % vd_type_) enable = vd_.get('enable', None) if vd_type == 'OS': name = vd_.get('name', 'Hypervisor') # auto_sync = vd_.get('auto_sync', False) elif vd_type == 'USER': name = vd_.get('name', 'UserPartition') else: name = vd_.get('name', None) vd = VirtualDrive(vd_type=vd_type, vd_name=name, vd_enable=enable) # if vd_type == 'OS': # vd.vd_auto_sync = auto_sync expected_vds[vd_type] = vd return expected_vds
def sol_get(handle, server_id=1, caller="sol_get"): parent_dn = get_server_dn(handle, server_id) dn = parent_dn + "/sol-if" mo = handle.query_dn(dn) if mo is None: raise ImcOperationError(caller, "SOL '%s' doesn't exist." % dn) return mo
def ip_filtering_disable(handle): """ Disables IP Filtering. Args: handle (ImcHandle) Returns: IPFiltering object Raises: ImcOperationError Example: ip_filtering_disable(handle) """ dn = _get_mgmtif_mo_dn(handle) + "/ip-filter" mo = handle.query_dn(dn) if mo is None: raise ImcOperationError("ip_filtering_enable", "%s does not exist." % dn) mo.enable = "no" handle.set_mo(mo) return mo
def vd_update(handle, controller_type, controller_slot, id, server_id=1, access_policy=None, read_policy=None, cache_policy=None, disk_cache_policy=None, write_policy=None): mo = vd_get(handle, controller_type, controller_slot, id, server_id) if mo is None: raise ImcOperationError("Get Virtual drive", "Managed Object not found") if access_policy is not None: mo.access_policy = access_policy if read_policy is not None: mo.read_policy = read_policy if cache_policy is not None: mo.cache_policy = cache_policy if disk_cache_policy is not None: mo.disk_cache_policy = disk_cache_policy if write_policy is not None: mo.requested_write_cache_policy = write_policy handle.set_mo(mo) return mo
def pd_encryption_capable(handle, controller_type, controller_slot, drive_slot, server_id=1): """ Checks if encryption is supported on the physical drive Args: handle (ImcHandle) controller_type (str): Controller type 'SAS' controller_slot (str): Controller slot name/number "MEZZ","0"-"9", "HBA" drive_slot (int): Slot in which the drive resides server_id (int): server_id for UCS 3260 platform Returns: bool Examples: capable = is_physical_drive_encryption_capable( handle, controller_type='SAS', controller_slot='HBA'', drive_slot=4') """ mo = pd_get(handle, controller_type, controller_slot, drive_slot, server_id) if mo is None: raise ImcOperationError("Get Physical drive:%s" % drive_slot, "Not found") return mo.fde_capable.lower() in ['yes', 'true']
def ntp_servers_clear(handle, ntp_servers=[]): """ Clears the NTP servers provided in the arguments. Clears all the NTP servers, only if ntp is disabled. Args: handle (ImcHandle) ntp_servers (list): List of NTP servers in the format ["192.168.1.1", "192.168.1.2"] Returns: CommNtpProvider object """ mo = _get_mo(handle, dn=NTP_DN) args = {} if ntp_servers: args = { x: "" for x in _NTP_SERVER_LIST if getattr(mo, x) in ntp_servers } else: args = {x: "" for x in _NTP_SERVER_LIST} if mo.ntp_enable.lower() in ["yes", "true"] and \ len(args) == len(_NTP_SERVER_LIST): raise ImcOperationError( "Clear NTP Servers", "Cannot clear all NTP servers when NTP is enabled") mo.set_prop_multiple(**args) mo.ntp_enable = mo.ntp_enable handle.set_mo(mo) return handle.query_dn(mo.dn)
def _validate_vics(vic_type, api_error_msg, vics, adaptor_ep_dict): ''' validates if vic name and adaptor slot present in input Validates if mentioned adaptor exists at end point Identifies list of adaptor to be configured ''' adaptor_to_configure = [] for vic in vics: _validate_vic(vic_type, api_error_msg, vic) vic_name = vic['name'] vic_adaptor_slot = vic['adaptor_slot'] # check if adaptor to configure is present at end point if vic_adaptor_slot not in adaptor_ep_dict: raise ImcOperationError( api_error_msg, "Adaptor %s is not present at end point for interface %s" % (vic_adaptor_slot, vic_name)) # identify which all adaptor to configure if vic_adaptor_slot not in adaptor_to_configure: adaptor_to_configure.append(vic_adaptor_slot) return adaptor_to_configure
def is_physical_drive_encryption_enabled(handle, controller_type, controller_slot, drive_slot, server_id=1): """ Checks if encryption is enabled on the physical drive Args: handle (ImcHandle) controller_type (str): Controller type 'SAS' controller_slot (str): Controller slot name/number "MEZZ","0"-"9", "HBA" drive_slot (int): Slot in which the drive resides server_id (int): server_id for UCS 3260 platform Returns: bool Examples: enabled = is_physical_drive_encryption_enabled( handle, controller_type='SAS', controller_slot='HBA'', drive_slot=4') """ drive = physical_drive_get(handle, controller_type, controller_slot, drive_slot, server_id) if drive is None: raise ImcOperationError("Get Physical Drive:%s" % drive_slot, "Managed Object not found") return drive.fde_enabled.lower() in ['yes', 'true']
def smtp_recipient_remove_all(handle): """ Clears the smtp recipient with given id Args: handle (ImcHandle) Returns: None Raises: ImcOperationError Example: smtp_recipient_remove(handle,1) """ mos = _get_smtp_recipients(handle) if mos is None: raise ImcOperationError("smtp_recipient_remove_all", "No Recipient exist") for mo in mos: if not mo.email: continue mo.admin_action = MailRecipientConsts.ADMIN_ACTION_CLEAR handle.set_mo(mo)
def _wait_for_power_state(handle, state, timeout=60, interval=5, server_id=1): """ This method should be called after a power state change has been triggered. It will poll the server and return when the desired state is achieved. Args: handle(ImcHandle) state(str) timeout(int) interval(int) server_id (int): Server Id to be specified for C3260 platforms Returns: bool """ # Verify desired state is valid if state not in ("on", "off"): raise ValueError("ERROR invalid state: {0}".format(state)) # Verify interval not set to zero if interval < 1 or type(interval) is not int: raise ValueError("ERROR: interval must be positive integer") wait_time = 0 while server_power_state_get(handle, server_id) != state: # Raise error if we've reached timeout if wait_time > timeout: raise ImcOperationError( 'Power State Change', '{%s}: ERROR - Power {%s} did not complete within ' '{%s} sec' % (handle.ip, state, timeout)) # Wait interval sec between checks time.sleep(interval) wait_time += interval
def snmp_trap_modify(handle, hostname, **kwargs): """ Modifies snmp trap referred to by id Args: handle (ImcHandle) kwargs : Key-Value paired arguments relevant to CommSnmpTrap object Returns: CommSnmpTrap: Managed Object Raises: ImcOperationError if trap not found Example: snmp_trap_modify(handle, id="5", hostname="10.10.10.10", port="162", version="v3", notification_type="traps", user="******") """ mo = snmp_trap_get(handle, hostname) if mo is None: raise ImcOperationError("Modify SNMP trap", "Trap does not exist.") mo.set_prop_multiple(**kwargs) handle.set_mo(mo) return mo
def snmp_user_remove(handle, name): """ removes snmp user. Args: handle (ImcHandle) name (string): snmp username Returns: None Raises: ImcOperationError: If user is not present Example: snmp_user_remove(handle, name="snmpuser") """ from imcsdk.mometa.comm.CommSnmpUser import CommSnmpUserConsts found_user = snmp_user_get(handle, name=name) if found_user is None: raise ImcOperationError("Snmp User Delete", "User does not exist") found_user.name = "" found_user.admin_action = CommSnmpUserConsts.ADMIN_ACTION_CLEAR handle.set_mo(found_user)
def _set_ntp_servers(mo, ntp_servers): if len(ntp_servers) > len(_NTP_SERVER_LIST): raise ImcOperationError( "Set NTP Servers", "Cannot specify more than %d servers" % len(_NTP_SERVER_LIST)) args = {"ntp_server" + str(x["id"]): x["ip"] for x in ntp_servers} mo.set_prop_multiple(**args)