-
Notifications
You must be signed in to change notification settings - Fork 42
/
airflowDagGen.py
executable file
·506 lines (425 loc) · 15.1 KB
/
airflowDagGen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import division, with_statement
'''
Copyright 2015, 陈同 (chentong_biology@163.com).
===========================================================
'''
__author__ = 'chentong & ct586[9]'
__author_email__ = 'chentong_biology@163.com'
#=========================================================
desc = '''
Program description:
This is designed to generate airflow dag for batch assignments.
config.json
{
"Attention": [
"1. No comma sign for the last item in each group.",
"2. No single quote or parenthesis is allowed.",
"3. No chinese comma out of double quote.",
"4. Use list to order subjects."
],
"work_dir": "/working-directory",
"program": "virtualScreening.py",
"program_parameter": [
["-p", ["prot1.pdb", "prot2.pdb", "prot3.pdb"]],
["-l", ["chem1.pdb", "chem2.pdb"]],
["-o", "result"]
],
"airflow_parameter":{
"owner": "'ct'",
"dag_id" : "'vs'",
"start_date": "one_min_ago",
"depends_on_past": "False",
"email": ["chentong_biology@163.com"],
"email_on_failure": "True",
"email_on_retry": "True",
"retries": 500,
"retry_delay": "timedelta(hours=30)",
"schedule_interval": "'@once'",
"comment": {
"comment": "all airflow supported parameters.",
"start_date": "can be <one_min_ago> or <'2016-01-01'>"
"special_attention": "sting value shuould be quoted in ***single quote (')***"
}
},
"parallel_parameter": {
"maxrun": 5,
"comment": {
"maxrun": "Set the number of assignments running parallely"
}
},
"comment": {
"comment": "Explanation words (optional)",
"program": "The program wants to run",
"program_parameter": "Parameters given to the program. For parameters accepting one or more files, both a list as exampled above for <-l> or a string like <\"'chem1.pdb','chemb.pdb'\"> are acceptable.",
"work_dir": "The absolute path for working directory"
}
}
generated DAG
from airflow import DAG
from airflow.operators import BashOperator, EmailOperator
from datetime import datetime, timedelta
one_min_ago = datetime.combine(datetime.today() + timedelta(minutes=20),
datetime.min.time())
default_args = {
'email_on_retry': True,
'email': [u'chentong_biology@163.com'],
'email_on_failure': True,
'retry_delay': timedelta(hours=30),
'owner': 'ct',
'depends_on_past': False,
'start_date': one_min_ago,
'retries': 500
}
dag = DAG('vs', default_args=default_args, schedule_interval='@once')
chem1_pdb_prot1_pdb = BashOperator(
task_id='chem1_pdb_prot1_pdb',
bash_command="(cd /working-directory; virtualScreening.py -l chem1.pdb -o result -p prot1.pdb) ",
dag=dag)
chem1_pdb_prot1_pdb_success_mail = EmailOperator(
task_id="chem1_pdb_prot1_pdb_success_mail",
to=[u'chentong_biology@163.com'],
subject="chem1_pdb_prot1_pdb success",
html_content="chem1_pdb_prot1_pdb success",
dag=dag)
chem1_pdb_prot1_pdb_success_mail.set_upstream(chem1_pdb_prot1_pdb)
#chem1_pdb_prot1_pdb.set_upstream( )
chem1_pdb_prot2_pdb = BashOperator(
task_id='chem1_pdb_prot2_pdb',
bash_command="(cd /working-directory; virtualScreening.py -l chem1.pdb -o result -p prot2.pdb) ",
dag=dag)
chem1_pdb_prot2_pdb_success_mail = EmailOperator(
task_id="chem1_pdb_prot2_pdb_success_mail",
to=[u'chentong_biology@163.com'],
subject="chem1_pdb_prot2_pdb success",
html_content="chem1_pdb_prot2_pdb success",
dag=dag)
chem1_pdb_prot2_pdb_success_mail.set_upstream(chem1_pdb_prot2_pdb)
#chem1_pdb_prot2_pdb.set_upstream( )
chem1_pdb_prot3_pdb = BashOperator(
task_id='chem1_pdb_prot3_pdb',
bash_command="(cd /working-directory; virtualScreening.py -l chem1.pdb -o result -p prot3.pdb) ",
dag=dag)
chem1_pdb_prot3_pdb_success_mail = EmailOperator(
task_id="chem1_pdb_prot3_pdb_success_mail",
to=[u'chentong_biology@163.com'],
subject="chem1_pdb_prot3_pdb success",
html_content="chem1_pdb_prot3_pdb success",
dag=dag)
chem1_pdb_prot3_pdb_success_mail.set_upstream(chem1_pdb_prot3_pdb)
#chem1_pdb_prot3_pdb.set_upstream( )
chem2_pdb_prot1_pdb = BashOperator(
task_id='chem2_pdb_prot1_pdb',
bash_command="(cd /working-directory; virtualScreening.py -l chem2.pdb -o result -p prot1.pdb) ",
dag=dag)
chem2_pdb_prot1_pdb_success_mail = EmailOperator(
task_id="chem2_pdb_prot1_pdb_success_mail",
to=[u'chentong_biology@163.com'],
subject="chem2_pdb_prot1_pdb success",
html_content="chem2_pdb_prot1_pdb success",
dag=dag)
chem2_pdb_prot1_pdb_success_mail.set_upstream(chem2_pdb_prot1_pdb)
#chem2_pdb_prot1_pdb.set_upstream( )
chem2_pdb_prot2_pdb = BashOperator(
task_id='chem2_pdb_prot2_pdb',
bash_command="(cd /working-directory; virtualScreening.py -l chem2.pdb -o result -p prot2.pdb) ",
dag=dag)
chem2_pdb_prot2_pdb_success_mail = EmailOperator(
task_id="chem2_pdb_prot2_pdb_success_mail",
to=[u'chentong_biology@163.com'],
subject="chem2_pdb_prot2_pdb success",
html_content="chem2_pdb_prot2_pdb success",
dag=dag)
chem2_pdb_prot2_pdb_success_mail.set_upstream(chem2_pdb_prot2_pdb)
#chem2_pdb_prot2_pdb.set_upstream( )
chem2_pdb_prot3_pdb = BashOperator(
task_id='chem2_pdb_prot3_pdb',
bash_command="(cd /working-directory; virtualScreening.py -l chem2.pdb -o result -p prot3.pdb) ",
dag=dag)
chem2_pdb_prot3_pdb_success_mail = EmailOperator(
task_id="chem2_pdb_prot3_pdb_success_mail",
to=[u'chentong_biology@163.com'],
subject="chem2_pdb_prot3_pdb success",
html_content="chem2_pdb_prot3_pdb success",
dag=dag)
chem2_pdb_prot3_pdb_success_mail.set_upstream(chem2_pdb_prot3_pdb)
chem2_pdb_prot3_pdb.set_upstream(chem1_pdb_prot1_pdb)
'''
import sys
import os
from json import dumps as json_dumps
from json import loads as json_loads
from time import localtime, strftime
timeformat = "%Y-%m-%d %H:%M:%S"
from optparse import OptionParser as OP
from string import maketrans
import re
debug = 0
def cmdparameter(argv):
if len(argv) == 1:
global desc
print >>sys.stderr, desc
cmd = 'python ' + argv[0] + ' -h'
os.system(cmd)
sys.exit(1)
usages = "%prog -i file"
parser = OP(usage=usages)
parser.add_option("-i", "--input-file", dest="filein",
metavar="FILEIN", help="A config file in JSON format as described above.")
parser.add_option("-v", "--verbose", dest="verbose",
action="store_true", help="Show process information")
parser.add_option("-D", "--debug", dest="debug",
default=False, action="store_true", help="Debug the program")
(options, args) = parser.parse_args(argv[1:])
assert options.filein != None, "A filename needed for -i"
return (options, args)
#--------------------------------------------------------------------
def iterateParameters(optL, cmdD):
'''
optL = [
["-p prot1", "-p prot2", "-p prot3"],
["-l chem1", "-l chem2"],
["-o result"]
]
cmdD = {
"-p prot1": {"-l chem1": "result", "-l chem2": "result"}
}
'''
if debug:
print >>sys.stderr, "New"
print >>sys.stderr, optL
print >>sys.stderr, cmdD
for opt in optL[0]:
newOptL = optL[1:]
if len(newOptL)>1:
tmpD = {}
cmdD[opt] = tmpD
if debug:
print >>sys.stderr, "Next"
print >>sys.stderr, newOptL
print >>sys.stderr, cmdD
iterateParameters(newOptL, tmpD)
else:
cmdD[opt] = {}
for last_opt in newOptL[0]:
cmdD[opt][last_opt] = ''
#------------------------------------
def iterateParameters2(optL, recordL, cmdL):
'''
optL = [
["-p prot1", "-p prot2", "-p prot3"],
["-l chem1", "-l chem2"],
["-o result"]
]
recordL: tmp record variable
cmdL = [
["-p prot1", "-l chem1", "result"],
["-p prot1", "-l chem2", "result"]
]
'''
if debug:
print >>sys.stderr, "New"
print >>sys.stderr, optL
print >>sys.stderr, recordL
for opt in optL[0]:
newOptL = optL[1:]
if len(newOptL) > 1:
tmpL = recordL[:]
tmpL.append(opt)
if debug:
print >>sys.stderr, "Next"
print >>sys.stderr, newOptL
print >>sys.stderr, tmpL
iterateParameters2(newOptL, tmpL, cmdL)
else:
for last_opt in newOptL[0]:
tmpL = recordL[:]
tmpL.append(opt)
tmpL.append(last_opt)
cmdL.append(tmpL)
#------------------------------------
def generateCmd(program, program_parameterD, work_dir, maxrun, email):
count = 1
chdir = "(cd {}; ".format(work_dir)
assignmentL = [' '] * maxrun
optL = [[program]]
nameL = []
for opt, optV in program_parameterD.items():
cmdL = []
subNameL = []
if type(optV) == list:
for eachV in optV:
cmd = ' '.join([opt, str(eachV)])
cmdL.append(cmd)
subNameL.append(str(eachV))
else:
cmdL = [' '.join([opt, str(optV)])]
optL.append(cmdL)
if subNameL:
nameL.append(subNameL)
#=------------------------------------------
if debug:
print >>sys.stderr, optL
print >>sys.stderr, nameL
recordL = []
cmdLL = []
iterateParameters2(optL, recordL, cmdLL)
nameLL = []
recordL = []
iterateParameters2(nameL, recordL, nameLL)
if debug:
print >>sys.stderr, cmdLL
print >>sys.stderr, nameLL
num_start = re.compile('^[0-9]')
illegal_char = re.compile('[^a-zA-Z0-9]')
count = 1
for cmdL in cmdLL:
cmd = chdir+' '.join(cmdL)+')'
task_name = "_".join(nameLL[count-1])
task_name = illegal_char.sub('_', task_name)
if num_start.match(task_name):
task_name = '_'+task_name
comment = '' if count > maxrun else '#'
index = count%maxrun-1
upstream_task = assignmentL[index]
assignmentL[index] = task_name
tmpD = {"cmd":cmd, "task_name":task_name,
"upstream_task":upstream_task,
"email": email,
"comment": comment}
count += 1
print '''
{d[task_name]} = BashOperator(
task_id='{d[task_name]}',
bash_command="{d[cmd]} ",
dag=dag)
{d[task_name]}_success_mail = EmailOperator(
task_id="{d[task_name]}_success_mail",
to={d[email]},
subject="{d[task_name]} success",
html_content="{d[task_name]} success",
dag=dag)
{d[task_name]}_success_mail.set_upstream({d[task_name]})
{d[comment]}{d[task_name]}.set_upstream({d[upstream_task]})
'''.format(d=tmpD)
#---------END of generateCmd----------------------
def generateCmd2(program, program_parameterL, work_dir, maxrun, email):
'''
program_parameterL = [
['-p', ['1.pdb', '2.pdb', '3.pdb']],
['-l', ['c1.pdb', 'c2.pdb']],
['-o', 'result']
]
'''
count = 1
chdir = "(cd {}; ".format(work_dir)
assignmentL = [' '] * maxrun
optL = [[program]]
nameL = []
for opt, optV in program_parameterL:
cmdL = []
subNameL = []
if type(optV) == list:
for eachV in optV:
cmd = ' '.join([opt, str(eachV)])
cmdL.append(cmd)
subNameL.append(str(eachV))
else:
cmdL = [' '.join([opt, str(optV)])]
optL.append(cmdL)
if subNameL:
nameL.append(subNameL)
#=------------------------------------------
if debug:
print >>sys.stderr, optL
print >>sys.stderr, nameL
recordL = []
cmdLL = []
iterateParameters2(optL, recordL, cmdLL)
nameLL = []
recordL = []
iterateParameters2(nameL, recordL, nameLL)
if debug:
print >>sys.stderr, cmdLL
print >>sys.stderr, nameLL
num_start = re.compile('^[0-9]')
illegal_char = re.compile('[^a-zA-Z0-9]')
count = 1
for cmdL in cmdLL:
cmd = chdir+' '.join(cmdL)+')'
task_name = "_".join(nameLL[count-1])
task_name = illegal_char.sub('_', task_name)
if num_start.match(task_name):
task_name = '_'+task_name
comment = '' if count > maxrun else '#'
index = count%maxrun-1
upstream_task = assignmentL[index]
assignmentL[index] = task_name
tmpD = {"cmd":cmd, "task_name":task_name,
"upstream_task":upstream_task,
"email": email,
"comment": comment}
count += 1
print '''
{d[task_name]} = BashOperator(
task_id='{d[task_name]}',
bash_command="{d[cmd]} ",
dag=dag)
{d[task_name]}_success_mail = EmailOperator(
task_id="{d[task_name]}_success_mail",
to={d[email]},
subject="{d[task_name]} success",
html_content="{d[task_name]} success",
dag=dag)
{d[task_name]}_success_mail.set_upstream({d[task_name]})
{d[comment]}{d[task_name]}.set_upstream({d[upstream_task]})
'''.format(d=tmpD)
#---------END of generateCmd----------------------
def main():
options, args = cmdparameter(sys.argv)
#-----------------------------------
config = options.filein
verbose = options.verbose
global debug
debug = options.debug
#-----------------------------------
fh = open(config)
context = ''.join(fh.readlines())
fh.close()
if debug:
print >>sys.stderr, context
configD = json_loads(context)
#--------------------------------
print '''
from airflow import DAG
from airflow.operators import BashOperator, EmailOperator
from datetime import datetime, timedelta
one_min_ago = datetime.combine(datetime.today() - timedelta(minutes=20),
datetime.min.time())
default_args = {'''
airflowArgD = configD['airflow_parameter']
arg_keyL = airflowArgD.keys()
arg_keyL.remove('dag_id')
arg_keyL.remove('schedule_interval')
if 'comment' in arg_keyL:
arg_keyL.remove('comment')
len_argKey = len(arg_keyL)
for i in range(1, len_argKey):
key = arg_keyL[i]
value = airflowArgD[key]
print " '{}': {},".format(key, value)
print " '{}': {}\n{}".format(
arg_keyL[0], airflowArgD[arg_keyL[0]], '}')
print
print '''
dag = DAG({}, default_args=default_args, schedule_interval={})
'''.format(airflowArgD['dag_id'], airflowArgD['schedule_interval'])
maxrun = configD["parallel_parameter"]["maxrun"]
program = configD['program']
program_parameter = configD['program_parameter']
work_dir = configD['work_dir']
generateCmd2(program, program_parameter, work_dir, maxrun, email=airflowArgD["email"])
if __name__ == '__main__':
main()