Merge branch 'master' into 9998-unsigned_manifest
[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 schema_salad.sourceline import SourceLine
10
11 from cwltool.pathmapper import PathMapper, MapperEnt, abspath, adjustFileObjs, adjustDirObjs
12 from cwltool.workflow import WorkflowException
13
14 logger = logging.getLogger('arvados.cwl-runner')
15
16 class ArvPathMapper(PathMapper):
17     """Convert container-local paths to and from Keep collection ids."""
18
19     pdh_path = re.compile(r'^keep:[0-9a-f]{32}\+\d+/.+$')
20     pdh_dirpath = re.compile(r'^keep:[0-9a-f]{32}\+\d+(/.+)?$')
21
22     def __init__(self, arvrunner, referenced_files, input_basedir,
23                  collection_pattern, file_pattern, name=None, **kwargs):
24         self.arvrunner = arvrunner
25         self.input_basedir = input_basedir
26         self.collection_pattern = collection_pattern
27         self.file_pattern = file_pattern
28         self.name = name
29         super(ArvPathMapper, self).__init__(referenced_files, input_basedir, None)
30
31     def visit(self, srcobj, uploadfiles):
32         src = srcobj["location"]
33         if srcobj["class"] == "File":
34             if "#" in src:
35                 src = src[:src.index("#")]
36             if isinstance(src, basestring) and ArvPathMapper.pdh_path.match(src):
37                 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "File")
38             if src not in self._pathmap:
39                 # Local FS ref, may need to be uploaded or may be on keep
40                 # mount.
41                 ab = abspath(src, self.input_basedir)
42                 st = arvados.commands.run.statfile("", ab, fnPattern="keep:%s/%s")
43                 with SourceLine(srcobj, "location", WorkflowException):
44                     if isinstance(st, arvados.commands.run.UploadFile):
45                         uploadfiles.add((src, ab, st))
46                     elif isinstance(st, arvados.commands.run.ArvFile):
47                         self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % st.fn[5:], "File")
48                     elif src.startswith("_:"):
49                         if "contents" in srcobj:
50                             pass
51                         else:
52                             raise WorkflowException("File literal '%s' is missing contents" % src)
53                     elif src.startswith("arvwf:"):
54                         self._pathmap[src] = MapperEnt(src, src, "File")
55                     else:
56                         raise WorkflowException("Input file path '%s' is invalid" % st)
57             if "secondaryFiles" in srcobj:
58                 for l in srcobj["secondaryFiles"]:
59                     self.visit(l, uploadfiles)
60         elif srcobj["class"] == "Directory":
61             if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
62                 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "Directory")
63             for l in srcobj.get("listing", []):
64                 self.visit(l, uploadfiles)
65
66     def addentry(self, obj, c, path, subdirs):
67         if obj["location"] in self._pathmap:
68             src, srcpath = self.arvrunner.fs_access.get_collection(self._pathmap[obj["location"]].resolved)
69             if srcpath == "":
70                 srcpath = "."
71             c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
72             for l in obj.get("secondaryFiles", []):
73                 self.addentry(l, c, path, subdirs)
74         elif obj["class"] == "Directory":
75             for l in obj["listing"]:
76                 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
77             subdirs.append((obj["location"], path + "/" + obj["basename"]))
78         elif obj["location"].startswith("_:") and "contents" in obj:
79             with c.open(path + "/" + obj["basename"], "w") as f:
80                 f.write(obj["contents"].encode("utf-8"))
81         else:
82             raise SourceLine(obj, "location", WorkflowException).makeError("Don't know what to do with '%s'" % obj["location"])
83
84     def setup(self, referenced_files, basedir):
85         # type: (List[Any], unicode) -> None
86         uploadfiles = set()
87
88         for k,v in self.arvrunner.get_uploaded().iteritems():
89             self._pathmap[k] = MapperEnt(v.resolved, self.collection_pattern % v.resolved[5:], "File")
90
91         for srcobj in referenced_files:
92             self.visit(srcobj, uploadfiles)
93
94         if uploadfiles:
95             arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
96                                              self.arvrunner.api,
97                                              dry_run=False,
98                                              num_retries=self.arvrunner.num_retries,
99                                              fnPattern="keep:%s/%s",
100                                              name=self.name,
101                                              project=self.arvrunner.project_uuid)
102
103         for src, ab, st in uploadfiles:
104             self._pathmap[src] = MapperEnt(st.fn, self.collection_pattern % st.fn[5:], "File")
105             self.arvrunner.add_uploaded(src, self._pathmap[src])
106
107         for srcobj in referenced_files:
108             if srcobj["class"] == "Directory":
109                 if srcobj["location"] not in self._pathmap:
110                     c = arvados.collection.Collection(api_client=self.arvrunner.api,
111                                                       keep_client=self.arvrunner.keep_client,
112                                                       num_retries=self.arvrunner.num_retries)
113                     subdirs = []
114                     for l in srcobj["listing"]:
115                         self.addentry(l, c, ".", subdirs)
116
117                     check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
118                     if not check["items"]:
119                         c.save_new(owner_uuid=self.arvrunner.project_uuid)
120
121                     ab = self.collection_pattern % c.portable_data_hash()
122                     self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "Directory")
123                     for loc, sub in subdirs:
124                         ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
125                         self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
126             elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
127                 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
128
129                 c = arvados.collection.Collection(api_client=self.arvrunner.api,
130                                                   keep_client=self.arvrunner.keep_client,
131                                                   num_retries=self.arvrunner.num_retries                                                  )
132                 subdirs = []
133                 self.addentry(srcobj, c, ".", subdirs)
134
135                 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
136                 if not check["items"]:
137                     c.save_new(owner_uuid=self.arvrunner.project_uuid)
138
139                 ab = self.file_pattern % (c.portable_data_hash(), srcobj["basename"])
140                 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "File")
141                 if srcobj.get("secondaryFiles"):
142                     ab = self.collection_pattern % c.portable_data_hash()
143                     self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt(ab, ab, "Directory")
144                 for loc, sub in subdirs:
145                     ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
146                     self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
147
148         self.keepdir = None
149
150     def reversemap(self, target):
151         if target.startswith("keep:"):
152             return (target, target)
153         elif self.keepdir and target.startswith(self.keepdir):
154             return (target, "keep:" + target[len(self.keepdir)+1:])
155         else:
156             return super(ArvPathMapper, self).reversemap(target)
157
158 class StagingPathMapper(PathMapper):
159     _follow_dirs = True
160
161     def visit(self, obj, stagedir, basedir, copy=False):
162         # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
163         loc = obj["location"]
164         tgt = os.path.join(stagedir, obj["basename"])
165         if obj["class"] == "Directory":
166             self._pathmap[loc] = MapperEnt(loc, tgt, "Directory")
167             if loc.startswith("_:") or self._follow_dirs:
168                 self.visitlisting(obj.get("listing", []), tgt, basedir)
169         elif obj["class"] == "File":
170             if loc in self._pathmap:
171                 return
172             if "contents" in obj and loc.startswith("_:"):
173                 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile")
174             else:
175                 if copy:
176                     self._pathmap[loc] = MapperEnt(loc, tgt, "WritableFile")
177                 else:
178                     self._pathmap[loc] = MapperEnt(loc, tgt, "File")
179                 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
180
181
182 class InitialWorkDirPathMapper(StagingPathMapper):
183     def setup(self, referenced_files, basedir):
184         # type: (List[Any], unicode) -> None
185
186         # Go through each file and set the target to its own directory along
187         # with any secondary files.
188         self.visitlisting(referenced_files, self.stagedir, basedir)
189
190         for path, (ab, tgt, type) in self._pathmap.items():
191             if type in ("File", "Directory") and ab.startswith("keep:"):
192                 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type)
193
194
195 class FinalOutputPathMapper(StagingPathMapper):
196     _follow_dirs = False
197     def setup(self, referenced_files, basedir):
198         # type: (List[Any], unicode) -> None
199         self.visitlisting(referenced_files, self.stagedir, basedir)