Example #1
0
def load_template(cls,
                  template_name,
                  template_source=None,
                  template_path=None,
                  openconfig=False,
                  jinja_filters={},
                  **template_vars):
    try:
        search_path = []
        if isinstance(template_source, py23_compat.string_types):
            template = jinja2.Template(template_source)
        else:
            if template_path is not None:
                if (isinstance(template_path, py23_compat.string_types)
                        and os.path.isdir(template_path)
                        and os.path.isabs(template_path)):
                    # append driver name at the end of the custom path
                    search_path.append(
                        os.path.join(template_path,
                                     cls.__module__.split('.')[-1]))
                else:
                    raise IOError("Template path does not exist: {}".format(
                        template_path))
            else:
                # Search modules for template paths
                search_path = [
                    os.path.dirname(
                        os.path.abspath(sys.modules[c.__module__].__file__))
                    for c in cls.__class__.mro() if c is not object
                ]

            if openconfig:
                search_path = [
                    '{}/oc_templates'.format(s) for s in search_path
                ]
            else:
                search_path = ['{}/templates'.format(s) for s in search_path]

            loader = jinja2.FileSystemLoader(search_path)
            environment = jinja2.Environment(loader=loader)

            for filter_name, filter_function in itertools.chain(
                    CustomJinjaFilters.filters().items(),
                    jinja_filters.items()):
                environment.filters[filter_name] = filter_function

            template = environment.get_template(
                '{template_name}.j2'.format(template_name=template_name))
        configuration = template.render(**template_vars)
    except jinja2.exceptions.TemplateNotFound:
        raise napalm.base.exceptions.TemplateNotImplemented(
            "Config template {template_name}.j2 not found in search path: {sp}"
            .format(template_name=template_name, sp=search_path))
    except (jinja2.exceptions.UndefinedError,
            jinja2.exceptions.TemplateSyntaxError) as jinjaerr:
        raise napalm.base.exceptions.TemplateRenderException(
            "Unable to render the Jinja config template {template_name}: {error}"
            .format(template_name=template_name, error=jinjaerr.message))
    return cls.load_merge_candidate(config=configuration)
Example #2
0
def load_template(cls, template_name, template_source=None, template_path=None,
                  openconfig=False, jinja_filters={}, **template_vars):
    try:
        search_path = []
        if isinstance(template_source, py23_compat.string_types):
            template = jinja2.Template(template_source)
        else:
            if template_path is not None:
                if (isinstance(template_path, py23_compat.string_types) and
                        os.path.isdir(template_path) and os.path.isabs(template_path)):
                    # append driver name at the end of the custom path
                    search_path.append(os.path.join(template_path, cls.__module__.split('.')[-1]))
                else:
                    raise IOError("Template path does not exist: {}".format(template_path))
            else:
                # Search modules for template paths
                search_path = [os.path.dirname(os.path.abspath(sys.modules[c.__module__].__file__))
                               for c in cls.__class__.mro() if c is not object]

            if openconfig:
                search_path = ['{}/oc_templates'.format(s) for s in search_path]
            else:
                search_path = ['{}/templates'.format(s) for s in search_path]

            loader = jinja2.FileSystemLoader(search_path)
            environment = jinja2.Environment(loader=loader)

            for filter_name, filter_function in itertools.chain(
                    CustomJinjaFilters.filters().items(),
                    jinja_filters.items()):
                environment.filters[filter_name] = filter_function

            template = environment.get_template('{template_name}.j2'.format(
                template_name=template_name
            ))
        configuration = template.render(**template_vars)
    except jinja2.exceptions.TemplateNotFound:
        raise napalm.base.exceptions.TemplateNotImplemented(
            "Config template {template_name}.j2 not found in search path: {sp}".format(
                template_name=template_name,
                sp=search_path
            )
        )
    except (jinja2.exceptions.UndefinedError, jinja2.exceptions.TemplateSyntaxError) as jinjaerr:
        raise napalm.base.exceptions.TemplateRenderException(
            "Unable to render the Jinja config template {template_name}: {error}".format(
                template_name=template_name,
                error=jinjaerr.message
            )
        )
    return cls.load_merge_candidate(config=configuration)
Example #3
0
def load_template(
    cls: "napalm.base.NetworkDriver",
    template_name: str,
    template_source: Optional[str] = None,
    template_path: Optional[str] = None,
    openconfig: bool = False,
    jinja_filters: Dict = {},
    **template_vars: Any,
) -> None:
    try:
        search_path = []
        if isinstance(template_source, str):
            template = jinja2.Template(template_source)
        else:
            if template_path is not None:
                if (isinstance(template_path, str)
                        and os.path.isdir(template_path)
                        and os.path.isabs(template_path)):
                    # append driver name at the end of the custom path
                    search_path.append(
                        os.path.join(template_path,
                                     cls.__module__.split(".")[-1]))
                else:
                    raise IOError("Template path does not exist: {}".format(
                        template_path))
            else:
                # Search modules for template paths
                for c in cls.__class__.mro():
                    if c is object:
                        continue
                    module = sys.modules[c.__module__].__file__
                    if module:
                        path = os.path.abspath(module)
                    else:
                        continue
                    if path:
                        path_to_append = os.path.dirname(path)
                    else:
                        continue
                    if path_to_append:
                        search_path.append(path_to_append)

            if openconfig:
                search_path = [
                    "{}/oc_templates".format(s) for s in search_path
                ]
            else:
                search_path = ["{}/templates".format(s) for s in search_path]

            loader = jinja2.FileSystemLoader(search_path)
            environment = jinja2.Environment(loader=loader)

            for filter_name, filter_function in itertools.chain(
                    CustomJinjaFilters.filters().items(),
                    jinja_filters.items()):
                environment.filters[filter_name] = filter_function

            template = environment.get_template(
                "{template_name}.j2".format(template_name=template_name))
        configuration = template.render(**template_vars)
    except jinja2.exceptions.TemplateNotFound:
        raise napalm.base.exceptions.TemplateNotImplemented(
            "Config template {template_name}.j2 not found in search path: {sp}"
            .format(template_name=template_name, sp=search_path))
    except (
            jinja2.exceptions.UndefinedError,
            jinja2.exceptions.TemplateSyntaxError,
    ) as jinjaerr:
        raise napalm.base.exceptions.TemplateRenderException(
            "Unable to render the Jinja config template {template_name}: {error}"
            .format(template_name=template_name, error=str(jinjaerr)))
    return cls.load_merge_candidate(config=configuration)