comparison DockerToolFactory.py @ 0:0fa46413d0d9 draft

planemo upload for repository https://bitbucket.org/mvdbeek/dockertoolfactory/ commit 2f33eb59c06ac3d6ba6e22622fd4ae729eb5e4da-dirty
author mvdbeek
date Sat, 03 Oct 2015 08:34:39 -0400
parents
children fccbc118bb5b
comparison
equal deleted inserted replaced
-1:000000000000 0:0fa46413d0d9
1 # DockerToolFactory.py
2 # see https://bitbucket.org/mvdbeek/DockerToolFactory
3
4 import sys
5 import shutil
6 import subprocess
7 import os
8 import time
9 import tempfile
10 import argparse
11 import tarfile
12 import re
13 import shutil
14 import math
15 import fileinput
16 from os.path import abspath
17
18 progname = os.path.split(sys.argv[0])[1]
19 myversion = 'V001.1 March 2014'
20 verbose = False
21 debug = False
22 toolFactoryURL = 'https://bitbucket.org/fubar/galaxytoolfactory'
23
24 # if we do html we need these dependencies specified in a tool_dependencies.xml file and referred to in the generated
25 # tool xml
26 toolhtmldepskel = """<?xml version="1.0"?>
27 <tool_dependency>
28 <package name="ghostscript" version="9.10">
29 <repository name="package_ghostscript_9_10" owner="devteam"/>
30 </package>
31 <package name="graphicsmagick" version="1.3.20">
32 <repository name="package_graphicsmagick_1_3_20" owner="iuc"/>
33 </package>
34 <package name="docker-py" version="0.4.0">
35 <install version="1.0">
36 <actions>
37 <action type="setup_virtualenv">docker-py==0.4.0
38 </action>
39 </actions>
40 </install>
41 </package>
42 <readme>
43 %s
44 </readme>
45 </tool_dependency>
46 """
47
48 protorequirements = """<requirements>
49 <requirement type="package" version="9.10">ghostscript</requirement>
50 <requirement type="package" version="1.3.20">graphicsmagick</requirement>
51 <container type="docker">toolfactory/custombuild:%s</container>
52 </requirements>"""
53
54
55 def timenow():
56 """return current time as a string
57 """
58 return time.strftime('%d/%m/%Y %H:%M:%S', time.localtime(time.time()))
59
60
61 html_escape_table = {
62 "&": "&amp;",
63 ">": "&gt;",
64 "<": "&lt;",
65 "$": "\$"
66 }
67
68
69 def html_escape(text):
70 """Produce entities within text."""
71 return "".join(html_escape_table.get(c, c) for c in text)
72
73
74 def cmd_exists(cmd):
75 return subprocess.call("type " + cmd, shell=True,
76 stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
77
78
79 def edit_dockerfile(dockerfile):
80 '''we have to change the userid of galaxy inside the container to the id with which the tool is run,
81 otherwise we have a mismatch in the file permissions inside the container'''
82 uid = os.getuid()
83 for line in fileinput.FileInput(dockerfile, inplace=1):
84 sys.stdout.write(re.sub("RUN adduser galaxy.*", "RUN adduser galaxy -u {0}\n".format(uid), line))
85
86
87 # TODO: try to download image it it exists.
88 def build_docker(dockerfile, docker_client, image_tag='base'):
89 '''Given the path to a dockerfile, and a docker_client, try to build the image, if it does not
90 exist yet.'''
91 image_id = 'toolfactory/custombuild:' + image_tag
92 existing_images = ", ".join(["".join(d['RepoTags']) for d in docker_client.images()])
93 if image_id in existing_images:
94 print 'docker container exists, skipping build'
95 return image_id
96 print "Building Docker image, using Dockerfile:{0}".format(dockerfile)
97 build_process = docker_client.build(fileobj=open(dockerfile, 'r'), tag=image_id)
98 print "succesfully dispatched docker build process, building now"
99 build_log = [line for line in build_process] # will block until image is built.
100 return image_id
101
102
103 def construct_bind(host_path, container_path=False, binds=None, ro=True):
104 # TODO remove container_path if it's alwyas going to be the same as host_path
105 '''build or extend binds dictionary with container path. binds is used
106 to mount all files using the docker-py client.'''
107 if not binds:
108 binds = {}
109 if isinstance(host_path, list):
110 for k, v in enumerate(host_path):
111 if not container_path:
112 container_path = host_path[k]
113 binds[host_path[k]] = {'bind': container_path, 'ro': ro}
114 container_path = False # could be more elegant
115 return binds
116 else:
117 if not container_path:
118 container_path = host_path
119 binds[host_path] = {'bind': container_path, 'ro': ro}
120 return binds
121
122
123 def exists_boot2docker():
124 '''
125 Try to see if boot2docker command is available.
126 If it is, run boot2docker shellinit
127 '''
128 return cmd_exists('boot2docker')
129
130
131 def boot2docker_shellinit():
132 '''
133 '''
134 cmd = "eval \"\$(boot2docker shellinit)\""
135 subprocess.call(cmd, shell=True)
136
137
138 def switch_to_docker(opts):
139 import docker # need local import, as container does not have docker-py
140 if exists_boot2docker():
141 boot2docker_shellinit()
142 from docker.utils import kwargs_from_env
143 kwargs = kwargs_from_env()
144 kwargs['tls'].assert_hostname = False
145 docker_client = docker.Client(**kwargs)
146 else:
147 docker_client = docker.Client()
148 toolfactory_path = abspath(sys.argv[0])
149 dockerfile = os.path.dirname(toolfactory_path) + '/Dockerfile'
150 edit_dockerfile(dockerfile)
151 image_id = build_docker(dockerfile, docker_client)
152 binds = construct_bind(host_path=opts.script_path, ro=False)
153 binds = construct_bind(binds=binds, host_path=abspath(opts.output_dir), ro=False)
154 if len(opts.input_tab) > 0:
155 binds = construct_bind(binds=binds, host_path=opts.input_tab, ro=True)
156 if not opts.output_tab == 'None':
157 binds = construct_bind(binds=binds, host_path=opts.output_tab, ro=False)
158 if opts.make_HTML:
159 binds = construct_bind(binds=binds, host_path=opts.output_html, ro=False)
160 if opts.make_Tool:
161 binds = construct_bind(binds=binds, host_path=opts.new_tool, ro=False)
162 binds = construct_bind(binds=binds, host_path=opts.help_text, ro=True)
163 binds = construct_bind(binds=binds, host_path=toolfactory_path)
164 volumes = binds.keys()
165 sys.argv = [abspath(opts.output_dir) if sys.argv[i - 1] == '--output_dir' else arg for i, arg in
166 enumerate(sys.argv)] ##inject absolute path of working_dir
167 cmd = ['python', '-u'] + sys.argv + ['--dockerized', '1']
168 container = docker_client.create_container(
169 image=image_id,
170 user=os.getuid(),
171 volumes=volumes,
172 command=cmd
173 )
174 docker_client.start(container=container[u'Id'], binds=binds)
175 docker_client.wait(container=container[u'Id'])
176 logs = docker_client.logs(container=container[u'Id'])
177 print "".join([log for log in logs])
178
179
180 class ScriptRunner:
181 """class is a wrapper for an arbitrary script
182 """
183
184 def __init__(self, opts=None, treatbashSpecial=True, image_tag='base'):
185 """
186 cleanup inputs, setup some outputs
187
188 """
189 self.opts = opts
190 self.useGM = cmd_exists('gm')
191 self.useIM = cmd_exists('convert')
192 self.useGS = cmd_exists('gs')
193 self.temp_warned = False # we want only one warning if $TMP not set
194 self.treatbashSpecial = treatbashSpecial
195 self.image_tag = image_tag
196 os.chdir(abspath(opts.output_dir))
197 self.thumbformat = 'png'
198 self.toolname_sanitized = re.sub('[^a-zA-Z0-9_]+', '_', opts.tool_name) # a sanitizer now does this but..
199 self.toolname = opts.tool_name
200 self.toolid = self.toolname
201 self.myname = sys.argv[0] # get our name because we write ourselves out as a tool later
202 self.pyfile = self.myname # crude but efficient - the cruft won't hurt much
203 self.xmlfile = '%s.xml' % self.toolname_sanitized
204 s = open(self.opts.script_path, 'r').readlines()
205 s = [x.rstrip() for x in s] # remove pesky dos line endings if needed
206 self.script = '\n'.join(s)
207 fhandle, self.sfile = tempfile.mkstemp(prefix=self.toolname_sanitized, suffix=".%s" % (opts.interpreter))
208 tscript = open(self.sfile, 'w') # use self.sfile as script source for Popen
209 tscript.write(self.script)
210 tscript.close()
211 self.indentedScript = '\n'.join([' %s' % html_escape(x) for x in s]) # for restructured text in help
212 self.escapedScript = '\n'.join([html_escape(x) for x in s])
213 self.elog = os.path.join(self.opts.output_dir, "%s_error.log" % self.toolname_sanitized)
214 if opts.output_dir: # may not want these complexities
215 self.tlog = os.path.join(self.opts.output_dir, "%s_runner.log" % self.toolname_sanitized)
216 art = '%s.%s' % (self.toolname_sanitized, opts.interpreter)
217 artpath = os.path.join(self.opts.output_dir, art) # need full path
218 artifact = open(artpath, 'w') # use self.sfile as script source for Popen
219 artifact.write(self.script)
220 artifact.close()
221 self.cl = []
222 self.html = []
223 a = self.cl.append
224 a(opts.interpreter)
225 if self.treatbashSpecial and opts.interpreter in ['bash', 'sh']:
226 a(self.sfile)
227 else:
228 a('-') # stdin
229 for input in opts.input_tab:
230 a(input)
231 if opts.output_tab == 'None': # If tool generates only HTML, set output name to toolname
232 a(str(self.toolname_sanitized) + '.out')
233 a(opts.output_tab)
234 for param in opts.additional_parameters:
235 param, value = param.split(',')
236 a('--' + param)
237 a(value)
238 # print self.cl
239 self.outFormats = opts.output_format
240 self.inputFormats = [formats for formats in opts.input_formats]
241 self.test1Input = '%s_test1_input.xls' % self.toolname_sanitized
242 self.test1Output = '%s_test1_output.xls' % self.toolname_sanitized
243 self.test1HTML = '%s_test1_output.html' % self.toolname_sanitized
244
245 def makeXML(self):
246 """
247 Create a Galaxy xml tool wrapper for the new script as a string to write out
248 fixme - use templating or something less fugly than this example of what we produce
249
250 <tool id="reverse" name="reverse" version="0.01">
251 <description>a tabular file</description>
252 <command interpreter="python">
253 reverse.py --script_path "$runMe" --interpreter "python"
254 --tool_name "reverse" --input_tab "$input1" --output_tab "$tab_file"
255 </command>
256 <inputs>
257 <param name="input1" type="data" format="tabular" label="Select a suitable input file from your history"/>
258
259 </inputs>
260 <outputs>
261 <data format=opts.output_format name="tab_file"/>
262
263 </outputs>
264 <help>
265
266 **What it Does**
267
268 Reverse the columns in a tabular file
269
270 </help>
271 <configfiles>
272 <configfile name="runMe">
273
274 # reverse order of columns in a tabular file
275 import sys
276 inp = sys.argv[1]
277 outp = sys.argv[2]
278 i = open(inp,'r')
279 o = open(outp,'w')
280 for row in i:
281 rs = row.rstrip().split('\t')
282 rs.reverse()
283 o.write('\t'.join(rs))
284 o.write('\n')
285 i.close()
286 o.close()
287
288
289 </configfile>
290 </configfiles>
291 </tool>
292
293 """
294 newXML = """<tool id="%(toolid)s" name="%(toolname)s" version="%(tool_version)s">
295 %(tooldesc)s
296 %(requirements)s
297 <command interpreter="python">
298 %(command)s
299 </command>
300 <inputs>
301 %(inputs)s
302 </inputs>
303 <outputs>
304 %(outputs)s
305 </outputs>
306 <configfiles>
307 <configfile name="runMe">
308 %(script)s
309 </configfile>
310 </configfiles>
311
312 %(tooltests)s
313
314 <help>
315
316 %(help)s
317
318 </help>
319 </tool>""" # needs a dict with toolname, toolname_sanitized, toolid, interpreter, scriptname, command, inputs as a multi line string ready to write, outputs ditto, help ditto
320
321 newCommand = """
322 %(toolname_sanitized)s.py --script_path "$runMe" --interpreter "%(interpreter)s"
323 --tool_name "%(toolname)s" %(command_inputs)s %(command_outputs)s """
324 # may NOT be an input or htmlout - appended later
325 tooltestsTabOnly = """
326 <tests>
327 <test>
328 <param name="input1" value="%(test1Input)s" ftype="tabular"/>
329 <param name="runMe" value="$runMe"/>
330 <output name="tab_file" file="%(test1Output)s" ftype="tabular"/>
331 </test>
332 </tests>
333 """
334 tooltestsHTMLOnly = """
335 <tests>
336 <test>
337 <param name="input1" value="%(test1Input)s" ftype="tabular"/>
338 <param name="runMe" value="$runMe"/>
339 <output name="html_file" file="%(test1HTML)s" ftype="html" lines_diff="5"/>
340 </test>
341 </tests>
342 """
343 tooltestsBoth = """<tests>
344 <test>
345 <param name="input1" value="%(test1Input)s" ftype="tabular"/>
346 <param name="runMe" value="$runMe"/>
347 <output name="tab_file" file="%(test1Output)s" ftype="tabular" />
348 <output name="html_file" file="%(test1HTML)s" ftype="html" lines_diff="10"/>
349 </test>
350 </tests>
351 """
352 xdict = {}
353 # xdict['requirements'] = ''
354 # if self.opts.make_HTML:
355 xdict['requirements'] = protorequirements % self.image_tag
356 xdict['tool_version'] = self.opts.tool_version
357 xdict['test1Input'] = self.test1Input
358 xdict['test1HTML'] = self.test1HTML
359 xdict['test1Output'] = self.test1Output
360 if self.opts.make_HTML and self.opts.output_tab <> 'None':
361 xdict['tooltests'] = tooltestsBoth % xdict
362 elif self.opts.make_HTML:
363 xdict['tooltests'] = tooltestsHTMLOnly % xdict
364 else:
365 xdict['tooltests'] = tooltestsTabOnly % xdict
366 xdict['script'] = self.escapedScript
367 # configfile is least painful way to embed script to avoid external dependencies
368 # but requires escaping of <, > and $ to avoid Mako parsing
369 if self.opts.help_text:
370 helptext = open(self.opts.help_text, 'r').readlines()
371 helptext = [html_escape(x) for x in helptext] # must html escape here too - thanks to Marius van den Beek
372 xdict['help'] = ''.join([x for x in helptext])
373 else:
374 xdict['help'] = 'Please ask the tool author (%s) for help as none was supplied at tool generation\n' % (
375 self.opts.user_email)
376 coda = ['**Script**',
377 'Pressing execute will run the following code over your input file and generate some outputs in your history::']
378 coda.append('\n')
379 coda.append(self.indentedScript)
380 coda.append('\n**Attribution**\nThis Galaxy tool was created by %s at %s\nusing the Galaxy Tool Factory.\n' % (
381 self.opts.user_email, timenow()))
382 coda.append('See %s for details of that project' % (toolFactoryURL))
383 coda.append(
384 'Please cite: Creating re-usable tools from scripts: The Galaxy Tool Factory. Ross Lazarus; Antony Kaspi; Mark Ziemann; The Galaxy Team. ')
385 coda.append('Bioinformatics 2012; doi: 10.1093/bioinformatics/bts573\n')
386 xdict['help'] = '%s\n%s' % (xdict['help'], '\n'.join(coda))
387 if self.opts.tool_desc:
388 xdict['tooldesc'] = '<description>%s</description>' % self.opts.tool_desc
389 else:
390 xdict['tooldesc'] = ''
391 xdict['command_outputs'] = ''
392 xdict['outputs'] = ''
393 if self.opts.input_tab <> 'None':
394 xdict['command_inputs'] = '--input_tab'
395 xdict['inputs'] = ''
396 for i, input in enumerate(self.inputFormats):
397 xdict[
398 'inputs'] += '<param name="input{0}" type="data" format="{1}" label="Select a suitable input file from your history"/> \n'.format(
399 i + 1, input)
400 xdict['command_inputs'] += ' $input{0}'.format(i + 1)
401 else:
402 xdict['command_inputs'] = '' # assume no input - eg a random data generator
403 xdict['inputs'] = ''
404 # I find setting the job name not very logical. can be changed in workflows anyway. xdict['inputs'] += '<param name="job_name" type="text" label="Supply a name for the outputs to remind you what they contain" value="%s"/> \n' % self.toolname
405 xdict['toolname'] = self.toolname
406 xdict['toolname_sanitized'] = self.toolname_sanitized
407 xdict['toolid'] = self.toolid
408 xdict['interpreter'] = self.opts.interpreter
409 xdict['scriptname'] = self.sfile
410 if self.opts.make_HTML:
411 xdict[
412 'command_outputs'] += ' --output_dir "$html_file.files_path" --output_html "$html_file" --make_HTML "yes"'
413 xdict['outputs'] += ' <data format="html" name="html_file"/>\n'
414 else:
415 xdict['command_outputs'] += ' --output_dir "./"'
416 # print self.opts.output_tab
417 if self.opts.output_tab != "None":
418 xdict['command_outputs'] += ' --output_tab "$tab_file"'
419 xdict['outputs'] += ' <data format="%s" name="tab_file"/>\n' % self.outFormats
420 xdict['command'] = newCommand % xdict
421 # print xdict['outputs']
422 xmls = newXML % xdict
423 xf = open(self.xmlfile, 'w')
424 xf.write(xmls)
425 xf.write('\n')
426 xf.close()
427 # ready for the tarball
428
429 def makeTooltar(self):
430 """
431 a tool is a gz tarball with eg
432 /toolname_sanitized/tool.xml /toolname_sanitized/tool.py /toolname_sanitized/test-data/test1_in.foo ...
433 """
434 retval = self.run()
435 if retval:
436 print >> sys.stderr, '## Run failed. Cannot build yet. Please fix and retry'
437 sys.exit(1)
438 tdir = self.toolname_sanitized
439 os.mkdir(tdir)
440 self.makeXML()
441 if self.opts.make_HTML:
442 if self.opts.help_text:
443 hlp = open(self.opts.help_text, 'r').read()
444 else:
445 hlp = 'Please ask the tool author for help as none was supplied at tool generation\n'
446 if self.opts.include_dependencies:
447 tooldepcontent = toolhtmldepskel % hlp
448 depf = open(os.path.join(tdir, 'tool_dependencies.xml'), 'w')
449 depf.write(tooldepcontent)
450 depf.write('\n')
451 depf.close()
452 if self.opts.input_tab <> 'None': # no reproducible test otherwise? TODO: maybe..
453 testdir = os.path.join(tdir, 'test-data')
454 os.mkdir(testdir) # make tests directory
455 for i in self.opts.input_tab:
456 # print i
457 shutil.copyfile(i, os.path.join(testdir, self.test1Input))
458 if not self.opts.output_tab:
459 shutil.copyfile(self.opts.output_tab, os.path.join(testdir, self.test1Output))
460 if self.opts.make_HTML:
461 shutil.copyfile(self.opts.output_html, os.path.join(testdir, self.test1HTML))
462 if self.opts.output_dir:
463 shutil.copyfile(self.tlog, os.path.join(testdir, 'test1_out.log'))
464 outpif = '%s.py' % self.toolname_sanitized # new name
465 outpiname = os.path.join(tdir, outpif) # path for the tool tarball
466 pyin = os.path.basename(self.pyfile) # our name - we rewrite ourselves (TM)
467 notes = ['# %s - a self annotated version of %s generated by running %s\n' % (outpiname, pyin, pyin), ]
468 notes.append('# to make a new Galaxy tool called %s\n' % self.toolname)
469 notes.append('# User %s at %s\n' % (self.opts.user_email, timenow()))
470 pi = [line.replace('if opts.dockerized==0:', 'if False:') for line in
471 open(self.pyfile)] # do not run docker in the generated tool
472 notes += pi
473 outpi = open(outpiname, 'w')
474 outpi.write(''.join(notes))
475 outpi.write('\n')
476 outpi.close()
477 stname = os.path.join(tdir, self.sfile)
478 if not os.path.exists(stname):
479 shutil.copyfile(self.sfile, stname)
480 xtname = os.path.join(tdir, self.xmlfile)
481 if not os.path.exists(xtname):
482 shutil.copyfile(self.xmlfile, xtname)
483 tarpath = "%s.gz" % self.toolname_sanitized
484 tar = tarfile.open(tarpath, "w:gz")
485 tar.add(tdir, arcname=self.toolname_sanitized)
486 tar.close()
487 shutil.copyfile(tarpath, self.opts.new_tool)
488 shutil.rmtree(tdir)
489 ## TODO: replace with optional direct upload to local toolshed?
490 return retval
491
492 def compressPDF(self, inpdf=None, thumbformat='png'):
493 """need absolute path to pdf
494 note that GS gets confoozled if no $TMP or $TEMP
495 so we set it
496 """
497 assert os.path.isfile(inpdf), "## Input %s supplied to %s compressPDF not found" % (inpdf, self.myName)
498 hlog = os.path.join(self.opts.output_dir, "compress_%s.txt" % os.path.basename(inpdf))
499 sto = open(hlog, 'a')
500 our_env = os.environ.copy()
501 our_tmp = our_env.get('TMP', None)
502 if not our_tmp:
503 our_tmp = our_env.get('TEMP', None)
504 if not (our_tmp and os.path.exists(our_tmp)):
505 newtmp = os.path.join(self.opts.output_dir, 'tmp')
506 try:
507 os.mkdir(newtmp)
508 except:
509 sto.write('## WARNING - cannot make %s - it may exist or permissions need fixing\n' % newtmp)
510 our_env['TEMP'] = newtmp
511 if not self.temp_warned:
512 sto.write('## WARNING - no $TMP or $TEMP!!! Please fix - using %s temporarily\n' % newtmp)
513 self.temp_warned = True
514 outpdf = '%s_compressed' % inpdf
515 cl = ["gs", "-sDEVICE=pdfwrite", "-dNOPAUSE", "-dUseCIEColor", "-dBATCH", "-dPDFSETTINGS=/printer",
516 "-sOutputFile=%s" % outpdf, inpdf]
517 x = subprocess.Popen(cl, stdout=sto, stderr=sto, cwd=self.opts.output_dir, env=our_env)
518 retval1 = x.wait()
519 sto.close()
520 if retval1 == 0:
521 os.unlink(inpdf)
522 shutil.move(outpdf, inpdf)
523 os.unlink(hlog)
524 hlog = os.path.join(self.opts.output_dir, "thumbnail_%s.txt" % os.path.basename(inpdf))
525 sto = open(hlog, 'w')
526 outpng = '%s.%s' % (os.path.splitext(inpdf)[0], thumbformat)
527 if self.useGM:
528 cl2 = ['gm', 'convert', inpdf, outpng]
529 else: # assume imagemagick
530 cl2 = ['convert', inpdf, outpng]
531 x = subprocess.Popen(cl2, stdout=sto, stderr=sto, cwd=self.opts.output_dir, env=our_env)
532 retval2 = x.wait()
533 sto.close()
534 if retval2 == 0:
535 os.unlink(hlog)
536 retval = retval1 or retval2
537 return retval
538
539 def getfSize(self, fpath, outpath):
540 """
541 format a nice file size string
542 """
543 size = ''
544 fp = os.path.join(outpath, fpath)
545 if os.path.isfile(fp):
546 size = '0 B'
547 n = float(os.path.getsize(fp))
548 if n > 2 ** 20:
549 size = '%1.1f MB' % (n / 2 ** 20)
550 elif n > 2 ** 10:
551 size = '%1.1f KB' % (n / 2 ** 10)
552 elif n > 0:
553 size = '%d B' % (int(n))
554 return size
555
556 def makeHtml(self):
557 """ Create an HTML file content to list all the artifacts found in the output_dir
558 """
559
560 galhtmlprefix = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
561 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
562 <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
563 <meta name="generator" content="Galaxy %s tool output - see http://g2.trac.bx.psu.edu/" />
564 <title></title>
565 <link rel="stylesheet" href="/static/style/base.css" type="text/css" />
566 </head>
567 <body>
568 <div class="toolFormBody">
569 """
570 galhtmlattr = """<hr/><div class="infomessage">This tool (%s) was generated by the <a href="https://bitbucket.org/fubar/galaxytoolfactory/overview">Galaxy Tool Factory</a></div><br/>"""
571 galhtmlpostfix = """</div></body></html>\n"""
572
573 flist = os.listdir(self.opts.output_dir)
574 flist = [x for x in flist if x <> 'Rplots.pdf']
575 flist.sort()
576 html = []
577 html.append(galhtmlprefix % progname)
578 html.append('<div class="infomessage">Galaxy Tool "%s" run at %s</div><br/>' % (self.toolname, timenow()))
579 fhtml = []
580 if len(flist) > 0:
581 logfiles = [x for x in flist if x.lower().endswith('.log')] # log file names determine sections
582 logfiles.sort()
583 logfiles = [x for x in logfiles if abspath(x) <> abspath(self.tlog)]
584 logfiles.append(abspath(self.tlog)) # make it the last one
585 pdflist = []
586 npdf = len([x for x in flist if os.path.splitext(x)[-1].lower() == '.pdf'])
587 for rownum, fname in enumerate(flist):
588 dname, e = os.path.splitext(fname)
589 sfsize = self.getfSize(fname, self.opts.output_dir)
590 if e.lower() == '.pdf': # compress and make a thumbnail
591 thumb = '%s.%s' % (dname, self.thumbformat)
592 pdff = os.path.join(self.opts.output_dir, fname)
593 retval = self.compressPDF(inpdf=pdff, thumbformat=self.thumbformat)
594 if retval == 0:
595 pdflist.append((fname, thumb))
596 else:
597 pdflist.append((fname, fname))
598 if (rownum + 1) % 2 == 0:
599 fhtml.append(
600 '<tr class="odd_row"><td><a href="%s">%s</a></td><td>%s</td></tr>' % (fname, fname, sfsize))
601 else:
602 fhtml.append('<tr><td><a href="%s">%s</a></td><td>%s</td></tr>' % (fname, fname, sfsize))
603 for logfname in logfiles: # expect at least tlog - if more
604 if abspath(logfname) == abspath(self.tlog): # handled later
605 sectionname = 'All tool run'
606 if (len(logfiles) > 1):
607 sectionname = 'Other'
608 ourpdfs = pdflist
609 else:
610 realname = os.path.basename(logfname)
611 sectionname = os.path.splitext(realname)[0].split('_')[0] # break in case _ added to log
612 ourpdfs = [x for x in pdflist if os.path.basename(x[0]).split('_')[0] == sectionname]
613 pdflist = [x for x in pdflist if os.path.basename(x[0]).split('_')[0] <> sectionname] # remove
614 nacross = 1
615 npdf = len(ourpdfs)
616
617 if npdf > 0:
618 nacross = math.sqrt(npdf) ## int(round(math.log(npdf,2)))
619 if int(nacross) ** 2 != npdf:
620 nacross += 1
621 nacross = int(nacross)
622 width = min(400, int(1200 / nacross))
623 html.append('<div class="toolFormTitle">%s images and outputs</div>' % sectionname)
624 html.append('(Click on a thumbnail image to download the corresponding original PDF image)<br/>')
625 ntogo = nacross # counter for table row padding with empty cells
626 html.append('<div><table class="simple" cellpadding="2" cellspacing="2">\n<tr>')
627 for i, paths in enumerate(ourpdfs):
628 fname, thumb = paths
629 s = """<td><a href="%s"><img src="%s" title="Click to download a PDF of %s" hspace="5" width="%d"
630 alt="Image called %s"/></a></td>\n""" % (fname, thumb, fname, width, fname)
631 if ((i + 1) % nacross == 0):
632 s += '</tr>\n'
633 ntogo = 0
634 if i < (npdf - 1): # more to come
635 s += '<tr>'
636 ntogo = nacross
637 else:
638 ntogo -= 1
639 html.append(s)
640 if html[-1].strip().endswith('</tr>'):
641 html.append('</table></div>\n')
642 else:
643 if ntogo > 0: # pad
644 html.append('<td>&nbsp;</td>' * ntogo)
645 html.append('</tr></table></div>\n')
646 logt = open(logfname, 'r').readlines()
647 logtext = [x for x in logt if x.strip() > '']
648 html.append('<div class="toolFormTitle">%s log output</div>' % sectionname)
649 if len(logtext) > 1:
650 html.append('\n<pre>\n')
651 html += logtext
652 html.append('\n</pre>\n')
653 else:
654 html.append('%s is empty<br/>' % logfname)
655 if len(fhtml) > 0:
656 fhtml.insert(0,
657 '<div><table class="colored" cellpadding="3" cellspacing="3"><tr><th>Output File Name (click to view)</th><th>Size</th></tr>\n')
658 fhtml.append('</table></div><br/>')
659 html.append('<div class="toolFormTitle">All output files available for downloading</div>\n')
660 html += fhtml # add all non-pdf files to the end of the display
661 else:
662 html.append(
663 '<div class="warningmessagelarge">### Error - %s returned no files - please confirm that parameters are sane</div>' % self.opts.interpreter)
664 html.append(galhtmlpostfix)
665 htmlf = file(self.opts.output_html, 'w')
666 htmlf.write('\n'.join(html))
667 htmlf.write('\n')
668 htmlf.close()
669 self.html = html
670
671 def run(self):
672 """
673 scripts must be small enough not to fill the pipe!
674 """
675 if self.treatbashSpecial and self.opts.interpreter in ['bash', 'sh']:
676 retval = self.runBash()
677 else:
678 if self.opts.output_dir:
679 ste = open(self.elog, 'w')
680 sto = open(self.tlog, 'w')
681 sto.write('## Toolfactory generated command line = %s\n' % ' '.join(self.cl))
682 sto.flush()
683 p = subprocess.Popen(self.cl, shell=False, stdout=sto, stderr=ste, stdin=subprocess.PIPE,
684 cwd=self.opts.output_dir)
685 else:
686 p = subprocess.Popen(self.cl, shell=False, stdin=subprocess.PIPE)
687 p.stdin.write(self.script)
688 p.stdin.close()
689 retval = p.wait()
690 if self.opts.output_dir:
691 sto.close()
692 ste.close()
693 err = open(self.elog, 'r').readlines()
694 if retval <> 0 and err: # problem
695 print >> sys.stderr, err # same problem, need to capture docker stdin/stdout
696 if self.opts.make_HTML:
697 self.makeHtml()
698 return retval
699
700 def runBash(self):
701 """
702 cannot use - for bash so use self.sfile
703 """
704 if self.opts.output_dir:
705 s = '## Toolfactory generated command line = %s\n' % ' '.join(self.cl)
706 sto = open(self.tlog, 'w')
707 sto.write(s)
708 sto.flush()
709 p = subprocess.Popen(self.cl, shell=False, stdout=sto, stderr=sto, cwd=self.opts.output_dir)
710 else:
711 p = subprocess.Popen(self.cl, shell=False)
712 retval = p.wait()
713 if self.opts.output_dir:
714 sto.close()
715 if self.opts.make_HTML:
716 self.makeHtml()
717 return retval
718
719
720 def main():
721 u = """
722 This is a Galaxy wrapper. It expects to be called by a special purpose tool.xml as:
723 <command interpreter="python">rgBaseScriptWrapper.py --script_path "$scriptPath" --tool_name "foo" --interpreter "Rscript"
724 </command>
725 """
726 op = argparse.ArgumentParser()
727 a = op.add_argument
728 a('--script_path', default=None)
729 a('--tool_name', default=None)
730 a('--interpreter', default=None)
731 a('--output_dir', default='./')
732 a('--output_html', default=None)
733 a('--input_tab', default='None', nargs='*')
734 a('--output_tab', default='None')
735 a('--user_email', default='Unknown')
736 a('--bad_user', default=None)
737 a('--make_Tool', default=None)
738 a('--make_HTML', default=None)
739 a('--help_text', default=None)
740 a('--tool_desc', default=None)
741 a('--new_tool', default=None)
742 a('--tool_version', default=None)
743 a('--include_dependencies', default=None)
744 a('--dockerized', default=0)
745 a('--output_format', default='tabular')
746 a('--input_format', dest='input_formats', action='append', default=[])
747 a('--additional_parameters', dest='additional_parameters', action='append', default=[])
748 opts = op.parse_args()
749 assert not opts.bad_user, 'UNAUTHORISED: %s is NOT authorized to use this tool until Galaxy admin adds %s to admin_users in universe_wsgi.ini' % (
750 opts.bad_user, opts.bad_user)
751 assert opts.tool_name, '## Tool Factory expects a tool name - eg --tool_name=DESeq'
752 assert opts.interpreter, '## Tool Factory wrapper expects an interpreter - eg --interpreter=Rscript'
753 assert os.path.isfile(opts.script_path), '## Tool Factory wrapper expects a script path - eg --script_path=foo.R'
754 if opts.output_dir:
755 try:
756 os.makedirs(opts.output_dir)
757 except:
758 pass
759 if opts.dockerized == 0:
760 switch_to_docker(opts)
761 return
762 r = ScriptRunner(opts)
763 if opts.make_Tool:
764 retcode = r.makeTooltar()
765 else:
766 retcode = r.run()
767 os.unlink(r.sfile)
768 if retcode:
769 sys.exit(retcode) # indicate failure to job runner
770
771
772 if __name__ == "__main__":
773 main()