9514: update delete_old_job_logs task also to use the better performing sql.
[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
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=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:
46                     pass
47                 else:
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)
57
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             if srcpath == "":
62                 srcpath = "."
63             c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
64             for l in obj.get("secondaryFiles", []):
65                 self.addentry(l, c, path, subdirs)
66         elif obj["class"] == "Directory":
67             for l in obj["listing"]:
68                 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
69             subdirs.append((obj["location"], path + "/" + obj["basename"]))
70         elif obj["location"].startswith("_:") and "contents" in obj:
71             with c.open(path + "/" + obj["basename"], "w") as f:
72                 f.write(obj["contents"].encode("utf-8"))
73         else:
74             raise WorkflowException("Don't know what to do with '%s'" % obj["location"])
75
76     def setup(self, referenced_files, basedir):
77         # type: (List[Any], unicode) -> None
78         self._pathmap = self.arvrunner.get_uploaded()
79         uploadfiles = set()
80
81         for srcobj in referenced_files:
82             self.visit(srcobj, uploadfiles)
83
84         if uploadfiles:
85             arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
86                                              self.arvrunner.api,
87                                              dry_run=False,
88                                              num_retries=self.arvrunner.num_retries,
89                                              fnPattern=self.file_pattern,
90                                              name=self.name,
91                                              project=self.arvrunner.project_uuid)
92
93         for src, ab, st in uploadfiles:
94             self._pathmap[src] = MapperEnt("keep:" + st.keepref, st.fn, "File")
95             self.arvrunner.add_uploaded(src, self._pathmap[src])
96
97         for srcobj in referenced_files:
98             if srcobj["class"] == "Directory":
99                 if srcobj["location"] not in self._pathmap:
100                     c = arvados.collection.Collection(api_client=self.arvrunner.api,
101                                                       num_retries=self.arvrunner.num_retries)
102                     subdirs = []
103                     for l in srcobj["listing"]:
104                         self.addentry(l, c, ".", subdirs)
105
106                     check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
107                     if not check["items"]:
108                         c.save_new(owner_uuid=self.arvrunner.project_uuid)
109
110                     ab = self.collection_pattern % c.portable_data_hash()
111                     self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "Directory")
112                     for loc, sub in subdirs:
113                         ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
114                         self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
115             elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
116                 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
117
118                 c = arvados.collection.Collection(api_client=self.arvrunner.api,
119                                                   num_retries=self.arvrunner.num_retries                                                  )
120                 subdirs = []
121                 self.addentry(srcobj, c, ".", subdirs)
122
123                 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
124                 if not check["items"]:
125                     c.save_new(owner_uuid=self.arvrunner.project_uuid)
126
127                 ab = self.file_pattern % (c.portable_data_hash(), srcobj["basename"])
128                 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "File")
129                 if srcobj.get("secondaryFiles"):
130                     ab = self.collection_pattern % c.portable_data_hash()
131                     self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt(ab, ab, "Directory")
132                 for loc, sub in subdirs:
133                     ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
134                     self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
135
136         self.keepdir = None
137
138     def reversemap(self, target):
139         if target.startswith("keep:"):
140             return (target, target)
141         elif self.keepdir and target.startswith(self.keepdir):
142             return (target, "keep:" + target[len(self.keepdir)+1:])
143         else:
144             return super(ArvPathMapper, self).reversemap(target)
145
146 class InitialWorkDirPathMapper(PathMapper):
147
148     def visit(self, obj, stagedir, basedir, copy=False):
149         # type: (Dict[unicode, Any], unicode, unicode, bool) -> None
150         if obj["class"] == "Directory":
151             self._pathmap[obj["location"]] = MapperEnt(obj["location"], stagedir, "Directory")
152             self.visitlisting(obj.get("listing", []), stagedir, basedir)
153         elif obj["class"] == "File":
154             loc = obj["location"]
155             if loc in self._pathmap:
156                 return
157             tgt = os.path.join(stagedir, obj["basename"])
158             if "contents" in obj and obj["location"].startswith("_:"):
159                 self._pathmap[loc] = MapperEnt(obj["contents"], tgt, "CreateFile")
160             else:
161                 if copy:
162                     self._pathmap[loc] = MapperEnt(obj["path"], tgt, "WritableFile")
163                 else:
164                     self._pathmap[loc] = MapperEnt(obj["path"], tgt, "File")
165                 self.visitlisting(obj.get("secondaryFiles", []), stagedir, basedir)
166
167     def setup(self, referenced_files, basedir):
168         # type: (List[Any], unicode) -> None
169
170         # Go through each file and set the target to its own directory along
171         # with any secondary files.
172         stagedir = self.stagedir
173         for fob in referenced_files:
174             self.visit(fob, stagedir, basedir)
175
176         for path, (ab, tgt, type) in self._pathmap.items():
177             if type in ("File", "Directory") and ab.startswith("keep:"):
178                 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type)