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 if src.startswith("file:"):
41 # Local FS ref, may need to be uploaded or may be on keep
43 ab = abspath(src, self.input_basedir)
44 st = arvados.commands.run.statfile("", ab,
45 fnPattern="keep:%s/%s",
46 dirPattern="keep:%s/%s")
47 with SourceLine(srcobj, "location", WorkflowException):
48 if isinstance(st, arvados.commands.run.UploadFile):
49 uploadfiles.add((src, ab, st))
50 elif isinstance(st, arvados.commands.run.ArvFile):
51 self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % st.fn[5:], "File", True)
53 raise WorkflowException("Input file path '%s' is invalid" % st)
54 elif src.startswith("_:"):
55 if "contents" in srcobj:
58 raise WorkflowException("File literal '%s' is missing contents" % src)
60 self._pathmap[src] = MapperEnt(src, src, "File", True)
62 with SourceLine(srcobj, "secondaryFiles", WorkflowException):
63 for l in srcobj.get("secondaryFiles", []):
64 self.visit(l, uploadfiles)
65 with SourceLine(srcobj, "listing", WorkflowException):
66 for l in srcobj.get("listing", []):
67 self.visit(l, uploadfiles)
69 def addentry(self, obj, c, path, subdirs):
70 if obj["location"] in self._pathmap:
71 src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
74 c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
75 for l in obj.get("secondaryFiles", []):
76 self.addentry(l, c, path, subdirs)
77 elif obj["class"] == "Directory":
78 for l in obj.get("listing", []):
79 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
80 subdirs.append((obj["location"], path + "/" + obj["basename"]))
81 elif obj["location"].startswith("_:") and "contents" in obj:
82 with c.open(path + "/" + obj["basename"], "w") as f:
83 f.write(obj["contents"].encode("utf-8"))
85 raise SourceLine(obj, "location", WorkflowException).makeError("Don't know what to do with '%s'" % obj["location"])
87 def setup(self, referenced_files, basedir):
88 # type: (List[Any], unicode) -> None
91 already_uploaded = self.arvrunner.get_uploaded()
92 for k in referenced_files:
94 if loc in already_uploaded:
95 v = already_uploaded[loc]
96 self._pathmap[loc] = MapperEnt(v.resolved, self.collection_pattern % v.resolved[5:], "File", True)
98 for srcobj in referenced_files:
99 self.visit(srcobj, uploadfiles)
102 arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
105 num_retries=self.arvrunner.num_retries,
106 fnPattern="keep:%s/%s",
108 project=self.arvrunner.project_uuid)
110 for src, ab, st in uploadfiles:
111 self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % st.keepref,
112 "Directory" if os.path.isdir(ab) else "File", True)
113 self.arvrunner.add_uploaded(src, self._pathmap[src])
115 for srcobj in referenced_files:
117 if srcobj["class"] == "Directory":
118 if srcobj["location"] not in self._pathmap:
119 c = arvados.collection.Collection(api_client=self.arvrunner.api,
120 keep_client=self.arvrunner.keep_client,
121 num_retries=self.arvrunner.num_retries)
122 for l in srcobj.get("listing", []):
123 self.addentry(l, c, ".", subdirs)
125 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
126 if not check["items"]:
127 c.save_new(owner_uuid=self.arvrunner.project_uuid)
129 ab = self.collection_pattern % c.portable_data_hash()
130 self._pathmap[srcobj["location"]] = MapperEnt("keep:"+c.portable_data_hash(), ab, "Directory", True)
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 )
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("keep:%s/%s" % (c.portable_data_hash(), srcobj["basename"]),
146 if srcobj.get("secondaryFiles"):
147 ab = self.collection_pattern % c.portable_data_hash()
148 self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt("keep:"+c.portable_data_hash(), ab, "Directory", True)
151 for loc, sub in subdirs:
152 # subdirs will all start with "./", strip it off
153 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
154 self._pathmap[loc] = MapperEnt("keep:%s/%s" % (c.portable_data_hash(), sub[2:]),
155 ab, "Directory", True)
159 def reversemap(self, target):
160 if target.startswith("keep:"):
161 return (target, target)
162 elif self.keepdir and target.startswith(self.keepdir):
163 return (target, "keep:" + target[len(self.keepdir)+1:])
165 return super(ArvPathMapper, self).reversemap(target)
167 class StagingPathMapper(PathMapper):
170 def visit(self, obj, stagedir, basedir, copy=False, staged=False):
171 # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
172 loc = obj["location"]
173 tgt = os.path.join(stagedir, obj["basename"])
174 if obj["class"] == "Directory":
175 self._pathmap[loc] = MapperEnt(loc, tgt, "Directory", staged)
176 if loc.startswith("_:") or self._follow_dirs:
177 self.visitlisting(obj.get("listing", []), tgt, basedir)
178 elif obj["class"] == "File":
179 if loc in self._pathmap:
181 if "contents" in obj and loc.startswith("_:"):
182 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile", staged)
185 self._pathmap[loc] = MapperEnt(loc, tgt, "WritableFile", staged)
187 self._pathmap[loc] = MapperEnt(loc, tgt, "File", staged)
188 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
191 class VwdPathMapper(StagingPathMapper):
192 def setup(self, referenced_files, basedir):
193 # type: (List[Any], unicode) -> None
195 # Go through each file and set the target to its own directory along
196 # with any secondary files.
197 self.visitlisting(referenced_files, self.stagedir, basedir)
199 for path, (ab, tgt, type, staged) in self._pathmap.items():
200 if type in ("File", "Directory") and ab.startswith("keep:"):
201 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type, staged)
204 class NoFollowPathMapper(StagingPathMapper):
206 def setup(self, referenced_files, basedir):
207 # type: (List[Any], unicode) -> None
208 self.visitlisting(referenced_files, self.stagedir, basedir)