def enumerate_list(self, retdoc, *comp_enum): for comp in comp_enum: # Ignore if component already present if TypeHelper.resolve(comp) in retdoc: continue comp_details = self.enumerate_view(comp) for field in comp_details: retdoc[field] = comp_details[field] self.complete() if not self.pfactory.sspec is None: subsystem = [] for comp in self.pfactory.sspec: subcomp = {} if not 'Component' in self.pfactory.sspec[comp]: continue if not 'Field' in self.pfactory.sspec[comp]: continue cc = TypeHelper.resolve(self.pfactory.sspec[comp]['Component']) fld = self.pfactory.sspec[comp]['Field'] if cc in retdoc and isinstance(retdoc[cc], list) \ and len(retdoc[cc]) > 0 and fld in retdoc[cc][0]: # subsystem[TypeHelper.resolve(comp)] = retdoc[cc][0][fld] subcomp["Key"] = TypeHelper.resolve(comp) if retdoc[cc][0][fld]: subcomp["PrimaryStatus"] = retdoc[cc][0][fld] else: subcomp["PrimaryStatus"] = 'Unknown' subsystem.append(subcomp) if len(subsystem) > 0: retdoc["Subsystem"] = subsystem return retdoc
def _spit_scp(self, desiredcfg, output, depth=""): if depth == "": output._write_output("<SystemConfiguration>\n") for fqdd in desiredcfg: _comp = self.get_comp_from_fqdd(fqdd) if _comp == "invalid": logger.debug("Invalid Component defined!") continue if not "registry" in self.complist[_comp]: logger.debug("Invalid Registry defined!") continue comp = self.complist[_comp]["registry"] grps = self.get_groups(comp) output._write_output(depth + " <Component FQDD=\"" + fqdd + "\">\n") for compen in desiredcfg[fqdd]: props = self.defs[comp]["definitions"][comp]["properties"] compen = UnicodeHelper.stringize(compen) if isinstance(compen, str): self._spit_scp({compen: desiredcfg[fqdd][compen]}, output, depth + " ") continue if not TypeHelper.resolve(compen) in props: logger.debug(TypeHelper.resolve(compen) + " is not found in props") continue cvalue = TypeHelper.resolve(compen) idx = 1 if not isinstance(desiredcfg[fqdd][compen], list): idx = self._attr_print(output, depth, _comp, cvalue, props, desiredcfg[fqdd][compen], idx) else: for ent in desiredcfg[fqdd][compen]: idx = self._attr_print(output, depth, _comp, cvalue, props, ent, idx) output._write_output(depth + " </Component>\n") if depth == "": output._write_output("</SystemConfiguration>\n")
def connect(self, ipaddr, creds, pOptions): self.ipaddr = ipaddr self.creds = None for supported_cred in self.supported_creds: if isinstance(creds, ProtocolCredentialsFactory): self.creds = creds.get(supported_cred) elif TypeHelper.resolve( creds.enid) == TypeHelper.resolve(supported_cred): self.creds = creds else: logger.debug("Invalid credentials provided!") if self.creds is None: return False logger.debug("Connecting to " + ipaddr + " using " + str(self.creds)) if Simulator.is_simulating(): return Simulator.simulator_connect(self.ipaddr, self.enumid, self) self.pOptions = None if pOptions is None: pOptions = ProtocolOptionsFactory() for supported_pOp in [self.enumid]: if isinstance(pOptions, ProtocolOptionsFactory): self.pOptions = pOptions.get(supported_pOp) elif TypeHelper.resolve( pOptions.enid) == TypeHelper.resolve(supported_pOp): self.pOptions = pOptions else: logger.debug("Invalid pOptions provided!") return self.my_connect(ipaddr, self.creds, self.pOptions)
def _build_ops(self, protocmds, cmdname, *args): toargs = {} if not "Parameters" in protocmds[cmdname]: logger.debug("no parameters") elif len(protocmds[cmdname]["Parameters"]) != len(args): logger.debug("Too many args") return { 'Status' : 'Failed', 'Message' : 'Client Side: Too many arguments' } else: counter = 0 for (var, arg, field, val, dest) in protocmds[cmdname]["Parameters"]: if (args[counter] is None): myval = "" else: args_fixed = args[counter] if PY2 and (val == str and type(args_fixed) == unicode): args_fixed = args_fixed.encode('ascii', 'ignore') if not TypeHelper.belongs_to(val, args_fixed): return { 'Status' : 'Failed', 'Message' : 'Client Side: Argument ' + str(counter) + " got " + str(type(args_fixed))+ "! Must be: " + val.__name__ } try : if (val == datetime) and args_fixed.year == 1970: myval = "TIME_NOW" elif (val == datetime): myval = datetime.strftime(args_fixed, "%Y%m%d%H%M%S") else: myval = TypeHelper.resolve(args_fixed.value) except Exception as ex: myval = args_fixed toargs[var] = myval if dest != None: toargs[var] = dest(toargs[var]) logger.debug(var + "<=>" + str(toargs[var])) counter = counter + 1 return { 'Status' : 'Success', 'retval' : toargs }
def lclog_export(self, share_path, job_wait=True): """ Exports the log from the Lifecycle Controller to a file on local/remote share :param share_path: the share path where file needs to be exported :param job_wait: the flag to wait for job completion. False will return the Job ID :type share_path: obj <FileOnShare (NFS and CIFS) or LocalFile(Local Share)> :type job_wait: bool :return: success/failure response :rtype: JSON .. code-block:: python :caption: Examples :name: Examples # Export LC Logs - NFS Share nfs_share = FileOnShare(remote=<IP OR HOSTNAME>:/<NFS-SHARE-PATH>, mount_point=<MOUNT-DRIVE>:\\>, isFolder=<True/False>, creds=UserCredentials(<USERNAME>, <PASSWORD>)) lclog_file = nfs_share.new_file(<FILE-NAME>) msg = idrac.log_mgr.lclog_export(lclog_file) # Export LC Logs - CIFS Share cifs_share = FileOnShare(remote=\\\\<IP OR HOSTNAME>\\<CIFS-SHARE-PATH>, isFolder=<True/False>, creds=UserCredentials(<USERNAME>, <PASSWORD>)) lclog_file = cifs_share.new_file(<FILE-NAME>) msg = idrac.log_mgr.lclog_export(lclog_file) # Export LC Logs - Local Share local_share = LocalFile(local=os.path.join(, "path", "to", "lc-logs-file.xml")) export_lclog_streaming = idrac.log_mgr.lclog_export(share_path=local_share) """ share = share_path.format(ip=self.entity.ipaddr) if isinstance(share, LocalFile): export_file = share.local_full_path rjson = self.entity.streaming_mgr.export_data( file_type=FileTypeEnum.LCLogs, export_file=export_file) else: if TypeHelper.resolve( share.remote_share_type) == TypeHelper.resolve( ShareTypeEnum.NFS): rjson = self.entity._log_export_nfs(share=share) else: rjson = self.entity._log_export(share=share, creds=share_path.creds) rjson['file'] = str(share) if job_wait: rjson = self._job_mgr._job_wait(rjson['file'], rjson, False) return rjson
def setup_idrac_syslog(idrac, module): """ Setup iDRAC remote syslog settings idrac -- iDRAC handle module -- Ansible module """ msg = {} msg['changed'] = False msg['failed'] = False msg['msg'] = {} err = False try: if module.params["state"] == "present": idrac.config_mgr._sysconfig.iDRAC.SysLog.SysLogEnable_SysLog = \ TypeHelper.convert_to_enum('Enabled', SysLogEnable_SysLogTypes) idrac.config_mgr._sysconfig.iDRAC.SysLog.Port_SysLog = \ module.params['syslog_port'] if module.params['syslog_servers']: servers = [ server for server in module.params['syslog_servers'] if server.strip() ] if servers: servers.extend(["", "", ""]) idrac.config_mgr._sysconfig.iDRAC.SysLog.Server1_SysLog = servers[ 0] idrac.config_mgr._sysconfig.iDRAC.SysLog.Server2_SysLog = servers[ 1] idrac.config_mgr._sysconfig.iDRAC.SysLog.Server3_SysLog = servers[ 2] else: idrac.config_mgr._sysconfig.iDRAC.SysLog.SysLogEnable_SysLog = \ TypeHelper.convert_to_enum('Disabled', SysLogEnable_SysLogTypes) msg['changed'] = idrac.config_mgr._sysconfig.is_changed() if module.check_mode: # since it is running in check mode, reject the changes idrac.config_mgr._sysconfig.reject() else: msg['msg'] = idrac.config_mgr.apply_changes() if "Status" in msg['msg'] and msg['msg']["Status"] != "Success": msg['failed'] = True msg['changed'] = False except Exception as e: err = True msg['msg'] = "Error: %s" % str(e) msg['failed'] = True return msg, err
def job_wait(self, jobid, track_jobid=True, show_progress=False, wait_for=2 * 60 * 60): # wait for a 2 hours (longgg time) """Wait for the job to finish(fail/success) :param jobid: id of the job. :param path: str. . :returns: returns a json/dict containing job details """ logger.info(self.entity.ipaddr + " : Waiting for the job to finish : " + jobid) if track_jobid: self.last_job = jobid ret_json = {} job_ret = False wait_till = time.time() + wait_for while True: status = {} time.sleep(30) if self.entity.use_redfish: status = self.get_job_status_redfish(jobid) else: status = self.get_job_status(jobid) if not 'Status' in status: logger.debug(self.entity.ipaddr + " : " + jobid + " : Invalid Status") else: logger.debug(self.entity.ipaddr+" : "+jobid+ ": status: "+str(status)) pcc = "0" msg = "" if 'PercentComplete' in status: pcc = status['PercentComplete'] if 'Message' in status: msg = status['Message'] if show_progress: logger.debug(self.entity.ipaddr+ "{0} : {1} : Percent Complete: {2} | Message = {3}".format(jobid, status['Status'], pcc, msg)) if status['Status'] == TypeHelper.resolve(JobStatusEnum.Success): if show_progress: logger.debug(self.entity.ipaddr+" : "+jobid+ ":Message:" + status['Message']) job_ret = True ret_json = status break elif status['Status'] != TypeHelper.resolve(JobStatusEnum.InProgress): if show_progress: logger.debug(self.entity.ipaddr+" : "+jobid+ ":Message:" + status['Message']) job_ret = False ret_json = status break else: logger.debug(self.entity.ipaddr+" : "+jobid+ ": status: "+str(status)) if time.time() > wait_till: ret_json['Status'] = 'Failed' ret_json['Message'] = 'Job wait did not return for {0} seconds'.format(wait_for) break ret_json['retval'] = job_ret return ret_json
def setup_idrac_webserver(idrac, module): """ Setup iDRAC Webserver services Keyword arguments: idrac -- iDRAC handle module -- Ansible module """ msg = {} msg['changed'] = False msg['failed'] = False msg['msg'] = {} error = False try: tls_protocol = TypeHelper.convert_to_enum(module.params['tls_protocol'], TLSProtocol_WebServerTypes) ssl_bits = TypeHelper.convert_to_enum(module.params['ssl_bits'], SSLEncryptionBitLength_WebServerTypes) if module.params['state'] == 'present': idrac.config_mgr._sysconfig.iDRAC.WebServer.\ Enable_WebServer = Enable_WebServerTypes.Enabled idrac.config_mgr._sysconfig.iDRAC.WebServer.\ Timeout_WebServer = module.params['timeout'] idrac.config_mgr._sysconfig.iDRAC.WebServer.\ HttpPort_WebServer = module.params['http_port'] idrac.config_mgr._sysconfig.iDRAC.WebServer.\ HttpsPort_WebServer = module.params['https_port'] idrac.config_mgr._sysconfig.iDRAC.WebServer.\ TLSProtocol_WebServer = tls_protocol idrac.config_mgr._sysconfig.iDRAC.WebServer.\ SSLEncryptionBitLength_WebServer = ssl_bits else: idrac.config_mgr._sysconfig.iDRAC.WebServer.\ Enable_WebServer = Enable_WebServerTypes.Disabled msg['changed'] = idrac.config_mgr._sysconfig.is_changed() if module.check_mode: # Since it is running in check mode, reject the changes idrac.config_mgr._sysconfig.reject() else: msg['msg'] = idrac.config_mgr.apply_changes(reboot=False) if "Status" in msg['msg'] and msg['msg']['Status'] != "Success": msg['failed'] = True msg['changed'] = False except Exception as err: error = True msg['msg'] = "Error: %s" % str(err) msg['failed'] = True return msg, error
def update_from_repo(self, catalog_path, apply_update=True, reboot_needed=False, job_wait=True): if isinstance(catalog_path, str): # Catalog name updmgr = UpdateManager.get_instance() if not updmgr: return {} (cache_share, ignore) = updmgr.getCatalogScoper(catalog_path) else: # DRM Repo cache_share = catalog_path catalog_dir = FileOnShare(remote=cache_share.remote_folder_path, isFolder=True, creds=cache_share.creds) catalog_file = cache_share.remote_file_name if self.entity.use_redfish: if isinstance(catalog_path, FileOnShare) and catalog_path.mount_point is None: raise ValueError("Share path or mount point does not exist") rjson = self.entity._update_from_repo_using_redfish( ipaddress=catalog_dir.remote_ipaddr, share_name=catalog_dir.remote.share_name, share_type=IFRShareTypeEnum[ catalog_dir.remote_share_type.name.lower()], username=catalog_dir.creds.username, password=catalog_dir.creds.password, reboot_needed=reboot_needed, catalog_file=catalog_file, apply_update=ApplyUpdateEnum[str(apply_update)], ignore_cert_warning=IgnoreCertWarnEnum['On']) if TypeHelper.resolve( catalog_dir.remote_share_type) == TypeHelper.resolve( ShareTypeEnum.NFS): rjson = self.entity._update_repo_nfs( share=catalog_dir, creds=catalog_dir.creds, catalog=catalog_file, apply=URLApplyUpdateEnum[str(apply_update)].value, reboot=RebootEnum[str(reboot_needed)].value) else: rjson = self.entity._update_repo( share=catalog_dir, creds=catalog_dir.creds, catalog=catalog_file, apply=URLApplyUpdateEnum[str(apply_update)].value, reboot=RebootEnum[str(reboot_needed)].value) rjson['file'] = str(cache_share) if job_wait: rjson = self._job_mgr._job_wait(rjson['file'], rjson) if not self.entity.use_redfish: rjson['job_details'] = self.entity._update_get_repolist() return rjson
def update_from_repo(self, catalog_path, apply_update=True, reboot_needed=False, job_wait=True): appUpdateLookup = {True: 1, False: 0} rebootLookup = {True: "TRUE", False: "FALSE"} appUpdate = appUpdateLookup[apply_update] rebootNeeded = rebootLookup[reboot_needed] if isinstance(catalog_path, str): # Catalog name updmgr = UpdateManager.get_instance() if not updmgr: return {} (cache_share, ignore) = updmgr.getCatalogScoper(catalog_path) else: # DRM Repo cache_share = catalog_path catalog_dir = FileOnShare(remote=cache_share.remote_folder_path, isFolder=True, creds=cache_share.creds) catalog_file = cache_share.remote_file_name if self.entity.use_redfish: if isinstance(catalog_path, FileOnShare) and catalog_path.mount_point is None: logger.error("Share path or mount point does not exist") raise ValueError("Share path or mount point does not exist") return self.update_from_repo_usingscp_redfish( catalog_dir, catalog_file, mount_point=catalog_path.mount_point.full_path, reboot_needed=reboot_needed, job_wait=job_wait) if TypeHelper.resolve( catalog_dir.remote_share_type) == TypeHelper.resolve( ShareTypeEnum.NFS): rjson = self.entity._update_repo_nfs(share=catalog_dir, catalog=catalog_file, apply=appUpdate, reboot=rebootNeeded) else: rjson = self.entity._update_repo(share=catalog_dir, creds=catalog_dir.creds, catalog=catalog_file, apply=appUpdate, reboot=rebootNeeded) rjson['file'] = str(cache_share) if job_wait: rjson = self._job_mgr._job_wait(rjson['file'], rjson) return rjson
def job_wait(self, jobid, track_jobid=True, show_progress=False, wait_for=2 * 60 * 60): # wait for a 2 hours (longgg time) if track_jobid: self.last_job = jobid ret_json = {} job_ret = False wait_till = time.time() + wait_for while True: status = self.get_job_status(jobid) if not 'Status' in status: logger.debug("Invalid Status") else: logger.debug(PrettyPrint.prettify_json(status)) pcc = "0" msg = "" if 'PercentComplete' in status: pcc = status['PercentComplete'] if 'Message' in status: msg = status['Message'] if show_progress: logger.debug( "{0} : {1} : Percent Complete: {2} | Message = {3}". format(jobid, status['Status'], pcc, msg)) if status['Status'] == TypeHelper.resolve( JobStatusEnum.Success): if show_progress: logger.debug("Message:" + status['Message']) job_ret = True ret_json = status break elif status['Status'] != TypeHelper.resolve( JobStatusEnum.InProgress): if show_progress: logger.debug("Message:" + status['Message']) job_ret = False ret_json = status break else: logger.debug(str(status)) time.sleep(5) if time.time() > wait_till: ret_json['Status'] = 'Failed' ret_json[ 'Message'] = 'Job wait did not return for {0} seconds'.format( wait_for) break ret_json['retval'] = job_ret return ret_json
def convert_comp_to_enum(self, comps, comp_union_spec, merge_join_spec, misc_join_spec, more_details_spec): en = [] for i in comps: found = False for j in self.ComponentEnum: if TypeHelper.resolve(j) == TypeHelper.resolve(i): en.append(j) found = True break if not found: en.append(i) processedComp = self.find_merge_components(en, comp_union_spec, merge_join_spec, misc_join_spec, more_details_spec) return processedComp
def setup_idrac_snmp(idrac, module): """ Setup iDRAC SNMP Configuration parameters Keyword arguments: idrac -- iDRAC handle module -- Ansible module """ msg = {} msg['changed'] = False msg['failed'] = False msg['msg'] = {} err = False try: idrac.config_mgr.SNMPConfiguration.AgentEnable_SNMP = \ TypeHelper.convert_to_enum(module.params['snmp_enable'], AgentEnable_SNMPTypes) idrac.config_mgr.SNMPConfiguration.AgentCommunity_SNMP = \ module.params['snmp_community'].lower() idrac.config_mgr.SNMPConfiguration.AlertPort_SNMP = \ module.params['snmp_trap_port'] idrac.config_mgr.SNMPConfiguration.DiscoveryPort_SNMP = \ module.params['snmp_port'] idrac.config_mgr.SNMPConfiguration.SNMPProtocol_SNMP = \ TypeHelper.convert_to_enum(module.params['snmp_protocol'], SNMPProtocol_SNMPTypes) idrac.config_mgr.SNMPConfiguration.TrapFormat_SNMP = \ TypeHelper.convert_to_enum(module.params['snmp_trap_format'], TrapFormat_SNMPTypes) msg['changed'] = idrac.config_mgr._sysconfig.is_changed() if module.check_mode: # since it is running in check mode, reject the changes idrac.config_mgr._sysconfig.reject() else: msg['msg'] = idrac.config_mgr.apply_changes() if "Status" in msg['msg'] and msg['msg']['Status'] != "Success": msg['failed'] = True msg['changed'] = False except Exception as e: err = True msg['msg'] = "Error: %s" % str(e) msg['failed'] = True return msg, err
def _setup_ipv4(idrac, module): """ Setup IPv4 parameters Keyword arguments: idrac -- iDRAC handle module -- Ansible module """ idrac.config_mgr._sysconfig.iDRAC.IPv4.Enable_IPv4 = \ TypeHelper.convert_to_enum(module.params['ipv4_enable'], Enable_IPv4Types) idrac.config_mgr._sysconfig.iDRAC.IPv4.DHCPEnable_IPv4 = \ TypeHelper.convert_to_enum(module.params['ipv4_dhcp_enable'], DHCPEnable_IPv4Types)
def get_job_status_redfish(self, jobid): """Gets status of the job :param jobid: id of the job. :param path: str. . :returns: returns a json/dict containing job status(key in the dict is Status) along with other details """ jobdetail = self.get_job_details_redfish(jobid) if jobdetail['Status'] == 'Failed': return jobdetail jobdetail_data = jobdetail['Data']['Jobs'] if jobdetail_data['PercentComplete'] < 100: jobstaten = JobStatusEnum.InProgress elif jobdetail_data['JobState'] == 'Completed': jobstaten = self.get_job_status_by_msgid( jobdetail_data['MessageId']) elif jobdetail_data[ 'JobState'] == 'Failed' or 'Errors' in jobdetail_data[ 'JobState']: jobstaten = JobStatusEnum.Failed else: jobstaten = JobStatusEnum.Invalid jobdetail_data['Status'] = TypeHelper.resolve(jobstaten) return jobdetail_data
def __init__(self, direct, complist): # self.defs contains mapping between AttribRegistry ==> AttribRegistry.json self.defs = {} # self.complist contains compspec self.complist = complist # load self.defs from config directory for file1 in glob.glob(os.path.join(direct, "*.json")): with open(file1) as enum_data: myjson = json.load(enum_data) comp = re.sub("^.*/", "", myjson["$ref"]) self.defs[comp] = myjson # self.compen is the enum for AttribRegistry's compens = {} for i in self.defs: compens[i] = i self.compen = EnumWrapper("ConfigComp", compens).enum_type arspec = {} for cenum in self.compen: ens = {} cvalue = TypeHelper.resolve(cenum) for i in self.get_fields(cvalue): ens[i] = i arspec[cvalue] = EnumWrapper(cvalue + "ConfigEnum", ens).enum_type self.arspec = AttribRegistryNames(arspec)
def setup_boot_settings(idrac, module): """ Configure Boot Order parameters on PowerEdge Servers Keyword arguments: idrac -- iDRAC handle module -- Ansible module """ msg = {} msg['changed'] = False msg['failed'] = False msg['msg'] = {} error = False try: curr_boot_mode = idrac.config_mgr._sysconfig.BIOS.BootMode # Boot Mode - reboot imminent _setup_boot_mode(idrac, module) # Boot Seq retry if module.params['boot_seq_retry']: idrac.config_mgr._sysconfig.BIOS.BootSeqRetry = \ TypeHelper.convert_to_enum(module.params['boot_seq_retry'], BootSeqRetryTypes) # Setup HDD Sequence _setup_hdd_seq(idrac, module) # Setup BIOS Boot Settings if curr_boot_mode == BootModeTypes.Bios: _setup_bios_boot_settings(idrac, module) # Setup Uefi Boot Settings if curr_boot_mode == BootModeTypes.Uefi: _setup_uefi_boot_settings(idrac, module) # Setup iDRAC Boot configuration parameters _setup_idrac_boot_settings(idrac, module) msg['changed'] = idrac.config_mgr._sysconfig.is_changed() if module.check_mode: # since it is running in check mode, reject the changes idrac.config_mgr._sysconfig.reject() else: msg['msg'] = idrac.config_mgr.apply_changes() if "Status" in msg['msg'] and msg['msg']['Status'] != "Success": msg['failed'] = True msg['changed'] = False except Exception as err: error = True msg['msg'] = "Error: %s" % str(err) msg['exception'] = traceback.format_exc() msg['failed'] = True return msg, error
def opget(self, index, selector): if not index in self.views: logger.debug("WARN: no " + str(index) + " for " + str(self.enumid)) return {'Status': 'Success', 'Message': 'Not supported'} clsName = TypeHelper.resolve(index) logger.debug("Collecting " + clsName + " ... via " + str(self.enumid) + "...") if Simulator.is_simulating(): retval = Simulator.simulate_proto(self.ipaddr, self.enumid, clsName) else: retval = self.proto.opget(self.views[index], clsName, selector) if Simulator.is_recording(): Simulator.record_proto(self.ipaddr, self.enumid, clsName, retval) if not 'Data' in retval or retval['Data'] is None: return retval counter = 0 for i in retval['Data']: counter = counter + 1 retval['Data'][clsName] = retval['Data'][i] del retval['Data'][i] if counter <= 1: break return retval
def _enumerate_view(self, index, views, bTrue): if not index in views: logger.debug("WARN: no " + str(index) + " for " + str(self.enumid)) return {'Status': 'Success', 'Message': 'Not supported'} clsName = TypeHelper.resolve(index) logger.debug("Collecting " + clsName + " ... via " + str(self.enumid) + "...") if Simulator.is_simulating(): retval = Simulator.simulate_proto(self.ipaddr, self.enumid, clsName) else: # Changed True to False for having single session wsprof = views[index] filter = None if isinstance(views[index], list) and self.enumid == ProtocolEnum.WSMAN: wsprof = views[index][0] filter = views[index][1] retval = self.proto.enumerate(clsName, wsprof, self.selectors, False, filter) if Simulator.is_recording(): Simulator.record_proto(self.ipaddr, self.enumid, clsName, retval) if not 'Data' in retval or retval['Data'] is None or len(retval['Data']) <= 0: return retval if index in self.classifier_cond: chk_func = self.classifier_cond[index].get(self.enumid, None) if chk_func: (valid, flist) = chk_func(retval['Data'][clsName], clsName) if valid: retval['Data'][clsName] = flist else: return { 'Status': 'Failed', 'Message': 'Classifier condition not satisfied' } if index in self.classifier: for attr in self.classifier[index]: if not clsName in retval['Data']: return { 'Status': 'Failed', 'Message': clsName + ' instance is not found!' } if not attr in retval['Data'][clsName]: return { 'Status': 'Failed', 'Message': 'Classifier attribute not found!' } if not re.search(self.classifier[index][attr], retval['Data'][clsName][attr]): return { 'Status': 'Failed', 'Message': 'Classifier did not match!' } for en in self.view_fieldspec: if en != index: continue for retobj in retval['Data']: if isinstance(retval['Data'][retobj], dict): self._apply_spec(retval['Data'][retobj], en) else: for i in retval['Data'][retobj]: self._apply_spec(i, en) return retval
def _setup_ipv4_static(idrac, module): """ Setup IPv4 Static parameters Keyword arguments: idrac -- iDRAC handle module -- Ansible module """ if module.params['ipv4_dhcp_enable'] == 'Disabled': if module.params['ipv4_static']: idrac.config_mgr._sysconfig.iDRAC.IPv4Static.Address_IPv4Static = \ module.params['ipv4_static'] if module.params['ipv4_static_gw']: idrac.config_mgr._sysconfig.iDRAC.IPv4Static.Gateway_IPv4Static = \ module.params['ipv4_static_gw'] if module.params['ipv4_static_mask']: idrac.config_mgr._sysconfig.iDRAC.IPv4Static.Netmask_IPv4Static = \ module.params['ipv4_static_mask'] idrac.config_mgr._sysconfig.iDRAC.IPv4Static.DNSFromDHCP_IPv4Static = \ TypeHelper.convert_to_enum(module.params['ipv4_dns_from_dhcp'], DNSFromDHCP_IPv4StaticTypes) if module.params['ipv4_dns_from_dhcp'] != 'Enabled': if module.params['ipv4_preferred_dns']: idrac.config_mgr._sysconfig.iDRAC.IPv4Static.DNS1_IPv4Static = \ module.params['ipv4_prefered_dns'] if module.params['ipv4_alternate_dns']: idrac.config_mgr._sysconfig.iDRAC.IPv4Static.DNS2_IPv4Static = \ module.params['ipv4_alternate_dns']
def get_server_status(self, protocol=SDKServerProtocolEnum.HTTP): server_details = SDKServer.__server[TypeHelper.resolve(protocol)] return { "IPAddress": socket.gethostbyname(socket.gethostname()), "Port": server_details["server_config"]["port"], "State": server_details["server_config"]["state"] }
def _build_tree(self, mTree, device_json, ctree, parent=None, parentClsName=None): comp_tree = {} if not ctree in mTree: return comp_tree for entry in mTree[ctree]: if isinstance(entry, str): comp_tree[entry] = self._build_tree(mTree, device_json, entry) continue # Enum enname = TypeHelper.resolve(entry) if not enname in device_json: logger.debug("Component " + enname + " is not present in device!") continue if isinstance(device_json[enname], dict): if len(device_json[enname]) <= 0: # Empty entry continue child_index = self._get_obj_index(enname, device_json[enname]) if parent == None or self._isin(parentClsName, parent, enname, device_json[enname]): if not entry in mTree: # entry is a leaf node comp_tree[enname] = child_index else: # entry is not a leaf node comp_tree[enname] = { child_index: self._build_tree(mTree, device_json, entry, device_json[enname], enname) } elif isinstance(device_json[enname], list): if len(device_json[enname]) <= 0: # Empty entry continue dict_list = {} list_list = [] for tt in device_json[enname]: child_index = self._get_obj_index(enname, tt) if parent == None or self._isin(parentClsName, parent, enname, tt): if not entry in mTree: # entry is a leaf node list_list.append(child_index) else: # entry is not a leaf node dict_list[child_index] = self._build_tree(mTree, device_json, entry, tt, enname) if len(dict_list) != 0 and len(list_list) == 0: comp_tree[enname] = dict_list elif len(dict_list) == 0 and len(list_list) != 0: comp_tree[enname] = list_list elif len(dict_list) != 0 and len(list_list) != 0: comp_tree[enname] = dict_list comp_tree[enname]["_unknown_"] = list_list else: logger.debug("Unexpected format!") return comp_tree
def _setup_idrac_boot_settings(idrac, module): # First boot device first_boot_device = module.params['first_boot_device'] if first_boot_device: idrac.config_mgr._sysconfig.iDRAC.ServerBoot.FirstBootDevice_ServerBoot = \ TypeHelper.convert_to_enum(first_boot_device, FirstBootDevice_ServerBootTypes) # Boot Once boot_once = TypeHelper.convert_to_enum(module.params['boot_once'], BootOnce_ServerBootTypes) if first_boot_device and first_boot_device in [ 'BIOS', 'F10', 'F11', 'UEFIDevicePath' ]: boot_once = TypeHelper.convert_to_enum('Enabled', BootOnce_ServerBootTypes) idrac.config_mgr._sysconfig.iDRAC.ServerBoot.BootOnce_ServerBoot = boot_once
def get_driver(self, driver_en, ipaddr, creds, protopref=None, pOptions=None): mod = TypeHelper.resolve(driver_en) logger.debug("get_driver(): Asking for " + mod) return self._create_driver(mod, ipaddr, creds, protopref, pOptions)
def _get_more_details(self, entityjson, more_details_spec, comps): tempList = [] if more_details_spec is not None: for item in more_details_spec: myList = more_details_spec[item]['_components_enum'] keyComp = item for val in myList: tempList.append(TypeHelper.resolve(val)) self._call_it(keyComp, tempList)
def CreateMonitorScopeFilter(argument = ""): if argument == "": argument = "Health+Inventory+Metrics+ConfigState" monitorfilter = MonitorScopeFilter() for i in argument.split("+"): for j in MonitorScope: if TypeHelper.get_name(j, MonitorScopeMap) == i: monitorfilter.add(j) return monitorfilter
def enumerate_view(self, index): clsName = TypeHelper.resolve(index) # view is a URI retdoc = {} collector = {} collector_idseq = {} for connection in self.work_connection: retval = connection.enumerate_view(index, True) if retval['Status'] != 'Success' or \ not 'Data' in retval or \ retval['Data'] is None or \ len(retval['Data']) <= 0: continue for retobj in retval['Data']: if isinstance(retval['Data'][retobj], dict): retval['Data'][retobj] = [retval['Data'][retobj]] if isinstance(retval['Data'][retobj], dict): # Merge System if not clsName in retdoc: retdoc[clsName] = {} idx = self.sdkobj._get_obj_index( clsName, retval['Data'][retobj]) retdoc[clsName]["Key"] = idx for i in retval['Data'][retobj]: retdoc[clsName][i] = retval['Data'][retobj][i] else: if not clsName in collector: collector[clsName] = {} collector_idseq[clsName] = [] for i in retval['Data'][retobj]: idx = self.sdkobj._get_obj_index(clsName, i) if idx is None: idx = "<null_index>" if not idx in collector[clsName]: collector[clsName][idx] = {} collector_idseq[clsName].append(idx) collector[clsName][idx]["Key"] = idx for ob in i: if i[ob] == "Not Available" or i[ ob] == "Not Applicable": continue collector[clsName][idx][ob] = i[ob] for clsName in collector: if not clsName in retdoc: retdoc[clsName] = [] for i in collector_idseq[clsName]: retdoc[clsName].append(collector[clsName][i]) return retdoc
def _isin(self, parentClsName, parent, childClsName, child): if TypeHelper.resolve(parentClsName) == "Controller" and \ TypeHelper.resolve(childClsName) == "PhysicalDisk" and \ ("Disk.Direct" not in self._get_obj_index(childClsName, child)): return False if TypeHelper.resolve(parentClsName) == "VirtualDisk" and \ TypeHelper.resolve(childClsName) == "PhysicalDisk": if 'PhysicalDiskIDs' in parent: parentdiskListStr = parent['PhysicalDiskIDs'].strip("[]") diskids = parentdiskListStr.split(',') for d in diskids: fd = d.strip().strip("'") # print("FD is ",fd, " VD ",self._get_obj_index(childClsName,child)) if (self._get_obj_index(childClsName, child) in fd): # print("Add to CTREE SUCCESS") return True else: return False return self._get_obj_index(parentClsName, parent) in \ self._get_obj_index(childClsName, child)
def get_job_status(self, jobid): jobs = {} jobret = {"Status": TypeHelper.resolve(JobStatusEnum.InProgress)} if jobid.startswith('DCIM_OSD'): # Poll for OSD Concrete Job jobs = self._get_osd_job_details() else: jobs = self.get_job_details(jobid) logger.debug(PrettyPrint.prettify_json(jobs)) if "Status" in jobs and jobs['Status'] != "Success": logger.debug("ERROR: get_job_status failed: " + jobs['Status']) logger.debug("ERROR: get_job_status failed: " + jobs['Message']) return jobs jb = jobs['Data']['Jobs'] if jb['InstanceID'] != jobid: logger.debug("ERROR: Job instance not found") return jobs if 'JobStatus' in jb: jobstatus = jb['JobStatus'] if jobstatus == 'Completed': jobstaten = JobStatusEnum.Success elif 'Message' in jb and jb['Message'] and 'completed' in jb[ 'Message']: jobstaten = JobStatusEnum.Success elif jobstatus == 'Failed': jobstaten = JobStatusEnum.Failed elif jobstatus == 'Pending': jobstaten = JobStatusEnum.InProgress elif jobstatus.endswith('In Progress'): jobstaten = JobStatusEnum.InProgress elif jobstatus.endswith('Scheduled'): jobstaten = JobStatusEnum.InProgress elif jobstatus.endswith('Running'): jobstaten = JobStatusEnum.InProgress elif jobstatus.endswith('Invalid'): jobstaten = JobStatusEnum.InProgress else: jobstaten = JobStatusEnum.InProgress jb['Status'] = TypeHelper.resolve(jobstaten) return jb
def _setup_boot_mode(idrac, module): """ Setup boot mode - reboot is imminent if you change the boot mode Keyword arguments: idrac -- idrac, module module -- Ansible module """ if module.params['boot_mode']: idrac.config_mgr._sysconfig.BIOS.BootMode = TypeHelper.convert_to_enum( module.params['boot_mode'], BootModeTypes)