def print_formatted_table(delimiter):
    """Read tabular data from standard input and print a table."""
    data = []
    for line in sys.stdin:
        line = line.rstrip()
        data.append(line.split(delimiter))
    print(format_table(data))
Beispiel #2
0
def print_formatted_table(delimiter):
    """Read tabular data from standard input and print a table."""
    data = []
    for line in sys.stdin:
        line = line.rstrip()
        data.append(line.split(delimiter))
    output(format_table(data))
def report_available_mirrors(updater):
    """Print the available mirrors to the terminal (in a human friendly format)."""
    if connected_to_terminal():
        have_bandwidth = any(c.bandwidth for c in updater.ranked_mirrors)
        have_last_updated = any(c.last_updated is not None
                                for c in updater.ranked_mirrors)
        column_names = ["Rank", "Mirror URL", "Available?", "Updating?"]
        if have_last_updated:
            column_names.append("Last updated")
        if have_bandwidth:
            column_names.append("Bandwidth")
        data = []
        for i, candidate in enumerate(updater.ranked_mirrors, start=1):
            row = [
                i, candidate.mirror_url,
                "Yes" if candidate.is_available else "No",
                "Yes" if candidate.is_updating else "No"
            ]
            if have_last_updated:
                row.append("Up to date" if candidate.last_updated == 0 else (
                    "%s behind" %
                    format_timespan(candidate.last_updated) if candidate.
                    last_updated else "Unknown"))
            if have_bandwidth:
                row.append("%s/s" % format_size(round(candidate.bandwidth, 2))
                           if candidate.bandwidth else "Unknown")
            data.append(row)
        output(format_table(data, column_names=column_names))
    else:
        output(u"\n".join(
            candidate.mirror_url for candidate in updater.ranked_mirrors
            if candidate.is_available and not candidate.is_updating))
    def create(configuration, debug=True):
        """
        Parse the target element from the configuration argument

        :param configuration: dictionary containing all user configuration to correctly setup Avatar modules
        :return:
        """

        c = configuration.checkGlobalTargetConfiguration()

        if c["name"] == "openocd" :

            init_openocd()

        elif c["name"] == "gdb" :

            raise NotImplementedError("Unimplmented GDB MI target")

            c = configuration.checkGdbConfiguration()

            return GdbserverTarget()

        elif c["name"] == "superspeed-jtag" :

            c = configuration.checkSuperspeedJtagConfiguration()

            nn = NameNormalizer()
            if debug:
                log.debug("\r\nTarget configuration : \r\n %s \r\n" % format_table([(nn.normalize_name(n), c[n]) for n in c]))


            return SuperspeedJtagTarget( c['access-port'], c['base_dir'], c['options'], debug=False)

        else :
            raise ValueError("Target configuration wrong : undefined target %s !" % self.name)
Beispiel #5
0
def report_available_mirrors(updater):
    """Print the available mirrors to the terminal (in a human friendly format)."""
    if connected_to_terminal() or os.getenv(
            'TRAVIS') == 'true':  # make Travis CI test this code
        # https://docs.travis-ci.com/user/environment-variables/#default-environment-variables
        have_bandwidth = any(c.bandwidth for c in updater.ranked_mirrors)
        have_last_updated = any(c.last_updated is not None
                                for c in updater.ranked_mirrors)
        column_names = ["Rank", "Mirror URL", "Available?", "Updating?"]
        if have_last_updated:
            column_names.append("Last updated")
        if have_bandwidth:
            column_names.append("Bandwidth")
        data = []
        long_mirror_urls = {}
        if os.getenv('TRAVIS') == 'true':
            updater.url_char_len = 50
        for i, candidate in enumerate(updater.ranked_mirrors, start=1):
            if len(candidate.mirror_url) <= updater.url_char_len:
                stripped_mirror_url = candidate.mirror_url
            else:  # the mirror_url is too long, strip it
                stripped_mirror_url = candidate.mirror_url[:updater.
                                                           url_char_len - 3]
                stripped_mirror_url = stripped_mirror_url + "..."
                long_mirror_urls[
                    i] = candidate.mirror_url  # store it, output as full afterwards
            row = [
                i, stripped_mirror_url,
                "Yes" if candidate.is_available else "No",
                "Yes" if candidate.is_updating else "No"
            ]
            if have_last_updated:
                row.append("Up to date" if candidate.last_updated == 0 else (
                    "%s behind" %
                    format_timespan(candidate.last_updated, max_units=1)
                    if candidate.last_updated else "Unknown"))
            if have_bandwidth:
                row.append("%s/s" % format_size(round(candidate.bandwidth, 0))
                           if candidate.bandwidth else "Unknown")
            data.append(row)
        output(format_table(data, column_names=column_names))
        if long_mirror_urls:
            output(u"Full URLs which are too long to be shown in above table:")
            for key in long_mirror_urls:
                output(u"%i: %s", key, long_mirror_urls[key])
    else:
        output(u"\n".join(
            candidate.mirror_url for candidate in updater.ranked_mirrors
            if candidate.is_available and not candidate.is_updating))
    def benchmark(self,
                  directory,
                  iterations=2,
                  reset_caches=True,
                  silent=False):
        """
        Benchmark ``npm install``, ``npm-accel``, ``npm-cache`` and ``npm-fast-install``.

        :param directory: The pathname of a directory with a ``package.json`` file (a string).
        :param iterations: The number of times to run each installation command.
        :param reset_caches: :data:`True` to reset all caches before the first
                             iteration of each installation method,
                             :data:`False` otherwise.
        :param silent: Used to set :attr:`~executor.ExternalCommand.silent`.
        :raises: Any exceptions raised by the :mod:`executor.contexts` module.
        """
        results = []
        for name, label in (('npm', 'npm install'), ('npm-accel', 'npm-accel'),
                            ('npm-cache', 'npm-cache install npm'),
                            ('npm-fast-install', 'npm-fast-install')):
            # Reset all caches before the first run of each installer?
            if reset_caches:
                self.clear_directory('~/.npm')  # npm
                self.clear_directory('~/.npm-fast-install')  # npm-fast-install
                self.clear_directory('~/.package_cache')  # npm-cache
                self.clear_directory(self.cache_directory)  # npm-accel
            # Run the test twice, the first time to prime the cache
            # and the second time to actually use the cache.
            for i in range(1, iterations + 1):
                iteration_label = "iteration %i/%i" % (i, iterations)
                logger.info("Testing '%s' (%s) ..", label, iteration_label)
                self.clear_directory(os.path.join(directory, 'node_modules'))
                timer = Timer()
                if name == 'npm-accel':
                    self.installer_name = 'npm'
                    self.read_from_cache = True
                    self.write_to_cache = True
                else:
                    self.installer_name = name
                    self.read_from_cache = False
                    self.write_to_cache = False
                self.install(directory, silent=silent)
                results.append((label, iteration_label, str(timer)))
                logger.info("Took %s for '%s' (%s).", timer, label,
                            iteration_label)
        print(
            format_table(
                results,
                column_names=["Approach", "Iteration", "Elapsed time"]))
    def init_openocd():

        c = configuration.checkOpenocdTargetConfiguration()

        nn = NameNormalizer()
        if debug:
            log.debug("\r\nTarget configuration : \r\n %s \r\n" % format_table([(nn.normalize_name(n), c[n]) for n in c]))

        if c["protocol"] == "telnet":
            log.info("\r\nAttempt to configure Openocd Telnet target\r\n")

            return OpenocdTarget(c["config_file"], c["host"], int(c["port"]), c["base_dir"], c["exec_path"], c["options"], c["log_stdout"])

        elif  c["protocol"] == "gdb":
            log.info("\r\nAttempt to configure Openocd GDB MI target\r\n")

            return GdbserverTarget(c["config_file"], c["host"], int(c["port"]), c["exec_path"], c["options"], c["log_stdout"])

            raise NotImplementedError("Unimplmented GDB MI connection to Openocd Server")

        elif  c["protocol"] == "gdb_openocd":
            log.info("\r\nAttempt to configure Openocd GDB MI target\r\n")

            openocdjig = OpenocdJig(c["config_file"], c["exec_path"],  c["base_dir"], options=c["options"], debug=debug)

            return GdbserverTarget(c["config_file"], c["host"], int(c["port"]), c["exec_path"], c["options"], c["log_stdout"])

            raise NotImplementedError("Unimplmented GDB MI connection to Openocd Server")

        elif  c["protocol"] == "tcl":

            log.info("\r\nAttempt to configure Openocd TCL target\r\n")

            raise NotImplementedError("Unimplmented TCP TCL connection to Openocd Server")

        else :
            raise ValueError("Target configuration wrong : undefined target protocol %s !" % self.name)
Beispiel #8
0
    def start(self):

        assert(self._emulator), "Emulator is not initialized"
        assert(self._target), "Target is not initialized"
        assert(self._events)

        if self.is_initialized == False :
            self._init()

        try:
            self._events.start()
            log.info("Event dispatcher started")

            self._emulator.set_read_request_handler(self._call_proxy.handle_emulator_read_request)
            self._emulator.set_write_request_handler(self._call_proxy.handle_emulator_write_request)
            self._emulator.set_set_cpu_state_request_handler(self._call_proxy.handle_emulator_set_cpu_state_request)
            self._emulator.set_get_cpu_state_request_handler(self._call_proxy.handle_emulator_get_cpu_state_request)
            self._emulator.set_continue_request_handler(self._call_proxy.handle_emulator_continue_request)
            self._emulator.set_get_checksum_request_handler(self._call_proxy.handle_emulator_get_checksum_request)
            self._call_proxy.set_target(self._target)
            log.info("Hook installed")

            self._target.start()
            log.info("Target started")

            self._emulator.start()
            log.info("Emulator started")

            self._started = True
        except (FileNotFoundError, ConnectionRefusedError) as e :
            log.critical("Fail to start : \r\n"+e+"\r\n")
            self.stop()

        nn = NameNormalizer()

        info = {"Version" : "2.0", "compatibility": "1/2", "Testing Support" : "S2E/Klee", "Debugger" : "SuperspeeedJTag/OpenOCD/GDB"}
        log.info("\r\nAvatar : The Dynamic Analysis Framework for Embedded Systems V2.0 : \r\n %s \r\n" % format_table([(nn.normalize_name(n), info[n]) for n in info]))