Exemplo n.º 1
0
    def _start_servod(self):
        in_chroot = False if which('dut-control') is None else True
        password = ''
        if not in_chroot:
            msg = 'Instrument %s requires sudo access on this machine to start `servod`'
            self.logger.info(msg, self.name)
            self.logger.info('You need to be sudoer to use it.')
            password = getpass.getpass()
            check = subprocess.call('echo {} | sudo -S ls > /dev/null'.format(password), shell=True)
            if check:
                raise InstrumentError('Given password was either wrong or you are not a sudoer')
        self.server_session = CrosSdkSession(self.chroot_path, password=password)
        password = ''

        command = 'sudo servod -b {b} -c {b}.xml'
        if self.vid and self.pid:
            command += " -v " + self.vid
            command += " -p " + self.pid
        command += '&'
        self.server_session.send_command(command.format(b=self.board_name))
        for _ in xrange(self.servod_max_tries):
            server_lines = self.server_session.get_lines(timeout=1, from_stderr=True,
                                                         timeout_only_for_first_line=False)
            if server_lines:
                if 'Listening on' in server_lines[-1]:
                    self.port = int(server_lines[-1].split()[-1])
                    break
            time.sleep(self.servod_delay_between_tries)
        else:
            raise InstrumentError('Failed to start servod in cros_sdk environment')
Exemplo n.º 2
0
    def perform_runtime_validation(self):
        if not self.device.is_rooted:
            raise InstrumentError(
                'the device must be rooted to generate energy models')
        if 'userspace' not in self.device.list_available_cluster_governors(0):
            raise InstrumentError('userspace cpufreq governor must be enabled')

        error_message = 'Frequency {} is not supported by {} cores'
        available_frequencies = self.device.list_available_core_frequencies(
            self.big_core)
        if self.big_frequencies:
            for freq in self.big_frequencies:
                if freq not in available_frequencies:
                    raise ConfigError(error_message.format(
                        freq, self.big_core))
        else:
            self.big_frequencies = available_frequencies
        available_frequencies = self.device.list_available_core_frequencies(
            self.little_core)
        if self.little_frequencies:
            for freq in self.little_frequencies:
                if freq not in available_frequencies:
                    raise ConfigError(
                        error_message.format(freq, self.little_core))
        else:
            self.little_frequencies = available_frequencies
Exemplo n.º 3
0
 def _generate_report_on_host(self, context):
     local_trace_file = os.path.join(context.output_directory,
                                     OUTPUT_TRACE_FILE)
     local_txt_trace_file = os.path.join(context.output_directory,
                                         OUTPUT_TEXT_FILE)
     command = 'trace-cmd report {} > {}'.format(local_trace_file,
                                                 local_txt_trace_file)
     self.logger.debug(command)
     if not os.path.isfile(local_trace_file):
         self.logger.warning(
             'Not generating trace.txt, as {} does not exist.'.format(
                 OUTPUT_TRACE_FILE))
     else:
         try:
             process = subprocess.Popen(command,
                                        stderr=subprocess.PIPE,
                                        shell=True)
             _, error = process.communicate()
             if process.returncode:
                 raise InstrumentError(
                     'trace-cmd returned non-zero exit code {}'.format(
                         process.returncode))
             if error:
                 # logged at debug level, as trace-cmd always outputs some
                 # errors that seem benign.
                 self.logger.debug(error)
         except OSError:
             raise InstrumentError(
                 'Could not find trace-cmd. Please make sure it is installed and is in PATH.'
             )
Exemplo n.º 4
0
 def initialize(self, context):
     status, devices = self._execute_command('list_devices')
     if status == daq.Status.OK and not devices:
         raise InstrumentError(
             'DAQ: server did not report any devices registered with the driver.'
         )
     self._results = OrderedDict()
     self.gpio_path = None
     if self.gpio_sync:
         if not self.device.file_exists(GPIO_ROOT):
             raise InstrumentError('GPIO sysfs not enabled on the device.')
         try:
             export_path = self.device.path.join(GPIO_ROOT, 'export')
             self.device.set_sysfile_value(export_path,
                                           self.gpio_sync,
                                           verify=False)
             pin_root = self.device.path.join(
                 GPIO_ROOT, 'gpio{}'.format(self.gpio_sync))
             direction_path = self.device.path.join(pin_root, 'direction')
             self.device.set_sysfile_value(direction_path, 'out')
             self.gpio_path = self.device.path.join(pin_root, 'value')
             self.device.set_sysfile_value(self.gpio_path, 0, verify=False)
             signal.connect(self.insert_start_marker,
                            signal.BEFORE_WORKLOAD_EXECUTION,
                            priority=11)
             signal.connect(self.insert_stop_marker,
                            signal.AFTER_WORKLOAD_EXECUTION,
                            priority=11)
         except DeviceError as e:
             raise InstrumentError(
                 'Could not configure GPIO on device: {}'.format(e))
Exemplo n.º 5
0
 def on_run_start(self, context):
     if subprocess.call('which caiman', stdout=subprocess.PIPE, shell=True):
         raise InstrumentError('caiman not in PATH. Cannot enable Streamline tracing.')
     p = subprocess.Popen('caiman --version 2>&1', stdout=subprocess.PIPE, shell=True)
     out, _ = p.communicate()
     match = VERSION_REGEX.search(out)
     if not match:
         raise InstrumentError('caiman not in PATH. Cannot enable Streamline tracing.')
     version_tuple = tuple(map(int, match.group(1).split('.')))
     if version_tuple < (5, 17):
         raise InstrumentError('Need DS-5 v5.17 or greater; found v{}'.format(match.group(1)))
     self.enabled = True
     self.resource_getter = _instantiate(context.resolver)
     self.resource_getter.register()
Exemplo n.º 6
0
 def validate(self):
     if not which('streamline'):
         raise InstrumentError(
             'streamline not in PATH. Cannot enable Streamline tracing.')
     p = subprocess.Popen('streamline --version 2>&1',
                          stdout=subprocess.PIPE,
                          shell=True)
     out, _ = p.communicate()
     match = VERSION_REGEX.search(out)
     if not match:
         raise InstrumentError('Could not find streamline version.')
     version_tuple = tuple(map(int, match.group(1).split('.')))
     if version_tuple < (5, 17):
         raise InstrumentError(
             'Need DS-5 v5.17 or greater; found v{}'.format(match.group(1)))
Exemplo n.º 7
0
    def update_result(self, context):  # pylint: disable=r0201
        self.logger.debug("Waiting for atrace to finish dumping data")
        self.p.wait()
        context.device.pull_file(self.output_file, context.output_directory)
        cmd = "python {} --from-file={} -o {}"
        cmd = cmd.format(
            os.path.join(os.environ['ANDROID_HOME'],
                         "platform-tools/systrace/systrace.py"),
            os.path.join(context.output_directory, "atrace.txt"),
            os.path.join(context.output_directory, "systrace.html"))
        self.logger.debug(cmd)
        _, error = check_output(cmd.split(" "), timeout=10)
        if error:
            raise InstrumentError(error)

        context.add_iteration_artifact('atrace.txt',
                                       path=os.path.join(
                                           context.output_directory,
                                           "atace.txt"),
                                       kind='data',
                                       description='atrace dump.')
        context.add_iteration_artifact('systrace.html',
                                       path=os.path.join(
                                           context.output_directory,
                                           "systrace.html"),
                                       kind='data',
                                       description='Systrace HTML report.')
Exemplo n.º 8
0
 def _execute_command(self, command, **kwargs):
     # pylint: disable=E1101
     q = Queue()
     p = Process(target=_send_daq_command, args=(q, self.server_config, command), kwargs=kwargs)
     p.start()
     result = q.get()
     p.join()
     if result.status == daq.Status.OK:
         pass  # all good
     elif result.status == daq.Status.OKISH:
         self.logger.debug(result.message)
     elif result.status == daq.Status.ERROR:
         raise InstrumentError('DAQ: {}'.format(result.message))
     else:
         raise InstrumentError('DAQ: Unexpected result: {} - {}'.format(result.status, result.message))
     return (result.status, result.data)
Exemplo n.º 9
0
 def validate(self):
     if not pd or LooseVersion(pd.__version__) < LooseVersion('0.13.1'):
         message = ('fps instrument requires pandas Python package (version 0.13.1 or higher) to be installed.\n'
                    'You can install it with pip, e.g. "sudo pip install pandas"')
         raise InstrumentError(message)
     if self.crash_check and not instrument_is_installed('execution_time'):
         raise ConfigError('execution_time instrument must be installed in order to check for content crash.')
Exemplo n.º 10
0
 def validate(self):
     if import_error:
         message = 'energy_model instrument requires pandas, jinja2 and matplotlib Python packages to be installed; got: "{}"'
         raise InstrumentError(message.format(import_error.message))
     for capability in ['cgroups', 'cpuidle']:
         if not self.device.has(capability):
             message = 'The Device does not appear to support {}; does it have the right module installed?'
             raise ConfigError(message.format(capability))
     device_cores = set(self.device.core_names)
     if (self.power_metric
             and self.energy_metric) or not (self.power_metric
                                             or self.energy_metric):
         raise ConfigError(
             'Either power_metric or energy_metric must be specified (but not both).'
         )
     if not device_cores:
         raise ConfigError(
             'The Device does not appear to have core_names configured.')
     elif len(device_cores) != 2:
         raise ConfigError(
             'The Device does not appear to be a big.LITTLE device.')
     if self.big_core and self.big_core not in self.device.core_names:
         raise ConfigError('Specified big_core "{}" is in divice {}'.format(
             self.big_core, self.device.name))
     if not self.big_core:
         self.big_core = self.device.core_names[
             -1]  # the last core is usually "big" in existing big.LITTLE devices
     if not self.device_name:
         self.device_name = self.device.name
     if self.num_of_freqs_to_thermal_adjust and not instrument_is_installed(
             'daq'):
         self.logger.warn(
             'Adjustment for thermal effect requires daq instrument. Disabling adjustment'
         )
         self.num_of_freqs_to_thermal_adjust = 0
Exemplo n.º 11
0
    def validate(self):
        if (self.temperature_between_specs is not None
                and self.fixed_between_specs is not None):
            raise ConfigError(
                'Both fixed delay and thermal threshold specified for specs.')

        if (self.temperature_between_iterations is not None
                and self.fixed_between_iterations is not None):
            raise ConfigError(
                'Both fixed delay and thermal threshold specified for iterations.'
            )

        if (self.temperature_before_start is not None
                and self.fixed_before_start is not None):
            raise ConfigError(
                'Both fixed delay and thermal threshold specified before start.'
            )

        if not any([
                self.temperature_between_specs, self.fixed_between_specs,
                self.temperature_before_start,
                self.temperature_between_iterations,
                self.fixed_between_iterations, self.fixed_before_start
        ]):
            raise ConfigError(
                'delay instrument is enabled, but no delay is specified.')

        if self.active_cooling and not self.device.has('active_cooling'):
            message = 'Your device does not support active cooling. Did you configure it with an approprite module?'
            raise InstrumentError(message)
Exemplo n.º 12
0
 def stop(self, context):
     self.stop_time = time.time()  # pylint: disable=attribute-defined-outside-init
     if self.mode == 'start':
         self.device.execute('{} stop'.format(self.trace_cmd),
                             timeout=60,
                             as_root=True)
     elif self.mode == 'record':
         # There will be a trace-cmd worker process per CPU core plus a main
         # control trace-cmd process. Interrupting the control process will
         # trigger the generation of the single binary trace file.
         trace_cmds = self.device.ps(name=self.trace_cmd)
         if not trace_cmds:
             raise InstrumentError(
                 'Could not find running trace-cmd on device.')
         # The workers will have their PPID set to the PID of control.
         parent_map = defaultdict(list)
         for entry in trace_cmds:
             parent_map[entry.ppid].append(entry.pid)
         controls = [
             v[0] for _, v in parent_map.iteritems()
             if len(v) == 1 and v[0] in parent_map
         ]
         if len(controls) > 1:
             self.logger.warning(
                 'More than one trace-cmd instance found; stopping all of them.'
             )
         for c in controls:
             self.device.kill(c, signal='INT', as_root=True)
     else:
         raise ValueError('Bad mode: {}'.format(
             self.mode))  # should never get here
Exemplo n.º 13
0
 def initialize(self, context):
     if self.device.platform != 'android':
         raise InstrumentError(
             'nestats instrument is only supported on Android devices.')
     apk = context.resolver.get(ApkFile(self))
     self.collector = NetstatsCollector(self.device, apk)  # pylint: disable=attribute-defined-outside-init
     self.collector.setup(force=self.force_reinstall)
Exemplo n.º 14
0
    def get_cluster_specs(self, old_specs, cluster, context):
        core = self.get_core_name(cluster)
        self.number_of_cpus[cluster] = sum([1 for c in self.device.core_names if c == core])

        cluster_frequencies = self.get_frequencies_param(cluster)
        if not cluster_frequencies:
            raise InstrumentError('Could not read available frequencies for {}'.format(core))
        min_frequency = min(cluster_frequencies)

        idle_states = self.get_device_idle_states(cluster)
        new_specs = []
        for state in idle_states:
            for num_cpus in xrange(1, self.number_of_cpus[cluster] + 1):
                spec = old_specs[0].copy()
                spec.workload_name = self.idle_workload
                spec.workload_parameters = self.idle_workload_params
                spec.idle_state_id = state.id
                spec.idle_state_desc = state.desc
                spec.idle_state_index = state.index
                if not self.no_hotplug:
                    spec.runtime_parameters['{}_cores'.format(core)] = num_cpus
                spec.runtime_parameters['{}_frequency'.format(core)] = min_frequency
                spec.runtime_parameters['ui'] = 'off'
                spec.cluster = cluster
                spec.num_cpus = num_cpus
                spec.id = '{}_idle_{}_{}'.format(cluster, state.id, num_cpus)
                spec.label = 'idle_{}'.format(cluster)
                spec.number_of_iterations = old_specs[0].number_of_iterations
                spec.load(self.device, context.config.ext_loader)
                spec.workload.init_resources(context)
                spec.workload.validate()
                new_specs.append(spec)
        for old_spec in old_specs:
            if old_spec.workload_name not in ['sysbench', 'dhrystone']:
                raise ConfigError('Only sysbench and dhrystone workloads currently supported for energy_model generation.')
            for freq in cluster_frequencies:
                for num_cpus in xrange(1, self.number_of_cpus[cluster] + 1):
                    spec = old_spec.copy()
                    spec.runtime_parameters['{}_frequency'.format(core)] = freq
                    if not self.no_hotplug:
                        spec.runtime_parameters['{}_cores'.format(core)] = num_cpus
                    spec.runtime_parameters['ui'] = 'off'
                    spec.id = '{}_{}_{}'.format(cluster, num_cpus, freq)
                    spec.label = 'freq_{}_{}'.format(cluster, spec.label)
                    spec.workload_parameters['taskset_mask'] = list_to_mask(self.get_cpus(cluster))
                    spec.workload_parameters['threads'] = num_cpus
                    if old_spec.workload_name == 'sysbench':
                        # max_requests set to an arbitrary high values to make sure
                        # sysbench runs for full duriation even on highly
                        # performant cores.
                        spec.workload_parameters['max_requests'] = 10000000
                    spec.cluster = cluster
                    spec.num_cpus = num_cpus
                    spec.frequency = freq
                    spec.load(self.device, context.config.ext_loader)
                    spec.workload.init_resources(context)
                    spec.workload.validate()
                    new_specs.append(spec)
        return new_specs
Exemplo n.º 15
0
 def _check_has_valid_display(self):  # pylint: disable=R0201
     reason = None
     if os.name == 'posix' and not os.getenv('DISPLAY'):
         reason = 'DISPLAY is not set.'
     else:
         p = subprocess.Popen('xhost', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
         _, error = p.communicate()
         if p.returncode:
             reason = 'Invalid DISPLAY; xhost returned: "{}".'.format(error.strip())  # pylint: disable=E1103
     if reason:
         raise InstrumentError('{}\nstreamline binary requires a valid display server to be running.'.format(reason))
Exemplo n.º 16
0
    def slow_update_result(self, context):  # pylint: disable=too-many-branches
        spec = context.result.spec
        cluster = spec.cluster
        is_freq_iteration = spec.label.startswith('freq_')
        perf_metric = 0
        power_metric = 0
        thermal_adjusted_power = 0
        if is_freq_iteration and cluster == 'big':
            thermal_adjusted_power = self.thermal_correction(context)
        for metric in context.result.metrics:
            if metric.name == self.performance_metric:
                perf_metric = metric.value
            elif thermal_adjusted_power and metric.name in self.big_power_metrics:
                power_metric += thermal_adjusted_power * self.power_scaling_factor
            elif (cluster == 'big') and metric.name in self.big_power_metrics:
                power_metric += metric.value * self.power_scaling_factor
            elif (cluster
                  == 'little') and metric.name in self.little_power_metrics:
                power_metric += metric.value * self.power_scaling_factor
            elif thermal_adjusted_power and metric.name in self.big_energy_metrics:
                power_metric += thermal_adjusted_power / self.run_time * self.power_scaling_factor
            elif (cluster == 'big') and metric.name in self.big_energy_metrics:
                power_metric += metric.value / self.run_time * self.power_scaling_factor
            elif (cluster
                  == 'little') and metric.name in self.little_energy_metrics:
                power_metric += metric.value / self.run_time * self.power_scaling_factor

        if not (power_metric and (perf_metric or not is_freq_iteration)):
            message = 'Incomplete results for {} iteration{}'
            raise InstrumentError(
                message.format(context.result.spec.id,
                               context.current_iteration))

        if is_freq_iteration:
            index_matter = [
                cluster, spec.num_cpus, spec.frequency,
                context.result.iteration
            ]
            data = self.freq_data
        else:
            index_matter = [
                cluster, spec.num_cpus, spec.idle_state_id,
                spec.idle_state_desc, context.result.iteration
            ]
            data = self.idle_data
            if self.no_hotplug:
                # due to that fact that hotpluging was disabled, power has to be artificially scaled
                # to the number of cores that should have been active if hotplugging had occurred.
                power_metric = spec.num_cpus * (power_metric /
                                                self.number_of_cpus[cluster])

        data.append(index_matter + ['performance', perf_metric])
        data.append(index_matter + ['power', power_metric])
Exemplo n.º 17
0
 def validate(self):
     if self.report and os.system('which trace-cmd > /dev/null'):
         raise InstrumentError('trace-cmd is not in PATH; is it installed?')
     if self.buffer_size:
         if self.mode == 'record':
             self.logger.debug(
                 'trace_buffer_size specified with record mode; it will be ignored.'
             )
         else:
             try:
                 int(self.buffer_size)
             except ValueError:
                 raise ConfigError('trace_buffer_size must be an int.')
Exemplo n.º 18
0
 def _generate_report_on_target(self, context):
     try:
         trace_file = self.output_file
         txt_trace_file = os.path.join(self.device.working_directory,
                                       OUTPUT_TEXT_FILE)
         command = 'trace-cmd report {} > {}'.format(
             trace_file, txt_trace_file)
         self.device.execute(command)
         self.device.pull_file(txt_trace_file,
                               context.output_directory,
                               timeout=self._pull_timeout)
     except DeviceError:
         raise InstrumentError('Could not generate TXT report on target.')
Exemplo n.º 19
0
    def update_result(self, context):
        host_output_file = os.path.join(context.output_directory, 'poller.csv')
        self.device.pull_file(self.target_output_path, host_output_file)
        context.add_artifact('poller_output', host_output_file, kind='data')
        host_log_file = os.path.join(context.output_directory, 'poller.log')
        self.device.pull_file(self.target_log_path, host_log_file)
        context.add_artifact('poller_log', host_log_file, kind='log')

        with open(host_log_file) as fh:
            for line in fh:
                if 'ERROR' in line:
                    raise InstrumentError(line.strip())
                if 'WARNING' in line:
                    self.logger.warning(line.strip())
Exemplo n.º 20
0
 def validate(self):
     if subprocess.call('which caiman', stdout=subprocess.PIPE, shell=True):
         raise InstrumentError(
             'caiman not in PATH. Cannot enable energy probe')
     if not self.resistor_values:
         raise ConfigError('At least one resistor value must be specified')
     if len(self.resistor_values) > self.MAX_CHANNELS:
         raise ConfigError(
             '{} Channels where specified when Energy Probe supports up to {}'
             .format(len(self.resistor_values), self.MAX_CHANNELS))
     if pandas is None:
         self.logger.warning(
             "pandas package will significantly speed up this instrument")
         self.logger.warning("to install it try: pip install pandas")
Exemplo n.º 21
0
    def _start_daemon(self):
        self.logger.debug('Starting gatord')
        self.device.killall('gatord', as_root=True)
        if self.configuration_file:
            command = '{} -c {}'.format(self.daemon, self.on_device_config)
        else:

            command = '{}'.format(self.daemon)

        self.daemon_process = self.device.execute(command, as_root=True, background=True)
        outlogger = StreamLogger('gatord', self.daemon_process.stdout)
        errlogger = StreamLogger('gatord', self.daemon_process.stderr, logging.ERROR)
        outlogger.start()
        errlogger.start()
        if self.daemon_process.poll() is not None:
            # If adb returned, something went wrong.
            raise InstrumentError('Could not start gatord.')
Exemplo n.º 22
0
 def update_result(self, context):
     for sensor in self.sensors:
         try:
             report_type, units, conversion = HWMON_SENSORS[sensor.kind]
             if report_type == 'diff':
                 before, after = sensor.readings
                 diff = conversion(after - before)
                 context.result.add_metric(sensor.label, diff, units)
             elif report_type == 'before/after':
                 before, after = sensor.readings
                 context.result.add_metric(sensor.label + ' before', conversion(before), units)
                 context.result.add_metric(sensor.label + ' after', conversion(after), units)
             else:
                 raise InstrumentError('Unexpected report_type: {}'.format(report_type))
         except ValueError, e:
             self.logger.error('Could not collect all {} readings for {}'.format(sensor.kind, sensor.label))
             self.logger.error('Got: {}'.format(e))
Exemplo n.º 23
0
    def initialize(self, context):
        # pylint: disable=access-member-before-definition
        self.poller = None
        self.data = None
        self.stopped = True

        if self.device.platform != "chromeos":
            raise InstrumentError("servo_power instrument only supports Chrome OS devices.")

        if not self.labels:
            self.labels = ["PORT_{}".format(channel) for channel, _ in enumerate(self.power_domains)]

        self.power_domains = [channel if channel.endswith("_mw") else
                              "{}_mw".format(channel) for channel in self.power_domains]
        self.label_map = {pd: l for pd, l in zip(self.power_domains, self.labels)}

        if self.autostart:
            self._start_servod()
Exemplo n.º 24
0
    def _initialize_run(self):
        self.context.runner = self
        self.context.run_info.start_time = datetime.utcnow()
        self._connect_to_device()
        self.logger.info('Initializing device')
        self.device.initialize(self.context)

        self.logger.info('Initializing workloads')
        for workload_spec in self.context.config.workload_specs:
            workload_spec.workload.initialize(self.context)

        props = self.device.get_properties(self.context)
        self.context.run_info.device_properties = props
        self.result_manager.initialize(self.context)
        self._send(signal.RUN_INIT)

        if instrumentation.check_failures():
            raise InstrumentError('Detected failure(s) during instrumentation initialization.')
Exemplo n.º 25
0
    def initialize(self, context):
        cmd_options = {}
        if context.device.get_sdk_version() >= 23:
            # Set up command line options
            if self.app_names:
                cmd_options["-a"] = ",".join(self.app_names)
            if self.buffer_size:
                cmd_options["-b"] = self.buffer_size
            if self.use_circular_buffer:
                cmd_options["-c"] = None
            if self.kernel_functions:
                cmd_options["-k"] = ",".join(self.kernel_functions)
            if self.ignore_signals:
                cmd_options["-n"] = None

            # Generate commands
            opt_string = ''.join([
                '{} {} '.format(name, value or "")
                for name, value in cmd_options.iteritems()
            ])
            self.start_cmd = "atrace --async_start {} {}".format(
                opt_string, " ".join(self.categories))
            self.output_file = os.path.join(self.device.working_directory,
                                            "atrace.txt")
            self.stop_cmd = "atrace --async_stop {} > {}".format(
                "-z" if self.compress_trace else "", self.output_file)

            # Check if provided categories are available on the device
            available_categories = [
                cat.strip().split(" - ")[0] for cat in context.device.execute(
                    "atrace --list_categories").splitlines()
            ]
            for category in self.categories:
                if category not in available_categories:
                    raise ConfigError(
                        "Unknown category '{}'; Must be one of: {}".format(
                            category, available_categories))
        else:
            raise InstrumentError(
                "Only android devices with an API level >= 23 can use systrace properly"
            )
Exemplo n.º 26
0
 def on_run_init(self, context):
     if not self.device.is_rooted:
         raise InstrumentError(
             'trace-cmd instrument cannot be used on an unrooted device.')
     if not self.no_install:
         host_file = context.resolver.get(
             Executable(self, self.device.abi, 'trace-cmd'))
         self.trace_cmd = self.device.install_executable(host_file)
     else:
         if not self.device.is_installed('trace-cmd'):
             raise ConfigError(
                 'No trace-cmd found on device and no_install=True is specified.'
             )
         self.trace_cmd = 'trace-cmd'
     # Register ourselves as absolute last event before and
     #   first after so we can mark the trace at the right time
     signal.connect(self.insert_start_mark,
                    signal.BEFORE_WORKLOAD_EXECUTION,
                    priority=11)
     signal.connect(self.insert_end_mark,
                    signal.AFTER_WORKLOAD_EXECUTION,
                    priority=11)
Exemplo n.º 27
0
 def initialize(self, context):
     self.monitor = None
     if self.device.platform != 'android':
         raise InstrumentError('screenon instrument currently only supports Android devices.')
Exemplo n.º 28
0
 def validate(self):
     if self.strict:
         if self.device.name.lower() != 'juno':
             message = 'juno_energy instrument is only supported on juno devices; found {}'
             raise InstrumentError(message.format(self.device.name))
Exemplo n.º 29
0
 def start(self, context):
     result = self.device.execute(self.start_cmd)
     if "error" in result:
         raise InstrumentError(result)
Exemplo n.º 30
0
    def initialize(self, context):  # pylint: disable=r0912
        if not self.device.is_rooted:
            raise InstrumentError(
                'The device must be rooted to sweep frequencies')

        if 'userspace' not in self.device.list_available_cluster_governors(0):
            raise InstrumentError(
                "'userspace' cpufreq governor must be enabled")

        # Create sweeps for each core type using num_cpus cores
        if not self.sweeps:
            self.sweeps = []
            for core in set(self.device.core_names):
                sweep_spec = {}
                sweep_spec['cluster'] = core
                sweep_spec['label'] = core
                self.sweeps.append(sweep_spec)

        new_specs = []
        old_specs = []
        for job in context.runner.job_queue:
            if job.spec not in old_specs:
                old_specs.append(job.spec)

        # Validate sweeps, add missing sections and create workload specs
        for i, sweep_spec in enumerate(self.sweeps):
            if 'cluster' not in sweep_spec:
                raise ConfigError('cluster must be define for all sweeps')
            # Check if cluster exists on device
            if caseless_string(
                    sweep_spec['cluster']) not in self.device.core_names:
                raise ConfigError(
                    'Only {} cores are present on this device, you specified {}'
                    .format(", ".join(set(self.device.core_names)),
                            sweep_spec['cluster']))

            # Default to all available frequencies
            if 'frequencies' not in sweep_spec:
                self.device.enable_cpu(
                    self.device.core_names.index(sweep_spec['cluster']))
                sweep_spec[
                    'frequencies'] = self.device.list_available_core_frequencies(
                        sweep_spec['cluster'])

            # Check that given frequencies are valid of the core cluster
            else:
                self.device.enable_cpu(
                    self.device.core_names.index(sweep_spec['cluster']))
                available_freqs = self.device.list_available_core_frequencies(
                    sweep_spec['cluster'])
                for freq in sweep_spec['frequencies']:
                    if freq not in available_freqs:
                        raise ConfigError(
                            'Frequency {} is not supported by {} cores'.format(
                                freq, sweep_spec['cluster']))

            # Add default labels
            if 'label' not in sweep_spec:
                sweep_spec['label'] = "sweep{}".format(i + 1)

            new_specs.extend(
                self.get_sweep_workload_specs(old_specs, sweep_spec, context))

        # Update config to refect jobs that will actually run.
        context.config.workload_specs = new_specs
        config_file = os.path.join(context.host_working_directory,
                                   'run_config.json')
        with open(config_file, 'wb') as wfh:
            context.config.serialize(wfh)
        context.runner.init_queue(new_specs)