6 import arvados.commands.run
7 import arvados.collection
9 from cwltool.pathmapper import PathMapper, MapperEnt, abspath, adjustFileObjs, adjustDirObjs
10 from cwltool.workflow import WorkflowException
12 logger = logging.getLogger('arvados.cwl-runner')
14 class ArvPathMapper(PathMapper):
15 """Convert container-local paths to and from Keep collection ids."""
17 pdh_path = re.compile(r'^keep:[0-9a-f]{32}\+\d+/.+$')
18 pdh_dirpath = re.compile(r'^keep:[0-9a-f]{32}\+\d+(/.+)?$')
20 def __init__(self, arvrunner, referenced_files, input_basedir,
21 collection_pattern, file_pattern, name=None, **kwargs):
22 self.arvrunner = arvrunner
23 self.input_basedir = input_basedir
24 self.collection_pattern = collection_pattern
25 self.file_pattern = file_pattern
27 super(ArvPathMapper, self).__init__(referenced_files, input_basedir, None)
29 def visit(self, srcobj, uploadfiles):
30 src = srcobj["location"]
31 if srcobj["class"] == "File":
33 src = src[:src.index("#")]
34 if isinstance(src, basestring) and ArvPathMapper.pdh_path.match(src):
35 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "File")
36 if src not in self._pathmap:
37 # Local FS ref, may need to be uploaded or may be on keep
39 ab = abspath(src, self.input_basedir)
40 st = arvados.commands.run.statfile("", ab, fnPattern=self.file_pattern)
41 if isinstance(st, arvados.commands.run.UploadFile):
42 uploadfiles.add((src, ab, st))
43 elif isinstance(st, arvados.commands.run.ArvFile):
44 self._pathmap[src] = MapperEnt(ab, st.fn, "File")
45 elif src.startswith("_:"):
46 if "contents" in srcobj:
49 raise WorkflowException("File literal '%s' is missing contents" % src)
51 raise WorkflowException("Input file path '%s' is invalid" % st)
52 if "secondaryFiles" in srcobj:
53 for l in srcobj["secondaryFiles"]:
54 self.visit(l, uploadfiles)
55 elif srcobj["class"] == "Directory":
56 if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
57 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "Directory")
58 for l in srcobj.get("listing", []):
59 self.visit(l, uploadfiles)
61 def addentry(self, obj, c, path, subdirs):
62 if obj["location"] in self._pathmap:
63 src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
66 c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
67 for l in obj.get("secondaryFiles", []):
68 self.addentry(l, c, path, subdirs)
69 elif obj["class"] == "Directory":
70 for l in obj["listing"]:
71 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
72 subdirs.append((obj["location"], path + "/" + obj["basename"]))
73 elif obj["location"].startswith("_:") and "contents" in obj:
74 with c.open(path + "/" + obj["basename"], "w") as f:
75 f.write(obj["contents"].encode("utf-8"))
77 raise WorkflowException("Don't know what to do with '%s'" % obj["location"])
79 def setup(self, referenced_files, basedir):
80 # type: (List[Any], unicode) -> None
81 self._pathmap = self.arvrunner.get_uploaded()
84 for srcobj in referenced_files:
85 self.visit(srcobj, uploadfiles)
88 arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
91 num_retries=self.arvrunner.num_retries,
92 fnPattern=self.file_pattern,
94 project=self.arvrunner.project_uuid)
96 for src, ab, st in uploadfiles:
97 self._pathmap[src] = MapperEnt("keep:" + st.keepref, st.fn, "File")
98 self.arvrunner.add_uploaded(src, self._pathmap[src])
100 for srcobj in referenced_files:
101 if srcobj["class"] == "Directory":
102 if srcobj["location"] not in self._pathmap:
103 c = arvados.collection.Collection(api_client=self.arvrunner.api,
104 keep_client=self.arvrunner.keep_client,
105 num_retries=self.arvrunner.num_retries)
107 for l in srcobj["listing"]:
108 self.addentry(l, c, ".", subdirs)
110 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
111 if not check["items"]:
112 c.save_new(owner_uuid=self.arvrunner.project_uuid)
114 ab = self.collection_pattern % c.portable_data_hash()
115 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "Directory")
116 for loc, sub in subdirs:
117 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
118 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
119 elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
120 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
122 c = arvados.collection.Collection(api_client=self.arvrunner.api,
123 keep_client=self.arvrunner.keep_client,
124 num_retries=self.arvrunner.num_retries )
126 self.addentry(srcobj, c, ".", subdirs)
128 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
129 if not check["items"]:
130 c.save_new(owner_uuid=self.arvrunner.project_uuid)
132 ab = self.file_pattern % (c.portable_data_hash(), srcobj["basename"])
133 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "File")
134 if srcobj.get("secondaryFiles"):
135 ab = self.collection_pattern % c.portable_data_hash()
136 self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt(ab, ab, "Directory")
137 for loc, sub in subdirs:
138 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
139 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
143 def reversemap(self, target):
144 if target.startswith("keep:"):
145 return (target, target)
146 elif self.keepdir and target.startswith(self.keepdir):
147 return (target, "keep:" + target[len(self.keepdir)+1:])
149 return super(ArvPathMapper, self).reversemap(target)
151 class InitialWorkDirPathMapper(PathMapper):
153 def visit(self, obj, stagedir, basedir, copy=False):
154 # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
155 loc = obj["location"]
156 if obj["class"] == "Directory":
157 self._pathmap[loc] = MapperEnt(obj["location"], stagedir, "Directory")
158 self.visitlisting(obj.get("listing", []), stagedir, basedir)
159 elif obj["class"] == "File":
160 if loc in self._pathmap:
162 tgt = os.path.join(stagedir, obj["basename"])
163 if "contents" in obj and obj["location"].startswith("_:"):
164 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile")
167 self._pathmap[loc] = MapperEnt(obj["path"], tgt, "WritableFile")
169 self._pathmap[loc] = MapperEnt(obj["path"], tgt, "File")
170 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
172 def setup(self, referenced_files, basedir):
173 # type: (List[Any], unicode) -> None
175 # Go through each file and set the target to its own directory along
176 # with any secondary files.
177 self.visitlisting(referenced_files, self.stagedir, basedir)
179 for path, (ab, tgt, type) in self._pathmap.items():
180 if type in ("File", "Directory") and ab.startswith("keep:"):
181 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type)
184 class FinalOutputPathMapper(PathMapper):
185 def visit(self, obj, stagedir, basedir, copy=False):
186 # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
187 loc = obj["location"]
188 if obj["class"] == "Directory":
189 self._pathmap[loc] = MapperEnt(loc, stagedir, "Directory")
190 elif obj["class"] == "File":
191 if loc in self._pathmap:
193 tgt = os.path.join(stagedir, obj["basename"])
194 self._pathmap[loc] = MapperEnt(loc, tgt, "File")
195 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
197 def setup(self, referenced_files, basedir):
198 # type: (List[Any], unicode) -> None
199 self.visitlisting(referenced_files, self.stagedir, basedir)