9570: Support Directory and file literal features. Support
[arvados.git] / sdk / cwl / arvados_cwl / pathmapper.py
1 import re
2 import logging
3
4 import arvados.commands.run
5 import arvados.collection
6
7 from cwltool.pathmapper import PathMapper, MapperEnt, abspath
8 from cwltool.workflow import WorkflowException
9
10 logger = logging.getLogger('arvados.cwl-runner')
11
12 class ArvPathMapper(PathMapper):
13     """Convert container-local paths to and from Keep collection ids."""
14
15     pdh_path = re.compile(r'^keep:[0-9a-f]{32}\+\d+/.+$')
16     pdh_dirpath = re.compile(r'^keep:[0-9a-f]{32}\+\d+(/.+)?$')
17
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
24         self.name = name
25         super(ArvPathMapper, self).__init__(referenced_files, input_basedir, None)
26
27     def visit(self, srcobj, uploadfiles):
28         src = srcobj["location"]
29         if srcobj["class"] == "File":
30             if "#" in src:
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
36                 # mount.
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:
44                     pass
45                 else:
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")
53             else:
54                 for l in srcobj["listing"]:
55                     self.visit(l, uploadfiles)
56
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"))
70         else:
71             raise WorkflowException("Don't know what to do with '%s'" % obj["location"])
72
73     def setup(self, referenced_files, basedir):
74         # type: (List[Any], unicode) -> None
75         self._pathmap = self.arvrunner.get_uploaded()
76         uploadfiles = set()
77
78         for srcobj in referenced_files:
79             self.visit(srcobj, uploadfiles)
80
81         if uploadfiles:
82             arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
83                                              self.arvrunner.api,
84                                              dry_run=False,
85                                              num_retries=self.arvrunner.num_retries,
86                                              fnPattern=self.file_pattern,
87                                              name=self.name,
88                                              project=self.arvrunner.project_uuid)
89
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])
93
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)
99                     subdirs = []
100                     for l in srcobj["listing"]:
101                         self.addentry(l, c, ".", subdirs)
102
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)
106
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)):
114
115                 c = arvados.collection.Collection(api_client=self.arvrunner.api,
116                                                   num_retries=self.arvrunner.num_retries                                                  )
117                 subdirs = []
118                 self.addentry(srcobj, c, ".", subdirs)
119
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)
123
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")
129
130         self.keepdir = None
131
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:])
137         else:
138             return super(ArvPathMapper, self).reversemap(target)