airflow.models.taskinstance
¶
Module Contents¶
Classes¶
Key used to identify task instance. |
|
Task instances store the state of a task instance. This table is the |
|
Simplified Task Instance. |
Functions¶
|
Sets the current execution context to the provided context object. |
|
Load and return error from error file |
|
Write error into error file by path |
|
Clears a set of task instances, but makes sure the running ones |
Attributes¶
- airflow.models.taskinstance.set_current_context(context)[source]¶
Sets the current execution context to the provided context object. This method should be called once per Task execution, before calling operator.execute.
- airflow.models.taskinstance.set_error_file(error_file, error)[source]¶
Write error into error file by path
- airflow.models.taskinstance.clear_task_instances(tis, session, activate_dag_runs=None, dag=None, dag_run_state=DagRunState.QUEUED)[source]¶
Clears a set of task instances, but makes sure the running ones get killed.
- Parameters
tis – a list of task instances
session – current session
dag_run_state (Union[airflow.utils.state.DagRunState, airflow.typing_compat.Literal[False]]) – state to set DagRun to. If set to False, dagrun state will not be changed.
dag – DAG object
activate_dag_runs – Deprecated parameter, do not pass
- class airflow.models.taskinstance.TaskInstanceKey[source]¶
Bases:
NamedTuple
Key used to identify task instance.
- class airflow.models.taskinstance.TaskInstance(task, execution_date=None, run_id=None, state=None, map_index=-1)[source]¶
Bases:
airflow.models.base.Base
,airflow.utils.log.logging_mixin.LoggingMixin
Task instances store the state of a task instance. This table is the authority and single source of truth around what tasks have run and the state they are in.
The SqlAlchemy model doesn’t have a SqlAlchemy foreign key to the task or dag model deliberately to have more control over transactions.
Database transactions on this table should insure double triggers and any confusion around what task instances are or aren’t ready to run even while multiple schedulers may be firing task instances.
A value of -1 in map_index represents any of: a TI without mapped tasks; a TI with mapped tasks that has yet to be expanded (state=pending); a TI with mapped tasks that expanded to an empty list (state=skipped).
- property try_number[source]¶
Return the try number that this task number will be when it is actually run.
If the TaskInstance is currently running, this will match the column in the database, in all other cases this will be incremented.
- property prev_attempted_tries[source]¶
Based on this instance’s try_number, this will calculate the number of previously attempted tries, defaulting to 0.
- command_as_list(mark_success=False, ignore_all_deps=False, ignore_task_deps=False, ignore_depends_on_past=False, ignore_ti_state=False, local=False, pickle_id=None, raw=False, job_id=None, pool=None, cfg_path=None)[source]¶
Returns a command that can be executed anywhere where airflow is installed. This command is part of the message sent to executors by the orchestrator.
- static generate_command(dag_id, task_id, run_id, mark_success=False, ignore_all_deps=False, ignore_depends_on_past=False, ignore_task_deps=False, ignore_ti_state=False, local=False, pickle_id=None, file_path=None, raw=False, job_id=None, pool=None, cfg_path=None, map_index=-1)[source]¶
Generates the shell command required to execute this task instance.
- Parameters
dag_id (str) – DAG ID
task_id (str) – Task ID
run_id (str) – The run_id of this task’s DagRun
mark_success (bool) – Whether to mark the task as successful
ignore_all_deps (bool) – Ignore all ignorable dependencies. Overrides the other ignore_* parameters.
ignore_depends_on_past (bool) – Ignore depends_on_past parameter of DAGs (e.g. for Backfills)
ignore_task_deps (bool) – Ignore task-specific dependencies such as depends_on_past and trigger rule
ignore_ti_state (bool) – Ignore the task instance’s previous failure/success
local (bool) – Whether to run the task locally
pickle_id (Optional[int]) – If the DAG was serialized to the DB, the ID associated with the pickled DAG
file_path (Optional[str]) – path to the file containing the DAG definition
raw (bool) – raw mode (needs more details)
job_id (Optional[str]) – job ID (needs more details)
pool (Optional[str]) – the Airflow pool that the task should run in
cfg_path (Optional[str]) – the Path to the configuration file
- Returns
shell command that can be used to run the task instance
- Return type
- current_state(session=NEW_SESSION)[source]¶
Get the very latest state from the database, if a session is passed, we use and looking up the state becomes part of the session, otherwise a new session is used.
- Parameters
session – SQLAlchemy ORM Session
- error(session=NEW_SESSION)[source]¶
Forces the task instance’s state to FAILED in the database.
- Parameters
session – SQLAlchemy ORM Session
- refresh_from_db(session=NEW_SESSION, lock_for_update=False)[source]¶
Refreshes the task instance from the database based on the primary key
- Parameters
session – SQLAlchemy ORM Session
lock_for_update – if True, indicates that the database should lock the TaskInstance (issuing a FOR UPDATE clause) until the session is committed.
- refresh_from_task(task, pool_override=None)[source]¶
Copy common attributes from the given task.
- Parameters
task (airflow.models.operator.Operator) – The task object to copy from
pool_override – Use the pool_override instead of task’s pool
- clear_xcom_data(session=NEW_SESSION)[source]¶
Clear all XCom data from the database for the task instance.
If the task is unmapped, all XComs matching this task ID in the same DAG run are removed. If the task is mapped, only the one with matching map index is removed.
- Parameters
session (sqlalchemy.orm.session.Session) – SQLAlchemy ORM Session
- set_state(state, session=NEW_SESSION)[source]¶
Set TaskInstance state.
- Parameters
state (Optional[str]) – State to set for the TI
session – SQLAlchemy ORM Session
- property is_premature[source]¶
Returns whether a task is in UP_FOR_RETRY state and its retry interval has elapsed.
- are_dependents_done(session=NEW_SESSION)[source]¶
Checks whether the immediate dependents of this task instance have succeeded or have been skipped. This is meant to be used by wait_for_downstream.
This is useful when you do not want to start processing the next schedule of a task until the dependents are done. For instance, if the task DROPs and recreates a table.
- Parameters
session – SQLAlchemy ORM Session
- get_previous_dagrun(state=None, session=None)[source]¶
The DagRun that ran before this task instance’s DagRun.
- Parameters
state (Optional[airflow.utils.state.DagRunState]) – If passed, it only take into account instances of a specific state.
session (Optional[sqlalchemy.orm.session.Session]) – SQLAlchemy ORM Session.
- get_previous_ti(state=None, session=NEW_SESSION)[source]¶
The task instance for the task that ran before this task instance.
- Parameters
state (Optional[airflow.utils.state.DagRunState]) – If passed, it only take into account instances of a specific state.
session (sqlalchemy.orm.session.Session) – SQLAlchemy ORM Session
- property previous_ti[source]¶
This attribute is deprecated. Please use airflow.models.taskinstance.TaskInstance.get_previous_ti method.
- property previous_ti_success[source]¶
This attribute is deprecated. Please use airflow.models.taskinstance.TaskInstance.get_previous_ti method.
- get_previous_execution_date(state=None, session=NEW_SESSION)[source]¶
The execution date from property previous_ti_success.
- Parameters
state (Optional[airflow.utils.state.DagRunState]) – If passed, it only take into account instances of a specific state.
session (sqlalchemy.orm.session.Session) – SQLAlchemy ORM Session
- get_previous_start_date(state=None, session=NEW_SESSION)[source]¶
The start date from property previous_ti_success.
- Parameters
state (Optional[airflow.utils.state.DagRunState]) – If passed, it only take into account instances of a specific state.
session (sqlalchemy.orm.session.Session) – SQLAlchemy ORM Session
- property previous_start_date_success[source]¶
This attribute is deprecated. Please use airflow.models.taskinstance.TaskInstance.get_previous_start_date method.
- are_dependencies_met(dep_context=None, session=NEW_SESSION, verbose=False)[source]¶
Returns whether or not all the conditions are met for this task instance to be run given the context for the dependencies (e.g. a task instance being force run from the UI will ignore some dependencies).
- Parameters
dep_context – The execution context that determines the dependencies that should be evaluated.
session – database session
verbose – whether log details on failed dependencies on info or debug log level
- next_retry_datetime()[source]¶
Get datetime of the next retry if the task instance fails. For exponential backoff, retry_delay is used as base and will be converted to seconds.
- ready_for_retry()[source]¶
Checks on whether the task instance is in the right state and timeframe to be retried.
- get_dagrun(session=NEW_SESSION)[source]¶
Returns the DagRun for this TaskInstance
- Parameters
session (sqlalchemy.orm.session.Session) – SQLAlchemy ORM Session
- Returns
DagRun
- Return type
- check_and_change_state_before_execution(verbose=True, ignore_all_deps=False, ignore_depends_on_past=False, ignore_task_deps=False, ignore_ti_state=False, mark_success=False, test_mode=False, job_id=None, pool=None, external_executor_id=None, session=NEW_SESSION)[source]¶
Checks dependencies and then sets state to RUNNING if they are met. Returns True if and only if state is set to RUNNING, which implies that task should be executed, in preparation for _run_raw_task
- Parameters
verbose (bool) – whether to turn on more verbose logging
ignore_all_deps (bool) – Ignore all of the non-critical dependencies, just runs
ignore_depends_on_past (bool) – Ignore depends_on_past DAG attribute
ignore_task_deps (bool) – Don’t check the dependencies of this TaskInstance’s task
ignore_ti_state (bool) – Disregards previous task instance state
mark_success (bool) – Don’t run the task, mark its state as success
test_mode (bool) – Doesn’t record success or failure in the DB
job_id (Optional[str]) – Job (BackfillJob / LocalTaskJob / SchedulerJob) ID
pool (Optional[str]) – specifies the pool to use to run the task instance
external_executor_id (Optional[str]) – The identifier of the celery executor
session – SQLAlchemy ORM Session
- Returns
whether the state was changed to running or not
- Return type
- run(verbose=True, ignore_all_deps=False, ignore_depends_on_past=False, ignore_task_deps=False, ignore_ti_state=False, mark_success=False, test_mode=False, job_id=None, pool=None, session=NEW_SESSION)[source]¶
Run TaskInstance
- static get_truncated_error_traceback(error, truncate_to)[source]¶
Truncates the traceback of an exception to the first frame called from within a given function
- Parameters
error (BaseException) – exception to get traceback from
truncate_to (Callable) – Function to truncate TB to. Must have a
__code__
attribute
- handle_failure(error, test_mode=None, force_fail=False, error_file=None, session=NEW_SESSION)[source]¶
Handle Failure for the TaskInstance
- get_rendered_template_fields(session=NEW_SESSION)[source]¶
Update task with rendered template fields for presentation in UI. If task has already run, will fetch from DB; otherwise will render.
- render_templates(context=None)[source]¶
Render templates in the operator fields.
If the task was originally mapped, this may replace
self.task
with the unmapped, fully rendered BaseOperator. The originalself.task
before replacement is returned.
- get_email_subject_content(exception, task=None)[source]¶
Get the email subject content for exceptions.
- xcom_push(key, value, execution_date=None, session=NEW_SESSION)[source]¶
Make an XCom available for tasks to pull.
- Parameters
key (str) – Key to store the value under.
value (Any) – Value to store. What types are possible depends on whether
enable_xcom_pickling
is true or not. If so, this can be any picklable object; only be JSON-serializable may be used otherwise.execution_date (Optional[datetime.datetime]) – Deprecated parameter that has no effect.
- xcom_pull(task_ids=None, dag_id=None, key=XCOM_RETURN_KEY, include_prior_dates=False, session=NEW_SESSION, *, map_indexes=None, default=None)[source]¶
Pull XComs that optionally meet certain criteria.
- Parameters
key (str) – A key for the XCom. If provided, only XComs with matching keys will be returned. The default key is
'return_value'
, also available as constantXCOM_RETURN_KEY
. This key is automatically given to XComs returned by tasks (as opposed to being pushed manually). To remove the filter, pass None.task_ids (Optional[Union[str, Iterable[str]]]) – Only XComs from tasks with matching ids will be pulled. Pass None to remove the filter.
dag_id (Optional[str]) – If provided, only pulls XComs from this DAG. If None (default), the DAG of the calling task is used.
map_indexes (Optional[Union[int, Iterable[int]]]) – If provided, only pull XComs with matching indexes. If None (default), this is inferred from the task(s) being pulled (see below for details).
include_prior_dates (bool) – If False, only XComs from the current execution_date are returned. If True, XComs from previous dates are returned as well.
When pulling one single task (
task_id
is None or a str) without specifyingmap_indexes
, the return value is inferred from whether the specified task is mapped. If not, value from the one single task instance is returned. If the task to pull is mapped, an iterator (not a list) yielding XComs from mapped task instances is returned. In either case,default
(None if not specified) is returned if no matching XComs are found.When pulling multiple tasks (i.e. either
task_id
ormap_index
is a non-str iterable), a list of matching XComs is returned. Elements in the list is ordered by item ordering intask_id
andmap_index
.