Debian Codegraph @

gavo/registry/publication.py

raw ◀ ▶
1 Debian patch touch this file
1 """
2 "Publishing" service records -- grammar-type stuff and UI.
3
4 This module basically turns "publishable things" -- services, resource
5 records, data items -- into row dictionaries that can be entered into
6 the database.
7
8 This is one half of getting them into the registry. The other half is
9 done in identifiers and builders; these take the stuff from the database,
10 rebuilds actual objects and creates registry records from them. So,
11 the content of the service table is not actually used to build resource
12 records.
13 """
14
15 #c Copyright 2008-2025, the GAVO project <[email protected]>
16 #c
17 #c This program is free software, covered by the GNU GPL. See the
18 #c COPYING file in the source distribution.
19
20
21 import functools
22 import datetime
23 import itertools
24 import os
25 import urllib.parse
26
•27 from gavo import pkg_resources
28
29 from gavo import base
30 from gavo import grammars
31 from gavo import rsc
32 from gavo import rscdef
33 from gavo import utils
34
35 from gavo.registry import builders
36 from gavo.registry import common
37
38
39 # Names of renders that should not be shown to humans; these are
40 # also not included in the dc.interfaces table. Right now, this
41 # list only contains the VOSI renderers, but other infrastructure-type
42 # capabilities might belong here, too.
43 HIDDEN_RENDERERS = frozenset([
44 'tableMetadata', 'availability', 'capabilities'])
45
46
47 @functools.lru_cache(1)
48 def getManagedAuthorities():
49 """returns a (cached) set of authorities our main registry
50 manages.
51 """
52 reg = base.resolveCrossId("//services#registry")
53 return frozenset(v.getContent()
54 for v in reg.iterMeta("managedAuthority"))
55
56
57 def makeBaseRecord(res, keepTimestamp=False):
58 """returns a dictionary giving the metadata common to resource records.
59 """
60 # bomb out if critical metadata is missing
61 base.validateStructure(res)
62 # bomb out if, for some reason, we can't come up with a resource record
63 # for this guy
64 builders.getVOResourceElement(res)
65 # skip this resource if we must not publish it because we don't
66 # manage its authority
67 ivoid = base.getMetaText(res, "identifier")
68 auth = urllib.parse.urlparse(ivoid).netloc
69
70 if (auth=="x-unregistred"
71 and not "yes"==base.getMetaText(res, "i-am-sure", "")):
72 # allow this if people have no ivo_managed publications
73 if list(res.getPublicationsForSet(
74 {"ivo_managed"}, includeDatalink=False)):
75 raise base.ReportableError("Resource {} uses the authority"
76 " x-unregistered; this is not permitted.".format(res.getFullId()),
77 hint="This in all likelihood means that you are not setting"
78 " the [ivoa]authority config item in your gavo.rc. Read up"
79 " on 'Choosing your authority' in the tutorial to see how"
80 " to fix this.")
81
82 if not auth in getManagedAuthorities():
83 base.ui.notifyWarning("Skipping publication of resource"
84 " with identifier %s because we don't manage its authority"%
85 ivoid)
86 raise base.SkipThis("Resource from non-managed authority")
87
88 rec = {}
89 rec["ivoid"] = ivoid
90 rec["shortName"] = base.getMetaText(res, "shortName")
91 rec["sourceRD"] = res.rd.sourceId
92 rec["resId"] = res.id
93 rec["title"] = base.getMetaText(res, "title", propagate=True)
94 rec["deleted"] = False
95 rec["recTimestamp"] = datetime.datetime.utcnow()
96 rec["description"] = base.getMetaText(res, "description")
97 rec["authors"] = "; ".join(m.getExpandedContent(res)
98 for m in res.iterMeta("creator.name", propagate=True))
99 rec["dateUpdated"] = base.getMetaText(res, "_dataUpdated", default=None)
100 rec["rank"] = int(base.getMetaText(res, "schema-rank", default="10000"))
101
102 if keepTimestamp:
103 try:
104 rec["recTimestamp"] = utils.parseISODT(
105 base.getMetaText(res, "recTimestamp")
106 or datetime.datetime.utcnow())
107 except base.NoMetaKey:
108 # not published, nothing to keep
109 pass
110
111 return rec
112
113
114 def iterAuthorsAndSubjects(resource, sourceRD, resId):
115 """yields rows for the subjects and authors tables.
116
117 resource is the meta-carrier for the resource to be described,
118 sourceRD and resId are its keys in the resources table.
119 """
120 for subject in [str(item) for item in resource.getMeta("subject") or (None,)]:
121 yield ("subjects", {
122 "sourceRD": sourceRD,
123 "resId": resId,
124 "subject": subject})
125
126 # for authors, we support a special notation, separating individual
127 # authors with semicolons.
128 for authors in resource.iterMeta("creator.name", propagate="True"):
129 authors = [s.strip() for s in
130 authors.getExpandedContent(resource).split(";")]
131 for author in authors:
132 if not author.startswith("et al"):
133 yield ("authors", {
134 "sourceRD": sourceRD,
135 "resId": resId,
136 "author": author})
137
138
139 def iterSvcRecs(service, keepTimestamp=False):
140 """iterates over records suitable for importing into the service list
141 for service.
142 """
143 if not service.publications:
144 return # don't worry about missing meta if there are no publications
145
146 try:
147 rec = makeBaseRecord(service, keepTimestamp)
148 except base.SkipThis:
149 return
150
151 rec["owner"] = service.limitTo
152 yield ("resources", rec)
153
154 # each publication becomes one interface, except for auxiliary
155 # and VOSI publications, which are for the VO registry only.
156 for pub in service.publications:
157 if pub.auxiliary:
158 continue
159 if pub.render in HIDDEN_RENDERERS:
160 continue
161
162 try:
163 browseable = service.isBrowseableWith(pub.render)
164 except AttributeError: # service is not a ServiceBasedPage
165 browseable = False
166
167 pubService = service
168 if pub.service:
169 pubService = pub.service
170
171 intfRec = {
172 "sourceRD": rec["sourceRD"],
173 "resId": rec["resId"],
174 "renderer": pub.render,
175 "accessURL": pubService.getURL(pub.render, absolute=False),
176 "referenceURL": base.getMetaText(pubService, "referenceURL"),
177 "browseable": browseable,
178 "deleted": False}
179 yield ("interfaces", intfRec)
180
181 for setName in pub.sets:
182 intfRec.copy()
183 intfRec["setName"] = setName
184 yield ("sets", intfRec)
185
186 for pair in iterAuthorsAndSubjects(service,
187 rec["sourceRD"], rec["resId"]):
188 yield pair
189
190
191 def iterResRecs(res, keepTimestamp=False):
192 """as iterSvcRecs, just for ResRecs rather than Services.
193 """
194 try:
195 rec = makeBaseRecord(res, keepTimestamp)
196 except base.SkipThis:
197 return
198
199 # resource records only make sense if destined for the registry
200 rec["setName"] = "ivo_managed"
201 rec["renderer"] = "rcdisplay"
202 yield ("resources", rec)
203 yield ("sets", rec)
204
205 for pair in iterAuthorsAndSubjects(res,
206 rec["sourceRD"], rec["resId"]):
207 yield pair
208
209
210 def iterDataRecs(res, keepTimestamp=False):
211 """as iterSvcRecs, just for DataDescriptors rather than Services.
212 """
213 try:
214 rec = makeBaseRecord(res, keepTimestamp)
215 except base.SkipThis:
216 return
217
218 yield ("resources", rec)
219 for setName in res.registration.sets:
220 rec["setName"] = setName
221 rec["renderer"] = "rcdisplay"
222 yield ("sets", rec.copy())
223 # if we have a local publication, add a fake interface with
224 # an accessURL pointing towards TAP
225 if setName=="local":
226 refURL = base.getMetaText(res, "referenceURL", macroPackage=res.rd)
227 yield ("interfaces", {
228 "sourceRD": rec["sourceRD"],
229 "resId": rec["resId"],
230 "renderer": "rcdisplay",
231 "accessURL": refURL+"?tapinfo=True" if refURL else None,
232 "referenceURL": refURL,
233 "browseable": False,
234 "deleted": False})
235
236 for pair in iterAuthorsAndSubjects(res,
237 rec["sourceRD"], rec["resId"]):
238 yield pair
239
240
241 def iterRDRecs(res, keepTimestamp=False):
242 """as iterSvcRecs, just for the entire RD.
243 """
244 try:
245 rec = makeBaseRecord(res, keepTimestamp)
246 except base.SkipThis:
247 return
248 rec["resId"] = "WHOLE_RD"
249 if rec["shortName"] is None:
250 rec["shortName"] = res.sourceId
251
252 yield ("resources", rec)
253 for setName in res.publication.sets:
254 rec["setName"] = setName
255 rec["renderer"] = "rcdisplay"
256 yield ("sets", rec.copy())
257
258 # if we have a local publication, add a fake interface with
259 # an accessURL pointing towards the RD info
260 if setName=="local":
261 refURL = base.getMetaText(res, "referenceURL")
262 yield ("interfaces", {
263 "sourceRD": rec["sourceRD"],
264 "resId": rec["resId"],
265 "renderer": "rcdisplay",
266 "accessURL": refURL,
267 "referenceURL": refURL,
268 "browseable": False,
269 "deleted": False})
270
271 for pair in iterAuthorsAndSubjects(res,
272 rec["sourceRD"], rec["resId"]):
273 yield pair
274
275
276 class RDRscRecIterator(grammars.RowIterator):
277 """A RowIterator yielding resource records for inclusion into the
278 service list for the services defined in the source token RD.
279 """
280 notify = False
281
282 def _iterRows(self):
283 if self.grammar.unpublish:
284 return
285
286 if self.sourceToken.publication:
287 self.curSource = self.sourceToken.sourceId
288 yield from iterRDRecs(self.sourceToken, self.grammar.keepTimestamp)
289
290 for svc in self.sourceToken.services:
291 self.curSource = svc.id
292 yield from iterSvcRecs(svc, self.grammar.keepTimestamp)
293
294 for res in self.sourceToken.resRecs:
295 self.curSource = res.id
296 yield from iterResRecs(res, self.grammar.keepTimestamp)
297
298 for res in itertools.chain(self.sourceToken.tables, self.sourceToken.dds):
299 self.curSource = res.id
300 if res.registration:
301 yield from iterDataRecs(res, self.grammar.keepTimestamp)
302
303 # now see if there's a TAP-published table in there. If so,
304 # re-publish the TAP service, too, unless that table is published
305 # by itself (in which case we deem the metadata update on the
306 # table enough for now -- TODO: reconsider this when we allow
307 # TAP registration without an associated tableset)
308
309 ignoredRegistrations = frozenset(["local"])
310 if self.sourceToken.sourceId!="__system__/tap":
311 for table in self.sourceToken.tables:
312 if table.adql:
313 if (table.registration
314 and table.registration.sets>ignoredRegistrations):
315 # this table has an independently published tableset
316 continue
317 # we shortcut this and directly update the TAP timestamp
318 # since producing a TAP record can be fairly expensive.
319 with base.getWritableAdminConn() as conn:
320 conn.execute("UPDATE dc.resources SET"
321 " dateupdated=CURRENT_TIMESTAMP,"
322 " rectimestamp=CURRENT_TIMESTAMP"
323 " WHERE sourcerd='__system__/tap'")
324 break
325
326 def getLocation(self):
327 return "%s#%s"%(self.sourceToken.sourceId, self.curSource)
328
329
330 # extra handwork to deal with timestamps on deleted records
331 def getDeletedIdentifiersUpdater(conn, rd):
332 """returns a function to be called after records have been
333 updated to mark new deleted identifiers as changed.
334
335 The problem solved here is that we mark all resource metadata
336 belonging to and RD as deleted before feeding the new stuff in.
337 We don't want to change resources.rectimestamp there; this would,
338 for instance, bump old deleted records.
339
340 What we can do is see if there's new deleted records after and rd
341 is through and update their rectimestamp. We don't need to like it.
342 """
343 oldDeletedRecords = set(r[0] for r in
344 conn.query("select ivoid from dc.resources"
345 " where sourcerd=%(rdid)s and deleted",
346 {"rdid": rd.sourceId}))
347
348 def bumpNewDeletedRecords():
349 newDeletedRecords = set(r[0] for r in
350 conn.query("select ivoid from dc.resources"
351 " where sourcerd=%(rdid)s and deleted",
352 {"rdid": rd.sourceId}))
353 toBump = newDeletedRecords-oldDeletedRecords
354 if toBump:
355 conn.execute("update dc.resources set rectimestamp=%(now)s"
356 " where ivoid in %(ivoids)s", {
357 "now": datetime.datetime.utcnow(),
358 "ivoids": toBump})
359
360 return bumpNewDeletedRecords
361
362
363 class RDRscRecGrammar(grammars.Grammar):
364 """A grammar for "parsing" raw resource records from RDs.
365 """
366 rowIterator = RDRscRecIterator
367 isDispatching = True
368
369 # this is a flag to try and keep the registry timestamps as they are
370 # during republication.
371 keepTimestamp = False
372 # setting the following to false will inhibit the re-creation of
373 # resources even if they're still defined in the RD.
374 unpublish = False
375
376
377 def updateServiceList(rds,
378 metaToo=False,
379 connection=None,
380 onlyWarn=True,
381 keepTimestamp=False,
382 unpublish=False):
383 """updates the services defined in rds in the services table in the database.
384
385 This is what actually does the publication.
386 """
387 if metaToo:
388 raise NotImplementedError("Meta updating from within pub is no longer"
389 " supported. Use dachs imp -m instead.")
390
391 recordsWritten = 0
392 parseOptions = rsc.getParseOptions(validateRows=True, batchSize=20)
393 if connection is None:
394 connection = base.getDBConnection("admin")
395 dd = common.getServicesRD().getById("tables")
396 dd.grammar = base.makeStruct(RDRscRecGrammar)
397 dd.grammar.keepTimestamp = keepTimestamp
398 dd.grammar.unpublish = unpublish
399
400 depDD = common.getServicesRD().getById("deptable")
401 msg = None
402 for rd in rds:
403 if rd.sourceId.startswith("/"):
404 raise base.Error("Resource descriptor ID must not be absolute, but"
405 " '%s' seems to be."%rd.sourceId)
406
407 deletedUpdater = getDeletedIdentifiersUpdater(connection, rd)
408
409 try:
410 data = rsc.makeData(dd, forceSource=rd, parseOptions=parseOptions,
411 connection=connection)
412 recordsWritten += data.nAffected
413 rsc.makeData(depDD, forceSource=rd, connection=connection)
414 deletedUpdater()
415 connection.commit()
416
417 except base.MetaValidationError as ex:
418 msg = ("Aborting publication of rd '%s' since meta structure of"
419 " %s (id='%s') is invalid:\n * %s")%(
420 rd.sourceId, repr(ex.carrier), ex.carrier.id, "\n * ".join(ex.failures))
421 except base.NoMetaKey as ex:
422 msg = ("Aborting publication of '%s' at service '%s': Resource"
423 " record generation failed: %s"%(
424 rd.sourceId, ex.carrier.id, str(ex)))
425 except Exception as ex:
426 base.ui.notifyError("Fatal error while publishing from RD %s: %s"%(
427 rd.sourceId, str(ex)))
428 raise
429
430 if msg is not None:
431 if onlyWarn:
432 base.ui.notifyWarning(msg)
433 else:
434 raise base.ReportableError(msg)
435 msg = None
436
437 common.getServicesRD().updateMetaInDB(connection, "import")
438
439 connection.commit()
440 return recordsWritten
441
442
443 def _purgeFromServiceTables(rdId, conn):
444 """purges all resources coming from rdId from the registry tables.
445
446 This is not for user code that should rely on the tables doing the
447 right thing (e.g., setting the deleted flag rather than deleting rows).
448 Test code that is not in contact with the actual registry might want
449 this, though (until postgres grows nested transactions).
450 """
451 cursor = conn.cursor()
452 for tableName in [
453 "resources", "interfaces", "sets", "subjects", "res_dependencies",
454 "authors"]:
455 cursor.execute("delete from dc.%s where sourceRD=%%(rdId)s"%tableName,
456 {"rdId": rdId})
457 cursor.close()
458
459
460 def makeDeletedRecord(ivoid, conn):
461 """enters records into the internal service tables to mark ivoid
462 as deleted.
463 """
464 fakeId = ivoid.split("/")[-1] or "<empty>"
465 svcRD = base.caches.getRD("//services")
466 rscTable = rsc.TableForDef(svcRD.getById("resources"),
467 connection=conn)
468 rscTable.addRow({
469 "sourceRD": "deleted",
470 "resId": fakeId,
471 "shortName": "deleted",
472 "title": "Ex "+ivoid,
473 "description": "This is a sentinel for a record once published"
474 " by this registry but now dropped.",
475 "owner": None,
476 "dateUpdated": datetime.datetime.utcnow(),
477 "recTimestamp": datetime.datetime.utcnow(),
478 "deleted": True,
479 "ivoid": ivoid,
480 "authors": "",
481 "rank": 10000})
482
483 setTable = rsc.TableForDef(svcRD.getById("sets"),
484 connection=conn)
485 setTable.addRow({
486 "sourceRD": "deleted",
487 "resId": fakeId,
488 "setName": "ivo_managed",
489 "renderer": "custom",
490 "deleted": True})
491
492
493 ################ UI stuff
494
495 def findAllRDs():
496 """returns ids of all RDs (inputs and built-in) known to the system.
497 """
498 rds = []
499 inputsDir = base.getConfig("inputsDir")
500 for dir, dirs, files in os.walk(inputsDir):
501
502 if "DACHS_PRUNE" in files:
503 dirs = [] #noflake: deliberately manipulating loop variable
504 continue
505
506 for file in files:
507 if file.endswith(".rd"):
508 rds.append(os.path.splitext(
509 utils.getRelativePath(os.path.join(dir, file), inputsDir))[0])
510
511 for name in pkg_resources.resource_listdir('gavo',
512 "resources/inputs/__system__"):
513 if not name.endswith(".rd"): # ignore VCS files (and possibly others:-)
514 continue
515 rds.append(os.path.splitext("__system__/%s"%name)[0])
516 return rds
517
518
519 def findPublishedRDs():
520 """returns the ids of all RDs which have been published before.
521 """
522 with base.getTableConn() as conn:
523 return [r['sourcerd'] for r in conn.queryToDicts(
524 "select distinct sourcerd from dc.resources where not deleted")]
525
526
527 def getRDs(args):
528 """returns a list of RDs from a list of RD ids or paths.
529 """
530 from gavo import rscdesc
531 allRDs = []
532 for rdPath in args:
533 try:
534 allRDs.append(
535 rscdef.getReferencedElement(rdPath, forceType=rscdesc.RD))
536 except:
537 base.ui.notifyError("RD %s faulty, ignored.\n"%rdPath)
538 return allRDs
539
540
541 def parseCommandLine():
542 import argparse
543 parser = argparse.ArgumentParser(
544 description="Publish services from an RD")
545 parser.add_argument("-k", "--keep-timestamps",
546 help="Preserve the time stamp of the last record modification."
547 " This may sometimes be desirable with minor updates to an RD"
548 " that don't justify a re-publication to the VO.",
549 action="store_true", dest="keepTimestamp")
550 parser.add_argument("-u", "--unpublish", help="Unpublish all"
551 " resources coming from this RD",
552 dest="unpublish", action="store_true")
553 parser.add_argument("rd", type=str, nargs="+",
554 help="RDs to publish; you can give ids or file paths. Use the"
555 " magic value ALL to check all published RDs, ALL_RECURSE to look"
556 " for RDs in the file system (check twice for detritus before doing"
557 " that later thing).")
558 return parser.parse_args()
559
560
561 def main():
562 """handles the user interaction for gavo publish.
563 """
564 from gavo import rscdesc #noflake: register cache
565 args = parseCommandLine()
566
567 if len(args.rd)==1 and args.rd[0]=="ALL":
568 args.rd = findPublishedRDs()
569 elif len(args.rd)==1 and args.rd[0]=="ALL_RECURSE":
570 args.rd = findAllRDs()
571
572 updateServiceList(getRDs(args.rd),
573 keepTimestamp=args.keepTimestamp,
574 unpublish=args.unpublish)
575 base.tryRemoteReload("__system__/services")