4 import arvados.commands.run
5 import arvados.collection
7 from cwltool.pathmapper import PathMapper, MapperEnt, abspath
8 from cwltool.workflow import WorkflowException
10 logger = logging.getLogger('arvados.cwl-runner')
12 class ArvPathMapper(PathMapper):
13 """Convert container-local paths to and from Keep collection ids."""
15 pdh_path = re.compile(r'^keep:[0-9a-f]{32}\+\d+/.+$')
16 pdh_dirpath = re.compile(r'^keep:[0-9a-f]{32}\+\d+(/.+)?$')
18 def __init__(self, arvrunner, referenced_files, input_basedir,
19 collection_pattern, file_pattern, name=None, **kwargs):
20 self.arvrunner = arvrunner
21 self.input_basedir = input_basedir
22 self.collection_pattern = collection_pattern
23 self.file_pattern = file_pattern
25 super(ArvPathMapper, self).__init__(referenced_files, input_basedir, None)
27 def visit(self, srcobj, uploadfiles):
28 src = srcobj["location"]
29 if srcobj["class"] == "File":
31 src = src[:src.index("#")]
32 if isinstance(src, basestring) and ArvPathMapper.pdh_path.match(src):
33 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "File")
34 if src not in self._pathmap:
35 # Local FS ref, may need to be uploaded or may be on keep
37 ab = abspath(src, self.input_basedir)
38 st = arvados.commands.run.statfile("", ab, fnPattern=self.file_pattern)
39 if isinstance(st, arvados.commands.run.UploadFile):
40 uploadfiles.add((src, ab, st))
41 elif isinstance(st, arvados.commands.run.ArvFile):
42 self._pathmap[src] = MapperEnt(ab, st.fn, "File")
43 elif src.startswith("_:") and "contents" in srcobj:
46 raise WorkflowException("Input file path '%s' is invalid" % st)
47 if "secondaryFiles" in srcobj:
48 for l in srcobj["secondaryFiles"]:
49 self.visit(l, uploadfiles)
50 elif srcobj["class"] == "Directory":
51 if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
52 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "Directory")
54 for l in srcobj["listing"]:
55 self.visit(l, uploadfiles)
57 def addentry(self, obj, c, path, subdirs):
58 if obj["location"] in self._pathmap:
59 src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
60 c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
61 for l in obj.get("secondaryFiles", []):
62 self.addentry(l, c, path, subdirs)
63 elif obj["class"] == "Directory":
64 for l in obj["listing"]:
65 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
66 subdirs.append((obj["location"], path + "/" + obj["basename"]))
67 elif obj["location"].startswith("_:") and "contents" in obj:
68 with c.open(path + "/" + obj["basename"], "w") as f:
69 f.write(obj["contents"].encode("utf-8"))
71 raise WorkflowException("Don't know what to do with '%s'" % obj["location"])
73 def setup(self, referenced_files, basedir):
74 # type: (List[Any], unicode) -> None
75 self._pathmap = self.arvrunner.get_uploaded()
78 for srcobj in referenced_files:
79 self.visit(srcobj, uploadfiles)
82 arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
85 num_retries=self.arvrunner.num_retries,
86 fnPattern=self.file_pattern,
88 project=self.arvrunner.project_uuid)
90 for src, ab, st in uploadfiles:
91 self._pathmap[src] = MapperEnt("keep:" + st.keepref, st.fn, "File")
92 self.arvrunner.add_uploaded(src, self._pathmap[src])
94 for srcobj in referenced_files:
95 if srcobj["class"] == "Directory":
96 if srcobj["location"] not in self._pathmap:
97 c = arvados.collection.Collection(api_client=self.arvrunner.api,
98 num_retries=self.arvrunner.num_retries)
100 for l in srcobj["listing"]:
101 self.addentry(l, c, ".", subdirs)
103 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
104 if not check["items"]:
105 c.save_new(owner_uuid=self.arvrunner.project_uuid)
107 ab = self.collection_pattern % c.portable_data_hash()
108 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "Directory")
109 for loc, sub in subdirs:
110 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
111 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
112 elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
113 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
115 c = arvados.collection.Collection(api_client=self.arvrunner.api,
116 num_retries=self.arvrunner.num_retries )
118 self.addentry(srcobj, c, ".", subdirs)
120 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
121 if not check["items"]:
122 c.save_new(owner_uuid=self.arvrunner.project_uuid)
124 ab = self.file_pattern % (c.portable_data_hash(), srcobj["basename"])
125 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "File")
126 for loc, sub in subdirs:
127 ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
128 self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
132 def reversemap(self, target):
133 if target.startswith("keep:"):
134 return (target, target)
135 elif self.keepdir and target.startswith(self.keepdir):
136 return (target, "keep:" + target[len(self.keepdir)+1:])
138 return super(ArvPathMapper, self).reversemap(target)