How to trigger email for airflow task run - airflow

We have an adhoc airflow DAG, which anyone can trigger to run manually from team of 50+.
We can check airflow audit logs who triggered the DAG via dag id and we can also get email upon failure.
But we are more curious to know if we can get email upon DAG start OR at the start of each task run, this will help us understand and track activity and usage/command executed from adhoc DAG.

#Khilesh Chauhan
There are a number of ways to achieve your intended outcome, in no particular order:
1. Task or Dag Level Callbacks
Official Callback Reference
We can take advantage of the on_success_callback callback, which can be harnessed in two distinct places.
# use a function inside a specific PythonOperator, for task level control
task = PythonOperator(
task_id='your_task',
on_success_callback=send_mail,
)
# use it inside your DAG initiation
dag = DAG(
dag_id='your_task',
on_failure_callback=send_mail
)
We can write an example send_mail function, which leverages the send_email utility.
from airflow.utils.email import send_email
def send_mail(**context):
task = context['task_instance'].task
subject = f'Airflow task has successfully completed {task.task_id}'
body = f'Hi, this is an alert to let you know that your task {task.task_id} has completed successfully.'
send_email(
dag.default_args['email'],
subject,
body
)
2. Add an EmailOperator to your DAG Official Email Operator Reference
You could add an EmailOperator task at the beginning of your DAG.
from airflow.operators.email_operator import EmailOperator
email = EmailOperator(
task_id='alert_DAG_start',
to='your#email.come',
subject='DAG Initiated - start {{ ds }}',
html_content=""" <h1>Some Content</h1> """
)
3. Create a function that uses a PythonOperator that executes send_email
You might need more control, such as including logging info etc. So you might want more control to use a PythonOperator.
I hope this helps you to resolve your problem.
Update
To answer your second question to get the username, I have created a function for you to use. We can import the session context manager, then use the .query method, for your debugging purposes, I loop through the array. you can see the username at index 3.
from airflow.models.log import Log
from airflow.utils.db import create_session
def return_user_name(**context):
"""
return the username for the executed tasks
"""
dag_id = context['task_instance'].dag_id
with create_session() as session:
result = session.query(Log.dttm, Log.dag_id, Log.execution_date, Log.owner, Log.extra).filter(Log.dag_id == dag_id, Log.event == 'trigger').first()
for index, result in enumerate(result):
print(index, result)

Related

Can I manually trigger the rendering of template fields of a custom Operator in Airflow?

I am using Airflow 1.10.12 and have a PythonOperator task which is defined like the following:
task = PythonOperator(task_id=task_id,
op_kwargs=instance,
provide_context=True,
python_callable=execute_request,
dag=MY_DAG)
I execute another (custom) Operator Within the function execute_request:
glue_operator = GlueCatalogUpdateOperator(data_path=s3_partition_path,
catalog_mapping=
get_google_sheet_catalog(r_table,
r_db,
s3_table_path),
dag=None, task_id='none')
glue_operator.execute(None)
The problem is, that I have defined some template_fields in GlueCatalogUpdateOperator and these don't get rendered. If I create a task defined as GlueCatalogUpdateOperator it works. I assume it's because I am directly calling execute and template rendering happens typically before the execution - is this correct?
Is there a way to trigger the rendering or manually render templated fields?
Edit
I am able to pass the context via
glue_operator.execute(context=context)
However, templated fields still don't get rendered.
Technically, yes. For example:
import datetime
from airflow import DAG
from airflow.operators.bash import BashOperator
from airflow.operators.python import PythonOperator
def _test_templating(**context):
# This will literally echo "Today is {{ ds_nodash }}."
BashOperator(task_id="whatever_name", bash_command="echo 'Today is {{ ds_nodash }}.'").execute(
context=context
)
# This will echo e.g. "Today is 20230101."
test = BashOperator(task_id="whatever_name", bash_command="echo 'Today is {{ ds_nodash }}.'")
test.render_template_fields(context=context)
test.execute(context={})
with DAG("test_templating", start_date=datetime.datetime(2023, 1, 1), schedule_interval="#daily") as dag:
task = PythonOperator(task_id="test_templating", python_callable=_test_templating)
The task instance context is passed to the _test_templating function (line 8). The context is then passed along when calling the method render_template_fields (line 16), which renders templated fields given the context on the BashOperator.
A few notes:
The question feels like the result of a workaround. I assume you're doing more than just calling the GlueCatalogUpdateOperator from inside a PythonOperator callable as shown in your question? If not, there's no need to and it adds unnecessary complexity. Would call the GlueCatalogUpdateOperator directly.
Code was tested on Airflow 2.5.0. There's a render_template_fields method on the BaseOperator in Airflow 1.10.12: https://github.com/apache/airflow/blob/6416d898060706787861ff8ecbc4363152a35f45/airflow/models/baseoperator.py#L705-L719, so I assume the code above also works in Airflow 1.10.12 (note: Airflow 1 requires provide_context=True on PythonOperators to pass context).
Airflow 1.10.12 has been end-of-life for a year and a half now (see https://endoflife.date/apache-airflow and https://airflow.apache.org/docs/apache-airflow/stable/installation/supported-versions.html), I strongly suggest upgrading to Airflow 2.

Create dynamic workflows in Airflow with XCOM value

Now, I create multiple tasks using a variable like this and it works fine.
with DAG(....) as dag:
body = Variable.get("config_table", deserialize_json=True)
for i in range(len(body.keys())):
simple_task = Operator(
task_id = 'task_' + str(i),
.....
But I need to use XCOM value for some reason instead of using a variable.
Is it possible to dynamically create tasks with XCOM pull value?
I try to set value like this and it's not working
body = "{{ ti.xcom_pull(key='config_table', task_ids='get_config_table') }}"
It's possible to dynamically create tasks from XComs generated from a previous task, there are more extensive discussions on this topic, for example in this question. One of the suggested approaches follows this structure, here is a working example I made:
sample_file.json:
{
"cities": [ "London", "Paris", "BA", "NY" ]
}
Get your data from an API or file or any source. Push it as XCom.
def _process_obtained_data(ti):
list_of_cities = ti.xcom_pull(task_ids='get_data')
Variable.set(key='list_of_cities',
value=list_of_cities['cities'], serialize_json=True)
def _read_file():
with open('dags/sample_file.json') as f:
data = json.load(f)
# push to XCom using return
return data
with DAG('dynamic_tasks_example', schedule_interval='#once',
start_date=days_ago(2),
catchup=False) as dag:
get_data = PythonOperator(
task_id='get_data',
python_callable=_read_file)
Add a second task which will pull from pull from XCom and set a Variable with the data you will use to iterate later on.
preparation_task = PythonOperator(
task_id='preparation_task',
python_callable=_process_obtained_data)
*Of course, if you want you can merge both tasks into one. I prefer not to because usually, I take a subset of the fetched data to create the Variable.
Read from that Variable and later iterate on it. It's critical to define default_var.
end = DummyOperator(
task_id='end',
trigger_rule='none_failed')
# Top-level code within DAG block
iterable_list = Variable.get('list_of_cities',
default_var=['default_city'],
deserialize_json=True)
Declare dynamic tasks and their dependencies within a loop. Make the task_id uniques. TaskGroup is optional, helps you sorting the UI.
with TaskGroup('dynamic_tasks_group',
prefix_group_id=False,
) as dynamic_tasks_group:
if iterable_list:
for index, city in enumerate(iterable_list):
say_hello = PythonOperator(
task_id=f'say_hello_from_{city}',
python_callable=_print_greeting,
op_kwargs={'city_name': city, 'greeting': 'Hello'}
)
say_goodbye = PythonOperator(
task_id=f'say_goodbye_from_{city}',
python_callable=_print_greeting,
op_kwargs={'city_name': city, 'greeting': 'Goodbye'}
)
# TaskGroup level dependencies
say_hello >> say_goodbye
# DAG level dependencies
get_data >> preparation_task >> dynamic_tasks_group >> end
DAG Graph View:
Imports:
import json
from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.models import Variable
from airflow.operators.python_operator import PythonOperator
from airflow.operators.dummy import DummyOperator
from airflow.utils.task_group import TaskGroup
Things to keep in mind:
If you have simultaneous dag_runs of this same DAG, all of them will use the same variable, so you may need to make it 'unique' by differentiating their names.
You must set the default value while reading the Variable, otherwise, the first execution may not be processable to the Scheduler.
The Airflow Graph View UI may not refresh the changes immediately. Happens especially in the first run after adding or removing items from the iterable on which the dynamic task generation is created.
If you need to read from many variables, it's important to remember that it's recommended to store them in one single JSON value to avoid constantly create connections to the metadata database (example in this article).
Good luck!
Edit:
Another important point to take into consideration:
With this approach, the call to Variable.get() method is top-level code, so is read by the scheduler every 30 seconds (default of min_file_process_interval setting). This means that a connection to the metadata DB will happen each time.
Edit:
Added if clause to handle emtpy iterable_list case.
This is not possible, and in general dynamic tasks are not recommended:
The way the Airflow scheduler works is by reading the dag file, loading the tasks into the memory and then checks which dags and which tasks it need to schedule, while xcom are a runtime values that are related to a specific dag run, so the scheduler cannot relay on xcom values.
When using dynamic tasks you're making debug much harder for yourself, as the values you use for creating the dag can change and you'll lose access to logs without even understanding why.
What you can do is use branch operator, to have those tasks always and just skip them based on the xcom value.
For example:
def branch_func(**context)
return f"task_{context['ti'].xcom_pull(key=key)}"
branch = BranchPythonOperator(
task_id="branch",
python_callback=branch_func
)
tasks = [BaseOperator(task_id=f"task_{i}") for i in range(3)]
branch >> tasks
In some cases it's also not good to use this method (for example when I've 100 possible tasks), in those cases I'd recommend writing your own operator or use a single PythonOperator.

Is there a way for me to know when a DAG finished running in airflow?

I'm running a script that checks the status of my database before a DAG runs and compares it to after the DAG finished running.
def pre_dag_db
pass
def run_dag
pass
def post_dag_db
pass
Is there a way for me to know when the DAG finished running so that my script knows when to run post_dag_db? The idea is that my post_dag_db runs after my DAG finished running because the DAG manipulates the db.
The easiest way to do this would be to just run the script as last task in your dag, maybe using a BashOperator.
Other options would be to trigger a separate dag (TriggerDagRunOperator) and there implement a dag that calls your script.
If you really cannot call your script from Airflow itself, you might want to check the REST APIs https://airflow.apache.org/docs/stable/api.html and use them to retrieve information about the dag_run. But this seems overly-complicated to me.
Quick and easy way is to add one task in DAG which will work/run as last task of the DAG, this will work like magic for you.
you can use any of the operator like (PythonOperator, BashOperator, etc).
I think you can use the following code:
dag = get_dag(args)
dr = DagRun.find(dag.dag_id, execution_date=args.execution_date)
print(dr[0].state if len(dr) > 0 else None)
This code is taken from airflow cli.
Make a custom class that inherits from dag, and whose dependencies are the same as your dag.
something like (custom_dag.py)
from airflow.models.dag import DAG
class PreAndPostDAG(DAG):
#property
def tasks(self) -> List[BaseOperator]:
return [self.pre_graph] + list(self.task_dict.values()) + [self.post_graph]
#property
def pre_graph(self):
#whatever crazy things you want to do here, before DAG starts
pass
#property
def post_graph(self):
#whatever crazy things you want to do here, AFTER DAG finishes
pass
That's the easiest I can think of, then you just import it when defining your dags:
from custom_dag import PreAndPostDAG
with PreAndPostDAG(
'LS',
default_args=default_args,
description='A simple tutorial DAG',
schedule_interval=timedelta(days=1),
start_date=days_ago(2),
tags=['example'],
) as dag:
# t1, t2 and t3 are examples of tasks created by instantiating operators
t1 = BashOperator(
task_id='list',
bash_command='ls',
)
You get the rest, hope that helps

airflow sla_miss_callback function doesn't trigger and doesn't show up in dag details page

I would like to send alerts via my custom callback function that I'm calling during dag initialization as show below-
dag = DAG('tutorial', default_args=default_args, schedule_interval=timedelta(days=1), sla_miss_callback=my_sla_miss_cb_func)
My def signature is as follows-
def my_sla_miss_cb_func():
...custom_logic....
I've got sla attribute for the tasks I would like to monitor and I see that I get SLA MISS emails when I give email_on_failure=True but my_sla_miss_cb_func function doesn't get called/triggered.
Also, sla_miss_callback attribute doesn't show up in Details page in airflow UI.
I'm using airflow 1.7.1.3

Finding out what triggered a task run programmatically

Is there a way to programmatically determine what triggered the current task run of the PythonOperator from inside of the operator?
I want to differentiate between the task runs triggered on schedule, those catching up, and those triggered by the backfill CLI command.
The template context contains two variables: dag_run and run_id that you can use to determine whether the run was scheduled, a backfill, or externally triggered.
from airflow import jobs
def python_target(**context):
is_backfill = context["dag_run"].is_backfill
is_external = context["dag_run"].external_trigger
is_latest = context["execution_date"] == context["dag"].latest_execution_date
# More code...

Resources