Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions airflow/decorators/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,9 +302,9 @@ class _TaskDecorator(ExpandableFactory, Generic[FParams, FReturn, OperatorSubcla
decorator_name: str = attr.ib(repr=False, default="task")

_airflow_is_task_decorator: ClassVar[bool] = True
is_setup: ClassVar[bool] = False
is_teardown: ClassVar[bool] = False
on_failure_fail_dagrun: ClassVar[bool] = False
is_setup: bool = False
is_teardown: bool = False
on_failure_fail_dagrun: bool = False

@multiple_outputs.default
def _infer_multiple_outputs(self):
Expand Down Expand Up @@ -382,6 +382,10 @@ def expand(self, **map_kwargs: OperatorExpandArgument) -> XComArg:
prevent_duplicates(self.kwargs, map_kwargs, fail_reason="mapping already partial")
# Since the input is already checked at parse time, we can set strict
# to False to skip the checks on execution.
if self.is_teardown:
if "trigger_rule" in self.kwargs:
raise ValueError("Trigger rule not configurable for teardown tasks.")
self.kwargs.update(trigger_rule=TriggerRule.ALL_DONE_SETUP_SUCCESS)
Comment on lines +385 to +388

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably be in __attrs_post_init__? Also covers the non-mapped case.

return self._expand(DictOfListsExpandInput(map_kwargs), strict=False)

def expand_kwargs(self, kwargs: OperatorExpandKwargsArgument, *, strict: bool = True) -> XComArg:
Expand All @@ -406,7 +410,12 @@ def _expand(self, expand_input: ExpandInput, *, strict: bool) -> XComArg:
task_params=task_kwargs.pop("params", None),
task_default_args=task_kwargs.pop("default_args", None),
)
partial_kwargs.update(task_kwargs)
partial_kwargs.update(
task_kwargs,
is_setup=self.is_setup,
is_teardown=self.is_teardown,
on_failure_fail_dagrun=self.on_failure_fail_dagrun,
)

task_id = get_unique_task_id(partial_kwargs.pop("task_id"), dag, task_group)
if task_group:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

"""Add is_setup to task_instance

Revision ID: 0646b768db47
Revises: 788397e78828
Create Date: 2023-07-24 10:12:07.630608

"""

import sqlalchemy as sa
from alembic import op


# revision identifiers, used by Alembic.
revision = "0646b768db47"
down_revision = "788397e78828"
branch_labels = None
depends_on = None
airflow_version = "2.7.0"


TABLE_NAME = "task_instance"


def upgrade():
"""Apply is_setup column to task_instance"""
with op.batch_alter_table(TABLE_NAME) as batch_op:
batch_op.add_column(sa.Column("is_setup", sa.Boolean(), nullable=False, server_default="0"))


def downgrade():
"""Remove is_setup column from task_instance"""
with op.batch_alter_table(TABLE_NAME) as batch_op:
batch_op.drop_column("is_setup", mssql_drop_default=True)
44 changes: 8 additions & 36 deletions airflow/models/abstractoperator.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,6 @@ class AbstractOperator(Templater, DAGNode):
inlets: list
trigger_rule: TriggerRule

_is_setup = False
_is_teardown = False
_on_failure_fail_dagrun = False

HIDE_ATTRS_FROM_UI: ClassVar[frozenset[str]] = frozenset(
Expand Down Expand Up @@ -160,44 +158,20 @@ def node_id(self) -> str:
return self.task_id

@property
def is_setup(self):
"""
Whether the operator is a setup task.

:meta private:
"""
return self._is_setup
def is_setup(self) -> bool:
raise NotImplementedError()

@is_setup.setter
def is_setup(self, value):
"""
Setter for is_setup property.

:meta private:
"""
if self.is_teardown is True and value is True:
raise ValueError(f"Cannot mark task '{self.task_id}' as setup; task is already a teardown.")
self._is_setup = value
def is_setup(self, value: bool) -> None:
raise NotImplementedError()

@property
def is_teardown(self):
"""
Whether the operator is a teardown task.

:meta private:
"""
return self._is_teardown
def is_teardown(self) -> bool:
raise NotImplementedError()

@is_teardown.setter
def is_teardown(self, value):
"""
Setter for is_teardown property.

:meta private:
"""
if self.is_setup is True and value is True:
raise ValueError(f"Cannot mark task '{self.task_id}' as teardown; task is already a setup.")
self._is_teardown = value
def is_teardown(self, value: bool) -> None:
raise NotImplementedError()

@property
def on_failure_fail_dagrun(self):
Expand Down Expand Up @@ -233,8 +207,6 @@ def as_teardown(
on_failure_fail_dagrun=NOTSET,
):
self.is_teardown = True
if TYPE_CHECKING:
assert isinstance(self, BaseOperator) # is_teardown not supported for MappedOperator
self.trigger_rule = TriggerRule.ALL_DONE_SETUP_SUCCESS
if on_failure_fail_dagrun is not NOTSET:
self.on_failure_fail_dagrun = on_failure_fail_dagrun
Expand Down
42 changes: 42 additions & 0 deletions airflow/models/baseoperator.py
Original file line number Diff line number Diff line change
Expand Up @@ -957,6 +957,8 @@ def __init__(
)
self.template_fields = [self.template_fields]

self._is_setup = False
self._is_teardown = False
if SetupTeardownContext.active:
SetupTeardownContext.update_context_map(self)

Expand Down Expand Up @@ -1415,6 +1417,43 @@ def output(self) -> XComArg:

return XComArg(operator=self)

@property
def is_setup(self) -> bool:
"""Whether the operator is a setup task.

:meta private:
"""
return self._is_setup

@is_setup.setter
def is_setup(self, value: bool) -> None:
"""Setter for is_setup property.

:meta private:
"""
if self.is_teardown and value:
raise ValueError(f"Cannot mark task '{self.task_id}' as setup; task is already a teardown.")
self._is_setup = value

@property
def is_teardown(self) -> bool:
"""Whether the operator is a teardown task.

:meta private:
"""
return self._is_teardown

@is_teardown.setter
def is_teardown(self, value: bool) -> None:
"""
Setter for is_teardown property.

:meta private:
"""
if self.is_setup and value:
raise ValueError(f"Cannot mark task '{self.task_id}' as teardown; task is already a setup.")
self._is_teardown = value

@staticmethod
def xcom_push(
context: Any,
Expand Down Expand Up @@ -1501,6 +1540,9 @@ def get_serialized_fields(cls):
"_BaseOperator__instantiated",
"_BaseOperator__init_kwargs",
"_BaseOperator__from_mapped",
"_is_setup",
"_is_teardown",
"_on_failure_fail_dagrun",
}
| { # Class level defaults need to be added to this list
"start_date",
Expand Down
14 changes: 6 additions & 8 deletions airflow/models/dag.py
Original file line number Diff line number Diff line change
Expand Up @@ -2674,7 +2674,7 @@ def test(
conn_file_path: str | None = None,
variable_file_path: str | None = None,
session: Session = NEW_SESSION,
) -> None:
) -> DagRun:
"""
Execute one single DagRun for a given DAG and execution date.

Expand Down Expand Up @@ -2738,19 +2738,17 @@ def add_logger_if_needed(ti: TaskInstance):
# than creating a BackfillJob and allows us to surface logs to the user
while dr.state == DagRunState.RUNNING:
schedulable_tis, _ = dr.update_state(session=session)
try:
for ti in schedulable_tis:
for ti in schedulable_tis:
try:
add_logger_if_needed(ti)
ti.task = tasks[ti.task_id]
_run_task(ti, session=session)
except Exception:
self.log.info(
"Task failed. DAG will continue to run until finished and be marked as failed.",
exc_info=True,
)
except Exception:
self.log.exception("Task failed; ti=%s", ti)
if conn_file_path or variable_file_path:
# Remove the local variables we have added to the secrets_backend_list
secrets_backend_list.pop(0)
return dr

@provide_session
def create_dagrun(
Expand Down
2 changes: 1 addition & 1 deletion airflow/models/dagrun.py
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,7 @@ def recalculate(self) -> _UnfinishedStates:
msg="all_tasks_deadlocked",
)

# finally, if the roots aren't done, the dag is still running
# finally, if the leaves aren't done, the dag is still running
else:
self.set_state(DagRunState.RUNNING)

Expand Down
49 changes: 26 additions & 23 deletions airflow/models/mappedoperator.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,24 +324,6 @@ def __attrs_post_init__(self):
f"{self.task_id!r}."
)

@AbstractOperator.is_setup.setter # type: ignore[attr-defined]
def is_setup(self, value):
"""
Setter for is_setup property. Disabled for MappedOperator.

:meta private:
"""
raise ValueError("Cannot set is_setup for mapped operator.")

@AbstractOperator.is_teardown.setter # type: ignore[attr-defined]
def is_teardown(self, value):
"""
Setter for is_teardown property. Disabled for MappedOperator.

:meta private:
"""
raise ValueError("Cannot set is_teardown for mapped operator.")

@classmethod
@cache
def get_serialized_fields(cls):
Expand All @@ -354,9 +336,9 @@ def get_serialized_fields(cls):
"task_group",
"upstream_task_ids",
"supports_lineage",
"is_setup",
"is_teardown",
"on_failure_fail_dagrun",
"_is_setup",
"_is_teardown",
"_on_failure_fail_dagrun",
}

@staticmethod
Expand Down Expand Up @@ -408,8 +390,23 @@ def trigger_rule(self) -> TriggerRule:

@trigger_rule.setter
def trigger_rule(self, value):
# required for mypy which complains about overriding writeable attr with read-only property
raise ValueError("Cannot set trigger_rule for mapped operator.")
self.partial_kwargs["trigger_rule"] = value

@property
def is_setup(self) -> bool:
return bool(self.partial_kwargs.get("is_setup"))

@is_setup.setter
def is_setup(self, value: bool) -> None:
self.partial_kwargs["is_setup"] = value

@property
def is_teardown(self) -> bool:
return bool(self.partial_kwargs.get("is_teardown"))

@is_teardown.setter
def is_teardown(self, value: bool) -> None:
self.partial_kwargs["is_teardown"] = value

@property
def depends_on_past(self) -> bool:
Expand Down Expand Up @@ -640,12 +637,18 @@ def unmap(self, resolve: None | Mapping[str, Any] | tuple[Context, Session]) ->
else:
raise RuntimeError("cannot unmap a non-serialized operator without context")
kwargs = self._get_unmap_kwargs(kwargs, strict=self._disallow_kwargs_override)
is_setup = kwargs.pop("is_setup", False)
is_teardown = kwargs.pop("is_teardown", False)
on_failure_fail_dagrun = kwargs.pop("on_failure_fail_dagrun", False)
op = self.operator_class(**kwargs, _airflow_from_mapped=True)
# We need to overwrite task_id here because BaseOperator further
# mangles the task_id based on the task hierarchy (namely, group_id
# is prepended, and '__N' appended to deduplicate). This is hacky,
# but better than duplicating the whole mangling logic.
op.task_id = self.task_id
op.is_setup = is_setup
op.is_teardown = is_teardown
op.on_failure_fail_dagrun = on_failure_fail_dagrun
return op

# After a mapped operator is serialized, there's no real way to actually
Expand Down
5 changes: 5 additions & 0 deletions airflow/models/taskinstance.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import pendulum
from jinja2 import TemplateAssertionError, UndefinedError
from sqlalchemy import (
Boolean,
Column,
DateTime,
Float,
Expand Down Expand Up @@ -419,6 +420,7 @@ class TaskInstance(Base, LoggingMixin):
# Usually used when resuming from DEFERRED.
next_method = Column(String(1000))
next_kwargs = Column(MutableDict.as_mutable(ExtendedJSON))
is_setup = Column(Boolean, nullable=False, default=False, server_default="0")

# If adding new fields here then remember to add them to
# refresh_from_db() or they won't display in the UI correctly
Expand Down Expand Up @@ -577,6 +579,7 @@ def insert_mapping(run_id: str, task: Operator, map_index: int) -> dict[str, Any
"operator": task.task_type,
"custom_operator_name": getattr(task, "custom_operator_name", None),
"map_index": map_index,
"is_setup": task.is_setup,
}

@reconstructor
Expand Down Expand Up @@ -875,6 +878,7 @@ def refresh_from_db(self, session: Session = NEW_SESSION, lock_for_update: bool
self.trigger_id = ti.trigger_id
self.next_method = ti.next_method
self.next_kwargs = ti.next_kwargs
self.is_setup = ti.is_setup
else:
self.state = None

Expand All @@ -896,6 +900,7 @@ def refresh_from_task(self, task: Operator, pool_override: str | None = None) ->
self.executor_config = task.executor_config
self.operator = task.task_type
self.custom_operator_name = getattr(task, "custom_operator_name", None)
self.is_setup = task.is_setup

@provide_session
def clear_xcom_data(self, session: Session = NEW_SESSION) -> None:
Expand Down
2 changes: 0 additions & 2 deletions airflow/models/xcom_arg.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,8 +346,6 @@ def as_teardown(
):
for operator, _ in self.iter_references():
operator.is_teardown = True
if TYPE_CHECKING:
assert isinstance(operator, BaseOperator) # Can't set MappedOperator as teardown
operator.trigger_rule = TriggerRule.ALL_DONE_SETUP_SUCCESS
if on_failure_fail_dagrun is not NOTSET:
operator.on_failure_fail_dagrun = on_failure_fail_dagrun
Expand Down
Loading