Merge branch 'master' into 9369-arv-cwl-docs
[arvados.git] / sdk / cwl / arvados_cwl / pathmapper.py
1 import re
2 import logging
3 import uuid
4
5 import arvados.commands.run
6 import arvados.collection
7
8 from cwltool.pathmapper import PathMapper, MapperEnt, abspath
9 from cwltool.workflow import WorkflowException
10
11 logger = logging.getLogger('arvados.cwl-runner')
12
13 class ArvPathMapper(PathMapper):
14     """Convert container-local paths to and from Keep collection ids."""
15
16     pdh_path = re.compile(r'^keep:[0-9a-f]{32}\+\d+/.+$')
17     pdh_dirpath = re.compile(r'^keep:[0-9a-f]{32}\+\d+(/.+)?$')
18
19     def __init__(self, arvrunner, referenced_files, input_basedir,
20                  collection_pattern, file_pattern, name=None, **kwargs):
21         self.arvrunner = arvrunner
22         self.input_basedir = input_basedir
23         self.collection_pattern = collection_pattern
24         self.file_pattern = file_pattern
25         self.name = name
26         super(ArvPathMapper, self).__init__(referenced_files, input_basedir, None)
27
28     def visit(self, srcobj, uploadfiles):
29         src = srcobj["location"]
30         if srcobj["class"] == "File":
31             if "#" in src:
32                 src = src[:src.index("#")]
33             if isinstance(src, basestring) and ArvPathMapper.pdh_path.match(src):
34                 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "File")
35             if src not in self._pathmap:
36                 # Local FS ref, may need to be uploaded or may be on keep
37                 # mount.
38                 ab = abspath(src, self.input_basedir)
39                 st = arvados.commands.run.statfile("", ab, fnPattern=self.file_pattern)
40                 if isinstance(st, arvados.commands.run.UploadFile):
41                     uploadfiles.add((src, ab, st))
42                 elif isinstance(st, arvados.commands.run.ArvFile):
43                     self._pathmap[src] = MapperEnt(ab, st.fn, "File")
44                 elif src.startswith("_:") and "contents" in srcobj:
45                     pass
46                 else:
47                     raise WorkflowException("Input file path '%s' is invalid" % st)
48             if "secondaryFiles" in srcobj:
49                 for l in srcobj["secondaryFiles"]:
50                     self.visit(l, uploadfiles)
51         elif srcobj["class"] == "Directory":
52             if isinstance(src, basestring) and ArvPathMapper.pdh_dirpath.match(src):
53                 self._pathmap[src] = MapperEnt(src, self.collection_pattern % src[5:], "Directory")
54             else:
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             c.copy(srcpath, path + "/" + obj["basename"], source_collection=src, overwrite=True)
62             for l in obj.get("secondaryFiles", []):
63                 self.addentry(l, c, path, subdirs)
64         elif obj["class"] == "Directory":
65             for l in obj["listing"]:
66                 self.addentry(l, c, path + "/" + obj["basename"], subdirs)
67             subdirs.append((obj["location"], path + "/" + obj["basename"]))
68         elif obj["location"].startswith("_:") and "contents" in obj:
69             with c.open(path + "/" + obj["basename"], "w") as f:
70                 f.write(obj["contents"].encode("utf-8"))
71         else:
72             raise WorkflowException("Don't know what to do with '%s'" % obj["location"])
73
74     def setup(self, referenced_files, basedir):
75         # type: (List[Any], unicode) -> None
76         self._pathmap = self.arvrunner.get_uploaded()
77         uploadfiles = set()
78
79         for srcobj in referenced_files:
80             self.visit(srcobj, uploadfiles)
81
82         if uploadfiles:
83             arvados.commands.run.uploadfiles([u[2] for u in uploadfiles],
84                                              self.arvrunner.api,
85                                              dry_run=False,
86                                              num_retries=self.arvrunner.num_retries,
87                                              fnPattern=self.file_pattern,
88                                              name=self.name,
89                                              project=self.arvrunner.project_uuid)
90
91         for src, ab, st in uploadfiles:
92             self._pathmap[src] = MapperEnt("keep:" + st.keepref, st.fn, "File")
93             self.arvrunner.add_uploaded(src, self._pathmap[src])
94
95         for srcobj in referenced_files:
96             if srcobj["class"] == "Directory":
97                 if srcobj["location"] not in self._pathmap:
98                     c = arvados.collection.Collection(api_client=self.arvrunner.api,
99                                                       num_retries=self.arvrunner.num_retries)
100                     subdirs = []
101                     for l in srcobj["listing"]:
102                         self.addentry(l, c, ".", subdirs)
103
104                     check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
105                     if not check["items"]:
106                         c.save_new(owner_uuid=self.arvrunner.project_uuid)
107
108                     ab = self.collection_pattern % c.portable_data_hash()
109                     self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "Directory")
110                     for loc, sub in subdirs:
111                         ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
112                         self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
113             elif srcobj["class"] == "File" and (srcobj.get("secondaryFiles") or
114                 (srcobj["location"].startswith("_:") and "contents" in srcobj)):
115
116                 c = arvados.collection.Collection(api_client=self.arvrunner.api,
117                                                   num_retries=self.arvrunner.num_retries                                                  )
118                 subdirs = []
119                 self.addentry(srcobj, c, ".", subdirs)
120
121                 check = self.arvrunner.api.collections().list(filters=[["portable_data_hash", "=", c.portable_data_hash()]], limit=1).execute(num_retries=self.arvrunner.num_retries)
122                 if not check["items"]:
123                     c.save_new(owner_uuid=self.arvrunner.project_uuid)
124
125                 ab = self.file_pattern % (c.portable_data_hash(), srcobj["basename"])
126                 self._pathmap[srcobj["location"]] = MapperEnt(ab, ab, "File")
127                 if srcobj.get("secondaryFiles"):
128                     ab = self.collection_pattern % c.portable_data_hash()
129                     self._pathmap["_:" + unicode(uuid.uuid4())] = MapperEnt(ab, ab, "Directory")
130                 for loc, sub in subdirs:
131                     ab = self.file_pattern % (c.portable_data_hash(), sub[2:])
132                     self._pathmap[loc] = MapperEnt(ab, ab, "Directory")
133
134         self.keepdir = None
135
136     def reversemap(self, target):
137         if target.startswith("keep:"):
138             return (target, target)
139         elif self.keepdir and target.startswith(self.keepdir):
140             return (target, "keep:" + target[len(self.keepdir)+1:])
141         else:
142             return super(ArvPathMapper, self).reversemap(target)
143
144 class InitialWorkDirPathMapper(PathMapper):
145     def setup(self, referenced_files, basedir):
146         # type: (List[Any], unicode) -> None
147
148         # Go through each file and set the target to its own directory along
149         # with any secondary files.
150         stagedir = self.stagedir
151         for fob in referenced_files:
152             self.visit(fob, stagedir, basedir)
153
154         for path, (ab, tgt, type) in self._pathmap.items():
155             if type in ("File", "Directory") and ab.startswith("keep:"):
156                 self._pathmap[path] = MapperEnt("$(task.keep)/%s" % ab[5:], tgt, type)