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