Exemplo n.º 1
0
 def get_section(self, config, section):
     if config is not None:
         netcfg = NetworkConfig(indent=1, contents=config)
         try:
             config = netcfg.get_block_config(to_list(section))
         except ValueError:
             config = None
         return config
Exemplo n.º 2
0
 def get_config_context(self, config, path, indent=2):
     if config is not None:
         netcfg = NetworkConfig(indent=indent, contents=config)
         try:
             config = netcfg.get_block_config(to_list(path))
         except ValueError:
             config = None
         return config
Exemplo n.º 3
0
def get_sublevel_config(running_config, module):
    contents = list()
    current_config_contents = list()
    running_config = NetworkConfig(contents=running_config, indent=1)
    obj = running_config.get_object(module.params['parents'])
    if obj:
        contents = obj.children
    contents[:0] = module.params['parents']

    indent = 0
    for c in contents:
        if isinstance(c, str):
            current_config_contents.append(c.rjust(len(c) + indent, ' '))
        if isinstance(c, ConfigLine):
            current_config_contents.append(c.raw)
        indent = 1
    sublevel_config = '\n'.join(current_config_contents)

    return sublevel_config
Exemplo n.º 4
0
    def get_diff(self, candidate=None, running=None, diff_match='line', diff_ignore_lines=None, path=None, diff_replace='line'):
        diff = {}
        device_operations = self.get_device_operations()
        option_values = self.get_option_values()

        if candidate is None and device_operations['supports_generate_diff']:
            raise ValueError("candidate configuration is required to generate diff")

        if diff_match not in option_values['diff_match']:
            raise ValueError("'match' value %s in invalid, valid values are %s" % (diff_match, ', '.join(option_values['diff_match'])))

        if diff_replace not in option_values['diff_replace']:
            raise ValueError("'replace' value %s in invalid, valid values are %s" % (diff_replace, ', '.join(option_values['diff_replace'])))

        # prepare candidate configuration
        candidate_obj = NetworkConfig(indent=2)
        candidate_obj.load(candidate)

        if running and diff_match != 'none' and diff_replace != 'config':
            # running configuration
            running_obj = NetworkConfig(indent=2, contents=running, ignore_lines=diff_ignore_lines)
            configdiffobjs = candidate_obj.difference(running_obj, path=path, match=diff_match, replace=diff_replace)

        else:
            configdiffobjs = candidate_obj.items

        diff['config_diff'] = dumps(configdiffobjs, 'commands') if configdiffobjs else ''
        return diff
Exemplo n.º 5
0
    def get_diff(self, candidate=None, running=None, diff_match='line', diff_ignore_lines=None, path=None, diff_replace='line'):
        diff = {}

        # prepare candidate configuration
        candidate_obj = NetworkConfig(indent=3)
        candidate_obj.load(candidate)

        if running and diff_match != 'none' and diff_replace != 'config':
            # running configuration
            running_obj = NetworkConfig(indent=3, contents=running, ignore_lines=diff_ignore_lines)
            configdiffobjs = candidate_obj.difference(running_obj, path=path, match=diff_match, replace=diff_replace)

        else:
            configdiffobjs = candidate_obj.items

        diff['config_diff'] = dumps(configdiffobjs, 'commands') if configdiffobjs else {}
        return diff
Exemplo n.º 6
0
    def get_diff(self,
                 candidate=None,
                 running=None,
                 diff_match='line',
                 diff_ignore_lines=None,
                 path=None,
                 diff_replace='line'):
        """
        Generate diff between candidate and running configuration. If the
        remote host supports onbox diff capabilities ie. supports_onbox_diff in that case
        candidate and running configurations are not required to be passed as argument.
        In case if onbox diff capability is not supported candidate argument is mandatory
        and running argument is optional.
        :param candidate: The configuration which is expected to be present on remote host.
        :param running: The base configuration which is used to generate diff.
        :param diff_match: Instructs how to match the candidate configuration with current device configuration
                      Valid values are 'line', 'strict', 'exact', 'none'.
                      'line' - commands are matched line by line
                      'strict' - command lines are matched with respect to position
                      'exact' - command lines must be an equal match
                      'none' - will not compare the candidate configuration with the running configuration
        :param diff_ignore_lines: Use this argument to specify one or more lines that should be
                                  ignored during the diff.  This is used for lines in the configuration
                                  that are automatically updated by the system.  This argument takes
                                  a list of regular expressions or exact line matches.
        :param path: The ordered set of parents that uniquely identify the section or hierarchy
                     the commands should be checked against.  If the parents argument
                     is omitted, the commands are checked against the set of top
                    level or global commands.
        :param diff_replace: Instructs on the way to perform the configuration on the device.
                        If the replace argument is set to I(line) then the modified lines are
                        pushed to the device in configuration mode.  If the replace argument is
                        set to I(block) then the entire command block is pushed to the device in
                        configuration mode if any line is not correct.
        :return: Configuration diff in  json format.
               {
                   'config_diff': '',
                   'banner_diff': {}
               }

        """
        diff = {}
        device_operations = self.get_device_operations()
        option_values = self.get_option_values()

        if candidate is None and device_operations['supports_generate_diff']:
            raise ValueError(
                "candidate configuration is required to generate diff")

        if diff_match not in option_values['diff_match']:
            raise ValueError(
                "'match' value %s in invalid, valid values are %s" %
                (diff_match, ', '.join(option_values['diff_match'])))

        if diff_replace not in option_values['diff_replace']:
            raise ValueError(
                "'replace' value %s in invalid, valid values are %s" %
                (diff_replace, ', '.join(option_values['diff_replace'])))

        # prepare candidate configuration
        candidate_obj = NetworkConfig(indent=1)
        want_src, want_banners = self._extract_banners(candidate)
        candidate_obj.load(want_src)

        if running and diff_match != 'none':
            # running configuration
            have_src, have_banners = self._extract_banners(running)

            running_obj = NetworkConfig(indent=1,
                                        contents=have_src,
                                        ignore_lines=diff_ignore_lines)
            configdiffobjs = candidate_obj.difference(running_obj,
                                                      path=path,
                                                      match=diff_match,
                                                      replace=diff_replace)

        else:
            configdiffobjs = candidate_obj.items
            have_banners = {}

        diff['config_diff'] = dumps(configdiffobjs,
                                    'commands') if configdiffobjs else ''

        banners = self._diff_banners(want_banners, have_banners)
        diff['banner_diff'] = banners if banners else {}
        return diff
Exemplo n.º 7
0
    def get_diff(self,
                 candidate=None,
                 running=None,
                 diff_match='line',
                 diff_ignore_lines=None,
                 path=None,
                 diff_replace=None):
        diff = {}
        device_operations = self.get_device_operations()
        option_values = self.get_option_values()

        if candidate is None and device_operations['supports_generate_diff']:
            raise ValueError(
                "candidate configuration is required to generate diff")

        if diff_match not in option_values['diff_match']:
            raise ValueError(
                "'match' value %s in invalid, valid values are %s" %
                (diff_match, ', '.join(option_values['diff_match'])))

        if diff_replace:
            raise ValueError("'replace' in diff is not supported")

        if diff_ignore_lines:
            raise ValueError("'diff_ignore_lines' in diff is not supported")

        if path:
            raise ValueError("'path' in diff is not supported")

        set_format = candidate.startswith('set') or candidate.startswith(
            'delete')
        candidate_obj = NetworkConfig(indent=4, contents=candidate)
        if not set_format:
            config = [c.line for c in candidate_obj.items]
            commands = list()
            # this filters out less specific lines
            for item in config:
                for index, entry in enumerate(commands):
                    if item.startswith(entry):
                        del commands[index]
                        break
                commands.append(item)

            candidate_commands = [
                'set %s' % cmd.replace(' {', '') for cmd in commands
            ]

        else:
            candidate_commands = str(candidate).strip().split('\n')

        if diff_match == 'none':
            diff['config_diff'] = list(candidate_commands)
            return diff

        running_commands = [
            str(c).replace("'", '') for c in running.splitlines()
        ]

        updates = list()
        visited = set()

        for line in candidate_commands:
            item = str(line).replace("'", '')

            if not item.startswith('set') and not item.startswith('delete'):
                raise ValueError(
                    'line must start with either `set` or `delete`')

            elif item.startswith('set') and item not in running_commands:
                updates.append(line)

            elif item.startswith('delete'):
                if not running_commands:
                    updates.append(line)
                else:
                    item = re.sub(r'delete', 'set', item)
                    for entry in running_commands:
                        if entry.startswith(item) and line not in visited:
                            updates.append(line)
                            visited.add(line)

        diff['config_diff'] = list(updates)
        return diff