def checktoprint(self, options, contents, nocontent, arg):
     """ function to decide what/how to print
     :param options: list of options
     :type options: list.
     :param contents: dictionary value returned by getprops.
     :type contents: dict.
     :param nocontent: props not found are added to the list.
     :type nocontent: list.
     :param arg: string of args
     :type arg: string
     """
     if options and options.json and contents:
         UI().print_out_json(contents)
     elif contents:
         UI().print_out_human_readable(contents)
     else:
         try:
             if nocontent or not any(next(iter(contents))):
                 raise Exception()
         except:
             strtoprint = ', '.join(str(val) for val in nocontent)
             if not strtoprint and arg:
                 strtoprint = arg
                 raise NoContentsFoundForOperationError('No get contents '\
                                        'found for entry: %s' % strtoprint)
             else:
                 raise NoContentsFoundForOperationError('No get contents '\
                                                'found for selected type.')
    def getworkerhelper(self, results, content, newlist, newargs, jsono=False):
        """ helper function for list items

        :param results: current results collected
        :type results: string.
        :param content: current content to work on
        :type content: string.
        :param newlist: new style list
        :type newlist: list.
        :param newargs: new style arguments
        :type newargs: list.
        :param jsono: boolean to determine output style
        :type jsono: boolean.
        """
        somethingfound = False
        innerresults = OrderedDict()
        listitem = False
        for item in newargs:
            if isinstance(content, list):
                if not content:
                    return

                if len(content) > 1:
                    argleft = [x for x in newargs if x not in newlist]
                    _ = [self.getworkerhelper(results, content[x], newlist[:],\
                                argleft, jsono) for x in range(len(content))]
                    listitem = True
                    break
                else:
                    content = content[0]

            for key in content.keys():
                if item.lower() == key.lower():
                    newlist.append(key)
                    content = content.get(key)
                    somethingfound = True
                    break
            else:
                somethingfound = False

            if not somethingfound:
                return somethingfound

        counter = 0
        for item in reversed(newlist):
            if counter == 0:
                innerresults = {item: content}
                counter += 1
            else:
                innerresults = {item: innerresults}
                content = innerresults

        if somethingfound and results:
            return content
        elif somethingfound and not listitem:
            if jsono:
                UI().print_out_json(content)
            else:
                UI().print_out_human_readable(content)
Ejemplo n.º 3
0
    def __init__(self, name, usage, summary, aliases, argparser, Args=None):
        super().__init__(name, usage, summary, aliases, argparser)
        self._commands = collections.OrderedDict()
        self.ui = UI(1)
        self.commands_dict = dict()
        self.interactive = False
        self._progname = '%s : %s' % (versioning.__shortname__, \
                                      versioning.__longname__)
        self.opts = None
        self.encoding = None
        self.config = RdmcConfig()
        self.app = redfish.ris.RmcApp(showwarnings=True)
        self.retcode = 0
        self.candidates = dict()
        self.comm_map = dict()  #point command id names or alias to handle
        self.commlist = list()
        self._redobj = None
        self.loaded_commands = []

        #import all extensions dynamically
        for name in extensions.classNames:
            pkgName, cName = name.rsplit('.', 1)
            pkgName = 'extensions' + pkgName
            try:
                if '__pycache__' not in pkgName and 'Command' in cName:
                    self.commands_dict[cName] = getattr(
                        importlib.import_module(pkgName), cName)()
                    sName = pkgName.split('.')[1]
                    self.add_command(cName, section=sName)
            except cliutils.ResourceAllocationError as excp:
                self.ui.error(excp)
                retcode = ReturnCodes.RESOURCE_ALLOCATION_ISSUES_ERROR
                self.ui.error("Unable to allocate more resources.")
                self.ui.printer(("ILOREST return code: %s\n" % retcode))
                sys.exit(retcode)
            except Exception as excp:
                self.ui.error(("loading command: %s" % cName), None)

        #command mapping
        commands_to_remove = []
        for command in self.commands_dict:
            try:
                self.comm_map[self.commands_dict[command].ident.get(
                    'name')] = command
                for alias in self.commands_dict[command].ident.get('aliases'):
                    self.comm_map[alias] = command
            except Exception as excp:
                self.ui.command_not_enabled(("Command \'%s\' unable to be "\
                    "initialized...Removing" % command), excp)
                commands_to_remove.append(command)

        # removing commands marked for deletion
        for cmd in commands_to_remove:
            del self.commands_dict[cmd]
        del commands_to_remove
Ejemplo n.º 4
0
    def run(self, line):
        """ Main serverinfo function.

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        if args:
            raise InvalidCommandLineError("serverinfo command takes no "\
                                          "arguments.")

        self.serverinfovalidation(options)

        info = self.gatherinfo(options)

        if not info:
            raise InvalidCommandLineError(
                "Please add options to view server info.")

        if options.json:
            UI().print_out_json(info)
        else:
            self.prettyprintinfo(info, options.showabsent)

        return ReturnCodes.SUCCESS
    def run(self, line, autotest=False):
        """ Main info worker function

        :param line: command line input
        :type line: string.
        :param autotest: flag to determine if running automatictesting
        :type autotest: bool.
        """
        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.infovalidation(options)

        if args:
            inforesp = ''

            for item in args:
                newargs = list()
                if self._rdmc.app.get_selector().lower().startswith('bios.') \
                                        and not 'attributes' in item.lower():
                    if not (item.lower() in HARDCODEDLIST or '@odata' in item.lower()):
                        item = "Attributes/" + item

                if "/" in item:
                    newargs = item.split("/")
                    item = newargs[0]

                (contents, outdata) = self._rdmc.app.info(selector=item, \
                    dumpjson=options.json, autotest=autotest, newarg=newargs, \
                                            latestschema=options.latestschema)
                if outdata and options.json:
                    UI().print_out_json(outdata)
                elif outdata:
                    sys.stdout.write(outdata)

                if isinstance(contents, list) and not autotest:
                    if 'none' in contents and inforesp != 'success':
                        inforesp = 'none'
                    elif 'Success' in contents:
                        inforesp = 'success'

                try:
                    if not contents or inforesp == 'none':
                        raise InfoMissingEntriesError("There are no valid "\
                            "entries for info in the current instance.")
                except Exception, excp:
                    raise excp

                if len(args) > 1 and not item == args[-1]:
                    sys.stdout.write("\n************************************"\
                                     "**************\n")
    def get_running_job(self):
        """
        Retrieves and decodes, running job
        :return returncode: int
        """

        results = self._rdmc.app.get_handler(self.running_jobs, silent=True)
        if results.status == 404:
            raise PathUnavailableError("The Intelligent Provisioning resource "\
                                   "is not available on this system. You may need"\
                                   " to run IP at least once to add the resource.")

        if results and results.status == 200:
            j2python = json.loads(results.read)
            for _, val in enumerate(j2python.keys()):
                if isinstance(val, six.string_types):
                    result = self.decode_base64_string(str(j2python[val]))
                    if result is not None:
                        j2python[val] = result

            results.read = json.dumps(j2python, ensure_ascii=False)
            if results.dict:
                UI().print_out_json(results.dict)
        else:
            sys.stdout.write("No IP profiles found\n")
Ejemplo n.º 7
0
    def run(self, line):
        """ Main raw head 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.headvalidation(options)

        if len(args) > 1:
            raise InvalidCommandLineError("Raw head only takes 1 argument.\n")
        elif not args:
            raise InvalidCommandLineError("Missing raw head input path.\n")

        if args[0].startswith('"') and args[0].endswith('"'):
            args[0] = args[0][1:-1]

        results = self._rdmc.app.head_handler(args[0], silent=options.silent, \
             service=options.service)

        content = None
        tempdict = dict()

        if results and results.status == 200:
            if results._http_response:
                content = results.getheaders()
            else:
                content = results._headers

            tempdict = dict(content)

            if options.filename:
                output = json.dumps(tempdict,
                                    indent=2,
                                    cls=redfish.ris.JSONEncoder,
                                    sort_keys=True)
                filehndl = open(options.filename[0], "w")
                filehndl.write(output)
                filehndl.close()

                sys.stdout.write("Results written out to '%s'.\n" %
                                 options.filename[0])
            else:
                if options.service:
                    sys.stdout.write("%s\n" % tempdict)
                else:
                    UI().print_out_json(tempdict)
        else:
            return ReturnCodes.NO_CONTENTS_FOUND_FOR_OPERATION

        #Return code
        return ReturnCodes.SUCCESS
    def vmdefaulthelper(self, options, paths):
        """Worker function to reset virtual media config to default

        :param paths: virtual media paths
        :type paths: list
        :param options: command line options
        :type options: list.
        """
        images = {}
        count = 0
        mediatypes = self.auxcommands['get'].getworkerfunction(\
            "MediaTypes", options, results=True, uselist=False)
        ids = self.auxcommands['get'].getworkerfunction("Id",
                                                        options,
                                                        results=True,
                                                        uselist=False)
        ids = {ind: id for ind, id in enumerate(ids)}
        mediatypes = {ind: med for ind, med in enumerate(mediatypes)}
        # To keep indexes consistent between versions
        if not list(ids.keys())[0] == list(list(ids.values())[0].values())[0]:
            finalmet = {}
            for mount in mediatypes:
                finalmet.update(
                    {int(list(ids[mount].values())[0]): mediatypes[mount]})
            mediatypes = finalmet

        for path in paths:
            count += 1
            image = self.rdmc.app.get_handler(paths[path],
                                              service=True,
                                              silent=True)
            image = image.dict['Image']
            images.update({path: image})

        self.rdmc.ui.printer("Available Virtual Media Options:\n")
        if getattr(options, "json", False):
            json_str = dict()
            json_str['MediaTypes'] = dict()
        else:
            self.rdmc.ui.printer("Available Virtual Media Options:\n")

        for image in images:
            media = ""

            if images[image]:
                imagestr = images[image]
            else:
                imagestr = "None"

            for medtypes in mediatypes[image]['MediaTypes']:
                media += medtypes + " "

            if getattr(options, "json", False):
                json_str['MediaTypes'][str(media)] = imagestr
            else:
                self.rdmc.ui.printer("[%s] Media Types Available: %s Image Inserted:" \
                                        " %s\n" %(str(image), str(media), imagestr))
        if getattr(options, "json", False):
            UI().print_out_json(json_str)
    def selection_output(self, options, content):
        """ Selection of output for smart array command

        :param options: command line options
        :type options: attributes
        :param content: ordered dictionary of properties
        :type content: dictionary
        """
        controldict = {}
        outputcontent = False
        use_slot = False
        use_indx = False

        for _opt in options.controller:
            found = False
            for pos, control in enumerate(content):
                if isinstance(_opt, int) and not use_slot:
                    if pos == (_opt - 1):
                        controldict[_opt] = content[control]
                        found = True
                        use_indx = True
                elif _opt.lower() == content[control]["Location"].lower() and not use_indx:
                    controldict[int(content[control]["Location"].split(' ')[-1])] = content[control]
                    found = True
                    use_slot = True
                if found:
                    break

            if not found:
                sys.stderr.write("\nController \'%s\' not found in the current inventory " \
                                "list.\n" % _opt)

        if controldict:
            for controller in controldict:
                if options.physicaldrives or options.pdrive:
                    outputcontent = True
                    try:
                        self.get_drives(options, controldict[controller]["PhysicalDrives"], \
                                        physical=True)
                    except KeyError as excp:
                        if excp.message == "PhysicalDrives":
                            raise IncompatableServerTypeError("Cannot "\
                                "configure physical drives using this controller.")

                if options.logicaldrives or options.ldrive:
                    outputcontent = True
                    self.get_drives(options, controldict[controller]["LogicalDrives"], logical=True)

                if not outputcontent:
                    for k in list(controldict[controller].keys()):
                        if k.lower() in HARDCODEDLIST or '@odata' in k.lower():
                            del controldict[controller][k]

                    UI().print_out_json_ordered(controldict[controller])
Ejemplo n.º 10
0
    def selection_output(self, options, content):
        """ Selection of output for smart array command

        :param options: command line options
        :type options: list.
        :param options: list of contents
        :type options: list.
        """
        controllist = []
        outputcontent = False

        try:
            if options.controller.isdigit():
                if int(options.controller) > 0:
                    controllist.append(content[int(options.controller) - 1])
            else:
                slotcontrol = options.controller.lower().strip('\"').split(
                    'slot')[-1].lstrip()
                for control in content:
                    if slotcontrol.lower() == control["Location"].lower(
                    ).split('slot')[-1].lstrip():
                        controllist.append(control)
            if not controllist:
                raise InvalidCommandLineError("")
        except InvalidCommandLineError:
            raise InvalidCommandLineError("Selected controller not found in the current inventory "\
                                          "list.")

        for controller in controllist:
            if options.physicaldrives or options.pdrive:
                outputcontent = True
                try:
                    self.get_drives(options,
                                    controller["PhysicalDrives"],
                                    physical=True)
                except KeyError as excp:
                    if excp.message == "PhysicalDrives":
                        raise IncompatableServerTypeError("Cannot "\
                            "configure physical drives using this controller.")

            if options.logicaldrives or options.ldrive:
                outputcontent = True
                self.get_drives(options,
                                controller["LogicalDrives"],
                                logical=True)

            if not outputcontent:
                for k in list(controller.keys()):
                    if k.lower() in HARDCODEDLIST or '@odata' in k.lower():
                        del controller[k]

                UI().print_out_json(controller)
    def jsonprinthelper(self, content):
        """ Helper for JSON UI print out

        :param content: current content to work on
        :type content: string.
        """
        final = dict()

        for item in content:
            for num, _ in item.iteritems():
                self.dict_merge(final, item)
        for num in final:
            UI().print_out_json(final[num])
Ejemplo n.º 12
0
    def displayAvailableCapacity(self,
                                 scalable_pmem_config,
                                 output_as_json=False):
        if output_as_json:
            data = {
                "TotalSupported": scalable_pmem_config.regions.maxPmemGiB,
                "TotalAvailable":
                scalable_pmem_config.regions.availableSizeGiB,
                "Processor": {},
                "ProcessorPair": {}
            }
            for _, socket in scalable_pmem_config.regions.sockets.items():
                availableSize, isSlotAvailable = socket.availableSizeGiBHint
                data["Processor"][socket.labelString] = {
                    'AvailableSize': availableSize,
                    'MaxLogicalNvdimmsCreated': not isSlotAvailable,
                    'MaximumLogicalNvdimms': socket.maxRegions
                }
            for _, pair in scalable_pmem_config.regions.socketPairs.items():
                availableSize, isSlotAvailable = pair.availableSizeGiBHint
                data["ProcessorPair"][pair.labelString] = {
                    'AvailableSize': availableSize,
                    'MaxLogicalNvdimmsCreated': not isSlotAvailable
                }
            UI().print_out_json(data)
        else:
            self.writeHeader3(
                "By Processor (for single processor logical NVDIMMs):")
            self.writeTableHeader(u"{:12} {:40}".format(
                "Processor", "Available For Scalable PMEM"))
            for _, socket in scalable_pmem_config.regions.sockets.items():
                availableSize, isSlotAvailable = socket.availableSizeGiBHint
                sys.stdout.write(u"\n  {:12} {}".format(
                    socket.labelString, "{:4} GiB {}".format(
                        availableSize, "(Max logical NVDIMMs created)"
                        if not isSlotAvailable else "")))

            sys.stdout.write(u"\n")
            self.writeHeader3(
                "By Processor Pair (for spanned logical NVDIMMs):")
            self.writeTableHeader(u"{:12} {:40}".format(
                "Processors", "Available For Scalable PMEM"))
            for _, pair in scalable_pmem_config.regions.socketPairs.items():
                availableSize, isSlotAvailable = pair.availableSizeGiBHint
                sys.stdout.write(u"\n  {:12} {}".format(
                    pair.labelString, "{:4} GiB {}".format(
                        availableSize, "(Max logical NVDIMMs created)"
                        if not isSlotAvailable else "")))

            self.noticeRestartRequired(scalable_pmem_config)
            sys.stdout.write(u"\n")
Ejemplo n.º 13
0
    def get_data_drives(self,
                        options,
                        drives,
                        print_ctrl=False,
                        single_use=False):
        """
        Identify/parse a physical component drive collection of a respective logical drive. The
        physical disk properties as well as some logical RAID parameters within each respective
        member.

        :param options: command line options
        :type options: object attributes
        :param content: collection of data drives href or @odata.id paths (as members) as attributed
        to a respective logical drive.
        :type content: dict
        :param print_ctrl: flag for console print enablement/disablement (default disabled)
        :type print_ctrl: bool
        :param single_use: singular usage, returns dictionary of results to calling function
        (default disabled)
        :type single_use: bool
        :returns: None, dictionary of all physical drives composing a parent logical drive,
        each instance identified by 'Id'
        """

        if not (getattr(options, "json", False)) and print_ctrl:
            sys.stdout.write("\t\tData Drives:\n")
        if single_use:
            subsetdrives = {}
        found_entries = False
        for member in drives.get('Members', {}):
            try:
                tmp = member[self.rdmc.app.typepath.defs.hrefstring]
            except:
                tmp = member[next(iter(member))]
            finally:
                tmp = self.rdmc.app.get_handler(tmp, silent=True).dict
                found_entries = True
            if single_use:
                subsetdrives[tmp['Id']] = tmp
            if print_ctrl:
                sys.stdout.write("\t\t[%s]: Model %s, Serial %s - %s MiB\n" % (tmp['Location'], \
                            tmp['Model'], tmp['SerialNumber'], tmp['CapacityMiB']))
                sys.stdout.write("\t\t\tLocation: %s\n" % (tmp['Location']))
            elif getattr(options, "json", False):
                UI().print_out_json(tmp)
        if not found_entries and print_ctrl:
            sys.stdout.write("\t\tComponent drives not found.\n")

        if single_use:
            return subsetdrives
Ejemplo n.º 14
0
    def get_selected_drive(self, location):
        """ Function to get all selected drives

        :param location: list of all locations
        :type location: list.
        """
        self.selobj.selectfunction("HpSmartStorageDiskDrive.")

        for drive in self._rdmc.app.getprops():
            if drive["Location"] in location:
                for k in list(drive.keys()):
                    if k.lower() in HARDCODEDLIST or '@odata' in k.lower():
                        del drive[k]

                UI().print_out_json(drive)
Ejemplo n.º 15
0
    def jsonprinthelper(self, content):
        """ Helper for JSON UI print out

        :param content: current content to work on
        :type content: string.
        """
        final = dict()

        for item in content:
            for num, _ in item.iteritems():
                try:
                    final[num].update(item[num])
                except:
                    final[num] = item[num]
        for num in final:
            UI().print_out_json(final[num])
Ejemplo n.º 16
0
    def pendingfunction(self):
        """ Main pending command worker function
        """
        settingsuri = []
        ignorekeys = ['@odata.id', '@odata.etag', '@redfish.settings', 'oem']
        ignoreuri = [unicode('hpsut*')]
        ignorekeys.extend(HARDCODEDLIST)

        resourcedir = self._rdmc.app.get_handler(self._rdmc.app.monolith._resourcedir, \
                                                 service=True, silent=True)

        for resource in resourcedir.dict['Instances']:
            if (resource['@odata.id'].split('/').__len__() - 1) > 4:
                splitstr = resource['@odata.id'].split('/')[5]
            for element in ignoreuri:
                if '/settings' in resource['@odata.id'] and not \
                                                        self.wildcard_str_match(element, splitstr):
                    settingsuri.append(resource['@odata.id'])

        sys.stdout.write('Current Pending Changes:\n')

        for uri in settingsuri:
            diffprint = {}
            baseuri = uri.split('settings')[0]

            base = self._rdmc.app.get_handler(baseuri,
                                              service=True,
                                              silent=True)
            settings = self._rdmc.app.get_handler(uri,
                                                  service=True,
                                                  silent=True)

            typestring = self._rdmc.app.monolith.typepath.defs.typestring
            currenttype = '.'.join(
                base.dict[typestring].split('#')[-1].split('.')[:-1])

            differences = json.loads(jsondiff.diff(base.dict, settings.dict, \
                                                syntax='symmetric', dump=True))

            diffprint = self.recursdict(differences, ignorekeys)

            sys.stdout.write('\n%s:' % currenttype)
            if not diffprint:
                sys.stdout.write('\nNo pending changes found.\n')
            else:
                UI().pretty_human_readable(diffprint)
                sys.stdout.write('\n')
Ejemplo n.º 17
0
 def validateFeatureEnabledByUser(self,
                                  scalable_pmem_config,
                                  output_as_json=False):
     (isEnabled, overallMessage,
      messages) = scalable_pmem_config.isEnabledByUser
     if not isEnabled:
         if output_as_json:
             UI().print_out_json({
                 "IsEnabled": isEnabled,
                 "OverallMessage": overallMessage,
                 "Messages": messages
             })
             raise NoChangesFoundOrMadeError(u"")
         else:
             sys.stdout.write(u"\n\n{}:\n".format(overallMessage))
             self.printLimitedMessageList(messages, 3)
             sys.stdout.write(u"\n\n")
             raise NoChangesFoundOrMadeError(u"Unable to continue")
Ejemplo n.º 18
0
 def validateAllConfigurationPolicies(self,
                                      scalable_pmem_config,
                                      output_as_json=False):
     (isValid, overallMessage,
      messages) = scalable_pmem_config.validateConfigurationPolicies()
     if not isValid:
         if output_as_json:
             UI().print_out_json({
                 "IsValid": isValid,
                 "OverallMessage": overallMessage,
                 "Messages": messages
             })
             raise NoChangesFoundOrMadeError(u"")
         else:
             sys.stdout.write(u"\n\n{}:\n".format(overallMessage))
             self.printLimitedMessageList(messages, 3)
             sys.stdout.write(u"\n\n")
             raise NoChangesFoundOrMadeError(u"Unable to continue")
    def getipprofiledataanddecode(self, options):
        """
        Retrieves and decodes, if encoded, data from hpeprofile data store
        :param options: command line options
        :type options: list.
        :return returncode: int
        """

        results = self._rdmc.app.get_handler(self.path,
                                             silent=True,
                                             response=True)
        if results.status == 404:
            raise PathUnavailableError("The Intelligent Provisioning resource "\
                                   "is not available on this system. You may need"\
                                   " to run IP at least once to add the resource.")

        if results and results.status == 200:
            j2python = json.loads(results.read)
            for _, val in enumerate(j2python.keys()):
                if isinstance(val, six.string_types):
                    result = self.decode_base64_string(str(j2python[val]))
                    if result is not None:
                        j2python[val] = result

            results.read = json.dumps(j2python,
                                      ensure_ascii=False,
                                      sort_keys=True)
            if results.dict:
                if options.filename:
                    output = json.dumps(results.dict, indent=2, cls=redfish.ris.JSONEncoder, \
                                        sort_keys=True)

                    filehndl = open(options.filename[0], "w")
                    filehndl.write(output)
                    filehndl.close()

                    sys.stdout.write("Results written out to '%s'.\n" %
                                     options.filename[0])
                else:
                    UI().print_out_json(results.dict)
        else:
            sys.stdout.write("No IP profiles found\n")
Ejemplo n.º 20
0
    def get_hvt_output(self):
        """
        Retrieves and decodes, running job
        :return returncode: int
        """
        return_value = {}
        results = self._rdmc.app.get_handler(self.hvt_output, silent=True, response=True)
        if results.status == 404:
            raise PathUnavailableError("The Intelligent Provisioning resource "\
                                   "is not available on this system. You may need"\
                                   " to run IP at least once to add the resource.")

        if results and results.status == 200:
            j2python = json.loads(results.read)
            for _, val in enumerate(j2python.keys()):
                if isinstance(val, six.string_types) and '@' not in val:
                    return_value = json.loads(self.decode_base64_string(str(j2python[val])))
            UI().print_out_json(return_value)
        else:
            sys.stdout.write("No IP profiles found\n")
    def test_directory(self, options, json=False):
        """ Function to perform directory testing

        :param options: namespace of custom parser attributes which contain the original command
                        arguments for 'start/stop/viewresults'
        :type options: namespace
        :param json: Bool to print in json format or not.
        :type json: bool.
        """
        results = self._rdmc.app.select(selector='HpeDirectoryTest.', path_refresh=True)[0].dict
        if options.start_stop_view.lower() == 'start':
            path = None
            for item in results['Actions']:
                if 'StartTest' in item:
                    path = results['Actions'][item]['target']
                    break
            if not path:
                raise NoContentsFoundForOperationError("Unable to start directory test.")
            sys.stdout.write("Starting the directory test. Monitor results with command: directory"\
                             " viewresults\n")
            self._rdmc.app.post_handler(path, {})
        elif options.start_stop_view.lower() == 'stop':
            path = None
            for item in results['Actions']:
                if 'StopTest' in item:
                    path = results['Actions'][item]['target']
                    break
            if not path:
                raise NoContentsFoundForOperationError("Unable to stop directory test.")
            sys.stdout.write("Stopping the directory test.\n")
            self._rdmc.app.post_handler(path, {})
        elif options.start_stop_view.lower() == 'viewresults':
            if json:
                UI().print_out_json(results['TestResults'])
            else:
                for test in results['TestResults']:
                    sys.stdout.write('Test: %s\n' % test['TestName'])
                    sys.stdout.write("------------------------\n")
                    sys.stdout.write('Status: %s\n' % test['Status'])
                    sys.stdout.write('Notes: %s\n' % test['Notes'])
                    sys.stdout.write("\n")
Ejemplo n.º 22
0
    def getipprofiledataanddecode(self, options):
        """
        Retrieves and decodes, if encoded, data from hpeprofile data store
        :param options: command line options
        :type options: list.
        :return returncode: int
        """

        try:
            results = self._rdmc.app.get_handler(self.path, \
                verbose=self._rdmc.opts.verbose, silent=True)
        except:
            raise PathUnavailableError("The Intelligent Provisioning resource "\
                                       "is not available on this system.")

        j2python = json.loads(results.read)
        for _, val in enumerate(j2python.keys()):
            if isinstance(val, basestring):
                result = self.decode_base64_string(str(j2python[val]))
                if result is not None:
                    j2python[val] = result

        results.read = json.dumps(j2python, ensure_ascii=False)

        if results and results.status == 200:
            if results.dict:
                if options.filename:
                    output = json.dumps(results.dict, indent=2,\
                                                    cls=redfish.ris.JSONEncoder)

                    filehndl = open(options.filename[0], "w")
                    filehndl.write(output)
                    filehndl.close()

                    sys.stdout.write(u"Results written out to '%s'.\n" % \
                                                            options.filename[0])
                else:
                    UI().print_out_json(results.dict)
        else:
            return ReturnCodes.NO_CONTENTS_FOUND_FOR_OPERATION
    def test_directory(self, command, json=False):
        """ Function to perform directory testing

        :param command: command to run against directory test. (start/stop/viewresults)
        :type command: str.
        :param json: Bool to print in json format or not.
        :type json: bool.
        """
        results = self._rdmc.app.select(selector='HpeDirectoryTest.', rel=True)[0].dict
        if command.lower() == 'start':
            path = None
            for item in results['Actions']:
                if 'StartTest' in item:
                    path = results['Actions'][item]['target']
                    break
            if not path:
                raise NoContentsFoundForOperationError("Unable to start directory test.")
            sys.stdout.write("Starting the directory test. Monitor results with command: directory"\
                             " viewresults\n")
            self._rdmc.app.post_handler(path, {})
        elif command.lower() == 'stop':
            path = None
            for item in results['Actions']:
                if 'StopTest' in item:
                    path = results['Actions'][item]['target']
                    break
            if not path:
                raise NoContentsFoundForOperationError("Unable to stop directory test.")
            sys.stdout.write("Stopping the directory test.\n")
            self._rdmc.app.post_handler(path, {})
        elif command.lower() == 'viewresults':
            if json:
                UI().print_out_json(results['TestResults'])
            else:
                for test in results['TestResults']:
                    sys.stdout.write('Test: %s\n' % test['TestName'])
                    sys.stdout.write("------------------------\n")
                    sys.stdout.write('Status: %s\n' % test['Status'])
                    sys.stdout.write('Notes: %s\n' % test['Notes'])
                    sys.stdout.write("\n")
    def pendingfunction(self):
        """ Main pending command worker function
        """

        settingsuri = []
        ignorekeys = ['@odata.id', '@odata.etag', '@redfish.settings']
        ignorekeys.extend(HARDCODEDLIST)

        resourcedir = self._rdmc.app.get_handler(self._rdmc.app.current_client.\
                monolith._resourcedir, \
                verbose=self._rdmc.opts.verbose, service=True, silent=True)

        for resource in resourcedir.dict['Instances']:
            if '/settings' in resource['@odata.id']:
                settingsuri.append(resource['@odata.id'])
        sys.stdout.write('Current Pending Changes:\n')
        for uri in settingsuri:
            diffprint = {}
            baseuri = uri.split('settings')[0]
            base = self._rdmc.app.get_handler(baseuri, \
                    verbose=self._rdmc.opts.verbose, service=True, silent=True)
            settings = self._rdmc.app.get_handler(uri, \
                    verbose=self._rdmc.opts.verbose, service=True, silent=True)

            typestring = self._rdmc.app._rmc_clients._monolith._typestring
            currenttype = '.'.join(base.dict[typestring].split('#')\
                                                        [-1].split('.')[:-1])

            differences = json.loads(jsondiff.diff(base.dict, settings.dict, \
                                                syntax='symmetric', dump=True))

            diffprint = self.recursdict(differences, ignorekeys)

            sys.stdout.write('\n%s:' % currenttype)
            if not diffprint:
                sys.stdout.write('\nNo pending changes found.\n')
            else:
                UI().pretty_human_readable(diffprint)
                sys.stdout.write('\n')
    def run(self, line):
        """ Main serverinfo function.

        :param line: string of arguments passed in
        :type line: str.
        """
        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("")

        if args:
            raise InvalidCommandLineError("serverinfo command takes no "\
                                          "arguments.")

        self.serverinfovalidation(options)

        self.optionsvalidation(options)

        info = self.gatherinfo(options)

        if not info:
            raise InvalidCommandLineError("Please verify the commands entered "\
                                          "and try again.")

        if options.json:
            UI().print_out_json(info)
        else:
            self.prettyprintinfo(info, options.showabsent)

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    def getworkerfunction(self, args, options, line, newargs=None, readonly=False,\
                                results=None, uselist=False, multivals=False):
        """ main get worker function

        :param args: command line arguments
        :type args: list.
        :param options: command line options
        :type options: list.
        :param line: command line input
        :type line: string.
        :param newargs: new style arguments
        :type newargs: list.
        :param readonly: remove readonly properties
        :type newargs: bool
        :param results: current results collected
        :type results: string.
        :param uselist: use reserved properties list to filter results
        :type uselist: boolean.
        :param multivals: multiple values
        :type multivals: boolean.
        """
        listitem = False
        somethingfound = False
        if readonly:
            try:
                contents = self._rdmc.app.get_save(args, remread=True)
                uselist = False
            except redfish.ris.rmc_helper.EmptyRaiseForEAFP:
                contents = self._rdmc.app.get_save(args)
        else:
            contents = self._rdmc.app.get_save(args)

        values = {}
        itemnum = 0

        if not contents:
            raise NoContentsFoundForOperationError('No contents '\
                                                'found for entries: %s' % line)

        for content in contents:
            if 'bios.' in self._rdmc.app.get_selector().lower():
                if 'Attributes' in content.keys():
                    content.update(content['Attributes'])
                    del content['Attributes']

                    try:
                        for item in newargs:
                            if item.lower() == 'attributes':
                                newargs.remove(item)
                                break
                    except:
                        pass

            content = OrderedDict(sorted(content.items(), key=lambda x: x[0]))

            if uselist:
                self.removereserved(content)

            if len(content):
                itemnum += 1

                if not newargs:
                    somethingfound = True
                else:
                    innerresults = OrderedDict()
                    newlist = list()

                    for item in newargs:
                        somethingfound = False
                        if isinstance(content, list):
                            if not content:
                                break
                            if len(content) > 1:
                                argleft = [x for x in newargs if x not in \
                                                                        newlist]

                                _ = [self.getworkerhelper(results, content[x], \
                                    newlist[:], argleft, jsono=options.json) \
                                                for x in range(len(content))]
                                somethingfound = True
                                listitem = True
                                break
                            else:
                                content = content[0]

                        for key in content.keys():
                            if item.lower() == key.lower():
                                newlist.append(key)
                                content = content.get(key)
                                somethingfound = True
                                break
                        else:
                            somethingfound = False

                        if not somethingfound:
                            return somethingfound

                    counter = 0
                    for item in reversed(newlist):
                        if counter == 0:
                            innerresults = {item: content}
                            counter += 1
                        else:
                            innerresults = {item: innerresults}

                    content = innerresults
            else:
                continue

            if somethingfound and results:
                if multivals:
                    values[itemnum] = content
                else:
                    return content
            elif somethingfound and not listitem:
                if options.json:
                    UI().print_out_json(content)
                else:
                    UI().print_out_human_readable(content)

        if multivals:
            return values

        return somethingfound
Ejemplo n.º 27
0
    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)
Ejemplo n.º 28
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))
        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 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
Ejemplo n.º 29
0
    for cName in extensions.classNames:
        sName = cName.split('.')[1]
        cName = cName.split('.')[-1]

        if not cName.endswith("Command"):
            continue

        if cName == 'HelpCommand':
            RDMC.add_command(extensions.Commands[cName](rdmc=RDMC),
                             section=sName)
        else:
            try:
                RDMC.add_command(extensions.Commands[cName](RDMC),
                                 section=sName)
            except cliutils.ResourceAllocationError as excp:
                UI().error(excp)
                retcode = ReturnCodes.RESOURCE_ALLOCATION_ISSUES_ERROR
                UI().printmsg("Unable to allocate more resources.")
                sys.stdout.write("ILOREST return code: %s\n" % retcode)
                sys.exit(retcode)
            except Exception as excp:
                sys.stderr.write("Error loading extension: %s\n" % cName)
                sys.stderr.write("\t" + str(excp) + '\n')

    # Main execution function call wrapper
    if os.name != 'nt':
        FOUND = False
        VARIABLE = setproctitle.getproctitle()

        for items in VARIABLE.split(" "):
            if FOUND:
Ejemplo n.º 30
0
    def run(self, line, autotest=False):
        """ Main info worker function

        :param line: command line input
        :type line: string.
        :param autotest: flag to determine if running automatictesting
        :type autotest: bool.
        """
        try:
            (options, args) = self._parse_arglist(line)
        except:
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.infovalidation(options)

        if args:
            for item in args:
                if self._rdmc.app.get_selector().lower().startswith('bios.') \
                                        and not 'attributes' in item.lower():
                    if not (item.lower() in HARDCODEDLIST
                            or '@odata' in item.lower()):
                        item = "Attributes/" + item

                outdata = self._rdmc.app.info(selector=item, dumpjson=options.json, \
                                                                latestschema=options.latestschema)
                if autotest:
                    return outdata
                if outdata and options.json:
                    UI().print_out_json(outdata)
                elif outdata:
                    sys.stdout.write(outdata)

                if not outdata:
                    raise InfoMissingEntriesError("There are no valid "\
                            "entries for info in the current instance.")
                else:
                    if len(args) > 1 and not item == args[-1]:
                        sys.stdout.write("\n************************************"\
                                     "**************\n")
        else:
            results = sorted(self._rdmc.app.info(selector=None,\
                   ignorelist=HARDCODEDLIST, latestschema=options.latestschema))

            if results and autotest:
                return results
            elif results:
                sys.stdout.write("Info options:\n")
                for item in results:
                    sys.stdout.write("%s\n" % item)
            else:
                raise InfoMissingEntriesError('No info items '\
                        'available for this selected type. Try running with the '\
                        '--latestschema flag.')

        if options.logout:
            self.logoutobj.run("")

        #Return code
        return ReturnCodes.SUCCESS