-
Notifications
You must be signed in to change notification settings - Fork 17.5k
Add ability to clear downstream tis in "List Task Instances" view #34529
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
hussein-awala
merged 8 commits into
apache:main
from
peloyeje:feature/clear-with-downstream
Sep 22, 2023
Merged
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
3347671
Add "clear including downstream" action in task instance view
5255185
Extract logic into helper + support dynamic tasks
ab8b502
Add unit test
8cde29c
Restore quick path for ti clear without downstream
peloyeje 73d709d
Fix wording
peloyeje 8edf8c2
Call clear_task_instances once per dag + split cleared ti count
peloyeje 9e5a466
Handle plural
peloyeje d3970a0
Update airflow/www/views.py
hussein-awala File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -31,7 +31,16 @@ | |
| from collections import defaultdict | ||
| from functools import cached_property, wraps | ||
| from json import JSONDecodeError | ||
| from typing import TYPE_CHECKING, Any, Callable, Collection, Iterator, Mapping, MutableMapping, Sequence | ||
| from typing import ( | ||
| TYPE_CHECKING, | ||
| Any, | ||
| Callable, | ||
| Collection, | ||
| Iterator, | ||
| Mapping, | ||
| MutableMapping, | ||
| Sequence, | ||
| ) | ||
| from urllib.parse import unquote, urljoin, urlsplit | ||
|
|
||
| import configupdater | ||
|
|
@@ -5657,6 +5666,7 @@ class TaskInstanceModelView(AirflowPrivilegeVerifierModelView): | |
| "list": "read", | ||
| "delete": "delete", | ||
| "action_clear": "edit", | ||
| "action_clear_downstream": "edit", | ||
| "action_muldelete": "delete", | ||
| "action_set_running": "edit", | ||
| "action_set_failed": "edit", | ||
|
|
@@ -5793,6 +5803,68 @@ def duration_f(self): | |
| "duration": duration_f, | ||
| } | ||
|
|
||
| def _clear_task_instances( | ||
| self, task_instances: list[TaskInstance], session: Session, clear_downstream: bool = False | ||
| ) -> tuple[int, int]: | ||
| """ | ||
| Clears task instances, optionally including their downstream dependencies. | ||
|
|
||
| :param task_instances: list of TIs to clear | ||
| :param clear_downstream: should downstream task instances be cleared as well? | ||
|
|
||
| :return: a tuple with: | ||
| - count of cleared task instances actually selected by the user | ||
| - count of downstream task instances that were additionally cleared | ||
| """ | ||
| cleared_tis_count = 0 | ||
| cleared_downstream_tis_count = 0 | ||
|
|
||
| # Group TIs by dag id in order to call `get_dag` only once per dag | ||
| tis_grouped_by_dag_id = itertools.groupby(task_instances, lambda ti: ti.dag_id) | ||
|
|
||
| for dag_id, dag_tis in tis_grouped_by_dag_id: | ||
| dag = get_airflow_app().dag_bag.get_dag(dag_id) | ||
|
|
||
| tis_to_clear = list(dag_tis) | ||
| downstream_tis_to_clear = [] | ||
|
|
||
| if clear_downstream: | ||
| tis_to_clear_grouped_by_dag_run = itertools.groupby(tis_to_clear, lambda ti: ti.dag_run) | ||
|
|
||
| for dag_run, dag_run_tis in tis_to_clear_grouped_by_dag_run: | ||
| # Determine tasks that are downstream of the cleared TIs and fetch associated TIs | ||
| # This has to be run for each dag run because the user may clear different TIs across runs | ||
| task_ids_to_clear = [ti.task_id for ti in dag_run_tis] | ||
|
|
||
| partial_dag = dag.partial_subset( | ||
| task_ids_or_regex=task_ids_to_clear, include_downstream=True, include_upstream=False | ||
| ) | ||
|
|
||
| downstream_task_ids_to_clear = [ | ||
| task_id for task_id in partial_dag.task_dict if task_id not in task_ids_to_clear | ||
| ] | ||
|
|
||
| # dag.clear returns TIs when in dry run mode | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
| downstream_tis_to_clear.extend( | ||
| dag.clear( | ||
| start_date=dag_run.execution_date, | ||
| end_date=dag_run.execution_date, | ||
| task_ids=downstream_task_ids_to_clear, | ||
| include_subdags=False, | ||
| include_parentdag=False, | ||
| session=session, | ||
| dry_run=True, | ||
| ) | ||
| ) | ||
|
|
||
| # Once all TIs are fetched, perform the actual clearing | ||
| models.clear_task_instances(tis=tis_to_clear + downstream_tis_to_clear, session=session, dag=dag) | ||
|
|
||
| cleared_tis_count += len(tis_to_clear) | ||
| cleared_downstream_tis_count += len(downstream_tis_to_clear) | ||
|
|
||
| return cleared_tis_count, cleared_downstream_tis_count | ||
|
|
||
| @action( | ||
| "clear", | ||
| lazy_gettext("Clear"), | ||
|
|
@@ -5806,21 +5878,45 @@ def duration_f(self): | |
| @provide_session | ||
| @action_logging | ||
| def action_clear(self, task_instances, session: Session = NEW_SESSION): | ||
| """Clears the action.""" | ||
| """Clears an arbitrary number of task instances.""" | ||
| try: | ||
| dag_to_tis = collections.defaultdict(list) | ||
|
|
||
| for ti in task_instances: | ||
| dag = get_airflow_app().dag_bag.get_dag(ti.dag_id) | ||
| dag_to_tis[dag].append(ti) | ||
| count, _ = self._clear_task_instances( | ||
| task_instances=task_instances, session=session, clear_downstream=False | ||
| ) | ||
| session.commit() | ||
| flash(f"{count} task instance{'s have' if count > 1 else ' has'} been cleared") | ||
| except Exception as e: | ||
| flash(f'Failed to clear task instances: "{e}"', "error") | ||
|
|
||
| for dag, task_instances_list in dag_to_tis.items(): | ||
| models.clear_task_instances(task_instances_list, session, dag=dag) | ||
| self.update_redirect() | ||
| return redirect(self.get_redirect()) | ||
|
|
||
| @action( | ||
| "clear_downstream", | ||
| lazy_gettext("Clear (including downstream tasks)"), | ||
| lazy_gettext( | ||
| "Are you sure you want to clear the state of the selected task" | ||
| " instance(s) and all their downstream dependencies, and set their dagruns to the QUEUED state?" | ||
| ), | ||
| single=False, | ||
| ) | ||
| @action_has_dag_edit_access | ||
| @provide_session | ||
| @action_logging | ||
| def action_clear_downstream(self, task_instances, session: Session = NEW_SESSION): | ||
| """Clears an arbitrary number of task instances, including downstream dependencies.""" | ||
| try: | ||
| selected_ti_count, downstream_ti_count = self._clear_task_instances( | ||
| task_instances=task_instances, session=session, clear_downstream=True | ||
| ) | ||
| session.commit() | ||
| flash(f"{len(task_instances)} task instances have been cleared") | ||
| flash( | ||
| f"Cleared {selected_ti_count} selected task instance{'s' if selected_ti_count > 1 else ''} " | ||
| f"and {downstream_ti_count} downstream dependencies" | ||
| ) | ||
| except Exception as e: | ||
| flash(f'Failed to clear task instances: "{e}"', "error") | ||
|
|
||
| self.update_redirect() | ||
| return redirect(self.get_redirect()) | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.