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"]
33 if srcobj["class"] == "File":
35 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:], "File")
38 if src not in self._pathmap:
39 # Local FS ref, may need to be uploaded or may be on keep
41 ab = abspath(src, self.input_basedir)
42 st = arvados.commands.run.statfile("", ab, fnPattern="keep:%s/%s")
43 with SourceLine(srcobj, "location", WorkflowException):
44 if isinstance(st, arvados.commands.run.UploadFile):
45 uploadfiles.add((src, ab, st))
46 elif isinstance(st, arvados.commands.run.ArvFile):
47 self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % st.fn[5:], "File")
48 elif src.startswith("_:"):
49 if "contents" in srcobj:
52 raise WorkflowException("File literal '%s' is missing contents" % src)
53 elif src.startswith("arvwf:"):
54 self._pathmap[src] = MapperEnt(src, src, "File")
56 raise WorkflowException("Input file path '%s' is invalid" % st)
57 if "secondaryFiles" in srcobj:
58 for l in srcobj["secondaryFiles"]:
59 self.visit(l, uploadfiles)
60 elif srcobj["class"] == "Directory":
61 if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
62 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "Directory")
63 for l in srcobj.get("listing", []):
64 self.visit(l, uploadfiles)
66 def addentry(self, obj, c, path, subdirs):
67 if obj["location"] in self._pathmap:
68 src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
71 c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
72 for l in obj.get("secondaryFiles", []):
73 self.addentry(l, c, path, subdirs)
74 elif obj["class"] == "Directory":
75 for l in obj["listing"]:
76 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
77 subdirs.append((obj["location"], path + "/" + obj["basename"]))
78 elif obj["location"].startswith("_:") and "contents" in obj:
79 with c.open(path + "/" + obj["basename"], "w") as f:
80 f.write(obj["contents"].encode("utf-8"))
82 raise SourceLine(obj, "location", WorkflowException).makeError("Don't know what to do with '%s'" % obj["location"])
84 def setup(self, referenced_files, basedir):
85 # type: (List[Any], unicode) -> None
88 already_uploaded = self.arvrunner.get_uploaded()
89 for k in referenced_files:
91 if loc in already_uploaded:
92 v = already_uploaded[loc]
93 self._pathmap[loc] = MapperEnt(v.resolved, self.collection_pattern % v.resolved[5:], "File")
95 for srcobj in referenced_files:
96 self.visit(srcobj, uploadfiles)
99 arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
102 num_retries=self.arvrunner.num_retries,
103 fnPattern="keep:%s/%s",
105 project=self.arvrunner.project_uuid)
107 for src, ab, st in uploadfiles:
108 self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % st.fn[5:], "File")
109 self.arvrunner.add_uploaded(src, self._pathmap[src])
111 for srcobj in referenced_files:
112 if srcobj["class"] == "Directory":
113 if srcobj["location"] not in self._pathmap:
114 c = arvados.collection.Collection(api_client=self.arvrunner.api,
115 keep_client=self.arvrunner.keep_client,
116 num_retries=self.arvrunner.num_retries)
118 for l in srcobj["listing"]:
119 self.addentry(l, c, ".", subdirs)
121 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
122 if not check["items"]:
123 c.save_new(owner_uuid=self.arvrunner.project_uuid)
125 ab = self.collection_pattern % c.portable_data_hash()
126 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "Directory")
127 for loc, sub in subdirs:
128 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
129 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
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 )
137 self.addentry(srcobj, c, ".", subdirs)
139 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
140 if not check["items"]:
141 c.save_new(owner_uuid=self.arvrunner.project_uuid)
143 ab = self.file_pattern % (c.portable_data_hash(), srcobj["basename"])
144 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "File")
145 if srcobj.get("secondaryFiles"):
146 ab = self.collection_pattern % c.portable_data_hash()
147 self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt(ab, ab, "Directory")
148 for loc, sub in subdirs:
149 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
150 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
154 def reversemap(self, target):
155 if target.startswith("keep:"):
156 return (target, target)
157 elif self.keepdir and target.startswith(self.keepdir):
158 return (target, "keep:" + target[len(self.keepdir)+1:])
160 return super(ArvPathMapper, self).reversemap(target)
162 class StagingPathMapper(PathMapper):
165 def visit(self, obj, stagedir, basedir, copy=False):
166 # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
167 loc = obj["location"]
168 tgt = os.path.join(stagedir, obj["basename"])
169 if obj["class"] == "Directory":
170 self._pathmap[loc] = MapperEnt(loc, tgt, "Directory")
171 if loc.startswith("_:") or self._follow_dirs:
172 self.visitlisting(obj.get("listing", []), tgt, basedir)
173 elif obj["class"] == "File":
174 if loc in self._pathmap:
176 if "contents" in obj and loc.startswith("_:"):
177 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile")
180 self._pathmap[loc] = MapperEnt(loc, tgt, "WritableFile")
182 self._pathmap[loc] = MapperEnt(loc, tgt, "File")
183 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
186 class VwdPathMapper(StagingPathMapper):
187 def setup(self, referenced_files, basedir):
188 # type: (List[Any], unicode) -> None
190 # Go through each file and set the target to its own directory along
191 # with any secondary files.
192 self.visitlisting(referenced_files, self.stagedir, basedir)
194 for path, (ab, tgt, type) in self._pathmap.items():
195 if type in ("File", "Directory") and ab.startswith("keep:"):
196 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type)
199 class NoFollowPathMapper(StagingPathMapper):
201 def setup(self, referenced_files, basedir):
202 # type: (List[Any], unicode) -> None
203 self.visitlisting(referenced_files, self.stagedir, basedir)