Debian Codegraph @

gavo/rscdef/common.py

raw
1 """
2 Common items used by resource definition objects.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import functools
12 import os
13 import re
14 import urllib.parse
15
16 from gavo import base
17 from gavo import utils
18 from gavo.base import meta
19
20
21 # The following is a flag for initdachs (and initdachs exclusively)
22 # to prevent resource metadata reading from database tables during
23 # the dachs init.
24 _BOOTSTRAPPING = False
25
26
27 class RDAttribute(base.AttributeDef):
28 """an attribute that gives access to the current rd.
29
30 The attribute is always called rd. There is no default, but on
31 the first access, we look for an ancestor with an rd attribute and
32 use that if it exists, otherwise rd will be None. There currently
33 is no way to reset the rd.
34
35 These attributes cannot (yet) be fed, so rd="xxx" won't work.
36 If we need this, the literal would probably be an id.
37 """
38 computed_ = True
39 typeDesc_ = "reference to a resource descriptor"
40
41 def __init__(self):
42 base.AttributeDef.__init__(self, "rd", None, "The parent"
43 " resource descriptor; never set this manually, the value will"
44 " be filled in by the software.")
45
46 def iterParentMethods(self):
47 def _getRD(self):
48 if getattr(self, "parent", None) is None:
49 # not yet adopted, we may want to try again later
50 return None
51 try:
52 return self.__rd
53 except AttributeError:
54 parent = self.parent
55 while parent is not None:
56 if hasattr(parent, "rd") and parent.rd is not None:
57 self.__rd = parent.rd
58 break
59 parent = parent.parent
60 else: # a parent hasn't been adopted yet, try again later.
61 return None
62 return self.__rd
63 yield ("rd", property(_getRD))
64
65 def getFullId(self):
66 if self.rd is None:
67 return self.id
68 return "%s#%s"%(self.rd.sourceId, self.id)
69 yield ("getFullId", getFullId)
70
71 def makeUserDoc(self):
72 return None # don't mention it in docs -- users can't and mustn't set it.
73
74
75 class ResdirRelativeAttribute(base.FunctionRelativePathAttribute):
76 """is a path that is interpreted relative to the current RD's resdir.
77
78 The parent needs an RDAttribute.
79 """
80 def __init__(self, name, default=None, description="Undocumented", **kwargs):
81 base.FunctionRelativePathAttribute.__init__(self, name,
82 baseFunction=self.getResdir,
83 default=default, description=description, **kwargs)
84
85 def getResdir(self, instance):
86 if instance.rd is None:
87 # we don't have a parent yet, but someone wants to see our
88 # value. This can happen if an element is validated before
89 # it is adopted (which we probably should forbid). Here, we
90 # hack around it and hope nobody trips over it
91 return None
92 return instance.rd.resdir
93
94
95 class ProfileListAttribute(base.AtomicAttribute):
96 """An attribute containing a comma separated list of profile names.
97
98 There's the special role name "defaults" for whatever default this
99 profile list was constructed with.
100 """
101 typeDesc_ = "Comma separated list of profile names"
102
103 def __init__(self, name, default, description, defaultSource):
104 base.AtomicAttribute.__init__(self, name, base.Computed, description)
105 self.realDefault = default
106 self.defaultSource_ = defaultSource
107
108 @property
109 def default_(self):
110 return self.realDefault.copy()
111
112 def parse(self, value):
113 pNames = set()
114 for pName in value.split(","):
115 pName = pName.strip()
116 if not pName:
117 continue
118 if pName=="defaults":
119 pNames = pNames|self.default_
120 else:
121 pNames.add(pName)
122 return pNames
123
124 def unparse(self, value):
125 # It would be nice to reconstruct "defaults" here, but right now it's
126 # certainly not worth the effort.
127 return ", ".join(value)
128
129 def makeUserDoc(self):
130 return (f"**{self.name_}** ({self.typeDesc_}, defaults to"
131 f" {self.defaultSource_} from gavorc) -- {self.description_}")
132
133
134 class PrivilegesMixin(base.StructCallbacks):
135 """A mixin for structures declaring access to database objects (tables,
136 schemas).
137
138 Access is managed on the level of database profiles. Thus, the names
139 here are not directly role names in the database.
140
141 We have two types of privileges: "All" means at least read and write,
142 and "Read" meaning at least read and lookup.
143 """
144 _readProfiles = ProfileListAttribute("readProfiles",
145 default=base.getConfig("db", "queryProfiles"),
146 description="A (comma separated) list of profile names through"
147 " which the object can be read.",
148 defaultSource="[db]queryProfiles")
149 _allProfiles = ProfileListAttribute("allProfiles",
150 default=base.getConfig("db", "maintainers"),
151 description="A (comma separated) list of profile names through"
152 " which the object can be written or administred.",
153 defaultSource="[db]maintainers")
154
155
156 @functools.lru_cache(None)
157 def getIvoidsForRDId(rdId):
158 with base.getTableConn() as conn:
159 res = [res[0] for res in conn.query(
160 "SELECT ivoid FROM dc.resources WHERE sourcerd=%(rdId)s",
161 locals())]
162 return res
163
164
165 class IVOMetaMixin(base.StructCallbacks):
166 """A mixin for resources aspiring to have IVO ids.
167
168 All those need to have an RDAttribute. In return, we're filling
169 in sensible defaults for the referenceURL, identifier, and status
170 meta items (which, as usual for the computed metas, are overridable
171 by normal setMetas).
172 """
173 def _meta_referenceURL(self):
174 if self.rd is None:
175 return None
176
177 return base.META_CLASSES_FOR_KEYS["referenceURL"](
178 self.getURL("info"),
179 title="Service info")
180
181 def _meta_identifier(self):
182 # if we're called without an RD, that's probably while we're
183 # copied. Code there knows what to do when we return None
184 if self.rd is None:
185 return None
186
187 return "ivo://%s/%s/%s"%(base.getConfig("ivoa", "authority"),
188 urllib.parse.quote(self.rd.sourceId), self.id)
189
190 def _meta_published_identifier(self):
191 """returns identifier if we believe we are dealing with a published
192 resource.
193
194 There is a hitch here: there are many situations in which the "object"
195 itself has no publications even though there is a published resource,
196 for instance, when a table is published through a service or
197 a service as a secondary service. Hence, we don't look at our
198 metadata here but instead at what's actually published, and
199 we return all identifiers associated with the current RD. This
200 may be overdoing things a bit, but in this particular case that's
201 better than the other way round.
202 """
203 if not getattr(self, "rd", None):
204 return
205 try:
206 return [meta.MetaValue(i) for i in getIvoidsForRDId(self.rd.sourceId)
207 ] or None
208 except base.DBError:
209 return None
210
211 def _meta_status(self):
212 return "active"
213
214
215 class Registration(base.Structure, base.MetaMixin):
216 """A request for registration of a data or table item.
217
218 This is much like publish for services, just for data and tables;
219 since they have no renderers, you can only have one register element
220 per such element.
221
222 Data registrations may refer to published services that make their
223 data available.
224 """
225 name_ = "publish"
226 docName_ = "publish (data)"
227
228 _sets = base.StringSetAttribute("sets", default=frozenset(["ivo_managed"]),
229 description="A comma-separated list of sets this data will be"
230 " published in. To publish data to the VO registry, just"
231 " say ivo_managed here, local puts a link on the front page."
232 " ivo_managed also is the default.")
233
234 _servedThrough = base.ReferenceListAttribute("services",
235 description="A DC-internal reference to a service that lets users"
236 " query that within the data collection; tables with adql=True"
237 " are automatically declared as isServiceFor the TAP service.")
238
239 # the following attribute is for compatibility with service.Publication
240 # in case someone manages to pass such a publication to the capability
241 # builder.
242 auxiliary = True
243
244 def _completeMetadataFromResRow(self, resRow):
245 """fiddles publication dates from a dc.resources row for the parent
246 table or data item.
247
248 (see rscdef.rdjinj for where this comes from).
249 """
250 if resRow.get("rectimestamp"):
251 self.parent.setMeta("_metadataUpdated", resRow["rectimestamp"])
252 # we ignore dateupdated here, assuming that the info coming from
253 # the RD is more current.
254
255 def completeElement(self, ctx):
256 if (ctx is not None
257 and self.id
258 and self.parent.rd is not None):
259 self._completeMetadataFromResRow(
260 ctx.getInjected("resprop:%s#%s"%(
261 self.parent.rd.sourceId, self.parent.id), {}))
262 super().completeElement(ctx)
263
264 def publishedForADQL(self):
265 """returns true if at least one table published is available for
266 TAP/ADQL.
267 """
268 if getattr(self.parent, "adql", False):
269 # single table
270 return True
271
272 for t in getattr(self.parent, "iterTableDefs", lambda: [])():
273 # data item with multiple tables
274 if t.adql:
275 return True
276
277 return False
278
279 def register(self):
280 """adds isServiceFor and isServedBy metadata to data, service pairs
281 in this registration.
282 """
283 if self.publishedForADQL():
284 tapSvc = base.caches.getRD("//tap").getById("run")
285 if not tapSvc in self.services:
286 self.services.append(tapSvc)
287
288 for srv in self.services:
289 srv.declareServes(self.parent)
290
291
292 class ColumnList(list):
293 """A list of column.Columns (or derived classes) that takes
294 care that no duplicates (in name) occur.
295
296 If you add a field with the same dest to a ColumnList, the previous
297 instance will be overwritten. The idea is that you can override
298 ColumnList in, e.g., interfaces later on.
299
300 Also, two ColumnLists are considered equal if they contain the
301 same names.
302
303 After construction, you should set the withinId attribute to
304 something that will help make sense of error messages.
305 """
306 def __init__(self, *args):
307 list.__init__(self, *args)
308 self.redoIndex()
309 self.withinId = "unnamed table"
310
311 def __contains__(self, fieldName):
312 return fieldName in self.nameIndex
313
314 def __eq__(self, other):
315 if isinstance(other, ColumnList):
316 myFields = set([f.name for f in self
317 if f.name not in self.internallyUsedFields])
318 otherFields = set([f.name for f in other
319 if f.name not in self.internallyUsedFields])
320 return myFields==otherFields
321 elif other==[] and len(self)==0:
322 return True
323 return False
324
325 def redoIndex(self):
326 """creates a mapping of names to list indexes.
327
328 You must call this when you dare to munge this manually (which you
329 shouldn't).
330 """
331 self.nameIndex = dict([(c.name, ct) for ct, c in enumerate(self)])
332
333 def deepcopy(self, newParent):
334 """returns a deep copy of self.
335
336 This means that all child structures are being copied. In that
337 process, they receive a new parent, which is why you need to
338 pass one in.
339 """
340 return self.__class__([c.copy(newParent) for c in self])
341
342 def getIdIndex(self):
343 try:
344 return self.__idIndex
345 except AttributeError:
346 self.__idIndex = dict((c.id, c) for c in self if c.id is not None)
347 return self.__idIndex
348
349 def append(self, item):
350 """adds the Column item to the data field list.
351
352 It will overwrite a Column of the same name if such a thing is already
353 in the list. Indices are updated.
354 """
355 key = item.name
356 if key in self.nameIndex:
357 nameInd = self.nameIndex[key]
358 assert self[nameInd].name==key, \
359 "Someone tampered with ColumnList"
360 self[nameInd] = item
361 else:
362 self.nameIndex[item.name] = len(self)
363 list.append(self, item)
364
365 def replace(self, oldCol, newCol):
366 ind = 0
367 while True:
368 if self[ind]==oldCol:
369 self[ind] = newCol
370 break
371 ind += 1
372 del self.nameIndex[oldCol.name]
373 self.nameIndex[newCol.name] = ind
374
375 def remove(self, col):
376 del self.nameIndex[col.name]
377 list.remove(self, col)
378
379 def extend(self, seq):
380 for item in seq:
381 self.append(item)
382
383 def getColumnByName(self, name):
384 """returns the column with name.
385
386 It will raise a NotFoundError if no such column exists.
387 """
388 try:
389 return self[self.nameIndex[name]]
390 except KeyError:
391 try:
392 return self[self.nameIndex[utils.QuotedName(name)]]
393 except KeyError:
394 raise base.NotFoundError(name, what="column", within=self.withinId)
395
396 def getColumnById(self, id):
397 """returns the column with id.
398
399 It will raise a NotFoundError if no such column exists.
400 """
401 try:
402 return self.getIdIndex()[id]
403 except KeyError:
404 raise base.NotFoundError(id, what="column", within=self.withinId)
405
406 def getColumnByUtype(self, utype):
407 """returns the column having utype.
408
409 This should be unique, but this method does not check for uniqueness.
410 """
411 utype = utype.lower()
412 for item in self:
413 if item.utype and item.utype.lower()==utype:
414 return item
415 raise base.NotFoundError(utype, what="column with utype",
416 within=self.withinId)
417
418 def getColumnsByUCD(self, ucd):
419 """returns all columns having ucd.
420 """
421 return [item for item in self if item.ucd==ucd]
422
423 def getColumnByUCD(self, ucd):
424 """returns the single, unique column having ucd.
425
426 It raises a StructureError if there is no such column or more than one.
427 """
428 cols = self.getColumnsByUCD(ucd)
429 if len(cols)==1:
430 return cols[0]
431 elif cols:
432 raise base.StructureError("More than one column for %s"%ucd)
433 else:
434 raise base.StructureError("No column for %s"%ucd)
435
436 def getColumnByUCDs(self, *ucds):
437 """returns the single, unique column having one of ucds.
438
439 This method has a confusing interface. It sole function is to
440 help when there are multiple possible UCDs that may be interesting
441 (like pos.eq.ra;meta.main and POS_EQ_RA_MAIN). It should only be
442 used for such cases.
443 """
444 for ucd in ucds:
445 try:
446 return self.getColumnByUCD(ucd)
447 except base.StructureError:
448 # probably just no column with this UCD, try next
449 pass
450 raise base.StructureError("No unique column for any of %s"%", ".join(ucds))
451
452
453 class ColumnListAttribute(base.StructListAttribute):
454 """An adapter from a ColumnList to a structure attribute.
455 """
456 @property
457 def default_(self):
458 return ColumnList()
459
460 def getCopy(self, instance, newParent, ctx):
461 return ColumnList(base.StructListAttribute.getCopy(self,
462 instance, newParent, ctx))
463
464 def replace(self, instance, oldStruct, newStruct):
465 if oldStruct.name!=newStruct.name:
466 raise base.StructureError("Can only replace fields of the same"
467 " name in a ColumnList")
468 getattr(instance, self.name_).append(newStruct)
469
470 def feedObject(self, instance, obj):
471 # we really want columns and params to have the proper parents
472 if isinstance(obj, list):
473 for child in obj:
474 self.feedObject(instance, child)
475 else:
476 if obj.parent and obj.parent is not instance:
477 obj = obj.copy(instance)
478 super().feedObject(instance, obj)
479
480
481 class NamePathAttribute(base.AtomicAttribute):
482 """defines an attribute NamePath used for resolution of "original"
483 attributes.
484
485 The NamePathAttribute provides a resolveName method as expected
486 by base.OriginalAttribute.
487 """
488 typeDesc_ = "id reference"
489
490 def __init__(self, **kwargs):
491 if "description" not in kwargs:
492 kwargs["description"] = ("Reference to an element tried to"
493 " satisfy requests for names in id references of this"
494 " element's children.")
495 base.AtomicAttribute.__init__(self, name="namePath", **kwargs)
496
497 def iterParentMethods(self):
498 def resolveName(instance, context, id):
499 if hasattr(instance, "parentTable"):
500 try:
501 return base.resolveNameBased(instance.parentTable, id)
502 except base.NotFoundError:
503 # try on real name path
504 pass
505
506 if hasattr(instance, "getByName"):
507 try:
508 return instance.getByName(id)
509 except base.NotFoundError:
510 pass
511
512 np = instance.namePath
513 if np is None and instance.parent:
514 np = getattr(instance.parent, "namePath", None)
515 if np is None:
516 raise base.NotFoundError(id, "Element with name", repr(self),
517 hint="No namePath here")
518 res = context.resolveId(np+"."+id)
519 return res
520 yield "resolveName", resolveName
521
522 def parse(self, value):
523 return value
524
525 def unparse(self, value):
526 return value
527
528
529 _atPattern = re.compile("@(%s)"%utils.identifierPattern.pattern[:-1])
530
531 def replaceProcDefAt(src, dictName="vars"):
532 """replaces @<identifier> with <dictName>["<identifier>"] in src.
533
534 We do this to support this shortcut in the vicinity of rowmakers (i.e.,
535 there and in procApps).
536 """
537 return _atPattern.sub(r'%s["\1"]'%dictName, src)
538
539
540 # this is mainly here for lack of a better place. I don't want it in
541 # base.parsecontext as it needs config, and I don't want it
542 # in user.common as it might be useful for non-UI stuff.
543 def getReferencedElement(refString, forceType=None, **kwargs):
544 """returns the element for the DaCHS reference ``refString``.
545
546 ``refString`` has the form ``rdId[#subRef]``; ``rdId`` can be
547 filesystem-relative, but the RD referenced must be below ``inputsDir``
548 anyway.
549
550 You can pass a structure class into ``forceType``, and a ``StructureError``
551 will be raised if what's pointed to by the id isn't of that type.
552
553 You should usually use ``base.resolveCrossId`` instead of this from *within*
554 DaCHS. This is intended for code handling RD ids from users.
555
556 This supports further keyword arguments to getRD.
557 """
558 # get the inputs postfix now so we don't pollute the current exception later
559 try:
560 cwdInInputs = utils.getRelativePath(os.getcwd(),
561 base.getConfig("inputsDir"), liberalChars=True)
562 except ValueError:
563 # not in inputs
564 cwdInInputs = None
565
566 try:
567 return base.resolveCrossId(refString, forceType=forceType, **kwargs)
568 except base.RDNotFound:
569 if cwdInInputs:
570 return base.resolveCrossId("%s/%s"%(cwdInInputs, refString),
571 forceType=forceType)
572 raise
573
574
575 @utils.document
576 def getStandardPubDID(path):
577 """returns the standard DaCHS PubDID for ``path``.
578
579 The publisher dataset identifier (PubDID) is important in protocols like
580 SSAP and obscore. If you use this function, the PubDID will be your
581 authority, the path component ~, and the inputs-relative path of
582 the input file as the parameter.
583
584 ``path`` can be relative, in which case it is interpreted relative to
585 the DaCHS ``inputsDir.``
586
587 You *can* define your PubDIDs in a different way, but you'd then need
588 to provide a custom descriptorGenerator to datalink services (and
589 might need other tricks). If your data comes from plain files, use
590 this function.
591
592 In a rowmaker, you'll usually use the \\standardPubDID macro.
593 """
594 # Why add inputsDir first and remove it again? Well, I want to keep
595 # getInputsRelativePath in the loop since it does some validation
596 # and may, at some point, do more.
597 if path[0]!="/":
598 path = base.getConfig("inputsDir") / path
599
600 auth = base.getConfig("ivoa", "authority")
601 if auth=="x-unregistred":
602 raise base.ReportableError("You must configure your IVOA authority"
603 " before creating standard PubDIDs.",
604 hint="Read up on 'Choosing your authority' in the tutorial to see how"
605 " to fix this.")
606
607 return "ivo://%s/~?%s"%(
608 auth,
609 getInputsRelativePath(path, liberalChars=True))
610
611
612 @utils.document
613 def getDatalinkMetaLink(dlSvc, accref):
614 """returns a datalink URL for the product referenced through accref
615 with the datalink service dlSvc.
616
617 This assumes that dlSvc uses the standard DaCHS pubDIDs. dlSvc
618 needs to be the service element.
619
620 Since DaCHS 2.13, this also accepts full pubDIDs rather than accrefs.
621
622 A typical use is in a metaMaker and would look like this::
623
624 getDatalinkMetaLink(rd.getById("dl"), descriptor.accref)
625 """
626 if not accref.startswith("ivo://"):
627 accref = getStandardPubDID(accref)
628
629 return '%s?ID=%s'%(
630 dlSvc.getURL("dlmeta"),
631 urllib.parse.quote_plus(accref))
632
633
634
635 @utils.document
636 def getAccrefFromStandardPubDID(pubdid,
637 authBase="ivo://%s/~?"%base.getConfig("ivoa", "authority")):
638 """returns an accref from a standard DaCHS PubDID.
639
640 This is basically the inverse of getStandardPubDID. It will raise
641 NotFound if pubdid "looks like a URI" (implementation detail: has a colon
642 in the first 10 characters) and does not start with ivo://<authority>/~?.
643 If it's not a URI, we assume it's a local accref and just return it.
644
645 The function does not check if the remaining characters are a valid
646 accref, much less whether it can be resolved.
647
648 authBase's default will reflect you system's settings on your installation,
649 which probably is not what's given in this documentation.
650 """
651 if ":" not in pubdid[:10]:
652 return pubdid
653
654 if not pubdid.startswith(authBase):
655 raise base.NotFoundError(pubdid,
656 "The authority in the dataset identifier",
657 "the authorities managed here")
658 return urllib.parse.unquote(pubdid[len(authBase):])
659
660
661 @utils.document
662 def getInputsRelativePath(absPath, liberalChars=True):
663 """returns absath relative to the DaCHS inputsDir.
664
665 If ``absPath`` is not below ``inputsDir``, a ``ValueError`` results. On
666 ``liberalChars``, we see the `function getRelativePath`_.
667
668 In rowmakers and rowfilters, you'll usually use the macro
669 ``\\inputRelativePath`` that inserts the appropriate code.
670 """
671 res = str(utils.getRelativePath(absPath,
672 base.getConfig("inputsDir"), liberalChars=liberalChars))
673 if res==".":
674 return ""
675 return res
676