response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
List all hooks at the command line. | def hooks_list(args):
"""List all hooks at the command line."""
AirflowConsole().print_as(
data=list(ProvidersManager().hooks.items()),
output=args.output,
mapper=lambda x: {
"connection_type": x[0],
"class": x[1].hook_class_name if x[1] else ERROR_IMPORTING_HOOK,... |
List all custom connection form fields at the command line. | def connection_form_widget_list(args):
"""List all custom connection form fields at the command line."""
AirflowConsole().print_as(
data=sorted(ProvidersManager().connection_form_widgets.items()),
output=args.output,
mapper=lambda x: {
"connection_parameter_name": x[0],
... |
List field behaviours. | def connection_field_behaviours(args):
"""List field behaviours."""
AirflowConsole().print_as(
data=list(ProvidersManager().field_behaviours),
output=args.output,
mapper=lambda x: {
"field_behaviours": x,
},
) |
List all extra links at the command line. | def extra_links_list(args):
"""List all extra links at the command line."""
AirflowConsole().print_as(
data=ProvidersManager().extra_links_class_names,
output=args.output,
mapper=lambda x: {
"extra_link_class_name": x,
},
) |
List all log task handlers at the command line. | def logging_list(args):
"""List all log task handlers at the command line."""
AirflowConsole().print_as(
data=list(ProvidersManager().logging_class_names),
output=args.output,
mapper=lambda x: {
"logging_class_name": x,
},
) |
List all secrets backends at the command line. | def secrets_backends_list(args):
"""List all secrets backends at the command line."""
AirflowConsole().print_as(
data=list(ProvidersManager().secrets_backend_class_names),
output=args.output,
mapper=lambda x: {
"secrets_backend_class_name": x,
},
) |
List all API auth backend modules at the command line. | def auth_backend_list(args):
"""List all API auth backend modules at the command line."""
AirflowConsole().print_as(
data=list(ProvidersManager().auth_backend_module_names),
output=args.output,
mapper=lambda x: {
"api_auth_backend_module": x,
},
) |
List all auth managers at the command line. | def auth_managers_list(args):
"""List all auth managers at the command line."""
AirflowConsole().print_as(
data=list(ProvidersManager().auth_managers),
output=args.output,
mapper=lambda x: {
"auth_managers_module": x,
},
) |
List all executors at the command line. | def executors_list(args):
"""List all executors at the command line."""
AirflowConsole().print_as(
data=list(ProvidersManager().executor_class_names),
output=args.output,
mapper=lambda x: {
"executor_class_names": x,
},
) |
List all configurations at the command line. | def config_list(args):
"""List all configurations at the command line."""
AirflowConsole().print_as(
data=list(ProvidersManager().provider_configs),
output=args.output,
mapper=lambda x: {
"provider_config": x,
},
) |
Informs if providers manager has been initialized too early.
If provider is initialized, shows the stack trace and exit with error code 1. | def lazy_loaded(args):
"""Informs if providers manager has been initialized too early.
If provider is initialized, shows the stack trace and exit with error code 1.
"""
import rich
if ProvidersManager.initialized():
rich.print(
"\n[red]ProvidersManager was initialized during CL... |
Rotates all encrypted connection credentials and variables. | def rotate_fernet_key(args):
"""Rotates all encrypted connection credentials and variables."""
with create_session() as session:
conns_query = select(Connection).where(Connection.is_encrypted | Connection.is_extra_encrypted)
for conn in session.scalars(conns_query):
conn.rotate_ferne... |
Start Airflow Scheduler. | def scheduler(args: Namespace):
"""Start Airflow Scheduler."""
print(settings.HEADER)
run_command_with_daemon_option(
args=args,
process_name="scheduler",
callback=lambda: _run_scheduler_job(args),
should_setup_logging=True,
) |
Start serve_logs sub-process. | def _serve_logs(skip_serve_logs: bool = False):
"""Start serve_logs sub-process."""
from airflow.utils.serve_logs import serve_logs
sub_proc = None
executor_class, _ = ExecutorLoader.import_default_executor_cls()
if executor_class.serve_logs:
if skip_serve_logs is False:
sub_pr... |
Start serve_health_check sub-process. | def _serve_health_check(enable_health_check: bool = False):
"""Start serve_health_check sub-process."""
sub_proc = None
if enable_health_check:
sub_proc = Process(target=serve_health_check)
sub_proc.start()
try:
yield
finally:
if sub_proc:
sub_proc.termin... |
Generate a ``run_id`` for a DAG run that will be created temporarily.
This is used mostly by ``airflow task test`` to create a DAG run that will
be deleted after the task is run. | def _generate_temporary_run_id() -> str:
"""Generate a ``run_id`` for a DAG run that will be created temporarily.
This is used mostly by ``airflow task test`` to create a DAG run that will
be deleted after the task is run.
"""
return f"__airflow_temporary_run_{timezone.utcnow().isoformat()}__" |
Try to retrieve a DAG run from a string representing either a run ID or logical date.
This checks DAG runs like this:
1. If the input ``exec_date_or_run_id`` matches a DAG run ID, return the run.
2. Try to parse the input as a date. If that works, and the resulting
date matches a DAG run's logical date, return the... | def _get_dag_run(
*,
dag: DAG,
create_if_necessary: CreateIfNecessary,
exec_date_or_run_id: str | None = None,
session: Session | None = None,
) -> tuple[DagRun | DagRunPydantic, bool]:
"""Try to retrieve a DAG run from a string representing either a run ID or logical date.
This checks DAG ... |
Get the task instance through DagRun.run_id, if that fails, get the TI the old way. | def _get_ti_db_access(
dag: DAG,
task: Operator,
map_index: int,
*,
exec_date_or_run_id: str | None = None,
pool: str | None = None,
create_if_necessary: CreateIfNecessary = False,
session: Session = NEW_SESSION,
) -> tuple[TaskInstance | TaskInstancePydantic, bool]:
"""Get the task ... |
Run the task based on a mode.
Any of the 3 modes are available:
- using LocalTaskJob
- as raw task
- by executor | def _run_task_by_selected_method(
args, dag: DAG, ti: TaskInstance | TaskInstancePydantic
) -> None | TaskReturnCode:
"""
Run the task based on a mode.
Any of the 3 modes are available:
- using LocalTaskJob
- as raw task
- by executor
"""
if TYPE_CHECKING:
assert not isinst... |
Send the task to the executor for execution.
This can result in the task being started by another host if the executor implementation does. | def _run_task_by_executor(args, dag: DAG, ti: TaskInstance) -> None:
"""
Send the task to the executor for execution.
This can result in the task being started by another host if the executor implementation does.
"""
pickle_id = None
if args.ship_dag:
try:
# Running remotely... |
Run LocalTaskJob, which monitors the raw task execution process. | def _run_task_by_local_task_job(args, ti: TaskInstance | TaskInstancePydantic) -> TaskReturnCode | None:
"""Run LocalTaskJob, which monitors the raw task execution process."""
if InternalApiConfig.get_use_internal_api():
from airflow.models.renderedtifields import RenderedTaskInstanceFields # noqa: F40... |
Run the main task handling code. | def _run_raw_task(args, ti: TaskInstance) -> None | TaskReturnCode:
"""Run the main task handling code."""
return ti._run_raw_task(
mark_success=args.mark_success,
job_id=args.job_id,
pool=args.pool,
) |
Move handlers for task logging to root logger.
We want anything logged during task run to be propagated to task log handlers.
If running in a k8s executor pod, also keep the stream handler on root logger
so that logs are still emitted to stdout. | def _move_task_handlers_to_root(ti: TaskInstance | TaskInstancePydantic) -> Generator[None, None, None]:
"""
Move handlers for task logging to root logger.
We want anything logged during task run to be propagated to task log handlers.
If running in a k8s executor pod, also keep the stream handler on ro... |
Redirect stdout to ti logger.
Redirect stdout and stderr to the task instance log as INFO and WARNING
level messages, respectively.
If stdout already redirected (possible when task running with option
`--local`), don't redirect again. | def _redirect_stdout_to_ti_log(ti: TaskInstance | TaskInstancePydantic) -> Generator[None, None, None]:
"""
Redirect stdout to ti logger.
Redirect stdout and stderr to the task instance log as INFO and WARNING
level messages, respectively.
If stdout already redirected (possible when task running w... |
Run a single task instance.
Note that there must be at least one DagRun for this to start,
i.e. it must have been scheduled and/or triggered previously.
Alternatively, if you just need to run it for testing then use
"airflow tasks test ..." command instead. | def task_run(args, dag: DAG | None = None) -> TaskReturnCode | None:
"""
Run a single task instance.
Note that there must be at least one DagRun for this to start,
i.e. it must have been scheduled and/or triggered previously.
Alternatively, if you just need to run it for testing then use
"airfl... |
Get task instance dependencies that were not met.
Returns the unmet dependencies for a task instance from the perspective of the
scheduler (i.e. why a task instance doesn't get scheduled and then queued by the
scheduler, and then run by an executor).
>>> airflow tasks failed-deps tutorial sleep 2015-01-01
Task instanc... | def task_failed_deps(args) -> None:
"""
Get task instance dependencies that were not met.
Returns the unmet dependencies for a task instance from the perspective of the
scheduler (i.e. why a task instance doesn't get scheduled and then queued by the
scheduler, and then run by an executor).
>>> ... |
Return the state of a TaskInstance at the command line.
>>> airflow tasks state tutorial sleep 2015-01-01
success | def task_state(args) -> None:
"""
Return the state of a TaskInstance at the command line.
>>> airflow tasks state tutorial sleep 2015-01-01
success
"""
dag = get_dag(args.subdir, args.dag_id)
task = dag.get_task(task_id=args.task_id)
ti, _ = _get_ti(task, args.map_index, exec_date_or_ru... |
List the tasks within a DAG at the command line. | def task_list(args, dag: DAG | None = None) -> None:
"""List the tasks within a DAG at the command line."""
dag = dag or get_dag(args.subdir, args.dag_id)
if args.tree:
dag.tree_view()
else:
tasks = sorted(t.task_id for t in dag.tasks)
print("\n".join(tasks)) |
Try to guess the debugger used by the user.
When it doesn't find any user-installed debugger, returns ``pdb``.
List of supported debuggers:
* `pudb <https://github.com/inducer/pudb>`__
* `web_pdb <https://github.com/romanvm/python-web-pdb>`__
* `ipdb <https://github.com/gotcha/ipdb>`__
* `pdb <https://docs.python.or... | def _guess_debugger() -> _SupportedDebugger:
"""
Try to guess the debugger used by the user.
When it doesn't find any user-installed debugger, returns ``pdb``.
List of supported debuggers:
* `pudb <https://github.com/inducer/pudb>`__
* `web_pdb <https://github.com/romanvm/python-web-pdb>`__
... |
Get the status of all task instances in a DagRun. | def task_states_for_dag_run(args, session: Session = NEW_SESSION) -> None:
"""Get the status of all task instances in a DagRun."""
dag_run = session.scalar(
select(DagRun).where(DagRun.run_id == args.execution_date_or_run_id, DagRun.dag_id == args.dag_id)
)
if not dag_run:
try:
... |
Test task for a given dag_id. | def task_test(args, dag: DAG | None = None, session: Session = NEW_SESSION) -> None:
"""Test task for a given dag_id."""
# We want to log output from operators etc to show up here. Normally
# airflow.task would redirect to a file, but here we want it to propagate
# up to the normal airflow handler.
... |
Render and displays templated fields for a given task. | def task_render(args, dag: DAG | None = None) -> None:
"""Render and displays templated fields for a given task."""
if not dag:
dag = get_dag(args.subdir, args.dag_id)
task = dag.get_task(task_id=args.task_id)
ti, _ = _get_ti(
task, args.map_index, exec_date_or_run_id=args.execution_date... |
Clear all task instances or only those matched by regex for a DAG(s). | def task_clear(args) -> None:
"""Clear all task instances or only those matched by regex for a DAG(s)."""
logging.basicConfig(level=settings.LOGGING_LEVEL, format=settings.SIMPLE_LOG_FORMAT)
if args.dag_id and not args.subdir and not args.dag_regex and not args.task_regex:
dags = [get_dag_by_file_l... |
Start serve_logs sub-process. | def _serve_logs(skip_serve_logs: bool = False) -> Generator[None, None, None]:
"""Start serve_logs sub-process."""
sub_proc = None
if skip_serve_logs is False:
port = conf.getint("logging", "trigger_log_server_port", fallback=8794)
sub_proc = Process(target=partial(serve_logs, port=port))
... |
Start Airflow Triggerer. | def triggerer(args):
"""Start Airflow Triggerer."""
settings.MASK_SECRETS_IN_LOGS = True
print(settings.HEADER)
triggerer_heartrate = conf.getfloat("triggerer", "JOB_HEARTBEAT_SEC")
run_command_with_daemon_option(
args=args,
process_name="triggerer",
callback=lambda: trigger... |
Display all the variables. | def variables_list(args):
"""Display all the variables."""
with create_session() as session:
variables = session.scalars(select(Variable)).all()
AirflowConsole().print_as(data=variables, output=args.output, mapper=lambda x: {"key": x.key}) |
Display variable by a given name. | def variables_get(args):
"""Display variable by a given name."""
try:
if args.default is None:
var = Variable.get(args.key, deserialize_json=args.json)
print(var)
else:
var = Variable.get(args.key, deserialize_json=args.json, default_var=args.default)
... |
Create new variable with a given name, value and description. | def variables_set(args):
"""Create new variable with a given name, value and description."""
Variable.set(args.key, args.value, args.description, serialize_json=args.json)
print(f"Variable {args.key} created") |
Delete variable by a given name. | def variables_delete(args):
"""Delete variable by a given name."""
Variable.delete(args.key)
print(f"Variable {args.key} deleted") |
Import variables from a given file. | def variables_import(args, session):
"""Import variables from a given file."""
if not os.path.exists(args.file):
raise SystemExit("Missing variables file.")
with open(args.file) as varfile:
try:
var_json = json.load(varfile)
except JSONDecodeError:
raise Syste... |
Export all the variables to the file. | def variables_export(args):
"""Export all the variables to the file."""
var_dict = {}
with create_session() as session:
qry = session.scalars(select(Variable))
data = json.JSONDecoder()
for var in qry:
try:
val = data.decode(var.val)
except Ex... |
Display Airflow version at the command line. | def version(args):
"""Display Airflow version at the command line."""
print(airflow.__version__) |
Start Airflow Webserver. | def webserver(args):
"""Start Airflow Webserver."""
print(settings.HEADER)
# Check for old/insecure config, and fail safe (i.e. don't launch) if the config is wildly insecure.
if conf.get("webserver", "secret_key") == "temporary_key":
from rich import print as rich_print
rich_print(
... |
Retrieve the dataset manager. | def resolve_dataset_manager() -> DatasetManager:
"""Retrieve the dataset manager."""
_dataset_manager_class = conf.getimport(
section="core",
key="dataset_manager_class",
fallback="airflow.datasets.manager.DatasetManager",
)
_dataset_manager_kwargs = conf.getjson(
section... |
Place-hold a :class:`~urllib.parse.SplitResult`` normalizer.
:meta private: | def normalize_noop(parts: SplitResult) -> SplitResult:
"""Place-hold a :class:`~urllib.parse.SplitResult`` normalizer.
:meta private:
"""
return parts |
Sanitize a dataset URI.
This checks for URI validity, and normalizes the URI if needed. A fully
normalized URI is returned. | def _sanitize_uri(uri: str) -> str:
"""Sanitize a dataset URI.
This checks for URI validity, and normalizes the URI if needed. A fully
normalized URI is returned.
"""
if not uri:
raise ValueError("Dataset URI cannot be empty")
if uri.isspace():
raise ValueError("Dataset URI can... |
Coerce a user input into a sanitized URI.
If the input value is a string, it is treated as a URI and sanitized. If the
input is a :class:`Dataset`, the URI it contains is considered sanitized and
returned directly.
:meta private: | def coerce_to_uri(value: str | Dataset) -> str:
"""Coerce a user input into a sanitized URI.
If the input value is a string, it is treated as a URI and sanitized. If the
input is a :class:`Dataset`, the URI it contains is considered sanitized and
returned directly.
:meta private:
"""
if is... |
Generate unique task id given a DAG (or if run in a DAG context).
IDs are generated by appending a unique number to the end of
the original task id.
Example:
task_id
task_id__1
task_id__2
...
task_id__20 | def get_unique_task_id(
task_id: str,
dag: DAG | None = None,
task_group: TaskGroup | None = None,
) -> str:
"""
Generate unique task id given a DAG (or if run in a DAG context).
IDs are generated by appending a unique number to the end of
the original task id.
Example:
task_id
... |
Generate a wrapper that wraps a function into an Airflow operator.
Can be reused in a single DAG.
:param python_callable: Function to decorate.
:param multiple_outputs: If set to True, the decorated function's return
value will be unrolled to multiple XCom values. Dict will unroll to XCom
values with its keys... | def task_decorator_factory(
python_callable: Callable | None = None,
*,
multiple_outputs: bool | None = None,
decorated_operator_class: type[BaseOperator],
**kwargs,
) -> TaskDecorator:
"""Generate a wrapper that wraps a function into an Airflow operator.
Can be reused in a single DAG.
... |
Wrap a function into a BashOperator.
Accepts kwargs for operator kwargs. Can be reused in a single DAG. This function is only used only used
during type checking or auto-completion.
:param python_callable: Function to decorate.
:meta private: | def bash_task(
python_callable: Callable | None = None,
**kwargs,
) -> TaskDecorator:
"""Wrap a function into a BashOperator.
Accepts kwargs for operator kwargs. Can be reused in a single DAG. This function is only used only used
during type checking or auto-completion.
:param python_callable:... |
Wrap a python function into a BranchExternalPythonOperator.
For more information on how to use this operator, take a look at the guide:
:ref:`concepts:branching`
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
:param python_callable: Function to decorate
:param multiple_outputs: if set, function re... | def branch_external_python_task(
python_callable: Callable | None = None, multiple_outputs: bool | None = None, **kwargs
) -> TaskDecorator:
"""
Wrap a python function into a BranchExternalPythonOperator.
For more information on how to use this operator, take a look at the guide:
:ref:`concepts:bra... |
Wrap a python function into a BranchPythonOperator.
For more information on how to use this operator, take a look at the guide:
:ref:`concepts:branching`
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
:param python_callable: Function to decorate
:param multiple_outputs: if set, function return val... | def branch_task(
python_callable: Callable | None = None, multiple_outputs: bool | None = None, **kwargs
) -> TaskDecorator:
"""
Wrap a python function into a BranchPythonOperator.
For more information on how to use this operator, take a look at the guide:
:ref:`concepts:branching`
Accepts kwa... |
Wrap a python function into a BranchPythonVirtualenvOperator.
For more information on how to use this operator, take a look at the guide:
:ref:`concepts:branching`
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
:param python_callable: Function to decorate
:param multiple_outputs: if set, function ... | def branch_virtualenv_task(
python_callable: Callable | None = None, multiple_outputs: bool | None = None, **kwargs
) -> TaskDecorator:
"""
Wrap a python function into a BranchPythonVirtualenvOperator.
For more information on how to use this operator, take a look at the guide:
:ref:`concepts:branch... |
Wrap a callable into an Airflow operator to run via a Python virtual environment.
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
This function is only used during type checking or auto-completion.
:meta private:
:param python: Full path string (file-system specific) that points to a Python binary... | def external_python_task(
python: str | None = None,
python_callable: Callable | None = None,
multiple_outputs: bool | None = None,
**kwargs,
) -> TaskDecorator:
"""
Wrap a callable into an Airflow operator to run via a Python virtual environment.
Accepts kwargs for operator kwarg. Can be r... |
Wrap a function into an Airflow operator.
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
:param python_callable: Function to decorate
:param multiple_outputs: If set to True, the decorated function's return value will be unrolled to
multiple XCom values. Dict will unroll to XCom values with its... | def python_task(
python_callable: Callable | None = None,
multiple_outputs: bool | None = None,
**kwargs,
) -> TaskDecorator:
"""
Wrap a function into an Airflow operator.
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
:param python_callable: Function to decorate
:pa... |
Wrap a callable into an Airflow operator to run via a Python virtual environment.
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
This function is only used only used during type checking or auto-completion.
:meta private:
:param python_callable: Function to decorate
:param multiple_outputs: If se... | def virtualenv_task(
python_callable: Callable | None = None,
multiple_outputs: bool | None = None,
**kwargs,
) -> TaskDecorator:
"""
Wrap a callable into an Airflow operator to run via a Python virtual environment.
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
This fun... |
Wrap a function into an Airflow operator.
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
:param python_callable: Function to decorate | def sensor_task(python_callable: Callable | None = None, **kwargs) -> TaskDecorator:
"""
Wrap a function into an Airflow operator.
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
:param python_callable: Function to decorate
"""
return task_decorator_factory(
python_cal... |
Wrap a function into an ShortCircuitOperator.
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
This function is only used only used during type checking or auto-completion.
:param python_callable: Function to decorate
:param multiple_outputs: If set to True, the decorated function's return value wil... | def short_circuit_task(
python_callable: Callable | None = None,
multiple_outputs: bool | None = None,
**kwargs,
) -> TaskDecorator:
"""
Wrap a function into an ShortCircuitOperator.
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
This function is only used only used duri... |
Python TaskGroup decorator.
This wraps a function into an Airflow TaskGroup. When used as the
``@task_group()`` form, all arguments are forwarded to the underlying
TaskGroup class. Can be used to parametrize TaskGroup.
:param python_callable: Function to decorate.
:param tg_kwargs: Keyword arguments for the TaskGroup... | def task_group(python_callable=None, **tg_kwargs):
"""Python TaskGroup decorator.
This wraps a function into an Airflow TaskGroup. When used as the
``@task_group()`` form, all arguments are forwarded to the underlying
TaskGroup class. Can be used to parametrize TaskGroup.
:param python_callable: F... |
Determine which empty_task should be run based on if the execution date minute is even or odd.
:param dict kwargs: Context
:return: Id of the task to run | def should_run(**kwargs) -> str:
"""
Determine which empty_task should be run based on if the execution date minute is even or odd.
:param dict kwargs: Context
:return: Id of the task to run
"""
print(
f"------------- exec dttm = {kwargs['execution_date']} and minute = {kwargs['executio... |
DAG to send server IP to email.
:param email: Email to send IP to. Defaults to example@example.com. | def example_dag_decorator(email: str = "example@example.com"):
"""
DAG to send server IP to email.
:param email: Email to send IP to. Defaults to example@example.com.
"""
get_ip = GetRequestOperator(task_id="get_ip", url="http://httpbin.org/get")
@task(multiple_outputs=True)
def prepare_em... |
Print out the "foo" param passed in via
`airflow tasks test example_passing_params_via_test_command run_this <date>
-t '{"foo":"bar"}'` | def my_py_command(params, test_mode=None, task=None):
"""
Print out the "foo" param passed in via
`airflow tasks test example_passing_params_via_test_command run_this <date>
-t '{"foo":"bar"}'`
"""
if test_mode:
print(
f" 'foo' was passed in via test={test_mode} command : kwa... |
Print out the "foo" param passed in via
`airflow tasks test example_passing_params_via_test_command env_var_test_task <date>
--env-vars '{"foo":"bar"}'` | def print_env_vars(test_mode=None):
"""
Print out the "foo" param passed in via
`airflow tasks test example_passing_params_via_test_command env_var_test_task <date>
--env-vars '{"foo":"bar"}'`
"""
if test_mode:
print(f"foo={os.environ.get('foo')}")
print(f"AIRFLOW_TEST_MODE={os.e... |
Instantiate a number of operators for the given DAG.
:param str suffix: Suffix to append to the operator task_ids
:param str trigger_rule: TriggerRule for the join task
:param DAG dag_: The DAG to run the operators on | def create_test_pipeline(suffix, trigger_rule):
"""
Instantiate a number of operators for the given DAG.
:param str suffix: Suffix to append to the operator task_ids
:param str trigger_rule: TriggerRule for the join task
:param DAG dag_: The DAG to run the operators on
"""
skip_operator = E... |
Empty Task which is First Task of Dag | def task_start():
"""Empty Task which is First Task of Dag"""
return "[Task_start]" |
Empty Task1 | def task_1(value: int) -> str:
"""Empty Task1"""
return f"[ Task1 {value} ]" |
Empty Task2 | def task_2(value: str) -> str:
"""Empty Task2"""
return f"[ Task2 {value} ]" |
Empty Task3 | def task_3(value: str) -> None:
"""Empty Task3"""
print(f"[ Task3 {value} ]") |
Empty Task which is Last Task of Dag | def task_end() -> None:
"""Empty Task which is Last Task of Dag"""
print("[ Task_End ]") |
TaskGroup for grouping related Tasks | def task_group_function(value: int) -> None:
"""TaskGroup for grouping related Tasks"""
task_3(task_2(task_1(value))) |
Print the payload "message" passed to the DagRun conf attribute.
:param dag_run: The DagRun object | def run_this_func(dag_run=None):
"""
Print the payload "message" passed to the DagRun conf attribute.
:param dag_run: The DagRun object
"""
print(f"Remotely received value of {dag_run.conf.get('message')} for key=message") |
Pushes an XCom without a specific target | def push(ti=None):
"""Pushes an XCom without a specific target"""
ti.xcom_push(key="value from pusher 1", value=value_1) |
Pushes an XCom without a specific target, just by returning it | def push_by_returning():
"""Pushes an XCom without a specific target, just by returning it"""
return value_2 |
Pull all previously pushed XComs and check if the pushed values match the pulled values. | def puller(pulled_value_2, ti=None):
"""Pull all previously pushed XComs and check if the pushed values match the pulled values."""
pulled_value_1 = ti.xcom_pull(task_ids="push", key="value from pusher 1")
_compare_values(pulled_value_1, value_1)
_compare_values(pulled_value_2, value_2) |
Empty function | def generate_value():
"""Empty function"""
return "Bring me a shrubbery!" |
Empty function | def print_value(value, ts=None):
"""Empty function"""
log.info("The knights of Ni say: %s (at %s)", value, ts) |
### Object Storage Tutorial Documentation
This is a tutorial DAG to showcase the usage of the Object Storage API.
Documentation that goes along with the Airflow Object Storage tutorial is
located
[here](https://airflow.apache.org/docs/apache-airflow/stable/tutorial/objectstorage.html) | def tutorial_objectstorage():
"""
### Object Storage Tutorial Documentation
This is a tutorial DAG to showcase the usage of the Object Storage API.
Documentation that goes along with the Airflow Object Storage tutorial is
located
[here](https://airflow.apache.org/docs/apache-airflow/stable/tutor... |
### TaskFlow API Tutorial Documentation
This is a simple data pipeline example which demonstrates the use of
the TaskFlow API using three simple tasks for Extract, Transform, and Load.
Documentation that goes along with the Airflow TaskFlow API tutorial is
located
[here](https://airflow.apache.org/docs/apache-airflow/s... | def tutorial_taskflow_api():
"""
### TaskFlow API Tutorial Documentation
This is a simple data pipeline example which demonstrates the use of
the TaskFlow API using three simple tasks for Extract, Transform, and Load.
Documentation that goes along with the Airflow TaskFlow API tutorial is
locate... |
This method is called when task state changes to RUNNING.
Through callback, parameters like previous_task_state, task_instance object can be accessed.
This will give more information about current task_instance that is running its dag_run,
task and dag information. | def on_task_instance_running(previous_state: TaskInstanceState, task_instance: TaskInstance, session):
"""
This method is called when task state changes to RUNNING.
Through callback, parameters like previous_task_state, task_instance object can be accessed.
This will give more information about current ... |
This method is called when task state changes to SUCCESS.
Through callback, parameters like previous_task_state, task_instance object can be accessed.
This will give more information about current task_instance that has succeeded its
dag_run, task and dag information. | def on_task_instance_success(previous_state: TaskInstanceState, task_instance: TaskInstance, session):
"""
This method is called when task state changes to SUCCESS.
Through callback, parameters like previous_task_state, task_instance object can be accessed.
This will give more information about current ... |
This method is called when task state changes to FAILED.
Through callback, parameters like previous_task_state, task_instance object can be accessed.
This will give more information about current task_instance that has failed its dag_run,
task and dag information. | def on_task_instance_failed(
previous_state: TaskInstanceState, task_instance: TaskInstance, error: None | str | BaseException, session
):
"""
This method is called when task state changes to FAILED.
Through callback, parameters like previous_task_state, task_instance object can be accessed.
This wi... |
This method is called when dag run state changes to SUCCESS. | def on_dag_run_success(dag_run: DagRun, msg: str):
"""
This method is called when dag run state changes to SUCCESS.
"""
print("Dag run in success state")
start_date = dag_run.start_date
end_date = dag_run.end_date
print(f"Dag run start:{start_date} end:{end_date}") |
This method is called when dag run state changes to FAILED. | def on_dag_run_failed(dag_run: DagRun, msg: str):
"""
This method is called when dag run state changes to FAILED.
"""
print("Dag run in failure state")
dag_id = dag_run.dag_id
run_id = dag_run.run_id
external_trigger = dag_run.external_trigger
print(f"Dag information:{dag_id} Run id: {... |
This method is called when dag run state changes to RUNNING. | def on_dag_run_running(dag_run: DagRun, msg: str):
"""
This method is called when dag run state changes to RUNNING.
"""
print("Dag run in running state")
queued_at = dag_run.queued_at
dag_hash_info = dag_run.dag_hash
print(f"Dag information Queued at: {queued_at} hash info: {dag_hash_info}... |
Generate a DAG to be used as a subdag.
:param str parent_dag_name: Id of the parent DAG
:param str child_dag_name: Id of the child DAG
:param dict args: Default arguments to provide to the subdag
:return: DAG to use as a subdag | def subdag(parent_dag_name, child_dag_name, args) -> DAG:
"""
Generate a DAG to be used as a subdag.
:param str parent_dag_name: Id of the parent DAG
:param str child_dag_name: Id of the child DAG
:param dict args: Default arguments to provide to the subdag
:return: DAG to use as a subdag
"... |
Get a filesystem by scheme.
:param scheme: the scheme to get the filesystem for
:return: the filesystem method
:param conn_id: the airflow connection id to use
:param storage_options: the storage options to pass to the filesystem | def get_fs(
scheme: str, conn_id: str | None = None, storage_options: Properties | None = None
) -> AbstractFileSystem:
"""
Get a filesystem by scheme.
:param scheme: the scheme to get the filesystem for
:return: the filesystem method
:param conn_id: the airflow connection id to use
:param ... |
Check if a filesystem is available for a scheme.
:param scheme: the scheme to check
:return: True if a filesystem is available for the scheme | def has_fs(scheme: str) -> bool:
"""
Check if a filesystem is available for a scheme.
:param scheme: the scheme to check
:return: True if a filesystem is available for the scheme
"""
return scheme in _register_filesystems() |
Attach a filesystem or object storage.
:param alias: the alias to be used to refer to the store, autogenerated if omitted
:param protocol: the scheme that is used without ://
:param conn_id: the connection to use to connect to the filesystem
:param encryption_type: the encryption type to use to connect to the filesyst... | def attach(
protocol: str | None = None,
conn_id: str | None = None,
alias: str | None = None,
encryption_type: str | None = "",
fs: AbstractFileSystem | None = None,
**kwargs,
) -> ObjectStore:
"""
Attach a filesystem or object storage.
:param alias: the alias to be used to refer t... |
Return the most recent job of this type, if any, based on last heartbeat received.
Jobs in "running" state take precedence over others to make sure alive
job is returned if it is available.
:param job_type: job type to query for to get the most recent job for
:param session: Database session | def most_recent_job(job_type: str, session: Session = NEW_SESSION) -> Job | JobPydantic | None:
"""
Return the most recent job of this type, if any, based on last heartbeat received.
Jobs in "running" state take precedence over others to make sure alive
job is returned if it is available.
:param j... |
Run the job.
The Job is always an ORM object and setting the state is happening within the
same DB session and the session is kept open throughout the whole execution.
:meta private: | def run_job(
job: Job, execute_callable: Callable[[], int | None], session: Session = NEW_SESSION
) -> int | None:
"""
Run the job.
The Job is always an ORM object and setting the state is happening within the
same DB session and the session is kept open throughout the whole execution.
:meta p... |
Execute the job.
Job execution requires no session as generally executing session does not require an
active database connection. The session might be temporary acquired and used if the job
runs heartbeat during execution, but this connection is only acquired for the time of heartbeat
and in case of AIP-44 implementat... | def execute_job(job: Job, execute_callable: Callable[[], int | None]) -> int | None:
"""
Execute the job.
Job execution requires no session as generally executing session does not require an
active database connection. The session might be temporary acquired and used if the job
runs heartbeat durin... |
Perform heartbeat for the Job passed to it,optionally checking if it is necessary.
:param job: job to perform heartbeat for
:param heartbeat_callback: callback to run by the heartbeat
:param only_if_necessary: only heartbeat if it is necessary (i.e. if there are things to run for
triggerer for example) | def perform_heartbeat(
job: Job, heartbeat_callback: Callable[[Session], None], only_if_necessary: bool
) -> None:
"""
Perform heartbeat for the Job passed to it,optionally checking if it is necessary.
:param job: job to perform heartbeat for
:param heartbeat_callback: callback to run by the heartb... |
Whether this is a parent process.
Return True if the current process is the parent process.
False if the current process is a child process started by multiprocessing. | def _is_parent_process() -> bool:
"""
Whether this is a parent process.
Return True if the current process is the parent process.
False if the current process is a child process started by multiprocessing.
"""
return multiprocessing.current_process().name == "MainProcess" |
Configure logging where each trigger logs to its own file and can be exposed via the airflow webserver.
Generally speaking, we take the log handler configured for logger ``airflow.task``,
wrap it with TriggerHandlerWrapper, and set it as the handler for root logger.
If there already is a handler configured for the ro... | def configure_trigger_log_handler():
"""
Configure logging where each trigger logs to its own file and can be exposed via the airflow webserver.
Generally speaking, we take the log handler configured for logger ``airflow.task``,
wrap it with TriggerHandlerWrapper, and set it as the handler for root log... |
Route log messages to a queue and process them with QueueListener.
Airflow task handlers make blocking I/O calls.
We replace trigger log handlers, with LocalQueueHandler,
which sends log records to a queue.
Then we start a QueueListener in a thread, which is configured
to consume the queue and pass the records to the ... | def setup_queue_listener():
"""
Route log messages to a queue and process them with QueueListener.
Airflow task handlers make blocking I/O calls.
We replace trigger log handlers, with LocalQueueHandler,
which sends log records to a queue.
Then we start a QueueListener in a thread, which is conf... |
Attach additional specs to an existing pod object.
:param pod: A pod to attach a list of Kubernetes objects to
:param k8s_objects: a potential None list of K8SModels
:return: pod with the objects attached if they exist | def append_to_pod(pod: k8s.V1Pod, k8s_objects: list[K8SModel] | None):
"""
Attach additional specs to an existing pod object.
:param pod: A pod to attach a list of Kubernetes objects to
:param k8s_objects: a potential None list of K8SModels
:return: pod with the objects attached if they exist
"... |
Enable TCP keepalive mechanism.
This prevents urllib3 connection to hang indefinitely when idle connection
is time-outed on services like cloud load balancers or firewalls.
See https://github.com/apache/airflow/pull/11406 for detailed explanation.
Please ping @michalmisiewicz or @dimberman in the PR if you want to mo... | def _enable_tcp_keepalive() -> None:
"""
Enable TCP keepalive mechanism.
This prevents urllib3 connection to hang indefinitely when idle connection
is time-outed on services like cloud load balancers or firewalls.
See https://github.com/apache/airflow/pull/11406 for detailed explanation.
Pleas... |
Retrieve Kubernetes client.
:param in_cluster: whether we are in cluster
:param cluster_context: context of the cluster
:param config_file: configuration file
:return kubernetes client
:rtype client.CoreV1Api | def get_kube_client(
in_cluster: bool = conf.getboolean("kubernetes_executor", "in_cluster"),
cluster_context: str | None = None,
config_file: str | None = None,
) -> client.CoreV1Api:
"""
Retrieve Kubernetes client.
:param in_cluster: whether we are in cluster
:param cluster_context: conte... |
Generate random lowercase alphanumeric string of length num.
:meta private: | def rand_str(num):
"""Generate random lowercase alphanumeric string of length num.
:meta private:
"""
return "".join(secrets.choice(alphanum_lower) for _ in range(num)) |
Add random string to pod name while staying under max length.
:param pod_name: name of the pod
:param rand_len: length of the random string to append
:max_len: maximum length of the pod name
:meta private: | def add_pod_suffix(pod_name: str, rand_len: int = 8, max_len: int = 80) -> str:
"""Add random string to pod name while staying under max length.
:param pod_name: name of the pod
:param rand_len: length of the random string to append
:max_len: maximum length of the pod name
:meta private:
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.