Skip to content

Commit 130f3b9

Browse files
authored
Merge branch 'master' into fix/unsupported-operands
2 parents dc67575 + 4482257 commit 130f3b9

Some content is hidden

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

69 files changed

+916
-492
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/builder.py

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ def bind_input(self, schema, datum, lead_pos=None, tail_pos=None):
7878
lead_pos = []
7979
bindings = [] # type: List[Dict[Text,Text]]
8080
binding = None # type: Dict[Text,Any]
81+
value_from_expression = False
8182
if "inputBinding" in schema and isinstance(schema["inputBinding"], dict):
8283
binding = copy.copy(schema["inputBinding"])
8384

@@ -87,29 +88,33 @@ def bind_input(self, schema, datum, lead_pos=None, tail_pos=None):
8788
binding["position"] = aslist(lead_pos) + [0] + aslist(tail_pos)
8889

8990
binding["datum"] = datum
91+
if "valueFrom" in binding:
92+
value_from_expression = True
9093

9194
# Handle union types
9295
if isinstance(schema["type"], list):
93-
for t in schema["type"]:
94-
if isinstance(t, (str, Text)) and self.names.has_name(t, ""):
95-
avsc = self.names.get_name(t, "")
96-
elif isinstance(t, dict) and "name" in t and self.names.has_name(t["name"], ""):
97-
avsc = self.names.get_name(t["name"], "")
98-
else:
99-
avsc = AvroSchemaFromJSONData(t, self.names)
100-
if validate.validate(avsc, datum):
101-
schema = copy.deepcopy(schema)
102-
schema["type"] = t
103-
return self.bind_input(schema, datum, lead_pos=lead_pos, tail_pos=tail_pos)
104-
raise validate.ValidationException(u"'%s' is not a valid union %s" % (datum, schema["type"]))
96+
if not value_from_expression:
97+
for t in schema["type"]:
98+
if isinstance(t, (str, Text)) and self.names.has_name(t, ""):
99+
avsc = self.names.get_name(t, "")
100+
elif isinstance(t, dict) and "name" in t and self.names.has_name(t["name"], ""):
101+
avsc = self.names.get_name(t["name"], "")
102+
else:
103+
avsc = AvroSchemaFromJSONData(t, self.names)
104+
if validate.validate(avsc, datum):
105+
schema = copy.deepcopy(schema)
106+
schema["type"] = t
107+
return self.bind_input(schema, datum, lead_pos=lead_pos, tail_pos=tail_pos)
108+
raise validate.ValidationException(u"'%s' is not a valid union %s" % (datum, schema["type"]))
105109
elif isinstance(schema["type"], dict):
106-
st = copy.deepcopy(schema["type"])
107-
if binding and "inputBinding" not in st and st["type"] == "array" and "itemSeparator" not in binding:
108-
st["inputBinding"] = {}
109-
for k in ("secondaryFiles", "format", "streamable"):
110-
if k in schema:
111-
st[k] = schema[k]
112-
bindings.extend(self.bind_input(st, datum, lead_pos=lead_pos, tail_pos=tail_pos))
110+
if not value_from_expression:
111+
st = copy.deepcopy(schema["type"])
112+
if binding and "inputBinding" not in st and st["type"] == "array" and "itemSeparator" not in binding:
113+
st["inputBinding"] = {}
114+
for k in ("secondaryFiles", "format", "streamable"):
115+
if k in schema:
116+
st[k] = schema[k]
117+
bindings.extend(self.bind_input(st, datum, lead_pos=lead_pos, tail_pos=tail_pos))
113118
else:
114119
if schema["type"] in self.schemaDefs:
115120
schema = self.schemaDefs[schema["type"]]
@@ -218,12 +223,12 @@ def generate_arg(self, binding): # type: (Dict[Text,Any]) -> List[Text]
218223

219224
l = [] # type: List[Dict[Text,Text]]
220225
if isinstance(value, list):
221-
if binding.get("itemSeparator"):
226+
if binding.get("itemSeparator") and value:
222227
l = [binding["itemSeparator"].join([self.tostr(v) for v in value])]
223228
elif binding.get("valueFrom"):
224229
value = [self.tostr(v) for v in value]
225230
return ([prefix] if prefix else []) + value
226-
elif prefix:
231+
elif prefix and value:
227232
return [prefix]
228233
else:
229234
return []

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."""

0 commit comments

Comments
 (0)