def run(self, line):
        """ Main clearrestapistate 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(
                "clearrestapistate command takes no arguments.")

        self.clearrestapistatevalidation(options)

        select = 'Manager.'
        results = self.rdmc.app.select(selector=select)

        try:
            results = results[0]
        except:
            pass

        if results:
            path = results.resp.request.path
        else:
            raise NoContentsFoundForOperationError("Manager. not found.")

        bodydict = results.resp.dict['Oem'][self.rdmc.app.typepath.defs.oemhp]
        try:
            for item in bodydict['Actions']:
                if 'ClearRestApiState' in item:
                    if self.rdmc.app.typepath.defs.isgen10:
                        action = item.split('#')[-1]
                    else:
                        action = "ClearRestApiState"
                    path = bodydict['Actions'][item]['target']
                    body = {"Action": action}
                    break
        except:
            body = {"Action": "ClearRestApiState", "Target": "/Oem/Hp"}
        self.rdmc.app.post_handler(path, body)

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Ejemplo n.º 2
0
class RawPostCommand(RdmcCommandBase):
    """ Raw form of the post command """
    def __init__(self, rdmcObj):
        RdmcCommandBase.__init__(self,\
            name='rawpost',\
            usage='rawpost [FILENAME] [OPTIONS]\n\n\tRun to send a post from ' \
                    'the data in the input file.\n\texample: rawpost rawpost.' \
                    'txt\n\n\tExample input file:\n\t{\n\t    "path": "/' \
                    'redfish/v1/systems/(system ID)/Actions/ComputerSystem.'
                    'Reset",\n\t    "body": {\n\t        "ResetType": '\
                    '"ForceRestart"\n\t    }\n\t}',\
            summary='This is the raw form of the POST command.',\
            aliases=['rawpost'],\
            optparser=OptionParser())
        self.definearguments(self.parser)
        self._rdmc = rdmcObj
        self.lobobj = rdmcObj.commandsDict["LoginCommand"](rdmcObj)

    def run(self, line):
        """ Main raw patch worker function

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

        url = None
        headers = {}
        results = None

        if options.sessionid:
            url = self.sessionvalidation(options)
        else:
            self.postvalidation(options)

        contentsholder = None

        if len(args) == 1:
            try:
                inputfile = open(args[0], 'r')
                contentsholder = json.loads(inputfile.read())
            except Exception, excp:
                raise InvalidFileInputError("%s" % excp)
        elif len(args) > 1:
            raise InvalidCommandLineError("Raw post only takes 1 argument.\n")
    def secureboothelper(self, securebootoption):
        """ Helper function for secure boot function

        :param securebootoption: option passed in for secure boot
        :type securebootoption: string.
        """
        actionlist = ['defaultkeys', 'deletekeys', 'deletepk']

        if not securebootoption.lower() in actionlist:
            raise InvalidCommandLineError('%s is not a valid option for '\
                                  'the securebootkeys flag.' % securebootoption)

        if securebootoption == actionlist[0]:
            action = 'ResetAllKeysToDefault'
        elif securebootoption == actionlist[1]:
            action = 'DeleteAllKeys'
        elif securebootoption == actionlist[2]:
            action = 'DeletePK'

        results = self.rdmc.app.select(
            selector=self.rdmc.app.typepath.defs.hpsecureboot)

        try:
            results = results[0]
        except:
            pass

        if results:
            path = results.resp.request.path
            results = results.resp.dict

        try:
            for item in results['Actions']:
                if 'ResetKeys' in item:
                    path = results['Actions'][item]['target']
                    break

            body = {"ResetKeysType": action}
            self.rdmc.app.post_handler(path, body)
        except:
            if securebootoption == actionlist[0]:
                self.auxcommands['select'].selectfunction(
                    self.rdmc.app.typepath.defs.hpsecureboot)
                self.auxcommands['set'].run('ResetToDefaultKeys=True --commit')
            elif securebootoption == actionlist[1]:
                self.auxcommands['select'].selectfunction(
                    self.rdmc.app.typepath.defs.hpsecureboot)
                self.auxcommands['set'].run('ResetAllKeys=True --commit')
            else:
                self.rdmc.ui.warn(
                    "DeletePK option is not available on Gen9.\n")
    def validate_options(self, options):
        """
        Validate whether options specified by user are valid or not
        :param options: options specified by the user with the 'provisionpmm' command
        :type options: instance of OptionParser class
        """
        some_flag = options.memorymode or options.interleave or options.proc or options.force
        if not some_flag:
            raise InvalidCommandLineError("No flag specified.\n\nUsage: " +
                                          self.usage)

        # If the memory mode option value is not valid.
        if options.memorymode < 0 or options.memorymode > 100:
            raise InvalidCommandLineError("Specify the correct value (1-100)"
                                          " to configure PMM")
        if options.interleave:
            if (options.interleave).lower() not in ['on', 'off']:
                raise InvalidCommandLineError("Specify the correct value to set interleave"\
                    " state of persistent memory regions\n\n" + self.usage)
            options.interleave = options.interleave.lower()

        if options.proc and not options.memorymode and not options.interleave:
            raise InvalidCommandLineError \
            ("Use '-m|--memory-mode' flag to specify the size in percentage"
             " or '-i|--pmem-interleave' flag to set interleave"
             " state of persistent memory regions")

        # If not 100% memorymode, -i flag is mandatory to interleave memroy regions.
        if options.memorymode >= 0 and options.memorymode < 100 and not options.interleave:
            raise InvalidCommandLineError(
                "Use '-i | --pmem-interleave' flag to"
                " specify the interleave state of persistent"
                " memory regions")
        if options.proc:
            for proc_id in options.proc:
                if not proc_id.isdigit():
                    raise InvalidCommandLineError(
                        "Specify the correct processor id")
    def run(self, line):
        """ Main factorydefaults 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 not len(args) == 1:
            raise InvalidCommandLineError(
                "backuprestore command takes one argument.")

        self.ilobackuprestorevalidation(options)

        if 'blobstore' in self.rdmc.app.current_client.base_url:
            raise InvalidCommandLineError(
                "This command is only available remotely.")

        sessionkey = self.rdmc.app.current_client.session_key
        #sessionkey = (sessionkey).encode('ascii', 'ignore')

        if args[0].lower() == 'backup':
            self.backupserver(options, sessionkey)
        elif args[0].lower() == 'restore':
            self.restoreserver(options, sessionkey)
        else:
            raise InvalidCommandLineError("%s is not a valid option for this "\
                                          "command."% str(args[0]))

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main disk inventory 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.createlogicaldrivevalidation(options)

        self.selobj.selectfunction("SmartStorageConfig.")
        content = self._rdmc.app.get_save()
        if not options.controller:
            raise InvalidCommandLineError('You must include a controller '\
                                          'to select.')
        controllist = []
        if not args:
            raise InvalidCommandLineError('Please choose customdrive or '\
                                          'quickdrive creation.')
        elif args[0].lower() == 'customdrive' and not len(args) == 3:
            raise InvalidCommandLineError('customdrive takes 2 arguments')
        elif args[0].lower() == 'quickdrive' and not len(args) == 6:
            raise InvalidCommandLineError('quickdrive takes 5 arguments')
        elif not args[0] in ['quickdrive', 'customdrive']:
            raise InvalidCommandLineError('Please choose customdrive or '\
                                          'quickdrive creation.')

        if options.controller.isdigit() and not options.controller == '0':
            try:
                controllist.append(content[int(options.controller) - 1])
            except:
                pass
        else:
            for control in content:
                if options.controller.lower() == control["Location"].lower():
                    controllist.append(control)

        if not controllist:
            raise InvalidCommandLineError("Selected controller not " \
                                    "found in the current inventory list.")
        else:
            for controller in controllist:
                if self.createlogicaldrive(args[0], args[1:], options,
                                           controller):
                    controller['DataGuard'] = "Disabled"

                    self._rdmc.app.put_handler(controller["@odata.id"], \
                                       controller, headers={'If-Match': \
                                        self.getetag(controller['@odata.id'])})
                    self._rdmc.app.reloadmonolith(controller["@odata.id"])
        #Return code
        return ReturnCodes.SUCCESS
    def removeRegion(self, options):
        """ Removes the Logical NVDIMM specified

        :param socketIdx: the socket of the NUMA region, or None for Non-NUMA
        :type socketIdx: string or int

        :param regionIdx: the index of the region
        :type regionIdx: string or int
        """

        validator = LogicalNvdimmValidator()

        scalable_pmem_config = ScalablePersistentMemoryConfig(self._restHelpers,\
                                                     validator, self._chif_lib)
        scalable_pmem_config.refresh()

        # pre-validation
        self._helpers.validateAllConfigurationPolicies(scalable_pmem_config)

        matchingRegion = None
        if options.processorPair:
            matchingPair = next((p for _, p in scalable_pmem_config.regions.\
                                 socketPairs.items() if p.labelString == options.\
                                                            processorPair), None)
            if matchingPair:
                matchingRegion = matchingPair.nonNumaRegion
        else:
            matchingSocket = next((s for _, s in scalable_pmem_config.regions.\
                                   sockets.items() if s.labelString == options.\
                                                        processorNumber), None)
            if matchingSocket:
                matchingRegion = matchingSocket.numaRegions.get(options.index)

        if matchingRegion and matchingRegion.isConfigured:
            if self._rdmc.interactive:
                if matchingRegion.isActivelyConfigured:
                    self._helpers.confirmBeforeConfigCausesDataLoss(scalable_pmem_config)

            patchAttributes = {
                matchingRegion.settingName : 0
            }
            _ = self._restHelpers.patchScalablePmemSettingAttributes(patchAttributes)
        else:
            self._helpers.displayRegionConfiguration(scalable_pmem_config)
            raise InvalidCommandLineError(u"Unable to identify an existing logical NVDIMM")

        # display the new state
        scalable_pmem_config.refresh()
        self._helpers.displayRegionConfiguration(scalable_pmem_config)
        sys.stdout.write(u"\n")
    def validate_options(self, options):
        """
        Validate whether options specified by user are valid.
        :param options: options specified by the user.
        :type options: instance of OptionParser class.
        """
        # Set of valid configIDs
        valid_config_ids = {config_id.get("name").lower() for config_id
                            in self.config_ids}

        if not options.config and not options.list and not options.force:
            raise InvalidCommandLineError(
                "No flag specified.\n\nUsage: " + self.usage)
        if not options.config and options.force:
            raise InvalidCommandLineError("'--force | -f' flag mandatorily requires the "
                                          "'--config | -C' flag.")
        if options.config and options.list:
            raise InvalidCommandLineError("Only one of '--config | -C' or '--list | -L' "
                                          "may be specified")
        # Check whether the user entered configID is valid
        if options.config and not options.config.lower() in valid_config_ids:
            raise InvalidCommandLineError("Invalid configID.\nTo view a list of pre-defined "
                                          "configIDs, use 'applypmmconfig --list'")
Ejemplo n.º 9
0
    def run(self, line):
        """ Main deletecomp worker 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("")

        self.deletecomponentvalidation(options)

        if self.rdmc.app.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                              'only available on iLO 5.')

        comps = self.rdmc.app.getcollectionmembers(\
                            '/redfish/v1/UpdateService/ComponentRepository/')

        if not comps:
            self.rdmc.ui.warn('No components found to delete\n')

        elif options.deleteall:
            delopts = []

            for comp in comps:
                try:
                    if comp['Locked']:
                        self.rdmc.ui.warn("Unable to delete %s. It is in use by "\
                                          "an install set or update task.\n" % comp['Filename'])
                        continue
                except KeyError:
                    pass
                delopts.append(comp['@odata.id'])

            self.deletecomponents(comps, delopts)
        elif args:
            self.deletecomponents(comps, args)
        else:
            InvalidCommandLineError(
                "Please include the component(s) you wish to delete")

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Ejemplo n.º 10
0
    def run(self, line):
        """ Main firmware update worker function

        :param line: string of arguments passed in
        :type line: str.
        """
        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('fwintegritycheck command takes no ' \
                                                                    'arguments')

        self.firmwareintegritycheckvalidation(options)

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('fwintegritycheck command is ' \
                                                    'only available on iLO 5.')

        licenseres = self._rdmc.app.filter('HpeiLOLicense.', None, None)
        try:
            licenseres = licenseres[0]
        except:
            pass
        if not licenseres.dict['LicenseFeatures']['FWScan']:
            raise IloLicenseError(
                "This command is not available with this iLO license.")

        select = self.typepath.defs.hpilofirmwareupdatetype
        results = self._rdmc.app.filter(select, None, None)

        try:
            results = results[0]
        except:
            pass

        bodydict = results.resp.dict

        path = bodydict['Oem']['Hpe']['Actions']\
            ['#HpeiLOUpdateServiceExt.StartFirmwareIntegrityCheck']['target']

        self._rdmc.app.post_handler(path, {})

        return ReturnCodes.SUCCESS
Ejemplo n.º 11
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

        if options.controller.isdigit() and not options.controller == '0':
            try:
                controllist.append(content[int(options.controller) - 1])
            except:
                pass
        else:
            for control in content:
                if options.controller.lower() == control["Location"].lower():
                    controllist.append(control)

        if not controllist:
            raise InvalidCommandLineError("Selected controller not " \
                                        "found in the current inventory list.")
        else:
            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_ordered(controller)
Ejemplo n.º 12
0
    def run(self, line):
        """ Main iscsi configuration worker function

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

        self.iscsiconfigurationvalidation(options)

        if self.typepath.defs.biospath[-1] == '/':
            iscsipath = self.typepath.defs.biospath + 'iScsi/'
            iscsisettingspath = self.typepath.defs.biospath + 'iScsi/settings/'
            bootpath = self.typepath.defs.biospath + 'Boot/'
        else:
            iscsipath = self.typepath.defs.biospath + '/iScsi'
            iscsisettingspath = self.typepath.defs.biospath + '/iScsi/settings'
            bootpath = self.typepath.defs.biospath + '/Boot'

        if options.list:
            self.listoptionhelper(options, iscsipath, iscsisettingspath, \
                                                                    bootpath)
        elif options.modify:
            self.modifyoptionhelper(options, iscsisettingspath)
        elif options.add:
            self.addoptionhelper(options, iscsipath, iscsisettingspath, \
                                                                    bootpath)
        elif options.delete:
            self.deleteoptionhelper(options, iscsisettingspath)
        elif not args:
            self.defaultsoptionhelper(options, iscsipath, bootpath)
        else:
            if len(args) < 2:
                self.iscsiconfigurationvalidation(options)
            else:
                raise InvalidCommandLineError("Invalid number of parameters. " \
                        "Iscsi configuration takes a maximum of 1 parameter.")

        if options.reboot:
            self.rebootobj.run(options.reboot)

        #Return code
        return ReturnCodes.SUCCESS
Ejemplo n.º 13
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
Ejemplo n.º 15
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)

        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)

        logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main disk inventory worker function

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

        self.frcontrollervalidation(options)

        self.selobj.selectfunction("SmartStorageConfig.")
        content = self._rdmc.app.getprops()

        if options.controller:
            controllist = []

            if options.controller.isdigit() and not options.controller == '0':
                try:
                    controllist.append(content[int(options.controller) - 1])
                except:
                    pass
            else:
                for control in content:
                    if options.controller.lower() == control["Location"].lower(
                    ):
                        controllist.append(control)

            if not controllist:
                raise InvalidCommandLineError("Selected controller not " \
                                        "found in the current inventory list.")
            else:
                for controller in controllist:
                    contentsholder = {"Actions": [{"Action": "FactoryReset"}], \
                                                        "DataGuard": "Disabled"}
                    self._rdmc.app.patch_handler(controller["@odata.id"],
                                                 contentsholder)
        else:
            for idx, val in enumerate(content):
                sys.stdout.write("[%d]: %s\n" % (idx + 1, val["Location"]))

        #Return code
        return ReturnCodes.SUCCESS
Ejemplo n.º 17
0
    def serverinfovalidation(self, options):
        """ serverinfo method validation function.

        :param options: command line options
        :type options: list.
        """
        client = None
        inputline = list()

        try:
            client = self._rdmc.app.current_client
        except:
            if options.user or options.password or options.url:
                if options.url:
                    inputline.extend([options.url])
                if options.user:
                    if options.encode:
                        options.user = Encryption.decode_credentials(
                            options.user)
                    inputline.extend(["-u", options.user])
                if options.password:
                    if options.encode:
                        options.password = Encryption.decode_credentials(
                            options.password)
                    inputline.extend(["-p", options.password])
                if options.https_cert:
                    inputline.extend(["--https", options.https_cert])
            else:
                if self._rdmc.app.config.get_url():
                    inputline.extend([self._rdmc.app.config.get_url()])
                if self._rdmc.app.config.get_username():
                    inputline.extend(
                        ["-u", self._rdmc.app.config.get_username()])
                if self._rdmc.app.config.get_password():
                    inputline.extend(
                        ["-p", self._rdmc.app.config.get_password()])
                if self._rdmc.app.config.get_ssl_cert():
                    inputline.extend(
                        ["--https",
                         self._rdmc.app.config.get_ssl_cert()])

        if inputline or not client:
            if not inputline:
                sys.stdout.write('Local login initiated...\n')
            self.lobobj.loginfunction(inputline)
        elif not client:
            raise InvalidCommandLineError("Please login or pass credentials" \
                                          " to complete the operation.")
Ejemplo n.º 18
0
    def defaultsvalidation(self, options):
        """ BIOS defaults method validation function """
        client = None
        inputline = list()

        try:
            client = self._rdmc.app.current_client
        except:
            if options.user or options.password or options.url:
                if options.url:
                    inputline.extend([options.url])
                if options.user:
                    if options.encode:
                        options.user = Encryption.decode_credentials(
                            options.user)
                    inputline.extend(["-u", options.user])
                if options.password:
                    if options.encode:
                        options.password = Encryption.decode_credentials(
                            options.password)
                    inputline.extend(["-p", options.password])
                if options.https_cert:
                    inputline.extend(["--https", options.https_cert])
            else:
                if self._rdmc.app.config.get_url():
                    inputline.extend([self._rdmc.app.config.get_url()])
                if self._rdmc.app.config.get_username():
                    inputline.extend(
                        ["-u", self._rdmc.app.config.get_username()])
                if self._rdmc.app.config.get_password():
                    inputline.extend(
                        ["-p", self._rdmc.app.config.get_password()])
                if self._rdmc.app.config.get_ssl_cert():
                    inputline.extend(
                        ["--https",
                         self._rdmc.app.config.get_ssl_cert()])

        if inputline:
            self.lobobj.loginfunction(inputline)
        elif not client:
            raise InvalidCommandLineError("Please login or pass credentials" \
                                          " to complete the operation.")

        if options.encode:
            options.biospassword = Encryption.decode_credentials(
                options.biospassword)
    def modifyoptionhelper(self, options, iscsisettingspath):
        """ Helper function to modify options for iscsi

        :param options: command line options
        :type options: list.
        :param iscsisettingspath: current iscsi settings path
        :type iscsisettingspath: str.
        """
        try:
            inputfile = open(options.modify, 'r')
            contentsholder = json.loads(inputfile.read())
        except Exception as excp:
            raise InvalidCommandLineError("%s" % excp)

        iscsibootsources = self.rawdatahandler(action="GET",
                                               silent=True,
                                               jsonflag=True,
                                               path=iscsisettingspath)

        count = 0
        resultsdict = list()

        for item in contentsholder:
            for entry in item.values():
                enteredsection = False

                for key, value in entry.items():
                    enteredsection = True
                    resultsdict.append(
                        self.modifyfunctionhelper(
                            key, value, iscsibootsources[
                                self.rdmc.app.typepath.defs.iscsisource]))

                if not enteredsection:
                    resultsdict.append(iscsibootsources[
                        self.rdmc.app.typepath.defs.iscsisource][count])

                count += 1

        contentsholder = {self.rdmc.app.typepath.defs.iscsisource: resultsdict}

        self.rdmc.app.patch_handler(iscsisettingspath,
                                    contentsholder,
                                    optionalpassword=options.biospassword)
        self.rdmc.app.get_handler(iscsisettingspath, silent=True)
    def vmbootnextreset(self, args, paths):
        """Worker function to boot virtual media on next serverreset

        :param args: arguments passed from command line
        :type args: list
        :param paths: all virtual media paths
        :type paths: list
        """
        try:
            path = paths[int(args[0])]
        except:
            raise InvalidCommandLineError("Invalid input value for virtual media"\
                                        " please run the command with no " \
                                        "arguments for possible values.")

        self.rdmc.app.patch_handler(path, \
                    {"Oem":{self.rdmc.app.typepath.defs.oemhp:{"BootOnNextServerReset":\
                                            True}}}, service=True, silent=True)
    def run(self, line):
        """ Main deletecomp worker function

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

        if self.typepath.defs.isgen9:
            raise IncompatibleiLOVersionError('iLO Repository commands are ' \
                                              'only available on iLO 5.')

        comps = self._rdmc.app.getcollectionmembers(\
                            '/redfish/v1/UpdateService/ComponentRepository/')

        if not comps:
            sys.stdout.write('No components found to delete\n')

        elif options.deleteall:
            delopts = []

            for comp in comps:
                delopts.append(comp['@odata.id'])

            self.deletecomponents(comps, delopts)
        elif args:
            self.deletecomponents(comps, args[0])
        else:
            InvalidCommandLineError("Please include the component(s) you wish "\
                                                                    "to delete")

        return ReturnCodes.SUCCESS
Ejemplo n.º 22
0
    def run(self, line):
        """ Wrapper function for help main function

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

        if not args or not line:
            RdmcOptionParser().print_help()
            if self._rdmc:
                cmddict = self._rdmc.get_commands()
                sorted_keys = sorted(list(cmddict.keys()))

                for key in sorted_keys:
                    if key[0] == '_':
                        continue
                    else:
                        sys.stdout.write('\n%s\n' % key)

                    for cmd in cmddict[key]:
                        cmd.print_summary()
        else:
            if self._rdmc:
                cmddict = self._rdmc.get_commands()
                sorted_keys = list(cmddict.keys())

                for key in sorted_keys:
                    for cmd in cmddict[key]:
                        if cmd.ismatch(args[0]):
                            cmd.print_help()
                            return ReturnCodes.SUCCESS

                raise InvalidCommandLineError("Command '%s' not found." %
                                              args[0])
        #Return code
        return ReturnCodes.SUCCESS
    def clonevalidation(self, options):
        """ results method validation function

        :param options: command line options
        :type options: list.
        """
        client = None
        inputline = list()

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

        try:
            client = self._rdmc.app.get_current_client()
            if options.user and options.password:
                if not client.get_username():
                    client.set_username(options.user)
                if not client.get_password():
                    client.set_password(options.password)
        except:
            if options.user or options.password or options.url:
                if options.url:
                    inputline.extend([options.url])
                if options.user:
                    inputline.extend(["-u", options.user])
                if options.password:
                    inputline.extend(["-p", options.password])
            else:
                if self._rdmc.app.config.get_url():
                    inputline.extend([self._rdmc.app.config.get_url()])
                if self._rdmc.app.config.get_username():
                    inputline.extend(["-u", \
                                  self._rdmc.app.config.get_username()])
                if self._rdmc.app.config.get_password():
                    inputline.extend(["-p", \
                                  self._rdmc.app.config.get_password()])

        if inputline:
            self.loginobj.loginfunction(inputline)
        elif not client:
            raise InvalidCommandLineError("Please login or pass credentials" \
                                          " to complete the operation.")
Ejemplo n.º 24
0
    def typesfunction(self, line, returntypes=False):
        """ Main types worker function

        :param line: command line input
        :type line: string.
        :param returntypes: flag to determine if types should be printed
        :type returntypes: boolean.
        """
        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.typesvalidation(options)

        try:
            if not args:
                typeslist = list()
                typeslist = list(set(self._rdmc.app.types(options.fulltypes)))
                typeslist.sort()

                if not returntypes:
                    sys.stdout.write("Type options:")
                    sys.stdout.write('\n')

                    for item in typeslist:
                        sys.stdout.write(item)
                        sys.stdout.write('\n')
                else:
                    return typeslist
            else:
                raise InvalidCommandLineError("The 'types' command does not "\
                                                        "take any arguments.")

        except redfish.ris.InstanceNotFoundError, infe:
            raise redfish.ris.InstanceNotFoundError(infe)
Ejemplo n.º 25
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 ilofunctionalityvalidation(self, options):
        """ ilofunctionalityvalidation method validation function

        :param options: command line options
        :type options: list.
        """
        client = None
        inputline = list()

        try:
            client = self._rdmc.app.get_current_client()
            if options.user and options.password:
                if not client.get_username():
                    client.set_username(options.user)
                if not client.get_password():
                    client.set_password(options.password)
        except:
            if options.user or options.password or options.url:
                if options.url:
                    inputline.extend([options.url])
                if options.user:
                    inputline.extend(["-u", options.user])
                if options.password:
                    inputline.extend(["-p", options.password])
            else:
                if self._rdmc.app.config.get_url():
                    inputline.extend([self._rdmc.app.config.get_url()])
                if self._rdmc.app.config.get_username():
                    inputline.extend(["-u", \
                                  self._rdmc.app.config.get_username()])
                if self._rdmc.app.config.get_password():
                    inputline.extend(["-p", \
                                  self._rdmc.app.config.get_password()])

        if inputline or not client:
            if not inputline:
                sys.stdout.write(u'Local login initiated...\n')
            self.lobobj.loginfunction(inputline)
        elif not client:
            raise InvalidCommandLineError("Please login or pass credentials" \
                                          " to complete the operation.")
Ejemplo n.º 27
0
    def run(self, line):
        """ Show pending changes of settings objects

        :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("Pending command does not take any arguments.")
        self.pendingvalidation(options)

        self.pendingfunction()

        return ReturnCodes.SUCCESS
Ejemplo n.º 28
0
    def firmwareintegritycheckvalidation(self, options):
        """ Firmware update method validation function

        :param options: command line options
        :type options: list.
        """
        client = None
        inputline = list()

        try:
            client = self._rdmc.app.get_current_client()
            if options.user and options.password:
                if not client.get_username():
                    client.set_username(options.user)
                if not client.get_password():
                    client.set_password(options.password)
        except Exception:
            if options.user or options.password or options.url:
                if options.url:
                    inputline.extend([options.url])
                if options.user:
                    inputline.extend(["-u", options.user])
                if options.password:
                    inputline.extend(["-p", options.password])
            else:
                if self._rdmc.app.config.get_url():
                    inputline.extend([self._rdmc.app.config.get_url()])
                if self._rdmc.app.config.get_username():
                    inputline.extend(["-u", \
                                  self._rdmc.app.config.get_username()])
                if self._rdmc.app.config.get_password():
                    inputline.extend(["-p", \
                                  self._rdmc.app.config.get_password()])

        if inputline:
            self.lobobj.loginfunction(inputline)
        elif not client:
            raise InvalidCommandLineError("Please login or pass credentials" \
                                                " to complete the operation.")
    def vmremovehelper(self, args, options, paths, isredfish, ilover):
        """Worker function to remove virtual media

        :param args: arguments passed from command line
        :type args: list
        :param paths: virtual media paths
        :type paths: list
        :param isredfish: redfish flag
        :type isredfish: bool
        :param ilover: iloversion
        :type ilover: int
        :param options: command line options
        :type options: list.
        """
        path = None

        if isredfish:
            path, body = self.vmredfishhelper('remove', args[0])
        else:
            if ilover <= 4.230:
                body = {"Image": None}
            else:
                body = {"Action": "EjectVirtualMedia", "Target": "/Oem/Hp"}

        try:
            path = paths[int(args[0])] if not path else path
        except:
            raise InvalidCommandLineError("Invalid input value for virtual " \
                                      "media please run the command with no " \
                                      "arguments for possible values.")

        if ilover <= 4.230:
            self.rdmc.app.patch_handler(path, body)
        else:
            self.rdmc.app.post_handler(path, body)

        if options.reboot:
            self.auxcommands['reboot'].run(options.reboot)
    def deletecomponents(self, comps, delopts):
        """ component validation function

        :param comps: component list
        :type comps: list.
        :param delopts: delete items list
        :type delopts: list.
        """
        if ',' in delopts:
            delopts = delopts.split(',')
        elif not isinstance(delopts, list):
            delopts = [delopts]

        for opt in delopts:
            deleted = False

            if '/' in opt:
                self._rdmc.app.delete_handler(opt)
                deleted = True
            else:
                for comp in comps:
                    if opt == comp['Id'] or opt == comp['Filename']:
                        try:
                            if comp['Locked']:
                                sys.stdout.write("Unable to delete %s. It is in use by "\
                                         "an install set or update task.\n" % comp['Filename'])
                                continue
                        except KeyError:
                            pass

                        self._rdmc.app.delete_handler(comp['@odata.id'])
                        deleted = True

                if deleted:
                    sys.stdout.write('Deleted %s\n' % opt)
                else:
                    raise InvalidCommandLineError('Cannot find or unable to delete component %s' \
                                                                                            % opt)