Ensure column information is up-to-date before creating full text indexes. refs ...
[arvados.git] / sdk / cwl / arvados_cwl / pathmapper.py
1 import re
2 import logging
3 import uuid
4 import os
5
6 import arvados.commands.run
7 import arvados.collection
8
9 from cwltool.pathmapper import PathMapper, MapperEnt, abspath, adjustFileObjs, adjustDirObjs
10 from cwltool.workflow import WorkflowException
11
12 logger = logging.getLogger('arvados.cwl-runner')
13
14 class ArvPathMapper(PathMapper):
15     """Convert container-local paths to and from Keep collection ids."""
16
17     pdh_path = re.compile(r'^keep:[0-9a-f]{32}\+\d+/.+$')
18     pdh_dirpath = re.compile(r'^keep:[0-9a-f]{32}\+\d+(/.+)?$')
19
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
26         self.name = name
27         super(ArvPathMapper, self).__init__(referenced_files, input_basedir, None)
28
29     def visit(self, srcobj, uploadfiles):
30         src = srcobj["location"]
31         if srcobj["class"] == "File":
32             if "#" in src:
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
38                 # mount.
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:
47                         pass
48                     else:
49                         raise WorkflowException("File literal '%s' is missing contents" % src)
50                 elif src.startswith("arvwf:"):
51                     self._pathmap[src] = MapperEnt(src, src, "File")
52                 else:
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)
62
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)
66             if srcpath == "":
67                 srcpath = "."
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"))
78         else:
79             raise WorkflowException("Don't know what to do with '%s'" % obj["location"])
80
81     def setup(self, referenced_files, basedir):
82         # type: (List[Any], unicode) -> None
83         uploadfiles = set()
84
85         for k,v in self.arvrunner.get_uploaded().iteritems():
86             self._pathmap[k] = MapperEnt(v.resolved, self.collection_pattern % v.resolved[5:], "File")
87
88         for srcobj in referenced_files:
89             self.visit(srcobj, uploadfiles)
90
91         if uploadfiles:
92             arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
93                                              self.arvrunner.api,
94                                              dry_run=False,
95                                              num_retries=self.arvrunner.num_retries,
96                                              fnPattern="keep:%s/%s",
97                                              name=self.name,
98                                              project=self.arvrunner.project_uuid)
99
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])
103
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)
110                     subdirs = []
111                     for l in srcobj["listing"]:
112                         self.addentry(l, c, ".", subdirs)
113
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)
117
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)):
125
126                 c = arvados.collection.Collection(api_client=self.arvrunner.api,
127                                                   keep_client=self.arvrunner.keep_client,
128                                                   num_retries=self.arvrunner.num_retries                                                  )
129                 subdirs = []
130                 self.addentry(srcobj, c, ".", subdirs)
131
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)
135
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")
144
145         self.keepdir = None
146
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:])
152         else:
153             return super(ArvPathMapper, self).reversemap(target)
154
155 class StagingPathMapper(PathMapper):
156     _follow_dirs = True
157
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:
168                 return
169             if "contents" in obj and loc.startswith("_:"):
170                 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile")
171             else:
172                 if copy:
173                     self._pathmap[loc] = MapperEnt(loc, tgt, "WritableFile")
174                 else:
175                     self._pathmap[loc] = MapperEnt(loc, tgt, "File")
176                 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
177
178
179 class InitialWorkDirPathMapper(StagingPathMapper):
180     def setup(self, referenced_files, basedir):
181         # type: (List[Any], unicode) -> None
182
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)
186
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)
190
191
192 class FinalOutputPathMapper(StagingPathMapper):
193     _follow_dirs = False
194     def setup(self, referenced_files, basedir):
195         # type: (List[Any], unicode) -> None
196         self.visitlisting(referenced_files, self.stagedir, basedir)