6 import arvados.commands.run
7 import arvados.collection
9 from cwltool.pathmapper import PathMapper, MapperEnt, abspath
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=self.file_pattern)
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(ab, st.fn, "File")
45 elif src.startswith("_:") and "contents" in srcobj:
48 raise WorkflowException("Input file path '%s' is invalid" % st)
49 if "secondaryFiles" in srcobj:
50 for l in srcobj["secondaryFiles"]:
51 self.visit(l, uploadfiles)
52 elif srcobj["class"] == "Directory":
53 if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
54 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "Directory")
55 for l in srcobj["listing"]:
56 self.visit(l, uploadfiles)
58 def addentry(self, obj, c, path, subdirs):
59 if obj["location"] in self._pathmap:
60 src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
61 c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
62 for l in obj.get("secondaryFiles", []):
63 self.addentry(l, c, path, subdirs)
64 elif obj["class"] == "Directory":
65 for l in obj["listing"]:
66 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
67 subdirs.append((obj["location"], path + "/" + obj["basename"]))
68 elif obj["location"].startswith("_:") and "contents" in obj:
69 with c.open(path + "/" + obj["basename"], "w") as f:
70 f.write(obj["contents"].encode("utf-8"))
72 raise WorkflowException("Don't know what to do with '%s'" % obj["location"])
74 def setup(self, referenced_files, basedir):
75 # type: (List[Any], unicode) -> None
76 self._pathmap = self.arvrunner.get_uploaded()
79 for srcobj in referenced_files:
80 self.visit(srcobj, uploadfiles)
83 arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
86 num_retries=self.arvrunner.num_retries,
87 fnPattern=self.file_pattern,
89 project=self.arvrunner.project_uuid)
91 for src, ab, st in uploadfiles:
92 self._pathmap[src] = MapperEnt("keep:" + st.keepref, st.fn, "File")
93 self.arvrunner.add_uploaded(src, self._pathmap[src])
95 for srcobj in referenced_files:
96 if srcobj["class"] == "Directory":
97 if srcobj["location"] not in self._pathmap:
98 c = arvados.collection.Collection(api_client=self.arvrunner.api,
99 num_retries=self.arvrunner.num_retries)
101 for l in srcobj["listing"]:
102 self.addentry(l, c, ".", subdirs)
104 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
105 if not check["items"]:
106 c.save_new(owner_uuid=self.arvrunner.project_uuid)
108 ab = self.collection_pattern % c.portable_data_hash()
109 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "Directory")
110 for loc, sub in subdirs:
111 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
112 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
113 elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
114 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
116 c = arvados.collection.Collection(api_client=self.arvrunner.api,
117 num_retries=self.arvrunner.num_retries )
119 self.addentry(srcobj, 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.file_pattern % (c.portable_data_hash(), srcobj["basename"])
126 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "File")
127 if srcobj.get("secondaryFiles"):
128 ab = self.collection_pattern % c.portable_data_hash()
129 self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt(ab, ab, "Directory")
130 for loc, sub in subdirs:
131 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
132 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
136 def reversemap(self, target):
137 if target.startswith("keep:"):
138 return (target, target)
139 elif self.keepdir and target.startswith(self.keepdir):
140 return (target, "keep:" + target[len(self.keepdir)+1:])
142 return super(ArvPathMapper, self).reversemap(target)
144 class InitialWorkDirPathMapper(PathMapper):
146 def visit(self, obj, stagedir, basedir, copy=False):
147 # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
148 if obj["class"] == "Directory":
149 self._pathmap[obj["location"]] = MapperEnt(obj["location"], stagedir, "Directory")
150 self.visitlisting(obj.get("listing", []), stagedir, basedir)
151 elif obj["class"] == "File":
152 loc = obj["location"]
153 if loc in self._pathmap:
155 tgt = os.path.join(stagedir, obj["basename"])
156 if "contents" in obj and obj["location"].startswith("_:"):
157 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile")
160 self._pathmap[loc] = MapperEnt(obj["path"], tgt, "WritableFile")
162 self._pathmap[loc] = MapperEnt(obj["path"], tgt, "File")
163 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
165 def setup(self, referenced_files, basedir):
166 # type: (List[Any], unicode) -> None
168 # Go through each file and set the target to its own directory along
169 # with any secondary files.
170 stagedir = self.stagedir
171 for fob in referenced_files:
172 self.visit(fob, stagedir, basedir)
174 for path, (ab, tgt, type) in self._pathmap.items():
175 if type in ("File", "Directory") and ab.startswith("keep:"):
176 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type)