def save_clone(self, clone, filename, options):
        """ save the clone file

        :param clone: filename to save the clone config data
        :type clone: list
        :param filename: filename containing the clone config data
        :type filename: str
        :param options: command line options
        :type options: list.
        """
        if not filename:
            filename = 'clone.json'

        if options.encryption:
            outfile = open(filename, 'wb')
            outfile.write(Encryption().encrypt_file(json.dumps(clone, \
                                separators=(',', ':'), \
                                cls=redfish.ris.JSONEncoder),\
                                options.encryption))
        else:
            outfile = open(filename, 'w')
            #compact
            outfile.write(json.dumps(clone, separators=(',', ':'), \
                                                    cls=redfish.ris.JSONEncoder))

            #human-readable
            #outfile.write(json.dumps(clone, indent=2, cls=redfish.ris.JSONEncoder))
        outfile.close()

        sys.stdout.write("Configuration saved to: %s\n" % filename)
    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
Exemplo n.º 3
0
    def file_handler(self, filename, operation, options, data=None, sk=None):
        """
        Wrapper function to read or write data to a respective file

        :param data: data to be written to output file
        :type data: container (list of dictionaries, dictionary, etc.)
        :param file: filename to be written
        :type file: string (generally this should be self.clone_file or tmp_clone_file
        :param operation: file operation to be performed
        :type operation: string ('w+', 'a+', 'r+')
        :param sk: sort keys flag
        :type sk: boolean
        :param options: command line options
        :type options: attribute
        :returns: json file data
        """
        writeable_ops = ['w', 'w+', 'a', 'a+']
        readable_ops = ['r', 'r+']
        fdata = None

        try:
            if operation in writeable_ops:
                if getattr(options, "encryption", False):
                    with open(filename, operation + 'b') as outfile:
                        outfile.write(Encryption().encrypt_file(json.dumps(data, indent=2, \
                            cls=redfish.ris.JSONEncoder, sort_keys=sk), \
                                                        getattr(options, "encryption", False)))
                else:
                    with open(filename, operation) as outfile:
                        outfile.write(json.dumps(data, indent=2, cls=redfish.ris.JSONEncoder, \
                                                                                sort_keys=sk))
            else:
                if getattr(options, "encryption", False):
                    with open(filename, operation + 'b') as file_handle:
                        fdata = json.loads(Encryption().decrypt_file(file_handle.read(),\
                                                        getattr(options, "encryption", False)))
                else:
                    with open(filename, operation) as file_handle:
                        fdata = json.loads(file_handle.read())
                return fdata
        except Exception as excp:
            raise InvalidFileInputError("Unable to open file: %s.\nVerify the file location " \
                                        "and the file has a valid JSON format.\n" % excp)
Exemplo n.º 4
0
    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
Exemplo n.º 5
0
    def run(self, line):
        """ Main save 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("")

        self.savevalidation(options)

        if args:
            raise InvalidCommandLineError('Save command takes no arguments.')

        sys.stdout.write("Saving configuration...\n")
        if options.filter:
            try:
                if (str(options.filter)[0] == str(options.filter)[-1])\
                        and str(options.filter).startswith(("'", '"')):
                    options.filter = options.filter[1:-1]

                (sel, val) = options.filter.split('=')
                sel = sel.strip()
                val = val.strip()
            except:
                raise InvalidCommandLineError("Invalid filter" \
                  " parameter format [filter_attribute]=[filter_value]")

            instances = self._rdmc.app.select(selector=self._rdmc.app.selector, \
                                                fltrvals=(sel, val), path_refresh=options.ref)
            contents = self.saveworkerfunction(instances=instances)
        else:
            contents = self.saveworkerfunction()

        if options.multisave:
            for select in options.multisave:
                self.selobj.run(select)
                contents += self.saveworkerfunction()

        if not contents:
            raise redfish.ris.NothingSelectedError
        else:
            #TODO: Maybe add this to the command. Not sure we use it elsewhere in the lib
            contents = self.add_save_file_header(contents)

        if options.encryption:
            with open(self.filename, 'wb') as outfile:
                outfile.write(Encryption().encrypt_file(json.dumps(contents, \
                                indent=2, cls=redfish.ris.JSONEncoder), options.encryption))
        else:
            with open(self.filename, 'w') as outfile:
                outfile.write(json.dumps(contents, indent=2, cls=redfish.ris.JSONEncoder, \
                                                                            sort_keys=True))
        sys.stdout.write("Configuration saved to: %s\n" % self.filename)

        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 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("")

        if options.encode and options.user and options.password:
            options.user = Encryption.decode_credentials(options.user)
            options.password = Encryption.decode_credentials(options.password)

        self.savevalidation(options)

        if args:
            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]

                    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)

        if options.encryption:
            outfile = open(self.filename, 'wb')
            outfile.write(Encryption().encrypt_file(json.dumps(contents, \
                                indent=2, cls=redfish.ris.JSONEncoder),\
                                options.encryption))
        else:
            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.run("")

        #Return code
        return ReturnCodes.SUCCESS
Exemplo n.º 8
0
        if len(args) == 1:
            try:
                inputfile = open(args[0], 'r')
                contentsholder = json.loads(inputfile.read())
            except Exception, 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(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.")
Exemplo n.º 9
0
    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