Exemple #1
0
        if not args.encode and not args.decode and not args.script and not args.hash and not args.interactive:
            # Start GUI when no other parameters were used.
            try:
                app = QApplication(sys.argv)
                ex = MainWindow(context)
                sys.exit(app.exec_())
            except Exception as e:
                context.logger().error("Unexpected Exception: {}".format(e))
                sys.exit(1)

        if args.interactive:
            setup_syntax_completion()
            from ptpython.repl import embed
            print("{app_name} {app_version}".format(
                app_name=context.config().getName(),
                app_version=context.config().getVersion()))
            embed(globals=globals(), locals=locals())
            sys.exit(0)

        if not args.encode and not args.decode and not args.script and not args.hash:
            context.logger().error("No action specified!")
            sys.exit(1)

        if not args.file and not args.input:
            context.logger().error("No input specified!")
            sys.exit(1)

        if args.file and args.input:
            context.logger().error(
                "Argument --file and input can not be used in together.")
Exemple #2
0
def main():

    # -w (run preprocessor write)
    if args.run_preprocessor:
        run_preprocessor()
        exit(0)

    # -r (run preprocessor read)
    if args.run_preprocessor_read:
        run_preprocessor_read()
        exit(0)

    # -a (run aggregated plotter)
    if args.aggregated_plots:
        if not args.plotters:
            logger.error("The -u option is required for -a. Exit now.")
            exit(1)
        if args.plotters == 'util/agg_preprocessor.py':
            args.run_preprocessor = args.aggregated_plots
            run_preprocessor()
            exit(0)
        run_aggregated_plotter()
        exit(0)

    # -p and -u (run plotter from pickle file)
    if args.picklefile:
        run_plotter()
        exit(0)

    # -t (run tests)
    if args.run_tests:
        run_tests()
        exit(0)

    # make sure the file that should be run exists
    if not args.filename:
        logger.error('The -f options is required. Exit now.')
        exit(1)

    try:
        # TODO: currently, filenames are relative to the topo folder
        topo_folder = os.path.join(os.getcwd(), 'topo')
        filename = args.filename.strip()
        if not filename.endswith('.py'): filename = filename + '.py'

        # make sure the file that should be run exists
        if not os.path.exists(os.path.join(topo_folder, filename)):
            scripts = get_scripts(topo_folder)
            print(scripts)
            for script in scripts:
                if filename == os.path.basename(script):
                    logger.info('use file: %s' % script)
                    filename = script
                    break
            else:
                logger.error('The file specified via -f was not found: %s' %
                             str(filename))
                # fallback to default
                topo_folder = os.path.join(os.getcwd(), 'topo')
                filename = os.path.join(topo_folder, 'custom/pbce/exp800-2.py')
                logger.error('Using fallback: %s' % filename)
                if not os.path.exists(os.path.join(topo_folder, filename)):
                    logger.error('Fallback failed')
                    exit(1)

        # create a new experiment context that stores all the data; this is
        # the central object that is basically injected everywhere from now on; try not
        # to add anything here except raw objects (i.e., no functions) due to
        # serialization issues
        ctx = Context()
        ctx.started = time.time()
        timer = Timer(ctx, 'main')
        timer.start('total_time')

        # enforce specific seed (stored in ctx)
        if args.seed:
            logger.info('Global seed set to %d via CLI' % int(args.seed))
            ctx.seed = int(args.seed)

        # only run the scenario generator (neither the simulator nor the DTS/RSA algorithms
        # are executed)
        if args.run_scenario_generator:
            logger.info(
                'Note: -g flag is set, i.e., the scenario generator ctx flag is active and the simulator will not be executed'
            )
            ctx.run_scenario_generator = True

        # inject config from configfile into ctx
        # this is useful if the tool is used in an automated fashion
        if args.config:
            with open(args.config, 'r') as file:
                config = json.loads(file.read())
                ctx.configfile = args.config
                ctx.config = config
                #logger.info(str(config) + " " + args.filename)

        # create topology
        topo = Topology(ctx, filename=filename)

        if args.run_scenario_generator:
            logger.info(
                'Run scenario generator instead of simulator (-g flag was set)'
            )
            ctx.statistics['sim.skipped'] = 1

        # finally run the simulator if requested
        if not ctx.skip_main_simulation == True:
            sim = Simulator(ctx)
            sim.run()

        # print the statistics
        print_statistics(ctx)

        # save the aggregated statistics (statistics.json)
        if ctx.configfile:
            statistics_file = os.path.join(os.path.dirname(ctx.configfile),
                                           'statistics.json')
            with open(statistics_file, 'w') as file:
                file.write(json.dumps(ctx.statistics))

        # saves a pickle result file from ctx to access all raw data later on
        # (skipped if -n flag is used)
        if not args.nopickle:
            if ctx.scenario is not None:
                timer.stop()
                return
                #raise Exception("ctx.scenario is set -> not possible to create a pickle file (-n option is mandatory here!")
            if ctx.configfile:
                sys.setrecursionlimit(100000)
                result_file = os.path.join(os.path.dirname(ctx.configfile),
                                           'result.pickle')
                pickle.dump(ctx,
                            open(result_file, "wb"),
                            protocol=pickle.HIGHEST_PROTOCOL)

        # deprecated
        if args.plotters:
            logger.info("run plotters..")
            plotters = args.plotters.split(',')
            # handle plotters
            for plotter in plotters:
                modulepath = "plotter.%s" % plotter.replace('.py', '').replace(
                    os.sep, '.')
                modulepath = modulepath.replace('..', '.')
                logger.info("loading plotter: %s" % modulepath)
                importlib.import_module(modulepath).plot(ctx)

        timer.stop()

    except TimeoutError as e:
        timer.stop()
        # maximum time has exceeded
        logger.info("Timelimit exceeded, abort")
        # create statistics file (this is not technically an error, some experiments are just
        # running too long)
        if ctx.configfile:
            statistics_file = os.path.join(os.path.dirname(ctx.configfile),
                                           'statistics.json')
            ctx.statistics['hit_timelimit'] = time.time() - ctx.started
            print_statistics(ctx)
            with open(statistics_file, 'w') as file:
                file.write(json.dumps(ctx.statistics))
        # still create an error message for quick checks
        exc_string = traceback.format_exc()
        if ctx.configfile:
            error_file = os.path.join(os.path.dirname(ctx.configfile),
                                      'timeout-error.txt')
            with open(error_file, 'w') as file:
                file.write(exc_string)
        # finally print the exception and exit
        print("Exception:")
        print('-' * 60)
        print(exc_string)
        print('-' * 60)
        exit(0)

    except Exception as e:
        timer.stop()
        print("Exception:")
        print('-' * 60)
        exc_string = traceback.format_exc()
        print(exc_string)
        print('-' * 60)
        # save the aggregated statistics (statistics.json)
        if ctx.configfile:
            error_file = os.path.join(os.path.dirname(ctx.configfile),
                                      'error.txt')
            with open(error_file, 'w') as file:
                file.write(exc_string)
        raise e