示例#1
0
    def add_configs(self, plugin_name, values, source):
        if self.is_global_alias(plugin_name):
            self.add_global_alias(plugin_name, values, source)
            return

        if source not in self.sources:
            msg = "Source '{}' has not been added to the plugin cache."
            raise RuntimeError(msg.format(source))

        if caseless_string(plugin_name) in ['global', 'config']:
            msg = '"{}" entry specified inside config/global section; If this is ' \
                  'defined in a config file, move the entry content into the top level'
            raise ConfigError(msg.format((plugin_name)))

        if (not self.loader.has_plugin(plugin_name)
                and plugin_name not in self.targets
                and plugin_name not in GENERIC_CONFIGS):
            msg = 'configuration provided for unknown plugin "{}"'
            raise ConfigError(msg.format(plugin_name))

        if not hasattr(values, 'items'):
            msg = 'Plugin configuration for "{}" not a dictionary ({} is {})'
            raise ConfigError(
                msg.format(plugin_name, repr(values), type(values)))

        for name, value in values.items():
            if (plugin_name not in GENERIC_CONFIGS
                    and name not in self.get_plugin_parameters(plugin_name)):
                msg = "'{}' is not a valid parameter for '{}'"
                raise ConfigError(msg.format(name, plugin_name))

            self.plugin_configs[plugin_name][source][name] = value
    def add_configs(self, plugin_name, values, source):
        if self.is_global_alias(plugin_name):
            self.add_global_alias(plugin_name, values, source)
            return

        if source not in self.sources:
            msg = "Source '{}' has not been added to the plugin cache."
            raise RuntimeError(msg.format(source))

        if caseless_string(plugin_name) in ['global', 'config']:
            msg = '"{}" entry specified inside config/global section; If this is ' \
                  'defined in a config file, move the entry content into the top level'
            raise ConfigError(msg.format((plugin_name)))

        if (not self.loader.has_plugin(plugin_name) and
                plugin_name not in self.targets and
                plugin_name not in GENERIC_CONFIGS):
            msg = 'configuration provided for unknown plugin "{}"'
            raise ConfigError(msg.format(plugin_name))

        if not hasattr(values, 'items'):
            msg = 'Plugin configuration for "{}" not a dictionary ({} is {})'
            raise ConfigError(msg.format(plugin_name, repr(values), type(values)))

        for name, value in values.items():
            if (plugin_name not in GENERIC_CONFIGS and
                    name not in self.get_plugin_parameters(plugin_name)):
                msg = "'{}' is not a valid parameter for '{}'"
                raise ConfigError(msg.format(name, plugin_name))

            self.plugin_configs[plugin_name][source][name] = value
 def _get_state_ID(self, value):
     '''Checks passed state and converts to its ID'''
     value = caseless_string(value)
     for s_id, s_name, s_desc in self.values:
         if value == s_id or value == s_name or value == s_desc:
             return s_id
     msg = 'Invalid IdleState: "{}"; Must be in {}'
     raise ValueError(msg.format(value, self.values))
 def _get_state_ID(self, value):
     '''Checks passed state and converts to its ID'''
     value = caseless_string(value)
     for s_id, s_name, s_desc in self.values:
         if value == s_id or value == s_name or value == s_desc:
             return s_id
     msg = 'Invalid IdleState: "{}"; Must be in {}'
     raise ValueError(msg.format(value, self.values))
示例#5
0
def get_by_extension(path, ext):
    if not ext.startswith('.'):
        ext = '.' + ext
    ext = caseless_string(ext)

    found = []
    for entry in os.listdir(path):
        entry_ext = os.path.splitext(entry)[1]
        if entry_ext == ext:
            found.append(os.path.join(path, entry))
    return found
示例#6
0
def get_by_extension(path, ext):
    if not ext.startswith('.'):
        ext = '.' + ext
    ext = caseless_string(ext)

    found = []
    for entry in os.listdir(path):
        entry_ext = os.path.splitext(entry)[1]
        if entry_ext == ext:
            found.append(os.path.join(path, entry))
    return found
示例#7
0
    def execute(self, state, args):
        name = identifier(args.plugin)
        rst_output = None

        if name == caseless_string('settings'):
            rst_output = get_rst_for_global_config()
            rst_output += get_rst_for_envars()
            plugin_name = name.lower()
            kind = 'global:'
        else:
            try:
                plugin = pluginloader.get_plugin_class(name)
            except NotFoundError:
                plugin = None
            if plugin:
                rst_output = get_rst_from_plugin(plugin)
                plugin_name = plugin.name
                kind = '{}:'.format(plugin.kind)
            else:
                target = get_target_description(name)
                if target:
                    rst_output = get_rst_from_target(target)
                    plugin_name = target.name
                    kind = 'target:'

        if not rst_output:
            raise NotFoundError(
                'Could not find plugin or alias "{}"'.format(name))

        if which('pandoc'):
            p = Popen(['pandoc', '-f', 'rst', '-t', 'man'],
                      stdin=PIPE,
                      stdout=PIPE,
                      stderr=PIPE)
            if sys.version_info[0] == 3:
                output, _ = p.communicate(rst_output.encode(
                    sys.stdin.encoding))
                output = output.decode(sys.stdout.encoding)
            else:
                output, _ = p.communicate(rst_output)

            # Make sure to double escape back slashes
            output = output.replace('\\', '\\\\\\')

            # Correctly format the title and page number of the man page
            title, body = output.split('\n', 1)
            title = '.TH {}{} 7'.format(kind, plugin_name)
            output = '\n'.join([title, body])

            call('echo "{}" | man -l -'.format(escape_double_quotes(output)),
                 shell=True)
        else:
            print(rst_output)  # pylint: disable=superfluous-parens
示例#8
0
    def execute(self, state, args):
        name = identifier(args.plugin)
        rst_output = None

        if name == caseless_string('settings'):
            rst_output = get_rst_for_global_config()
            rst_output += get_rst_for_envars()
            plugin_name = name.lower()
            kind = 'global:'
        else:
            try:
                plugin = pluginloader.get_plugin_class(name)
            except NotFoundError:
                plugin = None
            if plugin:
                rst_output = get_rst_from_plugin(plugin)
                plugin_name = plugin.name
                kind = '{}:'.format(plugin.kind)
            else:
                target = get_target_description(name)
                if target:
                    rst_output = get_rst_from_target(target)
                    plugin_name = target.name
                    kind = 'target:'

        if not rst_output:
            raise NotFoundError('Could not find plugin or alias "{}"'.format(name))

        if which('pandoc'):
            p = Popen(['pandoc', '-f', 'rst', '-t', 'man'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
            if sys.version_info[0] == 3:
                output, _ = p.communicate(rst_output.encode(sys.stdin.encoding))
                output = output.decode(sys.stdout.encoding)
            else:
                output, _ = p.communicate(rst_output)

            # Make sure to double escape back slashes
            output = output.replace('\\', '\\\\\\')

            # Correctly format the title and page number of the man page
            title, body = output.split('\n', 1)
            title = '.TH {}{} 7'.format(kind, plugin_name)
            output = '\n'.join([title, body])

            call('echo "{}" | man -l -'.format(escape_double_quotes(output)), shell=True)
        else:
            print(rst_output)  # pylint: disable=superfluous-parens
    def __call__(self, value):
        if self.values is None:
            return value

        if isinstance(value, str):
            value = caseless_string(value)
            if value == 'all':
                return [state[0] for state in self.values]
            elif value == 'none':
                return []
            else:
                return [self._get_state_ID(value)]

        elif isinstance(value, list):
            valid_states = []
            for state in value:
                valid_states.append(self._get_state_ID(state))
            return valid_states
        else:
            raise ValueError('Invalid IdleState: "{}"'.format(value))
    def __call__(self, value):
        if self.values is None:
            return value

        if isinstance(value, str):
            value = caseless_string(value)
            if value == 'all':
                return [state[0] for state in self.values]
            elif value == 'none':
                return []
            else:
                return [self._get_state_ID(value)]

        elif isinstance(value, list):
            valid_states = []
            for state in value:
                valid_states.append(self._get_state_ID(state))
            return valid_states
        else:
            raise ValueError('Invalid IdleState: "{}"'.format(value))
示例#11
0
    def __call__(self, value):
        '''
        `self.values` can be `None` if the device's supported values could not be retrieved
        for some reason e.g. the cluster was offline, in this case we assume
        the user values will be available and allow any integer values.
        '''
        if self.values is None:
            if isinstance(value, int):
                return value
            else:
                msg = 'CPU frequency values could not be retrieved, cannot resolve "{}"'
                raise TargetError(msg.format(value))
        elif isinstance(value, int) and value in self.values:
            return value
        elif isinstance(value, str):
            value = caseless_string(value)
            if value in ['min', 'max']:
                return value

        msg = 'Invalid frequency value: {}; Must be in {}'
        raise ValueError(msg.format(value, self.values))
    def __call__(self, value):
        '''
        `self.values` can be `None` if the device's supported values could not be retrieved
        for some reason e.g. the cluster was offline, in this case we assume
        the user values will be available and allow any integer values.
        '''
        if self.values is None:
            if isinstance(value, int):
                return value
            else:
                msg = 'CPU frequency values could not be retrieved, cannot resolve "{}"'
                raise TargetError(msg.format(value))
        elif isinstance(value, int) and value in self.values:
            return value
        elif isinstance(value, str):
            value = caseless_string(value)
            if value in ['min', 'max']:
                return value

        msg = 'Invalid frequency value: {}; Must be in {}'
        raise ValueError(msg.format(value, self.values))
示例#13
0
def create_target_description(name, *args, **kwargs):
    name = identifier(name)
    for td in _adhoc_target_descriptions:
        if caseless_string(name) == td.name:
            msg = 'Target with name "{}" already exists (from source: {})'
            raise ValueError(msg.format(name, td.source))

    stack = inspect.stack()
    # inspect.stack() returns a list of call frame records for the current thread
    # in reverse call order. So the first entry is for the current frame and next one
    # for the immediate caller. Each entry is a tuple in the format
    #  (frame_object, module_path, line_no, function_name, source_lines, source_lines_index)
    #
    # Here we assign the path of the calling module as the "source" for this description.
    # because this might be invoked via the add_scription_for_target wrapper, we need to
    # check for that, and make sure that we get the info for *its* caller in that case.
    if stack[1][3] == 'add_description_for_target':
        source = stack[2][1]
    else:
        source = stack[1][1]

    _adhoc_target_descriptions.append(TargetDescription(name, source, *args, **kwargs))
示例#14
0
def create_target_description(name, *args, **kwargs):
    name = identifier(name)
    for td in _adhoc_target_descriptions:
        if caseless_string(name) == td.name:
            msg = 'Target with name "{}" already exists (from source: {})'
            raise ValueError(msg.format(name, td.source))

    stack = inspect.stack()
    # inspect.stack() returns a list of call frame records for the current thread
    # in reverse call order. So the first entry is for the current frame and next one
    # for the immediate caller. Each entry is a tuple in the format
    #  (frame_object, module_path, line_no, function_name, source_lines, source_lines_index)
    #
    # Here we assign the path of the calling module as the "source" for this description.
    # because this might be invoked via the add_scription_for_target wrapper, we need to
    # check for that, and make sure that we get the info for *its* caller in that case.
    if stack[1][3] == 'add_description_for_target':
        source = stack[2][1]
    else:
        source = stack[1][1]

    _adhoc_target_descriptions.append(
        TargetDescription(name, source, *args, **kwargs))
 def get_config_for_name(self, name):
     name = caseless_string(name)
     for k, v in self.runtime_params.items():
         if name == k:
             return v.rt_config
     return None
 def get_cfg_point(self, name):
     name = caseless_string(name)
     for k, v in self.runtime_params.items():
         if name == k or name in v.cfg_point.aliases:
             return v.cfg_point
     raise ConfigError('Unknown runtime parameter: {}'.format(name))
 def get_config_for_name(self, name):
     name = caseless_string(name)
     for k, v in self.runtime_params.items():
         if name == k:
             return v.rt_config
     return None
 def get_cfg_point(self, name):
     name = caseless_string(name)
     for k, v in self.runtime_params.items():
         if name == k:
             return v.cfg_point
     raise ConfigError('Unknown runtime parameter: {}'.format(name))