dag8_copy_ongoing_seqrun.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. from datetime import timedelta
  2. import os,json,logging
  3. from airflow.models import DAG,Variable
  4. from airflow.utils.dates import days_ago
  5. from airflow.operators.bash_operator import BashOperator
  6. from airflow.contrib.operators.ssh_operator import SSHOperator
  7. from airflow.operators.python_operator import PythonOperator,BranchPythonOperator
  8. from airflow.contrib.hooks.ssh_hook import SSHHook
  9. from airflow.operators.dummy_operator import DummyOperator
  10. from igf_airflow.seqrun.ongoing_seqrun_processing import fetch_ongoing_seqruns
  11. from igf_airflow.logging.upload_log_msg import send_log_to_channels,log_success,log_failure,log_sleep
  12. from igf_data.utils.fileutils import get_temp_dir,copy_remote_file,check_file_path,read_json_data
  13. ## DEFAULT ARGS
  14. default_args = {
  15. 'owner': 'airflow',
  16. 'depends_on_past': False,
  17. 'start_date': days_ago(2),
  18. 'email_on_failure': False,
  19. 'email_on_retry': False,
  20. 'retries': 1,
  21. 'retry_delay': timedelta(minutes=5),
  22. 'provide_context': True,
  23. }
  24. ## CONN HOOKS
  25. orwell_ssh_hook = \
  26. SSHHook(
  27. key_file=Variable.get('hpc_ssh_key_file'),
  28. username=Variable.get('hpc_user'),
  29. remote_host=Variable.get('seqrun_server'))
  30. ## DAG
  31. dag = \
  32. DAG(
  33. dag_id='dag8_copy_ongoing_seqrun',
  34. catchup=False,
  35. schedule_interval="0 */2 * * *",
  36. max_active_runs=1,
  37. tags=['hpc'],
  38. default_args=default_args)
  39. ## FUNCTIONS
  40. def get_ongoing_seqrun_list(context):
  41. """
  42. A function for fetching ongoing sequencing run ids
  43. """
  44. try:
  45. ti = context.get('ti')
  46. seqrun_server = Variable.get('seqrun_server')
  47. seqrun_base_path = Variable.get('seqrun_base_path')
  48. database_config_file = Variable.get('database_config_file')
  49. ongoing_seqruns = \
  50. fetch_ongoing_seqruns(
  51. seqrun_server=seqrun_server,
  52. seqrun_base_path=seqrun_base_path,
  53. database_config_file=database_config_file)
  54. ti.xcom_push(key='ongoing_seqruns',value=ongoing_seqruns)
  55. branch_list = ['generate_seqrun_file_list_{0}'.format(i[0])
  56. for i in enumerate(ongoing_seqruns)]
  57. if len(branch_list) == 0:
  58. branch_list = ['no_ongoing_seqrun']
  59. else:
  60. send_log_to_channels(
  61. slack_conf=Variable.get('slack_conf'),
  62. ms_teams_conf=Variable.get('ms_teams_conf'),
  63. task_id=context['task'].task_id,
  64. dag_id=context['task'].dag_id,
  65. comment='Ongoing seqruns found: {0}'.format(ongoing_seqruns),
  66. reaction='pass')
  67. return branch_list
  68. except Exception as e:
  69. logging.error(e)
  70. send_log_to_channels(
  71. slack_conf=Variable.get('slack_conf'),
  72. ms_teams_conf=Variable.get('ms_teams_conf'),
  73. task_id=context['task'].task_id,
  74. dag_id=context['task'].dag_id,
  75. comment=e,
  76. reaction='fail')
  77. def copy_seqrun_manifest_file(context):
  78. """
  79. A function for copying filesize manifest for ongoing sequencing runs to hpc
  80. """
  81. try:
  82. remote_file_path = context['params'].get('file_path')
  83. seqrun_server = context['params'].get('seqrun_server')
  84. xcom_pull_task_ids = context['params'].get('xcom_pull_task_ids')
  85. ti = context.get('ti')
  86. remote_file_path = ti.xcom_pull(task_ids=xcom_pull_task_ids)
  87. tmp_work_dir = get_temp_dir(use_ephemeral=True)
  88. local_file_path = \
  89. os.path.join(
  90. tmp_work_dir,
  91. os.path.basename(remote_file_path))
  92. copy_remote_file(
  93. remote_file_path,
  94. local_file_path,
  95. source_address=seqrun_server)
  96. return local_file_path
  97. except Exception as e:
  98. logging.error(e)
  99. send_log_to_channels(
  100. slack_conf=Variable.get('slack_conf'),
  101. ms_teams_conf=Variable.get('ms_teams_conf'),
  102. task_id=context['task'].task_id,
  103. dag_id=context['task'].dag_id,
  104. comment=e,
  105. reaction='fail')
  106. def get_seqrun_chunks(context):
  107. """
  108. A function for setting file chunk size for seqrun files copy
  109. """
  110. try:
  111. ti = context.get('ti')
  112. worker_size = context['params'].get('worker_size')
  113. child_task_prefix = context['params'].get('child_task_prefix')
  114. seqrun_chunk_size_key = context['params'].get('seqrun_chunk_size_key')
  115. xcom_pull_task_ids = context['params'].get('xcom_pull_task_ids')
  116. file_path = ti.xcom_pull(task_ids=xcom_pull_task_ids)
  117. check_file_path(file_path)
  118. file_data = read_json_data(file_path)
  119. chunk_size = None
  120. if worker_size is None or \
  121. worker_size == 0:
  122. raise ValueError(
  123. 'Incorrect worker size: {0}'.\
  124. format(worker_size))
  125. if len(file_data) == 0:
  126. raise ValueError(
  127. 'No data present in seqrun list file {0}'.\
  128. format(file_path))
  129. if len(file_data) < int(5 * worker_size):
  130. worker_size = 1 # setting worker size to 1 for low input
  131. if len(file_data) % worker_size == 0:
  132. chunk_size = int(len(file_data) / worker_size)
  133. else:
  134. chunk_size = int(len(file_data) / worker_size)+1
  135. ti.xcom_push(key=seqrun_chunk_size_key,value=chunk_size)
  136. worker_branchs = ['{0}_{1}'.format(child_task_prefix,i)
  137. for i in range(worker_size)]
  138. return worker_branchs
  139. except Exception as e:
  140. logging.error(e)
  141. send_log_to_channels(
  142. slack_conf=Variable.get('slack_conf'),
  143. ms_teams_conf=Variable.get('ms_teams_conf'),
  144. task_id=context['task'].task_id,
  145. dag_id=context['task'].dag_id,
  146. comment=e,
  147. reaction='fail')
  148. def copy_seqrun_chunk(context):
  149. """
  150. A function for copying seqrun chunks
  151. """
  152. try:
  153. ti = context.get('ti')
  154. file_path_task_ids = context['params'].get('file_path_task_ids')
  155. seqrun_chunk_size_key = context['params'].get('seqrun_chunk_size_key')
  156. seqrun_chunk_size_task_ids = context['params'].get('seqrun_chunk_size_task_ids')
  157. chunk_index_number = context['params'].get('chunk_index_number')
  158. run_index_number = context['params'].get('run_index_number')
  159. local_seqrun_path = context['params'].get('local_seqrun_path')
  160. seqrun_id_pull_key = context['params'].get('seqrun_id_pull_key')
  161. seqrun_id_pull_task_ids = context['params'].get('seqrun_id_pull_task_ids')
  162. seqrun_server = Variable.get('seqrun_server'),
  163. seqrun_base_path = Variable.get('seqrun_base_path')
  164. seqrun_id = ti.xcom_pull(key=seqrun_id_pull_key,task_ids=seqrun_id_pull_task_ids)[run_index_number]
  165. file_path = ti.xcom_pull(task_ids=file_path_task_ids)
  166. chunk_size = ti.xcom_pull(key=seqrun_chunk_size_key,task_ids=seqrun_chunk_size_task_ids)
  167. check_file_path(file_path)
  168. file_data = read_json_data(file_path)
  169. start_index = chunk_index_number*chunk_size
  170. finish_index = ((chunk_index_number+1)*chunk_size) - 1
  171. if finish_index > len(file_data) - 1:
  172. finish_index = len(file_data) - 1
  173. local_seqrun_path = \
  174. os.path.join(local_seqrun_path,seqrun_id)
  175. for entry in file_data[start_index:finish_index]:
  176. file_path = entry.get('file_path')
  177. file_size = entry.get('file_size')
  178. remote_path = \
  179. os.path.join(
  180. seqrun_base_path,
  181. file_path)
  182. local_path = \
  183. os.path.join(
  184. local_seqrun_path,
  185. file_path)
  186. if os.path.exists(local_path) and \
  187. os.path.getsize(local_path) == file_size:
  188. pass
  189. else:
  190. copy_remote_file(
  191. remote_path,
  192. local_path,
  193. source_address=seqrun_server,
  194. check_file=False)
  195. except Exception as e:
  196. logging.error(e)
  197. send_log_to_channels(
  198. slack_conf=Variable.get('slack_conf'),
  199. ms_teams_conf=Variable.get('ms_teams_conf'),
  200. task_id=context['task'].task_id,
  201. dag_id=context['task'].dag_id,
  202. comment=e,
  203. reaction='fail')
  204. with dag:
  205. ## TASK
  206. generate_seqrun_list = \
  207. BranchPythonOperator(
  208. task_id='generate_seqrun_list',
  209. dag=dag,
  210. queue='hpc_4G',
  211. python_callable=get_ongoing_seqrun_list)
  212. ## TASK
  213. no_ongoing_seqrun = \
  214. DummyOperator(
  215. task_id='no_ongoing_seqrun',
  216. dag=dag,
  217. queue='hpc_4G',
  218. on_success_callback=log_sleep)
  219. ## TASK
  220. tasks = list()
  221. for i in range(5):
  222. t1 = \
  223. SSHOperator(
  224. task_id='generate_seqrun_file_list_{0}'.format(i),
  225. dag=dag,
  226. pool='orwell_exe_pool',
  227. do_xcom_push=True,
  228. queue='hpc_4G',
  229. params={'source_task_id':'generate_seqrun_list',
  230. 'pull_key':'ongoing_seqruns',
  231. 'index_number':i},
  232. command="""
  233. source /home/igf/igf_code/airflow/env.sh; \
  234. python /home/igf/igf_code/airflow/data-management-python/scripts/seqrun_processing/create_file_list_for_ongoing_seqrun.py \
  235. --seqrun_base_dir /home/igf/seqrun/illumina \
  236. --output_path /home/igf/ongoing_run_tracking \
  237. --seqrun_id {{ ti.xcom_pull(key=params.pull_key,task_ids=params.source_task_id)[ params.index_number ] }}
  238. """)
  239. ## TASK
  240. t2 = \
  241. PythonOperator(
  242. task_id='copy_seqrun_file_list_{0}'.format(i),
  243. dag=dag,
  244. pool='orwell_scp_pool',
  245. queue='hpc_4G',
  246. params={'xcom_pull_task_ids':'generate_seqrun_file_list_{0}'.format(i),
  247. 'seqrun_server':Variable.get('seqrun_server')},
  248. python_callable=copy_seqrun_manifest_file)
  249. ## TASK
  250. t3 = \
  251. BranchPythonOperator(
  252. task_id='decide_copy_branch_{0}'.format(i),
  253. dag=dag,
  254. queue='hpc_4G',
  255. params={'xcom_pull_task_ids':'copy_seqrun_file_list_{0}'.format(i),
  256. 'worker_size':10,
  257. 'seqrun_chunk_size_key':'seqrun_chunk_size',
  258. 'child_task_prefix':'copy_file_run_{0}_chunk_'.format(i)},
  259. python_callable=get_seqrun_chunks)
  260. ## TASK
  261. t4 = list()
  262. for j in range(10):
  263. t4j = \
  264. PythonOperator(
  265. task_id='copy_file_run_{0}_chunk_{1}'.format(i,j),
  266. dag=dag,
  267. queue='hpc_4G',
  268. pool='orwell_scp_pool',
  269. params={'file_path_task_ids':'copy_seqrun_file_list_{0}'.format(i),
  270. 'seqrun_chunk_size_key':'seqrun_chunk_size',
  271. 'seqrun_chunk_size_task_ids':'decide_copy_branch_{0}'.format(i),
  272. 'run_index_number':i,
  273. 'chunk_index_number':j,
  274. 'seqrun_id_pull_key':'ongoing_seqruns',
  275. 'seqrun_id_pull_task_ids':'generate_seqrun_list',
  276. 'local_seqrun_path':Variable.get('hpc_seqrun_path')},
  277. python_callable=copy_seqrun_chunk)
  278. t4.append(t4j)
  279. tasks.append([ t1 >> t2 >> t3 >> t4 ])
  280. ## PIPELINE
  281. generate_seqrun_list >> no_ongoing_seqrun
  282. generate_seqrun_list >> tasks