示例#1
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument( "-c", "--config-file", help='Set config file path (default config.json)',
                         default='config.json', type=str )
    parser.add_argument( "-l", "--log-level", help="Set log level. 10=debug 20=info 30=warn 40=error (default 20)",
                         default=20, type=int)
    arguments = parser.parse_args()

    FORMAT = "%(levelname)s\t%(name)s: %(message)s"
    logging.basicConfig(format=FORMAT)
    log = logging.getLogger('main')
    log.setLevel(arguments.log_level)


    readVisitors = pv.getVisitorsFromFolder( 'read' )
    processVisitors = pv.getVisitorsFromFolder( 'process' )
    writeVisitors = pv.getVisitorsFromFolder( 'write' )

    resources = Collection()

    # get contents of config file
    config = json.load( open( arguments.config_file, 'r' ) )

    for section in config['read']:
        visitor = readVisitors.select( section )
        if visitor is None:
            log.error( 'no read visitor could be found for section {0}'.format( section ) )
            continue
        try:
            resources.update( visitor.visit( section ) )
        except Exception as e:
            log.error( 'an exception occurred when visiting {0}: {1}'.format( visitor.__class__.__name__, str(e) ) )
            log.debug(traceback.format_exc())

    resources.report('after reading, the available resources are:')

    for section in config['process']:
        visitor = processVisitors.select( section )
        if visitor is None:
            log.error( 'no process visitor could be found for section {0}'.format( section ) )
            continue
        try:
            resources.update( visitor.visit( section, resources ) )
        except Exception as e:
            log.error( 'an exception occurred when visiting {0}: {1}'.format( visitor.__class__.__name__, str(e) ) )
            log.debug(traceback.format_exc())

    resources.report('after processing, the available resources are:')

    for section in config['write']:
        visitor = writeVisitors.select( section )
        if visitor is None:
            log.error( 'no write visitor could be found for section {0}'.format( section ) )
            continue
        try:
            visitor.visit( section, resources )
        except Exception as e:
            log.error( 'an exception occurred when visiting {0}: {1}'.format( visitor.__class__.__name__, str(e) ) )
            log.debug(traceback.format_exc())
    def visit( self, json, resources ):
        out = Report( json['subject'] )

        if 'cssfile' in json:
            css = json['cssfile']
        else:
            css = 'default report.css'
        #time variable to use the same time everywhere
        thetime = time()
        htmlgenerator = HmtlReportGenerator( open(css, 'r').read(), json['subject'] )
        #process the kpis
        if json.get('kpis'):
            kpiVisitors = pv.getVisitorsFromFolder( 'kpis' )
            #create the multidimensional list later to be used to create the table
            kpilist = [["KPI","","Value"]]
            for kpi in json['kpis']:
                visitor = kpiVisitors.select( kpi)
                if visitor is None:
                    log.error( 'no read visitor could be found for kpi {0}'.format( kpi ) )
                    continue
                try:
                    #visit the kpi and fetch the value
                    indicator, kpivalue = visitor.visit( kpi,resources )
                    name = kpi['name']
                    kpilist.append([name,indicator,"%6.3f"%kpivalue]) 
                except Exception as e:
                    log.error( 'an exception occurred when visiting {0}: {1}'.format( visitor.__class__.__name__, str(e) ) )      
            htmlgenerator.addTable(kpilist,"KPI table")
                
        #process the tables that should be added
        if json.get('tables'):
            for table in json['tables']:
                #create tabledata with the given period
                tabledata = TableData(float(table['period']),int(table['count']),thetime)

                #add the source to the tabledata
                log.info('adding sources to table')
                balanceCollection = resources.selectMany(table['sources'],FullBalance)
                #if no resources are found skip to the next table
                if len(balanceCollection) <1:
                    log.warn('No resources found to add to table')
                    continue
                for key, resource in balanceCollection:
                    tabledata.addValueRow(resource.value,key,table.get('type'))

                tabledata.sort()
                #add the total row and column if the options are set
                if table.get('totalrow'):
                    log.info('adding total row to table')
                    tabledata.addTotalRow()
                if table.get('totalcolumn'):
                    log.info('adding total column to table')
                    tabledata.addDiffTotalColumn()
                log.info('adding tabledata to htmltable')
                htmlgenerator.addTable(tabledata,table['title'],table.get('diffcolors'))
            
        htmlgenerator.finalize()

        out.setBody( htmlgenerator.body )
        resources[ json['out'] ] = out
        return resources