def run(self, line):
        """ Wrapper function for showlogicalnvdimmdrives command main function

        :param line: command line input
        :type line: string.
        """
        LOGGER.info("Scalable PMEM: {}".format(self.name))
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if args:
            raise InvalidCommandLineError("No argument is required.")

        LOGGER.info("Options: {}".format(options))

        if not self._chif_lib:
            self._helpers.failNoChifLibrary()

        self.showDriveData()

        #Return code
        return ReturnCodes.SUCCESS
Beispiel #2
0
    def run(self, line):
        """ Wrapper function for showlogicalnvdimmconfiguration command main function

        :param line: command line input
        :type line: string.
        """

        LOGGER.info("Scalable PMEM: {}".format(self.name))

        try:
            (options, args) = self._parse_arglist(line)
            if options:
                self._options = options
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if len(args):
            InvalidCommandLineError("This command takes no parameters.")

        LOGGER.info("Options: {}".format(options))

        if not self._chif_lib:
            self._helpers.failNoChifLibrary()

        self.showLogicalNvdimmConfig(options)

        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """
        Wrapper function for new command main function
        :param line: command line input
        :type line: string.
        """
        LOGGER.info("PMM: %s", self.name)
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineError("Failed to parse options")

        if args:
            self.validate_args(options)
        self.validate_show_pmem_options(options)
        # Raise exception if server is in POST
        if self._rest_helpers.in_post():
            raise NoContentsFoundForOperationError("Unable to retrieve resources - "\
                                                   "server might be in POST or powered off")
        self.show_pmem_modules(options)

        return ReturnCodes.SUCCESS
    def _run_command(self, opts, args):
        """ Calls the commands run function

        :param opts: command options
        :type opts: options.
        :param args: list of the entered arguments
        :type args: list.
        """
        cmd = self.search_commands(args[0])
        #may conserve memory to have the parser initialized here

        self.load_command(cmd)

        if opts.debug:
            LOGGER.setLevel(logging.DEBUG)
            LERR.setLevel(logging.DEBUG)

        if not opts.nologo and not self.interactive:
            #sys.stdout.write(FIPSSTR) #purpose of this?
            CLI.version(self._progname, versioning.__version__,
                        versioning.__extracontent__)
        if len(args) > 1:
            return cmd.run(args[1:])

        return cmd.run([])
Beispiel #5
0
    def run(self, line):
        """ Wrapper function for new command main function

        :param line: command line input
        :type line: string.
        """
        LOGGER.info("Scalable PMEM: {}".format(self.name))
        try:
            (options, _) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        LOGGER.info("Options: {}".format(options))

        if options.size <= 0:
            self.parser.print_help()
            raise InvalidCommandLineError("Invalid value for --size")

        self.autoselectdrives(options.size, options.confirm)

        #Return code
        return ReturnCodes.SUCCESS
Beispiel #6
0
    def run(self, line):
        """ Wrapper function for setbackupdrives command main function

        :param line: command line input
        :type line: string.
        """
        LOGGER.info("Scalable PMEM: {}".format(self.name))
        try:
            (options, _) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        LOGGER.info("Options: {}".format(options))

        if not self._chif_lib:
            self._helpers.failNoChifLibrary()

        if options.removeAll and options.driveId:
            raise InvalidCommandLineError(u"--device and --remove-all may not "\
                                                        "be used at the same time")
        if options.removeAll:
            return self.removeAllDrives()
        else:
            return self.setDrives(options)
    def run(self, line):
        """ Wrapper function for the Remove logical NVDIMM command

        :param line: command line input
        :type line: string.
        """
        LOGGER.info("Scalable PMEM: {}".format(self.name))
        try:
            (options, _) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if len(args):
            InvalidCommandLineError("This command takes no parameters.")

        LOGGER.info("Options: {}".format(options))

        if not self._chif_lib:
            self._helpers.failNoChifLibrary()

        enable = True
        if options.enableFeature is False:
            enable = False

        self.enableOrDisableFeature(enable)

        #Return code
        return ReturnCodes.SUCCESS
Beispiel #8
0
    def run(self, line):
        """
        Wrapper function for new command main function
        :param line: command line input
        :type line: string.
        """
        LOGGER.info("Clear Pending Configuration: %s", self.name)
        # pylint: disable=unused-variable
        try:
            (options, args) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineError("Failed to parse options")
        if args:
            raise InvalidCommandLineError(
                "Chosen flag doesn't expect additional arguments")
        # Raise exception if server is in POST
        if self._rest_helpers.in_post():
            raise NoContentsFoundForOperationError("Unable to retrieve resources - "\
                                                   "server might be in POST or powered off")
        memory_chunk_tasks = self.get_memory_chunk_tasks()
        self.delete_tasks(memory_chunk_tasks, verbose=True)

        return ReturnCodes.SUCCESS
    def cmdloop(self, opts):
        """ Interactive mode worker function

        :param opts: command options
        :type opts: options.
        """
        self.interactive = True

        if not opts.nologo:
            CLI.version(self._progname, versioning.__version__,\
                                versioning.__extracontent__, fileh=sys.stdout)

        if opts.debug:
            LOGGER.setLevel(logging.DEBUG)
            LERR.setLevel(logging.DEBUG)

        #**********Handler for GUI tab tab ***************
        for section in self._commands:
            if section.startswith('_'):
                continue

            for command in self._commands[section]:
                self.commlist.append(command.name)

        for item in self.commlist:
            if item == "help":
                self.candidates[item] = self.commlist
            else:
                self.candidates[item] = []

        self._redobj = TabAndHistoryCompletionClass(dict(self.candidates))
        readline.set_completer(self._redobj.main_completer_handler)
        readline.parse_and_bind("tab: complete")
        #***************************************************

        while True:
            line = input(versioning.__shortname__ + ' > ')
            readline.add_history(line)

            if not len(line):
                continue
            elif line.endswith(os.linesep):
                line.rstrip(os.linesep)

            nargv = shlex.split(line, posix=False)

            try:
                if "login " in line or line == 'login':
                    self.app.logout()

                self.retcode = self._run_command(opts, nargv)
                self.check_for_tab_lists(nargv)
            except Exception as excp:
                self.handle_exceptions(excp)

            if self.opts.verbose:
                sys.stdout.write(u"REDFISH return code: %s\n" % self.retcode)

        return self.retcode
    def selectfunction(self, line):
        """ Main select 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.selectvalidation(options)

        try:
            if args:
                if options.ref:
                    LOGGER.warn(
                        "Patches from current selection will be cleared.")
                selector = args[0]
                selections = self._rdmc.app.select(selector=selector,
                                                   rel=options.ref)

                if self._rdmc.opts.verbose and selections:
                    templist = list()
                    sys.stdout.write("Selected option(s): ")

                    for item in selections:
                        if item.type not in templist:
                            templist.append(item.type)

                    sys.stdout.write('%s' % ', '.join(map(str, templist)))
                    sys.stdout.write('\n')
            else:
                selector = self._rdmc.app.get_selector()

                if selector:
                    sellist = [sel for sel in self._rdmc.app.current_client.\
                       monolith.typesadded if selector.lower() in sel.lower()]
                    sys.stdout.write("Current selection: ")
                    sys.stdout.write('%s' % ', '.join(map(str, sellist)))
                    sys.stdout.write('\n')
                else:
                    raise InvalidCommandLineError("No type currently selected."\
                                " Please use the 'types' command to\nget a" \
                                " list of types, or pass your type by using" \
                                " the '--selector' flag.")

        except redfish.ris.InstanceNotFoundError as infe:
            raise redfish.ris.InstanceNotFoundError(infe)
    def run(self, line):
        """ Wrapper function for the Remove logical NVDIMM command

        :param line: command line input
        :type line: string.
        """
        LOGGER.info("Scalable PMEM: {}".format(self.name))
        try:
            (options, _) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        LOGGER.info("Options: {}".format(options))

        if not self._chif_lib:
            self._helpers.failNoChifLibrary()

        if not options.processorNumber and not options.processorPair:
            self.parser.print_help()
            raise InvalidCommandLineError(u"One of --processor or --processors"\
                                                                " is required")

        if options.processorNumber and options.processorPair:
            self.parser.print_help()
            raise InvalidCommandLineError(u"--processor and --processors may not"\
                                                        " be used at the same time")

        if options.processorNumber:
            if options.index is None:
                self.parser.print_help()
                raise InvalidCommandLineError(u"--index must be specified with "\
                                                                    "--processor")
            self.removeRegion(options)

        if options.processorPair:
            if not options.index is None:
                self.parser.print_help()
                raise InvalidCommandLineError(u"--index is not a valid option to"\
                                                        " use with --processors")
            self.removeRegion(options)

        #Return code
        return ReturnCodes.SUCCESS
Beispiel #12
0
    def selectfunction(self, line):
        """ Main select worker function

        :param line: command line input
        :type line: string.
        """
        try:
            (options, args) = self.rdmc.rdmc_parse_arglist(self, line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.selectvalidation(options)

        if args:
            if options.ref:
                LOGGER.warn("Patches from current selection will be cleared.")
            selector = args[0]
            selections = self.rdmc.app.select(selector=selector, path_refresh=options.ref)

            if self.rdmc.opts.verbose and selections:
                templist = list()
                self.rdmc.ui.printer("Selected option(s): ")

                for item in selections:
                    if item.type not in templist:
                        templist.append(item.type)

                self.rdmc.ui.printer('%s\n' % ', '.join(map(str, templist)))

        else:
            selector = self.rdmc.app.selector

            if selector:
                sellist = [sel for sel in self.rdmc.app.\
                   monolith.typesadded if selector.lower() in sel.lower()]
                self.rdmc.ui.printer("Current selection: ")
                self.rdmc.ui.printer('%s' % ', '.join(map(str, sellist)))
            else:
                raise NothingSelectedError

        self.cmdbase.logout_routine(self, options)
 def display_data(self, data_to_display, output_format, unique_id_property_name=None):
     """
     Wrapper function for displaying data in the proper format: table, list, json, etc.
     :param data_to_display: The data to display. Each object represents a row in a table
             or an item in a list.
     :type data_to_display: array of objects
     :param output_format: Specifies which output format to use
     :type output_format: enum
     :param unique_id_property_name: Specifies the property which acts as the identifier
     :type unique_id_property_name: string
     """
     if data_to_display is None or data_to_display == []:
         LOGGER.info("DCPMEM: Empty data")
         return None
     if output_format not in self.output_dict:
         LOGGER.info("Incorrect output format")
         return None
     self.output_dict[output_format](data_to_display, unique_id_property_name)
     return None
Beispiel #14
0
    def run(self, line):
        """
        Wrapper function for new command main function
        :param line: command line input
        :type line: string.
        """
        LOGGER.info("PMM Apply Pre-Defined Configuration: %s", self.name)
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineError("Failed to parse options")
        if args:
            self.validate_args(options)
        self.validate_options(options)
        self.apply_pmm_config(options)

        return ReturnCodes.SUCCESS
    def _run_command(self, opts, args):
        """ Calls the commands run function

        :param opts: command options
        :type opts: options.
        :param args: list of the entered arguments
        :type args: list.
        """
        cmd = self.search_commands(args[0])

        if opts.debug:
            LOGGER.setLevel(logging.DEBUG)
            LERR.setLevel(logging.DEBUG)

        if not (opts.nologo or cmd.nologo) and not self.interactive:
            sys.stdout.write(FIPSSTR)
            CLI.version(self._progname, versioning.__version__,\
                                versioning.__extracontent__, fileh=sys.stdout)
        if len(args) > 1:
            return cmd.run(args[1:])

        return cmd.run([])
Beispiel #16
0
    def run(self, line):
        """
        Wrapper function for new command main function
        :param line: command line input
        :type line: string.
        """
        LOGGER.info("PMM Apply Pre-Defined Configuration: %s",
                    self.ident['name'])
        try:
            (options, args) = self.rdmc.rdmc_parse_arglist(self, line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineError("Failed to parse options")
        if args:
            self.validate_args(options)
        self.validate_options(options)
        self.apply_pmm_config(options)

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Beispiel #17
0
    def run(self, line):
        """
        Wrapper function for new command main function
        :param line: command line input
        :type line: string.
        """
        LOGGER.info("PMM Pending Configuration: %s", self.ident['name'])
        try:
            (options, args) = self.rdmc.rdmc_parse_arglist(self, line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineError("Failed to parse options")
        if args:
            raise InvalidCommandLineError(
                "Chosen command or flag doesn't expect additional arguments")
        # Raise exception if server is in POST
        if RestHelpers(rdmcObject=self.rdmc).in_post():
            raise NoContentsFoundForOperationError("Unable to retrieve resources - "\
                                                   "server might be in POST or powered off")
        self.show_pending_config(options)

        return ReturnCodes.SUCCESS
    def run(self, line):
        """
        Wrapper function for new command main function
        :param line: command line input
        :type line: string.
        """
        LOGGER.info("Show Recommended Configuration: %s", self.name)
        try:
            (_, args) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineError("Failed to parse options")
        if args:
            raise InvalidCommandLineError(
                "Chosen command doesn't expect additional arguments")
        # Raise exception if server is in POST
        if self._rest_helpers.in_post():
            raise NoContentsFoundForOperationError("Unable to retrieve resources - "\
                                                   "server might be in POST or powered off")
        self.show_recommended_config()

        return ReturnCodes.SUCCESS
Beispiel #19
0
    def run(self, line):
        """ Wrapper function for the revert configuration command

        :param line: command line input
        :type line: string.
        """
        LOGGER.info("Scalable PMEM: {}".format(self.name))
        try:
            (options, _) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        LOGGER.info("Options: {}".format(options))

        if not self._chif_lib:
            self._helpers.failNoChifLibrary()

        self.revertPendingChanges()

        #Return code
        return ReturnCodes.SUCCESS
    def handle_exceptions(self, excp):
        """ Main exception handler for both shell and interactive modes

        :param excp: captured exception to be handled
        :type excp: exception.
        """
        try:
            if excp:
                errorstr = "Exception: {0}".format(excp.__class__.__name__)
                errorstr = errorstr+"({0})".format(excp.message) if \
                                hasattr(excp, "message") else errorstr
                LOGGER.info(errorstr)
            raise
        # ****** RDMC ERRORS ******
        except ConfigurationFileError as excp:
            self.retcode = ReturnCodes.CONFIGURATION_FILE_ERROR
            UI().error(excp)
            sys.exit(excp.errcode)
        except CommandNotEnabledError as excp:
            self.retcode = ReturnCodes.COMMAND_NOT_ENABLED_ERROR
            UI().command_not_enabled(excp)
            extensions.Commands['HelpCommand'](rdmc=self).run("")
        except InvalidCommandLineError as excp:
            self.retcode = ReturnCodes.INVALID_COMMAND_LINE_ERROR
            UI().invalid_commmand_line(excp)
        except NoCurrentSessionEstablished as excp:
            self.retcode = ReturnCodes.NO_CURRENT_SESSION_ESTABLISHED
            UI().error(excp)
        except NoChangesFoundOrMadeError as excp:
            self.retcode = ReturnCodes.NO_CHANGES_MADE_OR_FOUND
            UI().invalid_commmand_line(excp)
        except StandardBlobErrorHandler as excp:
            self.retcode = ReturnCodes.GENERAL_ERROR
            UI().standard_blob_error(excp)
        except InvalidFileInputError as excp:
            self.retcode = ReturnCodes.INVALID_FILE_INPUT_ERROR
            UI().invalid_commmand_line(excp)
        except InvalidCommandLineErrorOPTS as excp:
            self.retcode = ReturnCodes.INVALID_COMMAND_LINE_ERROR
        except InvalidFileFormattingError as excp:
            self.retcode = ReturnCodes.INVALID_FILE_FORMATTING_ERROR
            UI().invalid_file_formatting(excp)
        except NoContentsFoundForOperationError as excp:
            self.retcode = ReturnCodes.NO_CONTENTS_FOUND_FOR_OPERATION
            UI().no_contents_found_for_operation(excp)
        except InfoMissingEntriesError as excp:
            self.retcode = ReturnCodes.NO_VALID_INFO_ERROR
            UI().error(excp)
        except (InvalidOrNothingChangedSettingsError, redfish.ris.rmc_helper.\
                                                IncorrectPropValue) as excp:
            self.retcode = ReturnCodes.SAME_SETTINGS_ERROR
            UI().error(excp)
        except NoDifferencesFoundError as excp:
            self.retcode = ReturnCodes.NO_CHANGES_MADE_OR_FOUND
            UI().no_differences_found(excp)
        except MultipleServerConfigError as excp:
            self.retcode = ReturnCodes.MULTIPLE_SERVER_CONFIG_FAIL
            UI().multiple_server_config_fail(excp)
        except InvalidMSCfileInputError as excp:
            self.retcode = ReturnCodes.MULTIPLE_SERVER_INPUT_FILE_ERROR
            UI().multiple_server_config_input_file(excp)
        except FirmwareUpdateError as excp:
            self.retcode = ReturnCodes.FIRMWARE_UPDATE_ERROR
            UI().error(excp)
        except FailureDuringCommitError as excp:
            self.retcode = ReturnCodes.FAILURE_DURING_COMMIT_OPERATION
            UI().error(excp)
        except BootOrderMissingEntriesError as excp:
            self.retcode = ReturnCodes.BOOT_ORDER_ENTRY_ERROR
            UI().error(excp)
        except NicMissingOrConfigurationError as excp:
            self.retcode = ReturnCodes.NIC_MISSING_OR_INVALID_ERROR
            UI().error(excp)
        except (IncompatibleiLOVersionError, redfish.ris.rmc_helper.\
                                IncompatibleiLOVersionError) as excp:
            self.retcode = ReturnCodes.INCOMPATIBLE_ILO_VERSION_ERROR
            UI().printmsg(excp)
        except IncompatableServerTypeError as excp:
            self.retcode = ReturnCodes.INCOMPATIBLE_SERVER_TYPE
            UI().printmsg(excp)
        except IloLicenseError as excp:
            UI().printmsg(excp)
            self.retcode = ReturnCodes.ILO_LICENSE_ERROR
        except InvalidCListFileError as excp:
            self.retcode = ReturnCodes.INVALID_CLIST_FILE_ERROR
            UI().error(excp)
        except PartitionMoutingError as excp:
            self.retcode = ReturnCodes.UNABLE_TO_MOUNT_BB_ERROR
            UI().error(excp)
        except TimeOutError as excp:
            self.retcode = ReturnCodes.UPDATE_SERVICE_BUSY
            UI().error(excp)
        except DownloadError as excp:
            self.retcode = ReturnCodes.FAILED_TO_DOWNLOAD_COMPONENT
            UI().error(excp)
        except UploadError as excp:
            self.retcode = ReturnCodes.FAILED_TO_UPLOAD_COMPONENT
            UI().error(excp)
        except BirthcertParseError as excp:
            self.retcode = ReturnCodes.BIRTHCERT_PARSE_ERROR
            UI().error(excp)
        except ResourceExists as excp:
            self.retcode = ReturnCodes.RESOURCE_EXISTS_ERROR
            UI().error(excp)
        except InvalidKeyError as excp:
            self.retcode = ReturnCodes.ENCRYPTION_ERROR
            UI().error("Invalid key has been entered for " \
                        "encryption/decryption.")
        except UnableToDecodeError as excp:
            self.retcode = ReturnCodes.ENCRYPTION_ERROR
            UI().error(excp)
        except UnabletoFindDriveError as excp:
            self.retcode = ReturnCodes.DRIVE_MISSING_ERROR
            UI().error(excp)
            UI().printmsg("Error occurred while reading device labels.")
        except PathUnavailableError as excp:
            self.retcode = ReturnCodes.PATH_UNAVAILABLE_ERROR
            if excp:
                UI().error(excp)
            else:
                UI().printmsg("Requested path is unavailable.")
        except TaskQueueError as excp:
            self.retcode = ReturnCodes.TASKQUEUE_ERROR
            UI().error(excp)
        # ****** CLI ERRORS ******
        except cliutils.CommandNotFoundException as excp:
            self.retcode = ReturnCodes.UI_CLI_COMMAND_NOT_FOUND_EXCEPTION
            UI().command_not_found(excp)
            extensions.Commands['HelpCommand'](rdmc=self).run("")
        # ****** RMC/RIS ERRORS ******
        except redfish.ris.UndefinedClientError:
            self.retcode = ReturnCodes.RIS_UNDEFINED_CLIENT_ERROR
            UI().error("Please login before making a selection")
        except (redfish.ris.InstanceNotFoundError, redfish.ris.\
                RisInstanceNotFoundError) as excp:
            self.retcode = ReturnCodes.RIS_INSTANCE_NOT_FOUND_ERROR
            UI().printmsg(excp)
        except redfish.ris.CurrentlyLoggedInError as excp:
            self.retcode = ReturnCodes.RIS_CURRENTLY_LOGGED_IN_ERROR
            UI().error(excp)
        except redfish.ris.NothingSelectedError as excp:
            self.retcode = ReturnCodes.RIS_NOTHING_SELECTED_ERROR
            UI().nothing_selected()
        except redfish.ris.NothingSelectedFilterError as excp:
            self.retcode = ReturnCodes.RIS_NOTHING_SELECTED_FILTER_ERROR
            UI().nothing_selected_filter()
        except redfish.ris.NothingSelectedSetError as excp:
            self.retcode = ReturnCodes.RIS_NOTHING_SELECTED_SET_ERROR
            UI().nothing_selected_set()
        except redfish.ris.InvalidSelectionError as excp:
            self.retcode = ReturnCodes.RIS_INVALID_SELECTION_ERROR
            UI().error(excp)
        except redfish.ris.rmc_helper.UnableToObtainIloVersionError as excp:
            self.retcode = ReturnCodes.INCOMPATIBLE_ILO_VERSION_ERROR
            UI().error(excp)
        except redfish.ris.IdTokenError as excp:
            if excp.message:
                UI().printmsg(excp.message)
            else:
                UI().printmsg(u"Logged-in account does not have the privilege "\
                              " required to fulfill the request or a required "\
                              " token is missing."\
                              "\nEX: biospassword flag if bios password present "\
                              "or tpmenabled flag if TPM module present.")
            self.retcode = ReturnCodes.RIS_MISSING_ID_TOKEN
        except redfish.ris.SessionExpired as excp:
            self.retcode = ReturnCodes.RIS_SESSION_EXPIRED
            self.app.logout()
            UI().printmsg("Current session has expired or is invalid, "\
                    "please login again with proper credentials to continue.\n")
        except redfish.ris.ValidationError as excp:
            self.retcode = ReturnCodes.RIS_VALIDATION_ERROR
        except redfish.ris.ValueChangedError as excp:
            self.retcode = ReturnCodes.RIS_VALUE_CHANGED_ERROR
        except redfish.ris.ris.SchemaValidationError as excp:
            UI().printmsg("Error found in schema, try running with the "\
                          "--latestschema flag.")
            self.retcode = ReturnCodes.RIS_SCHEMA_PARSE_ERROR
        # ****** RMC/RIS ERRORS ******
        except redfish.rest.v1.RetriesExhaustedError as excp:
            self.retcode = ReturnCodes.V1_RETRIES_EXHAUSTED_ERROR
            UI().retries_exhausted_attemps()
        except redfish.rest.v1.InvalidCredentialsError as excp:
            self.retcode = ReturnCodes.V1_INVALID_CREDENTIALS_ERROR
            UI().invalid_credentials(excp)
        except redfish.rest.v1.JsonDecodingError as excp:
            self.retcode = ReturnCodes.JSON_DECODE_ERROR
            UI().error(excp)
        except redfish.rest.v1.ServerDownOrUnreachableError as excp:
            self.retcode = \
                    ReturnCodes.V1_SERVER_DOWN_OR_UNREACHABLE_ERROR
            UI().error(excp)
        except redfish.rest.v1.ChifDriverMissingOrNotFound as excp:
            self.retcode = ReturnCodes.V1_CHIF_DRIVER_MISSING_ERROR
            UI().printmsg("Chif driver not found, please check that the " \
                                            "chif driver is installed.")
        except redfish.rest.v1.SecurityStateError as excp:
            self.retcode = ReturnCodes.V1_SECURITY_STATE_ERROR
            if isinstance(excp.message, int):
                UI().printmsg("High security mode [%s] has been enabled. " \
                              "Please provide credentials." % excp.message)
            else:
                UI().error(excp)
        except redfish.hpilo.risblobstore2.ChifDllMissingError as excp:
            self.retcode = ReturnCodes.REST_ILOREST_CHIF_DLL_MISSING_ERROR
            UI().printmsg("iLOrest Chif dll not found, please check that the "\
                                            "chif dll is present.")
        except redfish.hpilo.risblobstore2.UnexpectedResponseError as excp:
            self.retcode = ReturnCodes.REST_ILOREST_UNEXPECTED_RESPONSE_ERROR
            UI().printmsg("Unexpected data received from iLO.")
        except redfish.hpilo.risblobstore2.HpIloError as excp:
            self.retcode = ReturnCodes.REST_ILOREST_ILO_ERROR
            UI().printmsg("iLO returned a failed error code.")
        except redfish.hpilo.risblobstore2.Blob2CreateError as excp:
            self.retcode = ReturnCodes.REST_ILOREST_CREATE_BLOB_ERROR
            UI().printmsg("Blob create operation failed.")
        except redfish.hpilo.risblobstore2.Blob2ReadError as excp:
            self.retcode = ReturnCodes.REST_ILOREST_READ_BLOB_ERROR
            UI().printmsg("Blob read operation failed.")
        except redfish.hpilo.risblobstore2.Blob2WriteError as excp:
            self.retcode = ReturnCodes.REST_ILOREST_WRITE_BLOB_ERROR
            UI().printmsg("Blob write operation failed.")
        except redfish.hpilo.risblobstore2.Blob2DeleteError as excp:
            self.retcode = ReturnCodes.REST_ILOREST_BLOB_DELETE_ERROR
            UI().printmsg("Blob delete operation failed.")
        except redfish.hpilo.risblobstore2.Blob2OverrideError as excp:
            self.retcode = ReturnCodes.REST_ILOREST_BLOB_OVERRIDE_ERROR
            UI().error(excp)
            UI().printmsg("\nBlob was overwritten by another user. Please " \
                  "ensure only one user is making changes at a time locally.")
        except redfish.hpilo.risblobstore2.BlobRetriesExhaustedError as excp:
            self.retcode = ReturnCodes.REST_BLOB_RETRIES_EXHAUSETED_ERROR
            UI().printmsg("\nBlob operation still fails after max retries.")
        except redfish.hpilo.risblobstore2.Blob2FinalizeError as excp:
            self.retcode = ReturnCodes.REST_ILOREST_BLOB_FINALIZE_ERROR
            UI().printmsg("Blob finalize operation failed.")
        except redfish.hpilo.risblobstore2.BlobNotFoundError as excp:
            self.retcode = ReturnCodes.REST_ILOREST_BLOB_NOT_FOUND_ERROR
            UI().printmsg("Blob not found with key and namespace provided.")
        except redfish.ris.rmc_helper.InvalidPathError as excp:
            self.retcode = ReturnCodes.RIS_REF_PATH_NOT_FOUND_ERROR
            UI().printmsg("Reference path not found.")
        except redfish.ris.rmc_helper.IloResponseError as excp:
            self.retcode = ReturnCodes.RIS_ILO_RESPONSE_ERROR
        except redfish.ris.rmc_helper.UserNotAdminError as excp:
            UI().user_not_admin()
            self.retcode = ReturnCodes.USER_NOT_ADMIN
        except redfish.hpilo.rishpilo.HpIloInitialError as excp:
            UI().error(excp)
            self.retcode = ReturnCodes.RIS_ILO_INIT_ERROR
        except redfish.hpilo.rishpilo.HpIloWriteError as excp:
            UI().error(excp)
            self.retcode = ReturnCodes.RESOURCE_ALLOCATION_ISSUES_ERROR
        except redfish.hpilo.rishpilo.HpIloReadError as excp:
            UI().error(excp)
            self.retcode = ReturnCodes.RESOURCE_ALLOCATION_ISSUES_ERROR
        # ****** RIS OBJECTS ERRORS ******
        except redfish.ris.ris.BiosUnregisteredError as excp:
            self.retcode = ReturnCodes.RIS_RIS_BIOS_UNREGISTERED_ERROR
            UI().bios_unregistered_error()
        # ****** GENERAL ERRORS ******
        except SystemExit:
            self.retcode = ReturnCodes.GENERAL_ERROR
            raise
        except Exception as excp:
            self.retcode = ReturnCodes.GENERAL_ERROR
            sys.stderr.write('ERROR: %s\n' % excp)

            if self.opts.debug:
                traceback.print_exc(file=sys.stderr)
    def run(self, line):
        """ Main rdmc command worker function

        :param line: entered command line
        :type line: list.
        """
        if os.name == 'nt':
            if not ctypes.windll.shell32.IsUserAnAdmin() != 0:
                self.app.typepath.adminpriv = False
        elif not os.getuid() == 0:
            self.app.typepath.adminpriv = False

        nargv = []
        curr = []
        argfound = False

        if "--version" in line or "-V" in line:
            sys.stdout.write("""%(progname)s %(version)s\n""" % \
                     {'progname': versioning.__longname__, 'version': \
                                                        versioning.__version__})
            sys.stdout.flush()
            sys.exit(self.retcode)

        else:
            for argument in enumerate(line):
                if not argfound and not argument[1].startswith('-'):
                    nargv = line[argument[0]:]
                    break
                else:
                    argfound = False

                if argument[1] == "-c":
                    argfound = True

                curr.append(argument[1])

        (self.opts, _) = self.parser.parse_args(curr)

        try:
            Encryption.encode_credentials('test')
            self.app.set_encode_funct(Encryption.encode_credentials)
            self.app.set_decode_funct(Encryption.decode_credentials)
            self.encoding = True
        except redfish.hpilo.risblobstore2.ChifDllMissingError:
            self.encoding = False

        if self.opts.config is not None and len(self.opts.config) > 0:
            if not os.path.isfile(self.opts.config):
                self.retcode = ReturnCodes.CONFIGURATION_FILE_ERROR
                sys.exit(self.retcode)

            self.app.config_file = self.opts.config

        self.app.config_from_file(self.app.config_file)
        if self.opts.logdir and self.opts.debug:
            logdir = self.opts.logdir
        else:
            logdir = self.app.config.get_logdir()

        if logdir and self.opts.debug:
            try:
                os.makedirs(logdir)
            except OSError as ex:
                if ex.errno == errno.EEXIST:
                    pass
                else:
                    raise

        if self.opts.debug:
            logfile = os.path.join(logdir, versioning.__shortname__ + '.log')

            # Create a file logger since we got a logdir
            lfile = logging.FileHandler(filename=logfile)
            formatter = logging.Formatter("%(asctime)s %(levelname)s\t: " \
                                                                "%(message)s")

            lfile.setFormatter(formatter)
            lfile.setLevel(logging.DEBUG)
            LOGGER.addHandler(lfile)
            self.app.LOGGER = LOGGER

        cachedir = None
        if self.opts.nocache:
            self.app.config.set_cache(False)
        else:
            self.app.config.set_cachedir(os.path.join(self.opts.config_dir, \
                                                                        'cache'))
            cachedir = self.app.config.get_cachedir()

        if cachedir:
            try:
                os.makedirs(cachedir)
            except OSError as ex:
                if ex.errno == errno.EEXIST:
                    pass
                else:
                    raise

        if ("login" in line or any(x.startswith("--url") for x in line) or not line)\
                        and not (any(x.startswith(("-h", "--h")) for x in nargv) or "help" in line):
            self.app.logout()
        else:
            self.app.restore()
            self.opts.is_redfish = self.app.updatedefinesflag(redfishflag=\
                                                        self.opts.is_redfish)

        if nargv:
            try:
                self.retcode = self._run_command(self.opts, nargv)
                if self.app.config.get_cache():
                    if ("logout" not in line) and ("--logout" not in line):
                        self.app.save()
                else:
                    self.app.logout()
            except Exception as excp:
                self.handle_exceptions(excp)

            return self.retcode
        else:
            self.cmdloop(self.opts)

            if self.app.config.get_cache():
                self.app.save()
            else:
                self.app.logout()
Beispiel #22
0
    def run(self, line):
        """ Main rdmc command worker function

        :param line: entered command line
        :type line: list.
        """
        if os.name == 'nt':
            if not ctypes.windll.shell32.IsUserAnAdmin() != 0:
                UI().user_not_admin()
                raw_input("Press enter to exit")
                sys.exit(ReturnCodes.USER_NOT_ADMIN)
        elif not os.getuid() == 0:
            UI().user_not_admin()
            raw_input("Press enter to exit")
            sys.exit(ReturnCodes.USER_NOT_ADMIN)

        nargv = []
        curr = []
        argfound = False

        if "--version" in line:
            sys.stdout.write("""%(progname)s %(version)s\n""" % \
                     {'progname': versioning.__longname__, 'version': \
                                                        versioning.__version__})

            sys.stdout.flush()
            sys.exit(self.retcode)
        else:
            for argument in enumerate(line):
                if not argfound and not argument[1].startswith('-'):
                    nargv = line[argument[0]:]
                    break
                else:
                    argfound = False

                if argument[1] == "-c":
                    argfound = True

                curr.append(argument[1])

        (self.opts, _) = self.parser.parse_args(curr)

        if self.opts.config is not None and len(self.opts.config) > 0:
            if not os.path.isfile(self.opts.config):
                self.retcode = ReturnCodes.CONFIGURATION_FILE_ERROR
                sys.exit(self.retcode)

            self.app.config_file = self.opts.config

        self.app.config_from_file(self.app.config_file)
        logdir = self.app.config.get_logdir()

        if logdir:
            try:
                os.makedirs(logdir)
            except OSError as ex:
                if ex.errno == errno.EEXIST:
                    pass
                else:
                    raise

        logfile = os.path.join(logdir, versioning.__shortname__ + '.log')

        # Create a file logger since we got a logdir
        lfile = logging.FileHandler(filename=logfile)
        formatter = logging.Formatter("%(asctime)s %(levelname)s\t: " \
                                                                "%(message)s")

        lfile.setFormatter(formatter)
        lfile.setLevel(logging.DEBUG)
        LOGGER.addHandler(lfile)
        self.app.LOGGER = LOGGER

        if self.opts.nocache:
            self.app.config.set_cache(False)

        self.app.config.set_cachedir(os.path.join(self.opts.config_dir, \
                                                                    'cache'))
        cachedir = self.app.config.get_cachedir()

        if cachedir:
            try:
                os.makedirs(cachedir)
            except OSError as ex:
                if ex.errno == errno.EEXIST:
                    pass
                else:
                    raise

        if ("login" in line and not "help" in line) or not line:
            self.app.logout()
        else:
            self.app.restore()

        if len(nargv) > 0:
            try:
                self.retcode = self._run_command(self.opts, nargv)
                if self.app.config.get_cache():
                    if ("logout" not in line) and ("--logout" not in line):
                        self.app.save()
            except Exception as excp:
                self.handle_exceptions(excp)

            return self.retcode
        else:
            self.cmdloop(self.opts)

            if self.app.config.get_cache():
                self.app.save()
Beispiel #23
0
    def run(self, line):
        """ Main rdmc command worker function

        :param line: entered command line
        :type line: list.
        """
        if os.name == 'nt':
            if not ctypes.windll.shell32.IsUserAnAdmin() != 0:
                self.app.typepath.adminpriv = False
        elif not os.getuid() == 0:
            self.app.typepath.adminpriv = False

        nargv = []

        if "--version" in line or "-V" in line:
            sys.stdout.write("""%(progname)s %(version)s\n""" % \
                     {'progname': versioning.__longname__, 'version': \
                                                        versioning.__version__})
            sys.stdout.flush()
            sys.exit(self.retcode)

        (self.opts, nargv) = self.parser.parse_known_args(line)

        if self.opts.silent:
            if isinstance(self.opts.silent, (int, float)):
                new_tgt = os.devnull
            else:
                new_tgt = self.opts.silent

            sys.stdout = open(new_tgt, 'w')
            sys.stdout.write("Start stdout file.\n\n")

        self.app.verbose = self.opts.verbose

        try:
            #Test encoding functions are there
            Encryption.encode_credentials('test')
            self.app.set_encode_funct(Encryption.encode_credentials)
            self.app.set_decode_funct(Encryption.decode_credentials)
            self.encoding = True
        except redfish.hpilo.risblobstore2.ChifDllMissingError:
            self.encoding = False

        if self.opts.config is not None and len(self.opts.config) > 0:
            if not os.path.isfile(self.opts.config):
                self.retcode = ReturnCodes.CONFIGURATION_FILE_ERROR
                sys.exit(self.retcode)

            self.config.configfile = self.opts.config
        else:
            # Default locations: Windows: executed directory Linux: /etc/ilorest/redfish.conf
            self.config.configfile = os.path.join(os.path.dirname(sys.executable), \
             'redfish.conf') if os.name == 'nt' else '/etc/ilorest/redfish.conf'

        if not os.path.isfile(self.config.configfile):
            LOGGER.warning("Config file '%s' not found\n\n",
                           self.config.configfile)

        self.config.load()

        cachedir = None
        if not self.opts.nocache:
            self.config.cachedir = os.path.join(self.opts.config_dir, 'cache')
            cachedir = self.config.cachedir

        if cachedir:
            self.app.cachedir = cachedir
            try:
                os.makedirs(cachedir)
            except OSError as ex:
                if ex.errno == errno.EEXIST:
                    pass
                else:
                    raise

        if self.opts.logdir and self.opts.debug:
            logdir = self.opts.logdir
        else:
            logdir = self.config.logdir

        if logdir and self.opts.debug:
            try:
                os.makedirs(logdir)
            except OSError as ex:
                if ex.errno == errno.EEXIST:
                    pass
                else:
                    raise

        if self.opts.debug:
            logfile = os.path.join(logdir, versioning.__shortname__ + '.log')

            # Create a file logger since we got a logdir
            lfile = logging.FileHandler(filename=logfile)
            formatter = logging.Formatter(
                "%(asctime)s %(levelname)s\t: %(message)s")

            lfile.setFormatter(formatter)
            lfile.setLevel(logging.DEBUG)
            LOGGER.addHandler(lfile)
            self.app.LOGGER = LOGGER

        if ("login" in line or any(x.startswith("--url") for x in line) or not line)\
                        and not (any(x.startswith(("-h", "--h")) for x in nargv) or "help" in line):
            self.app.logout()
        else:
            creds, enc = self._pull_creds(nargv)
            self.app.restore(creds=creds, enc=enc)
            self.opts.is_redfish = self.app.typepath.updatedefinesflag(\
                                                                redfishflag=self.opts.is_redfish)

        if nargv:
            try:
                self.retcode = self._run_command(self.opts, nargv)
                if self.app.cache:
                    if ("logout" not in line) and ("--logout" not in line):
                        self.app.save()
                        self.app.redfishinst = None
                else:
                    self.app.logout()
            except Exception as excp:
                self.handle_exceptions(excp)

            return self.retcode
        else:
            self.cmdloop(self.opts)

            if self.app.cache:
                self.app.save()
            else:
                self.app.logout()
Beispiel #24
0
    def cmdloop(self, opts):
        """ Interactive mode worker function

        :param opts: command options
        :type opts: options.
        """
        self.interactive = True

        if not opts.nologo:
            sys.stdout.write(FIPSSTR)
            CLI.version(self._progname, versioning.__version__,\
                                versioning.__extracontent__, fileh=sys.stdout)

        if not self.app.typepath.adminpriv:
            UI().user_not_admin()

        if opts.debug:
            LOGGER.setLevel(logging.DEBUG)
            LERR.setLevel(logging.DEBUG)

        #**********Handler for GUI tab tab ***************
        for section in self._commands:
            if section.startswith('_'):
                continue

            for command in self._commands[section]:
                self.commlist.append(command.name)

        for item in self.commlist:
            if item == "help":
                self.candidates[item] = self.commlist
            else:
                self.candidates[item] = []

        self._redobj = TabAndHistoryCompletionClass(dict(self.candidates))
        try:
            session = PromptSession(completer=self._redobj, \
                                                        complete_style=CompleteStyle.READLINE_LIKE)

        except:
            LOGGER.info("Console error: Tab complete is unavailable.")
            session = None

        while True:
            try:
                if session:
                    line = session.prompt(versioning.__shortname__+ u' > ', \
                                bottom_toolbar=self._redobj.bottom_toolbar)
                else:
                    line = input(versioning.__shortname__ + u' > ')

            except (EOFError, KeyboardInterrupt) as error:
                line = "quit\n"

            if not len(line):
                continue
            elif line.endswith(os.linesep):
                line.rstrip(os.linesep)

            nargv = shlex.split(line, posix=False)

            try:
                if not (any(x.startswith("-h") for x in nargv) or \
                    any(x.startswith("--h") for x in nargv) or "help" in line):
                    if "login " in line or line == 'login' or \
                        any(x.startswith("--url") for x in nargv):
                        self.app.logout()
                self.retcode = self._run_command(opts, nargv)
                self.check_for_tab_lists(nargv)
            except Exception as excp:
                self.handle_exceptions(excp)

            if self.opts.verbose:
                sys.stdout.write("iLOrest return code: %s\n" % self.retcode)

        return self.retcode
    def run(self, line):
        """ Main rdmc command worker function

        :param line: entered command line
        :type line: list.
        """
        if os.name == 'nt':
            if not ctypes.windll.shell32.IsUserAnAdmin() != 0:
                self.app.typepath.adminpriv = False
        elif not os.getuid() == 0:
            self.app.typepath.adminpriv = False

        if "--version" in line or "-V" in line:
            CLI.printer("%s %s\n" %
                        (versioning.__longname__, versioning.__version__))
            sys.exit(self.retcode)

        all_opts = True
        help_indx = None
        help_list = ['-h', '--help', 'help']
        for indx, elem in enumerate(line):
            if elem in help_list:
                help_indx = indx
            if '-' in elem:
                continue
            else:
                all_opts = False
        if all_opts and ('-h' in line) or ('--help' in line):
            line = ['-h']
        elif help_indx:
            del line[help_indx]

        (self.opts, nargv) = self.parser.parse_known_args(line)

        if self.opts.redirect:
            try:
                sys.stdout = open("console.log", 'w')
            except:
                print("Unable to re-direct output for STDOUT.\n")
            else:
                print("Start of stdout file.\n\n")
            try:
                sys.stderr = open("console_err.log", 'w')
            except IOError:
                print("Unable to re-direct output for STDERR.\n")
            else:
                print("Start of stderr file.\n\n")

        self.app.verbose = self.ui.verbosity = self.opts.verbose

        try:
            #Test encoding functions are there
            Encryption.encode_credentials('test')
            self.app.set_encode_funct(Encryption.encode_credentials)
            self.app.set_decode_funct(Encryption.decode_credentials)
            self.encoding = True
        except redfish.hpilo.risblobstore2.ChifDllMissingError:
            self.encoding = False

        if self.opts.config is not None and len(self.opts.config) > 0:
            if not os.path.isfile(self.opts.config):
                self.retcode = ReturnCodes.CONFIGURATION_FILE_ERROR
                sys.exit(self.retcode)

            self.config.configfile = self.opts.config
        else:
            # Default locations: Windows: executed directory Linux: /etc/ilorest/redfish.conf
            self.config.configfile = os.path.join(os.path.dirname(sys.executable), \
             'redfish.conf') if os.name == 'nt' else '/etc/ilorest/redfish.conf'

        if not os.path.isfile(self.config.configfile):
            LOGGER.warning("Config file '%s' not found\n\n",
                           self.config.configfile)

        self.config.load()

        cachedir = None
        if not self.opts.nocache:
            self.config.cachedir = os.path.join(self.opts.config_dir, 'cache')
            cachedir = self.config.cachedir

        if cachedir:
            self.app.cachedir = cachedir
            try:
                os.makedirs(cachedir)
            except OSError as ex:
                if ex.errno == errno.EEXIST:
                    pass
                else:
                    raise

        if self.opts.logdir and self.opts.debug:
            logdir = self.opts.logdir
        else:
            logdir = self.config.logdir

        if logdir and self.opts.debug:
            try:
                os.makedirs(logdir)
            except OSError as ex:
                if ex.errno == errno.EEXIST:
                    pass
                else:
                    raise

        if self.opts.debug:
            logfile = os.path.join(logdir, versioning.__shortname__ + '.log')

            # Create a file logger since we got a logdir
            lfile = logging.FileHandler(filename=logfile)
            formatter = logging.Formatter(
                "%(asctime)s %(levelname)s\t: %(message)s")

            lfile.setFormatter(formatter)
            lfile.setLevel(logging.DEBUG)
            LOGGER.addHandler(lfile)
            self.app.LOGGER = LOGGER

        if ("login" in line or any(x.startswith("--url") for x in line) or not line)\
                        and not (any(x.startswith(("-h", "--h")) for x in nargv) or "help" in line):
            self.app.logout()
        else:
            creds, enc = self._pull_creds(nargv)
            self.app.restore(creds=creds, enc=enc)
            self.opts.is_redfish = self.app.typepath.updatedefinesflag(\
                                                                redfishflag=self.opts.is_redfish)

        if nargv:
            try:
                self.retcode = self._run_command(self.opts, nargv)
                if self.app.cache:
                    if ("logout" not in line) and ("--logout" not in line):
                        self.app.save()
                        self.app.redfishinst = None
                else:
                    self.app.logout()
            except Exception as excp:
                self.handle_exceptions(excp)

            return self.retcode
        else:
            self.cmdloop(self.opts)

            if self.app.cache:
                self.app.save()
            else:
                self.app.logout()