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"]
34 if srcobj["class"] == "File":
36 src = src[:src.index("#")]
37 if isinstance(src, basestring) and ArvPathMapper.pdh_path.match(src):
38 self._pathmap[src] = MapperEnt(src, self.collection_pattern % urllib.unquote(src[5:]), "File")
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, fnPattern="keep:%s/%s")
44 with SourceLine(srcobj, "location", WorkflowException):
45 if isinstance(st, arvados.commands.run.UploadFile):
46 uploadfiles.add((src, ab, st))
47 elif isinstance(st, arvados.commands.run.ArvFile):
48 self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % urllib.unquote(st.fn[5:]), "File")
49 elif src.startswith("_:"):
50 if "contents" in srcobj:
53 raise WorkflowException("File literal '%s' is missing contents" % src)
54 elif src.startswith("arvwf:"):
55 self._pathmap[src] = MapperEnt(src, src, "File")
57 raise WorkflowException("Input file path '%s' is invalid" % st)
58 if "secondaryFiles" in srcobj:
59 for l in srcobj["secondaryFiles"]:
60 self.visit(l, uploadfiles)
61 elif srcobj["class"] == "Directory":
62 if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
63 self._pathmap[src] = MapperEnt(src, self.collection_pattern % urllib.unquote(src[5:]), "Directory")
64 for l in srcobj.get("listing", []):
65 self.visit(l, uploadfiles)
67 def addentry(self, obj, c, path, subdirs):
68 if obj["location"] in self._pathmap:
69 src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
72 c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
73 for l in obj.get("secondaryFiles", []):
74 self.addentry(l, c, path, subdirs)
75 elif obj["class"] == "Directory":
76 for l in obj["listing"]:
77 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
78 subdirs.append((obj["location"], path + "/" + obj["basename"]))
79 elif obj["location"].startswith("_:") and "contents" in obj:
80 with c.open(path + "/" + obj["basename"], "w") as f:
81 f.write(obj["contents"].encode("utf-8"))
83 raise SourceLine(obj, "location", WorkflowException).makeError("Don't know what to do with '%s'" % obj["location"])
85 def setup(self, referenced_files, basedir):
86 # type: (List[Any], unicode) -> None
89 already_uploaded = self.arvrunner.get_uploaded()
90 for k in referenced_files:
92 if loc in already_uploaded:
93 v = already_uploaded[loc]
94 self._pathmap[loc] = MapperEnt(v.resolved, self.collection_pattern % urllib.unquote(v.resolved[5:]), "File")
96 for srcobj in referenced_files:
97 self.visit(srcobj, uploadfiles)
100 arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
103 num_retries=self.arvrunner.num_retries,
104 fnPattern="keep:%s/%s",
106 project=self.arvrunner.project_uuid)
108 for src, ab, st in uploadfiles:
109 self._pathmap[src] = MapperEnt(urllib.quote(st.fn, "/:+@"), self.collection_pattern % st.fn[5:], "File")
110 self.arvrunner.add_uploaded(src, self._pathmap[src])
112 for srcobj in referenced_files:
113 if srcobj["class"] == "Directory":
114 if srcobj["location"] not in self._pathmap:
115 c = arvados.collection.Collection(api_client=self.arvrunner.api,
116 keep_client=self.arvrunner.keep_client,
117 num_retries=self.arvrunner.num_retries)
119 for l in srcobj["listing"]:
120 self.addentry(l, c, ".", subdirs)
122 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
123 if not check["items"]:
124 c.save_new(owner_uuid=self.arvrunner.project_uuid)
126 ab = self.collection_pattern % c.portable_data_hash()
127 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "Directory")
128 for loc, sub in subdirs:
129 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
130 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
131 elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
132 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
134 c = arvados.collection.Collection(api_client=self.arvrunner.api,
135 keep_client=self.arvrunner.keep_client,
136 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(ab, ab, "File")
146 if srcobj.get("secondaryFiles"):
147 ab = self.collection_pattern % c.portable_data_hash()
148 self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt(ab, ab, "Directory")
149 for loc, sub in subdirs:
150 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
151 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
155 def reversemap(self, target):
156 if target.startswith("keep:"):
157 return (target, target)
158 elif self.keepdir and target.startswith(self.keepdir):
159 return (target, "keep:" + target[len(self.keepdir)+1:])
161 return super(ArvPathMapper, self).reversemap(target)
163 class StagingPathMapper(PathMapper):
166 def visit(self, obj, stagedir, basedir, copy=False):
167 # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
168 loc = obj["location"]
169 tgt = os.path.join(stagedir, obj["basename"])
170 if obj["class"] == "Directory":
171 self._pathmap[loc] = MapperEnt(loc, tgt, "Directory")
172 if loc.startswith("_:") or self._follow_dirs:
173 self.visitlisting(obj.get("listing", []), tgt, basedir)
174 elif obj["class"] == "File":
175 if loc in self._pathmap:
177 if "contents" in obj and loc.startswith("_:"):
178 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile")
181 self._pathmap[loc] = MapperEnt(loc, tgt, "WritableFile")
183 self._pathmap[loc] = MapperEnt(loc, tgt, "File")
184 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
187 class VwdPathMapper(StagingPathMapper):
188 def setup(self, referenced_files, basedir):
189 # type: (List[Any], unicode) -> None
191 # Go through each file and set the target to its own directory along
192 # with any secondary files.
193 self.visitlisting(referenced_files, self.stagedir, basedir)
195 for path, (ab, tgt, type) in self._pathmap.items():
196 if type in ("File", "Directory") and ab.startswith("keep:"):
197 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type)
200 class NoFollowPathMapper(StagingPathMapper):
202 def setup(self, referenced_files, basedir):
203 # type: (List[Any], unicode) -> None
204 self.visitlisting(referenced_files, self.stagedir, basedir)