class Applications(object):
    def __init__(self, user, password):
        self.logger = Logger()
        self.xml_parser = xml_parser.XmlParser()
        self.user = user
        self.password = password
        return

    def get_apps(self):
        apps = []
        try:
            self.logger.info('Attempting to get applications!!!')
            resp = requests.post(endpoints.REQUEST_APPS,
                                 auth=HTTPBasicAuth(self.user, self.password))
            if resp.status_code == 200:
                response = self.xml_parser.parse_xml(resp.text)
                for item in response:
                    if item.attrib['app_id'] is not None and not item.attrib[
                            'app_id'] in apps:
                        apps.append({
                            'app_id': item.attrib['app_id'],
                            'app_name': item.attrib['app_name'],
                            'sandboxes': []
                        })
                self.logger.info('Successfully retrieved app list!')
            else:
                self.logger.error('Authentication Issue: {}'.format(
                    resp.status_code))
        except Exception as e:
            self.logger.exception('Error retrieving app list: {}'.format(e))
        return apps
Esempio n. 2
0
def OnlyCleanupOldNar(log, array, user, password, scope, options):
    onlycleannarfiles_logger = Logger(log, logging.DEBUG, logging.INFO)
    onlycleannarfiles_logger.debug('Staring def_OnlyCleanupOldNar module.')

    for x in xrange(len(array)):
        cli = NaviCLI(log, array[x], user[x], passwd[x], scope[x])
        var_array = array[x]
        var_user = user[x]
        var_passwd = passwd[x]
        var_scope = scope[x]

        onlycleannarfiles_logger.info(
            '************************************************')
        onlycleannarfiles_logger.info('Getting Serial Number for ' +
                                      var_array + ' ....')
        ##        SerialNo,SNerror = def_GetSerialNumber(var_array,var_user,var_passwd,var_scope)
        SerialNo, SNerror = cli._GetSerialNumber()

        if SNerror != '0':
            onlycleannarfiles_logger.info(SerialNo)
        else:
            ##            l,narstring,oldnar,ol = def_GetNARList2(SerialNo,var_array,var_user,var_passwd,var_scope)
            l, narstring, oldnar, ol = cli._GetNARList2(
                SerialNo, options['--nnf'])
            onlycleannarfiles_logger.info(
                '**** Cleaning Up ' + str(ol) +
                ' NAR/NAZ files, older than 7 days, from ' + SerialNo +
                ' ****')
            ##            def_CleanupOldNar(var_array,var_user,var_passwd,var_scope,oldnar)
            cli._CleanupOldNar(oldnar)
Esempio n. 3
0
def ScriptGet(log,array,user,passwd,scope,options):
    scriptget_logger = Logger(log,logging.DEBUG,logging.INFO)
    scriptget_logger.debug('Starting def_ScriptGet module.')
    timenow =  datetime.datetime.now().hour + datetime.datetime.now().minute + datetime.datetime.now().second + datetime.datetime.now().microsecond

    for x in xrange(len(array)):
        cli = NaviCLI(log,array[x],user[x],passwd[x],scope[x])
        var_array = array[x]
        var_user=user[x]
        var_passwd = passwd[x]
        var_scope = scope[x]
        bool_32plus = False

        scriptget_logger.info('************************************************')
        scriptget_logger.info('Getting Serial Number for ' + var_array + ' ....')
        SerialNo, SNerror = cli._GetSerialNumber()
        if SNerror != '0':
            scriptget_logger.critical(SerialNo)
        else:
            scriptget_logger.info('Getting OE Version for ' + var_array + ' ....')
            Version, Verror = cli._GetVersion()
            scriptget_logger.info('     Running OE Version ' + Version)
            if '7.32.' in Version:
                bool_32plus = True
            if '7.33.' in Version:
                bool_32plus = True
            outPath = ''.join([var_cwd,'\\',SerialNo])

            if not os.path.exists(outPath):
                scriptget_logger.info('Creating Local Directory ' + outPath + ' ....')
                os.makedirs(outPath)
                if bool_32plus == True:
                    skew_outpath = outPath+'_SkewData'
                    scriptget_logger.info('Creating Directory for Skew Data ' + skew_outpath + ' ....')
                    os.makedirs(skew_outpath)
            else:

                if os.path.isdir(outPath):
                    scriptget_logger.info('Found Existing Folder: ' + outPath)
                    outPath = outPath +'_'+str(date.today())+'_'+str(timenow)

                    if not os.path.exists(outPath):
                        scriptget_logger.info('Creating Local Directory ' + outPath + ' ....')
                        os.makedirs(outPath)
                        if bool_32plus == True:
                            skew_outpath = outPath+'_SkewData'
                            scriptget_logger.info('Creating Directory for Skew Data ' + skew_outpath + ' ....')
                            os.makedirs(skew_outpath)
            scriptget_logger.info('Using ' + outPath + ' to save files for ' + SerialNo)
            scriptget_logger.info('Retrieving SPcollect for '+SerialNo +' ....')

            SPColStat = cli._GetSPCollectList(outPath)
            scriptget_logger.debug(SPColStat)

            l,narstring,oldnar,ol = cli._GetNARList2(SerialNo,options['--nnf'])
            scriptget_logger.info('Retrieving ' + str(l) + ' NAR/NAZ files from ' + SerialNo + ' ....')
            stat = cli._GetNarFiles(narstring,outPath)
            scriptget_logger.info(stat)
            if bool_32plus == True:
                scriptget_logger.info('Retrieving skew files from ' + SerialNo + ' ....')
                stat = cli._GetArrayconfigXML(skew_outpath)
                scriptget_logger.debug(stat)
                stat = cli._GetFASTData(skew_outpath)
                scriptget_logger.debug(stat)
                os.chdir(var_cwd)
            scriptget_logger.info('**** File Retrieval Complete for ' + SerialNo + ' ****')
            scriptget_logger.info('**** Creating zip of Data for ' + SerialNo + ' ****')
            shutil.make_archive(outPath, 'zip', outPath)
            if bool_32plus == True:
                shutil.make_archive(skew_outpath, 'zip', skew_outpath)
            scriptget_logger.info('**** Cleaning Up Local Directory ****')
            shutil.rmtree(outPath, ignore_errors=True)
            if bool_32plus == True:
                shutil.rmtree(skew_outpath, ignore_errors=True)
            if options['--c'] == True:
                scriptget_logger.info('**** Cleaning Up '+str(ol)+' NAR/NAZ files from '+SerialNo+' ****')
                cleanupstat = cli._CleanupOldNar(oldnar)
                scriptget_logger.debug(cleanupstat)

    scriptget_logger.debug('Exiting def_ScriptGet module.')
    scriptget_logger.debug('Script is finished retrieving files.')
Esempio n. 4
0
def ScriptSet(log,array,user,passwd,scope,options):

    scriptset_logger = Logger(log,logging.DEBUG,logging.INFO)
    scriptset_logger.debug('Starting ScriptSet module.')

    for x in xrange(len(array)):
        cli = NaviCLI(log,array[x],user[x],passwd[x],scope[x])
        var_array = array[x]
        var_user=user[x]
        var_passwd = passwd[x]
        var_scope = scope[x]
        bol_Analyzer = True
        mod = 0
        scriptset_logger.info('************************************************')
        scriptset_logger.info('Getting Current Settings for '+var_array+' :')
        SerialNo,SNerrcode = cli._GetSerialNumber()
        if SNerrcode != '0':
            scriptset_logger.critical(SerialNo)
        else:
            scriptset_logger.info('Serial Number:\t'+SerialNo)
            NARInterval,NIerrcode = cli._GetNarInterval()
            SPcollectstat,SPstaterrcode = cli._GetSPCollectStatus()
            scriptset_logger.info('SPCollect AutoExecution:\t'+SPcollectstat)
            if SPcollectstat != 'Enabled':
                SPcollectAEstat,SPcollectAEerrcode = cli._SetSPcollectAE()
                scriptset_logger.info('Enabling SPCollect AutoExecution....')
            scriptset_logger.info('Archive Interval:\t'+NARInterval)
            RTInterval,RTerrcode = cli._GetRealtimeInterval()
            if RTerrcode != '0':
                bol_Analyzer = False
                scriptset_logger.info('**** Analyzer is not installed ****')
            else:
                scriptset_logger.info('Real Time Interval:\t'+RTInterval)
            LogDays,LDerrcode = cli._GetLogPeriod()
            scriptset_logger.info('Current Logging Period:\t'+LogDays)
            if bol_Analyzer is False:
                scriptset_logger.info('**** Skipping Periodic Archive Setting, Analyzer is not installed ****')
            else:
                PeriodicArchive,PAerrcode = cli._GetPeriodicArchive()
                scriptset_logger.info('Periodic Archiving:\t'+PeriodicArchive)

            if options['--ni'] != None:
                if NARInterval == options['--ni']:
                    scriptset_logger.info('NAR Polling Interval is correctly set to:\t' + NARInterval)
                else:
                    NARInterval = options['--ni']
                    scriptset_logger.info('****Modifying the Archive Poll interval to:\t' + NARInterval)
                    mod = mod + 1
            if LogDays != 'nonstop':
                if options['--ns'] == True:
                    LogDays = 'nonstop'
                    scriptset_logger.info('****Logging Period is being modified to:\t' + LogDays)
                    mod = mod + 1
                elif LogDays != '7':
                    LogDays = '7'
                    scriptset_logger.info('****Logging Period is being modified to:\t' + LogDays)
                    mod = mod + 1
                else:
                    scriptset_logger.info('Logging Period is correctly set to:\t' + LogDays)
            else:
                scriptset_logger.info('Logging Period is correctly set to:\t' + LogDays)

            if bol_Analyzer is True:

                if PeriodicArchive != 'Yes':
                    PeriodicArchive = 'Yes'
                    scriptset_logger.info('****Periodic Archiving is Being Enabled')
                    mod = mod + 1
                else:
                    scriptset_logger.info('Periodic Archiving is correctly set to:\t' +PeriodicArchive)
            else:
                scriptset_logger.info('Skipping Periodic Archiving Modification - No Analyzer')

            NaviStat = cli._GetAnalyzerStatus()

            if mod > 0:
                if 'Stopped' in NaviStat:
                    scriptset_logger.debug('*****Analyzer Logging is NOT Running *****')
                else:
                    StopLogStat,SLSerrcode = cli._StopLogging()
                    time.sleep(10)

                    if 'stopped' in StopLogStat:
                        scriptset_logger.info('*****Analyzer Logging is Already Stopped *****')
                if bol_Analyzer is True:
                    SetLogsStat,SetLogserrcode = cli._SetNaviAnalyzerOptionsLicensed(NARInterval,LogDays)

                    if SetLogserrcode != '0':
                        scriptset_logger.debug('*****Error Setting Analyzer Logging and Archiving Options *****')

                else:
                    SetLogsStat,SetLogserrcode = cli._SetNaviAnalyzerOptions(NARInterval,LogDays)
                    if SetLogserrcode != '0':
                        scriptset_logger.debug('*****Error Setting Analyzer Logging and Archiving Options *****')
                StartLogStat,Starterrcode = cli._StartLogging()
                if Starterrcode != '0':
                    time.sleep(5)
                    scriptset_logger.debug('*****Error Starting Analyzer Logging *****')
                    NaviStat = cli._GetAnalyzerStatus()
                    if 'Stopped' in NaviStat:
                        scriptset_logger.debug('*****Analyzer Logging is NOT Running *****')
                        time.sleep(5)
                        StartLogStat,Starterrcode = cli._StartLogging()
                        if Starterrcode != '0':
                            scriptset_logger.info('*****Error Starting Analyzer Logging *****')
                NARInterval, NIerrcode = cli._GetNarInterval()

                if bol_Analyzer is True:
                    RTInterval,RTerrcode = cli._GetRealtimeInterval()
                    PeriodicArchive,PAerrcode = cli._GetPeriodicArchive()
                else:
                    RTInterval = ''
                    PeriodicArchive = ''
                LogDays, LDerrcode = cli._GetLogPeriod()
                scriptset_logger.info('\tSerial Number:\t' + SerialNo)
                scriptset_logger.info('\tNAR Interval:\t' + NARInterval)
                scriptset_logger.info('\tRealTime Interval:\t' + RTInterval)
                scriptset_logger.info('\tLog Days:\t' + LogDays)
                scriptset_logger.info('\tPeriodic Archive:\t' + PeriodicArchive)

            else:
                scriptset_logger.info('No Need to Change Analyzer Options. Skipping....')
                NaviStat = cli._GetAnalyzerStatus()

            if 'Stopped' in NaviStat:
                scriptset_logger.debug('*****Analyzer Logging is NOT Running *****')
                StartLogStat,Starterrcode = cli._StartLogging()
                if Starterrcode != '0':
                    scriptset_logger.debug('*****Error Starting Analyzer Logging *****')
                    time.sleep(5)
                    NaviStat = cli._GetAnalyzerStatus()
                    if 'Stopped' in NaviStat:
                        scriptset_logger.debug('*****Analyzer Logging is NOT Running *****')
                        time.sleep(5)
                        StartLogStat,Starterrcode = cli._StartLogging()
                        if Starterrcode != '0':
                            scriptset_logger.info('*****Error Starting Analyzer Logging *****')
                time.sleep(5)
                NaviStat = cli._GetAnalyzerStatus()
            scriptset_logger.info(var_array + ' Analyzer Status = ' + NaviStat)
            if 'Stopped' in NaviStat:
                scriptset_logger.info('*****Analyzer Logging is NOT Running *****')

    scriptset_logger.debug('Exiting def_ScriptSet module.')
    scriptset_logger.info('Script is finished setting options.')
Esempio n. 5
0
def ScriptGet(log, array, user, passwd, scope, options):
    scriptget_logger = Logger(log, logging.DEBUG, logging.INFO)
    scriptget_logger.debug('Starting def_ScriptGet module.')
    timenow = datetime.datetime.now().hour + datetime.datetime.now(
    ).minute + datetime.datetime.now().second + datetime.datetime.now(
    ).microsecond

    for x in xrange(len(array)):
        cli = NaviCLI(log, array[x], user[x], passwd[x], scope[x])
        var_array = array[x]
        var_user = user[x]
        var_passwd = passwd[x]
        var_scope = scope[x]
        bool_32plus = False

        scriptget_logger.info(
            '************************************************')
        scriptget_logger.info('Getting Serial Number for ' + var_array +
                              ' ....')
        SerialNo, SNerror = cli._GetSerialNumber()
        if SNerror != '0':
            scriptget_logger.critical(SerialNo)
        else:
            scriptget_logger.info('Getting OE Version for ' + var_array +
                                  ' ....')
            Version, Verror = cli._GetVersion()
            scriptget_logger.info('     Running OE Version ' + Version)
            if '7.32.' in Version:
                bool_32plus = True
            if '7.33.' in Version:
                bool_32plus = True
            outPath = ''.join([var_cwd, '\\', SerialNo])

            if not os.path.exists(outPath):
                scriptget_logger.info('Creating Local Directory ' + outPath +
                                      ' ....')
                os.makedirs(outPath)
                if bool_32plus == True:
                    skew_outpath = outPath + '_SkewData'
                    scriptget_logger.info('Creating Directory for Skew Data ' +
                                          skew_outpath + ' ....')
                    os.makedirs(skew_outpath)
            else:

                if os.path.isdir(outPath):
                    scriptget_logger.info('Found Existing Folder: ' + outPath)
                    outPath = outPath + '_' + str(
                        date.today()) + '_' + str(timenow)

                    if not os.path.exists(outPath):
                        scriptget_logger.info('Creating Local Directory ' +
                                              outPath + ' ....')
                        os.makedirs(outPath)
                        if bool_32plus == True:
                            skew_outpath = outPath + '_SkewData'
                            scriptget_logger.info(
                                'Creating Directory for Skew Data ' +
                                skew_outpath + ' ....')
                            os.makedirs(skew_outpath)
            scriptget_logger.info('Using ' + outPath + ' to save files for ' +
                                  SerialNo)
            scriptget_logger.info('Retrieving SPcollect for ' + SerialNo +
                                  ' ....')

            SPColStat = cli._GetSPCollectList(outPath)
            scriptget_logger.debug(SPColStat)

            l, narstring, oldnar, ol = cli._GetNARList2(
                SerialNo, options['--nnf'])
            scriptget_logger.info('Retrieving ' + str(l) +
                                  ' NAR/NAZ files from ' + SerialNo + ' ....')
            stat = cli._GetNarFiles(narstring, outPath)
            scriptget_logger.info(stat)
            if bool_32plus == True:
                scriptget_logger.info('Retrieving skew files from ' +
                                      SerialNo + ' ....')
                stat = cli._GetArrayconfigXML(skew_outpath)
                scriptget_logger.debug(stat)
                stat = cli._GetFASTData(skew_outpath)
                scriptget_logger.debug(stat)
                os.chdir(var_cwd)
            scriptget_logger.info('**** File Retrieval Complete for ' +
                                  SerialNo + ' ****')
            scriptget_logger.info('**** Creating zip of Data for ' + SerialNo +
                                  ' ****')
            shutil.make_archive(outPath, 'zip', outPath)
            if bool_32plus == True:
                shutil.make_archive(skew_outpath, 'zip', skew_outpath)
            scriptget_logger.info('**** Cleaning Up Local Directory ****')
            shutil.rmtree(outPath, ignore_errors=True)
            if bool_32plus == True:
                shutil.rmtree(skew_outpath, ignore_errors=True)
            if options['--c'] == True:
                scriptget_logger.info('**** Cleaning Up ' + str(ol) +
                                      ' NAR/NAZ files from ' + SerialNo +
                                      ' ****')
                cleanupstat = cli._CleanupOldNar(oldnar)
                scriptget_logger.debug(cleanupstat)

    scriptget_logger.debug('Exiting def_ScriptGet module.')
    scriptget_logger.debug('Script is finished retrieving files.')
Esempio n. 6
0
def ScriptSet(log, array, user, passwd, scope, options):

    scriptset_logger = Logger(log, logging.DEBUG, logging.INFO)
    scriptset_logger.debug('Starting ScriptSet module.')

    for x in xrange(len(array)):
        cli = NaviCLI(log, array[x], user[x], passwd[x], scope[x])
        var_array = array[x]
        var_user = user[x]
        var_passwd = passwd[x]
        var_scope = scope[x]
        bol_Analyzer = True
        mod = 0
        scriptset_logger.info(
            '************************************************')
        scriptset_logger.info('Getting Current Settings for ' + var_array +
                              ' :')
        SerialNo, SNerrcode = cli._GetSerialNumber()
        if SNerrcode != '0':
            scriptset_logger.critical(SerialNo)
        else:
            scriptset_logger.info('Serial Number:\t' + SerialNo)
            NARInterval, NIerrcode = cli._GetNarInterval()
            SPcollectstat, SPstaterrcode = cli._GetSPCollectStatus()
            scriptset_logger.info('SPCollect AutoExecution:\t' + SPcollectstat)
            if SPcollectstat != 'Enabled':
                SPcollectAEstat, SPcollectAEerrcode = cli._SetSPcollectAE()
                scriptset_logger.info('Enabling SPCollect AutoExecution....')
            scriptset_logger.info('Archive Interval:\t' + NARInterval)
            RTInterval, RTerrcode = cli._GetRealtimeInterval()
            if RTerrcode != '0':
                bol_Analyzer = False
                scriptset_logger.info('**** Analyzer is not installed ****')
            else:
                scriptset_logger.info('Real Time Interval:\t' + RTInterval)
            LogDays, LDerrcode = cli._GetLogPeriod()
            scriptset_logger.info('Current Logging Period:\t' + LogDays)
            if bol_Analyzer is False:
                scriptset_logger.info(
                    '**** Skipping Periodic Archive Setting, Analyzer is not installed ****'
                )
            else:
                PeriodicArchive, PAerrcode = cli._GetPeriodicArchive()
                scriptset_logger.info('Periodic Archiving:\t' +
                                      PeriodicArchive)

            if options['--ni'] != None:
                if NARInterval == options['--ni']:
                    scriptset_logger.info(
                        'NAR Polling Interval is correctly set to:\t' +
                        NARInterval)
                else:
                    NARInterval = options['--ni']
                    scriptset_logger.info(
                        '****Modifying the Archive Poll interval to:\t' +
                        NARInterval)
                    mod = mod + 1
            if LogDays != 'nonstop':
                if options['--ns'] == True:
                    LogDays = 'nonstop'
                    scriptset_logger.info(
                        '****Logging Period is being modified to:\t' + LogDays)
                    mod = mod + 1
                elif LogDays != '7':
                    LogDays = '7'
                    scriptset_logger.info(
                        '****Logging Period is being modified to:\t' + LogDays)
                    mod = mod + 1
                else:
                    scriptset_logger.info(
                        'Logging Period is correctly set to:\t' + LogDays)
            else:
                scriptset_logger.info('Logging Period is correctly set to:\t' +
                                      LogDays)

            if bol_Analyzer is True:

                if PeriodicArchive != 'Yes':
                    PeriodicArchive = 'Yes'
                    scriptset_logger.info(
                        '****Periodic Archiving is Being Enabled')
                    mod = mod + 1
                else:
                    scriptset_logger.info(
                        'Periodic Archiving is correctly set to:\t' +
                        PeriodicArchive)
            else:
                scriptset_logger.info(
                    'Skipping Periodic Archiving Modification - No Analyzer')

            NaviStat = cli._GetAnalyzerStatus()

            if mod > 0:
                if 'Stopped' in NaviStat:
                    scriptset_logger.debug(
                        '*****Analyzer Logging is NOT Running *****')
                else:
                    StopLogStat, SLSerrcode = cli._StopLogging()
                    time.sleep(10)

                    if 'stopped' in StopLogStat:
                        scriptset_logger.info(
                            '*****Analyzer Logging is Already Stopped *****')
                if bol_Analyzer is True:
                    SetLogsStat, SetLogserrcode = cli._SetNaviAnalyzerOptionsLicensed(
                        NARInterval, LogDays)

                    if SetLogserrcode != '0':
                        scriptset_logger.debug(
                            '*****Error Setting Analyzer Logging and Archiving Options *****'
                        )

                else:
                    SetLogsStat, SetLogserrcode = cli._SetNaviAnalyzerOptions(
                        NARInterval, LogDays)
                    if SetLogserrcode != '0':
                        scriptset_logger.debug(
                            '*****Error Setting Analyzer Logging and Archiving Options *****'
                        )
                StartLogStat, Starterrcode = cli._StartLogging()
                if Starterrcode != '0':
                    time.sleep(5)
                    scriptset_logger.debug(
                        '*****Error Starting Analyzer Logging *****')
                    NaviStat = cli._GetAnalyzerStatus()
                    if 'Stopped' in NaviStat:
                        scriptset_logger.debug(
                            '*****Analyzer Logging is NOT Running *****')
                        time.sleep(5)
                        StartLogStat, Starterrcode = cli._StartLogging()
                        if Starterrcode != '0':
                            scriptset_logger.info(
                                '*****Error Starting Analyzer Logging *****')
                NARInterval, NIerrcode = cli._GetNarInterval()

                if bol_Analyzer is True:
                    RTInterval, RTerrcode = cli._GetRealtimeInterval()
                    PeriodicArchive, PAerrcode = cli._GetPeriodicArchive()
                else:
                    RTInterval = ''
                    PeriodicArchive = ''
                LogDays, LDerrcode = cli._GetLogPeriod()
                scriptset_logger.info('\tSerial Number:\t' + SerialNo)
                scriptset_logger.info('\tNAR Interval:\t' + NARInterval)
                scriptset_logger.info('\tRealTime Interval:\t' + RTInterval)
                scriptset_logger.info('\tLog Days:\t' + LogDays)
                scriptset_logger.info('\tPeriodic Archive:\t' +
                                      PeriodicArchive)

            else:
                scriptset_logger.info(
                    'No Need to Change Analyzer Options. Skipping....')
                NaviStat = cli._GetAnalyzerStatus()

            if 'Stopped' in NaviStat:
                scriptset_logger.debug(
                    '*****Analyzer Logging is NOT Running *****')
                StartLogStat, Starterrcode = cli._StartLogging()
                if Starterrcode != '0':
                    scriptset_logger.debug(
                        '*****Error Starting Analyzer Logging *****')
                    time.sleep(5)
                    NaviStat = cli._GetAnalyzerStatus()
                    if 'Stopped' in NaviStat:
                        scriptset_logger.debug(
                            '*****Analyzer Logging is NOT Running *****')
                        time.sleep(5)
                        StartLogStat, Starterrcode = cli._StartLogging()
                        if Starterrcode != '0':
                            scriptset_logger.info(
                                '*****Error Starting Analyzer Logging *****')
                time.sleep(5)
                NaviStat = cli._GetAnalyzerStatus()
            scriptset_logger.info(var_array + ' Analyzer Status = ' + NaviStat)
            if 'Stopped' in NaviStat:
                scriptset_logger.info(
                    '*****Analyzer Logging is NOT Running *****')

    scriptset_logger.debug('Exiting def_ScriptSet module.')
    scriptset_logger.info('Script is finished setting options.')
Esempio n. 7
0
def main():
    log = options['--l']
    if options['--debug'] == True:
        main_logger = Logger(
            log,
            logging.DEBUG,
            logging.INFO
            )
    else:
        main_logger = Logger(
            log,
            logging.INFO,
            logging.INFO
            )

    rd_csv = ReadCSV(
        log,
        options
        )

    if options['--set'] == True:
        main_logger.debug(
            'Set argument is set'
            )
        ScriptSet(
            log,
            rd_csv.host,
            rd_csv.uname,
            rd_csv.passwd,
            rd_csv.scope,
            options
            )
    if options['--get'] == True:
        main_logger.debug(
            'Get argument is set'
            )
        ScriptGet(
            log,
            rd_csv.host,
            rd_csv.uname,
            rd_csv.passwd,
            rd_csv.scope,
            options
            )

    if options['--c'] == True:
        main_logger.debug(
            'Cleanup argument is set with the Get argument'
            )
        if options['--get'] == False:
            main_logger.debug(
                'Cleanup argument is set by itself'
                )
            OnlyCleanupOldNar(
                log,
                rd_csv.host,
                rd_csv.uname,
                rd_csv.passwd,
                rd_csv.scope,
                options
                )
    main_logger.debug(
        'Exiting.'
        )
    main_logger.info(
        'Script Complete.'
        )
    sys.exit(0)
Esempio n. 8
0
def main():
    log = options['--l']

    if options['--debug'] == True:
        main_logger = Logger(
            options['--l'],
            logging.DEBUG,
            logging.INFO
            )
    else:
        main_logger = Logger(
            options['--l'],
            logging.INFO,
            logging.INFO
            )

    main_logger.info(
        'Running XtremIO Snap Script'
        )
    main_options = Options(
        log,
        options
        )
    XMS_IP = options['XMS_IP']
    XMS_USER = main_options.XMS_USER
    XMS_PASS = main_options.XMS_PASS
    snap_tgt_folder = main_options.snap_tgt_folder
    parent_folder_id = main_options.var_snap_tgt_folder
    num_snaps = options['--n']
    snap_src = options['--snap']
    SnapFolder = '_Snapshots'
    bool_create_folder = True ## will change to False if the /_Snapshots folder already exists
    rest = Restful(
        log,
        options['--debug'],
        XMS_IP,
        XMS_USER,
        XMS_PASS
        )
    folder_list = rest._get(
        '/api/json/types/volume-folders'
        ).json()['folders']
    for folder_list_rs in folder_list:
        if folder_list_rs['name'] == '/'+ snap_tgt_folder:
            bool_create_folder = False
            main_logger.info(
                'The target snapshot folder, '+folder_list_rs['name']+' already exists.'
                )
    if bool_create_folder is True:
        cf_payload = '{\
            "caption": \"'+SnapFolder+'\" , \
            "parent-folder-id": \"/'+main_options.var_snap_tgt_folder+'\" \
            }'
        cf_resp = rest._post(
            '/api/json/types/volume-folders',
            cf_payload
            )
        if cf_resp.status_code == 201:
            main_logger.warn(
                'Created folder: '+main_options.snap_tgt_folder
                )
    if options['--f'] ==True:
        newsnapsuffix = '.folder.'+main_options.schedule+'.'
        folder_vol_list = rest._get(
            '/api/json/types/volume-folders/?name=/'+snap_src
            ).json()['content']['direct-list']
        arr_folder_vol_list_component = []
        for folder_vol_list_rs in folder_vol_list:
            if '/_Snapshots' in folder_vol_list_rs[1]:
                pass
            else:
                arr_folder_vol_list_component.append(folder_vol_list_rs[1])
                main_logger.info(
                    'Will retain '+num_snaps+' snapshots for volume: '+folder_vol_list_rs [1]
                    )
                vol_snap_list = rest._get(
                    '/api/json/types/volumes/?name='+folder_vol_list_rs [1]
                    ).json()['content']['dest-snap-list']##<--Initial list of snapshots
                arr_vol_snap_list_component = []
                for vol_snap_list_rs in vol_snap_list:
                    if newsnapsuffix in vol_snap_list_rs[1]:
                        arr_vol_snap_list_component.append(vol_snap_list_rs[1])
                arr_vol_snap_list_component.sort(reverse=True)
                for y in range(len(arr_vol_snap_list_component)): ##<--shifting the suffix of each matchin snap by 1
                    if newsnapsuffix in arr_vol_snap_list_component[y]:
                        list_snapname = []
                        try:
                            list_snapname = arr_vol_snap_list_component[y].split('.',3)
                        except:
                            pass
                        rename_to =list_snapname[0]+newsnapsuffix+str(y+1)
                        rename_payload = '{"vol-name": \"'+rename_to+'\"}'
                        rename_resp = rest._put(
                            '/api/json/types/volumes/?name='+arr_vol_snap_list_component[y],
                            rename_payload
                            )
                        if rename_resp.status_code == 200:
                            main_logger.info(
                                'Snapshot: '+arr_vol_snap_list_component[y]+' was renamed to '+rename_to
                                )
        timestamp = datetime.datetime.now()
        timestamp = timestamp.isoformat()
        arr_timestamp = timestamp.split('.',2) ##<--stripping the microseconds from the timestamp for aesthetics
        fullsuffix = '_'+arr_timestamp[0]+newsnapsuffix+'0'
        fs_payload = '{\
            "source-folder-id": \"/'+snap_src+'\" , \
            "suffix": \"'+fullsuffix+'\" ,\
            "folder-id": \"/'+snap_tgt_folder+'\" \
            }'
        vol_snap = rest._post(
            '/api/json/types/snapshots',
            fs_payload
            )
        folder_vol_list = rest._get(
            '/api/json/types/volume-folders/?name=/'+snap_src
            ).json()['content']['direct-list']
        arr_folder_vol_list_component = []
        for folder_vol_list_rs in folder_vol_list:
            if '/_Snapshots' in folder_vol_list_rs[1]:
                pass
            else:
                vol_snap_list = rest._get(
                    '/api/json/types/volumes/?name='+folder_vol_list_rs [1]
                    ).json()['content']['dest-snap-list']##<--Refresh the snap list
                arr_vol_snap_list_component = []
                for vol_snap_list_rs in vol_snap_list:
                    if newsnapsuffix in vol_snap_list_rs[1]:
                        arr_vol_snap_list_component.append(vol_snap_list_rs[1])
                arr_vol_snap_list_component.sort(reverse=False)
                for x in xrange(len(arr_vol_snap_list_component)-(int(num_snaps))):
                    if newsnapsuffix in arr_vol_snap_list_component[x]:
                        main_logger.debug(
                            str(x)+': '+ arr_vol_snap_list_component[x]
                            )
                        get_snap_details = rest._get(
                            '/api/json/types/snapshots/?name='+arr_vol_snap_list_component[x]
                            )
                        arr_ancestor_vol_id = get_snap_details.json()['content']['ancestor-vol-id']
                        snap_parent_name = arr_ancestor_vol_id[1]
                        snap_creation_time = get_snap_details.json()['content']['creation-time']
                        snap_space_consumed = get_snap_details.json()['content']['logical-space-in-use']
                        arr_snap_lun_mapping = get_snap_details.json()['content']['lun-mapping-list']
                        main_logger.warn(
                            'Parent Volume of '+arr_vol_snap_list_component[x]+' = '+snap_parent_name
                            )
                        main_logger.warn(
                            'Snapshot: ' +arr_vol_snap_list_component[x]
                            )
                        main_logger.warn(
                            '       Snap was created on '+snap_creation_time
                            )
                        main_logger.warn(
                            '       Snap is using '+ str((float(snap_space_consumed)/1024)/1024)+' GB'
                            )
                        arr_lun_mapping_component = []
                        if len(arr_snap_lun_mapping) > 0:##<--checking to see if an active LUN mapping exists
                            for rs in arr_snap_lun_mapping:
                                arr_lun_mapping_component = [[y] for y in rs[0]]
                                arr_lun_mapping_component =str(arr_lun_mapping_component[1])
                                arr_lun_mapping_component = arr_lun_mapping_component.replace('[u\'','')
                                arr_lun_mapping_component = arr_lun_mapping_component.replace('\']','')
                                main_logger.critical(
                                    'Snapshot: '+arr_vol_snap_list_component[x]+' is currently mapped to '+arr_lun_mapping_component+', it will not be deleted.'
                                    )
                        else:
                            main_logger.warn(
                                '       No hosts mapped to '+arr_vol_snap_list_component[x]+', it will be deleted.'
                                )
                            delete_status = rest._delete(
                                '/api/json/types/volumes/?name='+arr_vol_snap_list_component[x]
                                )
    elif options['--v'] ==True:
        main_logger.info(
            'Will retain '+num_snaps+' snapshots for volume: '+snap_src
            )
        newsnapsuffix = '.'+main_options.schedule+'.'
        vol_snap_list = rest._get(
            '/api/json/types/volumes/?name='+snap_src
            ).json()['content']['dest-snap-list']
        arr_vol_snap_list_component = []
        for vol_snap_list_rs in vol_snap_list:
            if newsnapsuffix in vol_snap_list_rs[1]:
                if '.folder.' in vol_snap_list_rs[1]:
                    pass
                else:
                    arr_vol_snap_list_component.append(vol_snap_list_rs[1])
        arr_vol_snap_list_component.sort(reverse=True)
        for y in range(len(arr_vol_snap_list_component)): ##<--shifting the suffix of each matchin snap by 1
            if newsnapsuffix in arr_vol_snap_list_component[y]:
                list_snapname = []
                try:
                    list_snapname = arr_vol_snap_list_component[y].split('.',3)
                except:
                    pass
                rename_to =list_snapname[0]+newsnapsuffix+str(y+1)
                rename_payload = '{"vol-name": \"'+rename_to+'\"}'
                rename_resp = rest._put(
                    '/api/json/types/volumes/?name='+arr_vol_snap_list_component[y],
                    rename_payload
                    )
                if rename_resp.status_code == 200:
                            main_logger.info(
                                'Snapshot: '+arr_vol_snap_list_component[y]+' was renamed to '+rename_to
                                )
        timestamp = datetime.datetime.now()
        timestamp = timestamp.isoformat()
        arr_timestamp = timestamp.split('.',2) ##<--stripping the microseconds from the timestamp for aesthetics
        fullsuffix = '_'+arr_timestamp[0]+newsnapsuffix
        newsnap = snap_src+fullsuffix+'0'##<--sets the newly created snapshot to always be .0
        vol_snap_payload = '{\
            "ancestor-vol-id": \"'+snap_src+'\" , \
            "snap-vol-name": \"'+newsnap+'\" ,\
            "folder-id": \"/'+snap_tgt_folder+'\" \
            }'
        vol_snap_resp = rest._post(
            '/api/json/types/snapshots',
            vol_snap_payload
            )
        vol_snap_list = rest._get(
            '/api/json/types/volumes/?name='+snap_src
            ).json()['content']['dest-snap-list']
        arr_vol_snap_list_component = []
        for vol_snap_list_rs in vol_snap_list:
            if newsnapsuffix in vol_snap_list_rs[1]:
                if '.folder.' in vol_snap_list_rs[1]:
                    pass
                else:
                    arr_vol_snap_list_component.append(vol_snap_list_rs[1])
        arr_vol_snap_list_component.sort(reverse=False)
        for x in xrange(len(arr_vol_snap_list_component)-(int(num_snaps))):
            if newsnapsuffix in arr_vol_snap_list_component[x]:
                main_logger.debug(str(x)+': '+ arr_vol_snap_list_component[x])
                get_snap_details = rest._get(
                    '/api/json/types/snapshots/?name='+arr_vol_snap_list_component[x]
                    )
                arr_ancestor_vol_id = get_snap_details.json()['content']['ancestor-vol-id']
                snap_parent_name = arr_ancestor_vol_id[1]
                snap_creation_time = get_snap_details.json()['content']['creation-time']
                snap_space_consumed = get_snap_details.json()['content']['logical-space-in-use']
                arr_snap_lun_mapping = get_snap_details.json()['content']['lun-mapping-list']
                main_logger.warn(
                    'Parent Volume of '+arr_vol_snap_list_component[x]+' = '+snap_parent_name
                    )
                main_logger.warn(
                    'Snapshot: '+arr_vol_snap_list_component[x]
                    )
                main_logger.warn(
                    '       Snap was created on '+snap_creation_time
                    )
                main_logger.warn(
                    '       Snap is using '+ str((float(snap_space_consumed)/1024)/1024)+' GB'
                    )
                arr_lun_mapping_component = []
                if len(arr_snap_lun_mapping) > 0:##<--checking to see if an active LUN mapping exists
                    for rs in arr_snap_lun_mapping:
                        arr_lun_mapping_component = [[y] for y in rs[0]]
                        arr_lun_mapping_component =str(arr_lun_mapping_component[1])
                        arr_lun_mapping_component = arr_lun_mapping_component.replace('[u\'','')
                        arr_lun_mapping_component = arr_lun_mapping_component.replace('\']','')
                        main_logger.critical(
                            'Snapshot '+arr_vol_snap_list_component[x]+' is currently mapped to '+arr_lun_mapping_component+', it will not be deleted.'
                            )
                else:
                    main_logger.warn(
                        '       No hosts mapped to '+arr_vol_snap_list_component[x]+', it will be deleted.'
                        )
                    delete_status = rest._delete(
                        '/api/json/types/volumes/?name='+arr_vol_snap_list_component[x]
                        )
    else:
        print 'NO FOLDER OR VOLUME OPTION SPECIFIED'
        sys.exit(1)

    main_logger.info('Complete!')
    sys.exit(0)
Esempio n. 9
0
    def __init__(self,logfile,options):

        global options_logger
        if options['--debug'] == True:
            options_logger = Logger(logfile,logging.DEBUG,logging.INFO)
        else:
            options_logger = Logger(logfile,logging.INFO,logging.INFO)

        options_logger.debug('Loading Options Module')
        encoder = Encode(options['--l'],options['--debug'])

        if options['--encode'] is True:
            options_logger.info('Encoding user id and password')
            encode_user = encoder._encodeuser(options['XMS_USER'])
            encode_pass = encoder._encodepass(options['XMS_PASS'])
            print ''
            print 'Encoded User ID = ' + encode_user
            print 'Encoded Password = '******''
            options_logger.info('Use the above, encoded, user id and password with the --e option')
            options_logger.info('to execute the tool without using the plain text usename and password')
            sys.exit(0)

        elif options['--e']:
            options_logger.debug('Using an encoded username and password')
            XMS_USER = encoder._decodeuser(options['XMS_USER'])
            XMS_PASS = encoder._decodepass(options['XMS_PASS'])

        else:
            options_logger.debug('Username and password are not encoded')
            XMS_USER = options['XMS_USER']
            XMS_PASS = options['XMS_PASS']

        self.XMS_USER = XMS_USER
        self.XMS_PASS = XMS_PASS

        if options['--schedule'] == 'hourly':
            options_logger.debug('Using the hourly schedule')
            self.schedule = 'hourly'

        elif options['--schedule'] == 'daily':
            options_logger.debug('Using the daily schedule')
            self.schedule = 'daily'

        elif options['--schedule'] == 'weekly':
            options_logger.debug('Using the weekly schedule')
            self.schedule = 'weekly'

        else:
            options_logger.critical('No schedule, or incorrect option Specified.  Exiting...')
            sys.exit(1)

        SnapFolder = '_Snapshots'

        self.var_snap_tgt_folder = options['--tf'] ## this should be an optional variable, if the customer wants to organize snapshots under a folder hierarchy

        if self.var_snap_tgt_folder == None:
            options_logger.debug('No snapshot target folder specified')
            self.var_snap_tgt_folder =''
            self.snap_tgt_folder = SnapFolder
            options_logger.debug('Using '+self.snap_tgt_folder+' as the snapshot target')
        else:
            self.snap_tgt_folder = self.var_snap_tgt_folder+'/'+SnapFolder
            options_logger.debug('Using '+self.snap_tgt_folder+' as the snapshot target')