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="keep:%s/%s")
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(st.fn, self.collection_pattern % st.fn[5:], "File")
45 elif src.startswith("_:"):
46 if "contents" in srcobj:
49 raise WorkflowException("File literal '%s' is missing contents" % src)
50 elif src.startswith("arvwf:"):
51 self._pathmap[src] = MapperEnt(src, src, "File")
53 raise WorkflowException("Input file path '%s' is invalid" % st)
54 if "secondaryFiles" in srcobj:
55 for l in srcobj["secondaryFiles"]:
56 self.visit(l, uploadfiles)
57 elif srcobj["class"] == "Directory":
58 if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
59 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "Directory")
60 for l in srcobj.get("listing", []):
61 self.visit(l, uploadfiles)
63 def addentry(self, obj, c, path, subdirs):
64 if obj["location"] in self._pathmap:
65 src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
68 c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
69 for l in obj.get("secondaryFiles", []):
70 self.addentry(l, c, path, subdirs)
71 elif obj["class"] == "Directory":
72 for l in obj["listing"]:
73 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
74 subdirs.append((obj["location"], path + "/" + obj["basename"]))
75 elif obj["location"].startswith("_:") and "contents" in obj:
76 with c.open(path + "/" + obj["basename"], "w") as f:
77 f.write(obj["contents"].encode("utf-8"))
79 raise WorkflowException("Don't know what to do with '%s'" % obj["location"])
81 def setup(self, referenced_files, basedir):
82 # type: (List[Any], unicode) -> None
85 for k,v in self.arvrunner.get_uploaded().iteritems():
86 self._pathmap[k] = MapperEnt(v.resolved, self.collection_pattern % v.resolved[5:], "File")
88 for srcobj in referenced_files:
89 self.visit(srcobj, uploadfiles)
92 arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
95 num_retries=self.arvrunner.num_retries,
96 fnPattern="keep:%s/%s",
98 project=self.arvrunner.project_uuid)
100 for src, ab, st in uploadfiles:
101 self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % st.fn[5:], "File")
102 self.arvrunner.add_uploaded(src, self._pathmap[src])
104 for srcobj in referenced_files:
105 if srcobj["class"] == "Directory":
106 if srcobj["location"] not in self._pathmap:
107 c = arvados.collection.Collection(api_client=self.arvrunner.api,
108 keep_client=self.arvrunner.keep_client,
109 num_retries=self.arvrunner.num_retries)
111 for l in srcobj["listing"]:
112 self.addentry(l, c, ".", subdirs)
114 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
115 if not check["items"]:
116 c.save_new(owner_uuid=self.arvrunner.project_uuid)
118 ab = self.collection_pattern % c.portable_data_hash()
119 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "Directory")
120 for loc, sub in subdirs:
121 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
122 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
123 elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
124 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
126 c = arvados.collection.Collection(api_client=self.arvrunner.api,
127 keep_client=self.arvrunner.keep_client,
128 num_retries=self.arvrunner.num_retries )
130 self.addentry(srcobj, c, ".", subdirs)
132 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
133 if not check["items"]:
134 c.save_new(owner_uuid=self.arvrunner.project_uuid)
136 ab = self.file_pattern % (c.portable_data_hash(), srcobj["basename"])
137 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "File")
138 if srcobj.get("secondaryFiles"):
139 ab = self.collection_pattern % c.portable_data_hash()
140 self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt(ab, ab, "Directory")
141 for loc, sub in subdirs:
142 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
143 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
147 def reversemap(self, target):
148 if target.startswith("keep:"):
149 return (target, target)
150 elif self.keepdir and target.startswith(self.keepdir):
151 return (target, "keep:" + target[len(self.keepdir)+1:])
153 return super(ArvPathMapper, self).reversemap(target)
155 class StagingPathMapper(PathMapper):
158 def visit(self, obj, stagedir, basedir, copy=False):
159 # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
160 loc = obj["location"]
161 tgt = os.path.join(stagedir, obj["basename"])
162 if obj["class"] == "Directory":
163 self._pathmap[loc] = MapperEnt(loc, tgt, "Directory")
164 if loc.startswith("_:") or self._follow_dirs:
165 self.visitlisting(obj.get("listing", []), tgt, basedir)
166 elif obj["class"] == "File":
167 if loc in self._pathmap:
169 if "contents" in obj and loc.startswith("_:"):
170 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile")
173 self._pathmap[loc] = MapperEnt(loc, tgt, "WritableFile")
175 self._pathmap[loc] = MapperEnt(loc, tgt, "File")
176 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
179 class InitialWorkDirPathMapper(StagingPathMapper):
180 def setup(self, referenced_files, basedir):
181 # type: (List[Any], unicode) -> None
183 # Go through each file and set the target to its own directory along
184 # with any secondary files.
185 self.visitlisting(referenced_files, self.stagedir, basedir)
187 for path, (ab, tgt, type) in self._pathmap.items():
188 if type in ("File", "Directory") and ab.startswith("keep:"):
189 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type)
192 class FinalOutputPathMapper(StagingPathMapper):
194 def setup(self, referenced_files, basedir):
195 # type: (List[Any], unicode) -> None
196 self.visitlisting(referenced_files, self.stagedir, basedir)