Debian Codegraph @

gavo/rscdef/dddef.py

raw
1 """
2 Definition of data.
3
4 Data descriptors describe what to do with data. They contain
5 a grammar, information on where to obtain source data from, and "makes",
6 a specification of the tables to be generated and how they are made
7 from the grammar output.
8 """
9
10 #c Copyright 2008-2025, the GAVO project <[email protected]>
11 #c
12 #c This program is free software, covered by the GNU GPL. See the
13 #c COPYING file in the source distribution.
14
15
16 import datetime
17 import fnmatch
18 import glob
19 import itertools
20 import os
21
22 from gavo import base
23 from gavo import utils
24 from gavo.rscdef import builtingrammars
25 from gavo.rscdef import column
26 from gavo.rscdef import common
27 from gavo.rscdef import rmkdef
28 from gavo.rscdef import scripting
29 from gavo.rscdef import tabledef
30
31
32 class IgnoreSpec(base.Structure):
33 """A specification of sources to ignore.
34
35 Sources mentioned here are compared against the inputsDir-relative path
36 of sources generated by sources (cf. `Element sources`_). If there is
37 a match, the corresponding source will not be processed.
38
39 You can get ignored files from various sources. If you give more
40 than one source, the set of ignored files is the union of the the
41 individual sets.
42
43 fromdbUpdating is a bit special in that the query must return
44 UTC timestamps of the file's mtime during the last ingest in addition
45 to the accrefs (see the reference documentation for an example).
46
47 Macros are expanded in the RD.
48 """
49 name_ = "ignoreSources"
50
51 _fromdb = base.UnicodeAttribute("fromdb", default=None,
52 description="A DB query to obtain a set of sources to ignore; the"
53 " select clause must select exactly one column containing the"
54 " source key. See also `Using fromdb on ignoreSources`_",
55 copyable=True)
56 _fromdbUpdating = base.UnicodeAttribute("fromdbUpdating",
57 default=None, description="A DB query to obtain a set of sources"
58 " to ignore unless they the timestamp on disk is newer than"
59 " what's returned. The query given must return pairs of accrefs"
60 " and UTC timestamps of the last ingest. See also `Using fromdbUpdating"
61 " on ignoreSources`_", copyable=True)
62 _fromfile = common.ResdirRelativeAttribute("fromfile", default=None,
63 description="A name of a file containing blacklisted source"
64 " paths, one per line. Empty lines and lines beginning with a hash"
65 " are ignored. If you have foolishly used non-ASCII in your filenames:"
66 " The names in this file are interpreted as utf-8.", copyable=True)
67 _patterns = base.ListOfAtomsAttribute("patterns", description=
68 "Shell patterns to ignore. Slashes are treated like any other"
69 " character, i.e., patterns do not know about paths.",
70 itemAttD=base.UnicodeAttribute("pattern", description="Shell pattern"
71 " for source file(s), relative to resource directory."),
72 copyable=True)
73 _rd = common.RDAttribute()
74
75 def ignoresVaryingStuff(self):
76 return not (self.fromdb is None
77 and self.fromdbUpdating is None)
78
79 def completeElement(self, ctx):
80 super().completeElement(ctx)
81 if self.fromdb and self.rd:
82 self.fromdb = self.rd.expand(self.fromdb)
83 if self.fromdbUpdating and self.rd:
84 self.fromdbUpdating = self.rd.expand(self.fromdbUpdating)
85
86 def prepare(self, connection):
87 """sets attributes to speed up isIgnored()
88 """
89 self.inputsDir = base.getConfig("inputsDir")
90 # ignored is a dict either mapping to None (ignore unconditionally)
91 # or to a UTC datetime.datetime instance (ignore if not newer than
92 # that datetime).
93 self.ignored = {}
94
95 if self.fromdb and connection is not None:
96 try:
97 with connection.savepoint():
98 for r in connection.query(self.fromdb):
99 self.ignored[r[0]] = None
100 except base.DBError as msg: # table probably doesn't exist yet.
101 base.ui.notifyWarning(f"ignore fromdb(Updating) failed ({msg}) --"
102 " unless you have a typo in the query, fix this by importing the RD")
103
104 if self.fromdbUpdating and connection is not None:
105 try:
106 with connection.savepoint():
107 for r in connection.query(self.fromdbUpdating):
108 self.ignored[r[0]] = r[1]
109 except base.DBError: # table probably doesn't exist yet.
110 base.ui.notifyError("ignore fromdbUpdating failed --"
111 " unless you have a typo in the query, fix this by importing the RD")
112
113 if self.fromfile:
114 for ln in open(self.fromfile, "rb"):
115 ln = ln.strip().decode("utf-8")
116 if ln and not ln.startswith("#"):
117 self.ignored[ln] = None
118
119 def isIgnored(self, path):
120 """returns true if path, made inputsdir-relative, should be ignored.
121 """
122 try:
123 path = utils.getRelativePath(path, self.inputsDir, liberalChars=True)
124 except ValueError: # not in inputs, use full path.
125 pass
126
127 lastMtime = self.ignored.get(path, base.NotGiven)
128 if lastMtime is base.NotGiven:
129 # not mentioned: proceed to pattern test
130 pass
131 elif lastMtime is None:
132 # unconditionally ignored
133 return True
134 else:
135 # lastMtime is given, now see if the file has been touched.
136 if (lastMtime<
137 datetime.datetime.utcfromtimestamp(
138 os.path.getmtime(self.inputsDir / path))):
139 # changed since last import, proceed to pattern test
140 # (but of course that has not triggered before either.
141 # ah well).
142 pass
143 else:
144 # file unchanged, ignore
145 return True
146
147 for pat in self.patterns:
148 if fnmatch.fnmatch(path, pat):
149 return True
150 return False
151
152
153 class SourceSpec(base.Structure):
154 """A Specification of a data descriptor's inputs.
155
156 This will typically be files taken from a file system. If so, DaCHS will,
157 in each directory, process the files in alphabetical order. No guarantees
158 are made as to the sequence directories are processed in.
159
160 Multiple patterns are processed in the order given in the RD.
161 """
162 name_ = "sources"
163
164 _patterns = base.ListOfAtomsAttribute("patterns", description=
165 "Paths to the source files. You can use shell patterns here.",
166 itemAttD=base.UnicodeAttribute("pattern", description="Shell pattern"
167 " for source file(s), relative to resource directory."),
168 copyable=True)
169 _items = base.ListOfAtomsAttribute("items", description=
170 "String literals to pass to grammars. In contrast to patterns,"
171 " they are not interpreted as file names but passed to the"
172 " grammar verbatim. Normal grammars do not like this. It is"
173 " mainly intended for use with custom or null grammars.",
174 itemAttD=base.UnicodeAttribute("item",
175 description="Grammar-specific string"), copyable=True)
176 _recurse = base.BooleanAttribute("recurse", default=False,
177 description="Search for pattern(s) recursively in their directory"
178 " part(s)?", copyable=True)
179 _ignore = base.StructAttribute("ignoredSources", childFactory=
180 IgnoreSpec, description="Specification of sources that should not"
181 " be processed although they match patterns. Typically used"
182 " in update-type data descriptors.", copyable=True)
183 _file = base.DataContent(description="A single"
184 " file name (this is for convenience)", copyable="True")
185 _original = base.OriginalAttribute()
186
187 def __iter__(self):
188 return self.iterSources()
189
190 def completeElement(self, ctx):
191 if self.ignoredSources is base.Undefined:
192 self.ignoredSources = base.makeStruct(IgnoreSpec)
193
194 newPatterns = []
195 for pat in self.patterns:
196 try:
197 newPatterns.append(pat)
198 except UnicodeEncodeError:
199 raise base.DataError("Pattern %r contains a non-ASCII"
200 " characters. DaCHS currently"
201 " forbids that. If you need non-ASCII in your file"
202 " names, complain to [email protected]."%pat)
203 self.patterns = newPatterns
204
205 super().completeElement(ctx)
206
207 def _expandDirParts(self, dirParts, ignoreDotDirs=True):
208 """expands a list of directories into a list of them and all their
209 descendants.
210
211 It follows symbolic links but doesn't do any bookkeeping, so bad
212 things will happen if the directory graph contains cycles.
213 """
214 res = []
215 for root in itertools.chain.from_iterable(
216 glob.glob(d) for d in dirParts):
217 for root, dirs, files in os.walk(root):
218 if ignoreDotDirs:
219 if os.path.basename(root).startswith("."):
220 continue
221 dirs = [dir for dir in dirs if not dir.startswith(".")]
222 dirs = (os.path.join(root, dir) for dir in dirs)
223 res.extend(dir for dir in dirs if os.path.isdir(dir))
224 for child in files:
225 destName = os.path.join(root, child)
226 if os.path.islink(destName) and not os.path.isfile(destName):
227 res.extend(self._expandDirParts(destName))
228 return res
229
230 def iterSources(self, connection=None):
231 self.ignoredSources.prepare(connection)
232 for item in self.items:
233 if not self.ignoredSources.isIgnored(item):
234 yield item
235
236 baseDir = ""
237 if self.parent.rd:
238 baseDir = self.parent.rd.resdir
239
240 for pattern in self.patterns:
241 dirPart, baseName = os.path.split(pattern)
242 if self.parent.rd:
243 dirParts = [os.path.join(baseDir, dirPart)]
244 else:
245 dirParts = [dirPart]
246 if self.recurse:
247 dirParts = dirParts+self._expandDirParts(dirParts)
248
249 for dir in sorted(dirParts):
250 for name in sorted(glob.glob(os.path.join(dir, baseName))):
251 fullName = os.path.abspath(name)
252 if not self.ignoredSources.isIgnored(fullName):
253 try:
254 yield str(fullName)
255 except (UnicodeDecodeError, UnicodeEncodeError):
256 raise base.DataError("File %r has"
257 " non-ASCII name components. DaCHS currently"
258 " forbids that. If you need non-ASCII in your file"
259 " names, complain to [email protected]."%(
260 fullName))
261
262 if self.content_:
263 yield str(os.path.abspath(os.path.join(baseDir, self.content_)))
264
265
266 def __bool__(self):
267 return (not not self.patterns) or (not not self.items
268 ) or (not not self.content_)
269
270
271 class Make(base.Structure, scripting.ScriptingMixin):
272 """A build recipe for tables belonging to a data descriptor.
273
274 All makes belonging to a DD will be processed in the order in which they
275 appear in the file.
276 """
277 name_ = "make"
278
279 acceptedScriptTypes = {"preImport", "preIndex", "preCreation",
280 "postCreation", "beforeDrop", "newSource", "sourceDone"}
281
282 _table = base.ReferenceAttribute("table",
283 description="Reference to the table to be embedded",
284 default=base.Undefined,
285 copyable=True,
286 forceType=tabledef.TableDef)
287
288 _rowmaker = base.ReferenceAttribute("rowmaker",
289 default=base.NotGiven,
290 forceType=rmkdef.RowmakerDef,
291 description="The rowmaker (i.e., mapping rules from grammar keys to"
292 " table columns) for the table being made.",
293 copyable=True)
294
295 _parmaker = base.ReferenceAttribute("parmaker",
296 default=base.NotGiven,
297 forceType=rmkdef.ParmakerDef,
298 description="The parmaker (i.e., mapping rules from grammar parameters"
299 " to table parameters) for the table being made. You will usually"
300 " not give a parmaker.",
301 copyable=True)
302
303 _role = base.UnicodeAttribute("role",
304 default=None,
305 description="The role of the embedded table within the data set",
306 copyable=True)
307
308 _rowSource = base.EnumeratedUnicodeAttribute("rowSource",
309 default="rows",
310 validValues=["rows", "parameters"],
311 description="Source for the raw rows processed by this rowmaker.",
312 copyable=True,
313 strip=True)
314
315 def __repr__(self):
316 return "Make of table=%r"%(self.table and self.table.id)
317
318 def onParentComplete(self):
319 if self.rowmaker is base.NotGiven:
320 self.rowmaker = rmkdef.RowmakerDef.makeIdentityFromTable(self.table)
321
322 def getExpander(self):
323 """used by the scripts of expanding their source.
324
325 We always return the expander of the table being made.
326 """
327 return self.table.getExpander()
328
329 def create(self, connection, parseOptions, tableFactory, **kwargs):
330 """returns a new empty instance of the table this is making.
331 """
332 newTable = tableFactory(self.table,
333 parseOptions=parseOptions, connection=connection, role=self.role,
334 create=not parseOptions.suppressMeta,
335 updating=getattr(self.parent, "updating", False),
336 make=self,
337 **kwargs)
338 return newTable
339
340 def runParmakerFor(self, grammarParameters, destTable):
341 """feeds grammarParameter to destTable.
342 """
343 if self.parmaker is base.NotGiven:
344 return
345 parmakerFunc = self.parmaker.compileForTableDef(destTable.tableDef)
346 destTable.setParams(parmakerFunc(grammarParameters, destTable),
347 raiseOnBadKeys=False)
348
349
350 class DataDescriptor(base.Structure, base.ComputedMetaMixin,
351 common.IVOMetaMixin, tabledef.PublishableDataMixin,
352 base.ExpansionDelegator):
353 """A description of how to process data from a given set of sources.
354
355 Data descriptors bring together a grammar, a source specification and
356 "makes", each giving a table and a rowmaker to feed the table from the
357 grammar output.
358
359 They are the "executable" parts of a resource descriptor. Their ids
360 are used as arguments to gavoimp for partial imports.
361 """
362 name_ = "data"
363 resType = "data"
364
365 _rowmakers = base.StructListAttribute("rowmakers",
366 childFactory=rmkdef.RowmakerDef,
367 description="Embedded build rules (preferably put rowmakers directly"
368 " into make elements)",
369 copyable=True,
370 before="makes")
371
372 _tables = base.StructListAttribute("tables",
373 childFactory=tabledef.TableDef,
374 description="Embedded table definitions (usually, tables are defined"
375 " toplevel)",
376 copyable=True,
377 before="makes")
378
379 _grammar = base.MultiStructAttribute("grammar",
380 default=None,
381 childFactory=builtingrammars.getGrammar,
382 childNames=list(builtingrammars.GRAMMAR_REGISTRY.keys()),
383 description="Grammar used to parse this data set.",
384 copyable=True,
385 before="makes")
386
387 _sources = base.StructAttribute("sources",
388 default=None,
389 childFactory=SourceSpec,
390 description="Specification of sources that should be fed to the grammar.",
391 copyable=True,
392 before="grammar")
393
394 _dependents = base.ListOfAtomsAttribute("dependents",
395 itemAttD=base.UnicodeAttribute("recreateAfter"),
396 description="A data ID to recreate when this resource is"
397 " remade; use # syntax to reference in other RDs.")
398
399 _auto = base.BooleanAttribute("auto",
400 default=True,
401 description="Import this data set if not explicitly"
402 " mentioned on the command line?")
403
404 _updating = base.BooleanAttribute("updating",
405 default=False,
406 description="Keep existing tables on import? You usually want this"
407 " False unless you have some kind of sources management,"
408 " e.g., via a sources ignore specification.",
409 copyable=True)
410
411 _makes = base.StructListAttribute("makes",
412 childFactory=Make,
413 copyable=True,
414 description="Specification of a target table and the rowmaker"
415 " to feed them.")
416
417 _params = common.ColumnListAttribute("params",
418 childFactory=column.Param,
419 description='Param ("global columns") for this data (mostly for'
420 ' VOTable serialization).',
421 copyable=True)
422
423 _remakeOnDataChange = base.BooleanAttribute("remakeOnDataChange",
424 default=False,
425 description="If this data is made as a dependent of some other,"
426 " remake it even if the other just has data updates? You generally"
427 " want to keep this at the default for data that just makes views"
428 " and the like. You'd want this true when the data produces some"
429 " statistics or the like.",
430 copyable=True)
431
432 _properties = base.PropertyAttribute()
433
434 _rd = common.RDAttribute()
435
436 _original = base.OriginalAttribute()
437
438 metaModel = ("title(1), creationDate(1), description(1),"
439 "subject, referenceURL(1), contentLevel(? voc:voresource/content_level)")
440
441 def __repr__(self):
442 return "<data descriptor with id %s>"%self.id
443
444 def validate(self):
445 super().validate()
446 if self.registration and self.id is None:
447 raise base.StructureError("Published data needs an assigned id.")
448
449 def onElementComplete(self):
450 super().onElementComplete()
451 for t in self.tables:
452 t.setMetaParent(self)
453 if self.registration:
454 self.registration.register()
455
456 # since we want to be able to create DDs dynamically , they must find their
457 # meta parent themselves. We do this while the DD is being adopted;
458 # the rules here are: if the parent is a meta mixin itself, it's the
459 # meta parent, if it has an rd attribute, use that, else give up.
460 # TODO: For DDs on cores, it would be *desirable* to come up
461 # with some magic that makes the current service their meta parent.
462
463 def _getParent(self):
464 return self.__parent
465
466 def _setParent(self, value):
467 self.__parent = value
468 if isinstance(value, base.MetaMixin):
469 self.setMetaParent(value)
470 elif hasattr(value, "rd"):
471 self.setMetaParent(value.rd)
472
473 parent = property(_getParent, _setParent)
474
475 def iterSources(self, connection=None):
476 if self.sources:
477 return self.sources.iterSources(connection)
478 else:
479 return iter([])
480
481 def __iter__(self):
482 for m in self.makes:
483 yield m.table
484
485 def iterTableDefs(self):
486 """iterates over the definitions of all the tables built by this DD.
487
488 This will not include system tables.
489 """
490 for m in self.makes:
491 if not m.table.system:
492 yield m.table
493
494 def getTableDefById(self, id):
495 for td in self.iterTableDefs():
496 if td.id==id:
497 return td
498 raise base.StructureError("No table named %s found, none will be built"%id)
499
500 def getTableDefWithRole(self, role):
501 for m in self.makes:
502 if m.role==role:
503 return m.table
504 raise base.StructureError("No table def with role '%s'"%role)
505
506 def getPrimary(self):
507 """returns the "primary" table definition in the data descriptor.
508
509 "primary" means the only table in a one-table dd, the table with the
510 role "primary" if there are more. If no matching table is found, a
511 StructureError is raised.
512 """
513 if len(self.makes)==1:
514 return self.makes[0].table
515 else:
516 try:
517 return self.getTableDefWithRole("primary")
518 except base.StructureError: # raise more telling message
519 pass
520 raise base.StructureError("Ambiguous request for primary table")
521
522 def copyShallowly(self):
523 """returns a shallow copy of self.
524
525 Sources are not copied.
526 """
527 return DataDescriptor(self.parent, rowmakers=self.rowmakers[:],
528 tables=self.tables[:], grammar=self.grammar, makes=self.makes[:])
529
530 def getURL(self, rendName, absolute=True):
531 # there's no sensible URL for DDs; thus, let people browse
532 # the RD info. At least they should find links to any tables
533 # included here there.
534 basePath = "%sbrowse/%s"%(
535 base.getConfig("web", "nevowRoot"),
536 self.rd.sourceId)
537 if absolute:
538 return base.makeAbsoluteURL(basePath)
539 return basePath