Debian Codegraph @

gavo/rscdesc.py

raw ◀ ▶
1 Debian patch touch this file
1 """
2 Structure definition of resource descriptors.
3
4 The stuff they are describing is not a resource in the VO sense (whatever
5 that is) or in the Dublin Core sense, but simply stuff held together
6 by common metadata. If it's got the same creator, the same base title,
7 the same keywords, etc., it's described by one RD.
8
9 In the DaCHS, a resource descriptor typically sets up a schema in
10 the database.
11 """
12
13 #c Copyright 2008-2025, the GAVO project <[email protected]>
14 #c
15 #c This program is free software, covered by the GNU GPL. See the
16 #c COPYING file in the source distribution.
17
18
19 import datetime
20 import pathlib
21 import os
•22 from gavo import pkg_resources
23 import time
24 import threading
25 import weakref
26 from urllib import parse as urlparse
27
28 from gavo import base
29 from gavo import registry
30 from gavo import rsc
31 from gavo import rscdef
32 from gavo import svcs
33 from gavo import utils
34 from gavo.rscdef import common
35 from gavo.rscdef import rdinj
36 from gavo.rscdef import regtest
37 from gavo.rscdef import scripting
38 from gavo.rscdef import executing
39
40
41 class ResdirAttribute(base.UnicodeAttribute):
42 """An attribute representing an RD's resdir.
43
44 This is for resource's resdir attribute, which will by default
45 get the inputsDir prepended. There is the special value "." that
46 means "the directory containing the RD", which is what people should
47 do now.
48
49 This will only work for RDs.
50
51 Note that without that, the resdir defaults to <inputsDir>/<schemaName>.
52 """
53 def feedObject(self, instance, parsedValue):
54 setattr(self, f"_original_resdir_{self.name_}", parsedValue)
55 if parsedValue==".":
56 parsedValue = "/".join(instance.sourceId.split("/")[:-1])
57
58 parsedValue = base.getConfig("inputsDir") / parsedValue
59 super().feedObject(instance, parsedValue)
60
61
62 class Publication(base.Structure):
63 """A request to publish the entire RD.
64
65 This will produce a record with all ADQL-readable tables as its
66 tableset and all plausible services as capabilities.
67 """
68 name_ = "publish"
69 docName_ = "publish (resource)"
70
71 _sets = base.StringSetAttribute("sets", default=frozenset(["ivo_managed"]),
72 description="A comma-separated list of sets this data will be"
73 " published in. To publish data to the VO registry, just"
74 " say ivo_managed here, local puts a link on the front page."
75 " ivo_managed is the default.")
76
77
78 @base.buildstructure
79 class RD(base.Structure, base.ComputedMetaMixin, scripting.ScriptingMixin,
80 base.StandardMacroMixin, common.PrivilegesMixin):
81 """A resource descriptor.
82
83 RDs collect all information about how to parse a particular source (like a
84 collection of FITS images, a catalogue, or whatever), about the database
85 tables the data ends up in, and the services used to access them.
86
87 This is the root element of all RDs.
88
89 To give your schema a utype, set a ``utype`` meta on resource.
90
91 To set the schema_index in TAP_SCHEMA, put some integer to
92 a schema-rank meta; lower-ranked schemas are displayed further
93 up in supporting clients (since version 2.9.3).
94 """
95 name_ = "resource"
96
97 metaModel = ("creationDate(1), title(1), description(1), subject,"
98 " coverage.waveband (? voc:messenger),"
99 " content.level (? voc:voresource/content_level),"
100 " content.type (? voc:voresource/content_type),"
101 " _news.role (? voc:voresource/date_role)"
102 )
103
104 # this is set somewhere below once parsing has proceeded far enough
105 # such that caching the RD make sense
106 cacheable = False
107
108 # we used to accept scripts in RDs and probably will do so again,
109 # but for now the semantics are not well-defined and we reject all
110 # scripts for a while
111 acceptedScriptTypes = {}
112
113 _resdir = ResdirAttribute("resdir",
114 default=None,
115 description="Base directory for source files and everything else"
116 " belonging to the resource. Use a single dot (.) to say 'the"
117 " directory the RD resides in', which is recommended in modern"
118 " DaCHS.",
119 copyable=True)
120
121 _schema = base.UnicodeAttribute("schema",
122 default=base.Undefined,
123 description="Database schema for tables defined here. Follow the rule"
124 " 'one schema, one RD' if at all possible. If two RDs share the same"
125 " schema, the must generate exactly the same permissions for that"
126 " schema; this means, in particular, that if one has an ADQL-published"
127 " table, so must the other. In a nutshell: one schema, one RD.",
128 copyable=True,
129 callbacks=["_inferResdir"])
130
131 _dds = base.StructListAttribute("dds",
132 childFactory=rscdef.DataDescriptor,
133 description="Descriptors for the data generated and/or published"
134 " within this resource.",
135 copyable=True,
136 before="outputTables")
137
138 _tables = base.StructListAttribute("tables",
139 childFactory=rscdef.TableDef,
140 description="A table used or created by this resource",
141 copyable=True,
142 before="dds")
143
144 _outputTables = base.StructListAttribute("outputTables",
145 childFactory=svcs.OutputTableDef,
146 description="Canned output tables for later reference.",
147 copyable=True)
148
149 _rowmakers = base.StructListAttribute("rowmakers",
150 childFactory=rscdef.RowmakerDef,
151 description="Transformations for going from grammars to tables."
152 " If specified in the RD, they must be referenced from make"
153 " elements to become active.",
154 copyable=True,
155 before="dds")
156
157 _procDefs = base.StructListAttribute("procDefs",
158 childFactory=rscdef.ProcDef,
159 description="Procedure definintions (rowgens, rowmaker apply-s)",
160 copyable=True, before="rowmakers")
161
162 _condDescs = base.StructListAttribute("condDescs",
163 childFactory=svcs.CondDesc,
164 description="Global condition descriptors for later reference",
165 copyable=True,
166 before="cores")
167
168 _resRecs = base.StructListAttribute("resRecs",
169 childFactory=registry.ResRec,
170 description="Non-service resources for the IVOA registry. They will"
171 " be published when gavo publish is run on the RD.")
172
173 _publication = base.StructAttribute("publication",
174 childFactory=Publication, description="The presence of this element"
175 " publishes the entire RD to the VO or the front page; is is more"
176 " common to publish individual tables or services at this point.",
177 default=None)
178
179 _services = base.StructListAttribute("services",
180 childFactory=svcs.Service,
181 description="Services exposing data from this resource.",
182 copyable=True)
183
184 _macDefs = base.MacDefAttribute(before="tables",
185 description="User-defined macros available on this RD")
186
187 _mixinDefs = base.StructListAttribute("mixdefs",
188 childFactory=rscdef.MixinDef,
189 description="Mixin definitions (usually not for users)")
190
191 _require = base.ActionAttribute("require",
192 methodName="importModule",
193 description="Deprecated, don't use this any more."
194 " May go away by DaCHS 2.12")
195
196 _cores = base.MultiStructListAttribute("cores",
197 childFactory=svcs.getCore,
198 childNames=list(svcs.CORE_REGISTRY.keys()),
199 description="Cores available in this resource.", copyable=True,
200 before="services")
201
202 _jobs = base.StructListAttribute("jobs",
203 childFactory=executing.Execute,
204 description="Jobs to be run while this RD is active.")
205
206 _tests = base.StructListAttribute("tests",
207 childFactory=regtest.RegTestSuite,
208 description="Suites of regression tests connected to this RD.")
209
210 _coverage = base.StructAttribute("coverage",
211 childFactory=rscdef.Coverage,
212 default=None,
213 description="STC coverage of this resource.", copyable=True)
214
215 _properties = base.PropertyAttribute()
216
217 resType = "rd"
218
219 def __init__(self, srcId, **kwargs):
220 # RDs never have parents, so contrary to all other structures they
221 # are constructed with with a srcId instead of a parent. You
222 # *can* have that None, but such RDs cannot be used to create
223 # non-temporary tables, services, etc, since the srcId is used
224 # in the construction of identifiers and such.
225 self.sourceId = srcId or "temporary"
226 base.Structure.__init__(self, None, **kwargs)
227 # The rd attribute is a weakref on self. Always. So, this is the class
228 # that roots common.RDAttributes
229 self.rd = weakref.proxy(self)
230 # real dateUpdated is set by getRD, this is just for RDs created
231 # on the fly.
232 self.dateUpdated = datetime.datetime.utcnow()
233 # if an RD is parsed from a disk file, this gets set to its path
234 # by getRD below
235 self.srcPath = None
236 # this is for modified-since and friends.
237 self.loadedAt = time.time()
238 # keep track of RDs depending on us for the registry code
239 # (only read this)
240 self.rdDependencies = set()
241
242 def __iter__(self):
243 return iter(self.dds)
244
245 def __repr__(self):
246 return "<resource descriptor for %s>"%self.sourceId
247
248 def validate(self):
249 if not utils.identifierPattern.match(self.schema):
250 raise base.StructureError("DaCHS schema attributes must be valid"
251 " python identifiers")
252
253 def isDirty(self):
254 """returns true if the RD on disk has a timestamp newer than
255 loadedAt.
256 """
257 if isinstance(self.srcPath, PkgResourcePath):
258 # stuff from the resource package should not change underneath us.
259 return False
260
261 try:
262 if self.srcPath is not None:
263 return os.path.getmtime(self.srcPath)>self.loadedAt
264 except os.error:
265 # this will usually mean the file went away
266 return True
267 return False
268
269 def importModule(self, ctx):
270 # this is a callback for the require attribute
271 utils.loadInternalObject(self.require, "__doc__")
272
273 def onElementComplete(self):
274 for table in self.tables:
275 self.readProfiles = self.readProfiles | table.readProfiles
276 table.setMetaParent(self)
277
278 self.serviceIndex = {}
279 for svc in self.services:
280 self.serviceIndex[svc.id] = svc
281 svc.setMetaParent(self)
282
283 for dd in self.dds:
284 dd.setMetaParent(self)
285
286 if (self.resdir
287 and not self.resdir.is_dir()
288 # the system RDs don't actually use their resdir, so be
289 # relaxed when people drop it
290 and not self.resdir.parts[-1]=="__system"):
291 base.ui.notifyWarning("RD %s: resource directory '%s' does not exist"%(
292 self.sourceId, self.resdir))
293
294 super().onElementComplete()
295
296 def _inferResdir(self, value):
297 # a callback for the schema attribute
298 if self.resdir is None:
299 self._resdir.feedObject(self, value)
300
301 def iterDDs(self):
302 return iter(self.dds)
303
304 def getService(self, id):
305 """returns a service or resRec object with id.
306
307 This will return None if neither exists.
308 """
309 try:
310 res = self.getById(id)
311 if isinstance(res, (svcs.Service, registry.ResRec)):
312 return res
313 except base.NotFoundError:
314 pass # Fall through when there's no id.
315 return None
316
317 def getTableDefById(self, id):
318 return self.getById(id, rscdef.TableDef)
319
320 def getDataDescById(self, id):
321 return self.getById(id, rscdef.DataDescriptor)
322
323 def getById(self, id, forceType=None):
324 try:
325 res = self.idmap[id]
326 except KeyError:
327 raise base.NotFoundError(
328 id, "Element with id", "RD %s"%(self.sourceId))
329 if forceType:
330 base.assertType(id, res, forceType)
331 return res
332
333 def getRelResdir(self):
334 """returns the inputsDir-relative resource directory path.
335
336 This never has either a leading or a trailing path.
337 """
338 return utils.getRelativePath(self.resdir, base.getConfig("inputsDir"))
339
340 def getAbsPath(self, relPath):
341 """returns the absolute path for a resdir-relative relPath.
342 """
343 return os.path.join(self.resdir, relPath)
344
345 def openRes(self, relPath, mode="rb"):
346 """returns a file object for relPath within self's resdir.
347
348 Deprecated. This is going to go away, use getAbsPath and a context
349 manager.
350 """
351 return open(self.getAbsPath(relPath), mode)
352
353 def _computeIdmap(self):
354 res = {}
355 for child in self.iterChildren():
356 if hasattr(child, "id"):
357 res[child.id] = child
358 return res
359
360 def addDependency(self, rd, prereq):
361 """declares that rd needs the RD prereq to properly work.
362
363 This is used in the generation of resource records to ensure that, e.g.
364 registered data have added their served-bys to the service resources.
365 """
366 if rd.sourceId!=prereq.sourceId:
367 self.rdDependencies.add((rd.sourceId, prereq.sourceId))
368
369 def copy(self, parent):
370 base.ui.notifyWarning("Copying an RD -- this may not be a good idea")
371 new = base.Structure.copy(self, parent)
372 new.idmap = new._computeIdmap()
373 new.sourceId = self.sourceId
374 return new
375
376 def updateMetaInDB(self, connection, reason):
377 """updates this RD's metadata in the database.
378
379 See the grammar in //rds for what you can give for reason.
380 """
381 rsc.makeData(
382 base.resolveCrossId("//rds#update-for-rd"),
383 connection=connection,
384 forceSource=(reason, self))
385
386 def invalidate(self):
387 """make the RD fail on every attribute read.
388
389 See rscdesc._loadRDIntoCache for why we want this.
390 """
391 errMsg = ("Loading of %s failed in another thread; this RD cannot"
392 " be used here")%self.sourceId
393
394 class BrokenClass(object):
395 """A class that reacts to all attribute requests with a some exception.
396 """
397 def __getattribute__(self, attributeName):
398 if attributeName=="__class__":
399 return BrokenClass
400 raise base.ReportableError(errMsg)
401
402 self.__class__ = BrokenClass
403
404 def getSchemaRank(self):
405 """returns the value of the schema-rank meta parsed and with a
406 fallback.
407 """
408 m = self.getMeta("schema-rank")
409 if m:
410 return int(m.getContent())
411 return 100000
412
413 def _meta__metadataUpdated(self):
414 """falls back to utcnow in case we don't know the metadata update
415 time.
416
417 Since _metadataUpdated falls back to the file creation time, this
418 is only reached for file-less RDs. For these, just about now
419 would be a good guess as to their creation time.
420
421 In reality, this shouldn't be reached outside of test code; there,
422 however, it's important because this is used in required attributes
423 in OAI-PMH and VOResource.
424 """
425 return utils.formatISODT(datetime.datetime.utcnow())
426
427 def _meta_referenceURL(self):
428 return base.META_CLASSES_FOR_KEYS["referenceURL"](
429 base.makeAbsoluteURL("/browse/"+self.sourceId),
430 title="Resource info")
431
432 def _meta_identifier(self):
433 return "ivo://%s/%s"%(base.getConfig("ivoa", "authority"),
434 urlparse.quote(self.sourceId))
435
436 def _meta_published_identifier(self):
437 if self.publication:
438 return self._meta_identifier()
439 return None
440
441 def macro_RSTccbysa(self, stuffDesignation):
442 """expands to a declaration that stuffDesignation is available under
443 CC-BY-SA.
444
445 This only works in reStructured text (though it's still almost
446 readable as source).
447
448 You'll probably want to use the `//procs#license-cc-by-sa`_ stream
449 instead of this, as that also sets the rights URI.
450 """
451 return ("%s is licensed under the `Creative Commons Attribution"
452 " Share-Alike 4.0"
453 " License <http://creativecommons.org/licenses/by-sa/4.0/>`_\n\n"
454 ".. image:: /static/img/ccbysa.png\n :alt: [CC-BY-SA]\n"
455 )%stuffDesignation
456
457 def macro_RSTccby(self, stuffDesignation):
458 """expands to a declaration that stuffDesignation is available under
459 CC-BY.
460
461 This only works in reStructured text (though it's still almost
462 readable as source).
463
464 You'll probably want to use the `//procs#license-cc-by`_ stream
465 instead of this, as that also sets the rights URI.
466 """
467 return ("%s is licensed under the `Creative Commons Attribution 4.0"
468 " License <http://creativecommons.org/licenses/by/4.0/>`_\n\n"
469 ".. image:: /static/img/ccby.png\n :alt: [CC-BY]\n\n"
470 )%stuffDesignation
471
472 def macro_RSTcc0(self, stuffDesignation):
473 """expands to a declaration that stuffDesignation is available under
474 CC-0.
475
476 This only works in reStructured text (though it's still almost
477 readable as source).
478
479 You'll probably want to use the `//procs#license-cc0`_ stream
480 instead of this, as that also sets the rights URI.
481 """
482 return ("To the extent possible under law, the publisher has"
483 " waived all copyright and related or neighboring rights to %s."
484 " For details, see the `Creative Commons CC0 1.0"
485 " Public Domain dedication"
486 " <http://creativecommons.org/publicdomain/zero/1.0/>`_. Of course,"
487 " you should still give proper credit when using this data as"
488 " required by good scientific practice.\n\n"
489 ".. image:: /static/img/cc0.png\n :alt: [CC0]\n\n"
490 )%stuffDesignation
491
492
493 class RDParseContext(base.ParseContext):
494 """is a parse context for RDs.
495
496 It defines a couple of attributes that structures can ask for (however,
497 it's good practice not to rely on their presence in case someone wants
498 to parse XML snippets with a standard parse context, so use
499 getattr(ctx, "doQueries", True) or somesuch.
500 """
501 def __init__(self, doQueries=True, restricted=False, forRD=None):
502 self.doQueries = doQueries
503 base.ParseContext.__init__(self, restricted, forRD)
504
505 @classmethod
506 def fromContext(cls, ctx, forRD=None):
507 """a constructor that makes a context with the parameters taken from
508 the RDParseContext ctx.
509 """
510 return cls(doQueries=ctx.doQueries, restricted=ctx.restricted,
511 forRD=forRD)
512
513 @property
514 def failuresAreCacheable(self):
515 """returns true if failures produced with this context should
516 be cached.
517
518 This is not the case with restricted parses.
519 """
520 return not self.restricted
521
522
523 class PkgResourcePath(str):
524 """A sentinel class used to mark an RD as coming from pkg_resources.
525 """
526 def __str__(self):
527 return self
528
529
530 def canonicalizeRDId(srcId):
531 """returns a standard rd id for srcId.
532
533 srcId may be a file system path, or it may be an "id". The canonical
534 basically is "inputs-relative path without .rd extension". Everything
535 that's not within inputs or doesn't end with .rd is handed through.
536 // is expanded to __system__/. The path to built-in RDs,
537 /resources/inputs, is treated analogous to inputsDir.
538 """
539 srcId = str(srcId)
540 if srcId.startswith("//"):
541 srcId = "__system__"+srcId[1:]
542
543 # This may see un-normalised path; let's try and follow unix path
544 # semantics
545 cleanedPath = []
546 for segment in srcId.split("/"):
547 if segment==".":
548 pass
549 elif segment=="..":
550 if cleanedPath:
551 cleanedPath.pop()
552 else:
553 raise ValueError("Too many .. in relative rd id")
554 else:
555 cleanedPath.append(segment)
556 srcId = "/".join(cleanedPath)
557
558 for inputsDir in (str(base.getConfig("inputsDir")), "/resources/inputs"):
559 if srcId.startswith(inputsDir):
560 srcId = srcId[len(inputsDir):].lstrip("/")
561
562 if srcId.endswith(".rd"):
563 srcId = srcId[:-3]
564
565 return srcId
566
567
568 def _getFilenamesForId(srcId):
569 """helps getRDInputStream by iterating over possible files for srcId.
570 """
571 if srcId.startswith("/"):
572 yield pathlib.Path(srcId+".rd")
573 yield pathlib.Path(srcId)
574 else:
575 inputsDir = base.getConfig("inputsDir")
576 yield inputsDir / (srcId+".rd")
577 yield inputsDir / srcId
578 yield "/resources/inputs/%s.rd"%srcId
579 yield "/resources/inputs/%s"%srcId
580
581
582 def getRDInputStream(srcId):
583 """returns a read-open stream for the XML source of the resource
584 descriptor with srcId.
585
586 srcId is already normalized; that means that absolute paths must
587 point to a file (sans possibly .rd), relative paths are relative
588 to inputsDir or pkg_resources(/resources/inputs).
589
590 This function prefers files with .rd to those without, and
591 inputsDir to pkg_resources (the latter allowing the user to
592 override built-in system RDs).
593 """
594 for fName in _getFilenamesForId(srcId):
595 if isinstance(fName, pathlib.Path):
596 # a user-controlled file
597 if fName.is_file():
598 # We don't want RDs from outside of inputs and config, as
599 # these make referencing really messy.
600 filePath = str(fName.absolute())
601 if not (
602 filePath.startswith(str(base.getConfig("inputsDir")))
603 or filePath.startswith(str(base.getConfig("configDir")))):
604 raise base.ReportableError("%s: Only RDs below inputsDir (%s) are"
605 " allowed."%(fName, base.getConfig("inputsDir")))
606
607 return fName, open(fName, "rb")
608
609 else:
610 # a pkg_resources key
611 if (pkg_resources.resource_exists('gavo', fName)
612 and not pkg_resources.resource_isdir('gavo', fName)):
613 return (PkgResourcePath(fName),
614 pkg_resources.resource_stream('gavo', fName))
615
616 raise base.RDNotFound(srcId)
617
618
619 def setRDDateTimes(ctx, rd, inputFile):
620 """sets the _dataUpdated and _metadataUpdated meta items on rd.
621 """
622 rd.setMeta("_metadataUpdated",
623 datetime.datetime.utcfromtimestamp(
624 utils.fgetmtime(inputFile)))
625
626 try:
627 rd.setMeta("_dataUpdated", ctx.getInjected("_dataUpdated"))
628 except KeyError:
629 # no data imported yet, probably
630 pass
631
632
633 USERCONFIG_RD_PATH = base.getConfig("configDir") / "userconfig"
634
635
636 class _UserConfigFakeRD(object):
637 """A fake object that's in the RD cache as "%".
638
639 This is used by the id resolvers in parsecontext; this certainly is
640 of no use as an RD otherwise.
641 """
642 def __init__(self):
643 pass
644
645 def getRealRD(self):
646 return base.caches.getRD(USERCONFIG_RD_PATH)
647
648 def getMeta(self, *args, **kwargs):
649 return base.caches.getRD(USERCONFIG_RD_PATH).getMeta(*args, **kwargs)
650
651 def getById(self, id, forceType=None):
652 """returns an item from userconfig.
653
654 This first tries to resolve id in gavo/etc/userconfig.rd, then in the
655 fallback //userconfig.rd.
656 """
657 try:
658 try:
659 return base.caches.getRD(
660 base.getConfig("configDir") / "userconfig.rd"
661 ).getById(id, forceType=forceType)
662 except base.NotFoundError:
663 pass
664 except Exception as msg:
665 base.ui.notifyError("Bad userconfig: (%s), ignoring it. Run"
666 " 'dachs val %%' to see actual errors."%repr(msg))
667
668 return base.caches.getRD("//userconfig"
669 ).getById(id, forceType=forceType)
670 except base.NotFoundError:
671 raise base.NotFoundError(id, "Element with id",
672 "etc/userconfig.rd")
673
674
675 def refuseBlacklisted(srcId, rdInputPath):
676 """raises an exception if rdInputPath ends with or srcId is equal to
677 one of the strings in [general]rdblacklist.
678 """
679 for blacklistedName in base.getConfig("rdblacklist"):
680 if (str(rdInputPath).endswith(blacklistedName)
681 or blacklistedName==srcId):
682 raise utils.Error(
683 f"RD {srcId} is blacklisted in gavo.rc. Not loading.")
684
685
686 def getRD(srcId, doQueries=True, restricted=False, useRD=None):
687 """returns a ResourceDescriptor for srcId.
688
689 srcId is something like an input-relative path; you'll generally
690 omit the extension (unless it's not the standard .rd).
691
692 getRD furnishes the resulting RD with an idmap attribute containing
693 the mapping from id to object collected by the parse context.
694
695 The useRD parameter is for _loadRDIntoCache exclusively and is
696 used by it internally. It is strictly an ugly implementation detail.
697 """
698 if srcId=='%':
699 return _UserConfigFakeRD()
700
701 if useRD is None:
702 rd = RD(canonicalizeRDId(srcId))
703 else:
704 rd = useRD
705
706 srcPath, inputFile = getRDInputStream(rd.sourceId)
707 try:
708 refuseBlacklisted(srcId, srcPath)
709 except utils.Error:
710 inputFile.close()
711 raise
712
713 # look for a context upstack and get the default parameters from there,
714 # overriding the parameters.
715 try:
716 getRD_context = RDParseContext.fromContext(
717 utils.stealVar("getRD_context"), forRD=rd.sourceId)
718 except ValueError:
719 # no getRD_context variable in the stack
720 getRD_context = RDParseContext(doQueries=doQueries,
721 restricted=restricted, forRD=rd.sourceId)
722
723 rdinj.injectIntoContext(getRD_context, rd.sourceId)
724
725 if not isinstance(srcPath, PkgResourcePath):
726 srcPath = os.path.abspath(srcPath)
727 rd.srcPath = getRD_context.srcPath = srcPath
728 rd.idmap = getRD_context.idmap
729
730 try:
731 rd = base.parseFromStream(rd, inputFile, context=getRD_context)
732 setRDDateTimes(getRD_context, rd, inputFile)
733 except Exception as ex:
734 ex.inFile = srcPath
735 ex.cacheable = getRD_context.failuresAreCacheable
736 raise
737 finally:
738 inputFile.close()
739 return rd
740
741
742 # in _CURRENTLY_PARSING, getRD keeps track of what RDs are currently being
743 # parsed. The keys are the canonical sourceIds, the values are pairs of
744 # an unfinished RD and RLocks protecting it.
745 _CURRENTLY_PARSING_LOCK = threading.Lock()
746 _CURRENTLY_PARSING = {}
747 import threading
748
749
750 class CachedException(object):
751 """An exception that occurred while parsing an RD.
752
753 This will remain in the cache until the underlying RD is changed.
754 """
755 def __init__(self, exception, sourcePath):
756 self.exception = exception.with_traceback(None)
757 self.sourcePath = sourcePath
758 # this can race a bit in that we won't catch saves done between
759 # we started parsing and we came up with the exception, but
760 # these are easy to fix by saving again, so we won't bother.
761 try:
762 self.loadedAt = os.path.getmtime(self.sourcePath)
763 except (TypeError, os.error):
764 # If the file doesn't exist, that state is "as of now"
765 self.loadedAt = time.time()
766
767 def isDirty(self):
768 if self.sourcePath is None:
769 # this can have various reasons, but most likely it's because
770 # the RD hasn't been there. Since we can't tell if the
771 # file has appreared in the mean time, we'll have to re-check
772 return False
773 if not os.path.exists(self.sourcePath):
774 # someone has removed the file, kill cache
775 return True
776 return os.path.getmtime(self.sourcePath)>self.loadedAt
777
778 def raiseAgain(self):
779 raise self.exception.with_traceback(None)
780
781
782 def _loadRDIntoCache(canonicalRDId, cacheDict):
783 """helps _makeRDCache.
784
785 This function contains the locking logic that makes sure multiple
786 threads can load RDs.
787 """
788 with _CURRENTLY_PARSING_LOCK:
789 if canonicalRDId in _CURRENTLY_PARSING:
790 lock, rd = _CURRENTLY_PARSING[canonicalRDId]
791 justWait = True
792 else:
793 lock, rd = threading.RLock(), RD(canonicalRDId)
794 _CURRENTLY_PARSING[canonicalRDId] = lock, rd
795 lock.acquire()
796 justWait = False
797
798 if justWait:
799 # Someone else is already parsing. If it's the current thread,
800 # go on (lock is an RLock!) so we can resolve self-references
801 # (as long as they are backward references). All other threads
802 # just wait for the parsing thread to finish
803 lock.acquire()
804 lock.release()
805 return rd
806
807 try:
808 cacheDict[canonicalRDId] = getRD(canonicalRDId, useRD=rd)
809 except Exception as ex:
810 # This could be a bug in python 3.11.2: the raise below gets
811 # a bad traceback without this hack. Perhaps it can go later
812 # again? You see, I suspect this leaks memory.
813 tb = ex.__traceback__
814
815 # Importing failed, invalidate the RD (in case other threads still
816 # see it from _CURRENTLY_PARSING)
817 if getattr(ex, "cacheable", False):
818 cacheDict[canonicalRDId] = CachedException(ex,
819 getattr(rd, "srcPath", None))
820 rd.invalidate()
821 raise ex.with_traceback(tb)
822 finally:
823 del _CURRENTLY_PARSING[canonicalRDId]
824 lock.release()
825 return cacheDict[canonicalRDId]
826
827
828 def _makeRDCache():
829 """installs the cache for RDs.
830
831 One trick here is to handle "aliasing", i.e. making sure that
832 you get identical objects regardless of whether you request
833 __system__/adql.rd, __system__/adql, or //adql.
834
835 Then, we're checking for "dirty" RDs (i.e., those that should
836 be reloaded).
837
838 The messiest part is the support for getting RDs in the presence of
839 threads while still supporting recursive references, though.
840 """
841 # TODO: Maybe unify this again with caches._makeCache? That stuff could
842 # do with a facility to invalidate cached entries, too.
843 # But care is necessary to not cache any RD parsed in a nonstandard
844 # fashion (e.g., in restricted mode). CAREFUL: since getRD indulges
845 # in variable stealing, explicit checks are necessary.
846 rdCache = {}
847 currentlyValidating = set()
848
849 def clearRDIfDirty(srcId):
850 """clears a cached RD for srcId if it's dirty and it can be
851 loaded from disk.
852
853 If it can't be loaded from disk, the disk file's time stamp
854 is being set as the change date on the rd, so it's counting as
855 clean until it's being changed again. This will avoid re-parsing
856 RDs all the time when they're broken for a while.
857 """
858 if (srcId in rdCache
859 and getattr(rdCache[srcId], "isDirty", lambda: False)()):
860 try:
861 # limit re-check rate to 10 seconds to avoid getRD storms
862 # on often-used but currently broken RDs
863 if time.time()-rdCache[srcId].loadedAt<10:
864 return
865
866 if srcId in currentlyValidating:
867 return
868 currentlyValidating.add(srcId)
869
870 base.ui.notifyWarning("RD dirty, attempting reload of %s"%srcId)
871 try:
872 tempCache = {}
873 _loadRDIntoCache(srcId, tempCache)
874 finally:
875 currentlyValidating.remove(srcId)
876 except Exception as ex:
877 base.ui.notifyError("Tried to reload RD %s but found it broken."
878 " Will retry loading when it has been edited."%srcId)
879 # the source path of the cached exception isn't necessarily
880 # right (for system and userconfig RDs); but it ought
881 # to be good enough for what users typically are confronted with.
882 if isinstance(rdCache[srcId], CachedException):
883 rdCache[srcId] = CachedException(ex,
884 str(os.path.join(base.getConfig("inputsDir"))+srcId+".rd"))
885
886 else:
887 rdCache[srcId].loadedAt = time.time()
888
889 return
890 base.caches.clearForName(srcId)
891
892 def getRDCached(srcId, **kwargs):
893 if kwargs:
894 return getRD(srcId, **kwargs)
895
896 srcId = canonicalizeRDId(srcId)
897 # Since the "validate before purge last" change it's possible
898 # that we're currently parsing and in the cache. During the
899 # validation run, we need to return from the the thing that
900 # currently parses. Hence, we need to re-do quite a bit of
901 # the logic of _loadRDIntoCache here. Gnwm.
902 if srcId in _CURRENTLY_PARSING:
903 lock, rd = _CURRENTLY_PARSING[srcId]
904 lock.acquire()
905 lock.release()
906 return rd
907
908 clearRDIfDirty(srcId)
909
910 if srcId in rdCache:
911 cachedOb = rdCache[srcId]
912 if isinstance(cachedOb, CachedException):
913 cachedOb.raiseAgain()
914 else:
915 return cachedOb
916
917 else:
918 return _loadRDIntoCache(srcId, rdCache)
919
920 getRDCached.cacheCopy = rdCache
921 base.caches.registerCache("getRD", rdCache, getRDCached)
922
923 _makeRDCache()