0
|
1 # replace with shebang for biocontainer
|
|
2 # see https://github.com/fubar2/toolfactory
|
|
3 #
|
|
4 # copyright ross lazarus (ross stop lazarus at gmail stop com) May 2012
|
|
5 #
|
|
6 # all rights reserved
|
|
7 # Licensed under the LGPL
|
|
8 # suggestions for improvement and bug fixes welcome at
|
|
9 # https://github.com/fubar2/toolfactory
|
|
10 #
|
|
11 # July 2020: BCC was fun and I feel like rip van winkle after 5 years.
|
|
12 # Decided to
|
|
13 # 1. Fix the toolfactory so it works - done for simplest case
|
|
14 # 2. Fix planemo so the toolfactory function works
|
|
15 # 3. Rewrite bits using galaxyxml functions where that makes sense - done
|
|
16 #
|
|
17 # uses planemo in a biodocker sort of image as a requirement
|
|
18 # otherwise planemo seems to leak dependencies back into the
|
|
19 # calling venv. Hilarity ensues.
|
|
20
|
|
21
|
|
22
|
|
23 import argparse
|
|
24 import copy
|
|
25 import datetime
|
|
26 import grp
|
|
27 import json
|
|
28 import logging
|
|
29 import os
|
|
30 import re
|
|
31 import shutil
|
|
32 import subprocess
|
|
33 import sys
|
|
34 import tarfile
|
|
35 import tempfile
|
|
36 import time
|
|
37
|
|
38
|
|
39 from bioblend import ConnectionError
|
|
40 from bioblend import toolshed
|
|
41
|
|
42 import docker
|
|
43
|
|
44 import galaxyxml.tool as gxt
|
|
45 import galaxyxml.tool.parameters as gxtp
|
|
46
|
|
47 import lxml
|
|
48
|
|
49 import yaml
|
|
50
|
|
51 myversion = "V2.1 July 2020"
|
|
52 verbose = True
|
|
53 debug = True
|
|
54 toolFactoryURL = "https://github.com/fubar2/toolfactory"
|
|
55 ourdelim = "~~~"
|
|
56
|
|
57 # --input_files="$intab.input_files~~~$intab.input_CL~~~$intab.input_formats\
|
|
58 #~~~$intab.input_label~~~$intab.input_help"
|
|
59 IPATHPOS = 0
|
|
60 ICLPOS = 1
|
|
61 IFMTPOS = 2
|
|
62 ILABPOS = 3
|
|
63 IHELPOS = 4
|
|
64 IOCLPOS = 5
|
|
65
|
|
66 # --output_files "$otab.history_name~~~$otab.history_format~~~$otab.history_CL~~~$otab.history_test"
|
|
67 ONAMEPOS = 0
|
|
68 OFMTPOS = 1
|
|
69 OCLPOS = 2
|
|
70 OTESTPOS = 3
|
|
71 OOCLPOS = 4
|
|
72
|
|
73
|
|
74 # --additional_parameters="$i.param_name~~~$i.param_value~~~
|
|
75 # $i.param_label~~~$i.param_help~~~$i.param_type~~~$i.CL~~~i$.param_CLoverride"
|
|
76 ANAMEPOS = 0
|
|
77 AVALPOS = 1
|
|
78 ALABPOS = 2
|
|
79 AHELPPOS = 3
|
|
80 ATYPEPOS = 4
|
|
81 ACLPOS = 5
|
|
82 AOVERPOS = 6
|
|
83 AOCLPOS = 7
|
|
84
|
|
85
|
|
86 foo = len(lxml.__version__)
|
|
87 # fug you, flake8. Say my name!
|
|
88 FAKEEXE = "~~~REMOVE~~~ME~~~"
|
|
89 # need this until a PR/version bump to fix galaxyxml prepending the exe even
|
|
90 # with override.
|
|
91
|
|
92
|
|
93 def timenow():
|
|
94 """return current time as a string"""
|
|
95 return time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(time.time()))
|
|
96
|
|
97
|
|
98 def quote_non_numeric(s):
|
|
99 """return a prequoted string for non-numerics
|
|
100 useful for perl and Rscript parameter passing?
|
|
101 """
|
|
102 try:
|
|
103 _ = float(s)
|
|
104 return s
|
|
105 except ValueError:
|
|
106 return '"%s"' % s
|
|
107
|
|
108
|
|
109 html_escape_table = {"&": "&", ">": ">", "<": "<", "$": r"\$","#":"#", "$":"$"}
|
|
110 cheetah_escape_table = {"$": "\$","#":"\#"}
|
|
111
|
|
112 def html_escape(text):
|
|
113 """Produce entities within text."""
|
|
114 return "".join([html_escape_table.get(c, c) for c in text])
|
|
115
|
|
116 def cheetah_escape(text):
|
|
117 """Produce entities within text."""
|
|
118 return "".join([cheetah_escape_table.get(c, c) for c in text])
|
|
119
|
|
120
|
|
121 def html_unescape(text):
|
|
122 """Revert entities within text. Multiple character targets so use replace"""
|
|
123 t = text.replace("&", "&")
|
|
124 t = t.replace(">", ">")
|
|
125 t = t.replace("<", "<")
|
|
126 t = t.replace("\\$", "$")
|
|
127 t = t.replace("$","$")
|
|
128 t = t.replace("#","#")
|
|
129 return t
|
|
130
|
|
131
|
|
132 def parse_citations(citations_text):
|
|
133 """"""
|
|
134 citations = [c for c in citations_text.split("**ENTRY**") if c.strip()]
|
|
135 citation_tuples = []
|
|
136 for citation in citations:
|
|
137 if citation.startswith("doi"):
|
|
138 citation_tuples.append(("doi", citation[len("doi") :].strip()))
|
|
139 else:
|
|
140 citation_tuples.append(("bibtex", citation[len("bibtex") :].strip()))
|
|
141 return citation_tuples
|
|
142
|
|
143
|
|
144 class ScriptRunner:
|
|
145 """Wrapper for an arbitrary script
|
|
146 uses galaxyxml
|
|
147
|
|
148 """
|
|
149
|
|
150 def __init__(self, args=None):
|
|
151 """
|
|
152 prepare command line cl for running the tool here
|
|
153 and prepare elements needed for galaxyxml tool generation
|
|
154 """
|
|
155 self.ourcwd = os.getcwd()
|
|
156 self.ourenv = copy.deepcopy(os.environ)
|
|
157 self.infiles = [x.split(ourdelim) for x in args.input_files]
|
|
158 self.outfiles = [x.split(ourdelim) for x in args.output_files]
|
|
159 self.addpar = [x.split(ourdelim) for x in args.additional_parameters]
|
|
160 self.args = args
|
|
161 self.cleanuppar()
|
|
162 self.lastclredirect = None
|
|
163 self.lastxclredirect = None
|
|
164 self.cl = []
|
|
165 self.xmlcl = []
|
|
166 self.is_positional = self.args.parampass == "positional"
|
|
167 if self.args.sysexe:
|
|
168 self.executeme = self.args.sysexe
|
|
169 else:
|
|
170 if self.args.packages:
|
|
171 self.executeme = self.args.packages.split(",")[0].split(":")[0]
|
|
172 else:
|
|
173 self.executeme = None
|
|
174 aCL = self.cl.append
|
|
175 aXCL = self.xmlcl.append
|
|
176 assert args.parampass in [
|
|
177 "0",
|
|
178 "argparse",
|
|
179 "positional",
|
|
180 ], 'args.parampass must be "0","positional" or "argparse"'
|
|
181 self.tool_name = re.sub("[^a-zA-Z0-9_]+", "", args.tool_name)
|
|
182 self.tool_id = self.tool_name
|
|
183 self.newtool = gxt.Tool(
|
|
184 self.tool_name,
|
|
185 self.tool_id,
|
|
186 self.args.tool_version,
|
|
187 self.args.tool_desc,
|
|
188 FAKEEXE,
|
|
189 )
|
|
190 self.newtarpath = "toolfactory_%s.tgz" % self.tool_name
|
|
191 self.tooloutdir = "./tfout"
|
|
192 self.repdir = "./TF_run_report_tempdir"
|
|
193 self.testdir = os.path.join(self.tooloutdir, "test-data")
|
|
194 if not os.path.exists(self.tooloutdir):
|
|
195 os.mkdir(self.tooloutdir)
|
|
196 if not os.path.exists(self.testdir):
|
|
197 os.mkdir(self.testdir)
|
|
198 if not os.path.exists(self.repdir):
|
|
199 os.mkdir(self.repdir)
|
|
200 self.tinputs = gxtp.Inputs()
|
|
201 self.toutputs = gxtp.Outputs()
|
|
202 self.testparam = []
|
|
203 if self.args.script_path:
|
|
204 self.prepScript()
|
|
205 if self.args.command_override:
|
|
206 scos = open(self.args.command_override, "r").readlines()
|
|
207 self.command_override = [x.rstrip() for x in scos]
|
|
208 else:
|
|
209 self.command_override = None
|
|
210 if self.args.test_override:
|
|
211 stos = open(self.args.test_override, "r").readlines()
|
|
212 self.test_override = [x.rstrip() for x in stos]
|
|
213 else:
|
|
214 self.test_override = None
|
|
215 if self.args.cl_prefix: # DIY CL start
|
|
216 clp = self.args.cl_prefix.split(" ")
|
|
217 for c in clp:
|
|
218 aCL(c)
|
|
219 aXCL(c)
|
|
220 else:
|
|
221 if self.args.script_path:
|
|
222 aCL(self.executeme)
|
|
223 aCL(self.sfile)
|
|
224 aXCL(self.executeme)
|
|
225 aXCL("$runme")
|
|
226 else:
|
|
227 aCL(self.executeme)
|
|
228 aXCL(self.executeme)
|
|
229 self.elog = os.path.join(self.repdir, "%s_error_log.txt" % self.tool_name)
|
|
230 self.tlog = os.path.join(self.repdir, "%s_runner_log.txt" % self.tool_name)
|
|
231
|
|
232 if self.args.parampass == "0":
|
|
233 self.clsimple()
|
|
234 else:
|
|
235 clsuffix = []
|
|
236 xclsuffix = []
|
|
237 for i, p in enumerate(self.infiles):
|
|
238 if p[IOCLPOS] == "STDIN":
|
|
239 appendme = [
|
|
240 p[IOCLPOS],
|
|
241 p[ICLPOS],
|
|
242 p[IPATHPOS],
|
|
243 "< %s" % p[IPATHPOS],
|
|
244 ]
|
|
245 xappendme = [
|
|
246 p[IOCLPOS],
|
|
247 p[ICLPOS],
|
|
248 p[IPATHPOS],
|
|
249 "< $%s" % p[ICLPOS],
|
|
250 ]
|
|
251 else:
|
|
252 appendme = [p[IOCLPOS], p[ICLPOS], p[IPATHPOS], ""]
|
|
253 xappendme = [p[IOCLPOS], p[ICLPOS], "$%s" % p[ICLPOS], ""]
|
|
254 clsuffix.append(appendme)
|
|
255 xclsuffix.append(xappendme)
|
|
256 for i, p in enumerate(self.outfiles):
|
|
257 if p[OOCLPOS] == "STDOUT":
|
|
258 self.lastclredirect = [">", p[ONAMEPOS]]
|
|
259 self.lastxclredirect = [">", "$%s" % p[OCLPOS]]
|
|
260 else:
|
|
261 clsuffix.append([p[ONAMEPOS], p[ONAMEPOS], p[ONAMEPOS], ""])
|
|
262 xclsuffix.append([p[ONAMEPOS], p[ONAMEPOS], "$%s" % p[ONAMEPOS], ""])
|
|
263 for p in self.addpar:
|
|
264 clsuffix.append([p[AOCLPOS], p[ACLPOS], p[AVALPOS], p[AOVERPOS]])
|
|
265 xclsuffix.append(
|
|
266 [p[AOCLPOS], p[ACLPOS], '"$%s"' % p[ANAMEPOS], p[AOVERPOS]]
|
|
267 )
|
|
268 clsuffix.sort()
|
|
269 xclsuffix.sort()
|
|
270 self.xclsuffix = xclsuffix
|
|
271 self.clsuffix = clsuffix
|
|
272 if self.args.parampass == "positional":
|
|
273 self.clpositional()
|
|
274 else:
|
|
275 self.clargparse()
|
|
276
|
|
277 def prepScript(self):
|
|
278 rx = open(self.args.script_path, "r").readlines()
|
|
279 rx = [x.rstrip() for x in rx]
|
|
280 rxcheck = [x.strip() for x in rx if x.strip() > ""]
|
|
281 assert len(rxcheck) > 0, "Supplied script is empty. Cannot run"
|
|
282 self.script = "\n".join(rx)
|
|
283 fhandle, self.sfile = tempfile.mkstemp(
|
|
284 prefix=self.tool_name, suffix="_%s" % (self.executeme)
|
|
285 )
|
|
286 tscript = open(self.sfile, "w")
|
|
287 tscript.write(self.script)
|
|
288 tscript.close()
|
|
289 self.escapedScript = [cheetah_escape(x) for x in rx]
|
|
290 self.spacedScript = [f" {x}" for x in rx if x.strip() > ""]
|
|
291 art = "%s.%s" % (self.tool_name, self.executeme)
|
|
292 artifact = open(art, "wb")
|
|
293 artifact.write(bytes('\n'.join(self.escapedScript),'utf8'))
|
|
294 artifact.close()
|
|
295
|
|
296 def cleanuppar(self):
|
|
297 """ positional parameters are complicated by their numeric ordinal"""
|
|
298 for i, p in enumerate(self.infiles):
|
|
299 infp = copy.copy(p)
|
|
300 if self.args.parampass == "positional":
|
|
301 assert infp[
|
|
302 ICLPOS
|
|
303 ].isdigit(), "Positional parameters must be ordinal integers - got %s for %s" % (
|
|
304 infp[ICLPOS],
|
|
305 infp[ILABPOS],
|
|
306 )
|
|
307 icl = infp[ICLPOS]
|
|
308 infp.append(icl)
|
|
309 if infp[ICLPOS].isdigit() or self.args.parampass == "0":
|
|
310 scl = "input%d" % (i + 1)
|
|
311 infp[ICLPOS] = scl
|
|
312 self.infiles[i] = infp
|
|
313 for i, p in enumerate(
|
|
314 self.outfiles
|
|
315 ):
|
|
316 if self.args.parampass == "positional" and p[OCLPOS].upper() != "STDOUT":
|
|
317 assert p[
|
|
318 OCLPOS
|
|
319 ].isdigit(), "Positional parameters must be ordinal integers - got %s for %s" % (
|
|
320 p[OCLPOS],
|
|
321 p[ONAMEPOS],
|
|
322 )
|
|
323 p.append(p[OCLPOS]) # keep copy
|
|
324 if p[OOCLPOS].isdigit() or p[OOCLPOS].upper() == "STDOUT":
|
|
325 scl = p[ONAMEPOS]
|
|
326 p[OCLPOS] = scl
|
|
327 self.outfiles[i] = p
|
|
328 for i, p in enumerate(self.addpar):
|
|
329 if self.args.parampass == "positional":
|
|
330 assert p[
|
|
331 ACLPOS
|
|
332 ].isdigit(), "Positional parameters must be ordinal integers - got %s for %s" % (
|
|
333 p[ACLPOS],
|
|
334 p[ANAMEPOS],
|
|
335 )
|
|
336 p.append(p[ACLPOS])
|
|
337 if p[ACLPOS].isdigit():
|
|
338 scl = "input%s" % p[ACLPOS]
|
|
339 p[ACLPOS] = scl
|
|
340 self.addpar[i] = p
|
|
341
|
|
342 def clsimple(self):
|
|
343 """no parameters - uses < and > for i/o"""
|
|
344 aCL = self.cl.append
|
|
345 aXCL = self.xmlcl.append
|
|
346
|
|
347 if len(self.infiles) > 0:
|
|
348 aCL("<")
|
|
349 aCL(self.infiles[0][IPATHPOS])
|
|
350 aXCL("<")
|
|
351 aXCL("$%s" % self.infiles[0][ICLPOS])
|
|
352 if len(self.outfiles) > 0:
|
|
353 aCL(">")
|
|
354 aCL(self.outfiles[0][OCLPOS])
|
|
355 aXCL(">")
|
|
356 aXCL("$%s" % self.outfiles[0][ONAMEPOS])
|
|
357
|
|
358 def clpositional(self):
|
|
359 # inputs in order then params
|
|
360 aCL = self.cl.append
|
|
361 for (o_v, k, v, koverride) in self.clsuffix:
|
|
362 if " " in v:
|
|
363 aCL("%s" % v)
|
|
364 else:
|
|
365 aCL(v)
|
|
366 aXCL = self.xmlcl.append
|
|
367 for (o_v, k, v, koverride) in self.xclsuffix:
|
|
368 aXCL(v)
|
|
369 if self.lastxclredirect:
|
|
370 aXCL(self.lastxclredirect[0])
|
|
371 aXCL(self.lastxclredirect[1])
|
|
372
|
|
373
|
|
374 def clargparse(self):
|
|
375 """argparse style"""
|
|
376 aCL = self.cl.append
|
|
377 aXCL = self.xmlcl.append
|
|
378 # inputs then params in argparse named form
|
|
379
|
|
380 for (o_v, k, v, koverride) in self.xclsuffix:
|
|
381 if koverride > "":
|
|
382 k = koverride
|
|
383 elif len(k.strip()) == 1:
|
|
384 k = "-%s" % k
|
|
385 else:
|
|
386 k = "--%s" % k
|
|
387 aXCL(k)
|
|
388 aXCL(v)
|
|
389 for (o_v, k, v, koverride) in self.clsuffix:
|
|
390 if koverride > "":
|
|
391 k = koverride
|
|
392 elif len(k.strip()) == 1:
|
|
393 k = "-%s" % k
|
|
394 else:
|
|
395 k = "--%s" % k
|
|
396 aCL(k)
|
|
397 aCL(v)
|
|
398
|
|
399
|
|
400 def getNdash(self, newname):
|
|
401 if self.is_positional:
|
|
402 ndash = 0
|
|
403 else:
|
|
404 ndash = 2
|
|
405 if len(newname) < 2:
|
|
406 ndash = 1
|
|
407 return ndash
|
|
408
|
|
409 def doXMLparam(self):
|
|
410 """flake8 made me do this..."""
|
|
411 for p in self.outfiles: # --output_files "$otab.history_name~~~$otab.history_format~~~$otab.history_CL~~~$otab.history_test"
|
|
412 newname, newfmt, newcl, test, oldcl = p
|
|
413 test = test.strip()
|
|
414 ndash = self.getNdash(newcl)
|
|
415 aparm = gxtp.OutputData(name=newname, format=newfmt, num_dashes=ndash, label=newcl)
|
|
416 aparm.positional = self.is_positional
|
|
417 if self.is_positional:
|
|
418 if oldcl.upper() == "STDOUT":
|
|
419 aparm.positional = 9999999
|
|
420 aparm.command_line_override = "> $%s" % newname
|
|
421 else:
|
|
422 aparm.positional = int(oldcl)
|
|
423 aparm.command_line_override = "$%s" % newname
|
|
424 self.toutputs.append(aparm)
|
|
425 ld = None
|
|
426 if test.strip() > "":
|
|
427 if test.startswith("diff"):
|
|
428 c = "diff"
|
|
429 ld = 0
|
|
430 if test.split(":")[1].isdigit:
|
|
431 ld = int(test.split(":")[1])
|
|
432 tp = gxtp.TestOutput(
|
|
433 name=newcl,
|
|
434 value="%s_sample" % newcl,
|
|
435 format=newfmt,
|
|
436 compare= c,
|
|
437 lines_diff=ld,
|
|
438 )
|
|
439 elif test.startswith("sim_size"):
|
|
440 c = "sim_size"
|
|
441 tn = test.split(":")[1].strip()
|
|
442 if tn > '':
|
|
443 if '.' in tn:
|
|
444 delta = None
|
|
445 delta_frac = min(1.0,float(tn))
|
|
446 else:
|
|
447 delta = int(tn)
|
|
448 delta_frac = None
|
|
449 tp = gxtp.TestOutput(
|
|
450 name=newcl,
|
|
451 value="%s_sample" % newcl,
|
|
452 format=newfmt,
|
|
453 compare= c,
|
|
454 delta = delta,
|
|
455 delta_frac = delta_frac
|
|
456 )
|
|
457 self.testparam.append(tp)
|
|
458 for p in self.infiles:
|
|
459 newname = p[ICLPOS]
|
|
460 newfmt = p[IFMTPOS]
|
|
461 ndash = self.getNdash(newname)
|
|
462 if not len(p[ILABPOS]) > 0:
|
|
463 alab = p[ICLPOS]
|
|
464 else:
|
|
465 alab = p[ILABPOS]
|
|
466 aninput = gxtp.DataParam(
|
|
467 newname,
|
|
468 optional=False,
|
|
469 label=alab,
|
|
470 help=p[IHELPOS],
|
|
471 format=newfmt,
|
|
472 multiple=False,
|
|
473 num_dashes=ndash,
|
|
474 )
|
|
475 aninput.positional = self.is_positional
|
|
476 self.tinputs.append(aninput)
|
|
477 tparm = gxtp.TestParam(name=newname, value="%s_sample" % newname)
|
|
478 self.testparam.append(tparm)
|
|
479 for p in self.addpar:
|
|
480 newname, newval, newlabel, newhelp, newtype, newcl, override, oldcl = p
|
|
481 if not len(newlabel) > 0:
|
|
482 newlabel = newname
|
|
483 ndash = self.getNdash(newname)
|
|
484 if newtype == "text":
|
|
485 aparm = gxtp.TextParam(
|
|
486 newname,
|
|
487 label=newlabel,
|
|
488 help=newhelp,
|
|
489 value=newval,
|
|
490 num_dashes=ndash,
|
|
491 )
|
|
492 elif newtype == "integer":
|
|
493 aparm = gxtp.IntegerParam(
|
|
494 newname,
|
|
495 label=newname,
|
|
496 help=newhelp,
|
|
497 value=newval,
|
|
498 num_dashes=ndash,
|
|
499 )
|
|
500 elif newtype == "float":
|
|
501 aparm = gxtp.FloatParam(
|
|
502 newname,
|
|
503 label=newname,
|
|
504 help=newhelp,
|
|
505 value=newval,
|
|
506 num_dashes=ndash,
|
|
507 )
|
|
508 else:
|
|
509 raise ValueError(
|
|
510 'Unrecognised parameter type "%s" for\
|
|
511 additional parameter %s in makeXML'
|
|
512 % (newtype, newname)
|
|
513 )
|
|
514 aparm.positional = self.is_positional
|
|
515 if self.is_positional:
|
|
516 aparm.positional = int(oldcl)
|
|
517 self.tinputs.append(aparm)
|
|
518 tparm = gxtp.TestParam(newname, value=newval)
|
|
519 self.testparam.append(tparm)
|
|
520
|
|
521 def doNoXMLparam(self):
|
|
522 """filter style package - stdin to stdout"""
|
|
523 if len(self.infiles) > 0:
|
|
524 alab = self.infiles[0][ILABPOS]
|
|
525 if len(alab) == 0:
|
|
526 alab = self.infiles[0][ICLPOS]
|
|
527 max1s = (
|
|
528 "Maximum one input if parampass is 0 but multiple input files supplied - %s"
|
|
529 % str(self.infiles)
|
|
530 )
|
|
531 assert len(self.infiles) == 1, max1s
|
|
532 newname = self.infiles[0][ICLPOS]
|
|
533 aninput = gxtp.DataParam(
|
|
534 newname,
|
|
535 optional=False,
|
|
536 label=alab,
|
|
537 help=self.infiles[0][IHELPOS],
|
|
538 format=self.infiles[0][IFMTPOS],
|
|
539 multiple=False,
|
|
540 num_dashes=0,
|
|
541 )
|
|
542 aninput.command_line_override = "< $%s" % newname
|
|
543 aninput.positional = self.is_positional
|
|
544 self.tinputs.append(aninput)
|
|
545 tp = gxtp.TestParam(name=newname, value="%s_sample" % newname)
|
|
546 self.testparam.append(tp)
|
|
547 if len(self.outfiles) > 0:
|
|
548 newname = self.outfiles[0][OCLPOS]
|
|
549 newfmt = self.outfiles[0][OFMTPOS]
|
|
550 anout = gxtp.OutputData(newname, format=newfmt, num_dashes=0)
|
|
551 anout.command_line_override = "> $%s" % newname
|
|
552 anout.positional = self.is_positional
|
|
553 self.toutputs.append(anout)
|
|
554 tp = gxtp.TestOutput(
|
|
555 name=newname, value="%s_sample" % newname, format=newfmt
|
|
556 )
|
|
557 self.testparam.append(tp)
|
|
558
|
|
559 def makeXML(self):
|
|
560 """
|
|
561 Create a Galaxy xml tool wrapper for the new script
|
|
562 Uses galaxyhtml
|
|
563 Hmmm. How to get the command line into correct order...
|
|
564 """
|
|
565 if self.command_override:
|
|
566 self.newtool.command_override = self.command_override # config file
|
|
567 else:
|
|
568 self.newtool.command_override = self.xmlcl
|
|
569 if self.args.help_text:
|
|
570 helptext = open(self.args.help_text, "r").readlines()
|
|
571 safertext = "\n".join([cheetah_escape(x) for x in helptext])
|
|
572 if self.args.script_path:
|
|
573 scr = [x for x in self.spacedScript if x.strip() > ""]
|
|
574 scr.insert(0,'\n------\n\n\nScript::\n')
|
|
575 if len(scr) > 300:
|
|
576 scr = (
|
|
577 scr[:100]
|
|
578 + [" >300 lines - stuff deleted", " ......"]
|
|
579 + scr[-100:]
|
|
580 )
|
|
581 scr.append('\n')
|
|
582 safertext = safertext + "\n".join(scr)
|
|
583 self.newtool.help = safertext
|
|
584 else:
|
|
585 self.newtool.help = (
|
|
586 "Please ask the tool author (%s) for help \
|
|
587 as none was supplied at tool generation\n"
|
|
588 % (self.args.user_email)
|
|
589 )
|
|
590 self.newtool.version_command = None # do not want
|
|
591 requirements = gxtp.Requirements()
|
|
592 if self.args.packages:
|
|
593 for d in self.args.packages.split(","):
|
|
594 ver = ''
|
|
595 d = d.replace('==',':')
|
|
596 d = d.replace('=',':')
|
|
597 if ":" in d:
|
|
598 packg, ver = d.split(":")
|
|
599 else:
|
|
600 packg = d
|
|
601 requirements.append(
|
|
602 gxtp.Requirement("package", packg.strip(), ver.strip())
|
|
603 )
|
|
604 self.newtool.requirements = requirements
|
|
605 if self.args.parampass == "0":
|
|
606 self.doNoXMLparam()
|
|
607 else:
|
|
608 self.doXMLparam()
|
|
609 self.newtool.outputs = self.toutputs
|
|
610 self.newtool.inputs = self.tinputs
|
|
611 if self.args.script_path:
|
|
612 configfiles = gxtp.Configfiles()
|
|
613 configfiles.append(gxtp.Configfile(name="runme", text="\n".join(self.escapedScript)))
|
|
614 self.newtool.configfiles = configfiles
|
|
615 tests = gxtp.Tests()
|
|
616 test_a = gxtp.Test()
|
|
617 for tp in self.testparam:
|
|
618 test_a.append(tp)
|
|
619 tests.append(test_a)
|
|
620 self.newtool.tests = tests
|
|
621 self.newtool.add_comment(
|
|
622 "Created by %s at %s using the Galaxy Tool Factory."
|
|
623 % (self.args.user_email, timenow())
|
|
624 )
|
|
625 self.newtool.add_comment("Source in git at: %s" % (toolFactoryURL))
|
|
626 self.newtool.add_comment(
|
|
627 "Cite: Creating re-usable tools from scripts doi:10.1093/bioinformatics/bts573"
|
|
628 )
|
|
629 exml0 = self.newtool.export()
|
|
630 exml = exml0.replace(FAKEEXE, "") # temporary work around until PR accepted
|
|
631 if (
|
|
632 self.test_override
|
|
633 ): # cannot do this inside galaxyxml as it expects lxml objects for tests
|
|
634 part1 = exml.split("<tests>")[0]
|
|
635 part2 = exml.split("</tests>")[1]
|
|
636 fixed = "%s\n%s\n%s" % (part1, self.test_override, part2)
|
|
637 exml = fixed
|
|
638 #exml = exml.replace('range="1:"', 'range="1000:"')
|
|
639 xf = open("%s.xml" % self.tool_name, "w")
|
|
640 xf.write(exml)
|
|
641 xf.write("\n")
|
|
642 xf.close()
|
|
643 # ready for the tarball
|
|
644
|
|
645 def run(self):
|
|
646 """
|
|
647 generate test outputs by running a command line
|
|
648 won't work if command or test override in play - planemo is the
|
|
649 easiest way to generate test outputs for that case so is
|
|
650 automagically selected
|
|
651 """
|
|
652 scl = " ".join(self.cl)
|
|
653 err = None
|
|
654 if self.args.parampass != "0":
|
|
655 if os.path.exists(self.elog):
|
|
656 ste = open(self.elog, "a")
|
|
657 else:
|
|
658 ste = open(self.elog, "w")
|
|
659 if self.lastclredirect:
|
|
660 sto = open(self.lastclredirect[1], "wb") # is name of an output file
|
|
661 else:
|
|
662 if os.path.exists(self.tlog):
|
|
663 sto = open(self.tlog, "a")
|
|
664 else:
|
|
665 sto = open(self.tlog, "w")
|
|
666 sto.write(
|
|
667 "## Executing Toolfactory generated command line = %s\n" % scl
|
|
668 )
|
|
669 sto.flush()
|
|
670 subp = subprocess.run(
|
|
671 self.cl, env=self.ourenv, shell=False, stdout=sto, stderr=ste
|
|
672 )
|
|
673 sto.close()
|
|
674 ste.close()
|
|
675 retval = subp.returncode
|
|
676 else: # work around special case - stdin and write to stdout
|
|
677 if len(self.infiles) > 0:
|
|
678 sti = open(self.infiles[0][IPATHPOS], "rb")
|
|
679 else:
|
|
680 sti = sys.stdin
|
|
681 if len(self.outfiles) > 0:
|
|
682 sto = open(self.outfiles[0][ONAMEPOS], "wb")
|
|
683 else:
|
|
684 sto = sys.stdout
|
|
685 subp = subprocess.run(
|
|
686 self.cl, env=self.ourenv, shell=False, stdout=sto, stdin=sti
|
|
687 )
|
|
688 sto.write("## Executing Toolfactory generated command line = %s\n" % scl)
|
|
689 retval = subp.returncode
|
|
690 sto.close()
|
|
691 sti.close()
|
|
692 if os.path.isfile(self.tlog) and os.stat(self.tlog).st_size == 0:
|
|
693 os.unlink(self.tlog)
|
|
694 if os.path.isfile(self.elog) and os.stat(self.elog).st_size == 0:
|
|
695 os.unlink(self.elog)
|
|
696 if retval != 0 and err: # problem
|
|
697 sys.stderr.write(err)
|
|
698 logging.debug("run done")
|
|
699 return retval
|
|
700
|
|
701 def copy_to_container(self, src, dest, container):
|
|
702 """Recreate the src directory tree at dest - full path included"""
|
|
703 idir = os.getcwd()
|
|
704 workdir = os.path.dirname(src)
|
|
705 os.chdir(workdir)
|
|
706 _, tfname = tempfile.mkstemp(suffix=".tar")
|
|
707 tar = tarfile.open(tfname, mode="w")
|
|
708 srcb = os.path.basename(src)
|
|
709 tar.add(srcb)
|
|
710 tar.close()
|
|
711 data = open(tfname, "rb").read()
|
|
712 container.put_archive(dest, data)
|
|
713 os.unlink(tfname)
|
|
714 os.chdir(idir)
|
|
715
|
|
716 def copy_from_container(self, src, dest, container):
|
|
717 """recreate the src directory tree at dest using docker sdk"""
|
|
718 os.makedirs(dest, exist_ok=True)
|
|
719 _, tfname = tempfile.mkstemp(suffix=".tar")
|
|
720 tf = open(tfname, "wb")
|
|
721 bits, stat = container.get_archive(src)
|
|
722 for chunk in bits:
|
|
723 tf.write(chunk)
|
|
724 tf.close()
|
|
725 tar = tarfile.open(tfname, "r")
|
|
726 tar.extractall(dest)
|
|
727 tar.close()
|
|
728 os.unlink(tfname)
|
|
729
|
|
730 def planemo_biodocker_test(self):
|
|
731 """planemo currently leaks dependencies if used in the same container and gets unhappy after a
|
|
732 first successful run. https://github.com/galaxyproject/planemo/issues/1078#issuecomment-731476930
|
|
733
|
|
734 Docker biocontainer has planemo with caches filled to save repeated downloads
|
|
735
|
|
736
|
|
737 """
|
|
738
|
|
739 def prun(container, tout, cl, user="biodocker"):
|
|
740 rlog = container.exec_run(cl, user=user)
|
|
741 slogl = str(rlog).split("\\n")
|
|
742 slog = "\n".join(slogl)
|
|
743 tout.write(f"## got rlog {slog} from {cl}\n")
|
|
744
|
|
745 if os.path.exists(self.tlog):
|
|
746 tout = open(self.tlog, "a")
|
|
747 else:
|
|
748 tout = open(self.tlog, "w")
|
|
749 planemoimage = "quay.io/fubar2/planemo-biocontainer"
|
|
750 xreal = "%s.xml" % self.tool_name
|
|
751 repname = f"{self.tool_name}_planemo_test_report.html"
|
|
752 ptestrep_path = os.path.join(self.repdir, repname)
|
|
753 tool_name = self.tool_name
|
|
754 client = docker.from_env()
|
|
755 tvol = client.volumes.create()
|
|
756 tvolname = tvol.name
|
|
757 destdir = "/toolfactory/ptest"
|
|
758 imrep = os.path.join(destdir, repname)
|
|
759 # need to keep the container running so keep it open with sleep
|
|
760 # will stop and destroy it when we are done
|
|
761 container = client.containers.run(
|
|
762 planemoimage,
|
|
763 "sleep 120m",
|
|
764 detach=True,
|
|
765 user="biodocker",
|
|
766 volumes={f"{tvolname}": {"bind": "/toolfactory", "mode": "rw"}},
|
|
767 )
|
|
768 cl = f"mkdir -p {destdir}"
|
|
769 prun(container, tout, cl, user="root")
|
|
770 # that's how hard it is to get root on a biodocker container :(
|
|
771 cl = f"rm -rf {destdir}/*"
|
|
772 prun(container, tout, cl, user="root")
|
|
773 ptestpath = os.path.join(destdir, "tfout", xreal)
|
|
774 self.copy_to_container(self.tooloutdir, destdir, container)
|
|
775 cl = "chown -R biodocker /toolfactory"
|
|
776 prun(container, tout, cl, user="root")
|
|
777 rlog = container.exec_run(f"ls -la {destdir}")
|
|
778 ptestcl = f"planemo test --update_test_data --no_cleanup --test_data {destdir}/tfout/test-data --galaxy_root /home/biodocker/galaxy-central {ptestpath}"
|
|
779 try:
|
|
780 rlog = container.exec_run(ptestcl)
|
|
781 # fails because test outputs missing but updates the test-data directory
|
|
782 except:
|
|
783 e = sys.exc_info()[0]
|
|
784 tout.write(f"#### error: {e} from {ptestcl}\n")
|
|
785 cl = f"planemo test --test_output {imrep} --no_cleanup --test_data {destdir}/tfout/test-data --galaxy_root /home/biodocker/galaxy-central {ptestpath}"
|
|
786 try:
|
|
787 prun(container, tout, cl)
|
|
788 except:
|
|
789 e = sys.exc_info()[0]
|
|
790 tout.write(f"#### error: {e} from {ptestcl}\n")
|
|
791 testouts = tempfile.mkdtemp(suffix=None, prefix="tftemp", dir=".")
|
|
792 self.copy_from_container(destdir, testouts, container)
|
|
793 src = os.path.join(testouts, "ptest")
|
|
794 if os.path.isdir(src):
|
|
795 shutil.copytree(src, ".", dirs_exist_ok=True)
|
|
796 src = repname
|
|
797 if os.path.isfile(repname):
|
|
798 shutil.copyfile(src, ptestrep_path)
|
|
799 else:
|
|
800 tout.write(f"No output from run to shutil.copytree in {src}\n")
|
|
801 tout.close()
|
|
802 container.stop()
|
|
803 container.remove()
|
|
804 tvol.remove()
|
|
805 shutil.rmtree(testouts) # leave for debugging
|
|
806
|
|
807 def shedLoad(self):
|
|
808 """
|
|
809 use bioblend to create new repository
|
|
810 or update existing
|
|
811
|
|
812 """
|
|
813 if os.path.exists(self.tlog):
|
|
814 sto = open(self.tlog, "a")
|
|
815 else:
|
|
816 sto = open(self.tlog, "w")
|
|
817
|
|
818 ts = toolshed.ToolShedInstance(
|
|
819 url=self.args.toolshed_url, key=self.args.toolshed_api_key, verify=False
|
|
820 )
|
|
821 repos = ts.repositories.get_repositories()
|
|
822 rnames = [x.get("name", "?") for x in repos]
|
|
823 rids = [x.get("id", "?") for x in repos]
|
|
824 tfcat = "ToolFactory generated tools"
|
|
825 if self.tool_name not in rnames:
|
|
826 tscat = ts.categories.get_categories()
|
|
827 cnames = [x.get("name", "?").strip() for x in tscat]
|
|
828 cids = [x.get("id", "?") for x in tscat]
|
|
829 catID = None
|
|
830 if tfcat.strip() in cnames:
|
|
831 ci = cnames.index(tfcat)
|
|
832 catID = cids[ci]
|
|
833 res = ts.repositories.create_repository(
|
|
834 name=self.args.tool_name,
|
|
835 synopsis="Synopsis:%s" % self.args.tool_desc,
|
|
836 description=self.args.tool_desc,
|
|
837 type="unrestricted",
|
|
838 remote_repository_url=self.args.toolshed_url,
|
|
839 homepage_url=None,
|
|
840 category_ids=catID,
|
|
841 )
|
|
842 tid = res.get("id", None)
|
|
843 sto.write(f"#create_repository {self.args.tool_name} tid={tid} res={res}\n")
|
|
844 else:
|
|
845 i = rnames.index(self.tool_name)
|
|
846 tid = rids[i]
|
|
847 try:
|
|
848 res = ts.repositories.update_repository(
|
|
849 id=tid, tar_ball_path=self.newtarpath, commit_message=None
|
|
850 )
|
|
851 sto.write(f"#update res id {id} ={res}\n")
|
|
852 except ConnectionError:
|
|
853 sto.write(
|
|
854 "####### Is the toolshed running and the API key correct? Bioblend shed upload failed\n"
|
|
855 )
|
|
856 sto.close()
|
|
857
|
|
858 def eph_galaxy_load(self):
|
|
859 """
|
|
860 use ephemeris to load the new tool from the local toolshed after planemo uploads it
|
|
861 """
|
|
862 if os.path.exists(self.tlog):
|
|
863 tout = open(self.tlog, "a")
|
|
864 else:
|
|
865 tout = open(self.tlog, "w")
|
|
866 cll = [
|
|
867 "shed-tools",
|
|
868 "install",
|
|
869 "-g",
|
|
870 self.args.galaxy_url,
|
|
871 "--latest",
|
|
872 "-a",
|
|
873 self.args.galaxy_api_key,
|
|
874 "--name",
|
|
875 self.tool_name,
|
|
876 "--owner",
|
|
877 "fubar",
|
|
878 "--toolshed",
|
|
879 self.args.toolshed_url,
|
|
880 "--section_label",
|
|
881 "ToolFactory",
|
|
882 ]
|
|
883 tout.write("running\n%s\n" % " ".join(cll))
|
|
884 subp = subprocess.run(
|
|
885 cll, env=self.ourenv, cwd=self.ourcwd, shell=False, stderr=tout, stdout=tout
|
|
886 )
|
|
887 tout.write(
|
|
888 "installed %s - got retcode %d\n" % (self.tool_name, subp.returncode)
|
|
889 )
|
|
890 tout.close()
|
|
891 return subp.returncode
|
|
892
|
|
893
|
|
894
|
|
895 def writeShedyml(self):
|
|
896 """for planemo"""
|
|
897 yuser = self.args.user_email.split("@")[0]
|
|
898 yfname = os.path.join(self.tooloutdir, ".shed.yml")
|
|
899 yamlf = open(yfname, "w")
|
|
900 odict = {
|
|
901 "name": self.tool_name,
|
|
902 "owner": yuser,
|
|
903 "type": "unrestricted",
|
|
904 "description": self.args.tool_desc,
|
|
905 "synopsis": self.args.tool_desc,
|
|
906 "category": "TF Generated Tools",
|
|
907 }
|
|
908 yaml.dump(odict, yamlf, allow_unicode=True)
|
|
909 yamlf.close()
|
|
910
|
|
911 def makeTool(self):
|
|
912 """write xmls and input samples into place"""
|
|
913 self.makeXML()
|
|
914 if self.args.script_path:
|
|
915 stname = os.path.join(self.tooloutdir, "%s" % (self.sfile))
|
|
916 if not os.path.exists(stname):
|
|
917 shutil.copyfile(self.sfile, stname)
|
|
918 xreal = "%s.xml" % self.tool_name
|
|
919 xout = os.path.join(self.tooloutdir, xreal)
|
|
920 shutil.copyfile(xreal, xout)
|
|
921 for p in self.infiles:
|
|
922 pth = p[IPATHPOS]
|
|
923 dest = os.path.join(self.testdir, "%s_sample" % p[ICLPOS])
|
|
924 shutil.copyfile(pth, dest)
|
|
925
|
|
926 def makeToolTar(self):
|
|
927 """move outputs into test-data and prepare the tarball"""
|
|
928 excludeme = "_planemo_test_report.html"
|
|
929
|
|
930 def exclude_function(tarinfo):
|
|
931 filename = tarinfo.name
|
|
932 return None if filename.endswith(excludeme) else tarinfo
|
|
933
|
|
934 if os.path.exists(self.tlog):
|
|
935 tout = open(self.tlog, "a")
|
|
936 else:
|
|
937 tout = open(self.tlog, "w")
|
|
938 for p in self.outfiles:
|
|
939 oname = p[ONAMEPOS]
|
|
940 tdest = os.path.join(self.testdir, "%s_sample" % oname)
|
|
941 if not os.path.isfile(tdest):
|
|
942 src = os.path.join(self.testdir, oname)
|
|
943 if os.path.isfile(src):
|
|
944 shutil.copyfile(src, tdest)
|
|
945 dest = os.path.join(self.repdir, "%s.sample" % (oname))
|
|
946 shutil.copyfile(src, dest)
|
|
947 else:
|
|
948 tout.write(
|
|
949 "###Output file %s not found in testdir %s. This is normal during the first Planemo run that generates test outputs"
|
|
950 % (tdest, self.testdir)
|
|
951 )
|
|
952 tf = tarfile.open(self.newtarpath, "w:gz")
|
|
953 tf.add(name=self.tooloutdir, arcname=self.tool_name, filter=exclude_function)
|
|
954 tf.close()
|
|
955 shutil.copyfile(self.newtarpath, self.args.new_tool)
|
|
956
|
|
957 def moveRunOutputs(self):
|
|
958 """need to move planemo or run outputs into toolfactory collection"""
|
|
959 with os.scandir(self.tooloutdir) as outs:
|
|
960 for entry in outs:
|
|
961 if not entry.is_file():
|
|
962 continue
|
|
963 if "." in entry.name:
|
|
964 nayme, ext = os.path.splitext(entry.name)
|
|
965 if ext in [".yml", ".xml", ".json", ".yaml"]:
|
|
966 ext = f"{ext}.txt"
|
|
967 else:
|
|
968 ext = ".txt"
|
|
969 ofn = "%s%s" % (entry.name.replace(".", "_"), ext)
|
|
970 dest = os.path.join(self.repdir, ofn)
|
|
971 src = os.path.join(self.tooloutdir, entry.name)
|
|
972 shutil.copyfile(src, dest)
|
|
973 with os.scandir(self.testdir) as outs:
|
|
974 for entry in outs:
|
|
975 if (
|
|
976 (not entry.is_file())
|
|
977 or entry.name.endswith("_sample")
|
|
978 or entry.name.endswith("_planemo_test_report.html")
|
|
979 ):
|
|
980 continue
|
|
981 if "." in entry.name:
|
|
982 nayme, ext = os.path.splitext(entry.name)
|
|
983 else:
|
|
984 ext = ".txt"
|
|
985 newname = f"{entry.name}{ext}"
|
|
986 dest = os.path.join(self.repdir, newname)
|
|
987 src = os.path.join(self.testdir, entry.name)
|
|
988 shutil.copyfile(src, dest)
|
|
989
|
|
990
|
|
991 def main():
|
|
992 """
|
|
993 This is a Galaxy wrapper. It expects to be called by a special purpose tool.xml
|
|
994
|
|
995 """
|
|
996 parser = argparse.ArgumentParser()
|
|
997 a = parser.add_argument
|
|
998 a("--script_path", default=None)
|
|
999 a("--history_test", default=None)
|
|
1000 a("--cl_prefix", default=None)
|
|
1001 a("--sysexe", default=None)
|
|
1002 a("--packages", default=None)
|
|
1003 a("--tool_name", default="newtool")
|
|
1004 a("--tool_dir", default=None)
|
|
1005 a("--input_files", default=[], action="append")
|
|
1006 a("--output_files", default=[], action="append")
|
|
1007 a("--user_email", default="Unknown")
|
|
1008 a("--bad_user", default=None)
|
|
1009 a("--make_Tool", default="runonly")
|
|
1010 a("--help_text", default=None)
|
|
1011 a("--tool_desc", default=None)
|
|
1012 a("--tool_version", default=None)
|
|
1013 a("--citations", default=None)
|
|
1014 a("--command_override", default=None)
|
|
1015 a("--test_override", default=None)
|
|
1016 a("--additional_parameters", action="append", default=[])
|
|
1017 a("--edit_additional_parameters", action="store_true", default=False)
|
|
1018 a("--parampass", default="positional")
|
|
1019 a("--tfout", default="./tfout")
|
|
1020 a("--new_tool", default="new_tool")
|
|
1021 a("--galaxy_url", default="http://localhost:8080")
|
|
1022 a("--toolshed_url", default="http://localhost:9009")
|
|
1023 # make sure this is identical to tool_sheds_conf.xml localhost != 127.0.0.1 so validation fails
|
|
1024 a("--toolshed_api_key", default="fakekey")
|
|
1025 a("--galaxy_api_key", default="fakekey")
|
|
1026 a("--galaxy_root", default="/galaxy-central")
|
|
1027 a("--galaxy_venv", default="/galaxy_venv")
|
|
1028 args = parser.parse_args()
|
|
1029 assert not args.bad_user, (
|
|
1030 'UNAUTHORISED: %s is NOT authorized to use this tool until Galaxy admin adds %s to "admin_users" in the galaxy.yml Galaxy configuration file'
|
|
1031 % (args.bad_user, args.bad_user)
|
|
1032 )
|
|
1033 assert args.tool_name, "## Tool Factory expects a tool name - eg --tool_name=DESeq"
|
|
1034 assert (
|
|
1035 args.sysexe or args.packages
|
|
1036 ), "## Tool Factory wrapper expects an interpreter or an executable package"
|
|
1037 args.input_files = [x.replace('"', "").replace("'", "") for x in args.input_files]
|
|
1038 # remove quotes we need to deal with spaces in CL params
|
|
1039 for i, x in enumerate(args.additional_parameters):
|
|
1040 args.additional_parameters[i] = args.additional_parameters[i].replace('"', "")
|
|
1041 r = ScriptRunner(args)
|
|
1042 r.writeShedyml()
|
|
1043 r.makeTool()
|
|
1044 if args.make_Tool == "generate":
|
|
1045 retcode = r.run() # for testing toolfactory itself
|
|
1046 r.moveRunOutputs()
|
|
1047 r.makeToolTar()
|
|
1048 else:
|
|
1049 r.planemo_biodocker_test() # test to make outputs and then test
|
|
1050 r.moveRunOutputs()
|
|
1051 r.makeToolTar()
|
|
1052 if args.make_Tool == "gentestinstall":
|
|
1053 r.shedLoad()
|
|
1054 r.eph_galaxy_load()
|
|
1055
|
|
1056
|
|
1057 if __name__ == "__main__":
|
|
1058 main()
|