Skip to content
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

Fix: Issue when the database objects passed to the cleanup task via params aren't JSON serializable #119

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
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
293 changes: 148 additions & 145 deletions db-cleanup/airflow-db-cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@
DEFAULT_MAX_DB_ENTRY_AGE_IN_DAYS = int(
Variable.get("airflow_db_cleanup__max_db_entry_age_in_days", 30)
)
# Prints the database entries which will be getting deleted; set to False to avoid printing large lists and slowdown process
# Prints the database entries which will be getting deleted; set to False to avoid printing large lists and slowdown
# process
PRINT_DELETES = True
# Whether the job should delete the db entries or not. Included if you want to
# temporarily avoid deleting the db entries.
Expand All @@ -62,138 +63,8 @@

# List of all the objects that will be deleted. Comment out the DB objects you
# want to skip.
DATABASE_OBJECTS = [
{
"airflow_db_model": BaseJob,
"age_check_column": BaseJob.latest_heartbeat,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
},
{
"airflow_db_model": DagRun,
"age_check_column": DagRun.execution_date,
"keep_last": True,
"keep_last_filters": [DagRun.external_trigger.is_(False)],
"keep_last_group_by": DagRun.dag_id
},
{
"airflow_db_model": TaskInstance,
"age_check_column": TaskInstance.execution_date,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
},
{
"airflow_db_model": Log,
"age_check_column": Log.dttm,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
},
{
"airflow_db_model": XCom,
"age_check_column": XCom.execution_date,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
},
{
"airflow_db_model": SlaMiss,
"age_check_column": SlaMiss.execution_date,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
},
{
"airflow_db_model": DagModel,
"age_check_column": dag_model_last_scheduler_run,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
}]

# Check for TaskReschedule model
try:
from airflow.models import TaskReschedule
DATABASE_OBJECTS.append({
"airflow_db_model": TaskReschedule,
"age_check_column": TaskReschedule.execution_date,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
})

except Exception as e:
logging.error(e)

# Check for TaskFail model
try:
from airflow.models import TaskFail
DATABASE_OBJECTS.append({
"airflow_db_model": TaskFail,
"age_check_column": TaskFail.execution_date,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
})

except Exception as e:
logging.error(e)

# Check for RenderedTaskInstanceFields model
try:
from airflow.models import RenderedTaskInstanceFields
DATABASE_OBJECTS.append({
"airflow_db_model": RenderedTaskInstanceFields,
"age_check_column": RenderedTaskInstanceFields.execution_date,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
})

except Exception as e:
logging.error(e)

# Check for ImportError model
try:
from airflow.models import ImportError
DATABASE_OBJECTS.append({
"airflow_db_model": ImportError,
"age_check_column": ImportError.timestamp,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
})

except Exception as e:
logging.error(e)

# Check for celery executor
airflow_executor = str(conf.get("core", "executor"))
logging.info("Airflow Executor: " + str(airflow_executor))
if(airflow_executor == "CeleryExecutor"):
logging.info("Including Celery Modules")
try:
from celery.backends.database.models import Task, TaskSet
DATABASE_OBJECTS.extend((
{
"airflow_db_model": Task,
"age_check_column": Task.date_done,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
},
{
"airflow_db_model": TaskSet,
"age_check_column": TaskSet.date_done,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
}))

except Exception as e:
logging.error(e)
DATABASE_OBJECTS = ['BaseJob', 'DagRun', 'TaskInstance', 'Log', 'XCom', 'SlaMiss', 'DagModel', 'TaskReschedule',
'TaskFail', 'RenderedTaskInstanceFields', 'ImportError', 'Task', 'TaskSet']

session = settings.Session()

Expand All @@ -213,7 +84,7 @@
default_args=default_args,
schedule_interval=SCHEDULE_INTERVAL,
start_date=START_DATE,
tags=['teamclairvoyant', 'airflow-maintenance-dags']
tags=['airflow-maintenance-dags']
)
if hasattr(dag, 'doc_md'):
dag.doc_md = __doc__
Expand All @@ -231,7 +102,7 @@ def print_configuration_function(**context):
"maxDBEntryAgeInDays", None
)
logging.info("maxDBEntryAgeInDays from dag_run.conf: " + str(dag_run_conf))
if (max_db_entry_age_in_days is None or max_db_entry_age_in_days < 1):
if max_db_entry_age_in_days is None or max_db_entry_age_in_days < 1:
logging.info(
"maxDBEntryAgeInDays conf variable isn't included or Variable " +
"value is less than 1. Using Default '" +
Expand Down Expand Up @@ -262,25 +133,158 @@ def print_configuration_function(**context):

def cleanup_function(**context):

database_objects_dict = {
'BaseJob': {
"airflow_db_model": BaseJob,
"age_check_column": BaseJob.latest_heartbeat,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
},
'DagRun': {
"airflow_db_model": DagRun,
"age_check_column": DagRun.execution_date,
"keep_last": True,
"keep_last_filters": [DagRun.external_trigger.is_(False)],
"keep_last_group_by": DagRun.dag_id
},
'TaskInstance': {
"airflow_db_model": TaskInstance,
"age_check_column": TaskInstance.run_id,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
},
'Log': {
"airflow_db_model": Log,
"age_check_column": Log.dttm,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
},
'XCom': {
"airflow_db_model": XCom,
"age_check_column": XCom.execution_date,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
},
'SlaMiss': {
"airflow_db_model": SlaMiss,
"age_check_column": SlaMiss.execution_date,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
},
'DagModel': {
"airflow_db_model": DagModel,
"age_check_column": dag_model_last_scheduler_run,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
}
}

# Check for TaskReschedule model
try:
from airflow.models import TaskReschedule
database_objects_dict['TaskReschedule'] = {
"airflow_db_model": TaskReschedule,
"age_check_column": TaskReschedule.run_id,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
}

except Exception as e:
logging.error(e)

# Check for TaskFail model
try:
from airflow.models import TaskFail
database_objects_dict['TaskFail'] = {
"airflow_db_model": TaskFail,
"age_check_column": TaskFail.execution_date,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
}

except Exception as e:
logging.error(e)

# Check for RenderedTaskInstanceFields model
try:
from airflow.models import RenderedTaskInstanceFields
database_objects_dict['RenderedTaskInstanceFields'] = {
"airflow_db_model": RenderedTaskInstanceFields,
"age_check_column": RenderedTaskInstanceFields.execution_date,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
}

except Exception as e:
logging.error(e)

# Check for ImportError model
try:
from airflow.models import ImportError
database_objects_dict['ImportError'] = {
"airflow_db_model": ImportError,
"age_check_column": ImportError.timestamp,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
}

except Exception as e:
logging.error(e)

# Check for celery executor
airflow_executor = str(conf.get("core", "executor"))
logging.info("Airflow Executor: " + str(airflow_executor))
if airflow_executor == "CeleryExecutor":
logging.info("Including Celery Modules")
try:
from celery.backends.database.models import Task, TaskSet
database_objects_dict['Task'] = {
"airflow_db_model": Task,
"age_check_column": Task.date_done,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
}
database_objects_dict['TaskSet'] = {
"airflow_db_model": TaskSet,
"age_check_column": TaskSet.date_done,
"keep_last": False,
"keep_last_filters": None,
"keep_last_group_by": None
}

except Exception as e:
logging.error(e)

logging.info("Retrieving max_execution_date from XCom")
max_date = context["ti"].xcom_pull(
task_ids=print_configuration.task_id, key="max_date"
)
max_date = dateutil.parser.parse(max_date) # stored as iso8601 str in xcom

airflow_db_model = context["params"].get("airflow_db_model")
state = context["params"].get("state")
age_check_column = context["params"].get("age_check_column")
keep_last = context["params"].get("keep_last")
keep_last_filters = context["params"].get("keep_last_filters")
keep_last_group_by = context["params"].get("keep_last_group_by")
object_name = str(context["params"].get("object_name"))

airflow_db_model = database_objects_dict[object_name].get("airflow_db_model")
age_check_column = database_objects_dict[object_name].get("age_check_column")
keep_last = database_objects_dict[object_name].get("keep_last")
keep_last_filters = database_objects_dict[object_name].get("keep_last_filters")
keep_last_group_by = database_objects_dict[object_name].get("keep_last_group_by")

logging.info("Configurations:")
logging.info("max_date: " + str(max_date))
logging.info("enable_delete: " + str(ENABLE_DELETE))
logging.info("session: " + str(session))
logging.info("airflow_db_model: " + str(airflow_db_model))
logging.info("state: " + str(state))
logging.info("age_check_column: " + str(age_check_column))
logging.info("keep_last: " + str(keep_last))
logging.info("keep_last_filters: " + str(keep_last_filters))
Expand Down Expand Up @@ -366,10 +370,9 @@ def cleanup_function(**context):
for db_object in DATABASE_OBJECTS:
Copy link

Choose a reason for hiding this comment

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

This doesn't work if you aren't using the CeleryExecutor as Task and TaskSet don't exist. There needs to be a conditional check like on line 247.


cleanup_op = PythonOperator(
task_id='cleanup_' + str(db_object["airflow_db_model"].__name__),
task_id='cleanup_' + str(db_object),
python_callable=cleanup_function,
params=db_object,
provide_context=True,
params={'object_name': db_object},
dag=dag
)

Expand Down