Debian Codegraph @

gavo/protocols/datapack.py

raw
1 """
2 Dumping our resources to frictionless data packages (henceforce: datapack)
3 and loading from them again.
4
5 Specifications:
6
7 * https://specs.frictionlessdata.io/data-package/
8 * https://specs.frictionlessdata.io/data-resource/
9
10 DaCHS-generated RDs can be recognised by the presence of
11 a dachs-rd-id key in the global metadata. Also, we will always
12 write the RD as the first resource; for good measure, we also mark
13 it by having a dachs-resource-descriptor name.
14 """
15
16 #c Copyright 2008-2025, the GAVO project <[email protected]>
17 #c
18 #c This program is free software, covered by the GNU GPL. See the
19 #c COPYING file in the source distribution.
20
21
22 import glob
23 import json
24 import os
25 import shutil
26 import subprocess
27 import zipfile
28 from typing import Callable, Generator
29
30 from gavo import base
31 from gavo import rscdef
32 from gavo import rscdesc
33 from gavo import utils
34
35
36 def _perhaps(d:dict, key:str, val:str) -> None:
37 if val:
38 d[key] = val
39
40
41 def makeBasicMeta(rd:rscdesc.RD) -> dict:
42 """returns a basic, resource-less, datapack descriptor from an RD.
43 """
44 res = {
45 "dachs-resdir":
46 utils.getRelativePath(str(rd.resdir), base.getConfig("inputsDir")),
47 "name": rd.schema,
48 "homepage": base.makeAbsoluteURL("/browse/"+rd.sourceId),
49 # TODO: We'd like to have an custom profile for DaCHS. We'll
50 # need to put in a json schema for that, though. Look into it.
51 "profile": "data-package",
52 }
53
54 _perhaps(res, "id", base.getMetaText(rd, "doi", acceptSequence=True))
55
56 licenses = []
57 for item in rd.iterMeta("rights"):
58 try:
59 uriMeta = base.getMetaText(item, "rightsURI")
60 if uriMeta:
61 licenses.append(
62 {"path": str(uriMeta)})
63 except base.NoMetaKey:
64 pass
65 _perhaps(res, "licenses", licenses)
66
67 contributors = []
68 for item in rd.iterMeta("creator"):
69 contributors.append({
70 "title": base.getMetaText(item, "name", "Unknown"),
71 "role": "author"
72 })
73 _perhaps(res, "contributors", contributors)
74
75 subjects = []
76 for item in rd.iterMeta("subject"):
77 subjects.append(str(item))
78 _perhaps(res, "keywords", subjects)
79
80 for ourKW, theirKW in [
81 ("title", None),
82 ("description", None),
83 ("version", None),
84 ("creationDate", "created")]:
85 _perhaps(res, theirKW or ourKW,
86 base.getMetaText(rd, ourKW, acceptSequence=True))
87
88 return res
89
90
91 def namer(template:str) -> Callable[[], int]:
92 i = 0
93 while True:
94 yield template%i
95 i += 1
96
97
98 def iterExtraResources(rd:rscdesc.RD, cleanPath:Callable[[str], str]
99 ) -> Generator[dict, None, None]:
100 """yields datapack resources from the datapack-extrafiles property.
101
102 This is a json sequence, and files are only returned if they exist.
103 Directories are ignored.
104 """
105 makeName = namer("extrafile-%04d")
106 pathLiteral = rd.getProperty("datapack-extrafiles", None)
107 if pathLiteral is None:
108 return
109
110 patterns = json.loads(pathLiteral)
111
112 for pattern in patterns:
113 for match in glob.glob(rd.getAbsPath(pattern)):
114 if os.path.isfile(match):
115 yield {
116 "name": next(makeName),
117 "profile": "data-resource",
118 "path": cleanPath(match)
119 }
120
121
122 def iterRDResources(rd:rscdesc.RD) -> Generator[dict, None, None]:
123 """yields datapack resource descriptions for the RD and all
124 ancillary files we can discover.
125
126 All path names here are relative to the RD. Anything that is not in the
127 RD will not be exported (without serious trickery, that is).
128 """
129 resdir = os.path.normpath(rd.resdir)
130 def cleanPath(path):
131 return utils.getRelativePath(path, resdir, liberalChars=True)
132
133 # the RD itself
134 yield {
135 "name": "dachs-resource-descriptor",
136 "path": cleanPath(rd.srcPath),
137 "profile": "data-resource",
138 "title": "The DaCHS resource descriptor",
139 "mediatype": "text/xml",
140 }
141
142 # a README, if it's there
143 if os.path.exists(rd.getAbsPath("README")):
144 yield {
145 "name": "readme",
146 "path": "README",
147 "profile": "data-resource",
148 "mediatype": "text/plain",
149 }
150
151 # Manually added files
152 for res in iterExtraResources(rd, cleanPath):
153 yield res
154
155 # extra instrumentation in getDRForDump creates the filesLoaded
156 # attribute, which we use to add ancillary files used by the RD
157 # TODO: catch a few more and add them in getRDForDump
158 makeName = namer("rdaux-%02d")
159
160 # filesLoaded are uniquefied because, e.g., multiple data
161 # elements might use the same custom grammar.
162 for extra in sorted(set(rd.filesLoaded)):
163 fullPath = os.path.join(rd.resdir, extra)
164 # hack: external python modules drop the .py in the attribute value
165 if not os.path.exists(fullPath) and os.path.exists(fullPath+".py"):
166 extra = extra+".py"
167
168 yield {
169 "name": next(makeName),
170 "profile": "data-resource",
171 "path": extra,
172 }
173
174 # files imported
175 makeName = namer("data-%05d")
176 for dd in rd.dds:
177 if dd.sources and dd.sources.ignoredSources.ignoresVaryingStuff():
178 base.ui.notifyWarning(
179 "data %s#%s ignored because of dynamic ignoreSources"%(
180 rd.sourceId, dd.id))
181 continue
182
183 for source in dd.iterSources():
184 if isinstance(source, str) and os.path.exists(source):
185 yield {
186 "name": next(makeName),
187 "profile": "data-resource",
188 "path": cleanPath(source)}
189
190 else:
191 # it's probably some artificial source token; don't even
192 # bother to report anything looks weird.
193 pass
194
195
196 def makeDescriptor(rd:rscdesc.RD) -> dict:
197 """returns a datapack descriptor in a python dictionary.
198 """
199 desc = makeBasicMeta(rd)
200 desc["resources"] = list(iterRDResources(rd))
201 return desc
202
203
204 def getRDForDump(rdId:str) -> rscdesc.RD:
205 """loads an RD for later dumping.
206
207 The main thing this does is instrument ResdirRelativeAttribute
208 (and possibly later other things) to record what ancillary
209 data the RD has loaded.
210
211 This is, of course, not thread-safe or anything, and it could collect
212 false positives when RDs reference or include other RDs.
213
214 Only use it while making datapacks.
215 """
216 origParse = rscdef.ResdirRelativeAttribute.parse
217 filesLoaded = []
218
219 def record(self, val):
220 # When RDs pull in other RDs, we're hosed: if we add the other
221 # RDs, it's a total mess and we'd have to create other resdirs
222 # and all. If we don't, the datapacks won't work unless the
223 # other resources are present on the target systems. Well,
224 # rather avoid the total mess by suppressing files coming
225 # from other RDs; and we know other RDs are parsing by looking
226 # at into rcdesc's guts.
227 if len(rscdesc._CURRENTLY_PARSING)==1:
228 filesLoaded.append(val)
229 return origParse(self, val)
230
231 try:
232 rscdef.ResdirRelativeAttribute.parse = record
233 rd = rscdef.getReferencedElement(rdId, forceType=rscdesc.RD)
234 rd.filesLoaded = filesLoaded
235 finally:
236 rscdef.ResdirRelativeAttribute.parse = origParse
237
238 return rd
239
240
241 def dumpPackage(rdId:str, destFile) -> None:
242 """write a zip of the complete data package for a resource descriptor
243 to destFile.
244
245 destFile an be anything that zip.ZipFile accepts in w mode.
246 """
247 with zipfile.ZipFile(destFile, "w") as dest:
248 rd = getRDForDump(rdId)
249 descriptor = makeDescriptor(rd)
250 dest.writestr("datapackage.json", json.dumps(descriptor))
251
252 for rsc in descriptor["resources"]:
253 dest.write(
254 os.path.join(rd.resdir, rsc["path"]),
255 rsc["path"])
256
257
258 def getPackageMeta(packageName:str) -> dict:
259 """returns a dict of DaCHS-specific metadata items from a DaCHS-produced
260 data package.
261 """
262 res = {}
263 try:
264 with zipfile.ZipFile(packageName, "r") as archive:
265 with archive.open("datapackage.json") as f:
266 packageMeta = json.load(f)
267
268 if "dachs-resdir" not in packageMeta:
269 raise ValueError("Need dachs-resdir key in package meta")
270 res["resdir"] = packageMeta["dachs-resdir"]
271
272 try:
273 res0 = packageMeta["resources"][0]
274 except (IndexError, KeyError):
275 raise ValueError("Data package without resources")
276
277 if res0["name"]!="dachs-resource-descriptor":
278 raise ValueError("First data package resource isn't a DaCHS RD")
279
280 res["rdpath"] = res0["path"]
281 except Exception as ex:
282 raise base.ui.logOldExc(
283 base.ReportableError("%s is not a data package produced by DaCHS"
284 " (or, if it was, DaCHS is broken and you should"
285 " complain)"%packageName,
286 hint="Here is what failed in the background: %s"%ex))
287
288 return res
289
290
291 @utils.exposedFunction([
292 utils.Arg("id", help="Absolute RD id to produce a datapack for"),
293 utils.Arg("dest", help="Name of a zip file to dump to")],
294 help="Produce a frictionless data package for the RD and the data"
295 " it imports.")
296 def create(args:list):
297 with open(args.dest, "wb") as dest:
298 dumpPackage(args.id, dest)
299
300
301 @utils.exposedFunction([
302 utils.Arg("source", help="Name of a DaCHS-produced data package zip file."),
303 utils.Arg("-t", "--no-test", help="Do not run tests after importing.",
304 dest="suppressTests", action="store_true"),
305 utils.Arg("--force", help="If the resdir the package declares already"
306 " exists, remove it before unpacking (rather than bailing out).",
307 dest="removeResdir", action="store_true"),],
308 help="Load and import a data package. This only works for data packages"
309 " actually produced by DaCHS.")
310 def load(args:list):
311 packageMeta = getPackageMeta(args.source)
312
313 absSource = os.path.abspath(args.source)
314 os.chdir(base.getConfig("inputsDir"))
315 if os.path.exists(packageMeta["resdir"]):
316 if args.removeResdir:
317 shutil.rmtree(packageMeta["resdir"])
318 else:
319 raise base.ReportableError(
320 "Refusing to overwrite directory '%s'"%packageMeta["resdir"],
321 hint="The data package is for a resource living in this resource"
322 " directory, and it can only run there. However, that directory"
323 " already exists. Move it away and try again.")
324 base.makeSharedDir(packageMeta["resdir"])
325 os.chdir(packageMeta["resdir"])
326
327 subprocess.run(["unzip", absSource], check=True)
328
329 subprocess.run(["dachs", "imp", packageMeta["rdpath"]], check=True)
330 if not args.suppressTests:
331 subprocess.run(["dachs", "test", "-v", packageMeta["rdpath"]])
332
333
334 def main():
335 """does the cli interaction.
336 """
337 args = utils.makeCLIParser(globals()).parse_args()
338 args.subAction(args)