HiveOperator 中 hql 模板路径解析失败的原因分析

本文由「大千AI助手」原创发布,专注用真话讲AI,回归技术本质。拒绝神话或妖魔化。搜索「大千AI助手」关注我,一起撕掉过度包装,学习真实的AI技术!

问题描述

  • HiveOperator 中以类似 ../xxx.hql 或 /yyy/xxx.hql 的方式设置参数 hql 时, 任务执行时报错找不到对应的模板
    • 比如 TemplateNotFound 异常

本文由「大千AI助手」原创发布,专注用真话讲AI,回归技术本质。拒绝神话或妖魔化。搜索「大千AI助手」关注我,一起撕掉过度包装,学习真实的AI技术!

往期文章推荐:

问题分析

  • 1.HiveOperator 的参数 hql 用来配置运行的 hive sql 或者 包含hive sql的jinja2模板文件
  • 2.并且参数 hql 被设置为可以被 jinja2 引擎渲染的
  • 3.并且参数 hql 被设置为如果以 .hql 或 .sql 结尾,那么 hql 被整体当作 模板文件名 来通过 jinja2 渲染,其余情况都被当作 hive sql字符串 直接渲染
python 复制代码
# 源码 HiveOperator 中的部分参数设置
template_fields = ('hql', 'schema', 'hive_cli_conn_id', 'mapred_queue',
                'hiveconfs', 'mapred_job_name', 'mapred_queue_priority')
template_ext = ('.hql', '.sql',)


# 源码 airflow/models/baseoperator.py
class BaseOperator(LoggingMixin):
    ...

    def render_template(self, content, context, jinja_env=None, seen_oids=None):
        if not jinja_env:
            jinja_env = self.get_template_env()

        if isinstance(content, six.string_types):
            if any(content.endswith(ext) for ext in self.template_ext):
                # Content contains a filepath
                return jinja_env.get_template(content).render(**context)
            else:
                return jinja_env.from_string(content).render(**context)
    ...
  • 4.而Jinja2 在模板加载阶段会对路径进行安全校验,明确禁止目录回溯和越权访问
    • jinja2 在通过 FileSystemLoader 加载本地模板文件时会对路径进行特殊检查和处理
      • 如果模板文件路径中包含 .. 则直接抛出异常 TemplateNotFound 表示找不到模板文件
        • 通过条件 piece == os.path.pardir 来判断的 (os.path.pardir 代表父目录,取值为 ..)
      • 并且模板都是在 searchpath 路径下查找的,如果用了绝对路径,那肯定也是找不到的(除非 searchpath = '/')
python 复制代码
# 源码路径: jinja2/loaders.py
def split_template_path(template: str) -> t.List[str]:
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split("/"):
        if (
            os.path.sep in piece
            or (os.path.altsep and os.path.altsep in piece)
            or piece == os.path.pardir
        ):
            raise TemplateNotFound(template)
        elif piece and piece != ".":
            pieces.append(piece)
    return pieces


class FileSystemLoader(BaseLoader):
    ...

    def get_source(
        self, environment: "Environment", template: str
    ) -> t.Tuple[str, str, t.Callable[[], bool]]:
        pieces = split_template_path(template)

        for searchpath in self.searchpath:
            # Use posixpath even on Windows to avoid "drive:" or UNC
            # segments breaking out of the search directory.
            filename = posixpath.join(searchpath, *pieces)

            if os.path.isfile(filename):
                break
        else:
            plural = "path" if len(self.searchpath) == 1 else "paths"
            paths_str = ", ".join(repr(p) for p in self.searchpath)
            raise TemplateNotFound(
                template,
                f"{template!r} not found in search {plural}: {paths_str}",
            )
        ...
  • 5.而使用的 searchpath 包括 任务所在的dag的定义的文件的路径 和 创建dag时传的参数 template_searchpath
    • self.folder 就是定义该任务的 dag 的文件所在的父目录
      • 一般在任务执行日志中能看到 '-sd', 'DAGS_FOLDER/xxx.py'
python 复制代码
# 源码 airflow/models/dag.py
class DAG(BaseDag, LoggingMixin):
    ...

    @property
    def folder(self):
        """Folder location of where the DAG object is instantiated."""
        return os.path.dirname(self.full_filepath)
    ...

    def get_template_env(self):  # type: () -> jinja2.Environment
        """Build a Jinja2 environment."""

        # Collect directories to search for template files
        searchpath = [self.folder]
        if self.template_searchpath:
            searchpath += self.template_searchpath

        # Default values (for backward compatibility)
        jinja_env_options = {
            'loader': jinja2.FileSystemLoader(searchpath),
            'undefined': self.template_undefined or jinja2.Undefined,
            'extensions': ["jinja2.ext.do"],
            'cache_size': 0
        }
        if self.jinja_environment_kwargs:
            jinja_env_options.update(self.jinja_environment_kwargs)

        env = jinja2.Environment(**jinja_env_options)  # type: ignore

        # Add any user defined items. Safe to edit globals as long as no templates are rendered yet.
        # http://jinja.pocoo.org/docs/2.10/api/#jinja2.Environment.globals
        if self.user_defined_macros:
            env.globals.update(self.user_defined_macros)
        if self.user_defined_filters:
            env.filters.update(self.user_defined_filters)

        return env

    ...

解决方案

  • 方案1.使用 相对路径 和 与对应的 DAG 定义文件同级或子目录存放模板文件
  • 方案2.通过参数 template_searchpath 来设置当前 DAG 特有的模板搜索目录
    • 创建 DAG 时的初始化参数
  • 方案3.通过 HiveOperator 执行的 hql 模板文件 禁止用绝对路径 和 带 .. 的路径

本文由「大千AI助手」原创发布,专注用真话讲AI,回归技术本质。拒绝神话或妖魔化。搜索「大千AI助手」关注我,一起撕掉过度包装,学习真实的AI技术!

相关推荐
wuyk55510 小时前
Python办公自动化-第01讲-环境搭建与自动化认知
python·自动化·pyqt
高洁0110 小时前
数字孪生与计算机视觉:让机器看懂现场
人工智能·python·机器学习·transformer·迁移学习
ComPDFKit10 小时前
RAG 回答只显示 PDF 文件名?用 Python 保留引用页码
开发语言·python·pdf·rag
yz_aiks12 小时前
Termux 使用教程:把安卓手机变成随身 Linux(装 Python、SSH 远程、跑自动化脚本)
android·linux·python·智能手机·ssh·termux
2601_9679801114 小时前
Flask Web 应用
python·flask·web开发·环境变量·虚拟环境
aifannihao14 小时前
ß 大写变 SS:用 Python 算清 Ruby2Shell 的缓冲区账本
python·安全·标准库·缓冲区溢出·字符串编码
liwulin050614 小时前
【OLLAMA】调用SKILL的通用ReAct
python
郝学胜-神的一滴15 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
Norna16 小时前
Git 给路径加了引号,这个文件就从 review 里消失了
python
wuyk55517 小时前
Python办公自动化-第04讲-批量新建Excel
开发语言·python·excel