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)
51 raise WorkflowException("Input file path '%s' is invalid" % st)
52 if "secondaryFiles" in srcobj:
53 for l in srcobj["secondaryFiles"]:
54 self.visit(l, uploadfiles)
55 elif srcobj["class"] == "Directory":
56 if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
57 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "Directory")
58 for l in srcobj.get("listing", []):
59 self.visit(l, uploadfiles)
61 def addentry(self, obj, c, path, subdirs):
62 if obj["location"] in self._pathmap:
63 src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
66 c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
67 for l in obj.get("secondaryFiles", []):
68 self.addentry(l, c, path, subdirs)
69 elif obj["class"] == "Directory":
70 for l in obj["listing"]:
71 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
72 subdirs.append((obj["location"], path + "/" + obj["basename"]))
73 elif obj["location"].startswith("_:") and "contents" in obj:
74 with c.open(path + "/" + obj["basename"], "w") as f:
75 f.write(obj["contents"].encode("utf-8"))
77 raise WorkflowException("Don't know what to do with '%s'" % obj["location"])
79 def setup(self, referenced_files, basedir):
80 # type: (List[Any], unicode) -> None
83 for k,v in self.arvrunner.get_uploaded().iteritems():
84 self._pathmap[k] = MapperEnt(v.resolved, self.collection_pattern % v.resolved[5:], "File")
86 for srcobj in referenced_files:
87 self.visit(srcobj, uploadfiles)
90 arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
93 num_retries=self.arvrunner.num_retries,
94 fnPattern="keep:%s/%s",
96 project=self.arvrunner.project_uuid)
98 for src, ab, st in uploadfiles:
99 self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % st.fn[5:], "File")
100 self.arvrunner.add_uploaded(src, self._pathmap[src])
102 for srcobj in referenced_files:
103 if srcobj["class"] == "Directory":
104 if srcobj["location"] not in self._pathmap:
105 c = arvados.collection.Collection(api_client=self.arvrunner.api,
106 keep_client=self.arvrunner.keep_client,
107 num_retries=self.arvrunner.num_retries)
109 for l in srcobj["listing"]:
110 self.addentry(l, c, ".", subdirs)
112 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
113 if not check["items"]:
114 c.save_new(owner_uuid=self.arvrunner.project_uuid)
116 ab = self.collection_pattern % c.portable_data_hash()
117 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "Directory")
118 for loc, sub in subdirs:
119 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
120 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
121 elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
122 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
124 c = arvados.collection.Collection(api_client=self.arvrunner.api,
125 keep_client=self.arvrunner.keep_client,
126 num_retries=self.arvrunner.num_retries )
128 self.addentry(srcobj, c, ".", subdirs)
130 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
131 if not check["items"]:
132 c.save_new(owner_uuid=self.arvrunner.project_uuid)
134 ab = self.file_pattern % (c.portable_data_hash(), srcobj["basename"])
135 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "File")
136 if srcobj.get("secondaryFiles"):
137 ab = self.collection_pattern % c.portable_data_hash()
138 self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt(ab, ab, "Directory")
139 for loc, sub in subdirs:
140 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
141 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
145 def reversemap(self, target):
146 if target.startswith("keep:"):
147 return (target, target)
148 elif self.keepdir and target.startswith(self.keepdir):
149 return (target, "keep:" + target[len(self.keepdir)+1:])
151 return super(ArvPathMapper, self).reversemap(target)
153 class StagingPathMapper(PathMapper):
156 def visit(self, obj, stagedir, basedir, copy=False):
157 # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
158 loc = obj["location"]
159 tgt = os.path.join(stagedir, obj["basename"])
160 if obj["class"] == "Directory":
161 self._pathmap[loc] = MapperEnt(loc, tgt, "Directory")
162 if loc.startswith("_:") or self._follow_dirs:
163 self.visitlisting(obj.get("listing", []), tgt, basedir)
164 elif obj["class"] == "File":
165 if loc in self._pathmap:
167 if "contents" in obj and loc.startswith("_:"):
168 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile")
171 self._pathmap[loc] = MapperEnt(loc, tgt, "WritableFile")
173 self._pathmap[loc] = MapperEnt(loc, tgt, "File")
174 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
177 class InitialWorkDirPathMapper(StagingPathMapper):
178 def setup(self, referenced_files, basedir):
179 # type: (List[Any], unicode) -> None
181 # Go through each file and set the target to its own directory along
182 # with any secondary files.
183 self.visitlisting(referenced_files, self.stagedir, basedir)
185 for path, (ab, tgt, type) in self._pathmap.items():
186 if type in ("File", "Directory") and ab.startswith("keep:"):
187 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type)
190 class FinalOutputPathMapper(StagingPathMapper):
192 def setup(self, referenced_files, basedir):
193 # type: (List[Any], unicode) -> None
194 self.visitlisting(referenced_files, self.stagedir, basedir)