7 import arvados.commands.run
8 import arvados.collection
10 from schema_salad.sourceline import SourceLine
12 from cwltool.pathmapper import PathMapper, MapperEnt, abspath, adjustFileObjs, adjustDirObjs
13 from cwltool.workflow import WorkflowException
15 logger = logging.getLogger('arvados.cwl-runner')
17 class ArvPathMapper(PathMapper):
18 """Convert container-local paths to and from Keep collection ids."""
20 pdh_path = re.compile(r'^keep:[0-9a-f]{32}\+\d+/.+$')
21 pdh_dirpath = re.compile(r'^keep:[0-9a-f]{32}\+\d+(/.*)?$')
23 def __init__(self, arvrunner, referenced_files, input_basedir,
24 collection_pattern, file_pattern, name=None, **kwargs):
25 self.arvrunner = arvrunner
26 self.input_basedir = input_basedir
27 self.collection_pattern = collection_pattern
28 self.file_pattern = file_pattern
30 super(ArvPathMapper, self).__init__(referenced_files, input_basedir, None)
32 def visit(self, srcobj, uploadfiles):
33 src = srcobj["location"]
35 src = src[:src.index("#")]
37 if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
38 self._pathmap[src] = MapperEnt(src, self.collection_pattern % urllib.unquote(src[5:]), srcobj["class"], True)
40 if src not in self._pathmap:
41 if src.startswith("file:"):
42 # Local FS ref, may need to be uploaded or may be on keep
44 ab = abspath(src, self.input_basedir)
45 st = arvados.commands.run.statfile("", ab,
46 fnPattern="keep:%s/%s",
47 dirPattern="keep:%s/%s")
48 with SourceLine(srcobj, "location", WorkflowException):
49 if isinstance(st, arvados.commands.run.UploadFile):
50 uploadfiles.add((src, ab, st))
51 elif isinstance(st, arvados.commands.run.ArvFile):
52 self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % urllib.unquote(st.fn[5:]), "File", True)
54 raise WorkflowException("Input file path '%s' is invalid" % st)
55 elif src.startswith("_:"):
56 if srcobj["class"] == "File" and "contents" not in srcobj:
57 raise WorkflowException("File literal '%s' is missing `contents`" % src)
58 if srcobj["class"] == "Directory" and "listing" not in srcobj:
59 raise WorkflowException("Directory literal '%s' is missing `listing`" % src)
61 self._pathmap[src] = MapperEnt(src, src, srcobj["class"], True)
63 with SourceLine(srcobj, "secondaryFiles", WorkflowException):
64 for l in srcobj.get("secondaryFiles", []):
65 self.visit(l, uploadfiles)
66 with SourceLine(srcobj, "listing", WorkflowException):
67 for l in srcobj.get("listing", []):
68 self.visit(l, uploadfiles)
70 def addentry(self, obj, c, path, subdirs):
71 if obj["location"] in self._pathmap:
72 src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
75 c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
76 for l in obj.get("secondaryFiles", []):
77 self.addentry(l, c, path, subdirs)
78 elif obj["class"] == "Directory":
79 for l in obj.get("listing", []):
80 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
81 subdirs.append((obj["location"], path + "/" + obj["basename"]))
82 elif obj["location"].startswith("_:") and "contents" in obj:
83 with c.open(path + "/" + obj["basename"], "w") as f:
84 f.write(obj["contents"].encode("utf-8"))
86 raise SourceLine(obj, "location", WorkflowException).makeError("Don't know what to do with '%s'" % obj["location"])
88 def setup(self, referenced_files, basedir):
89 # type: (List[Any], unicode) -> None
92 already_uploaded = self.arvrunner.get_uploaded()
93 for k in referenced_files:
95 if loc in already_uploaded:
96 v = already_uploaded[loc]
97 self._pathmap[loc] = MapperEnt(v.resolved, self.collection_pattern % urllib.unquote(v.resolved[5:]), "File", True)
99 for srcobj in referenced_files:
100 self.visit(srcobj, uploadfiles)
103 arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
106 num_retries=self.arvrunner.num_retries,
107 fnPattern="keep:%s/%s",
109 project=self.arvrunner.project_uuid)
111 for src, ab, st in uploadfiles:
112 self._pathmap[src] = MapperEnt(urllib.quote(st.fn, "/:+@"), self.collection_pattern % st.fn[5:],
113 "Directory" if os.path.isdir(ab) else "File", True)
114 self.arvrunner.add_uploaded(src, self._pathmap[src])
116 for srcobj in referenced_files:
118 if srcobj["class"] == "Directory":
119 if srcobj["location"] not in self._pathmap:
120 c = arvados.collection.Collection(api_client=self.arvrunner.api,
121 keep_client=self.arvrunner.keep_client,
122 num_retries=self.arvrunner.num_retries)
123 for l in srcobj.get("listing", []):
124 self.addentry(l, c, ".", subdirs)
126 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
127 if not check["items"]:
128 c.save_new(owner_uuid=self.arvrunner.project_uuid)
130 ab = self.collection_pattern % c.portable_data_hash()
131 self._pathmap[srcobj["location"]] = MapperEnt("keep:"+c.portable_data_hash(), ab, "Directory", True)
132 elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
133 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
135 c = arvados.collection.Collection(api_client=self.arvrunner.api,
136 keep_client=self.arvrunner.keep_client,
137 num_retries=self.arvrunner.num_retries )
138 self.addentry(srcobj, c, ".", subdirs)
140 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
141 if not check["items"]:
142 c.save_new(owner_uuid=self.arvrunner.project_uuid)
144 ab = self.file_pattern % (c.portable_data_hash(), srcobj["basename"])
145 self._pathmap[srcobj["location"]] = MapperEnt("keep:%s/%s" % (c.portable_data_hash(), srcobj["basename"]),
147 if srcobj.get("secondaryFiles"):
148 ab = self.collection_pattern % c.portable_data_hash()
149 self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt("keep:"+c.portable_data_hash(), ab, "Directory", True)
152 for loc, sub in subdirs:
153 # subdirs will all start with "./", strip it off
154 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
155 self._pathmap[loc] = MapperEnt("keep:%s/%s" % (c.portable_data_hash(), sub[2:]),
156 ab, "Directory", True)
160 def reversemap(self, target):
161 if target.startswith("keep:"):
162 return (target, target)
163 elif self.keepdir and target.startswith(self.keepdir):
164 return (target, "keep:" + target[len(self.keepdir)+1:])
166 return super(ArvPathMapper, self).reversemap(target)
168 class StagingPathMapper(PathMapper):
171 def visit(self, obj, stagedir, basedir, copy=False, staged=False):
172 # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
173 loc = obj["location"]
174 tgt = os.path.join(stagedir, obj["basename"])
175 if obj["class"] == "Directory":
176 self._pathmap[loc] = MapperEnt(loc, tgt, "Directory", staged)
177 if loc.startswith("_:") or self._follow_dirs:
178 self.visitlisting(obj.get("listing", []), tgt, basedir)
179 elif obj["class"] == "File":
180 if loc in self._pathmap:
182 if "contents" in obj and loc.startswith("_:"):
183 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile", staged)
186 self._pathmap[loc] = MapperEnt(loc, tgt, "WritableFile", staged)
188 self._pathmap[loc] = MapperEnt(loc, tgt, "File", staged)
189 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
192 class VwdPathMapper(StagingPathMapper):
193 def setup(self, referenced_files, basedir):
194 # type: (List[Any], unicode) -> None
196 # Go through each file and set the target to its own directory along
197 # with any secondary files.
198 self.visitlisting(referenced_files, self.stagedir, basedir)
200 for path, (ab, tgt, type, staged) in self._pathmap.items():
201 if type in ("File", "Directory") and ab.startswith("keep:"):
202 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type, staged)
205 class NoFollowPathMapper(StagingPathMapper):
207 def setup(self, referenced_files, basedir):
208 # type: (List[Any], unicode) -> None
209 self.visitlisting(referenced_files, self.stagedir, basedir)