|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import warnings |
| 20 | +from collections.abc import Sequence |
| 21 | +from typing import TYPE_CHECKING, Callable |
| 22 | + |
| 23 | +from airflow.providers.cncf.kubernetes.version_compat import AIRFLOW_V_3_0_PLUS |
| 24 | + |
| 25 | +if AIRFLOW_V_3_0_PLUS: |
| 26 | + from airflow.sdk.bases.decorator import DecoratedOperator, TaskDecorator, task_decorator_factory |
| 27 | +else: |
| 28 | + from airflow.decorators.base import ( # type: ignore[no-redef] |
| 29 | + DecoratedOperator, |
| 30 | + TaskDecorator, |
| 31 | + task_decorator_factory, |
| 32 | + ) |
| 33 | +from airflow.providers.cncf.kubernetes.operators.pod import KubernetesPodOperator |
| 34 | +from airflow.utils.context import context_merge |
| 35 | +from airflow.utils.operator_helpers import determine_kwargs |
| 36 | + |
| 37 | +if TYPE_CHECKING: |
| 38 | + from airflow.utils.context import Context |
| 39 | + |
| 40 | + |
| 41 | +class _KubernetesCmdDecoratedOperator(DecoratedOperator, KubernetesPodOperator): |
| 42 | + custom_operator_name = "@task.kubernetes_cmd" |
| 43 | + |
| 44 | + template_fields: Sequence[str] = KubernetesPodOperator.template_fields |
| 45 | + overwrite_rtif_after_execution: bool = True |
| 46 | + |
| 47 | + def __init__(self, *, python_callable: Callable, args_only: bool = False, **kwargs) -> None: |
| 48 | + self.args_only = args_only |
| 49 | + |
| 50 | + cmds = kwargs.pop("cmds", None) |
| 51 | + arguments = kwargs.pop("arguments", None) |
| 52 | + |
| 53 | + if cmds is not None or arguments is not None: |
| 54 | + warnings.warn( |
| 55 | + f"The `cmds` and `arguments` are unused in {self.custom_operator_name} decorator. " |
| 56 | + "You should return a list of commands or image entrypoint arguments with " |
| 57 | + "args_only=True from the python_callable.", |
| 58 | + UserWarning, |
| 59 | + stacklevel=3, |
| 60 | + ) |
| 61 | + |
| 62 | + # If the name was not provided, we generate operator name from the python_callable |
| 63 | + # we also instruct operator to add a random suffix to avoid collisions by default |
| 64 | + op_name = kwargs.pop("name", f"k8s-airflow-pod-{python_callable.__name__}") |
| 65 | + random_name_suffix = kwargs.pop("random_name_suffix", True) |
| 66 | + |
| 67 | + super().__init__( |
| 68 | + python_callable=python_callable, |
| 69 | + name=op_name, |
| 70 | + random_name_suffix=random_name_suffix, |
| 71 | + cmds=None, |
| 72 | + arguments=None, |
| 73 | + **kwargs, |
| 74 | + ) |
| 75 | + |
| 76 | + def execute(self, context: Context): |
| 77 | + generated = self._generate_cmds(context) |
| 78 | + if self.args_only: |
| 79 | + self.cmds = [] |
| 80 | + self.arguments = generated |
| 81 | + else: |
| 82 | + self.cmds = generated |
| 83 | + self.arguments = [] |
| 84 | + context["ti"].render_templates() # type: ignore[attr-defined] |
| 85 | + return super().execute(context) |
| 86 | + |
| 87 | + def _generate_cmds(self, context: Context) -> list[str]: |
| 88 | + context_merge(context, self.op_kwargs) |
| 89 | + kwargs = determine_kwargs(self.python_callable, self.op_args, context) |
| 90 | + generated_cmds = self.python_callable(*self.op_args, **kwargs) |
| 91 | + func_name = self.python_callable.__name__ |
| 92 | + if not isinstance(generated_cmds, list): |
| 93 | + raise TypeError( |
| 94 | + f"Expected python_callable to return a list of strings, but got {type(generated_cmds)}" |
| 95 | + ) |
| 96 | + if not all(isinstance(cmd, str) for cmd in generated_cmds): |
| 97 | + raise TypeError(f"Expected {func_name} to return a list of strings, but got {generated_cmds}") |
| 98 | + if not generated_cmds: |
| 99 | + raise ValueError(f"The {func_name} returned an empty list of commands") |
| 100 | + |
| 101 | + return generated_cmds |
| 102 | + |
| 103 | + |
| 104 | +def kubernetes_cmd_task( |
| 105 | + python_callable: Callable | None = None, |
| 106 | + **kwargs, |
| 107 | +) -> TaskDecorator: |
| 108 | + """ |
| 109 | + Kubernetes cmd operator decorator. |
| 110 | +
|
| 111 | + This wraps a function which should return command to be executed |
| 112 | + in K8s using KubernetesPodOperator. The function should return a list of strings. |
| 113 | + If args_only is set to True, the function should return a list of arguments for |
| 114 | + container default command. Also accepts any argument that KubernetesPodOperator |
| 115 | + will via ``kwargs``. Can be reused in a single DAG. |
| 116 | +
|
| 117 | + :param python_callable: Function to decorate |
| 118 | + """ |
| 119 | + return task_decorator_factory( |
| 120 | + python_callable=python_callable, |
| 121 | + decorated_operator_class=_KubernetesCmdDecoratedOperator, |
| 122 | + **kwargs, |
| 123 | + ) |
0 commit comments