示例#1
0
    def set_cpu_frequency(self, cpu, frequency, exact=True):
        """
        Set's the minimum value for CPU frequency. Actual frequency will
        depend on the Governor used and may vary during execution. The value should be
        either an int or a string representing an integer.

        If ``exact`` flag is set (the default), the Value must also be supported by
        the device. The available frequencies can be obtained by calling
        get_available_frequencies() or examining

        /sys/devices/system/cpu/cpuX/cpufreq/scaling_available_frequencies

        on the device (if it exists).

        :raises: ConfigError if the frequency is not supported by the CPU.
        :raises: DeviceError if, for some reason, frequency could not be set.

        """
        if isinstance(cpu, int):
            cpu = 'cpu{}'.format(cpu)
        try:
            value = int(frequency)
            if exact:
                available_frequencies = self.list_available_cpu_frequencies(cpu)
                if available_frequencies and value not in available_frequencies:
                    raise ConfigError('Can\'t set {} frequency to {}\nmust be in {}'.format(cpu,
                                                                                            value,
                                                                                            available_frequencies))
            if self.get_cpu_governor(cpu) != 'userspace':
                raise ConfigError('Can\'t set {} frequency; governor must be "userspace"'.format(cpu))
            sysfile = '/sys/devices/system/cpu/{}/cpufreq/scaling_setspeed'.format(cpu)
            self.device.set_sysfile_value(sysfile, value, verify=False)
        except ValueError:
            raise ValueError('frequency must be an integer; got: "{}"'.format(value))
示例#2
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)
示例#3
0
    def validate(self):  # pylint: disable=too-many-branches
        if not daq:
            raise ImportError(import_error_mesg)
        self._results = None
        self._metrics = set()
        if self.labels:
            if len(self.labels) != len(self.resistor_values):
                raise ConfigError('Number of DAQ port labels does not match the number of resistor values.')

            duplicates = set([x for x in self.labels if self.labels.count(x) > 1])
            if len(duplicates) > 0:
                raise ConfigError('Duplicate labels: {}'.format(', '.join(duplicates)))
        else:
            self.labels = ['PORT_{}'.format(i) for i, _ in enumerate(self.resistor_values)]
        self.server_config = ServerConfiguration(host=self.server_host,
                                                 port=self.server_port)
        self.device_config = DeviceConfiguration(device_id=self.device_id,
                                                 v_range=self.v_range,
                                                 dv_range=self.dv_range,
                                                 sampling_rate=self.sampling_rate,
                                                 resistor_values=self.resistor_values,
                                                 channel_map=self.channel_map,
                                                 labels=self.labels)
        try:
            self.server_config.validate()
            self.device_config.validate()
        except ConfigurationError, ex:
            raise ConfigError('DAQ configuration: ' + ex.message)  # Re-raise as a WA error
示例#4
0
 def validate(self):
     if not daq:
         raise ImportError(import_error_mesg)
     self._results = None
     self._metrics = set()
     if self.labels:
         if not (len(self.labels) == len(self.resistor_values)):  # pylint: disable=superfluous-parens
             raise ConfigError(
                 'Number of DAQ port labels does not match the number of resistor values.'
             )
     else:
         self.labels = [
             'PORT_{}'.format(i) for i, _ in enumerate(self.resistor_values)
         ]
     self.server_config = ServerConfiguration(host=self.server_host,
                                              port=self.server_port)
     self.device_config = DeviceConfiguration(
         device_id=self.device_id,
         v_range=self.v_range,
         dv_range=self.dv_range,
         sampling_rate=self.sampling_rate,
         resistor_values=self.resistor_values,
         channel_map=self.channel_map,
         labels=self.labels)
     try:
         self.server_config.validate()
         self.device_config.validate()
     except ConfigurationError, ex:
         raise ConfigError('DAQ configuration: ' +
                           ex.message)  # Re-raise as a WA error
示例#5
0
def adb_get_device():
    """
    Returns the serial number of a connected android device.

    If there are more than one device connected to the machine, or it could not
    find any device connected, :class:`wlauto.exceptions.ConfigError` is raised.
    """
    _check_env()
    # TODO this is a hacky way to issue a adb command to all listed devices

    # The output of calling adb devices consists of a heading line then
    # a list of the devices sperated by new line
    # The last line is a blank new line. in otherwords, if there is a device found
    # then the output length is 2 + (1 for each device)
    output = adb_command('0', "devices").splitlines()  # pylint: disable=E1103
    output_length = len(output)
    if output_length == 3:
        # output[1] is the 2nd line in the output which has the device name
        # Splitting the line by '\t' gives a list of two indexes, which has
        # device serial in 0 number and device type in 1.
        return output[1].split('\t')[0]
    elif output_length > 3:
        raise ConfigError(
            'Number of discovered devices is {}, it should be 1'.format(
                output_length - 2))
    else:
        raise ConfigError('No device is connected and available')
示例#6
0
    def validate(self):
        if ipython.import_error_str:
            raise ResultProcessorError(ipython.import_error_str)

        if not jinja2:
            msg = '{} requires python-jinja2 package to be installed'.format(
                self.name)
            raise ResultProcessorError(msg)

        if self.show_notebook and not self.notebook_directory:
            raise ConfigError(
                'Requested "show_notebook" but no notebook_directory was specified'
            )

        if self.notebook_directory and not os.path.isdir(
                self.notebook_directory):
            raise ConfigError('notebook_directory {} does not exist'.format(
                self.notebook_directory))

        if self.show_html and not self.convert_to_html:  # pylint: disable=E0203
            self.convert_to_html = True
            self.logger.debug(
                'Assuming "convert_to_html" as "show_html" is set')

        if self.show_pdf and not self.convert_to_pdf:  # pylint: disable=E0203
            self.convert_to_pdf = True
            self.logger.debug('Assuming "convert_to_pdf" as "show_pdf" is set')
示例#7
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
示例#8
0
 def set_value(self, obj, value=None):
     if value is None:
         if self.default is not None:
             value = self.default
         elif self.mandatory:
             msg = 'No values specified for mandatory parameter {} in {}'
             raise ConfigError(msg.format(self.name, obj.name))
     else:
         try:
             value = self.kind(value)
         except (ValueError, TypeError):
             typename = self.get_type_name()
             msg = 'Bad value "{}" for {}; must be {} {}'
             article = get_article(typename)
             raise ConfigError(
                 msg.format(value, self.name, article, typename))
     current_value = getattr(obj, self.name, None)
     if current_value is None:
         setattr(obj, self.name, value)
     elif not isiterable(current_value):
         setattr(obj, self.name, value)
     else:
         new_value = current_value + [value]
         setattr(obj, self.name, new_value)
     if value is not None:
         if self.allowed_values:
             self._validate_allowed_values(obj, value)
         if self.constraint:
             self._validate_constraint(obj, value)
示例#9
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
示例#10
0
 def finalize(self):
     """This must be invoked once all configuration sources have been loaded. This will
     do the final processing, setting instrumentation and result processor configuration
     for the run And making sure that all the mandatory config has been specified."""
     if self._finalized:
         return
     if not self._agenda:
         raise ValueError(
             'Attempting to finalize run configuration before an agenda is loaded.'
         )
     self._finalize_config_list('instrumentation')
     self._finalize_config_list('result_processors')
     if not self.device:
         raise ConfigError('Device not specified in the config.')
     self._finalize_device_config()
     if not self.reboot_policy.reboot_on_each_spec:
         for spec in self.workload_specs:
             if spec.boot_parameters:
                 message = 'spec {} specifies boot_parameters; reboot policy must be at least "each_spec"'
                 raise ConfigError(message.format(spec.id))
     for spec in self.workload_specs:
         for globinst in self._global_instrumentation:
             if globinst not in spec.instrumentation:
                 spec.instrumentation.append(globinst)
         spec.validate()
     self._finalized = True
示例#11
0
    def execute(self, args):  # pylint: disable=no-self-use,too-many-branches,too-many-statements
        loader = ExtensionLoader(packages=settings.extension_packages,
                                 paths=settings.extension_paths)
        agenda = OrderedDict()
        agenda['config'] = OrderedDict(instrumentation=[], result_processors=[])
        agenda['global'] = OrderedDict(iterations=args.iterations)
        agenda['workloads'] = []
        device = None
        device_config = None
        for name in args.extensions:
            extcls = loader.get_extension_class(name)
            config = loader.get_default_config(name)
            del config['modules']

            if extcls.kind == 'workload':
                entry = OrderedDict()
                entry['name'] = extcls.name
                if name != extcls.name:
                    entry['label'] = name
                entry['params'] = config
                agenda['workloads'].append(entry)
            elif extcls.kind == 'device':
                if device is not None:
                    raise ConfigError('Specifying multiple devices: {} and {}'.format(device.name, name))
                device = extcls
                device_config = config
                agenda['config']['device'] = name
                agenda['config']['device_config'] = config
            else:
                if extcls.kind == 'instrument':
                    agenda['config']['instrumentation'].append(name)
                if extcls.kind == 'result_processor':
                    agenda['config']['result_processors'].append(name)
                agenda['config'][name] = config

        if args.include_runtime_params:
            if not device:
                if settings.device:
                    device = loader.get_extension_class(settings.device)
                    device_config = loader.get_default_config(settings.device)
                else:
                    raise ConfigError('-r option requires for a device to be in the list of extensions')
            rps = OrderedDict()
            for rp in device.runtime_parameters:
                if hasattr(rp, 'get_runtime_parameters'):
                    # a core parameter needs to be expanded for each of the
                    # device's cores, if they're avialable
                    for crp in rp.get_runtime_parameters(device_config.get('core_names', [])):
                        rps[crp.name] = None
                else:
                    rps[rp.name] = None
            agenda['global']['runtime_params'] = rps

        if args.output:
            wfh = open(args.output, 'w')
        else:
            wfh = sys.stdout
        yaml.dump(agenda, wfh, indent=4, default_flow_style=False)
        if args.output:
            wfh.close()
示例#12
0
 def validate(self):
     if not instrument_is_installed('trace-cmd'):
         raise ConfigError('To use cci_pmu_logger, trace-cmd instrument must also be enabled.')
     if not self.event_labels:  # pylint: disable=E0203
         self.event_labels = ['event_{}'.format(e) for e in self.events]
     elif len(self.events) != len(self.event_labels):
         raise ConfigError('cci_pmu_events and cci_pmu_event_labels must be of the same length.')
     if len(self.events) > NUMBER_OF_CCI_PMU_COUNTERS:
         raise ConfigError('The number cci_pmu_counters must be at most {}'.format(NUMBER_OF_CCI_PMU_COUNTERS))
示例#13
0
 def validate(self):
     # pylint: disable=access-member-before-definition
     if self.labels and len(self.power_domains) != len(self.labels):
         raise ConfigError('There should be exactly one label per power domain')
     if self.autostart:
         if self.host != 'localhost':  # pylint: disable=access-member-before-definition
             self.logger.warning('Ignoring host "%s" since autostart is set to "True"', self.host)
             self.host = "localhost"
     if (self.vid is None) != (self.pid is None):
         raise ConfigError('`vid` and `pid` must both be specified')
示例#14
0
 def _validate_allowed_values(self, obj, value):
     if 'list' in str(self.kind):
         for v in value:
             if v not in self.allowed_values:
                 msg = 'Invalid value {} for {} in {}; must be in {}'
                 raise ConfigError(msg.format(v, self.name, obj.name, self.allowed_values))
     else:
         if value not in self.allowed_values:
             msg = 'Invalid value {} for {} in {}; must be in {}'
             raise ConfigError(msg.format(value, self.name, obj.name, self.allowed_values))
示例#15
0
 def _validate_image_bundle(self, image_bundle):
     if not tarfile.is_tarfile(image_bundle):
         raise ConfigError('File {} is not a tarfile'.format(image_bundle))
     with tarfile.open(image_bundle) as tar:
         files = [tf.name for tf in tar.getmembers()]
         if not any(pf in files for pf in (
                 self.partitions_file_name,
                 '{}/{}'.format(files[0], self.partitions_file_name))):
             ConfigError(
                 'Image bundle does not contain the required partition file (see documentation)'
             )
示例#16
0
def _load_raw_struct(source):
    """Load a raw dict config structure from the specified source."""
    if isinstance(source, basestring):
        if os.path.isfile(source):
            raw = load_struct_from_file(filepath=source)
        else:
            raise ConfigError('File "{}" does not exit'.format(source))
    elif isinstance(source, dict):
        raw = source
    else:
        raise ConfigError('Unknown config source: {}'.format(source))
    return raw
示例#17
0
 def validate(self):
     if self.duration is None:
         if self.user_triggered is None:
             self.user_triggered = True
         elif self.user_triggered is False:
             self.duration = self.default_duration
     if self.user_triggered and self.duration:
         message = 'Manual Workload can either specify duration or be user triggered, but not both'
         raise ConfigError(message)
     if not self.user_triggered and not self.duration:
         raise ConfigError(
             'Either user_triggered must be ``True`` or duration must be > 0.'
         )
示例#18
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")
示例#19
0
def get_mapping(base_dir, partition_file):
    mapping = {}
    with open(partition_file) as pf:
        for line in pf:
            pair = line.split()
            if len(pair) != 2:
                ConfigError('partitions.txt is not properly formated')
            image_path = os.path.join(base_dir, pair[1])
            if not os.path.isfile(expand_path(image_path)):
                ConfigError(
                    'file {} was not found in the bundle or was misplaced'.
                    format(pair[1]))
            mapping[pair[0]] = image_path
    return mapping
示例#20
0
def validate_image_bundle(bundle):
    if not tarfile.is_tarfile(bundle):
        raise ConfigError(
            'Image bundle {} does not appear to be a valid TAR file.'.format(
                bundle))
    with tarfile.open(bundle) as tar:
        try:
            tar.getmember('config.txt')
        except KeyError:
            try:
                tar.getmember('./config.txt')
            except KeyError:
                msg = 'Tarball {} does not appear to be a valid image bundle (did not see config.txt).'
                raise ConfigError(msg.format(bundle))
示例#21
0
    def _merge_config(self, config):
        """
        Merge the settings specified by the ``config`` dict-like object into current
        configuration.

        """
        if not isinstance(config, dict):
            raise ValueError('config must be a dict; found {}'.format(
                config.__class__.__name__))

        for k, v in config.iteritems():
            k = identifier(k)
            if k in self.ext_loader.global_param_aliases:
                self._resolve_global_alias(k, v)
            elif k in self._general_config_map:
                self._set_run_config_item(k, v)
            elif self.ext_loader.has_extension(k):
                self._set_extension_config(k, v)
            elif k == 'device_config':
                self._set_raw_dict(k, v)
            elif k in ['instrumentation', 'result_processors']:
                # Instrumentation can be enabled and disabled by individual
                # workloads, so we need to track it in two places: a list of
                # all instruments for the run (as they will all need to be
                # initialized and installed, and a list of only the "global"
                # instruments which can then be merged into instrumentation
                # lists of individual workload specs.
                self._set_raw_list('_global_{}'.format(k), v)
                self._set_raw_list(k, v)
            elif k in self.ignore_names:
                pass
            else:
                raise ConfigError('Unknown configuration option: {}'.format(k))
示例#22
0
 def __init__(self, policy):
     policy = policy.strip().lower().replace(' ', '_')
     if policy not in self.valid_policies:
         message = 'Invalid reboot policy {}; must be one of {}'.format(
             policy, ', '.join(self.valid_policies))
         raise ConfigError(message)
     self.policy = policy
示例#23
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.')
示例#24
0
    def set_runtime_parameters(self, params):
        """
        The parameters are taken from the keyword arguments and are specific to
        a particular device. See the device documentation.

        """
        runtime_parameters = self._expand_runtime_parameters()
        rtp_map = {rtp.name.lower(): rtp for rtp in runtime_parameters}

        params = OrderedDict(
            (k.lower(), v) for k, v in params.iteritems() if v is not None)

        expected_keys = rtp_map.keys()
        if not set(params.keys()) <= set(expected_keys):
            unknown_params = list(
                set(params.keys()).difference(set(expected_keys)))
            raise ConfigError(
                'Unknown runtime parameter(s): {}'.format(unknown_params))

        for param in params:
            self.logger.debug('Setting runtime parameter "{}"'.format(param))
            rtp = rtp_map[param]
            setter = getattr(self, rtp.setter)
            args = dict(rtp.setter_args.items() +
                        [(rtp.value_name, params[rtp.name.lower()])])
            setter(**args)
示例#25
0
    def _verify_and_deploy_benchmark(self, benchspec, cpumap):  # pylint: disable=R0914
        """Verifies that the supplied benchmark spec is valid and deploys the required assets
        to the device (if necessary). Returns a list of command specs (one for each CPU cluster)
        that can then be used to construct the final command."""
        bench = self.loaded_benchmarks[benchspec]
        basename = benchspec.split('.')[0]
        datadir = self.device.path.join(self.device.working_directory,
                                        self.name, basename)
        if self.force_push_assets or not self.device.file_exists(datadir):
            self.device.execute('mkdir -p {}'.format(datadir))
            for datafile in bench.datafiles:
                self.device.push_file(
                    datafile,
                    self.device.path.join(datadir, os.path.basename(datafile)))

        if self.mode == 'speed':
            cpus = [self._get_fastest_cpu().lower()]
        else:
            cpus = cpumap.keys()

        cmdspecs = []
        for cpu in cpus:
            try:
                host_bin_file = bench.get_binary(cpu)
            except ValueError, e:
                try:
                    msg = e.message
                    msg += ' Attempting to use generic binary instead.'
                    self.logger.debug(msg)
                    host_bin_file = bench.get_binary('generic')
                    cpu = 'generic'
                except ValueError, e:
                    raise ConfigError(e.message)  # re-raising as user error
示例#26
0
    def flash(self, image_bundle=None, images=None, recreate_uefi_entry=True):  # pylint: disable=arguments-differ
        device = self.owner
        if not hasattr(device, 'port') or not hasattr(device,
                                                      'microsd_mount_point'):
            msg = 'Device {} does not appear to support VExpress flashing.'
            raise ConfigError(msg.format(device.name))
        with open_serial_connection(port=device.port,
                                    baudrate=device.baudrate,
                                    timeout=device.timeout,
                                    init_dtr=0) as target:
            target.sendline(
                'usb_on'
            )  # this will cause the MicroSD to be mounted on the host
            device.wait_for_microsd_mount_point(target)
            self.deploy_images(device, image_bundle, images)

        self.logger.debug('Resetting the device.')
        device.hard_reset()

        with open_serial_connection(port=device.port,
                                    baudrate=device.baudrate,
                                    timeout=device.timeout,
                                    init_dtr=0) as target:
            menu = UefiMenu(target)
            menu.open(timeout=300)
            if recreate_uefi_entry and menu.has_option(device.uefi_entry):
                self.logger.debug('Deleting existing device entry.')
                menu.delete_entry(device.uefi_entry)
                menu.create_entry(device.uefi_entry, device.uefi_config)
            elif not menu.has_option(device.uefi_entry):
                menu.create_entry(device.uefi_entry, device.uefi_config)
            menu.select(device.uefi_entry)
            target.expect(device.android_prompt, timeout=device.timeout)
def ssh_get_shell(host,
                  username,
                  password=None,
                  keyfile=None,
                  port=None,
                  timeout=10,
                  telnet=False):
    _check_env()
    if telnet:
        if keyfile:
            raise ConfigError(
                'keyfile may not be used with a telnet connection.')
        conn = TelnetConnection()
    else:  # ssh
        conn = pxssh.pxssh()  # pylint: disable=redefined-variable-type
    try:
        if keyfile:
            conn.login(host,
                       username,
                       ssh_key=keyfile,
                       port=port,
                       login_timeout=timeout)
        else:
            conn.login(host,
                       username,
                       password,
                       port=port,
                       login_timeout=timeout)
    except EOF:
        raise DeviceError(
            'Could not connect to {}; is the host name correct?'.format(host))
    return conn
示例#28
0
    def initialize(self, context):
        if not self.device.is_rooted and self.as_root:
            raise ConfigError('The device is not rooted, cannot run poller as root.')
        host_poller = context.resolver.get(Executable(self, self.device.abi,
                                                      "poller"))
        target_poller = self.device.install(host_poller)

        expanded_paths = []
        for path in self.files:
            if "*" in path:
                for p in self.device.listdir(path):
                    expanded_paths.append(p)
            else:
                expanded_paths.append(path)
        self.files = expanded_paths
        if not self.labels:
            self.labels = self._generate_labels()

        self.target_output_path = self.device.path.join(self.device.working_directory, 'poller.csv')
        self.target_log_path = self.device.path.join(self.device.working_directory, 'poller.log')
        self.command = '{} -t {} -l {} {} > {} 2>{}'.format(target_poller,
                                                            self.sample_interval * 1000,
                                                            ','.join(self.labels),
                                                            ' '.join(self.files),
                                                            self.target_output_path,
                                                            self.target_log_path)
示例#29
0
    def set_cpu_governor(self, cpu, governor, **kwargs):
        """
        Set the governor for the specified CPU.
        See https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt

        :param cpu: The CPU for which the governor is to be set. This must be
                    the full name as it appears in sysfs, e.g. "cpu0".
        :param governor: The name of the governor to be used. This must be
                         supported by the specific device.

        Additional keyword arguments can be used to specify governor tunables for
        governors that support them.

        :note: On big.LITTLE all cores in a cluster must be using the same governor.
               Setting the governor on any core in a cluster will also set it on all
               other cores in that cluster.

        :raises: ConfigError if governor is not supported by the CPU.
        :raises: DeviceError if, for some reason, the governor could not be set.

        """
        if isinstance(cpu, int):
            cpu = 'cpu{}'.format(cpu)
        supported = self.list_available_cpu_governors(cpu)
        if governor not in supported:
            raise ConfigError('Governor {} not supported for cpu {}'.format(governor, cpu))
        sysfile = '/sys/devices/system/cpu/{}/cpufreq/scaling_governor'.format(cpu)
        self.device.set_sysfile_value(sysfile, governor)
        self.set_cpu_governor_tunables(cpu, governor, **kwargs)
示例#30
0
    def set_cpu_governor_tunables(self, cpu, governor, **kwargs):
        """
        Set tunables for the specified governor. Tunables should be specified as
        keyword arguments. Which tunables and values are valid depends on the
        governor.

        :param cpu: The cpu for which the governor will be set. This must be the
                    full cpu name as it appears in sysfs, e.g. ``cpu0``.
        :param governor: The name of the governor. Must be all lower case.

        The rest should be keyword parameters mapping tunable name onto the value to
        be set for it.

        :raises: ConfigError if governor specified is not a valid governor name, or if
                 a tunable specified is not valid for the governor.
        :raises: DeviceError if could not set tunable.


        """
        if isinstance(cpu, int):
            cpu = 'cpu{}'.format(cpu)
        valid_tunables = self.list_available_cpu_governor_tunables(cpu)
        for tunable, value in kwargs.iteritems():
            if tunable in valid_tunables:
                try:
                    path = '/sys/devices/system/cpu/{}/cpufreq/{}/{}'.format(cpu, governor, tunable)
                    self.device.set_sysfile_value(path, value)
                except DeviceError:  # May be an older kernel
                    path = '/sys/devices/system/cpu/cpufreq/{}/{}'.format(governor, tunable)
                    self.device.set_sysfile_value(path, value)
            else:
                message = 'Unexpected tunable {} for governor {} on {}.\n'.format(tunable, governor, cpu)
                message += 'Available tunables are: {}'.format(valid_tunables)
                raise ConfigError(message)