Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
def _get_comp_type(payload):
    """ Get's the component type and returns it

    :param payload: json payload of .fwpkg file
    :type payload: dict.
    :returns: returns the type of component. Either A,B,C, or D.
    :rtype: string
    """
    ctype = ''
    if "Uefi" in payload['UpdatableBy'] and "RuntimeAgent" in payload[
            'UpdatableBy']:
        ctype = 'D'
    else:
        for device in payload['Devices']['Device']:
            for image in device['FirmwareImages']:
                if 'DirectFlashOk' not in image.keys():
                    raise InvalidFileInputError("Cannot flash this firmware.")
                if image['DirectFlashOk']:
                    ctype = 'A'
                    if image['ResetRequired']:
                        ctype = 'B'
                        break
                elif image['UefiFlashable']:
                    ctype = 'C'
                    break
                else:
                    ctype = 'D'

    return ctype
    def load_clone(self, filename, options):
        """ load the clone file onto the server

        :param filename: filename containing the clone config data
        :type filename: str
        :param options: command line options
        :type options: list.
        """
        loadcontents = None

        if not filename:
            filename = 'clone.json'

        if not os.path.isfile(filename):
            raise InvalidFileInputError("File '%s' doesn't exist. Please " \
                            "create file by running save command." % file)
        if options.encryption:
            with open(filename, "rb") as myfile:
                data = myfile.read()
                data = Encryption().decrypt_file(data, \
                                                    options.encryption)
        else:
            myfile = open(filename, 'r')
            data = myfile.read()

        myfile.close()

        try:
            loadcontents = json.loads(data)
        except:
            raise InvalidFileFormattingError("Invalid file formatting " \
                                                "found in file %s" % file)

        return loadcontents
 def check_file_rw(filename, rw):
     try:
         fd = open(filename, rw)
         fd.close()
     except IOError:
         raise InvalidFileInputError("The file \'%s\' could not be opened for upload" % \
                                     filename)
Ejemplo n.º 5
0
    def preparefwpkg(self, pkgfile):
        """ Prepare fwpkg file for flashing

        :param pkgfile: Location of the .fwpkg file
        :type pkgfile: string.
        :returns: returns the files needed to flash, directory they are located
                                                            in, and type of file.
        :rtype: string, string, string
        """
        files = []
        imagefiles = []
        payloaddata = None
        tempfoldername = ''.join(
            random.choice(ascii_lowercase) for i in range(12))

        tempdir = os.path.join(self._rdmc.app.config.get_cachedir(), \
                                                                tempfoldername)
        if not os.path.exists(tempdir):
            os.makedirs(tempdir)
        try:
            zfile = zipfile.ZipFile(pkgfile)
            zfile.extractall(tempdir)
            zfile.close()
        except:
            raise InvalidFileInputError("Unable to unpack file.")

        files = os.listdir(tempdir)

        if 'payload.json' in files:
            with open(os.path.join(tempdir, 'payload.json'), "r") as pfile:
                data = pfile.read()
            payloaddata = json.loads(data)
        else:
            raise InvalidFileInputError(
                "Unable to find payload.json in fwpkg file.")

        comptype = _get_comp_type(payloaddata)

        if comptype == 'C':
            imagefiles = [self.type_c_change(tempdir, pkgfile)]
        else:
            for device in payloaddata['Devices']['Device']:
                for firmwareimage in device['FirmwareImages']:
                    if firmwareimage['FileName'] not in imagefiles:
                        imagefiles.append(firmwareimage['FileName'])

        return imagefiles, tempdir, comptype
    def downloadlocally(self, filepath, options=None):
        """ Used to download a component from the iLO Repo locally

        :param filepath: Path to the file to download.
        :type filepath: string.
        """
        try:
            bs2 = risblobstore2.BlobStore2()
            risblobstore2.BlobStore2.initializecreds(options.user,
                                                     options.password)
            bs2.channel.dll.downloadComponent.argtypes = [c_char_p, c_char_p]
            bs2.channel.dll.downloadComponent.restype = c_int

            filename = filepath.rsplit('/', 1)[-1]
            if not options.outdir:
                destination = os.path.join(os.getcwd(), filename)
            else:
                destination = os.path.join(options.outdir, filename)

            if not os.path.exists(os.path.join(os.path.split(destination)[0])):
                raise InvalidFileInputError("Invalid output file location.")
            if not os.access(os.path.join(os.path.split(destination)[0]),
                             os.W_OK):
                raise InvalidFileInputError("File location is not writable.")
            if os.access(destination, os.F_OK) and not os.access(destination, \
                                                                 os.W_OK):
                raise InvalidFileInputError(
                    "Existing File cannot be overwritten.")

            ret = bs2.channel.dll.downloadComponent(ctypes.create_string_buffer(\
                                                filename.encode('utf-8')), \
                                                ctypes.create_string_buffer(\
                                                destination.encode('utf-8')))

            if ret != 0:
                sys.stdout.write("Component " + filename +
                                 " download failed\n")
                return ReturnCodes.FAILED_TO_DOWNLOAD_COMPONENT
            else:
                sys.stdout.write("Component " + filename + \
                                                    " downloaded successfully\n")

        except Exception as excep:
            raise DownloadError(str(excep))

        return ReturnCodes.SUCCESS
    def downloadlocally(self, options=None):
        """ Used to download a component from the iLO Repo locally

        :param options: command options (argparse)
        :type options: options.
        """
        try:
            dll = self.rdmc.app.current_client.connection._conn.channel.dll
            dll.downloadComponent.argtypes = [c_char_p, c_char_p]
            dll.downloadComponent.restype = c_int

            filename = options.component.rsplit('/', 1)[-1]
            if not options.outdir:
                destination = os.path.join(os.getcwd(), filename)
            else:
                destination = os.path.join(options.outdir, filename)

            if not os.path.exists(os.path.join(os.path.split(destination)[0])):
                raise InvalidFileInputError("Invalid output file location.")
            if not os.access(os.path.join(os.path.split(destination)[0]),
                             os.W_OK):
                raise InvalidFileInputError("File location is not writable.")
            if os.access(destination, os.F_OK) and not os.access(destination, \
                                                                 os.W_OK):
                raise InvalidFileInputError(
                    "Existing File cannot be overwritten.")

            ret = dll.downloadComponent(ctypes.create_string_buffer(\
                                filename.encode('utf-8')), ctypes.create_string_buffer(\
                                                            destination.encode('utf-8')))

            if ret != 0:
                self.rdmc.ui.error("Component " + filename +
                                   " download failed\n")
                return ReturnCodes.FAILED_TO_DOWNLOAD_COMPONENT
            else:
                self.rdmc.ui.printer("Component " + filename +
                                     " downloaded successfully\n")

        except Exception as excep:
            raise DownloadError(str(excep))

        return ReturnCodes.SUCCESS
Ejemplo n.º 8
0
    def preparefwpkg(self, pkgfile):
        """ Prepare fwpkg file for flashing

        :param pkgfile: Location of the .fwpkg file
        :type pkgfile: string.
        :returns: returns the files needed to flash, directory they are located
                                                            in, and type of file.
        :rtype: string, string, string
        """
        files = []
        imagefiles = []
        payloaddata = None
        tempdir = tempfile.mkdtemp()

        try:
            zfile = zipfile.ZipFile(pkgfile)
            zfile.extractall(tempdir)
            zfile.close()
        except Exception as excp:
            raise InvalidFileInputError("Unable to unpack file. " + str(excp))

        files = os.listdir(tempdir)

        if 'payload.json' in files:
            with open(os.path.join(tempdir, 'payload.json'), "r") as pfile:
                data = pfile.read()
            payloaddata = json.loads(data)
        else:
            raise InvalidFileInputError(
                "Unable to find payload.json in fwpkg file.")

        comptype = _get_comp_type(payloaddata)

        if comptype == 'C':
            imagefiles = [self.type_c_change(tempdir, pkgfile)]
        else:
            for device in payloaddata['Devices']['Device']:
                for firmwareimage in device['FirmwareImages']:
                    if firmwareimage['FileName'] not in imagefiles:
                        imagefiles.append(firmwareimage['FileName'])

        return imagefiles, tempdir, comptype
Ejemplo n.º 9
0
    def validatempfile(self, mpfile=None, lfile=None):
        """ Validate temporary file

        :param mpfile: configuration file
        :type mpfile: string.
        :param lfile: custom file name
        :type lfile: string.
        """
        sys.stdout.write('Checking given server information...\n')

        if not mpfile:
            return False

        if not os.path.isfile(mpfile):
            raise InvalidFileInputError("File '%s' doesn't exist, please " \
                            "create file by running save command." % mpfile)

        try:
            with open(mpfile, "r") as myfile:
                data = list()
                cmdtorun = ['load']
                cmdargs = ['-f', str(lfile)]
                globalargs = ['-v', '--nocache']

                while True:
                    line = myfile.readline()

                    if not line:
                        break

                    if line.endswith(os.linesep):
                        line.rstrip(os.linesep)

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

                    if len(args) < 5:
                        sys.stderr.write('Incomplete data in input file: {}\n'\
                                                                .format(line))
                        raise InvalidMSCfileInputError('Please verify the '\
                                            'contents of the %s file' %mpfile)
                    else:
                        linelist = globalargs + cmdtorun + args + cmdargs
                        line = str(line).replace("\n", "")
                        self.queue.put(linelist)
                        data.append(linelist)
        except Exception:
            raise

        if data:
            return data
        else:
            return False
Ejemplo n.º 10
0
    def encode_base64_string(self, args):
        """
        Encode a given string  with base64 and gzip it.
        :param args: command line args
        :type args: string.
        """

        payload = {}
        filename = args[0]
        if filename:
            if not os.path.isfile(filename):
                raise InvalidFileInputError("File '%s' doesn't exist. "\
                    "Please create file by running 'save' command."\
                     % filename)

            try:
                inputfile = open(filename, 'r')
                contentsholder = json.loads(inputfile.read())
            except:
                raise InvalidFileFormattingError("Input file '%s' was not "\
                                                 "format properly."
                                                 % filename)

            try:
                text = json.dumps(contentsholder)
                buf = StringIO()
                gzfile = gzip.GzipFile(mode='wb', fileobj=buf)
                gzfile.write(text)
                gzfile.close()

                en_text = base64.encodestring(buf.getvalue())

                epoch = datetime.utcfromtimestamp(0)
                now = datetime.utcnow()
                delta = now - epoch
                time_stamp = delta.total_seconds() * 1000
                time_stamp = repr(time_stamp).split('.')[0]

                body_text = {time_stamp: en_text.strip()}
                payload["body"] = body_text
                payload["path"] = self.path
            except:
                raise UnableToDecodeError("Error while encoding string.")

        return payload
Ejemplo n.º 11
0
    def importtlshelper(self, args):
        """ Helper function for importing TLS certificate

        :param args: list of args
        :type args: list.
        """
        tlsfile = args[1]

        try:
            with open(tlsfile) as certfile:
                certdata = certfile.read()
                certfile.close()
        except:
            raise InvalidFileInputError("Error loading the specified file.")

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

        try:
            results = results[0]
        except:
            pass

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

        bodydict = results.resp.dict
        try:
            for item in bodydict['Actions']:
                if 'ImportCertificate' in item:
                    if self.typepath.defs.isgen10:
                        action = item.split('#')[-1]
                    else:
                        action = "ImportCertificate"
                    path = bodydict['Actions'][item]['target']
                    break
        except:
            action = "ImportCertificate"

        body = {"Action": action, "Certificate": certdata}

        self._rdmc.app.post_handler(path, body)
Ejemplo n.º 12
0
    def importcahelper(self, args):
        """ Helper function for importing TLS certificate

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

        tlsfile = args[1]

        try:
            with open(tlsfile) as certfile:
                certdata = certfile.read()
                certfile.close()
        except:
            raise InvalidFileInputError("Error loading the specified file.")

        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 'ImportCACertificate' in item:
                action = item.split('#')[-1]
                path = bodydict['Actions'][item]['target']
                break

        body = {"Action": action, "Certificate": certdata}

        self._rdmc.app.post_handler(path, body)
    def validatefile(self, installsetfile):
        """ validates json file

        :param file: json file to validate
        :type file: string.
        """
        listtype = True
        keylist = ['Name', 'UpdatableBy', 'Command', 'WaitTimeSeconds', \
                                                                    'Filename']

        if isinstance(installsetfile, list):
            for item in installsetfile:
                for key in item:
                    if key not in keylist:
                        raise InvalidFileInputError('Property %s is invalid ' \
                                                    'for an install set.' % key)
        else:
            listtype = False

        return listtype
    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, excp:
            raise InvalidFileInputError("%s" % excp)
Ejemplo n.º 15
0
    def run(self, line):
        """ Main raw patch worker function

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

        headers = {}
        results = []

        self.postvalidation(options)

        contentsholder = None

        try:
            with open(options.path, 'r') as _if:
                contentsholder = json.loads(_if.read(),
                                            object_pairs_hook=OrderedDict)
        except IOError:
            raise InvalidFileInputError("File '%s' doesn't exist. " \
                                "Please create file by running 'save' command." % options.path)
        except (ValueError):
            raise InvalidFileFormattingError("Input file '%s' was not " \
                                                            "formatted properly." % options.path)
        if options.encode:
            if "body" in contentsholder and "UserName" in contentsholder["body"] and \
                        "Password" in contentsholder["body"] and \
                        len(list(contentsholder["body"].keys())) == 2:
                encobj = Encryption()
                contentsholder["body"]["UserName"] = encobj.decode_credentials(\
                                            contentsholder["body"]["UserName"])
                contentsholder["body"]["Password"] = encobj.decode_credentials(\
                                            contentsholder["body"]["Password"])

        if options.headers:
            extraheaders = options.headers.split(',')
            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    raise InvalidCommandLineError(
                        "Invalid format for --headers option.")

        if "path" in contentsholder and "body" in contentsholder:
            results.append(self._rdmc.app.post_handler(contentsholder["path"], \
                  contentsholder["body"], headers=headers, \
                  silent=options.silent, service=options.service))
        elif all([re.match("^\/(\S+\/?)+$", key) for key in contentsholder]):
            for path, body in contentsholder.items():
                results.append(self._rdmc.app.post_handler(path, \
                                            body, headers=headers, \
                                            silent=options.silent, service=options.service))
        else:
            raise InvalidFileFormattingError("Input file '%s' was not "\
                                             "formatted properly." % options.path)
        returnresponse = False

        if options.response or options.getheaders:
            returnresponse = True

        if results and returnresponse:
            for result in results:
                if options.getheaders:
                    sys.stdout.write(
                        json.dumps(dict(result.getheaders())) + "\n")

                if options.response:
                    sys.stdout.write(result.ori + "\n")

        logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Ejemplo n.º 16
0
    def run(self, line):
        """ Main raw patch worker function

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

        headers = {}
        results = None

        self.patchvalidation(options)

        contentsholder = None
        if len(args) == 1:
            if not os.path.isfile(args[0]):
                raise InvalidFileInputError("File '%s' doesn't exist. " \
                    "Please create file by running 'save' command." % args[0])

            try:
                inputfile = open(args[0], 'r')
                contentsholder = json.loads(inputfile.read())
            except:
                raise InvalidFileFormattingError("Input file '%s' was not " \
                                                 "format properly." % args[0])
        elif len(args) > 1:
            raise InvalidCommandLineError("Raw patch only takes 1 argument.\n")
        else:
            raise InvalidCommandLineError(
                "Missing raw patch file input argument.\n")

        if options.headers:
            extraheaders = options.headers.split(',')

            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    raise InvalidCommandLineError(
                        "Invalid format for --headers option.")

        if "path" in contentsholder and "body" in contentsholder:
            returnresponse = False

            if options.response or options.getheaders:
                returnresponse = True

            results = self._rdmc.app.patch_handler(contentsholder["path"], \
                  contentsholder["body"], headers=headers, \
                  response=returnresponse, silent=options.silent, \
                  optionalpassword=options.biospassword, service=options.service)
        else:
            raise InvalidFileFormattingError(
                "Input file '%s' was not format properly." % args[0])

        if results and returnresponse:
            if options.getheaders:
                sys.stdout.write(json.dumps(dict(results.getheaders())) + "\n")

            if options.response:
                sys.stdout.write(results.read)

        #Return code
        return ReturnCodes.SUCCESS
    def restoreserver(self, options, skey):
        """Use a .bak file to restore a server

        :param options: command options
        :type options: list.
        :param skey: sessionkey of the currently logged in server
        :type skey: str.
        """

        select = "HpeiLOBackupRestoreService."

        if options.filename:
            filename = options.filename[0]
        else:
            files = []
            files = [
                f for f in os.listdir('.')
                if os.path.isfile(f) and f.endswith('.bak')
            ]
            if files and len(files) > 1:
                raise InvalidFileInputError("More than one .bak file found in "\
                                            "the current directory. Please specify "\
                                            "a file using the -f option.")
            elif not files:
                raise InvalidFileInputError("No .bak file found in current "\
                                            "directory. Please specify a file using the -f option.")
            else:
                filename = files[0]

        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)
        restorelocation = service['HttpPushUri']
        postdata = []

        with open(filename, 'rb') as fle:
            bakfile = fle.read()
        postdata.append(('sessionKey', skey))
        if options.fpass:
            postdata.append(('password', options.fpass))
        postdata.append(
            ('file', (filename, bakfile, 'application/octet-stream')))

        resp = self.rdmc.app.post_handler(restorelocation, postdata, service=False, silent=True, \
                                    headers={'Cookie': 'sessionKey=' + skey.decode('utf-8')})

        if not resp.status == 200:
            if resp.ori == 'invalid_restore_password':
                raise UploadError("Invalid or no password supplied during restore. Please "\
                                  "supply the password used during creation of the backup file.")
            else:
                raise UploadError("Error while uploading the backup file.")
        else:
            self.rdmc.ui.warn("Restore in progress. iLO while be unresponsive while the "\
                                        "restore completes.\nYour session will be terminated.\n")
            self.auxcommands['logout'].run("")
Ejemplo n.º 18
0
    def run(self, line):
        """ Main iloaccounts function

        :param line: string of arguments passed in
        :type line: str.
        """
        acct = mod_acct = None
        try:
            ident_subparser = False
            for cmnd in __subparsers__:
                if cmnd in line:
                    (options, args) = self.rdmc.rdmc_parse_arglist(self, line)
                    ident_subparser = True
                    break
            if not ident_subparser:
                (options, args) = self.rdmc.rdmc_parse_arglist(self,
                                                               line,
                                                               default=True)
        except (InvalidCommandLineErrorOPTS, SystemExit):
            if ("-h" in line) or ("--help" in line):
                return ReturnCodes.SUCCESS
            else:
                raise InvalidCommandLineErrorOPTS("")

        self.iloaccountsvalidation(options)

        redfish = self.rdmc.app.monolith.is_redfish
        path = self.rdmc.app.typepath.defs.accountspath
        results = self.rdmc.app.get_handler(path, service=True,
                                            silent=True).dict

        if redfish:
            results = results['Members']
        else:
            if 'Member' in results['links']:
                results = results['links']['Member']
            else:
                results = list()

        for indx, acct in enumerate(results):
            acct = self.rdmc.app.get_handler(acct[self.rdmc.app.typepath.defs.hrefstring],\
                                                                service=True, silent=True).dict
            try:
                if hasattr(options, 'identifier'):
                    if acct['Id'] == options.identifier or acct[
                            'UserName'] == options.identifier:
                        if redfish:
                            path = acct['@odata.id']
                        else:
                            path = acct['links']['self']['href']
                        mod_acct = acct
                elif options.command == 'default':
                    results[indx] = acct
                else:
                    raise KeyError
            except KeyError:
                continue
            else:
                if mod_acct:
                    acct = mod_acct
                    break

        if not results:
            raise NoContentsFoundForOperationError(
                "No iLO Management Accounts were found.")

        outdict = dict()
        if options.command.lower() == 'default':
            if not options.json:
                self.rdmc.ui.printer("\niLO Account info:\n\n[Id] UserName (LoginName): "\
                                     "\nPrivileges\n-----------------\n\n", verbose_override=True)
            for acct in sorted(results, key=lambda k: int(k['Id'])):
                privstr = ""
                privs = acct['Oem'][
                    self.rdmc.app.typepath.defs.oemhp]['Privileges']

                if 'ServiceAccount' in list(acct['Oem'][self.rdmc.app.typepath.defs.oemhp].keys()) \
                        and acct['Oem'][self.rdmc.app.typepath.defs.oemhp]['ServiceAccount']:
                    service = 'ServiceAccount=True'
                else:
                    service = 'ServiceAccount=False'
                if not options.json:
                    for priv in privs:
                        privstr += priv + '=' + str(privs[priv]) + '\n'
                    self.rdmc.ui.printer("[%s] %s (%s):\n%s\n%s\n" % (acct['Id'], \
                                    acct['UserName'], \
                                    acct['Oem'][self.rdmc.app.typepath.defs.oemhp]['LoginName'], \
                                    service, privstr), verbose_override=True)
                keyval = '[' + str(acct['Id']) + '] ' + acct['UserName']
                outdict[keyval] = privs
                outdict[keyval]['ServiceAccount'] = service.split(
                    '=')[-1].lower()
            if options.json:
                self.rdmc.ui.print_out_json_ordered(outdict)
        elif options.command.lower() == 'changepass':
            if not acct:
                raise InvalidCommandLineError(
                    "Unable to find the specified account.")
            if not options.acct_password:
                self.rdmc.ui.printer('Please input the new password.\n',
                                     verbose_override=True)
                tempinput = getpass.getpass()
                self.credentialsvalidation('', '', tempinput, '', True,
                                           options)
                options.acct_password = tempinput
            account = options.identifier.lower()
            self.credentialsvalidation('', '',
                                       options.acct_password.split('\r')[0],
                                       '', True)
            body = {'Password': options.acct_password.split('\r')[0]}

            if path and body:
                self.rdmc.app.patch_handler(path, body)
            else:
                raise NoContentsFoundForOperationError(
                    'Unable to find the specified account.')

        elif options.command.lower() == 'add':
            if options.encode:
                args[2] = Encryption.decode_credentials(args[2])
                if isinstance(args[2], bytes):
                    args[2] = args[2].decode('utf-8')

            privs = self.getprivs(options)
            path = self.rdmc.app.typepath.defs.accountspath

            body = {"UserName": options.identifier, "Password": options.acct_password, "Oem": \
                    {self.rdmc.app.typepath.defs.oemhp: {"LoginName": options.loginname}}}
            if privs:
                body["Oem"][self.rdmc.app.typepath.defs.oemhp].update(
                    {"Privileges": privs})
            self.credentialsvalidation(options.identifier, options.loginname, \
                                       options.acct_password, acct, True)
            if options.serviceacc:
                body["Oem"][self.rdmc.app.typepath.defs.oemhp].update(
                    {"ServiceAccount": True})
            if options.role:
                if self.rdmc.app.getiloversion() >= 5.140:
                    body["RoleId"] = options.role
                else:
                    raise IncompatibleiLOVersionError("Roles can only be set in iLO 5"\
                                                                                " 1.40 or greater.")
            if path and body:
                self.rdmc.app.post_handler(path, body)
        elif options.command.lower() == 'modify':
            if not mod_acct:
                raise InvalidCommandLineError(
                    "Unable to find the specified account.")
            body = {}

            if options.optprivs:
                body.update({
                    'Oem': {
                        self.rdmc.app.typepath.defs.oemhp: {
                            'Privileges': {}
                        }
                    }
                })
                if any(priv for priv in options.optprivs if 'SystemRecoveryConfigPriv' in priv) \
                                                            and 'SystemRecoveryConfigPriv' not in \
                                                                        self.getsesprivs().keys():
                    raise IdTokenError("The currently logged in account must have The System "\
                                         "Recovery Config privilege to add the System Recovery "\
                                         "Config privilege.")
                privs = self.getprivs(options)
                body['Oem'][
                    self.rdmc.app.typepath.defs.oemhp]['Privileges'] = privs

            if options.role and self.rdmc.app.getiloversion() >= 5.140:
                body["RoleId"] = options.role

            if not body:
                raise InvalidCommandLineError("Valid Privileges/RoleID have not been provided; "\
                        " no changes have been made to this account: %s\n" % options.identifier)
            self.rdmc.app.patch_handler(path, body)

        elif options.command.lower() == 'delete':
            if not acct:
                raise InvalidCommandLineError(
                    "Unable to find the specified account.")
            self.rdmc.app.delete_handler(path)

        elif 'cert' in options.command.lower():
            certpath = '/redfish/v1/AccountService/UserCertificateMapping/'
            privs = self.getsesprivs()
            if self.rdmc.app.typepath.defs.isgen9:
                IncompatibleiLOVersionError("This operation is only available on gen 10 "\
                                                  "and newer machines.")
            elif not privs['UserConfigPriv']:
                raise IdTokenError("The currently logged in account must have The User "\
                                     "Config privilege to manage certificates for users.")
            else:
                if options.command.lower() == 'addcert':
                    if not acct:
                        raise InvalidCommandLineError(
                            "Unable to find the specified account.")
                    body = {}
                    username = acct['UserName']
                    account = acct['Id']
                    fingerprintfile = options.certificate
                    if os.path.exists(fingerprintfile):
                        with open(fingerprintfile, 'r') as fingerfile:
                            fingerprint = fingerfile.read()
                    else:
                        raise InvalidFileInputError('%s cannot be read.' %
                                                    fingerprintfile)
                    body = {"Fingerprint": fingerprint, "UserName": username}
                    self.rdmc.app.post_handler(certpath, body)

                elif options.command.lower() == 'deletecert':
                    if not acct:
                        raise InvalidCommandLineError(
                            "Unable to find the specified account.")
                    certpath += acct['Id']
                    self.rdmc.app.delete_handler(certpath)

        else:
            raise InvalidCommandLineError('Invalid command.')

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

        :param line: string of arguments passed in
        :type line: str.
        """
        mod_acct = None
        valid_args = ['add', 'delete', 'modify', 'changepass', 'addcert', 'deletecert']
        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 len(args) > 4:
            raise InvalidCommandLineError("Invalid number of parameters for "\
                                                                "this command.")
        arg_cnt = 0
        for arg in args:
            if arg in valid_args:
                arg_cnt += 1
        if arg_cnt > 1:
            raise InvalidCommandLineError('Invalid command.')

        self.iloaccountsvalidation(options)

        redfish = self._rdmc.app.monolith.is_redfish
        path = self.typepath.defs.accountspath
        results = self._rdmc.app.get_handler(path, service=True, silent=True).dict

        newresults = []

        if redfish:
            results = results['Members']
        else:
            results = results['links']['Member']

        for acct in results:
            acct = self._rdmc.app.get_handler(acct[self.typepath.defs.hrefstring],\
                                                                service=True, silent=True).dict
            if acct['Id'] in args or acct['UserName'] in args:
                mod_acct = acct
                if redfish:
                    path = acct['@odata.id']
                else:
                    path = acct['links']['self']['href']
            newresults.append(acct)
            results = newresults

        acct = mod_acct
        if not results:
            raise NoContentsFoundForOperationError("")

        outdict = dict()
        if not args:
            if not options.json:
                sys.stdout.write("iLO Account info: \n[Id] UserName (LoginName): "\
                                "\nPrivileges\n-----------------\n")
            for acct in sorted(results, key=lambda k: int(k['Id'])):
                privstr = ""
                privs = acct['Oem'][self.typepath.defs.oemhp]['Privileges']

                if 'ServiceAccount' in list(acct['Oem'][self.typepath.defs.oemhp].keys()) and \
                acct['Oem'][self.typepath.defs.oemhp]['ServiceAccount']:
                    service = 'ServiceAccount=True'
                else:
                    service = 'ServiceAccount=False'
                if not options.json:
                    for priv in privs:
                        privstr += priv + '=' + str(privs[priv]) + '\n'
                    sys.stdout.write("[%s] %s (%s):\n%s\n%s\n" % (acct['Id'], acct['UserName'], \
                            acct['Oem'][self.typepath.defs.oemhp]['LoginName'], service, privstr))
                keyval = '['+str(acct['Id'])+'] '+acct['UserName']
                outdict[keyval] = privs
                outdict[keyval]['ServiceAccount'] = service.split('=')[-1].lower()
            if options.json:
                sys.stdout.write(str(json.dumps(outdict, indent=2, sort_keys=True)))
                sys.stdout.write('\n')
        elif args[0].lower() == 'changepass':
            if not mod_acct:
                raise InvalidCommandLineError("Unable to find the specified account.")
            if len(args) == 2:
                sys.stdout.write('Please input the new password.\n')
                tempinput = getpass.getpass()
                self.credentialsvalidation('', '', tempinput, '', True, options)
                args.extend([tempinput])
            if len(args) == 3:
                account = args[1].lower()
                if options.encode:
                    args[2] = Encryption.decode_credentials(args[2])
                self.credentialsvalidation('', '', args[2].split('\r')[0], '', True, options)
                body = {'Password': args[2].split('\r')[0]}

                if path and body:
                    self._rdmc.app.patch_handler(path, body)
                else:
                    raise NoContentsFoundForOperationError('Unable to find the specified account.')
            else:
                raise InvalidCommandLineError('Invalid number of parameters.')

        elif args[0].lower() == 'add':
            args.remove('add')
            if len(args) == 2:
                sys.stdout.write('Please input the account password.\n')
                tempinput = getpass.getpass()

                self.credentialsvalidation('', '', tempinput, '', True, options)
                args.extend([tempinput])

            if not len(args) == 3:
                raise InvalidCommandLineError('Invalid number of parameters.')

            if options.encode:
                args[2] = Encryption.decode_credentials(args[2])

            privs = self.getprivs(options)
            path = self.typepath.defs.accountspath

            body = {"UserName": args[0], "Password": args[2], "Oem": {self.\
                                        typepath.defs.oemhp: {"LoginName": args[1]}}}
            if privs:
                body["Oem"][self.typepath.defs.oemhp].update({"Privileges": privs})
            self.credentialsvalidation(args[0], args[1], args[2], results, True, options)
            if options.serviceacc:
                body["Oem"][self.typepath.defs.oemhp].update({"ServiceAccount": True})
            if options.role:
                if self._rdmc.app.getiloversion() >= 5.140:
                    body["RoleId"] = options.role
                else:
                    raise IncompatibleiLOVersionError("Roles can only be set in iLO 5"\
                                                                                " 1.40 or greater.")
            if path and body:
                self._rdmc.app.post_handler(path, body)
        elif args[0].lower() == 'modify':
            if not mod_acct:
                raise InvalidCommandLineError("Unable to find the specified account.")
            body = {}
            args.remove('modify')

            if not len(args) == 1:
                raise InvalidCommandLineError("Invalid number of parameters.")

            if options.optprivs:
                body.update({'Oem': {self.typepath.defs.oemhp: {'Privileges': {}}}})
                if any(priv for priv in options.optprivs if 'SystemRecoveryConfigPriv' in priv) \
                                                            and 'SystemRecoveryConfigPriv' not in \
                                                                        self.getsesprivs().keys():
                    raise IdTokenError("The currently logged in account must have The System "\
                                         "Recovery Config privilege to add the System Recovery "\
                                         "Config privilege.")
                privs = self.getprivs(options)
                body['Oem'][self.typepath.defs.oemhp]['Privileges'] = privs

            if options.role and self._rdmc.app.getiloversion >= 5.140:
                body["RoleId"] = options.role

            self._rdmc.app.patch_handler(path, body)

        elif args[0].lower() == 'delete':
            if not mod_acct:
                raise InvalidCommandLineError("Unable to find the specified account.")
            self._rdmc.app.delete_handler(path)

        elif 'cert' in args[0].lower():
            certpath = '/redfish/v1/AccountService/UserCertificateMapping/'
            privs = self.getsesprivs()
            if self.typepath.defs.isgen9:
                IncompatibleiLOVersionError("This operation is only available on gen 10 "\
                                                  "and newer machines.")
            elif privs['UserConfigPriv'] == False:
                raise IdTokenError("The currently logged in account must have The User "\
                                     "Config privilege to manage certificates for users.")
            else:
                if args[0].lower() == 'addcert':
                    if not mod_acct:
                        raise InvalidCommandLineError("Unable to find the specified account.")
                    body = {}
                    args.remove('addcert')
                    username = acct['UserName']
                    account = acct['Id']
                    if not len(args) == 2:
                        raise InvalidCommandLineError("Invalid number of parameters.")
                    fingerprintfile = args[1]
                    if os.path.exists(fingerprintfile):
                        with open(fingerprintfile, 'r') as fingerfile:
                            fingerprint = fingerfile.read()
                    else:
                        raise InvalidFileInputError('%s cannot be read.' % fingerprintfile)
                    body = {"Fingerprint": fingerprint, "UserName": username}
                    self._rdmc.app.post_handler(certpath, body)
                
                elif args[0].lower() == 'deletecert':
                    if not mod_acct:
                        raise InvalidCommandLineError("Unable to find the specified account.")
                    args.remove('deletecert')
                    certpath += acct['Id']
                    self._rdmc.app.delete_handler(certpath)

        else:
            raise InvalidCommandLineError('Invalid command.')

        return ReturnCodes.SUCCESS
class InstallSetCommand(RdmcCommandBase):
    """ Main download command class """
    def __init__(self, rdmcObj):
        RdmcCommandBase.__init__(self, \
            name='installset', \
            usage='installset [OPTIONS] \n\n\tRun to perform operations on ' \
            'install sets.\n\n\tList install sets.\n\texample: installset\n\n' \
            '\tAdd install set.\n\texample: installset add installsetfile.json'\
            ' --name=newinstallsetname\n\n\tDelete install set.\n\texample: ' \
            'installset delete --name=installsetname\n\n\tInvoke install ' \
            'set.\n\texample: installset invoke --name=installsetname\n\n\t' \
            'Remove all install sets.\n\texample: installset --removeall\n' \
            '\n\tExample install set json file:\n\t[\n\t\t{\n\t\t\t"Name": ' \
            '"Wait",\n\t\t\t"UpdatableBy": ["RuntimeAgent"],\n\t\t\t'\
            '"Command": "Wait",\n\t\t\t"WaitTimeSeconds": 60\n\t\t},\n\t\t{' \
            '\n\t\t\t"Name": "uniqueName",\n\t\t\t"UpdatableBy": ' \
            '["RuntimeAgent"],\n\t\t\t"Command": "ApplyUpdate",\n\t\t\t"' \
            'Filename": "filename.exe"\n\t\t},\n\t\t{\n\t\t\t"Name": ' \
            '"Reboot",\n\t\t\t"UpdatableBy": ["RuntimeAgent"],\n\t\t\t' \
            '"Command": "ResetServer"\n\t\t}\n\t]',\
            summary='Manages install sets for iLO.',\
            aliases=['Installset'], \
            optparser=OptionParser())
        self.definearguments(self.parser)
        self._rdmc = rdmcObj
        self.typepath = rdmcObj.app.typepath
        self.lobobj = rdmcObj.commands_dict["LoginCommand"](rdmcObj)
        self.logoutobj = rdmcObj.commands_dict["LogoutCommand"](rdmcObj)

    def run(self, line):
        """ Main listcomp 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.installsetvalidation(options)

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

        if args and args[0] in ['delete', 'invoke'] and not options.name:
            raise InvalidCommandLineError('Name option is required for ' \
                                          'delete and invoke commands.')
        if options.name:
            if options.name.startswith('"') and options.name.endswith('"'):
                options.name = options.name[1:-1]
        if options.removeall:
            self.removeinstallsets()
        elif not args:
            self.printinstallsets(options)
        elif args[0].lower() == 'add':
            if not len(args) == 2:
                raise InvalidCommandLineError('add command requires an ' \
                                                            'install set file.')
            else:
                self.addinstallset(args[1], options.name)
        elif args[0].lower() == 'delete':
            self.deleteinstallset(options.name)
        elif args[0].lower() == 'invoke':
            self.invokeinstallset(options)
        else:
            raise InvalidCommandLineError('%s is not a valid command.' %
                                          args[0])

        return ReturnCodes.SUCCESS

    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, excp:
            raise InvalidFileInputError("%s" % excp)

        listtype = self.validatefile(sequences)

        if listtype:
            body = {u"Name": name, u"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 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)
    def run(self, line):
        """ Main raw put 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.putvalidation(options)

        contentsholder = None

        if len(args) == 1:
            try:
                inputfile = open(args[0], 'r')
                contentsholder = json.loads(inputfile.read())
            except Exception as excp:
                raise InvalidFileInputError("%s" % excp)
        elif len(args) > 1:
            raise InvalidCommandLineError("Raw put only takes 1 argument.\n")
        else:
            raise InvalidCommandLineError("Missing raw put file input "\
                                                                "argument.\n")

        if options.headers:
            extraheaders = options.headers.split(',')

            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    raise InvalidCommandLineError("Invalid format for " \
                                                            "--headers option.")

        if "path" in contentsholder and "body" in contentsholder:
            returnresponse = False

            if options.response or options.getheaders:
                returnresponse = True

            results = self._rdmc.app.put_handler(contentsholder["path"], \
                      contentsholder["body"], verbose=self._rdmc.opts.verbose, \
                      sessionid=options.sessionid, url=url, headers=headers, \
                      response=returnresponse, silent=options.silent)
        else:
            raise InvalidFileFormattingError("Input file '%s' was not "\
                                             "formatted properly." % args[0])

        if results and returnresponse:
            if options.getheaders:
                sys.stdout.write(json.dumps(dict(\
                                 results._http_response.getheaders())) + "\n")
    
            if options.response:
                sys.stdout.write(results.text)

        #Return code
        return ReturnCodes.SUCCESS
Ejemplo n.º 22
0
    def preparefwpkg(self, pkgfile):
        """ Prepare fwpkg file for flashing

        :param pkgfile: Location of the .fwpkg file
        :type pkgfile: string.
        :returns: returns the files needed to flash, directory they are located
                                                            in, and type of file.
        :rtype: string, string, string
        """
        files = []
        imagefiles = []
        payloaddata = None
        tempdir = tempfile.mkdtemp()

        try:
            zfile = zipfile.ZipFile(pkgfile)
            zfile.extractall(tempdir)
            zfile.close()
        except Exception as excp:
            raise InvalidFileInputError("Unable to unpack file. " + str(excp))

        files = os.listdir(tempdir)

        if 'payload.json' in files:
            with open(os.path.join(tempdir, 'payload.json'),
                      encoding='utf-8') as pfile:
                data = pfile.read()
            payloaddata = json.loads(data)
        else:
            raise InvalidFileInputError(
                "Unable to find payload.json in fwpkg file.")

        comptype = _get_comp_type(payloaddata)

        if comptype == 'C':
            imagefiles = [
                self.auxcommands['flashfwpkg'].type_c_change(tempdir, pkgfile)
            ]
        else:
            results = self.rdmc.app.getprops(selector="UpdateService.", \
                                                                props=['Oem/Hpe/Capabilities'])

            for device in payloaddata['Devices']['Device']:
                for firmwareimage in device['FirmwareImages']:
                    if firmwareimage['FileName'] not in imagefiles:
                        imagefiles.append(firmwareimage['FileName'])

        if comptype in ['A','B'] and results and 'UpdateFWPKG' in results[0]['Oem']['Hpe']\
                                                                                ['Capabilities']:
            dll = BlobStore2.gethprestchifhandle()
            dll.isFwpkg20.argtypes = [c_char_p, c_int]
            dll.isFwpkg20.restype = c_bool

            with open(pkgfile, 'rb') as fwpkgfile:
                fwpkgdata = fwpkgfile.read()

            fwpkg_buffer = ctypes.create_string_buffer(fwpkgdata)
            if dll.isFwpkg20(fwpkg_buffer, 2048):
                imagefiles = [pkgfile]
                tempdir = ''

        return imagefiles, tempdir, comptype
Ejemplo n.º 23
0
    def run(self, line):
        """ Main load worker function

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

        self.loadvalidation(options)
        returnValue = False

        loadcontent = dict()
        if options.mpfilename:
            sys.stdout.write("Loading configuration for multiple servers...\n")
        else:
            sys.stdout.write("Loading configuration...\n")

        for files in self.filenames:
            if not os.path.isfile(files):
                raise InvalidFileInputError("File '%s' doesn't exist. Please " \
                                "create file by running save command." % files)

            with open(files, "r") as myfile:
                data = myfile.read()

            try:
                loadcontents = json.loads(data)
            except:
                raise InvalidFileFormattingError("Invalid file formatting " \
                                                    "found in file %s" % files)

            if options.mpfilename:
                mfile = options.mpfilename
                outputdir=None

                if options.outdirectory:
                    outputdir=options.outdirectory

                if self.runmpfunc(mpfile=mfile, lfile=files, \
                                                        outputdir=outputdir):
                    return ReturnCodes.SUCCESS
                else:
                    raise MultipleServerConfigError("One or more servers "\
                                        "failed to load given configuration.")

            results = False

            for loadcontent in loadcontents:
                skip = False

                for content, loaddict in loadcontent.iteritems():
                    inputlist = list()

                    if content == "Comments":
                        skip = True
                        break

                    inputlist.append(content)

                    self.selobj.selectfunction(inputlist)
                    if self._rdmc.app.get_selector().lower() not in \
                                                                content.lower():
                        raise InvalidCommandLineError("Selector not found.\n")

                    try:
                        for _, items in loaddict.iteritems():
                            dicttolist = list(items.items())

                            if len(dicttolist) < 1:
                                continue

                            multilevel = [isinstance(x[1], dict) for x in \
                                                                    dicttolist]
                            indices = [i for i, j in enumerate(multilevel) if j]

                            if len(indices) > 0:
                                for index in indices:
                                    changes = []
                                    self.loadmultihelper(dicttolist[index][0], \
                                                 dicttolist[index][1], changes)

                                    for change in changes:
                                        if self._rdmc.app.loadset(dicttolist=\
                                                dicttolist, newargs=change[0], val=change[0]):
                                            results = True

                                indices.sort(cmp=None, key=None, reverse=True)

                                #Test validate thoroughly
                                for index in indices:
                                    del dicttolist[index]

                            if len(dicttolist) < 1:
                                continue

                            try:
                                if self._rdmc.app.loadset(\
                                      dicttolist=dicttolist):
                                    results = True
                            except LoadSkipSettingError:
                                returnValue = True
                                results = True
                                pass
                            except Exception:
                                raise
                    except Exception:
                        raise

                if skip:
                    continue

                try:
                    if results:
                        self.comobj.commitfunction()
                except NoChangesFoundOrMadeError:
                    if returnValue:
                        pass
                    else:
                        raise

            if not results:
                raise NoDifferencesFoundError("No differences found from " \
                                                    "current configuration.")

        #Return code
        if returnValue:
            return ReturnCodes.LOAD_SKIP_SETTING_ERROR
        else:
            return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main raw patch worker function

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

        url = None
        headers = {}
        results = []

        if hasattr(options, 'sessionid') and options.sessionid:
            url = self.sessionvalidation(options)
        else:
            self.patchvalidation(options)

        contentsholder = None
        try:
            with open(options.path, 'r') as _if:
                contentsholder = json.loads(_if.read(),
                                            object_pairs_hook=OrderedDict)
        except IOError:
            raise InvalidFileInputError("File '%s' doesn't exist. " \
                                "Please create file by running 'save' command." % options.path)
        except (ValueError):
            raise InvalidFileFormattingError("Input file '%s' was not " \
                                                            "formatted properly." % options.path)

        if options.headers:
            extraheaders = options.headers.split(',')

            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    raise InvalidCommandLineError(
                        "Invalid format for --headers option.")

        if "path" in contentsholder and "body" in contentsholder:
            results.append(self.rdmc.app.patch_handler(contentsholder["path"], \
                  contentsholder["body"], headers=headers, silent=options.silent, \
                  optionalpassword=options.biospassword, service=options.service))

        elif all([re.match("^\/(\S+\/?)+$", key) for key in contentsholder]):
            for path, body in contentsholder.items():
                results.append(self.rdmc.app.patch_handler(path, \
                        body, headers=headers, silent=options.silent, \
                        optionalpassword=options.biospassword, service=options.service))
        else:
            raise InvalidFileFormattingError("Input file '%s' was not format properly." % \
                                                                                    options.path)

        returnresponse = False

        if options.response or options.getheaders:
            returnresponse = True

        if results and returnresponse:
            for result in results:
                if options.getheaders:
                    self.rdmc.ui.print_out_json(dict(result.getheaders()))

                if options.response:
                    self.rdmc.ui.printer(result.read)
                    self.rdmc.ui.printer("\n")

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS
Ejemplo n.º 25
0
    def run(self, line):
        """ Main fwpkg 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.fwpkgvalidation(options)

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

        if not len(args) == 1:
            raise InvalidCommandLineError("Fwpkg command only takes one argument.")

        if self._rdmc.app.getiloversion() <= 5.120 and args[0].lower().startswith('iegen10'):
            raise IncompatibleiLOVersionError('Please upgrade to iLO 5 1.20 or '\
                       'greater to ensure correct flash of this firmware.')
        tempdir = ''
        if not args[0].endswith('.fwpkg'):
            InvalidFileInputError("Invalid file type. Please make sure the file "\
                                  "provided is a valid .fwpkg file type.")

        try:
            components, tempdir, comptype = self.preparefwpkg(self, args[0])
            if comptype == 'D':
                raise InvalidFileInputError("Unable to flash this fwpkg file.")
            elif comptype == 'C':
                try:
                    self.taskqueuecheck()
                except TaskQueueError as excp:
                    if options.ignore:
                        sys.stderr.write(str(excp)+'\n')
                    else:
                        raise excp
            self.applyfwpkg(options, tempdir, components, comptype)

            if comptype == 'A':
                message = "Firmware has successfully been flashed.\n"
                if 'ilo' in args[0].lower():
                    message += "iLO will reboot to complete flashing. Session will be"\
                                " terminated.\n"
            elif comptype == 'B':
                message = "Firmware has successfully been flashed and a reboot is required for "\
                                                                "this firmware to take effect.\n"
            elif comptype == 'C':
                message = "This firmware is set to flash on reboot.\n"
            sys.stdout.write(message)
        finally:
            if tempdir:
                shutil.rmtree(tempdir)
            if 'ilo' in args[0].lower():
                self.logoutobj.run("")
        return ReturnCodes.SUCCESS
Ejemplo n.º 26
0
    def run(self, line):
        """ Main fwpkg 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.fwpkgvalidation(options)

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

        if not len(args) == 1:
            raise InvalidCommandLineError(
                "Fwpkg command only takes one argument.")

        if self._rdmc.app.getiloversion() <= 5.120 and args[0].lower(
        ).startswith('iegen10'):
            raise IncompatibleiLOVersionError('Please upgrade to iLO 5 1.20 or '\
                       'greater to ensure correct flash of this firmware.')
        tempdir = ''
        if not args[0].endswith('.fwpkg'):
            InvalidFileInputError("Invalid file type. Please make sure the file "\
                                  "provided is a valid .fwpkg file type.")
        try:
            self.taskqueuecheck()
        except TaskQueueError as excp:
            if options.ignore:
                sys.stderr.write(str(excp) + '\n')
            else:
                raise excp
        try:
            components, tempdir, comptype = self.preparefwpkg(self, args[0])
            if comptype == 'D':
                raise InvalidFileInputError("Unable to flash this fwpkg file.")
            self.applyfwpkg(options, tempdir, components)

            if comptype == 'A':
                message = "Firmware will flash and does not require a reboot.\n"
            elif comptype == 'B':
                message = "A reboot is required for this firmware to take effect.\n"\
                            "In order to properly take effect firmware must complete flashing "\
                            "before a reboot is applied. Please use iLOrest command: "\
                            "taskqueue to monitor flashing process.\n"
            elif comptype == 'C':
                message = "This firmware will flash on reboot.\n"
            sys.stdout.write(message)
        finally:
            if tempdir:
                shutil.rmtree(tempdir)

        return ReturnCodes.SUCCESS
    def run(self, line):
        """ Main raw patch worker function

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

        headers = {}
        results = None

        self.postvalidation(options)

        contentsholder = None

        if len(args) == 1:
            try:
                inputfile = open(args[0], 'r')
                contentsholder = json.loads(inputfile.read())
            except Exception as excp:
                raise InvalidFileInputError("%s" % excp)
        elif len(args) > 1:
            raise InvalidCommandLineError("Raw post only takes 1 argument.\n")
        else:
            raise InvalidCommandLineError(
                "Missing raw post file input argument.\n")
        if options.encode:
            if "body" in contentsholder and "UserName" in contentsholder["body"] and \
                        "Password" in contentsholder["body"] and \
                        len(list(contentsholder["body"].keys())) == 2:
                encobj = Encryption()
                contentsholder["body"]["UserName"] = encobj.decode_credentials(\
                                            contentsholder["body"]["UserName"])
                contentsholder["body"]["Password"] = encobj.decode_credentials(\
                                            contentsholder["body"]["Password"])

        if options.headers:
            extraheaders = options.headers.split(',')
            for item in extraheaders:
                header = item.split(':')

                try:
                    headers[header[0]] = header[1]
                except:
                    raise InvalidCommandLineError(
                        "Invalid format for --headers option.")

        if "path" in contentsholder and "body" in contentsholder:
            returnresponse = False

            if options.response or options.getheaders:
                returnresponse = True

            results = self._rdmc.app.post_handler(contentsholder["path"], \
                  contentsholder["body"], headers=headers, \
                  response=returnresponse, silent=options.silent, service=options.service)
        else:
            raise InvalidFileFormattingError("Input file '%s' was not "\
                                             "formatted properly." % args[0])

        if results and returnresponse:
            if options.getheaders:
                sys.stdout.write(json.dumps(dict(results.getheaders())) + "\n")

            if options.response:
                sys.stdout.write(results.ori + "\n")

        #Return code
        return ReturnCodes.SUCCESS
Ejemplo n.º 28
0
    def run(self, line):
        """ Main load worker function

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

        self.loadvalidation(options)
        returnvalue = False

        loadcontent = dict()

        if options.mpfilename:
            sys.stdout.write("Loading configuration for multiple servers...\n")
        else:
            sys.stdout.write("Loading configuration...\n")

        for files in self.filenames:
            if not os.path.isfile(files):
                raise InvalidFileInputError("File '%s' doesn't exist. Please " \
                                "create file by running save command." % files)
            if options.encryption:
                with open(files, "rb") as myfile:
                    data = myfile.read()
                    data = Encryption().decrypt_file(data, \
                                                        options.encryption)
            else:
                with open(files, "r") as myfile:
                    data = myfile.read()

            try:
                loadcontents = json.loads(data)
            except:
                raise InvalidFileFormattingError("Invalid file formatting " \
                                                    "found in file %s" % files)

            if options.mpfilename:
                mfile = options.mpfilename
                outputdir = None

                if options.outdirectory:
                    outputdir = options.outdirectory

                if self.runmpfunc(mpfile=mfile, lfile=files, \
                                                        outputdir=outputdir):
                    return ReturnCodes.SUCCESS
                else:
                    raise MultipleServerConfigError("One or more servers "\
                                        "failed to load given configuration.")

            results = False
            validation_errs = []

            for loadcontent in loadcontents:
                for content, loaddict in loadcontent.items():
                    inputlist = list()

                    if content == "Comments":
                        continue

                    inputlist.append(content)
                    if options.biospassword:
                        inputlist.extend(["--biospassword", options.biospassword])

                    self.selobj.selectfunction(inputlist)
                    if self._rdmc.app.get_selector().lower() not in content.lower():
                        raise InvalidCommandLineError("Selector not found.\n")

                    try:
                        for _, items in loaddict.items():
                            try:
                                if self._rdmc.app.loadset(seldict=items, \
                                      latestschema=options.latestschema, \
                                      uniqueoverride=options.uniqueoverride):
                                    results = True
                            except LoadSkipSettingError as excp:
                                returnvalue = True
                                results = True
                            except:
                                raise
                    except redfish.ris.ValidationError as excp:
                        errs = excp.get_errors()
                        validation_errs.append({self._rdmc.app.get_selector(): errs})
                    except:
                        raise

            try:
                if results:
                    self.comobj.commitfunction(options=options)
            except NoChangesFoundOrMadeError as excp:
                if returnvalue:
                    pass
                else:
                    raise excp

            if validation_errs:
                for validation_err in validation_errs:
                    for err_type in validation_err:
                        sys.stderr.write("Validation error(s) in type %s:\n" % err_type)
                        for err in validation_err[err_type]:
                            if isinstance(err, redfish.ris.RegistryValidationError):
                                sys.stderr.write(err.message)
                                sys.stderr.write('\n')

                                try:
                                    if err.reg:
                                        err.reg.print_help(str(err.sel))
                                        sys.stderr.write('\n')
                                except:
                                    pass
                raise redfish.ris.ValidationError(excp)

            if not results:
                raise NoDifferencesFoundError("No differences found from current configuration.")

        #Return code
        if returnvalue:
            return ReturnCodes.LOAD_SKIP_SETTING_ERROR

        return ReturnCodes.SUCCESS
Ejemplo n.º 29
0
    def run(self, line):
        """ Main fwpkg worker function

        :param line: string of arguments passed in
        :type line: str.
        """
        try:
            (options, _) = 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 self.rdmc.app.typepath.url:
            if 'http' not in self.rdmc.app.typepath.url:
                options.logout = True
                self.cmdbase.logout_routine(self, options)
        else:
            options.logout = True
            self.cmdbase.logout_routine(self, options)
        self.fwpkgvalidation(options)

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

        if self.rdmc.app.getiloversion() <= 5.120 and options.fwpkg.lower(
        ).startswith('iegen10'):
            raise IncompatibleiLOVersionError('Please upgrade to iLO 5 1.20 or '\
                       'greater to ensure correct flash of this firmware.')
        tempdir = ''
        if not options.fwpkg.endswith('.fwpkg'):
            InvalidFileInputError("Invalid file type. Please make sure the file "\
                                  "provided is a valid .fwpkg file type.")

        try:
            components, tempdir, comptype = self.preparefwpkg(
                self, options.fwpkg)
            if comptype == 'D':
                raise InvalidFileInputError("Unable to flash this fwpkg file.")
            elif comptype == 'C':
                try:
                    self.taskqueuecheck()
                except TaskQueueError as excp:
                    if options.ignore:
                        self.rdmc.ui.warn(str(excp) + '\n')
                    else:
                        raise excp
            self.applyfwpkg(options, tempdir, components, comptype)

            if comptype == 'A':
                message = "Firmware has successfully been flashed.\n"
                if 'ilo' in options.fwpkg.lower():
                    message += "iLO will reboot to complete flashing. Session will be"\
                                " terminated.\n"
            elif comptype == 'B':
                message = "Firmware has successfully been flashed and a reboot is required for "\
                                                                "this firmware to take effect.\n"
            elif comptype == 'C':
                message = "This firmware is set to flash on reboot.\n"
            self.rdmc.ui.printer(message)

        except (FirmwareUpdateError, UploadError) as excp:
            raise excp

        finally:
            if tempdir:
                shutil.rmtree(tempdir)

        self.cmdbase.logout_routine(self, options)
        #Return code
        return ReturnCodes.SUCCESS