Skip to content

Commit da702a5

Browse files
authored
Merge branch 'master' into v1.1/empty-array-input
2 parents df66457 + 92abb4e commit da702a5

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

68 files changed

+889
-470
lines changed

.travis.yml

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
sudo: false
22
language: python
3+
cache: pip
34
python:
45
- 2.7
56
- 3.3
@@ -10,9 +11,13 @@ os:
1011
- linux
1112
install:
1213
- pip install tox-travis
14+
jobs:
15+
include:
16+
- stage: release-test
17+
script: RELEASE_SKIP=head ./release-test.sh
1318
script: tox
1419
branches:
1520
only:
1621
- master
1722
notifications:
18-
email: false
23+
email: false

Makefile

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ install: FORCE
5656
dist: dist/${MODULE}-$(VERSION).tar.gz
5757

5858
dist/${MODULE}-$(VERSION).tar.gz: $(SOURCES)
59-
./setup.py sdist
59+
./setup.py sdist bdist_wheel
6060

6161
## clean : clean up all temporary / machine-generated files
6262
clean: FORCE
@@ -175,4 +175,18 @@ mypy3: ${PYSOURCES}
175175
--warn-redundant-casts \
176176
cwltool
177177

178+
release: FORCE
179+
./release-test.sh
180+
. testenv2/bin/activate && \
181+
testenv2/src/${MODULE}/setup.py sdist bdist_wheel && \
182+
pip install twine && \
183+
twine upload testenv2/src/${MODULE}/dist/* && \
184+
git tag ${VERSION} && git push --tags
185+
178186
FORCE:
187+
188+
# Use this to print the value of a Makefile variable
189+
# Example `make print-VERSION`
190+
# From https://www.cmcrossroads.com/article/printing-value-makefile-variable
191+
print-% : ; @echo $* = $($*)
192+

appveyor.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ install:
3131
- "python -c \"import struct; print(struct.calcsize('P') * 8)\""
3232

3333
build_script:
34+
- "%CMD_IN_ENV% pip install -U setuptools pip"
3435
- "%CMD_IN_ENV% pip install ."
3536

3637

cwltool/argparser.py

Lines changed: 399 additions & 0 deletions
Large diffs are not rendered by default.

cwltool/draft2tool.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,8 @@ def revmap_file(builder, outdir, f):
151151
return f
152152

153153

154-
raise WorkflowException(u"Output File object is missing both `location` and `path` fields: %s" % f)
154+
raise WorkflowException(u"Output File object is missing both 'location' "
155+
"and 'path' fields: %s" % f)
155156

156157

157158
class CallbackJob(object):

cwltool/executors.py

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
import logging
2+
import tempfile
3+
import threading
4+
5+
import os
6+
from abc import ABCMeta, abstractmethod
7+
8+
from typing import Dict, Text, Any, Tuple, Set, List
9+
10+
from .builder import Builder
11+
from .errors import WorkflowException
12+
from .mutation import MutationManager
13+
from .job import JobBase
14+
from .process import relocateOutputs, cleanIntermediate, Process
15+
from . import loghandler
16+
17+
_logger = logging.getLogger("cwltool")
18+
19+
class JobExecutor(object):
20+
__metaclass__ = ABCMeta
21+
22+
def __init__(self):
23+
# type: (...) -> None
24+
self.final_output = [] # type: List
25+
self.final_status = [] # type: List
26+
self.output_dirs = set() # type: Set
27+
28+
def __call__(self, *args, **kwargs):
29+
return self.execute(*args, **kwargs)
30+
31+
def output_callback(self, out, processStatus):
32+
self.final_status.append(processStatus)
33+
self.final_output.append(out)
34+
35+
@abstractmethod
36+
def run_jobs(self,
37+
t, # type: Process
38+
job_order_object, # type: Dict[Text, Any]
39+
logger,
40+
**kwargs # type: Any
41+
):
42+
pass
43+
44+
def execute(self, t, # type: Process
45+
job_order_object, # type: Dict[Text, Any]
46+
logger=_logger,
47+
**kwargs # type: Any
48+
):
49+
# type: (...) -> Tuple[Dict[Text, Any], Text]
50+
51+
if "basedir" not in kwargs:
52+
raise WorkflowException("Must provide 'basedir' in kwargs")
53+
54+
finaloutdir = os.path.abspath(kwargs.get("outdir")) if kwargs.get("outdir") else None
55+
kwargs["outdir"] = tempfile.mkdtemp(prefix=kwargs["tmp_outdir_prefix"]) if kwargs.get(
56+
"tmp_outdir_prefix") else tempfile.mkdtemp()
57+
self.output_dirs.add(kwargs["outdir"])
58+
kwargs["mutation_manager"] = MutationManager()
59+
60+
jobReqs = None
61+
if "cwl:requirements" in job_order_object:
62+
jobReqs = job_order_object["cwl:requirements"]
63+
elif ("cwl:defaults" in t.metadata and "cwl:requirements" in t.metadata["cwl:defaults"]):
64+
jobReqs = t.metadata["cwl:defaults"]["cwl:requirements"]
65+
if jobReqs:
66+
for req in jobReqs:
67+
t.requirements.append(req)
68+
69+
self.run_jobs(t, job_order_object, logger, **kwargs)
70+
71+
if self.final_output and self.final_output[0] and finaloutdir:
72+
self.final_output[0] = relocateOutputs(self.final_output[0], finaloutdir,
73+
self.output_dirs, kwargs.get("move_outputs"),
74+
kwargs["make_fs_access"](""))
75+
76+
if kwargs.get("rm_tmpdir"):
77+
cleanIntermediate(self.output_dirs)
78+
79+
if self.final_output and self.final_status:
80+
return (self.final_output[0], self.final_status[0])
81+
else:
82+
return (None, "permanentFail")
83+
84+
85+
class SingleJobExecutor(JobExecutor):
86+
def run_jobs(self,
87+
t, # type: Process
88+
job_order_object, # type: Dict[Text, Any]
89+
logger,
90+
**kwargs # type: Any
91+
):
92+
jobiter = t.job(job_order_object,
93+
self.output_callback,
94+
**kwargs)
95+
96+
try:
97+
for r in jobiter:
98+
if r:
99+
builder = kwargs.get("builder", None) # type: Builder
100+
if builder is not None:
101+
r.builder = builder
102+
if r.outdir:
103+
self.output_dirs.add(r.outdir)
104+
r.run(**kwargs)
105+
else:
106+
logger.error("Workflow cannot make any more progress.")
107+
break
108+
except WorkflowException:
109+
raise
110+
except Exception as e:
111+
logger.exception("Got workflow error")
112+
raise WorkflowException(Text(e))
113+
114+
115+
class MultithreadedJobExecutor(JobExecutor):
116+
def __init__(self):
117+
super(MultithreadedJobExecutor, self).__init__()
118+
self.threads = set()
119+
self.exceptions = []
120+
121+
def run_job(self,
122+
job, # type: JobBase
123+
**kwargs # type: Any
124+
):
125+
# type: (...) -> None
126+
def runner():
127+
try:
128+
job.run(**kwargs)
129+
except WorkflowException as e:
130+
self.exceptions.append(e)
131+
except Exception as e:
132+
self.exceptions.append(WorkflowException(Text(e)))
133+
134+
self.threads.remove(thread)
135+
136+
thread = threading.Thread(target=runner)
137+
thread.daemon = True
138+
self.threads.add(thread)
139+
thread.start()
140+
141+
def wait_for_next_completion(self): # type: () -> None
142+
if self.exceptions:
143+
raise self.exceptions[0]
144+
145+
def run_jobs(self,
146+
t, # type: Process
147+
job_order_object, # type: Dict[Text, Any]
148+
logger,
149+
**kwargs # type: Any
150+
):
151+
152+
jobiter = t.job(job_order_object, self.output_callback, **kwargs)
153+
154+
for r in jobiter:
155+
if r:
156+
builder = kwargs.get("builder", None) # type: Builder
157+
if builder is not None:
158+
r.builder = builder
159+
if r.outdir:
160+
self.output_dirs.add(r.outdir)
161+
self.run_job(r, **kwargs)
162+
else:
163+
if len(self.threads):
164+
self.wait_for_next_completion()
165+
else:
166+
logger.error("Workflow cannot make any more progress.")
167+
break
168+
169+
while len(self.threads) > 0:
170+
self.wait_for_next_completion()

cwltool/expression.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ def interpolate(scan, rootvars,
185185
e = evaluator(scan[w[0] + 1:w[1]], jslib, rootvars, fullJS=fullJS,
186186
timeout=timeout, force_docker_pull=force_docker_pull,
187187
debug=debug, js_console=js_console)
188-
if w[0] == 0 and w[1] == len(scan):
188+
if w[0] == 0 and w[1] == len(scan) and len(parts) <= 1:
189189
return e
190190
leaf = json.dumps(e, sort_keys=True)
191191
if leaf[0] == '"':

cwltool/factory.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
from typing import Callable as tCallable
44
from typing import Any, Dict, Text, Tuple, Union
55

6-
from . import load_tool, main, workflow
6+
from . import load_tool, workflow
7+
from .argparser import get_default_args
8+
from .executors import SingleJobExecutor
79
from .process import Process
810

911

@@ -35,13 +37,21 @@ class Factory(object):
3537
def __init__(self,
3638
makeTool=workflow.defaultMakeTool, # type: tCallable[[Any], Process]
3739
# should be tCallable[[Dict[Text, Any], Any], Process] ?
38-
executor=main.single_job_executor, # type: tCallable[...,Tuple[Dict[Text,Any], Text]]
40+
executor=None, # type: tCallable[...,Tuple[Dict[Text,Any], Text]]
3941
**execkwargs # type: Any
4042
):
4143
# type: (...) -> None
4244
self.makeTool = makeTool
45+
if executor is None:
46+
executor = SingleJobExecutor()
4347
self.executor = executor
44-
self.execkwargs = execkwargs
48+
49+
kwargs = get_default_args()
50+
kwargs.pop("job_order")
51+
kwargs.pop("workflow")
52+
kwargs.pop("outdir")
53+
kwargs.update(execkwargs)
54+
self.execkwargs = kwargs
4555

4656
def make(self, cwl):
4757
"""Instantiate a CWL object from a CWl document."""

cwltool/job.py

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from __future__ import absolute_import
2+
23
import codecs
4+
import datetime
35
import functools
46
import io
57
import json
@@ -12,25 +14,28 @@
1214
import sys
1315
import tempfile
1416
from io import open
17+
from threading import Lock
1518
from typing import (IO, Any, Callable, Dict, Iterable, List, MutableMapping, Text,
16-
Tuple, Union, cast)
19+
Union, cast)
1720

1821
import shellescape
1922

20-
from .utils import copytree_with_merge, docker_windows_path_adjust, onWindows
2123
from . import docker
2224
from .builder import Builder
2325
from .docker_id import docker_vm_id
2426
from .errors import WorkflowException
2527
from .pathmapper import PathMapper, ensure_writable
26-
from .process import (UnsupportedRequirement, empty_subtree, get_feature,
28+
from .process import (UnsupportedRequirement, get_feature,
2729
stageFiles)
2830
from .utils import bytes2str_in_dicts
31+
from .utils import copytree_with_merge, docker_windows_path_adjust, onWindows
2932

3033
_logger = logging.getLogger("cwltool")
3134

3235
needs_shell_quoting_re = re.compile(r"""(^$|[\s|&;()<>\'"$@])""")
3336

37+
job_output_lock = Lock()
38+
3439
FORCE_SHELLED_POPEN = os.getenv("CWLTOOL_FORCE_SHELL_POPEN", "0") == "1"
3540

3641
SHELL_COMMAND_TEMPLATE = """#!/bin/bash
@@ -266,7 +271,8 @@ def _execute(self, runtime, env, rm_tmpdir=True, move_outputs="move"):
266271
if _logger.isEnabledFor(logging.DEBUG):
267272
_logger.debug(u"[job %s] %s", self.name, json.dumps(outputs, indent=4))
268273

269-
self.output_callback(outputs, processStatus)
274+
with job_output_lock:
275+
self.output_callback(outputs, processStatus)
270276

271277
if self.stagedir and os.path.exists(self.stagedir):
272278
_logger.debug(u"[job %s] Removing input staging directory %s", self.name, self.stagedir)
@@ -363,8 +369,10 @@ def add_volumes(self, pathmapper, runtime):
363369
docker_windows_path_adjust(vol.target)))
364370

365371
def run(self, pull_image=True, rm_container=True,
372+
record_container_id=False, cidfile_dir="",
373+
cidfile_prefix="",
366374
rm_tmpdir=True, move_outputs="move", **kwargs):
367-
# type: (bool, bool, bool, Text, **Any) -> None
375+
# type: (bool, bool, bool, Text, Text, bool, Text, **Any) -> None
368376

369377
(docker_req, docker_is_req) = get_feature(self, "DockerRequirement")
370378

@@ -463,6 +471,26 @@ def run(self, pull_image=True, rm_container=True,
463471
# directory." but spec might change to designated temp directory.
464472
# runtime.append("--env=HOME=/tmp")
465473
runtime.append(u"--env=HOME=%s" % self.builder.outdir)
474+
475+
# add parameters to docker to write a container ID file
476+
if record_container_id:
477+
if cidfile_dir != "":
478+
if not os.path.isdir(cidfile_dir):
479+
_logger.error("--cidfile-dir %s error:\n%s", cidfile_dir,
480+
cidfile_dir + " is not a directory or "
481+
"directory doesn't exist, please check it first")
482+
exit(2)
483+
if not os.path.exists(cidfile_dir):
484+
_logger.error("--cidfile-dir %s error:\n%s", cidfile_dir,
485+
"directory doesn't exist, please create it first")
486+
exit(2)
487+
else:
488+
cidfile_dir = os.getcwd()
489+
cidfile_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S-%f")+".cid"
490+
if cidfile_prefix != "":
491+
cidfile_name = str(cidfile_prefix + "-" + cidfile_name)
492+
cidfile_path = os.path.join(cidfile_dir, cidfile_name)
493+
runtime.append(u"--cidfile=%s" % cidfile_path)
466494

467495
for t, v in self.environment.items():
468496
runtime.append(u"--env=%s=%s" % (t, v))

cwltool/loghandler.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import logging
2+
3+
_logger = logging.getLogger("cwltool")
4+
defaultStreamHandler = logging.StreamHandler()
5+
_logger.addHandler(defaultStreamHandler)
6+
_logger.setLevel(logging.INFO)

0 commit comments

Comments
 (0)