def ilodisablechecks(self, options):
        """ Verify it is safe to actually disable iLO

        :param options: command line options
        :type options: values, attributes of class obj
        """

        if options.force:
            sys.stdout.write(
                'Force Enabled: Ignoring critical operation/mode checking.\n')
            return True

        else:
            keyword_list = 'idle', 'complete'

            try:
                results = self._rdmc.app.select(selector='UpdateService.')[0]
            except:
                raise NoContentsFoundForOperationError(
                    "UpdateService. not found.")

            try:
                state = results.resp.dict['Oem']['Hpe']['State'].lower()
                for val in keyword_list:
                    if val in state:
                        return True
                return False

            except:
                raise NoContentsFoundForOperationError(
                    "iLO state not identified")
Ejemplo n.º 2
0
    def run(self, line):
        """ Wrapper function for main list 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.listvalidation(options)

        if args:
            for arg in args:
                newargs = list()

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

                if not self.getobj.getworkerfunction(arg, options, line,\
                                                newargs=newargs, uselist=True):
                    raise NoContentsFoundForOperationError('No contents found '\
                                                        'for entry: %s\n' % arg)
        else:
            if not self.getobj.getworkerfunction(args, options, line, \
                                                                uselist=True):
                raise NoContentsFoundForOperationError('No contents found.')

        #Return code
        return ReturnCodes.SUCCESS
 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.')
Ejemplo n.º 4
0
    def run(self, line):
        """ Main get 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.getvalidation(options)
        multiargs = False
        content = []

        if args:
            for arg in args:
                newargs = list()
                if "/" in arg:
                    newargs = arg.split("/")
                    arg = newargs[0]
                if len(args) > 1 and options.json:
                    multiargs = True
                    item = self.getworkerfunction(arg, options, line,\
                                newargs=newargs, results=True, multivals=True)
                    if item:
                        content.append(item)
                    else:
                        if not newargs:
                            raise NoContentsFoundForOperationError('No ' \
                                           'contents found for entry: %s' % arg)
                        else:
                            raise NoContentsFoundForOperationError('No ' \
                                       'contents found for entry: %s' % line[0])
                else:
                    if not self.getworkerfunction(arg, options, line,\
                                                                newargs=newargs):
                        if not newargs:
                            raise NoContentsFoundForOperationError('No ' \
                                           'contents found for entry: %s' % arg)
                        else:
                            raise NoContentsFoundForOperationError('No ' \
                                       'contents found for entry: %s' % line[0])
        else:
            if not self.getworkerfunction(args, options, line):
                raise NoContentsFoundForOperationError('No contents found')

        if multiargs and options.json:
            self.jsonprinthelper(content)

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

        #Return code
        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main iLO reset worker function

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

        self.iloresetvalidation(options)

        sys.stdout.write('\nAfter iLO resets the session will be terminated.' \
                         '\nPlease wait for iLO to initialize completely ' \
                         'before logging in again.\n')
        sys.stdout.write('This process may take up to 3 minutes.\n\n')

        select = "Manager."
        results = self._rdmc.app.select(selector=select)

        try:
            results = results[0]
        except:
            pass

        if results:
            put_path = results.resp.request.path
        else:
            raise NoContentsFoundForOperationError("Unable to find %s" % select)

        bodydict = results.resp.dict

        try:
            for item in bodydict['Actions']:
                if 'Reset' in item:
                    if self.typepath.defs.isgen10:
                        action = item.split('#')[-1]
                    else:
                        action = 'Reset'

                    put_path = bodydict['Actions'][item]['target']
                    break
        except:
            action = "Reset"

        body = {"Action": action}

        postres = self._rdmc.app.post_handler(put_path, body, silent=True, \
                                                    service=True, response=True)
        if postres.status == 200:
            sys.stdout.write("A management processor reset is in progress.\n")
        else:
            sys.stderr.write("An error occured during iLO reset.\n")
            raise IloResponseError("")
        #Return code
        return ReturnCodes.SUCCESS
Ejemplo n.º 6
0
    def copyjobtoipqueue(self, ipjobs, jobkey):
        """
        Copies HpeIpJob to Job queue. Function assumes there is a job to copy.
        A check was already done to make sure we have a job to copy in hasipjobs()
        :param ipjobs: url path of heip.
        :type ipjobs: list of dictionary.
        :param jobkey: key of job to copy.
        :type jokbey: str.
        """

        get_results = self._rdmc.app.get_handler(self.path,\
                verbose=self._rdmc.opts.verbose, silent=True)

        j2python = json.loads(get_results.read)
        copy_job = {}
        for ipj in j2python:
            if jobkey == ipj:
                copy_job = j2python[ipj]
                copy_job = json.loads(self.decode_base64_string(copy_job))
                break
        if not copy_job:
            raise NoContentsFoundForOperationError(
                "Job key does not match any ipprofile")
        copy_job['log'] = [{"msg": "WAITINGTOBEPROCESSED", "percent": 0}]
        copy_job['status'] = "waiting"
        payload = {}
        payload["path"] = self.ipjobs
        payload["body"] = copy_job

        self._rdmc.app.put_handler(payload["path"], payload["body"],\
              verbose=self._rdmc.opts.verbose)
    def run(self, line):
        """ Main factorydefaults 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("factorydefaults command takes no "\
                                                                "arguments.")

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

        self.factorydefaultsvalidation(options)

        sys.stdout.write("Resetting iLO to factory default settings.\n"\
                                        "Current session will be terminated.\n")

        select = 'Manager.'
        results = self._rdmc.app.filter(select, None, None)

        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.typepath.defs.oemhp]

        try:
            for item in bodydict['Actions']:
                if 'ResetToFactoryDefaults' in item:
                    if self.typepath.defs.isgen10:
                        action = item.split('#')[-1]
                    else:
                        action = "ResetToFactoryDefaults"

                    path = bodydict['Actions'][item]['target']
                    body = {"Action": action, "ResetType": "Default"}
                    break
        except:
            body = {"Action": "ResetToFactoryDefaults", \
                                "Target": "/Oem/Hp", "ResetType": "Default"}

        self._rdmc.app.post_handler(path, body, service=True)

        return ReturnCodes.SUCCESS
Ejemplo n.º 8
0
    def importcrlhelper(self, args):
        """ Helper function for importing CRL certificate

        :param args: list of args
        :type args: list.
        """
        if not self.typepath.flagiften:
            raise IncompatibleiLOVersionError(
                "This certificate is not available on this system.")

        select = 'HpeCertAuth.'
        results = self._rdmc.app.select(selector=select)

        try:
            results = results[0]
        except:
            pass

        if results:
            bodydict = results.resp.dict
        else:
            raise NoContentsFoundForOperationError("Unable to find %s" %
                                                   select)

        for item in bodydict['Actions']:
            if 'ImportCRL' in item:
                action = item.split('#')[-1]
                path = bodydict['Actions'][item]['target']
                break

        body = {"Action": action, "ImportUri": args[1]}

        self._rdmc.app.post_handler(path, body)
Ejemplo n.º 9
0
    def run(self, line):
        """Main serverstate 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("Invalid number of parameters, "\
                            "serverstate command does not take any parameters.")

        self.serverstatevalidation(options)

        path = self.typepath.defs.systempath
        results = self._rdmc.app.get_handler(path, silent=True,
                                             uncache=True).dict

        if results:
            results = results['Oem'][self.typepath.defs.oemhp]['PostState']
            sys.stdout.write("The server is currently in state: " + results +
                             '\n')
        else:
            raise NoContentsFoundForOperationError(
                "Unable to retrieve server state")

        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main ESKMCommand 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 not len(args) == 1:
            raise InvalidCommandLineError("eskm command only takes" \
                                                            " one parameter.")

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

        self.eskmvalidation(options)

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

        try:
            results = results[0]
        except:
            pass

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

        if args[0].lower() == 'clearlog':
            actionitem = "ClearESKMLog"
        elif args[0].lower() == 'testconnections':
            actionitem = "TestESKMConnections"
        else:
            raise InvalidCommandLineError('Invalid command.')

        bodydict = results.resp.dict
        try:
            for item in bodydict['Actions']:
                if actionitem in item:
                    if self.typepath.defs.isgen10:
                        actionitem = item.split('#')[-1]

                    path = bodydict['Actions'][item]['target']
                    break
        except:
            pass

        body = {"Action": actionitem}
        self._rdmc.app.post_handler(path, body)

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

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

        return ReturnCodes.SUCCESS
    def search_helper(self, new_searches, curr_searches):
        """ Helper to prepare search strings for patching

        :param new_serches: dictionary of new searches to add
        :type new_searches: dict.
        :param curr_searches: list of current searches
        :type curr_searches: dict.
        """
        final_searches = curr_searches

        if 'add' in new_searches:
            if 'BaseDistinguishedNames' in final_searches:
                for search in new_searches['add']:
                    final_searches['BaseDistinguishedNames'].append(search)
            else:
                final_searches['BaseDistinguishedNames'] = new_searches['add']
        elif 'remove' in new_searches:
            to_remove = []
            if 'BaseDistinguishedNames' not in curr_searches:
                raise NoContentsFoundForOperationError("No search strings to remove")
            for search in new_searches['remove']:
                if search in curr_searches['BaseDistinguishedNames']:
                    to_remove.append(search)
                else:
                    raise InvalidCommandLineError("Unable to find search %s to delete" % search)
            for item in to_remove:
                final_searches['BaseDistinguishedNames'].remove(item)

        return final_searches
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("Clear Pending Configuration: %s", self.name)
        # pylint: disable=unused-variable
        try:
            (options, args) = self._parse_arglist(line)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineError("Failed to parse options")
        if args:
            raise InvalidCommandLineError(
                "Chosen flag doesn't expect additional arguments")
        # Raise exception if server is in POST
        if self._rest_helpers.in_post():
            raise NoContentsFoundForOperationError("Unable to retrieve resources - "\
                                                   "server might be in POST or powered off")
        memory_chunk_tasks = self.get_memory_chunk_tasks()
        self.delete_tasks(memory_chunk_tasks, verbose=True)

        return ReturnCodes.SUCCESS
    def update_mapping_privs(self, roles_to_update):
        """ Helper function to update created role mappings to match user privileges.

        :param roles_to_update: Dictionary of privileges to update.
        :type roles_to_update: dict
        """
        sys.stdout.write("Updating privileges of created role maps...\n")
        try:
            results = self._rdmc.app.select(selector='AccountService.', path_refresh=True)[0].dict
            roles = self._rdmc.app.getcollectionmembers(\
                                    self._rdmc.app.getidbytype('RoleCollection.')[0])
        except (KeyError, IndexError):
            raise NoContentsFoundForOperationError("Unable to gather Role settings. Roles may not "\
                                                "be updated to match privileges requested.")
        for rolemap in results['LDAP']['RemoteRoleMapping']:
            for role in roles:
                if role['RoleId'] == rolemap['LocalRole']:
                    role['RemoteGroup'] = rolemap['RemoteGroup']
                    break
        for role in roles:
            privs = {'AssignedPrivileges' : [], 'OemPrivileges': []}

            for update_role in roles_to_update.keys():
                if role.get('RemoteGroup', None) == update_role:
                    for priv in roles_to_update[update_role]:
                        privs[PRIVKEY[priv][1]].append(PRIVKEY[priv][0])
                    try:
                        self._rdmc.app.patch_handler(role['@odata.id'], privs)
                        sys.stdout.write("Updated privileges for %s\n" % update_role)
                    except IloResponseError:
                        sys.stdout.write("Unable to update privileges for %s\n" % update_role)
                    break
Ejemplo n.º 15
0
    def show_pending_config(self, options):
        """
        Command to display information about pending Persistent Memory Configuration
        :param options: command options
        :type options: options.
        """
        # retrieving task members
        task_members = self._rest_helpers.retrieve_task_members()

        # filtering task members
        filtered_task_members = self._rest_helpers.filter_task_members(
            task_members)
        if not filtered_task_members:
            sys.stdout.write("\nNo pending configuration tasks found.\n\n")
            return None

        # retrieving memory members
        memory = self._rest_helpers.retrieve_memory_resources()
        if memory:
            memory_members = memory.get("Members")
        else:
            raise NoContentsFoundForOperationError(
                "Failed to retrieve Memory Resources")

        attributes = ["Operation", "PmemSize", "VolatileSize", "DimmIds"]
        display_output = list()
        for task in filtered_task_members:
            # finding operation of task
            operation = self._mapper.get_single_attribute(
                task, "Operation", MappingTable.tasks.value, True)
            # displaying existing configuration for DELETE operation
            if operation.get("Operation", "") == "DELETE":
                target_uri = task.get("Payload").get("TargetUri")
                data = self._rest_helpers.get_resource(target_uri)
                table = MappingTable.delete_task.value
            else:
                task_type = self._mapper.get_single_attribute(
                    task, "Type", MappingTable.tasks.value, True)
                task_type = task_type.get("Type", "")
                if task_type != "PMEM":
                    sys.stdout.write(
                        "Unsupported interleave set type found: " + task_type)
                    continue
                data = task
                table = MappingTable.tasks.value

            task_output = self._mapper.get_multiple_attributes(
                data,
                attributes,
                table,
                output_as_json=options.json,
                memory=memory_members)
            display_output.append(task_output)

        if options.json:
            self._display_helpers.display_data(display_output,
                                               OutputFormats.json)
        else:
            self._display_helpers.display_data(display_output,
                                               OutputFormats.table)
    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 args:
            raise InvalidCommandLineError(
                "factorydefaults command takes no arguments.")

        self.factorydefaultsvalidation(options)

        self.rdmc.ui.warn("Resetting iLO to factory default settings.\n"\
                                        "Current session will be terminated.\n")

        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 'ResetToFactoryDefaults' in item:
                    if self.rdmc.app.typepath.defs.isgen10:
                        action = item.split('#')[-1]
                    else:
                        action = "ResetToFactoryDefaults"

                    path = bodydict['Actions'][item]['target']
                    body = {"Action": action, "ResetType": "Default"}
                    break
        except:
            body = {"Action": "ResetToFactoryDefaults", \
                                "Target": "/Oem/Hp", "ResetType": "Default"}

        self.rdmc.app.post_handler(path, body, service=True)

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Ejemplo n.º 17
0
    def run(self, line):
        """ Main ESKMCommand 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("eskm command only takes one parameter.")

        self.eskmvalidation(options)

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

        try:
            results = results[0]
        except:
            pass

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

        if args[0].lower() == 'clearlog':
            actionitem = "ClearESKMLog"
        elif args[0].lower() == 'testconnections':
            actionitem = "TestESKMConnections"
        else:
            raise InvalidCommandLineError('Invalid command.')

        bodydict = results.resp.dict
        try:
            for item in bodydict['Actions']:
                if actionitem in item:
                    if self.rdmc.app.typepath.defs.isgen10:
                        actionitem = item.split('#')[-1]

                    path = bodydict['Actions'][item]['target']
                    break
        except:
            pass

        body = {"Action": actionitem}
        self.rdmc.app.post_handler(path, body)

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
    def timer(self, minutes=1, ping=False):
        """ helper that waits a certain number of minutes before returning or
        pings a server until service is restored (ping only available in local)

        :param minutes: time in minutes
        :type minutes: int
        :param ping: value indicating if ping or timer function
        :type ping: bool
        """
        if ping:
            results = None
            timeout = 0

            while True:
                if not results:
                    try:
                        if timeout == 0:
                            time.sleep(10)

                        self._rdmc.app.login(is_redfish=True)
                        results = self._rdmc.app.get_handler(self.typepath.\
                                                    defs.startpath, silent=True)

                        timeout = 0
                        self._rdmc.app.logout()
                    except:
                        self._rdmc.app.logout()
                        time.sleep(5)
                        timeout += 1
                else:
                    try:
                        if timeout == 0:
                            time.sleep(10)

                        self._rdmc.app.login(is_redfish=True)
                        self._rdmc.app.select(
                            selector=self.typepath.defs.biostype)
                        time.sleep(10)
                        self._rdmc.app.logout()
                        return
                    except:
                        self._rdmc.app.logout()
                        time.sleep(5)
                        timeout += 1

                if timeout >= 60:
                    raise NoContentsFoundForOperationError("Unable to connect" \
                                                                    " to iLO.")
        else:
            for minute in range(minutes):
                if minute + 1 == minutes:
                    sys.stdout.write("1 minute remaining...\n")
                else:
                    sys.stdout.write("%s minutes remaining...\n" \
                                                        % str(minutes-minute))

                time.sleep(60)
    def backupserver(self, options, skey):
        """Create .bak file for a server

        :param options: command options
        :type options: list.
        :param skey: sessionkey of the currently logged in server
        :type skey: str.
        """
        select = "HpeiLOBackupRestoreService."
        backupfile = None
        results = self.rdmc.app.select(selector=select)

        try:
            results = results[0]
        except:
            pass

        if results:
            service = results.resp.dict
        else:
            raise NoContentsFoundForOperationError("%s not found.It may not " \
                                       "be available on this system." % select)

        backuplocation = service['BackupFileLocation']
        backupname = backuplocation.split('/')[-1]

        postdata = []
        postdata.append(('sessionKey', skey))

        if options.fpass:
            postdata.append(('password', options.fpass))
        self.rdmc.ui.printer("Downloading backup file %s..." % backupname)
        backupfile = self.rdmc.app.post_handler(backuplocation, postdata,\
          service=True, silent=True)

        if backupfile:
            self.rdmc.ui.printer("Download complete.\n")
            outfile = open(backupname, 'wb')
            outfile.write(backupfile.ori)
            outfile.close()
        else:
            raise NoContentsFoundForOperationError(
                "Unable to download file.\n")
Ejemplo n.º 20
0
    def configure_pmm(self, options):
        """
        Applies selected configuration to the PMMs
        :param options: options specified by user
        :returns: None
        """
        # Retrieve Memory Chunks and Task Resources from server.
        (task_members, domain_members, memory_chunks) = self._rest_helpers \
                                    .retrieve_task_members_and_mem_domains()

        # Filter Task Resources to include only Pending Configuration Tasks.
        memory_chunk_tasks = self._rest_helpers.filter_task_members(task_members)

        if not domain_members:
            raise NoContentsFoundForOperationError("Failed to retrieve Memory Domain Resources")

        # Dict with input config data
        config_data = {"size": options.memorymode,
                       "pmeminterleave": options.interleave,
                       "proc": options.proc}
        # Check for given processor id list is valid or not.
        if options.proc:
            config_data["proc"] = self.get_valid_processor_list(config_data["proc"], domain_members)
            memory_chunks = self.filter_memory_chunks(memory_chunks,
                                                      domain_members,
                                                      config_data["proc"])

        # In case of 100% Volatile, Interleaving memory regions is not applicable.
        if config_data["size"] == 100 and config_data["pmeminterleave"] and \
        config_data["pmeminterleave"].lower() == "on":
            raise InvalidCommandLineError("Selected configuration is invalid. "
                                          "Interleaving not supported in 100% volatile.")

        if options.force:
            self.delete_existing_chunks_and_tasks(memory_chunk_tasks, memory_chunks)
        else:
            self.warn_existing_chunks_and_tasks(memory_chunk_tasks, memory_chunks)

        for member in domain_members:
            proc_id = member['Id'].encode('ascii', 'ignore')
            # If given proc list is not empty, applies configuration to selected processors
            if not config_data["proc"] or (proc_id in config_data["proc"]):
                path = member['MemoryChunks'].get('@odata.id').encode('ascii', 'ignore')
                data = self.get_post_data(config_data, member['InterleavableMemorySets'])
                for body in data:
                    resp = self._rest_helpers.post_resource(path, body)
                if resp is None:
                    raise NoChangesFoundOrMadeError("Error occurred while applying configuration")

        # Display warning
        sys.stdout.write("\n***WARNING: Configuration changes require reboot to take effect***\n")

        # Display pending configuration
        self._show_pmem_config.show_pending_config(type("MyOptions", (object, ), dict(json=False)))
        return None
Ejemplo n.º 21
0
    def run(self, line):
        """ Main clearrestapistate 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("clearrestapistate command takes no "\
                                          "arguments.")

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

        self.clearrestapistatevalidation(options)

        select = 'Manager.'
        results = self._rdmc.app.filter(select, None, None)

        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.typepath.defs.oemhp]
        try:
            for item in bodydict['Actions']:
                if 'ClearRestApiState' in item:
                    if self.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)

        return ReturnCodes.SUCCESS
    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")
    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")
Ejemplo n.º 24
0
    def addinstallset(self, setfile, name):
        """Adds an install set
        :param setfile: filename of install set
        :type setfile: str.
        :param name: string of the install set name to add
        :type name: str.
        """
        path = '/redfish/v1/UpdateService/InstallSets/'
        comps = self._rdmc.app.getcollectionmembers(\
                            '/redfish/v1/UpdateService/ComponentRepository/')

        sets = self._rdmc.app.getcollectionmembers(path)

        if not name:
            name = str(datetime.datetime.now())
            name = name.replace(':', '')
            name = name.replace(' ', 'T')
        try:
            inputfile = open(setfile, 'r')
            sequences = json.loads(inputfile.read())
        except Exception as excp:
            raise InvalidFileInputError("%s" % excp)

        listtype = self.validatefile(sequences)

        if listtype:
            body = {"Name": name, "Sequence": sequences}
        else:
            body = sequences
            if "Sequence" in body:
                sequences = body['Sequence']
            else:
                raise InvalidFileInputError("Invalid install set file.")
            sequences = body["Sequence"]

        filenamelist = [x['Filename'] for x in comps]

        for sequence in sequences:
            if sequence['Command'] == 'ApplyUpdate':
                if 'Filename' in list(sequence.keys()):
                    if not sequence['Filename'] in filenamelist:
                        raise NoContentsFoundForOperationError('Component' \
                            ' referenced in install set is not present on' \
                            ' iLO Drive: %s' % sequence['Filename'])
            elif sequence['Command'] == 'WaitTimeSeconds':
                sequence['WaitTimeSeconds'] = int(sequence['WaitTimeSeconds'])
        for setvar in sets:
            if setvar['Name'] == body['Name']:
                raise InvalidCommandLineError(
                    'Install set name is already in use.')

        self._rdmc.app.post_handler(path, body)
Ejemplo n.º 25
0
    def getcerthelper(self, _, options):
        """ Helper function for importing CRL certificate

        :param options: list of options
        :type options: list.
        """

        select = self.typepath.defs.hphttpscerttype
        results = self._rdmc.app.select(selector=select)

        try:
            results = results[0]
        except:
            pass

        if results:
            try:
                csr = results.resp.dict['CertificateSigningRequest']
                if not csr:
                    raise ValueError
            except (KeyError, ValueError):
                raise NoContentsFoundForOperationError('Unable to find a valid certificate. If '\
                                                       'you just generated a new certificate '\
                                                       'signing request the process may take '\
                                                       'up to 10 minutes.')

            if not options.filename:
                filename = __filename__
            else:
                filename = options.filename[0]

            outfile = open(filename, 'w')
            outfile.write(csr)
            outfile.close()

            sys.stdout.write("Certificate saved to: %s\n" % filename)
        else:
            raise NoContentsFoundForOperationError("Unable to find %s" %
                                                   select)
    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.º 27
0
    def copyjobtoipqueue(self, ipjobs, jobkey):
        """
        Copies HpeIpJob to Job queue. Function assumes there is a job to copy.
        A check was already done to make sure we have a job to copy in hasipjobs()
        :param ipjobs: url path of heip.
        :type ipjobs: list of dictionary.
        :param jobkey: key of job to copy.
        :type jokbey: str.
        """

        get_results = self._rdmc.app.get_handler(self.path,\
                verbose=self._rdmc.opts.verbose, silent=True)

        j2python = json.loads(get_results.read)
        copy_job = {}
        for ipj in j2python:
            if jobkey == ipj:
                _decode = self.decode_base64_string(j2python[ipj])
                if _decode is not None:
                    _critical_props = {
                        "log": "[{\"msg\": \"WAITINGTOBEPROCESSED\", \"percent\": 0}]",
                        "status": "waiting"
                    }
                    copy_job.update({k: v.update(_critical_props) or v \
                        for k, v in json.loads(_decode).items() if k in self.ipjobtype})
                else:
                    raise NoContentsFoundForOperationError(\
                        "Not supported profile content")
                break
        if not copy_job:
            raise NoContentsFoundForOperationError(\
                "The ID %s does not match any ipprofile" % jobkey)
        payload = {}
        payload["path"] = self.ipjobs
        payload["body"] = copy_job

        self._rdmc.app.put_handler(payload["path"], payload["body"],\
              verbose=self._rdmc.opts.verbose)
Ejemplo n.º 28
0
 def apply_pmm_config(self, options):
     """
     Calls relevant functions based on the flags specified by the user.
     :param options: options specified by the user.
     :type options: instance of OptionParser class.
     """
     if options.list:
         self.show_predefined_config_options()
     elif options.config:
         # 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.apply_predefined_config(options)
Ejemplo n.º 29
0
    def apply_predefined_config(self, options):
        """
        Apply the selected pre-defined configuration to Persistent Memory Modules.
        :param options: option specified by the user.
        :returns: None
        """
        # Retrieve Memory Chunks and Task Resources from server
        (task_members, domain_members, memory_chunks) = self._rest_helpers \
                                    .retrieve_task_members_and_mem_domains()

        # Filter Task Resources to include only Pending Configuration Tasks
        memory_chunk_tasks = self._rest_helpers.filter_task_members(
            task_members)

        if options.force:
            self.delete_existing_chunks_and_tasks(memory_chunk_tasks,
                                                  memory_chunks)
        else:
            self.warn_existing_chunks_and_tasks(memory_chunk_tasks,
                                                memory_chunks)

        if not domain_members:
            raise NoContentsFoundForOperationError(
                "Failed to retrive Memory Domain Resources")

        # Get the user specified configID
        config_data = next((config_id for config_id in self.config_ids \
                           if config_id.get("name").lower() == options.config.lower()), None)

        for proc in domain_members:
            path = proc['MemoryChunks'].get('@odata.id').encode(
                'ascii', 'ignore')
            data = self.get_post_data(config_data,
                                      proc['InterleavableMemorySets'])
            for body in data:
                resp = self._rest_helpers.post_resource(path, body)
                if resp is None:
                    raise NoChangesFoundOrMadeError(
                        "Error occured while applying configuration")

        # display warning
        sys.stdout.write(
            "\n***WARNING: Configuration changes require reboot to take effect***\n"
        )

        # display pending configuration
        self._show_pmem_config.show_pending_config(
            type("MyOptions", (object, ), dict(json=False)))
    def createtask(self, tasks):
        """ Creates a task in the update task queue

        :param tasks: arguments for creating tasks
        :type tasks: list.
        """
        path = '/redfish/v1/UpdateService/UpdateTaskQueue/'
        comps = self._rdmc.app.getcollectionmembers('/redfish/v1/UpdateService/'\
                                                    'ComponentRepository/')
        for task in tasks:
            usedcomp = None
            newtask = None

            try:
                usedcomp = int(task)
                newtask = {'Name': 'Wait-%s %s seconds' % (str(randint(0, \
                           1000000)), str(usedcomp)), 'Command': 'Wait', \
                           'WaitTimeSeconds':usedcomp, 'UpdatableBy':[\
                                                  'RuntimeAgent', 'Uefi']}
            except:
                pass

            if task.lower() == 'reboot':
                newtask = {'Name': 'Reboot-%s' % str(randint(0, 1000000)), \
                          'Command': 'ResetServer', 'UpdatableBy': \
                          ['RuntimeAgent']}
            elif not newtask:
                try:
                    for comp in comps:
                        if comp['Filename'] == task:
                            usedcomp = comp
                            break
                except:
                    pass

                if not usedcomp:
                    raise NoContentsFoundForOperationError('Component ' \
                           'referenced is not present on iLO Drive: %s' % task)

                newtask = {'Name': 'Update-%s %s' % (str(randint(0, 1000000)), \
                        usedcomp['Name']), 'Command': 'ApplyUpdate',\
                      'Filename': usedcomp['Filename'], 'UpdatableBy': usedcomp\
                      ['UpdatableBy'], 'TPMOverride': True}

            sys.stdout.write('Creating task: "%s"\n' % newtask['Name'])

            self._rdmc.app.post_handler(path, newtask)