Ejemplo n.º 1
0
def CollectInventory(arglist):
    parser = ArgumentParser(description='Inventory Collector')
    parser.add_argument('-u', '--user', 
        action="store", dest="user", type=str, nargs='?',
        default='root', help="Username to use for iDRAC")
    parser.add_argument('-p', '--password', 
        action="store", dest="password", type=str,
        default='calvin', help="Password to use for iDRAC")
    parser.add_argument('-i', '--ipaddress',
        action="store", dest="idrac_ip", nargs='+',
        help="ipaddress of iDRAC")
    parser.add_argument('-f', '--folder', 
        action="store", dest="folder", type=str,
        help="folder from where inventory is serialized")

    options = parser.parse_args(arglist)

    if options.password is None:
        print("password must be provided")
        return -1
    if options.user is None:
        print("user must be provided")
        return -1
    if options.folder is None:
        print("Folder must be provided")
        return -1
    if options.idrac_ip is None or len(options.idrac_ip) <= 0:
        print("iDRAC ip addresses must be provided")
        return -1


    updshare = LocalFile(local = options.folder, isFolder=True)
    if not updshare.IsValid:
        print("Folder is not writable!")
        return -2

    print("Configuring Update Share...")
    UpdateManager.configure(updshare)

    sd = sdkinfra()
    sd.importPath()
    creds = UserCredentials(options.user, options.password)
    for ipaddr in options.idrac_ip:
        try:
            print("Connecting to " + ipaddr + " ... ")
            idrac = sd.get_driver(sd.driver_enum.iDRAC, ipaddr, creds)
            if idrac:
                print("    ... saving firmware!")
                UpdateHelper.save_firmware_inventory(idrac)
                idrac.disconnect()
            else:
                print("    failed to connect to iDRAC")
        except Exception as ex:
            print(str(ex))
Ejemplo n.º 2
0
 def save_firmware_inventory(devices):
     if not isinstance(devices,list):
         devices = [devices]
     if not UpdateManager.get_instance():
         return { 'Status' : 'Failed',
                  'Message' : 'Update Manager is not initialized' }
     myshare = UpdateManager.get_instance().getInventoryShare()
     mydevinv = myshare.new_file('%ip_firmware.json')
     for device in devices:
         device.update_mgr.serialize_inventory(mydevinv)
     return { 'Status' : 'Success' }
Ejemplo n.º 3
0
    def build_repo(catalog, scoped, *components):
        updmgr = UpdateManager.get_instance()
        if not updmgr:
            return {
                'Status': 'Failed',
                'Message': 'Update Manager is not initialized'
            }
        myshare = updmgr.getInventoryShare()
        (catshare, catscope) = updmgr.getCatalogScoper(catalog)
        fwfiles_path = os.path.join(myshare.local_full_path, '*_firmware.json')
        for fname in glob.glob(fwfiles_path):
            fwinventory = None
            with open(fname) as firmware_data:
                fwinventory = json.load(firmware_data)
            if not fwinventory:
                logger.debug(' no data found in ' + fname)
                continue
            flist = []
            for comp in components:
                if comp in fwinventory['ComponentMap']:
                    flist.extend(fwinventory['ComponentMap'][comp])

            swidentity = fwinventory
            if not scoped: swidentity = None
            catscope.add_to_scope(fwinventory['Model_Hex'], swidentity, *flist)

        catscope.save()
        return {'Status': 'Success'}
Ejemplo n.º 4
0
def sw_inventory(idrac, module):
    """
    Get Firmware Inventory

    Keyword arguments:
    idrac  -- iDRAC handle
    module -- Ansible module
    """

    msg = {}
    msg['changed'] = False
    msg['failed'] = False
    msg['msg'] = {}
    error = False

    try:
        if module.params['choice'] == "all":
            msg['msg'] = idrac.update_mgr.get_swidentity()
        elif module.params['choice'] == "installed":
            msg['msg'] = idrac.update_mgr.InstalledFirmware

        if module.params['serialize']:
            fw_inv_path = LocalFile(local=module.params['share_mnt'],
                                    isFolder=True)

            if fw_inv_path.IsValid:
                UpdateManager.configure(fw_inv_path)
                msg['msg'] = UpdateHelper.save_firmware_inventory(idrac)

                if "Status" in msg['msg'] and msg['msg']['Status'] != "Success":
                    msg['failed'] = True
            else:
                msg['msg'] = "Error: Network share is not valid"
                msg['failed'] = True

    except Exception as err:
        error = True
        msg['msg'] = "Error: %s" % str(err)
        msg['exception'] = traceback.format_exc()
        msg['failed'] = True

    return msg, error
Ejemplo n.º 5
0
 def update_from_repo(self,
                      catalog_path,
                      apply_update=True,
                      reboot_needed=False,
                      job_wait=True):
     if isinstance(catalog_path, str):
         # Catalog name
         updmgr = UpdateManager.get_instance()
         if not updmgr: return {}
         (cache_share, ignore) = updmgr.getCatalogScoper(catalog_path)
     else:
         # DRM Repo
         cache_share = catalog_path
     catalog_dir = FileOnShare(remote=cache_share.remote_folder_path,
                               isFolder=True,
                               creds=cache_share.creds)
     catalog_file = cache_share.remote_file_name
     if self.entity.use_redfish:
         if isinstance(catalog_path,
                       FileOnShare) and catalog_path.mount_point is None:
             raise ValueError("Share path or mount point does not exist")
         rjson = self.entity._update_from_repo_using_redfish(
             ipaddress=catalog_dir.remote_ipaddr,
             share_name=catalog_dir.remote.share_name,
             share_type=IFRShareTypeEnum[
                 catalog_dir.remote_share_type.name.lower()],
             username=catalog_dir.creds.username,
             password=catalog_dir.creds.password,
             reboot_needed=reboot_needed,
             catalog_file=catalog_file,
             apply_update=ApplyUpdateEnum[str(apply_update)],
             ignore_cert_warning=IgnoreCertWarnEnum['On'])
     if TypeHelper.resolve(
             catalog_dir.remote_share_type) == TypeHelper.resolve(
                 ShareTypeEnum.NFS):
         rjson = self.entity._update_repo_nfs(
             share=catalog_dir,
             creds=catalog_dir.creds,
             catalog=catalog_file,
             apply=URLApplyUpdateEnum[str(apply_update)].value,
             reboot=RebootEnum[str(reboot_needed)].value)
     else:
         rjson = self.entity._update_repo(
             share=catalog_dir,
             creds=catalog_dir.creds,
             catalog=catalog_file,
             apply=URLApplyUpdateEnum[str(apply_update)].value,
             reboot=RebootEnum[str(reboot_needed)].value)
     rjson['file'] = str(cache_share)
     if job_wait:
         rjson = self._job_mgr._job_wait(rjson['file'], rjson)
     if not self.entity.use_redfish:
         rjson['job_details'] = self.entity._update_get_repolist()
     return rjson
Ejemplo n.º 6
0
    def update_from_repo(self,
                         catalog_path,
                         apply_update=True,
                         reboot_needed=False,
                         job_wait=True):
        appUpdateLookup = {True: 1, False: 0}
        rebootLookup = {True: "TRUE", False: "FALSE"}
        appUpdate = appUpdateLookup[apply_update]
        rebootNeeded = rebootLookup[reboot_needed]

        if isinstance(catalog_path, str):
            # Catalog name
            updmgr = UpdateManager.get_instance()
            if not updmgr: return {}
            (cache_share, ignore) = updmgr.getCatalogScoper(catalog_path)
        else:
            # DRM Repo
            cache_share = catalog_path
        catalog_dir = FileOnShare(remote=cache_share.remote_folder_path,
                                  isFolder=True,
                                  creds=cache_share.creds)
        catalog_file = cache_share.remote_file_name

        if self.entity.use_redfish:
            if isinstance(catalog_path,
                          FileOnShare) and catalog_path.mount_point is None:
                logger.error("Share path or mount point does not exist")
                raise ValueError("Share path or mount point does not exist")
            return self.update_from_repo_usingscp_redfish(
                catalog_dir,
                catalog_file,
                mount_point=catalog_path.mount_point.full_path,
                reboot_needed=reboot_needed,
                job_wait=job_wait)

        if TypeHelper.resolve(
                catalog_dir.remote_share_type) == TypeHelper.resolve(
                    ShareTypeEnum.NFS):
            rjson = self.entity._update_repo_nfs(share=catalog_dir,
                                                 catalog=catalog_file,
                                                 apply=appUpdate,
                                                 reboot=rebootNeeded)
        else:
            rjson = self.entity._update_repo(share=catalog_dir,
                                             creds=catalog_dir.creds,
                                             catalog=catalog_file,
                                             apply=appUpdate,
                                             reboot=rebootNeeded)

        rjson['file'] = str(cache_share)
        if job_wait:
            rjson = self._job_mgr._job_wait(rjson['file'], rjson)
        return rjson
Ejemplo n.º 7
0
    def get_firmware_inventory():
        updmgr = UpdateManager.get_instance()
        if not updmgr:
            return { 'Status' : 'Failed',
                     'Message' : 'Update Manager is not initialized' }
        myshare = updmgr.getInventoryShare()
        fwfiles_path = os.path.join(myshare.local_full_path, '*_firmware.json')
        device_fw = {}
        for fname in glob.glob(fwfiles_path):
            fwinventory = None
            with open(fname) as firmware_data:
                fwinventory = json.load(firmware_data)
            if not fwinventory:
                logger.debug(' no data found in '+ fname)
                continue
            device_fw[fwinventory['ServiceTag']] = fwinventory

        return { 'Status' : 'Success', 'retval' : device_fw }
Ejemplo n.º 8
0
    def get_updates_matching(self, catalog='Catalog', criteria=None):
        updmgr = UpdateManager.get_instance()
        if not updmgr:
            updates = RepoComparator(self.InstalledFirmware).final()
        else:
            (ignore, cache_cat) = updmgr.getCatalogScoper(catalog)
            updates = cache_cat.compare(self.entity.SystemIDInHex,
                                        self.InstalledFirmware)
        if not criteria:
            return updates

        retval = {}
        for comp in updates:
            for update in updates[comp]:
                if not criteria.meets(update):
                    continue
                if comp not in retval:
                    retval[comp] = []
                retval[comp].append(update)
        return retval
Ejemplo n.º 9
0
    def update_from_repo(self, catalog_path, apply_update = True, reboot_needed = False, job_wait = True):
        appUpdateLookup = { True : 1, False : 0 }
        rebootLookup = { True : "TRUE", False : "FALSE" }
        appUpdate = appUpdateLookup[apply_update]
        rebootNeeded = rebootLookup[reboot_needed]

        if isinstance(catalog_path, str):
            # Catalog name 
            updmgr = UpdateManager.get_instance()
            if not updmgr: return {}
            (cache_share, ignore) = updmgr.getCatalogScoper(catalog_path)
        else:
            # DRM Repo
            cache_share = catalog_path
        catalog_dir = FileOnShare(remote=cache_share.remote_folder_path,
                                  isFolder=True, creds=cache_share.creds)
        catalog_file = cache_share.remote_file_name
        rjson = self.entity._update_repo(share = catalog_dir,
                  creds = catalog_dir.creds, catalog = catalog_file,
                  apply = appUpdate, reboot = rebootNeeded)
        rjson['file'] = str(cache_share)
        if job_wait:
            rjson = self._job_mgr._job_wait(rjson['file'], rjson)
        return rjson
Ejemplo n.º 10
0
def CompareInventory(arglist):
    parser = ArgumentParser(description='Compare Inventory')
    # parser.add_argument('-u', '--user',
    #    action="store", dest="user", type=str, nargs='?',
    #    default='tempuser', help="Username to use for iDRAC")
    # parser.add_argument('-p', '--password',
    #    action="store", dest="password", type=str,
    #    default='temppwd', help="Password to use for iDRAC")
    # parser.add_argument('-i', '--ipaddress',
    #    action="store", dest="idrac_ip", nargs='+',
    #    help="ipaddress of iDRAC")
    parser.add_argument('-f',
                        '--folder',
                        action="store",
                        dest="folder",
                        type=str,
                        help="folder from where inventory is serialized")
    parser.add_argument('-C',
                        '--catalog',
                        action="store",
                        dest="catalog",
                        type=str,
                        nargs='?',
                        default='Catalog',
                        help="Catalog to load")

    parser.add_argument('-o',
                        '--output',
                        action="store",
                        dest="output",
                        type=str,
                        nargs='?',
                        default='csv',
                        help="Catalog to load")

    options = parser.parse_args(arglist)

    # if options.password is None:
    #    print("password must be provided")
    #    return -1
    # if options.user is None:
    #    print("user must be provided")
    #    return -1
    # if options.idrac_ip is None or len(options.idrac_ip) <= 0:
    #    print("iDRAC ip addresses must be provided")
    #    return -1
    if options.folder is None:
        print("Folder must be provided")
        return -1
    if options.catalog is None:
        options.catalog = 'Catalog'
    if options.output is None:
        options.output = 'csv'

    updshare = LocalFile(local=options.folder, isFolder=True)
    if not updshare.IsValid:
        print("Folder is not writable!")
        return -2

    UpdateManager.configure(updshare)
    rjson = UpdateHelper.get_firmware_inventory()
    dev_fw = {}
    if rjson['Status'] == 'Success':
        dev_fw = rjson['retval']

    updmgr = UpdateManager.get_instance()
    (ignore, cache_cat) = updmgr.getCatalogScoper(options.catalog)
    devcompare = {}
    for dev in dev_fw:
        swidentity = dev_fw[dev]
        devcompare[dev] = cache_cat.compare(swidentity['Model_Hex'],
                                            swidentity)
        print('{0},{1},{2},{3},{4},{5},{6},"{7}"'.format(
            'Device', 'Component', 'UpdateNeeded', 'UpdatePackage',
            'UpdateType', 'Server.Version', 'Catalog.Version',
            'Reboot Required'))
        for fqdd in devcompare[dev]:
            for fw in devcompare[dev][fqdd]:
                print('{0},"{1}",{2},{3},{4},"{5}","{6}",{7}'.format(
                    str(dev), str(fw.get('ElementName')),
                    str(TypeHelper.resolve(fw.get('UpdateNeeded'))),
                    str(TypeHelper.resolve(fw.get('UpdatePackage'))),
                    str(TypeHelper.resolve(fw.get('UpdateType'))),
                    str(fw.get('Server.Version')),
                    str(fw.get('Catalog.Version', 'Not Available')),
                    str(fw.get('Catalog.rebootRequired', ''))))
Ejemplo n.º 11
0
def RepoBuilder(arglist):
    parser = ArgumentParser(description='Local Repository Builder')
    parser.add_argument(
        '-C',
        '--catalog',
        action="store",
        dest="catalog",
        nargs='?',
        default='Catalog',
        type=str,
        help="Name of the Catalog file that contains the info about needed DUPs"
    )
    parser.add_argument('-f',
                        '--folder',
                        action="store",
                        dest="folder",
                        type=str,
                        help="folder from where repository is built")
    parser.add_argument('-c',
                        '--components',
                        action="store",
                        dest="component",
                        nargs='+',
                        help="components for which the DUPs are requested.")
    parser.add_argument('-s',
                        '--site',
                        action="store",
                        dest="site",
                        type=str,
                        nargs='?',
                        default='downloads.dell.com',
                        help="models for which the DUPs are requested.")
    parser.add_argument('-p',
                        '--protocol',
                        action="store",
                        dest="protocol",
                        nargs='?',
                        default='HTTP',
                        choices=['HTTP', 'FTP', 'NoOp', 'HashCheck'],
                        help="models for which the DUPs are requested.")
    parser.add_argument('-v',
                        '--verbose',
                        action="store_true",
                        help="verbose mode")
    parser.add_argument('-D',
                        '--download-dups',
                        action="store_true",
                        dest="dld_dups",
                        help="download DUPs")
    parser.add_argument('-l',
                        '--download-catalog',
                        action="store_true",
                        dest="dld_catalog",
                        help="download catalog")
    parser.add_argument('-b',
                        '--build-catalog',
                        action="store_true",
                        dest="build_catalog",
                        help="build catalog")
    parser.add_argument('-i',
                        '--download-index',
                        action="store_true",
                        dest="dld_index",
                        help="build index")

    options = parser.parse_args(arglist)
    if not options.component:
        options.component = []

    if options.folder is None:
        print("Folder must be provided")
        return -1

    if options.verbose is None:
        options.verbose = False

    if options.verbose:
        logging.basicConfig(level=logging.DEBUG)

    if not options.dld_dups and not options.build_catalog and \
       not options.dld_catalog:
        options.dld_catalog = True
        options.build_catalog = True
        options.dld_dups = True

    options.protocol = TypeHelper.convert_to_enum(options.protocol,
                                                  DownloadProtocolEnum)

    updshare = LocalFile(local=options.folder, isFolder=True)
    if not updshare.IsValid:
        print("Folder is not writable!")
        return -2

    if options.protocol != DownloadProtocolEnum.HashCheck:
        print("Configuring Update Share...")
    UpdateManager.configure(updshare,
                            site=options.site,
                            protocol=options.protocol)

    if options.dld_catalog:
        if options.protocol != DownloadProtocolEnum.HashCheck:
            print("Updating Catalog from downloads.dell.com...")
        UpdateManager.update_catalog()
    if options.build_catalog:
        if options.protocol != DownloadProtocolEnum.HashCheck:
            print("Building Repository Catalog ....")
            UpdateHelper.build_repo(options.catalog, True, *options.component)
    if options.dld_index:
        if options.protocol != DownloadProtocolEnum.HashCheck:
            print("Updating index from downloads.dell.com...")
        UpdateManager.update_index()

    if options.dld_dups:
        if options.protocol != DownloadProtocolEnum.HashCheck:
            print("Downloading DUPs ...")
        UpdateManager.update_cache(options.catalog)
Ejemplo n.º 12
0
ipaddr = get_args(argsinfo, 'ipaddr')
driver = get_optional(argsinfo, 'driver')
uname = get_optional(argsinfo, 'user.name')
upass = get_optional(argsinfo, 'user.password', '')
pref = get_optional(argsinfo, 'protocol', 'WSMAN')
nshare = get_optional(argsinfo, 'share')
nsharename = get_optional(argsinfo, 'share.user.name')
nsharepass = get_optional(argsinfo, 'share.user.password', '')
creds = UserCredentials(uname, upass)

@property
def not_implemented():
    print("===== not implemented ====")


myshare = LocalFile(local='C:\\Users\\vaideeswaran_ganesan\\Work\\omsdk', isFolder=True)
updshare = myshare.makedirs('DD')

UpdateManager.configure(updshare)
if updshare.IsValid:
    sd = sdkinfra()
    sd.importPath()
    idrac = sd.get_driver(sd.driver_enum.iDRAC, ipaddr, creds)
    UpdateHelper.save_firmware_inventory(idrac)
    idrac.disconnect()

    UpdateManager.update_catalog()
    print("Building repo....")
    UpdateHelper.build_repo_catalog('NIC')
Ejemplo n.º 13
0
    myshare = FileOnShare(remote=nshare,
                          mount_point='Z:\\',
                          isFolder=True,
                          common_path='',
                          creds=UserCredentials(nsharename, nsharepass))
    updshare = myshare
else:
    myshare = FileOnShare(remote=nshare,
                          mount_point='/tst',
                          isFolder=True,
                          creds=UserCredentials(nsharename, nsharepass))

sd = sdkinfra()
sd.importPath()

UpdateManager.configure(updshare)
#updshare.IsValid
#print(UpdateManager.update_catalog())
#idrac = sd.get_driver(sd.driver_enum.iDRAC, ipaddr, creds, protopref)
#UpdateManager.add_devices(idrac)
#UpdateManager.update_cache()

t1 = time.time()

RunNow = True
ToTest = False
Passed = False
Failed = False

if True:
    dprint("Driver SDK", "1.03 Connect to " + ipaddr)