Merge branch 'master' into 3373-improve-gatk3-snv-pipeline
authorPeter Amstutz <peter.amstutz@curoverse.com>
Wed, 6 Aug 2014 14:32:01 +0000 (10:32 -0400)
committerPeter Amstutz <peter.amstutz@curoverse.com>
Wed, 6 Aug 2014 14:32:01 +0000 (10:32 -0400)
crunch_scripts/collection-merge
crunch_scripts/decompress-all.py [new file with mode: 0755]
crunch_scripts/run-command
crunch_scripts/split-fastq.py [new file with mode: 0755]
crunch_scripts/subst.py
docker/jobs/Dockerfile
sdk/cli/bin/arv-run-pipeline-instance

index f16d62466a1e1853b56266ed58ef9935fd3f974b..63b63fa95152375946a50ed4d4e1fd482e380c7a 100755 (executable)
@@ -1,5 +1,18 @@
 #!/usr/bin/env python
 
+# collection-merge
+#
+# Merge two or more collections together.  Can also be used to extract specific
+# files from a collection to produce a new collection.
+#
+# input:
+# An array of collections or collection/file paths in script_parameter["input"]
+#
+# output:
+# A manifest with the collections merged.  Duplicate file names will
+# have their contents concatenated in the order that they appear in the input
+# array.
+
 import arvados
 import md5
 import subst
@@ -30,28 +43,4 @@ for c in p["input"]:
                 if fn in s.files():
                     merged += s.files()[fn].as_manifest()
 
-crm = arvados.CollectionReader(merged)
-
-combined = crm.manifest_text(strip=True)
-
-m = hashlib.new('md5')
-m.update(combined)
-
-uuid = "{}+{}".format(m.hexdigest(), len(combined))
-
-collection = arvados.api().collections().create(
-    body={
-        'uuid': uuid,
-        'manifest_text': crm.manifest_text(),
-    }).execute()
-
-for s in src:
-    l = arvados.api().links().create(body={
-        "link": {
-            "tail_uuid": s,
-            "head_uuid": uuid,
-            "link_class": "provenance",
-            "name": "provided"
-        }}).execute()
-
-arvados.current_task().set_output(uuid)
+arvados.current_task().set_output(merged)
diff --git a/crunch_scripts/decompress-all.py b/crunch_scripts/decompress-all.py
new file mode 100755 (executable)
index 0000000..8fa49f5
--- /dev/null
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+
+#
+# decompress-all.py
+#
+# Decompress all compressed files in the collection using the "dtrx" tool and
+# produce a new collection with the contents.  Uncompressed files
+# are passed through.
+#
+# input:
+# A collection at script_parameters["input"]
+#
+# output:
+# A manifest of the uncompressed contents of the input collection.
+
+import arvados
+import re
+import subprocess
+import os
+
+arvados.job_setup.one_task_per_input_file(if_sequence=0, and_end_task=True,
+                                          input_as_path=True)
+
+task = arvados.current_task()
+
+input_file = task['parameters']['input']
+
+result = re.match(r"(^[a-f0-9]{32}\+\d+)(\+\S+)*(/.*)(/[^/]+)$", input_file)
+
+outdir = os.path.join(task.tmpdir, "output")
+os.makedirs(outdir)
+os.chdir(outdir)
+
+if result != None:
+    cr = arvados.CollectionReader(result.group(1))
+    streamname = result.group(3)[1:]
+    filename = result.group(4)[1:]
+
+    subprocess.call(["mkdir", "-p", streamname])
+    os.chdir(streamname)
+    streamreader = filter(lambda s: s.name() == streamname, cr.all_streams())[0]
+    filereader = streamreader.files()[filename]
+    rc = subprocess.call(["dtrx", "-r", "-n", "-q", arvados.get_task_param_mount('input')])
+    if rc == 0:
+        out = arvados.CollectionWriter()
+        out.write_directory_tree(outdir, max_manifest_depth=0)
+        task.set_output(out.finish())
+    else:
+        task.set_output(streamname + filereader.as_manifest()[1:])
+else:
+    sys.exit(1)
index e6ec889bbcbdbd731b7e6930379b1957062b4178..d9f575ba25875ba5f86377c254ff5af757dc21a0 100755 (executable)
@@ -10,6 +10,11 @@ import subst
 import time
 import arvados.commands.put as put
 import signal
+import stat
+import copy
+import traceback
+import pprint
+import multiprocessing
 
 os.umask(0077)
 
@@ -23,28 +28,46 @@ os.mkdir("output")
 
 os.chdir("output")
 
+outdir = os.getcwd()
+
+taskp = None
+jobp = arvados.current_job()['script_parameters']
 if len(arvados.current_task()['parameters']) > 0:
     p = arvados.current_task()['parameters']
-else:
-    p = arvados.current_job()['script_parameters']
 
 links = []
 
 def sub_link(v):
-    r = os.path.basename(v)
-    os.symlink(os.path.join(os.environ['TASK_KEEPMOUNT'], v) , r)
+    r = os.path.join(outdir, os.path.basename(v))
+    os.symlink(v, r)
     links.append(r)
     return r
 
 def sub_tmpdir(v):
     return os.path.join(arvados.current_task().tmpdir, 'tmpdir')
 
+def sub_outdir(v):
+    return outdir
+
 def sub_cores(v):
-     return os.environ['CRUNCH_NODE_SLOTS']
+     return str(multiprocessing.cpu_count())
+
+def sub_jobid(v):
+     return os.environ['JOB_UUID']
+
+def sub_taskid(v):
+     return os.environ['TASK_UUID']
+
+def sub_jobsrc(v):
+     return os.environ['CRUNCH_SRC']
 
 subst.default_subs["link "] = sub_link
-subst.default_subs["tmpdir"] = sub_tmpdir
+subst.default_subs["task.tmpdir"] = sub_tmpdir
+subst.default_subs["task.outdir"] = sub_outdir
+subst.default_subs["job.srcdir"] = sub_jobsrc
 subst.default_subs["node.cores"] = sub_cores
+subst.default_subs["job.uuid"] = sub_jobid
+subst.default_subs["task.uuid"] = sub_taskid
 
 rcode = 1
 
@@ -60,19 +83,87 @@ class SigHandler(object):
         sp.send_signal(signum)
         self.sig = signum
 
+def expand_item(p, c):
+    if isinstance(c, dict):
+        if "foreach" in c and "command" in c:
+            var = c["foreach"]
+            items = get_items(p, p[var])
+            r = []
+            for i in items:
+                params = copy.copy(p)
+                params[var] = i
+                r.extend(expand_list(params, c["command"]))
+            return r
+    elif isinstance(c, list):
+        return expand_list(p, c)
+    elif isinstance(c, str) or isinstance(c, unicode):
+        return [subst.do_substitution(p, c)]
+
+    return []
+
+def expand_list(p, l):
+    return [exp for arg in l for exp in expand_item(p, arg)]
+
+def get_items(p, value):
+    if isinstance(value, list):
+        return expand_list(p, value)
+
+    fn = subst.do_substitution(p, value)
+    mode = os.stat(fn).st_mode
+    prefix = fn[len(os.environ['TASK_KEEPMOUNT'])+1:]
+    if mode != None:
+        if stat.S_ISDIR(mode):
+            items = ["$(dir %s/%s/)" % (prefix, l) for l in os.listdir(fn)]
+        elif stat.S_ISREG(mode):
+            with open(fn) as f:
+                items = [line for line in f]
+        return items
+    else:
+        return None
+
+stdoutname = None
+stdoutfile = None
+
 try:
-    cmd = []
-    for c in p["command"]:
-        cmd.append(subst.do_substitution(p, c))
-
-    stdoutname = None
-    stdoutfile = None
-    if "stdout" in p:
-        stdoutname = subst.do_substitution(p, p["stdout"])
+    if "task.foreach" in jobp:
+        if arvados.current_task()['sequence'] == 0:
+            var = jobp["task.foreach"]
+            items = get_items(jobp, jobp[var])
+            print("run-command: parallelizing on %s with items %s" % (var, items))
+            if items != None:
+                for i in items:
+                    params = copy.copy(jobp)
+                    params[var] = i
+                    arvados.api().job_tasks().create(body={
+                        'job_uuid': arvados.current_job()['uuid'],
+                        'created_by_job_task_uuid': arvados.current_task()['uuid'],
+                        'sequence': 1,
+                        'parameters': params
+                        }
+                    ).execute()
+                arvados.current_task().set_output(None)
+                sys.exit(0)
+            else:
+                sys.exit(1)
+    else:
+        p = jobp
+
+    cmd = expand_list(p, p["command"])
+
+    if "save.stdout" in p:
+        stdoutname = subst.do_substitution(p, p["save.stdout"])
         stdoutfile = open(stdoutname, "wb")
 
     print("run-command: {}{}".format(' '.join(cmd), (" > " + stdoutname) if stdoutname != None else ""))
 
+except Exception as e:
+    print("run-command: caught exception:")
+    traceback.print_exc(file=sys.stdout)
+    print("run-command: task parameters was:")
+    pprint.pprint(p)
+    sys.exit(1)
+
+try:
     sp = subprocess.Popen(cmd, shell=False, stdout=stdoutfile)
     sig = SigHandler()
 
@@ -91,7 +182,8 @@ try:
         print("run-command: completed with exit code %i (%s)" % (rcode, "success" if rcode == 0 else "failed"))
 
 except Exception as e:
-    print("run-command: caught exception: {}".format(e))
+    print("run-command: caught exception:")
+    traceback.print_exc(file=sys.stdout)
 
 # restore default signal handlers.
 signal.signal(signal.SIGINT, signal.SIG_DFL)
@@ -101,7 +193,7 @@ signal.signal(signal.SIGQUIT, signal.SIG_DFL)
 for l in links:
     os.unlink(l)
 
-print("run-command: the follow output files will be saved to keep:")
+print("run-command: the following output files will be saved to keep:")
 
 subprocess.call(["find", ".", "-type", "f", "-printf", "run-command: %12.12s %h/%f\\n"])
 
@@ -128,7 +220,8 @@ while not done:
         print("run-command: terminating on signal 2")
         sys.exit(2)
     except Exception as e:
-        print("run-command: caught exception: {}".format(e))
+        print("run-command: caught exception:")
+        traceback.print_exc(file=sys.stdout)
         time.sleep(5)
 
 sys.exit(rcode)
diff --git a/crunch_scripts/split-fastq.py b/crunch_scripts/split-fastq.py
new file mode 100755 (executable)
index 0000000..ece593d
--- /dev/null
@@ -0,0 +1,126 @@
+#!/usr/bin/python
+
+import arvados
+import re
+import hashlib
+import string
+
+api = arvados.api('v1')
+
+piece = 0
+manifest_text = ""
+
+# Look for paired reads
+
+inp = arvados.CollectionReader(arvados.getjobparam('reads'))
+
+prog = re.compile(r'(.*?)_1.fastq(.gz)?$')
+
+manifest_list = []
+
+chunking = False #arvados.getjobparam('chunking')
+
+def nextline(reader, start):
+    n = -1
+    while True:
+        r = reader.readfrom(start, 128)
+        if r == '':
+            break
+        n = string.find(r, "\n")
+        if n > -1:
+            break
+        else:
+            start += 128
+    return n
+
+def splitfastq(p):
+    for i in xrange(0, len(p)):
+        p[i]["start"] = 0
+        p[i]["end"] = 0
+
+    count = 0
+    recordsize = [0, 0]
+
+    global piece
+    finish = False
+    while not finish:
+        for i in xrange(0, len(p)):
+            recordsize[i] = 0
+
+        # read next 4 lines
+        for i in xrange(0, len(p)):
+            for ln in xrange(0, 4):
+                r = nextline(p[i]["reader"], p[i]["end"]+recordsize[i])
+                if r == -1:
+                    finish = True
+                    break
+                recordsize[i] += (r+1)
+
+        splitnow = finish
+        for i in xrange(0, len(p)):
+            if ((p[i]["end"] - p[i]["start"]) + recordsize[i]) >= (64*1024*1024):
+                splitnow = True
+
+        if splitnow:
+            for i in xrange(0, len(p)):
+                global manifest_list
+                print "Finish piece ./_%s/%s (%s %s)" % (piece, p[i]["reader"].name(), p[i]["start"], p[i]["end"])
+                manifest = []
+                manifest.extend(["./_" + str(piece)])
+                manifest.extend([d[arvados.LOCATOR] for d in p[i]["reader"]._stream._data_locators])
+
+                print p[i]
+                print arvados.locators_and_ranges(p[i]["reader"].segments, p[i]["start"], p[i]["end"] - p[i]["start"])
+
+                manifest.extend(["{}:{}:{}".format(seg[arvados.LOCATOR]+seg[arvados.OFFSET], seg[arvados.SEGMENTSIZE], p[i]["reader"].name().replace(' ', '\\040')) for seg in arvados.locators_and_ranges(p[i]["reader"].segments, p[i]["start"], p[i]["end"] - p[i]["start"])])
+                manifest_list.append(manifest)
+                print "Finish piece %s" % (" ".join(manifest))
+                p[i]["start"] = p[i]["end"]
+            piece += 1
+        else:
+            for i in xrange(0, len(p)):
+                p[i]["end"] += recordsize[i]
+            count += 1
+            if count % 10000 == 0:
+                print "Record %s at %s" % (count, p[i]["end"])
+
+for s in inp.all_streams():
+    if s.name() == ".":
+        for f in s.all_files():
+            result = prog.match(f.name())
+            if result != None:
+                p = [{}, {}]
+                p[0]["reader"] = s.files()[result.group(0)]
+                if result.group(2) != None:
+                    p[1]["reader"] = s.files()[result.group(1) + "_2.fastq" + result.group(2)]
+                else:
+                    p[1]["reader"] = s.files()[result.group(1) + "_2.fastq"]
+                if chunking:
+                    splitfastq(p)
+                else:
+                    m0 = p[0]["reader"].as_manifest()[1:]
+                    m1 = p[1]["reader"].as_manifest()[1:]
+                    manifest_list.append(["./_" + str(piece), m0[:-1]])
+                    manifest_list.append(["./_" + str(piece), m1[:-1]])
+                    piece += 1
+
+# No pairs found so just put each fastq file into a separate directory
+if len(manifest_list) == 0:
+    for s in inp.all_streams():
+        prog = re.compile("(.*?).fastq(.gz)?$")
+        if s.name() == ".":
+            for f in s.all_files():
+                result = prog.match(f.name())
+                if result != None:
+                    p = [{}]
+                    p[0]["reader"] = s.files()[result.group(0)]
+                    if chunking:
+                        splitfastq(p)
+                    else:
+                        m0 = p[0]["reader"].as_manifest()[1:]
+                        manifest_list.append(["./_" + str(piece), m0])
+                        piece += 1
+
+manifest_text = "\n".join(" ".join(m) for m in manifest_list)
+
+arvados.current_task().set_output(manifest_text)
index 2598e1cc944397324c9bb02b931a8bc7c20ed5a8..8154d0ed0c6dc7ee16c24e9de80a2ed031770687 100644 (file)
@@ -44,7 +44,11 @@ def sub_basename(v):
     return os.path.splitext(os.path.basename(v))[0]
 
 def sub_glob(v):
-    return glob.glob(v)[0]
+    l = glob.glob(v)
+    if len(l) == 0:
+        raise Exception("$(glob): No match on '%s'" % v)
+    else:
+        return l[0]
 
 default_subs = {"file ": sub_file,
                 "dir ": sub_dir,
index 2cad65c52746ecfdd40cb9236440cfbb9c714e11..1b493e3a30a88c68395dee7f52413be3f9f7b6db 100644 (file)
@@ -4,7 +4,7 @@ MAINTAINER Brett Smith <brett@curoverse.com>
 # Install dependencies and set up system.
 # The FUSE packages help ensure that we can install the Python SDK (arv-mount).
 RUN /usr/bin/apt-get install -q -y python-dev python-llfuse python-pip \
-      libio-socket-ssl-perl libjson-perl liburi-perl libwww-perl \
+      libio-socket-ssl-perl libjson-perl liburi-perl libwww-perl dtrx \
       fuse libattr1-dev libfuse-dev && \
     /usr/sbin/adduser --disabled-password \
       --gecos 'Crunch execution user' crunch && \
@@ -13,7 +13,7 @@ RUN /usr/bin/apt-get install -q -y python-dev python-llfuse python-pip \
 
 # Install Arvados packages.
 RUN (find /usr/src/arvados/sdk -name '*.gem' -print0 | \
-      xargs -0rn 1 gem install) && \
+      xargs -0rn 1 /usr/local/rvm/bin/rvm-exec default gem install) && \
     cd /usr/src/arvados/services/fuse && \
     python setup.py install && \
     cd /usr/src/arvados/sdk/python && \
index 389ce9cc21373eb079b4be2655e8211d7aaaaa43..ab3702cafc02b86825c3739ff63901828def793d 100755 (executable)
@@ -243,7 +243,7 @@ class PipelineInstance
   end
   def self.create(attributes)
     result = $client.execute(:api_method => $arvados.pipeline_instances.create,
-                             :body => {
+                             :body_object => {
                                :pipeline_instance => attributes.to_json
                              },
                              :authenticated => false,
@@ -262,7 +262,7 @@ class PipelineInstance
                              :parameters => {
                                :uuid => @pi[:uuid]
                              },
-                             :body => {
+                             :body_object => {
                                :pipeline_instance => @attributes_to_update.to_json
                              },
                              :authenticated => false,
@@ -328,7 +328,7 @@ class JobCache
     body = {job: no_nil_values(job)}.merge(no_nil_values(create_params))
 
     result = $client.execute(:api_method => $arvados.jobs.create,
-                             :body => body,
+                             :body_object => body,
                              :authenticated => false,
                              :headers => {
                                authorization: 'OAuth2 '+ENV['ARVADOS_API_TOKEN']
@@ -346,7 +346,7 @@ class JobCache
       msg += "Job submission was: #{body.to_json}"
 
       $client.execute(:api_method => $arvados.logs.create,
-                      :body => {
+                      :body_object => {
                         :log => {
                           :object_uuid => pipeline[:uuid],
                           :event_type => 'stderr',