dag13_cleanup_pipeline_db.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. """
  2. Copied from https://github.com/teamclairvoyant/airflow-maintenance-dags/blob/master/db-cleanup/airflow-db-cleanup.py
  3. A maintenance workflow that you can deploy into Airflow to periodically clean
  4. out the DagRun, TaskInstance, Log, XCom, Job DB and SlaMiss entries to avoid
  5. having too much data in your Airflow MetaStore.
  6. airflow trigger_dag --conf '[curly-braces]"maxDBEntryAgeInDays":30[curly-braces]' airflow-db-cleanup
  7. --conf options:
  8. maxDBEntryAgeInDays:<INT> - Optional
  9. """
  10. import airflow
  11. from airflow import settings
  12. from airflow.configuration import conf
  13. from airflow.models import DAG, DagModel, DagRun, Log, XCom, SlaMiss, TaskInstance, Variable
  14. try:
  15. from airflow.jobs import BaseJob
  16. except Exception as e:
  17. from airflow.jobs.base_job import BaseJob
  18. from airflow.operators.python_operator import PythonOperator
  19. from datetime import datetime, timedelta
  20. import dateutil.parser
  21. import logging
  22. import os
  23. from sqlalchemy import func, and_
  24. from sqlalchemy.exc import ProgrammingError
  25. from sqlalchemy.orm import load_only
  26. try:
  27. # airflow.utils.timezone is available from v1.10 onwards
  28. from airflow.utils import timezone
  29. now = timezone.utcnow
  30. except ImportError:
  31. now = datetime.utcnow
  32. # airflow-db-cleanup
  33. DAG_ID = os.path.basename(__file__).replace(".pyc", "").replace(".py", "")
  34. START_DATE = airflow.utils.dates.days_ago(1)
  35. # How often to Run. @daily - Once a day at Midnight (UTC)
  36. SCHEDULE_INTERVAL = "@daily"
  37. # Who is listed as the owner of this DAG in the Airflow Web Server
  38. DAG_OWNER_NAME = "airflow"
  39. # Length to retain the log files if not already provided in the conf. If this
  40. # is set to 30, the job will remove those files that arE 30 days old or older.
  41. DEFAULT_MAX_DB_ENTRY_AGE_IN_DAYS = int(
  42. Variable.get("airflow_db_cleanup__max_db_entry_age_in_days", 30)
  43. )
  44. # Prints the database entries which will be getting deleted; set to False to avoid printing large lists and slowdown process
  45. PRINT_DELETES = True
  46. # Whether the job should delete the db entries or not. Included if you want to
  47. # temporarily avoid deleting the db entries.
  48. ENABLE_DELETE = True
  49. # List of all the objects that will be deleted. Comment out the DB objects you
  50. # want to skip.
  51. DATABASE_OBJECTS = [
  52. {
  53. "airflow_db_model": BaseJob,
  54. "age_check_column": BaseJob.latest_heartbeat,
  55. "keep_last": False,
  56. "keep_last_filters": None,
  57. "keep_last_group_by": None
  58. },
  59. {
  60. "airflow_db_model": DagRun,
  61. "age_check_column": DagRun.execution_date,
  62. "keep_last": True,
  63. "keep_last_filters": [DagRun.external_trigger.is_(False)],
  64. "keep_last_group_by": DagRun.dag_id
  65. },
  66. {
  67. "airflow_db_model": TaskInstance,
  68. "age_check_column": TaskInstance.execution_date,
  69. "keep_last": False,
  70. "keep_last_filters": None,
  71. "keep_last_group_by": None
  72. },
  73. {
  74. "airflow_db_model": Log,
  75. "age_check_column": Log.dttm,
  76. "keep_last": False,
  77. "keep_last_filters": None,
  78. "keep_last_group_by": None
  79. },
  80. {
  81. "airflow_db_model": XCom,
  82. "age_check_column": XCom.execution_date,
  83. "keep_last": False,
  84. "keep_last_filters": None,
  85. "keep_last_group_by": None
  86. },
  87. {
  88. "airflow_db_model": SlaMiss,
  89. "age_check_column": SlaMiss.execution_date,
  90. "keep_last": False,
  91. "keep_last_filters": None,
  92. "keep_last_group_by": None
  93. },
  94. {
  95. "airflow_db_model": DagModel,
  96. "age_check_column": DagModel.last_scheduler_run,
  97. "keep_last": False,
  98. "keep_last_filters": None,
  99. "keep_last_group_by": None
  100. }]
  101. # Check for TaskReschedule model
  102. try:
  103. from airflow.models import TaskReschedule
  104. DATABASE_OBJECTS.append({
  105. "airflow_db_model": TaskReschedule,
  106. "age_check_column": TaskReschedule.execution_date,
  107. "keep_last": False,
  108. "keep_last_filters": None,
  109. "keep_last_group_by": None
  110. })
  111. except Exception as e:
  112. logging.error(e)
  113. # Check for TaskFail model
  114. try:
  115. from airflow.models import TaskFail
  116. DATABASE_OBJECTS.append({
  117. "airflow_db_model": TaskFail,
  118. "age_check_column": TaskFail.execution_date,
  119. "keep_last": False,
  120. "keep_last_filters": None,
  121. "keep_last_group_by": None
  122. })
  123. except Exception as e:
  124. logging.error(e)
  125. # Check for RenderedTaskInstanceFields model
  126. try:
  127. from airflow.models import RenderedTaskInstanceFields
  128. DATABASE_OBJECTS.append({
  129. "airflow_db_model": RenderedTaskInstanceFields,
  130. "age_check_column": RenderedTaskInstanceFields.execution_date,
  131. "keep_last": False,
  132. "keep_last_filters": None,
  133. "keep_last_group_by": None
  134. })
  135. except Exception as e:
  136. logging.error(e)
  137. # Check for ImportError model
  138. try:
  139. from airflow.models import ImportError
  140. DATABASE_OBJECTS.append({
  141. "airflow_db_model": ImportError,
  142. "age_check_column": ImportError.timestamp,
  143. "keep_last": False,
  144. "keep_last_filters": None,
  145. "keep_last_group_by": None
  146. })
  147. except Exception as e:
  148. logging.error(e)
  149. # Check for celery executor
  150. airflow_executor = str(conf.get("core", "executor"))
  151. logging.info("Airflow Executor: " + str(airflow_executor))
  152. if(airflow_executor == "CeleryExecutor"):
  153. logging.info("Including Celery Modules")
  154. try:
  155. from celery.backends.database.models import Task, TaskSet
  156. DATABASE_OBJECTS.extend(({
  157. "airflow_db_model": Task,
  158. "age_check_column": Task.date_done,
  159. "keep_last": False,
  160. "keep_last_filters": None,
  161. "keep_last_group_by": None
  162. }, {
  163. "airflow_db_model": TaskSet,
  164. "age_check_column": TaskSet.date_done,
  165. "keep_last": False,
  166. "keep_last_filters": None,
  167. "keep_last_group_by": None }))
  168. except Exception as e:
  169. logging.error(e)
  170. session = settings.Session()
  171. default_args = {
  172. 'owner': DAG_OWNER_NAME,
  173. 'depends_on_past': False,
  174. 'email_on_failure': False,
  175. 'email_on_retry': False,
  176. 'start_date': START_DATE,
  177. 'retries': 1,
  178. 'retry_delay': timedelta(minutes=1)
  179. }
  180. dag = DAG(
  181. DAG_ID,
  182. default_args=default_args,
  183. schedule_interval=SCHEDULE_INTERVAL,
  184. start_date=START_DATE
  185. )
  186. if hasattr(dag, 'doc_md'):
  187. dag.doc_md = __doc__
  188. if hasattr(dag, 'catchup'):
  189. dag.catchup = False
  190. def print_configuration_function(**context):
  191. logging.info("Loading Configurations...")
  192. dag_run_conf = context.get("dag_run").conf
  193. logging.info("dag_run.conf: " + str(dag_run_conf))
  194. max_db_entry_age_in_days = None
  195. if dag_run_conf:
  196. max_db_entry_age_in_days = dag_run_conf.get(
  197. "maxDBEntryAgeInDays", None
  198. )
  199. logging.info("maxDBEntryAgeInDays from dag_run.conf: " + str(dag_run_conf))
  200. if (max_db_entry_age_in_days is None or max_db_entry_age_in_days < 1):
  201. logging.info(
  202. "maxDBEntryAgeInDays conf variable isn't included or Variable " +
  203. "value is less than 1. Using Default '" +
  204. str(DEFAULT_MAX_DB_ENTRY_AGE_IN_DAYS) + "'"
  205. )
  206. max_db_entry_age_in_days = DEFAULT_MAX_DB_ENTRY_AGE_IN_DAYS
  207. max_date = now() + timedelta(-max_db_entry_age_in_days)
  208. logging.info("Finished Loading Configurations")
  209. logging.info("")
  210. logging.info("Configurations:")
  211. logging.info("max_db_entry_age_in_days: " + str(max_db_entry_age_in_days))
  212. logging.info("max_date: " + str(max_date))
  213. logging.info("enable_delete: " + str(ENABLE_DELETE))
  214. logging.info("session: " + str(session))
  215. logging.info("")
  216. logging.info("Setting max_execution_date to XCom for Downstream Processes")
  217. context["ti"].xcom_push(key="max_date", value=max_date.isoformat())
  218. print_configuration = PythonOperator(
  219. task_id='print_configuration',
  220. python_callable=print_configuration_function,
  221. provide_context=True,
  222. dag=dag)
  223. def cleanup_function(**context):
  224. logging.info("Retrieving max_execution_date from XCom")
  225. max_date = context["ti"].xcom_pull(
  226. task_ids=print_configuration.task_id, key="max_date"
  227. )
  228. max_date = dateutil.parser.parse(max_date) # stored as iso8601 str in xcom
  229. airflow_db_model = context["params"].get("airflow_db_model")
  230. state = context["params"].get("state")
  231. age_check_column = context["params"].get("age_check_column")
  232. keep_last = context["params"].get("keep_last")
  233. keep_last_filters = context["params"].get("keep_last_filters")
  234. keep_last_group_by = context["params"].get("keep_last_group_by")
  235. logging.info("Configurations:")
  236. logging.info("max_date: " + str(max_date))
  237. logging.info("enable_delete: " + str(ENABLE_DELETE))
  238. logging.info("session: " + str(session))
  239. logging.info("airflow_db_model: " + str(airflow_db_model))
  240. logging.info("state: " + str(state))
  241. logging.info("age_check_column: " + str(age_check_column))
  242. logging.info("keep_last: " + str(keep_last))
  243. logging.info("keep_last_filters: " + str(keep_last_filters))
  244. logging.info("keep_last_group_by: " + str(keep_last_group_by))
  245. logging.info("")
  246. logging.info("Running Cleanup Process...")
  247. try:
  248. query = session.query(airflow_db_model).options(
  249. load_only(age_check_column)
  250. )
  251. logging.info("INITIAL QUERY : " + str(query))
  252. if keep_last:
  253. subquery = session.query(func.max(DagRun.execution_date))
  254. # workaround for MySQL "table specified twice" issue
  255. # https://github.com/teamclairvoyant/airflow-maintenance-dags/issues/41
  256. if keep_last_filters is not None:
  257. for entry in keep_last_filters:
  258. subquery = subquery.filter(entry)
  259. logging.info("SUB QUERY [keep_last_filters]: " + str(subquery))
  260. if keep_last_group_by is not None:
  261. subquery = subquery.group_by(keep_last_group_by)
  262. logging.info(
  263. "SUB QUERY [keep_last_group_by]: " + str(subquery))
  264. subquery = subquery.from_self()
  265. query = query.filter(
  266. and_(age_check_column.notin_(subquery)),
  267. and_(age_check_column <= max_date)
  268. )
  269. else:
  270. query = query.filter(age_check_column <= max_date,)
  271. if PRINT_DELETES:
  272. entries_to_delete = query.all()
  273. logging.info("Query: " + str(query))
  274. logging.info(
  275. "Process will be Deleting the following " +
  276. str(airflow_db_model.__name__) + "(s):"
  277. )
  278. for entry in entries_to_delete:
  279. logging.info(
  280. "\tEntry: " + str(entry) + ", Date: " +
  281. str(entry.__dict__[str(age_check_column).split(".")[1]])
  282. )
  283. logging.info(
  284. "Process will be Deleting " + str(len(entries_to_delete)) + " " +
  285. str(airflow_db_model.__name__) + "(s)"
  286. )
  287. else:
  288. logging.warn(
  289. "You've opted to skip printing the db entries to be deleted. Set PRINT_DELETES to True to show entries!!!")
  290. if ENABLE_DELETE:
  291. logging.info("Performing Delete...")
  292. # using bulk delete
  293. query.delete(synchronize_session=False)
  294. session.commit()
  295. logging.info("Finished Performing Delete")
  296. else:
  297. logging.warn(
  298. "You've opted to skip deleting the db entries. Set ENABLE_DELETE to True to delete entries!!!")
  299. logging.info("Finished Running Cleanup Process")
  300. except ProgrammingError as e:
  301. logging.error(e)
  302. logging.error(str(airflow_db_model) +
  303. " is not present in the metadata. Skipping...")
  304. for db_object in DATABASE_OBJECTS:
  305. cleanup_op = PythonOperator(
  306. task_id='cleanup_' + str(db_object["airflow_db_model"].__name__),
  307. python_callable=cleanup_function,
  308. params=db_object,
  309. provide_context=True,
  310. dag=dag
  311. )
  312. print_configuration.set_downstream(cleanup_op)