6 import arvados.commands.run
7 import arvados.collection
9 from schema_salad.sourceline import SourceLine
11 from cwltool.pathmapper import PathMapper, MapperEnt, abspath, adjustFileObjs, adjustDirObjs
12 from cwltool.workflow import WorkflowException
14 logger = logging.getLogger('arvados.cwl-runner')
16 class ArvPathMapper(PathMapper):
17 """Convert container-local paths to and from Keep collection ids."""
19 pdh_path = re.compile(r'^keep:[0-9a-f]{32}\+\d+/.+$')
20 pdh_dirpath = re.compile(r'^keep:[0-9a-f]{32}\+\d+(/.+)?$')
22 def __init__(self, arvrunner, referenced_files, input_basedir,
23 collection_pattern, file_pattern, name=None, **kwargs):
24 self.arvrunner = arvrunner
25 self.input_basedir = input_basedir
26 self.collection_pattern = collection_pattern
27 self.file_pattern = file_pattern
29 super(ArvPathMapper, self).__init__(referenced_files, input_basedir, None)
31 def visit(self, srcobj, uploadfiles):
32 src = srcobj["location"]
34 src = src[:src.index("#")]
36 if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
37 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], srcobj["class"], True)
39 if src not in self._pathmap:
40 # Local FS ref, may need to be uploaded or may be on keep
42 ab = abspath(src, self.input_basedir)
43 st = arvados.commands.run.statfile("", ab,
44 fnPattern="keep:%s/%s",
45 dirPattern="keep:%s/%s")
46 with SourceLine(srcobj, "location", WorkflowException):
47 if isinstance(st, arvados.commands.run.UploadFile):
48 uploadfiles.add((src, ab, st))
49 elif isinstance(st, arvados.commands.run.ArvFile):
50 self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % st.fn[5:], "File", True)
51 elif src.startswith("_:"):
52 if "contents" in srcobj:
55 raise WorkflowException("File literal '%s' is missing contents" % src)
56 elif src.startswith("arvwf:"):
57 self._pathmap[src] = MapperEnt(src, src, "File", True)
59 raise WorkflowException("Input file path '%s' is invalid" % st)
61 with SourceLine(srcobj, "secondaryFiles", WorkflowException):
62 for l in srcobj.get("secondaryFiles", []):
63 self.visit(l, uploadfiles)
64 with SourceLine(srcobj, "listing", WorkflowException):
65 for l in srcobj.get("listing", []):
66 self.visit(l, uploadfiles)
68 def addentry(self, obj, c, path, subdirs):
69 if obj["location"] in self._pathmap:
70 src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
73 c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
74 for l in obj.get("secondaryFiles", []):
75 self.addentry(l, c, path, subdirs)
76 elif obj["class"] == "Directory":
77 for l in obj.get("listing", []):
78 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
79 subdirs.append((obj["location"], path + "/" + obj["basename"]))
80 elif obj["location"].startswith("_:") and "contents" in obj:
81 with c.open(path + "/" + obj["basename"], "w") as f:
82 f.write(obj["contents"].encode("utf-8"))
84 raise SourceLine(obj, "location", WorkflowException).makeError("Don't know what to do with '%s'" % obj["location"])
86 def setup(self, referenced_files, basedir):
87 # type: (List[Any], unicode) -> None
90 already_uploaded = self.arvrunner.get_uploaded()
91 for k in referenced_files:
93 if loc in already_uploaded:
94 v = already_uploaded[loc]
95 self._pathmap[loc] = MapperEnt(v.resolved, self.collection_pattern % v.resolved[5:], "File", True)
97 for srcobj in referenced_files:
98 self.visit(srcobj, uploadfiles)
101 arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
104 num_retries=self.arvrunner.num_retries,
105 fnPattern="keep:%s/%s",
107 project=self.arvrunner.project_uuid)
109 for src, ab, st in uploadfiles:
110 self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % st.keepref,
111 "Directory" if os.path.isdir(ab) else "File", True)
112 self.arvrunner.add_uploaded(src, self._pathmap[src])
114 for srcobj in referenced_files:
116 if srcobj["class"] == "Directory":
117 if srcobj["location"] not in self._pathmap:
118 c = arvados.collection.Collection(api_client=self.arvrunner.api,
119 keep_client=self.arvrunner.keep_client,
120 num_retries=self.arvrunner.num_retries)
121 for l in srcobj.get("listing", []):
122 self.addentry(l, c, ".", subdirs)
124 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
125 if not check["items"]:
126 c.save_new(owner_uuid=self.arvrunner.project_uuid)
128 ab = self.collection_pattern % c.portable_data_hash()
129 self._pathmap[srcobj["location"]] = MapperEnt("keep:"+c.portable_data_hash(), ab, "Directory", True)
130 elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
131 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
133 c = arvados.collection.Collection(api_client=self.arvrunner.api,
134 keep_client=self.arvrunner.keep_client,
135 num_retries=self.arvrunner.num_retries )
136 self.addentry(srcobj, c, ".", subdirs)
138 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
139 if not check["items"]:
140 c.save_new(owner_uuid=self.arvrunner.project_uuid)
142 ab = self.file_pattern % (c.portable_data_hash(), srcobj["basename"])
143 self._pathmap[srcobj["location"]] = MapperEnt("keep:%s/%s" % (c.portable_data_hash(), srcobj["basename"]),
145 if srcobj.get("secondaryFiles"):
146 ab = self.collection_pattern % c.portable_data_hash()
147 self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt("keep:"+c.portable_data_hash(), ab, "Directory", True)
150 for loc, sub in subdirs:
151 # subdirs will all start with "./", strip it off
152 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
153 self._pathmap[loc] = MapperEnt("keep:%s/%s" % (c.portable_data_hash(), sub[2:]),
154 ab, "Directory", True)
158 def reversemap(self, target):
159 if target.startswith("keep:"):
160 return (target, target)
161 elif self.keepdir and target.startswith(self.keepdir):
162 return (target, "keep:" + target[len(self.keepdir)+1:])
164 return super(ArvPathMapper, self).reversemap(target)
166 class StagingPathMapper(PathMapper):
169 def visit(self, obj, stagedir, basedir, copy=False, staged=False):
170 # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
171 loc = obj["location"]
172 tgt = os.path.join(stagedir, obj["basename"])
173 if obj["class"] == "Directory":
174 self._pathmap[loc] = MapperEnt(loc, tgt, "Directory", staged)
175 if loc.startswith("_:") or self._follow_dirs:
176 self.visitlisting(obj.get("listing", []), tgt, basedir)
177 elif obj["class"] == "File":
178 if loc in self._pathmap:
180 if "contents" in obj and loc.startswith("_:"):
181 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile", staged)
184 self._pathmap[loc] = MapperEnt(loc, tgt, "WritableFile", staged)
186 self._pathmap[loc] = MapperEnt(loc, tgt, "File", staged)
187 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
190 class VwdPathMapper(StagingPathMapper):
191 def setup(self, referenced_files, basedir):
192 # type: (List[Any], unicode) -> None
194 # Go through each file and set the target to its own directory along
195 # with any secondary files.
196 self.visitlisting(referenced_files, self.stagedir, basedir)
198 for path, (ab, tgt, type, staged) in self._pathmap.items():
199 if type in ("File", "Directory") and ab.startswith("keep:"):
200 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type, staged)
203 class NoFollowPathMapper(StagingPathMapper):
205 def setup(self, referenced_files, basedir):
206 # type: (List[Any], unicode) -> None
207 self.visitlisting(referenced_files, self.stagedir, basedir)