def addprofileandstartjob(self, options): """ Adds ip profile into the job queue and start it. :return returncode: int """ ipprovider = self.hasipprovider() if ipprovider is None: raise PathUnavailableError(u"System does not support this feature of IP.\n") ipjob = self.hasipjobs() if not ipjob: raise InvalidFileFormattingError(u"System does not have any IP"\ u" profile to copy to the job queue.\n") current_state = self.inipstate(ipprovider) if current_state is None: raise PathUnavailableError(u"System does not support this feature of IP.\n") later_state = False ipstate = current_state["InIP"] if isinstance(ipstate, bool) and ipstate: #make sure we are in IP state. Reset and monitor self.resetinipstate(ipprovider, current_state) #if we are in ip, monitor should be fast, use 15 seconds later_status = self.monitorinipstate(ipprovider, 3) if later_status: self.copyjobtoipqueue(ipjob) sys.stdout.write(u"Copy operation was successful...\n") return ReturnCodes.SUCCESS if not isinstance(ipstate, bool): # inip is in an unknown state, so ... #patch to false, reboot, then monitor...if it turns true later... #then we are in IP state otherwise, manually check system... self.resetinipstate(ipprovider, current_state) later_status = self.monitorinipstate(ipprovider, 3) if later_status: self.copyjobtoipqueue(ipjob) sys.stdout.write(u"Copy operation was successful...\n") return ReturnCodes.SUCCESS try: self.bootorderobj.run("--onetimeboot=Utilities "\ "--reboot=ColdBoot --commit") except: raise InvalidFileFormattingError(u"System failed to reboot") #After reboot, login again self.validation(options) later_state = self.monitorinipstate(ipprovider) if later_state: self.copyjobtoipqueue(ipjob) sys.stdout.write(u"Copy operation was successful...\n") else: raise InvalidFileFormattingError(u"\nSystem reboot took longer than 4 minutes."\ u"something is wrong. You need to physically check this system.\n") return ReturnCodes.SUCCESS
def load_clone(self, filename, options): """ load the clone file onto the server :param filename: filename containing the clone config data :type filename: str :param options: command line options :type options: list. """ loadcontents = None if not filename: filename = 'clone.json' if not os.path.isfile(filename): raise InvalidFileInputError("File '%s' doesn't exist. Please " \ "create file by running save command." % file) if options.encryption: with open(filename, "rb") as myfile: data = myfile.read() data = Encryption().decrypt_file(data, \ options.encryption) else: myfile = open(filename, 'r') data = myfile.read() myfile.close() try: loadcontents = json.loads(data) except: raise InvalidFileFormattingError("Invalid file formatting " \ "found in file %s" % file) return loadcontents
def deletekeyfromipprofiledata(self, options): """ Provide a string which represents a valid key in hpeipprofiles data store. :param options: command line options :type options: list. :return returncode: int """ get_results = self._rdmc.app.get_handler(self.path, silent=True) j2python = json.loads(get_results.read) all_keys = options.del_key[0].split(',') for key in all_keys: if isinstance(key, six.string_types) and j2python.get( key.strip(), False): del j2python[key.strip()] else: raise InvalidFileFormattingError("%s was not found .\n" % key) payload = {} payload["path"] = self.path payload["body"] = j2python self._rdmc.app.put_handler(payload["path"], payload["body"]) return ReturnCodes.SUCCESS
def verify_file(self, filedata, inputfile): """ Function used to handle oddly named files and convert to JSON :param filedata: input file data :type filedata: string. :param inputfile: current input file :type inputfile: string. """ try: tempholder = json.loads(filedata) return tempholder except: raise InvalidFileFormattingError("Invalid file formatting found in file %s" % inputfile)
def encode_base64_string(self, args): """ Encode a given string with base64 and gzip it. :param args: command line args :type args: string. """ payload = {} filename = args[0] if filename: if not os.path.isfile(filename): raise InvalidFileInputError("File '%s' doesn't exist. "\ "Please create file by running 'save' command."\ % filename) try: inputfile = open(filename, 'r') contentsholder = json.loads(inputfile.read()) except: raise InvalidFileFormattingError("Input file '%s' was not "\ "format properly." % filename) try: text = json.dumps(contentsholder) buf = StringIO() gzfile = gzip.GzipFile(mode='wb', fileobj=buf) gzfile.write(text) gzfile.close() en_text = base64.encodestring(buf.getvalue()) epoch = datetime.utcfromtimestamp(0) now = datetime.utcnow() delta = now - epoch time_stamp = delta.total_seconds() * 1000 time_stamp = repr(time_stamp).split('.')[0] body_text = {time_stamp: en_text.strip()} payload["body"] = body_text payload["path"] = self.path except: raise UnableToDecodeError("Error while encoding string.") return payload
def saveworkerfunction(self, instances=None): """ Returns the currently selected type for saving :param instances: list of instances from select to save :type instances: list. """ content = self._rdmc.app.getprops(insts=instances) try: contents = [{ val[self.typepath.defs.hrefstring]: val } for val in content] except KeyError: contents = [{val['links']['self'][self.typepath.defs.hrefstring]:val} for val in \ content] type_string = self.typepath.defs.typestring templist = list() for content in contents: typeselector = None pathselector = None for path, values in content.items(): for dictentry in list(values.keys()): if dictentry == type_string: typeselector = values[dictentry] pathselector = path del values[dictentry] if values: tempcontents = dict() if typeselector and pathselector: tempcontents[typeselector] = {pathselector: values} else: raise InvalidFileFormattingError( "Missing path or selector in input file.") templist.append(tempcontents) return templist
def run(self, line): """ Main save worker function :param line: command line input :type line: string. """ try: (options, args) = self._parse_arglist(line) except: if ("-h" in line) or ("--help" in line): return ReturnCodes.SUCCESS else: raise InvalidCommandLineErrorOPTS("") self.savevalidation(options) if not len(args) == 0: raise InvalidCommandLineError('Save command takes no arguments.') contents = self._rdmc.app.get_save(args, pluspath=True) type_string = self._rdmc.app.current_client.monolith._typestring if not contents: raise redfish.ris.NothingSelectedError else: sys.stdout.write("Saving configuration...\n") templist = list() for content in contents: typeselector = None pathselector = None for path, values in content.iteritems(): values = OrderedDict(sorted(values.items(),\ key=lambda x: x[0])) for dictentry in values.keys(): if dictentry == type_string: typeselector = values[dictentry] pathselector = path del values[dictentry] elif dictentry.lower() in HARDCODEDLIST or '@odata' in \ dictentry.lower(): del values[dictentry] if len(values): tempcontents = dict() if typeselector and pathselector: tempcontents[typeselector] = {pathselector: values} else: raise InvalidFileFormattingError("Missing path or" \ " selector in input file.") templist.append(tempcontents) contents = templist if not contents: raise redfish.ris.NothingSelectedError else: contents = self.add_save_file_header(contents) outfile = open(self.filename, 'w') outfile.write(json.dumps(contents, indent=2, \ cls=redfish.ris.JSONEncoder)) outfile.close() sys.stdout.write("Configuration saved to: %s\n" % self.filename) if options.logout: self.logoutobj.logoutfunction("") #Return code return ReturnCodes.SUCCESS
def run(self, line): """ Main raw patch worker function :param line: command line input :type line: string. """ try: (options, args) = self._parse_arglist(line) except (InvalidCommandLineErrorOPTS, SystemExit): if ("-h" in line) or ("--help" in line): return ReturnCodes.SUCCESS else: raise InvalidCommandLineErrorOPTS("") headers = {} results = None self.patchvalidation(options) contentsholder = None if len(args) == 1: if not os.path.isfile(args[0]): raise InvalidFileInputError("File '%s' doesn't exist. " \ "Please create file by running 'save' command." % args[0]) try: inputfile = open(args[0], 'r') contentsholder = json.loads(inputfile.read()) except: raise InvalidFileFormattingError("Input file '%s' was not " \ "format properly." % args[0]) elif len(args) > 1: raise InvalidCommandLineError("Raw patch only takes 1 argument.\n") else: raise InvalidCommandLineError( "Missing raw patch file input argument.\n") if options.headers: extraheaders = options.headers.split(',') for item in extraheaders: header = item.split(':') try: headers[header[0]] = header[1] except: raise InvalidCommandLineError( "Invalid format for --headers option.") if "path" in contentsholder and "body" in contentsholder: returnresponse = False if options.response or options.getheaders: returnresponse = True results = self._rdmc.app.patch_handler(contentsholder["path"], \ contentsholder["body"], headers=headers, \ response=returnresponse, silent=options.silent, \ optionalpassword=options.biospassword, service=options.service) else: raise InvalidFileFormattingError( "Input file '%s' was not format properly." % args[0]) if results and returnresponse: if options.getheaders: sys.stdout.write(json.dumps(dict(results.getheaders())) + "\n") if options.response: sys.stdout.write(results.read) #Return code return ReturnCodes.SUCCESS
except: raise InvalidCommandLineError("Invalid format for " \ "--headers option.") if "path" in contentsholder and "body" in contentsholder: returnresponse = False if options.response or options.getheaders: returnresponse = True results = self._rdmc.app.post_handler(contentsholder["path"], \ contentsholder["body"], verbose=self._rdmc.opts.verbose, \ sessionid=options.sessionid, url=url, headers=headers, \ response=returnresponse, silent=options.silent) else: raise InvalidFileFormattingError("Input file '%s' was not "\ "formatted properly." % args[0]) if results and returnresponse: if options.getheaders: sys.stdout.write(json.dumps(dict(\ results._http_response.getheaders())) + "\n") if options.response: sys.stdout.write(results.text) #Return code return ReturnCodes.SUCCESS def postvalidation(self, options): """ Raw post validation function
def run(self, line): """ Main load worker function :param line: command line input :type line: string. """ try: (options, _) = self._parse_arglist(line) except: if ("-h" in line) or ("--help" in line): return ReturnCodes.SUCCESS else: raise InvalidCommandLineErrorOPTS("") self.loadvalidation(options) returnvalue = False loadcontent = dict() if options.mpfilename: sys.stdout.write("Loading configuration for multiple servers...\n") else: sys.stdout.write("Loading configuration...\n") for files in self.filenames: if not os.path.isfile(files): raise InvalidFileInputError("File '%s' doesn't exist. Please " \ "create file by running save command." % files) if options.encryption: with open(files, "rb") as myfile: data = myfile.read() data = Encryption().decrypt_file(data, \ options.encryption) else: with open(files, "r") as myfile: data = myfile.read() try: loadcontents = json.loads(data) except: raise InvalidFileFormattingError("Invalid file formatting " \ "found in file %s" % files) if options.mpfilename: mfile = options.mpfilename outputdir = None if options.outdirectory: outputdir = options.outdirectory if self.runmpfunc(mpfile=mfile, lfile=files, \ outputdir=outputdir): return ReturnCodes.SUCCESS else: raise MultipleServerConfigError("One or more servers "\ "failed to load given configuration.") results = False validation_errs = [] for loadcontent in loadcontents: for content, loaddict in loadcontent.items(): inputlist = list() if content == "Comments": continue inputlist.append(content) if options.biospassword: inputlist.extend(["--biospassword", options.biospassword]) self.selobj.selectfunction(inputlist) if self._rdmc.app.get_selector().lower() not in content.lower(): raise InvalidCommandLineError("Selector not found.\n") try: for _, items in loaddict.items(): try: if self._rdmc.app.loadset(seldict=items, \ latestschema=options.latestschema, \ uniqueoverride=options.uniqueoverride): results = True except LoadSkipSettingError as excp: returnvalue = True results = True except: raise except redfish.ris.ValidationError as excp: errs = excp.get_errors() validation_errs.append({self._rdmc.app.get_selector(): errs}) except: raise try: if results: self.comobj.commitfunction(options=options) except NoChangesFoundOrMadeError as excp: if returnvalue: pass else: raise excp if validation_errs: for validation_err in validation_errs: for err_type in validation_err: sys.stderr.write("Validation error(s) in type %s:\n" % err_type) for err in validation_err[err_type]: if isinstance(err, redfish.ris.RegistryValidationError): sys.stderr.write(err.message) sys.stderr.write('\n') try: if err.reg: err.reg.print_help(str(err.sel)) sys.stderr.write('\n') except: pass raise redfish.ris.ValidationError(excp) if not results: raise NoDifferencesFoundError("No differences found from current configuration.") #Return code if returnvalue: return ReturnCodes.LOAD_SKIP_SETTING_ERROR return ReturnCodes.SUCCESS
def run(self, line): """ Main raw patch worker function :param line: command line input :type line: string. """ try: (options, _) = self.rdmc.rdmc_parse_arglist(self, line) except (InvalidCommandLineErrorOPTS, SystemExit): if ("-h" in line) or ("--help" in line): return ReturnCodes.SUCCESS else: raise InvalidCommandLineErrorOPTS("") url = None headers = {} results = [] if hasattr(options, 'sessionid') and options.sessionid: url = self.sessionvalidation(options) else: self.patchvalidation(options) contentsholder = None try: with open(options.path, 'r') as _if: contentsholder = json.loads(_if.read(), object_pairs_hook=OrderedDict) except IOError: raise InvalidFileInputError("File '%s' doesn't exist. " \ "Please create file by running 'save' command." % options.path) except (ValueError): raise InvalidFileFormattingError("Input file '%s' was not " \ "formatted properly." % options.path) if options.headers: extraheaders = options.headers.split(',') for item in extraheaders: header = item.split(':') try: headers[header[0]] = header[1] except: raise InvalidCommandLineError( "Invalid format for --headers option.") if "path" in contentsholder and "body" in contentsholder: results.append(self.rdmc.app.patch_handler(contentsholder["path"], \ contentsholder["body"], headers=headers, silent=options.silent, \ optionalpassword=options.biospassword, service=options.service)) elif all([re.match("^\/(\S+\/?)+$", key) for key in contentsholder]): for path, body in contentsholder.items(): results.append(self.rdmc.app.patch_handler(path, \ body, headers=headers, silent=options.silent, \ optionalpassword=options.biospassword, service=options.service)) else: raise InvalidFileFormattingError("Input file '%s' was not format properly." % \ options.path) returnresponse = False if options.response or options.getheaders: returnresponse = True if results and returnresponse: for result in results: if options.getheaders: self.rdmc.ui.print_out_json(dict(result.getheaders())) if options.response: self.rdmc.ui.printer(result.read) self.rdmc.ui.printer("\n") self.cmdbase.logout_routine(self, options) #Return code return ReturnCodes.SUCCESS
def run(self, line): """ Main raw patch worker function :param line: command line input :type line: string. """ try: (options, args) = self._parse_arglist(line) except (InvalidCommandLineErrorOPTS, SystemExit): if ("-h" in line) or ("--help" in line): return ReturnCodes.SUCCESS else: raise InvalidCommandLineErrorOPTS("") headers = {} results = None self.postvalidation(options) contentsholder = None if len(args) == 1: try: inputfile = open(args[0], 'r') contentsholder = json.loads(inputfile.read()) except Exception as excp: raise InvalidFileInputError("%s" % excp) elif len(args) > 1: raise InvalidCommandLineError("Raw post only takes 1 argument.\n") else: raise InvalidCommandLineError( "Missing raw post file input argument.\n") if options.encode: if "body" in contentsholder and "UserName" in contentsholder["body"] and \ "Password" in contentsholder["body"] and \ len(list(contentsholder["body"].keys())) == 2: encobj = Encryption() contentsholder["body"]["UserName"] = encobj.decode_credentials(\ contentsholder["body"]["UserName"]) contentsholder["body"]["Password"] = encobj.decode_credentials(\ contentsholder["body"]["Password"]) if options.headers: extraheaders = options.headers.split(',') for item in extraheaders: header = item.split(':') try: headers[header[0]] = header[1] except: raise InvalidCommandLineError( "Invalid format for --headers option.") if "path" in contentsholder and "body" in contentsholder: returnresponse = False if options.response or options.getheaders: returnresponse = True results = self._rdmc.app.post_handler(contentsholder["path"], \ contentsholder["body"], headers=headers, \ response=returnresponse, silent=options.silent, service=options.service) else: raise InvalidFileFormattingError("Input file '%s' was not "\ "formatted properly." % args[0]) if results and returnresponse: if options.getheaders: sys.stdout.write(json.dumps(dict(results.getheaders())) + "\n") if options.response: sys.stdout.write(results.ori + "\n") #Return code return ReturnCodes.SUCCESS
def run(self, line): """ Main load worker function :param line: command line input :type line: string. """ try: (options, _) = self._parse_arglist(line) except: if ("-h" in line) or ("--help" in line): return ReturnCodes.SUCCESS else: raise InvalidCommandLineErrorOPTS("") self.loadvalidation(options) returnValue = False loadcontent = dict() if options.mpfilename: sys.stdout.write("Loading configuration for multiple servers...\n") else: sys.stdout.write("Loading configuration...\n") for files in self.filenames: if not os.path.isfile(files): raise InvalidFileInputError("File '%s' doesn't exist. Please " \ "create file by running save command." % files) with open(files, "r") as myfile: data = myfile.read() try: loadcontents = json.loads(data) except: raise InvalidFileFormattingError("Invalid file formatting " \ "found in file %s" % files) if options.mpfilename: mfile = options.mpfilename outputdir=None if options.outdirectory: outputdir=options.outdirectory if self.runmpfunc(mpfile=mfile, lfile=files, \ outputdir=outputdir): return ReturnCodes.SUCCESS else: raise MultipleServerConfigError("One or more servers "\ "failed to load given configuration.") results = False for loadcontent in loadcontents: skip = False for content, loaddict in loadcontent.iteritems(): inputlist = list() if content == "Comments": skip = True break inputlist.append(content) self.selobj.selectfunction(inputlist) if self._rdmc.app.get_selector().lower() not in \ content.lower(): raise InvalidCommandLineError("Selector not found.\n") try: for _, items in loaddict.iteritems(): dicttolist = list(items.items()) if len(dicttolist) < 1: continue multilevel = [isinstance(x[1], dict) for x in \ dicttolist] indices = [i for i, j in enumerate(multilevel) if j] if len(indices) > 0: for index in indices: changes = [] self.loadmultihelper(dicttolist[index][0], \ dicttolist[index][1], changes) for change in changes: if self._rdmc.app.loadset(dicttolist=\ dicttolist, newargs=change[0], val=change[0]): results = True indices.sort(cmp=None, key=None, reverse=True) #Test validate thoroughly for index in indices: del dicttolist[index] if len(dicttolist) < 1: continue try: if self._rdmc.app.loadset(\ dicttolist=dicttolist): results = True except LoadSkipSettingError: returnValue = True results = True pass except Exception: raise except Exception: raise if skip: continue try: if results: self.comobj.commitfunction() except NoChangesFoundOrMadeError: if returnValue: pass else: raise if not results: raise NoDifferencesFoundError("No differences found from " \ "current configuration.") #Return code if returnValue: return ReturnCodes.LOAD_SKIP_SETTING_ERROR else: return ReturnCodes.SUCCESS
def run(self, line): """ Main raw put worker function :param line: command line input :type line: string. """ try: (options, args) = self._parse_arglist(line) except: if ("-h" in line) or ("--help" in line): return ReturnCodes.SUCCESS else: raise InvalidCommandLineErrorOPTS("") url = None headers = {} results = None if options.sessionid: url = self.sessionvalidation(options) else: self.putvalidation(options) contentsholder = None if len(args) == 1: try: inputfile = open(args[0], 'r') contentsholder = json.loads(inputfile.read()) except Exception as excp: raise InvalidFileInputError("%s" % excp) elif len(args) > 1: raise InvalidCommandLineError("Raw put only takes 1 argument.\n") else: raise InvalidCommandLineError("Missing raw put file input "\ "argument.\n") if options.headers: extraheaders = options.headers.split(',') for item in extraheaders: header = item.split(':') try: headers[header[0]] = header[1] except: raise InvalidCommandLineError("Invalid format for " \ "--headers option.") if "path" in contentsholder and "body" in contentsholder: returnresponse = False if options.response or options.getheaders: returnresponse = True results = self._rdmc.app.put_handler(contentsholder["path"], \ contentsholder["body"], verbose=self._rdmc.opts.verbose, \ sessionid=options.sessionid, url=url, headers=headers, \ response=returnresponse, silent=options.silent) else: raise InvalidFileFormattingError("Input file '%s' was not "\ "formatted properly." % args[0]) if results and returnresponse: if options.getheaders: sys.stdout.write(json.dumps(dict(\ results._http_response.getheaders())) + "\n") if options.response: sys.stdout.write(results.text) #Return code return ReturnCodes.SUCCESS
def run(self, line): """ Main raw patch worker function :param line: command line input :type line: string. """ try: (options, _) = self._parse_arglist(line) except (InvalidCommandLineErrorOPTS, SystemExit): if ("-h" in line) or ("--help" in line): return ReturnCodes.SUCCESS else: raise InvalidCommandLineErrorOPTS("") headers = {} results = [] self.postvalidation(options) contentsholder = None try: with open(options.path, 'r') as _if: contentsholder = json.loads(_if.read(), object_pairs_hook=OrderedDict) except IOError: raise InvalidFileInputError("File '%s' doesn't exist. " \ "Please create file by running 'save' command." % options.path) except (ValueError): raise InvalidFileFormattingError("Input file '%s' was not " \ "formatted properly." % options.path) if options.encode: if "body" in contentsholder and "UserName" in contentsholder["body"] and \ "Password" in contentsholder["body"] and \ len(list(contentsholder["body"].keys())) == 2: encobj = Encryption() contentsholder["body"]["UserName"] = encobj.decode_credentials(\ contentsholder["body"]["UserName"]) contentsholder["body"]["Password"] = encobj.decode_credentials(\ contentsholder["body"]["Password"]) if options.headers: extraheaders = options.headers.split(',') for item in extraheaders: header = item.split(':') try: headers[header[0]] = header[1] except: raise InvalidCommandLineError( "Invalid format for --headers option.") if "path" in contentsholder and "body" in contentsholder: results.append(self._rdmc.app.post_handler(contentsholder["path"], \ contentsholder["body"], headers=headers, \ silent=options.silent, service=options.service)) elif all([re.match("^\/(\S+\/?)+$", key) for key in contentsholder]): for path, body in contentsholder.items(): results.append(self._rdmc.app.post_handler(path, \ body, headers=headers, \ silent=options.silent, service=options.service)) else: raise InvalidFileFormattingError("Input file '%s' was not "\ "formatted properly." % options.path) returnresponse = False if options.response or options.getheaders: returnresponse = True if results and returnresponse: for result in results: if options.getheaders: sys.stdout.write( json.dumps(dict(result.getheaders())) + "\n") if options.response: sys.stdout.write(result.ori + "\n") logout_routine(self, options) #Return code return ReturnCodes.SUCCESS