dag8_copy_ongoing_seqrun.py 10 KB

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