| 1 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 2 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 3 |
# |
| 4 |
# This program is free software: you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation, either version 3 of the License, or |
| 7 |
# (at your option) any later version. |
| 8 |
# |
| 9 |
# This program is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
# GNU General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
"""cylc support for the Jinja2 template processor |
| 17 |
|
| 18 |
Importing code should catch ImportError in case Jinja2 is not installed. |
| 19 |
""" |
| 20 |
|
| 21 |
from contextlib import suppress |
| 22 |
from functools import lru_cache, wraps |
| 23 |
from glob import glob |
| 24 |
import importlib |
| 25 |
import os |
| 26 |
import pkgutil |
| 27 |
import re |
| 28 |
import sys |
| 29 |
import traceback |
| 30 |
from typing import Any |
| 31 |
|
| 32 |
from jinja2 import ( |
| 33 |
BaseLoader, |
| 34 |
ChoiceLoader, |
| 35 |
Environment, |
| 36 |
FileSystemLoader, |
| 37 |
StrictUndefined, |
| 38 |
TemplateNotFound, |
| 39 |
TemplateSyntaxError, |
| 40 |
) |
| 41 |
|
| 42 |
from cylc.flow import LOG |
| 43 |
from cylc.flow.exceptions import InputError |
| 44 |
import cylc.flow.flags |
| 45 |
from cylc.flow.parsec.exceptions import Jinja2Error |
| 46 |
from cylc.flow.parsec.fileparse import get_cylc_env_vars |
| 47 |
|
| 48 |
|
| 49 |
TRACEBACK_LINENO = re.compile( |
| 50 |
r'\s+?File "(?P<file>.*)", line (?P<line>\d+), in .*template' |
| 51 |
) |
| 52 |
CONTEXT_LINES = 3 |
| 53 |
|
| 54 |
|
| 55 |
def restore_deprecated_interfaces(): |
| 56 |
"""Extend support for some deprecated interfaces in Jinja2 3.1.x. |
| 57 |
|
| 58 |
Jinja2 renamed a bunch of interfaces. Warnings were added in version 3.0.0, |
| 59 |
support for the old names was removed in 3.1.0, however, our users did not |
| 60 |
notice these warnings (you have to manually turn them on) so did not take |
| 61 |
action. |
| 62 |
|
| 63 |
https://jinja.palletsprojects.com/en/stable/changes/#version-3-1-0 |
| 64 |
|
| 65 |
In https://github.com/cylc/cylc-flow/pull/7365 (8.6.6) we've captured |
| 66 |
Jinja2 warnings and turned them into Cylc warnings to ensure they cannot be |
| 67 |
missed. |
| 68 |
|
| 69 |
To give users a chance to take action, this patch restores the renamed |
| 70 |
interfaces just for ONE minor Cylc version. |
| 71 |
|
| 72 |
BACK COMPAT: restore_deprecated_interfaces |
| 73 |
FROM: 8.6.x |
| 74 |
TO: 8.7.0 |
| 75 |
REMOVE AT: 8.8.0 |
| 76 |
""" |
| 77 |
renamed_interfaces = { |
| 78 |
'contextfilter': 'pass_context', |
| 79 |
'contextfunction': 'pass_context', |
| 80 |
'evalcontextfilter': 'pass_eval_context', |
| 81 |
'evalcontextfunction': 'pass_eval_context', |
| 82 |
'environmentfilter': 'pass_environment', |
| 83 |
'environmentfunction': 'pass_environment', |
| 84 |
} |
| 85 |
url = 'https://jinja.palletsprojects.com/en/stable/changes/#version-3-1-0' |
| 86 |
|
| 87 |
@lru_cache # suppress duplicate warnings |
| 88 |
def _log_warning(old, new): |
| 89 |
LOG.warning( |
| 90 |
f'The Jinja2 function {old} was renamed to {new}.' |
| 91 |
f'\nCylc has extended support for {old} until 8.8.0.' |
| 92 |
f' Please search your workflow for {old} and upgrade any uses.' |
| 93 |
f'\nSee {url}' |
| 94 |
) |
| 95 |
|
| 96 |
def _warn(fcn, old, new): |
| 97 |
@wraps(fcn) |
| 98 |
def _inner(*args, **kwargs): |
| 99 |
_log_warning(old, new) |
| 100 |
return fcn(*args, **kwargs) |
| 101 |
return _inner |
| 102 |
|
| 103 |
import jinja2 |
| 104 |
import jinja2.filters |
| 105 |
for old, new in renamed_interfaces.items(): |
| 106 |
setattr(jinja2, old, _warn(getattr(jinja2, new), old, new)) |
| 107 |
setattr(jinja2.filters, old, _warn(getattr(jinja2, new), old, new)) |
| 108 |
|
| 109 |
|
| 110 |
# BACK COMPAT |
| 111 |
restore_deprecated_interfaces() |
| 112 |
|
| 113 |
|
| 114 |
class PyModuleLoader(BaseLoader): |
| 115 |
"""Load python module as Jinja2 template. |
| 116 |
|
| 117 |
This loader piggybacks on the jinja import mechanism and |
| 118 |
returns an empty template that exports module's namespace.""" |
| 119 |
|
| 120 |
# no source access for this loader |
| 121 |
has_source_access = False |
| 122 |
|
| 123 |
def __init__(self, prefix='__python__'): |
| 124 |
self._templates = {} |
| 125 |
# prefix that can be used to avoid name collisions with template files |
| 126 |
self._python_namespace_prefix = prefix + '.' |
| 127 |
|
| 128 |
def load( |
| 129 |
self, |
| 130 |
environment, |
| 131 |
name, |
| 132 |
globals=None # noqa: A002 (required to match underlying interface?) |
| 133 |
): |
| 134 |
"""Imports Python module and returns it as Jinja2 template.""" |
| 135 |
if name.startswith(self._python_namespace_prefix): |
| 136 |
name = name[len(self._python_namespace_prefix):] |
| 137 |
with suppress(KeyError): |
| 138 |
return self._templates[name] |
| 139 |
try: |
| 140 |
mdict = __import__(name, fromlist=['*']).__dict__ |
| 141 |
except ImportError: |
| 142 |
raise TemplateNotFound(name) from None |
| 143 |
|
| 144 |
# inject module dict into the context of an empty template |
| 145 |
def root_render_func(context, *args, **kwargs): |
| 146 |
"""Template render function.""" |
| 147 |
if False: |
| 148 |
yield None # to make it a generator |
| 149 |
context.vars.update(mdict) |
| 150 |
context.exported_vars.update(mdict) |
| 151 |
|
| 152 |
templ = environment.from_string('') |
| 153 |
templ.root_render_func = root_render_func |
| 154 |
self._templates[name] = templ |
| 155 |
return templ |
| 156 |
|
| 157 |
|
| 158 |
class Jinja2AssertionError(Exception): |
| 159 |
"""Exception raised by the Jinja2 "raise" and "assert" functions.""" |
| 160 |
|
| 161 |
|
| 162 |
def raise_helper(message): |
| 163 |
"""Provides a Jinja2 function for raising exceptions.""" |
| 164 |
raise Jinja2AssertionError(message) |
| 165 |
|
| 166 |
|
| 167 |
def assert_helper(logical, message): |
| 168 |
"""Provides a Jinja2 function for asserting logical expressions.""" |
| 169 |
if not logical: |
| 170 |
raise_helper(message) |
| 171 |
return '' # Prevent None return value polluting output. |
| 172 |
|
| 173 |
|
| 174 |
def _load_jinja2_extensions(): |
| 175 |
""" |
| 176 |
Load modules under the cylc.jinja package namespace. |
| 177 |
|
| 178 |
Filters provided by third-party packages (i.e. user created packages) will |
| 179 |
also be included if correctly put in the cylc.jinja.filters namespace. |
| 180 |
|
| 181 |
Global variables are expected to be found in cylc.jinja.globals, |
| 182 |
and jinja tests in cylc.jinja.tests. |
| 183 |
|
| 184 |
The dictionary returned contains the full module name (e.g. |
| 185 |
cylc.jinja.filters.pad), and the second value is the module |
| 186 |
object (same object as in __import__("module_name")__). |
| 187 |
|
| 188 |
:return: jinja2 filter modules |
| 189 |
:rtype: dict[string, object] |
| 190 |
""" |
| 191 |
jinja2_extensions = {} |
| 192 |
for module_name in [ |
| 193 |
"cylc.flow.jinja.filters", |
| 194 |
"cylc.flow.jinja.globals", |
| 195 |
"cylc.flow.jinja.tests" |
| 196 |
]: |
| 197 |
try: |
| 198 |
module = importlib.import_module(module_name) |
| 199 |
jinja2_filters_modules = pkgutil.iter_modules( |
| 200 |
module.__path__, f"{module.__name__}.") |
| 201 |
if jinja2_filters_modules: |
| 202 |
namespace = module_name.split(".")[-1] |
| 203 |
jinja2_extensions[namespace] = { |
| 204 |
name.split(".")[-1]: importlib.import_module(name) |
| 205 |
for finder, name, ispkg in jinja2_filters_modules |
| 206 |
} |
| 207 |
except ModuleNotFoundError: |
| 208 |
# Nothing to do, we may start without any filters/globals/tests |
| 209 |
pass |
| 210 |
|
| 211 |
return jinja2_extensions |
| 212 |
|
| 213 |
|
| 214 |
def jinja2environment(dir_=None): |
| 215 |
"""Set up and return Jinja2 environment.""" |
| 216 |
if dir_ is None: |
| 217 |
dir_ = os.getcwd() |
| 218 |
|
| 219 |
# Ignore bandit false positive: B701:jinja2_autoescape_false |
| 220 |
# This env is not used to render content that is vulnerable to XSS. |
| 221 |
env = Environment( # nosec |
| 222 |
loader=ChoiceLoader([FileSystemLoader(dir_), PyModuleLoader()]), |
| 223 |
undefined=StrictUndefined, |
| 224 |
extensions=['jinja2.ext.do']) |
| 225 |
|
| 226 |
# Load Jinja2 filters using setuptools |
| 227 |
for scope, extensions in _load_jinja2_extensions().items(): |
| 228 |
for fname, module in extensions.items(): |
| 229 |
getattr(env, scope)[fname] = getattr(module, fname) |
| 230 |
|
| 231 |
# Load any custom Jinja2 filters, tests or globals in the workflow |
| 232 |
# definition directory |
| 233 |
# Example: a filter to pad integer values some fill character: |
| 234 |
# |(file WORKFLOW_DEFINITION_DIRECTORY/Jinja2/foo.py) |
| 235 |
# | #!/usr/bin/env python3 |
| 236 |
# | def foo( value, length, fillchar ): |
| 237 |
# | return str(value).rjust( int(length), str(fillchar) ) |
| 238 |
for namespace in ['filters', 'tests', 'globals']: |
| 239 |
nspdir = 'Jinja2' + namespace.capitalize() |
| 240 |
fdirs = [os.path.join(dir_, nspdir)] |
| 241 |
try: |
| 242 |
fdirs.append(os.path.join(os.environ['HOME'], '.cylc', nspdir)) |
| 243 |
except KeyError: |
| 244 |
# (Needed for tests/f/cylc-get-site-config/04-homeless.t!) |
| 245 |
LOG.warning(f"$HOME undefined: can't load ~/.cylc/{nspdir}") |
| 246 |
for fdir in fdirs: |
| 247 |
if os.path.isdir(fdir): |
| 248 |
sys.path.insert(1, os.path.abspath(fdir)) |
| 249 |
for name in glob(os.path.join(fdir, '*.py')): |
| 250 |
fname = os.path.splitext(os.path.basename(name))[0] |
| 251 |
# TODO - EXCEPTION HANDLING FOR LOADING CUSTOM FILTERS |
| 252 |
module = __import__(fname) |
| 253 |
envnsp = getattr(env, namespace) |
| 254 |
envnsp[fname] = getattr(module, fname) |
| 255 |
|
| 256 |
# Import WORKFLOW HOST USER ENVIRONMENT into template: |
| 257 |
# (Usage e.g.: {{environ['HOME']}}). |
| 258 |
env.globals['environ'] = os.environ |
| 259 |
env.globals['raise'] = raise_helper |
| 260 |
env.globals['assert'] = assert_helper |
| 261 |
|
| 262 |
# Add `CYLC_` environment variables to the global namespace. |
| 263 |
env.globals.update( |
| 264 |
get_cylc_env_vars() |
| 265 |
) |
| 266 |
return env |
| 267 |
|
| 268 |
|
| 269 |
def get_error_lines( |
| 270 |
base_template_file: str, |
| 271 |
template_lines: list[str], |
| 272 |
) -> dict[str, list[str]]: |
| 273 |
"""Extract exception lines from Jinja2 tracebacks. |
| 274 |
|
| 275 |
Returns: |
| 276 |
{filename: [exception_line, ...]} |
| 277 |
|
| 278 |
There may be multiple entries due to {% include %} statements. |
| 279 |
|
| 280 |
""" |
| 281 |
ret = {} |
| 282 |
for line in reversed(traceback.format_exc().splitlines()): |
| 283 |
match = TRACEBACK_LINENO.match(line) |
| 284 |
lines: list[str] = [] |
| 285 |
if match: |
| 286 |
filename = match.groupdict()['file'] |
| 287 |
lineno = int(match.groupdict()['line']) |
| 288 |
start_line = max(lineno - CONTEXT_LINES, 0) |
| 289 |
if filename in {'<template>', '<unknown>'}: |
| 290 |
filename = base_template_file |
| 291 |
lineno += 1 # shebang line ignored by jinja2 |
| 292 |
lines = template_lines[start_line:lineno] |
| 293 |
elif os.path.isfile(filename): |
| 294 |
with open(filename, 'r') as jinja2_file: |
| 295 |
for i, fline in enumerate(jinja2_file, start=1): |
| 296 |
if i < start_line: |
| 297 |
continue |
| 298 |
if i > lineno: |
| 299 |
break |
| 300 |
# use splitlines to remove the newline char at the |
| 301 |
# end of the line |
| 302 |
lines.append(fline.splitlines()[0]) |
| 303 |
if lines: |
| 304 |
ret[filename] = lines |
| 305 |
|
| 306 |
return ret |
| 307 |
|
| 308 |
|
| 309 |
def jinja2process( |
| 310 |
fpath: str, |
| 311 |
flines: list[str], |
| 312 |
dir_: str, |
| 313 |
template_vars: dict[str, Any] | None = None, |
| 314 |
) -> list[str]: |
| 315 |
"""Pass configure file through Jinja2 processor. |
| 316 |
|
| 317 |
Args: |
| 318 |
fpath: |
| 319 |
The path to the root template file (i.e. the flow.cylc file) |
| 320 |
flines: |
| 321 |
List of template lines to process. |
| 322 |
dir_: |
| 323 |
The path to the configuration directory. |
| 324 |
template_vars: |
| 325 |
Dictionary of template variables. |
| 326 |
|
| 327 |
""" |
| 328 |
# Load file lines into a template, excluding '#!jinja2' so that |
| 329 |
# '#!cylc-x.y.z' rises to the top. Callers should handle jinja2 |
| 330 |
# TemplateSyntaxerror and TemplateError. |
| 331 |
if template_vars: |
| 332 |
LOG.debug( |
| 333 |
'Setting Jinja2 template variables:\n%s', |
| 334 |
'\n'.join( |
| 335 |
['+ %s=%s' % item for item in sorted(template_vars.items())])) |
| 336 |
|
| 337 |
# Jinja2 render method requires a dictionary as argument (not None): |
| 338 |
if not template_vars: |
| 339 |
template_vars = {} |
| 340 |
|
| 341 |
# CALLERS SHOULD HANDLE JINJA2 TEMPLATESYNTAXERROR AND TEMPLATEERROR |
| 342 |
# AND TYPEERROR (e.g. for not using "|int" filter on number inputs. |
| 343 |
# Convert unicode to plain str, ToDo - still needed for parsec?) |
| 344 |
try: |
| 345 |
env = jinja2environment(dir_) |
| 346 |
template = env.from_string('\n'.join(flines[1:])) |
| 347 |
lines = str(template.render(template_vars)).splitlines() |
| 348 |
except TemplateSyntaxError as exc: |
| 349 |
filename = None |
| 350 |
# extract source lines |
| 351 |
if exc.lineno and exc.source and not exc.filename: |
| 352 |
# error in flow.cylc or cylc include file |
| 353 |
lines = exc.source.splitlines() |
| 354 |
elif exc.lineno and exc.filename: |
| 355 |
# error in jinja2 include file |
| 356 |
filename = os.path.relpath(exc.filename, dir_) |
| 357 |
with open(exc.filename, 'r') as include_file: |
| 358 |
include_file.seek(max(exc.lineno - CONTEXT_LINES, 0), 0) |
| 359 |
lines = [] |
| 360 |
for _ in range(CONTEXT_LINES): |
| 361 |
lines.append(include_file.readline().splitlines()[0]) |
| 362 |
|
| 363 |
raise Jinja2Error( |
| 364 |
exc, |
| 365 |
lines=get_error_lines(fpath, flines), |
| 366 |
filename=filename |
| 367 |
) from None |
| 368 |
except Jinja2AssertionError as exc: |
| 369 |
if cylc.flow.flags.verbosity < 1: |
| 370 |
# raise a user-friently representation of this assertion error |
| 371 |
raise InputError( |
| 372 |
f'{str(exc)}' |
| 373 |
'\n(add --verbose for more context)' |
| 374 |
) from None |
| 375 |
|
| 376 |
# raise the full form of the error in verbose mode |
| 377 |
raise Jinja2Error( |
| 378 |
exc, |
| 379 |
lines=get_error_lines(fpath, flines), |
| 380 |
) from None |
| 381 |
except Exception as exc: |
| 382 |
raise Jinja2Error( |
| 383 |
exc, |
| 384 |
lines=get_error_lines(fpath, flines), |
| 385 |
) from None |
| 386 |
|
| 387 |
# Ignore blank lines (lone Jinja2 statements leave blank lines behind) |
| 388 |
return [line for line in lines if line.strip()] |