Debian Codegraph @

gavo/svcs/service.py

raw
1 """
2 Services, i.e. combinations of a core and at least one renderer.
3
4 See the __init__.py docstring for a bit more on the general
5 architecture.
6 """
7
8 #c Copyright 2008-2025, the GAVO project <[email protected]>
9 #c
10 #c This program is free software, covered by the GNU GPL. See the
11 #c COPYING file in the source distribution.
12
13
14 import functools
15 import os
16 import urllib.parse
17
18 from twisted.web.template import tags as T #noflake: namespace registration
19
20 from gavo import base
21 from gavo import rsc
22 from gavo import rscdef
23 from gavo import utils
24 from gavo.base import meta
25 from gavo.formal import nevowc
26 from gavo.rsc import table
27 from gavo.rscdef import rmkdef
28 from gavo.svcs import common
29 from gavo.svcs import core
30 from gavo.svcs import inputdef
31 from gavo.svcs import outputdef
32 from gavo.svcs import renderers
33
34
35 MS = base.makeStruct
36
37
38 class PreparsedInput(dict):
39 """a sentinel class signalling to the service that its input already
40 is parsed.
41
42 This is for for stuff coming from nevow formal rather than request.strargs,
43 and to be fed into service.run.
44
45 Construct with a dictionary.
46 """
47
48
49 class Publication(base.Structure, base.ComputedMetaMixin):
50 """A specification of how a service should be published.
51
52 This contains most of the metadata for what is an interface in
53 registry speak.
54 """
55 name_ = "publish"
56
57 _rd = rscdef.RDAttribute()
58 _render = base.UnicodeAttribute("render", default=base.Undefined,
59 description="The renderer the publication will point at.",
60 copyable=True)
61 _sets = base.StringSetAttribute("sets",
62 description="Comma-separated list of sets this service will be"
63 " published in. Predefined are: local=publish on front page,"
64 " ivo_managed=register with the VO registry. If you leave it"
65 " empty, 'local' publication is assumed.",
66 copyable="True")
67 _service = base.ReferenceAttribute("service", default=base.NotGiven,
68 description="Reference for a service actually implementing the"
69 " capability corresponding to this publication. This is"
70 " mainly when there is a vs:WebBrowser service accompanying a VO"
71 " protocol service, and this other service should be published"
72 " in the same resource record; you would say something like"
73 ' ``<publish render="form" sets="..." service="web"/>``.',
74 copyable="True")
75 _auxiliary = base.BooleanAttribute("auxiliary", default=False,
76 description="Auxiliary publications are for capabilities"
77 " not intended to be picked up for all-VO queries, typically"
78 " because they are already registered with other services."
79 " This is mostly used internally; you probably have no reason"
80 " to touch it.")
81
82 def __repr__(self):
83 return "<%sPublication of %s in %s>"%(
84 "Auxiliary " if self.auxiliary else "",
85 self.service.getFullId(),
86 self.sets)
87
88 def _completeMetadataFromResRow(self, resRow):
89 """fiddles publication dates from a dc.resources row for the parent
90 service.
91
92 (see rscdef.rdjinj for where this comes from).
93 """
94 if resRow.get("rectimestamp"):
95 self.service.setMeta("_metadataUpdated", resRow["rectimestamp"])
96 # we ignore dateupdated here, assuming that the info coming from
97 # the RD is more current.
98
99 def completeElement(self, ctx):
100 if self.render is base.Undefined:
101 self.render = "form"
102 if not self.sets:
103 self.sets.add("local")
104 if self.service is base.NotGiven:
105 self.service = self.parent
106 self.setMetaParent(self.service)
107
108 if (ctx is not None
109 # RD-less services are probably testing-only, and they certainly
110 # won't be registered.
111 and self.rd is not None):
112 self._completeMetadataFromResRow(
113 ctx.getInjected("resprop:%s#%s"%(
114 self.service.rd.sourceId, self.service.id), {}))
115
116 super().completeElement(ctx)
117
118 def validate(self):
119 super().validate()
120 try:
121 renderers.getRenderer(self.render)
122 except KeyError:
123 raise base.StructureError("Unknown renderer: %s"%self.render)
124
125 unknownSets = self.sets-set(base.getConfig("ivoa", "validoaisets"))
126 if unknownSets:
127 raise base.StructureError("Invalid OAI set(s) %s"%
128 ", ".join(unknownSets),
129 hint="If you really want to use custom sets, declare add them"
130 " using the [ivoa]validOAISets config item.")
131
132 def _meta_accessURL(self):
133 return self.service.getURL(self.render, canonical=True)
134
135 def _meta_urlUse(self):
136 return renderers.getRenderer(self.render).urlUse
137
138 def _meta_requestMethod(self):
139 return renderers.getRenderer(self.render).preferredMethod
140
141 def _meta_resultType(self):
142 return renderers.getRenderer(self.render).resultType
143
144
145 class _inevowFake(object):
146 """A minimal fake for DaCHS1 imp.nevow.inevow.
147
148 DaCHS 1 docs instructed users to get the request object using
149 inevow.IRequest(ctx). This thing lets people run RDs doing that.
150
151 I guess we won't remove it any time soon -- it's not expensive, and
152 removing it would probably break quite a few RDs.
153 """
154 @classmethod
155 def IRequest(cls, ctx):
156 return ctx.request
157
158
159 class CustomPageFunction(base.Structure, base.RestrictionMixin):
160 """An abstract base for t.w.resource.Resource-related functions on services.
161 """
162 _name = base.UnicodeAttribute("name", default=base.Undefined,
163 description="Name of the render or data function (use this in the"
164 " n:render or n:data attribute in custom templates).",
165 copyable=True, strip=True)
166 _code = base.DataContent(description="Function body of the renderer"
167 " or data function; the"
168 " arguments are named ``request`` and ``tag``, but you can also use"
169 " legacy ctx.tag and ctx.request. If data has been set on a tag,"
170 " you will see it as ``data``.", copyable=True)
171
172 def onElementComplete(self):
173 super().onElementComplete()
174 vars = globals().copy()
175 vars["service"] = self.parent
176 vars["_FakeContext"] = _FakeContext
177 vars["inevow"] = _inevowFake
178 exec("\n".join([
179 "def %s(self, request, tag):"%(self.name),
180 " ctx = _FakeContext(tag, request)",
181 " data = tag.slotData",
182 utils.fixIndentation(self.content_, newIndent=" ",
183 governingLine=1).rstrip()]), vars)
184 self.func = vars[self.name]
185
186
187 class _FakeContext(object):
188 """A compatibility wrapper for legacy nevow contexts.
189
190 These don't exist any more, but I didn't want to break all custom
191 render and data functions in RDs, so I fake enough to give people
192 the standard ctx.tag. There's even a fake invevow above that's just
193 enough to pull the request from here.
194 """
195 def __init__(self, tag, request):
196 self.tag, self.request = tag, request
197
198
199 class CustomRF(CustomPageFunction):
200 """A custom render function for a service.
201
202 Custom render functions can be used to expose certain aspects of a service
203 to Nevow templates. Thus, their definition usually only makes sense with
204 custom templates, though you could, in principle, override built-in
205 render functions.
206
207 In the render functions, you have the names ctx for a context and
208 data for the "current data" (i.e., what's last been set using n:data).
209 In ctx, only use ctx.tag (the tag on which the n:render attribute
210 sits) and, if necessary ctx.request (the t.w request object).
211
212 Also, the active renderer is visible as self; the one thing you
213 might want to see from there is self.queryMeta, which contains,
214 for instance, the input parameters (but be careful: the inputTable
215 will be None when input errors are rendered, so it is better to write
216 something like::
217
218 if self.queryMeta["inputTable"] and self.queryMeta["inputTable"]...:
219
220 You can return anything that can be in a stan DOM. Usually, this will be
221 a string. To return HTML, use the stan DOM available under the T namespace.
222
223 As an example, the following code returns the current data as a link::
224
225 return ctx.tag[T.a(href=data)[data]]
226
227 You can access the embedding service as service, the embedding
228 RD as service.rd.
229 """
230 name_ = "customRF"
231
232
233 class CustomDF(CustomPageFunction):
234 """A custom data function for a service.
235
236 Custom data functions can be used to expose certain aspects of a service
237 to Nevow templates. Thus, their definition usually only makes sense with
238 custom templates, though you could, in principle, override built-in
239 render functions.
240
241 In the data functions, you have the names ctx for a context and
242 data for the "current data" (i.e., what's last been set using n:data).
243 In ctx, only use ctx.tag (the tag on which the n:render attribute
244 sits) and, if necessary ctx.request (the t.w request object).
245
246 Also, the active renderer is visible as self; the one thing you
247 might want to see from there is self.queryMeta, which contains,
248 for instance, the input parameters.
249
250
251 You can access the embedding service as service, the embedding
252 RD as service.rd.
253
254 You can return arbitrary python objects -- whatever the render functions
255 can deal with. You could, e.g., write::
256
257 <customDF name="now">
258 return datetime.datetime.utcnow()
259 </customDF>
260
261 You can use the request to fetch request parameters. Within DaCHS,
262 in addition to the clumsy request.args (mapping bytes to bytes), there
263 is also request.strargs (mapping strings to strings). So, access a
264 query parameter ``order`` like this::
265
266 sortOrder = ctx.request.strargs.get("order", ["authors"])
267 """
268 name_ = "customDF"
269
270
271 class CoreAttribute(base.ReferenceAttribute):
272 def __init__(self):
273 base.ReferenceAttribute.__init__(self, "core",
274 description="The core that does the computations for this service."
275 " Instead of a reference, you can use an immediate element"
276 " of some registered core.",
277 forceType=core.Core, copyable=True, aliases=list(core.CORE_REGISTRY.keys()))
278
279 def _makeChild(self, name, parent):
280 return core.getCore(name)(parent)
281
282
283 @functools.lru_cache(1)
284 def getDALIServiceKeys():
285 """returns a list of the service keys defined in //pql#DALIPars.
286
287 This is always the same object, so if you really have to change anything
288 in here, be sure to make copies before touching either the list or
289 the items.
290 """
291 nullSvc = base.parseFromString(Service,
292 """<service><nullCore/><FEED source="//pql#DALIPars"/></service>""")
293
294 res = []
295 for inputKey in nullSvc.serviceKeys:
296 # let's orphan them in a way that they won't be reparented
297 inputKey.parent_ = base.NotGiven
298 res.append(inputKey)
299
300 return res
301
302
303 class GetURLMixin:
304 """A mixin for classes with rd and id, letting them compute
305 URLs working with the DaCHS root.py URL dispatcher.
306 """
307 def getURL(self, rendName, absolute=True, canonical=False, **kwargs):
308 """returns the full canonical access URL of this service together
309 with renderer.
310
311 rendName is the name of the intended renderer in the registry
312 of renderers.
313
314 With absolute, a fully qualified URL is being returned.
315
316 Further keyword arguments are translated into URL parameters in the
317 query part.
318 """
319 basePath = "%s%s/%s"%(base.getConfig("web", "nevowRoot"),
320 self.rd.sourceId, self.id)
321 if absolute:
322 basePath = base.makeAbsoluteURL(basePath, canonical=canonical)
323 res = renderers.getRenderer(rendName
324 ).makeAccessURL(basePath)
325
326 if kwargs:
327 res = res+"?"+urllib.parse.urlencode(kwargs)
328 return res
329
330
331 class Service(base.Structure, base.ComputedMetaMixin,
332 base.StandardMacroMixin, rscdef.IVOMetaMixin,
333 GetURLMixin):
334 """A service definition.
335
336 A service is a combination of a core and one or more renderers. They
337 can be published, and they carry the metadata published into the VO.
338
339
340 Properties evaluated:
341
342 * votableRespectsOutputTable -- usually, VOTable output puts in
343 all columns from the underlying database table with low enough
344 verbLevel (essentially). When this property is "True" (case-sensitive),
345 that's not done and only the service's output table is evaluated.
346 * fixedFormat -- if this is set to "True", the form renderer will
347 not produce an output format selector (and we shouldn't produce
348 DALI RESPONSEFORMAT metadata).
349 * publishedRenderers -- when you publish an entire RD, use these
350 (comma-separated) renderers to create capabilities from this service
351 rather than what's in allowed. Set it to empty to hide the service
352 entirely.
353 * defaultSort -- this is a name of a database column and preselects a sort
354 order. Note again that this will slow down responses for all but the
355 smallest tables unless there is an index on that column.
356 """
357 name_ = "service"
358
359 _core = CoreAttribute()
360 _templates = base.DictAttribute("templates", description="Custom"
361 ' nevow templates for this service; use key "form" to replace the Form'
362 " renderer's standard template; qp uses resulttable and resultline"
363 " depending on whether there's many result lines or just one."
364 " Start the path with two slashes to access system templates.",
365 aliases=["template"],
366 itemAttD=rscdef.ResdirRelativeAttribute(
367 "template", description="resdir-relative path to a nevow template"
368 " used for the function given in key."), copyable=True)
369 _publications = base.StructListAttribute("publications",
370 childFactory=Publication, description="Sets and renderers this service"
371 " is published with.")
372 _limitTo = base.UnicodeAttribute("limitTo", default=None,
373 description="Limit access to the group given; the empty default disables"
374 " access control.", copyable="True")
375 _customPage = rscdef.ResdirRelativeAttribute("customPage", default=None,
376 description="resdir-relative path to custom page code. It is used"
377 " by the 'custom' renderer", copyable="True")
378 _allowedRenderers = base.StringSetAttribute("allowed",
379 description="Names of renderers allowed on this service; leave empty"
380 " to allow the form renderer only.", copyable=True)
381 _customRF = base.StructListAttribute("customRFs",
382 description="Custom render functions for use in custom templates.",
383 childFactory=CustomRF, copyable=True)
384 _customDF = base.StructListAttribute("customDFs",
385 description="Custom data functions for use in custom templates.",
386 childFactory=CustomDF, copyable=True)
387 _outputTable = base.StructAttribute("outputTable", default=None,
388 childFactory=outputdef.OutputTableDef, copyable=True, description=
389 "The output fields of this service.")
390 _serviceKeys = base.UniquedStructListAttribute("serviceKeys",
391 uniqueAttribute="name", policy="drop",
392 childFactory=inputdef.InputKey, description="Input widgets for"
393 " processing by the service, e.g. output sets.", copyable=True)
394 _defaultRenderer = base.UnicodeAttribute("defaultRenderer",
395 default=None, description="A name of a renderer used when"
396 " none is provided in the URL (lets you have shorter URLs).")
397
398 _rd = rscdef.RDAttribute()
399 _props = base.PropertyAttribute()
400 _original = base.OriginalAttribute()
401
402 metaModel = ("title(1), creationDate(1), description(1),"
403 " subject, referenceURL(1), shortName(!),"
404 " productTypeServed(? voc:product-type),"
405 " dataSource(? voc:data-source),"
406 " contentLevel(? voc:voresource/content_level)")
407
408 # formats that should query the same fields as HTML (the others behave
409 # like VOTables and offer a "verbosity" widget in forms).
410 htmlLikeFormats = ["HTML", "tar"]
411
412 ####################### Housekeeping methods
413
414 def __repr__(self):
415 return "<Service %s at %s>"%(self.id, self.getSourcePosition())
416
417 def completeElement(self, ctx):
418 super().completeElement(ctx)
419 if not self.allowed:
420 self.allowed.add("form")
421
422 if self.core is base.Undefined:
423 raise base.StructureError("Services must have cores (add <nullCore/>"
424 " if you really do not want a core, e.g., with fixed renderers).")
425
426 # if there's only one renderer on this service, make it the default
427 if self.defaultRenderer is None and len(self.allowed)==1:
428 self.defaultRenderer = list(self.allowed)[0]
429
430 # if there's a DALI-compliant renderer on this service, declare
431 # its service parameters (MAXREC, RESPONSEFORMAT, etc).
432 # Of course, other renderers might ignore them, but presumably
433 # the metadata generated from this are only really evaluated
434 # by VO/DALI components.
435 # "DALI-complicance" is currently determined by a parameter
436 # style of dali or pql.
437 for rendName in self.allowed:
438 try:
439 ps = renderers.getRenderer(rendName).parameterStyle
440 except base.NotFoundError:
441 # letting this exc through could lead to confusing error messages
442 # on cross-RD reference, so we just warn:
443 base.ui.notifyWarning("Invalid renderer spec '%s' on service at %s"%
444 (rendName, self.getSourcePosition()))
445 continue
446
447 if ps in ["dali", "pql"]:
448 for inputKey in getDALIServiceKeys():
449 self._serviceKeys.addStruct(self, inputKey)
450 break
451
452 # cache all kinds of things expensive to create and parse
453 self._coresCache = {}
454 self._loadedTemplates = {}
455
456 # Schedule the capabilities to be added when the parse is
457 # done (i.e., the RD is complete)
458 ctx.addExitFunc(lambda rd, ctx: self._addAutomaticCapabilities())
459
460 def onElementComplete(self):
461 super().onElementComplete()
462
463 # Index custom render/data functions
464 self.nevowRenderers = {}
465 for customRF in self.customRFs:
466 self.nevowRenderers[customRF.name] = customRF.func
467 self.nevowDataFunctions = {}
468 for customDF in self.customDFs:
469 self.nevowDataFunctions[customDF.name] = customDF.func
470
471 self._compileCustomPage()
472
473 self._computeResourceType()
474
475 if hasattr(self.core, "queriedTable"):
476 # Copy over any served-by relationships from our table if
477 # we query one. This is important, for instance, for
478 # obscore-published tables, where we want to let our
479 # clients know they could be using obscore instead.
480 for m in self.core.queriedTable.iterMeta("isServedBy"):
481 self.addMeta("isServedBy", m)
482
483
484 def _compileCustomPage(self):
485 if self.customPage:
486 try:
487 modNs, moddesc = utils.loadPythonModule(self.customPage)
488 modNs.RD = self.rd
489 getattr(modNs, "initModule", lambda: None)()
490 page = modNs.MainPage
491 except ImportError:
492 raise base.ui.logOldExc(
493 base.LiteralParseError("customPage", self.customPage,
494 hint="This means that an exception was raised while DaCHS"
495 " tried to import the renderer module. If DaCHS ran"
496 " with --debug, the original traceback is available"
497 " in the logs."))
498 self.customPageCode = page, (os.path.basename(self.customPage),moddesc)
499
500 def getTemplate(self, key, reload=False):
501 """returns the nevow template for the function key on this service.
502
503 Pass reload to force a reload of templates already parsed.
504 """
505 if reload or key not in self._loadedTemplates:
506 tp = self.templates[key]
507 if tp.startswith("//"):
508 self._loadedTemplates[key] = common.loadSystemTemplate(tp[2:])
509 else:
510 self._loadedTemplates[key] = nevowc.XMLFile(
511 os.path.join(self.rd.resdir, tp))
512 return self._loadedTemplates[key]
513
514 def getUWS(self):
515 """returns the UWS worker system for this service.
516
517 This is a service for the DALIAsyncRenderer.
518 """
519 if not hasattr(self, "uws"):
520 if hasattr(self.core, "workerSystem"):
521 self.uws = self.core.workerSystem
522 else:
523 # todo: we don't want that any more. People wanting user UWS
524 # should attach their worker systems to their cores in the future.
525 from gavo.protocols import useruws
526 self.uws = useruws.makeUWSForService(self)
527 return self.uws
528
529 ################### Registry and related methods.
530
531 @property
532 def isVOPublished(self, renderer=None):
533 """is true if there is any ivo_managed publication on this
534 service.
535
536 If renderer is non-None, only publications with this renderer name
537 count.
538 """
539 for pub in self.publications:
540 if "ivo_managed" in pub.sets:
541 if renderer:
542 if pub.render==renderer:
543 return True
544 else:
545 return True
546 return False
547
548 def _computeResourceType(self):
549 """sets the resType attribute.
550
551 Services are resources, and the registry code wants to know what kind.
552 This method ventures a guess. You can override this decision by setting
553 the resType meta item.
554 """
555 if (self.core.outputTable.columns
556 or "dali" in self.allowed):
557 self.resType = "catalogService"
558 else: # no output table defined, we're a plain service
559 self.resType = "dataService"
560
561 def _iterAutomaticCapabilities(self):
562 """helps _addAutomaticCapabilities.
563
564 Actually, we also use it to generate VOSI capabilities for
565 unpublished services.
566 """
567 vosiSet = set(["ivo_managed"])
568
569 # Let's give everything a capability, even null cores.
570 yield base.makeStruct(Publication,
571 render="capabilities",
572 sets=vosiSet,
573 parent_=self)
574
575 # If it has a core, there is tables involved, and we do VOSI tables, too
576 if not isinstance(self.core, core.getCore("nullCore")):
577 yield base.makeStruct(Publication,
578 render="availability",
579 sets=vosiSet,
580 parent_=self)
581 yield base.makeStruct(Publication,
582 render="tableMetadata",
583 sets=vosiSet,
584 parent_=self)
585
586 # things querying tables get a TAP relationship if
587 # their table is adql-queriable
588 if isinstance(self.core, core.getCore("dbCore")):
589 if self.core.queriedTable.adql:
590 tapService = base.resolveCrossId("//tap#run")
591 yield base.makeStruct(Publication,
592 render="dali",
593 sets=vosiSet,
594 auxiliary=True,
595 service=tapService,
596 parent_=self)
597
598 # things with examples meta get an examples capability
599 try:
600 self.getMeta("_example", raiseOnFail=True)
601 yield base.makeStruct(Publication,
602 render="examples",
603 sets=utils.AllEncompassingSet(),
604 parent_=self)
605 except base.NoMetaKey:
606 pass
607
608 def _addAutomaticCapabilities(self):
609 """adds some publications that are automatic for certain types
610 of services.
611
612 For services with ivo_managed publications and with useful cores
613 (this keeps out doc-like publications, which shouldn't have VOSI
614 resources), artificial VOSI publications are added.
615
616 If there is _example meta, an examples publication is added.
617
618 If this service exposes a table (i.e., a DbCore with a queriedTable)
619 and that table is adql-readable, also add an auxiliary TAP publication
620 if going to the VO.
621
622 This is being run as an exit function from the parse context as
623 we want the RD to be complete at this point (e.g., _examples
624 meta might come from it). This also lets us liberally resolve
625 references anywhere.
626 """
627 if not self.isVOPublished:
628 return
629
630 for pub in self._iterAutomaticCapabilities():
631 self._publications.feedObject(self, pub)
632
633 # This is no longer a good place to do this, but TAP-published
634 # tables need a isServedBy, and we since it's automatic, let's
635 # do it here.
636 # According to the "discovering dependent" note, we don't
637 # do the reverse relationship lest the TAP service
638 # gets too related...
639 if isinstance(self.core, core.getCore("dbCore")):
640 if self.core.queriedTable.adql:
641 tapService = base.resolveCrossId("//tap#run")
642 self.addMeta("isServedBy",
643 base.getMetaText(tapService, "title"),
644 ivoId=base.getMetaText(tapService, "identifier"))
645
646 def _iterAssociatedDatalinkServices(self):
647 """yields instances for datalink services appropriate for this
648 service.
649
650 The datalink services are taken from the core's queriedTable
651 attribute, if available. As a legacy fallback, for now
652 the datalink property on the service is supported as well for now,
653 but I'll try to get rid of that.
654 """
655 queriedTable = getattr(self.core, "queriedTable", None)
656 # if there's not queried table, there's not much point in
657 # having a datalink service.
658 linkGenerated = False
659 if queriedTable:
660 for svcRef in queriedTable.iterMeta(
661 "_associatedDatalinkService.serviceId"):
662 yield base.resolveId(self.rd, str(svcRef))
663 linkGenerated = True
664
665 # Legacy fallback in case no datalink services are found in the table:
666 # the datalink property
667 if not linkGenerated:
668 svcRef = self.getProperty("datalink", None)
669 if svcRef:
670 yield self.rd.getById(svcRef)
671
672 def getPublicationsForSet(self, names, includeDatalink=True):
673 """returns publications for a set of set names (the names argument).
674
675 In the special case names=None, all allowed renderers are treated
676 as published.
677 """
678 addAllAllowed = False
679 if names is None:
680 names = utils.AllEncompassingSet()
681 addAllAllowed = True
682
683 # the or in the list comprehension is because I can't see a way
684 # to make AllEmcompassingSet work on the right side of the
685 # operand, but it can occur on both sides.
686 result = [pub for pub in self.publications
687 if pub.sets & names or names & pub.sets]
688
689 # for ivo_managed, also return a datalink endpoints if they're
690 # there; the specs imply that might be useful some day.
691 # (btw., I think we shouldn't do that but instead extend
692 # publish so people can ask for other services to be included
693 # as capabilities).
694 if includeDatalink and "ivo_managed" in names:
695 for dlSvc in self._iterAssociatedDatalinkServices():
696 if "dlget" in dlSvc.allowed:
697 result.append(base.makeStruct(Publication,
698 render="dlget",
699 sets=set(["ivo_managed"]),
700 service=dlSvc))
701
702 if "dlasync" in dlSvc.allowed:
703 result.append(base.makeStruct(Publication,
704 render="dlasync",
705 sets=set(["ivo_managed"]),
706 service=dlSvc))
707
708 if "dlmeta" in dlSvc.allowed:
709 result.append(base.makeStruct(Publication,
710 render="dlmeta",
711 sets=set(["ivo_managed"]),
712 service=dlSvc))
713
714 if addAllAllowed: # name=None was passed in,
715 # add publications for everything allowed but not yet marked
716 # as published (for VOSI)
717 alreadyPublished = set(p.render for p in result
718 # some TAP subrenderers never get capabilities for now
719 # (but then all this needs to change anyway; cf. caproles)
720 ) | frozenset(["sync", "async", "user_tables"])
721
722 for rendName in self.allowed:
723 if not rendName in alreadyPublished:
724 result.append(base.makeStruct(Publication,
725 render=rendName, sets=set(["vosi"]), service=self))
726 # these will only be added here for unpublished services
727 for pub in self._iterAutomaticCapabilities():
728 if not pub.render in alreadyPublished:
729 result.append(pub)
730
731 return result
732
733 # used by getBrowserURL; keep external higher than form as long as
734 # we have mess like Potsdam CdC.
735 _browserScores = {"form": 10, "external": 12, "fixed": 15,
736 "custom": 8, "img.jpeg": 7, "static": 5, "hips": 3, "examples": 2}
737
738 def getBrowserURL(self, fq=True):
739 """returns a published URL that's suitable for a web browser or None if
740 no such URL can be guessed.
741
742 If you pass fq=False, you will get a path rather than a URL.
743 """
744 # There can be multiple candidates for browser URLs (like when a service
745 # has both form, static, and external renderers). If so, we select
746 # by plain scores.
747 browseables = []
748 for rendName in self.allowed:
749 if self.isBrowseableWith(rendName):
750 browseables.append((self._browserScores.get(rendName, -1), rendName))
751 if browseables:
752 return self.getURL(max(browseables)[1], absolute=fq)
753 else:
754 return None
755
756 def isBrowseableWith(self, rendName):
757 """returns true if rendering this service through rendName results
758 in something pretty in a web browser.
759 """
760 try:
761 return bool(renderers.getRenderer(rendName).isBrowseable(self))
762 except base.NotFoundError: # renderer name not known
763 return False
764
765 def getTableSet(self):
766 """returns a list of table definitions that have something to do with
767 this service.
768
769 This is for VOSI-type requests.
770
771 Basically, we're leaving the decision to the core, except when
772 we have an output Table of our own.
773 """
774 if self.outputTable and self.outputTable.columns:
775 return [self.outputTable]
776
777 return self.core.getRelevantTables()
778
779 def declareServes(self, data):
780 """adds meta to self and data indicating that data is served by
781 this service.
782
783 This is used by table/@adql and the publish element on data.
784 """
785 if data.registration:
786 self.addMeta("isServiceFor",
787 base.getMetaText(data, "title", default="Anonymous"),
788 ivoId=base.getMetaText(data, "identifier"))
789 data.addMeta("isServedBy",
790 base.getMetaText(self, "title"),
791 ivoId=base.getMetaText(self, "identifier"))
792
793 # Since this is always initiated by the data, the dependency
794 # must show up in its RD to be properly added on publication
795 # and to be removed when the data is removed.
796 data.rd.addDependency(self.rd, data.rd)
797
798 ########################## Output field selection
799
800 _allSet = set(["ALL"])
801
802 def _getFilteredColumns(self, columnSource, queryMeta, verbLevel):
803 """filters columns in columnSource according to verbosity and column
804 set given in queryMeta.
805
806 Actually, we only evaluate verbosity and requireSet.
807 """
808 if queryMeta["columnSet"]:
809 columnSource = [f for f in columnSource
810 if f.sets==self._allSet or queryMeta["columnSet"]&f.sets]
811
812 return [f for f in columnSource
813 if f.verbLevel<=verbLevel and not f.hidden]
814
815 def _getVOTableOutputFields(self, queryMeta):
816 """returns a list of OutputFields suitable for a VOTable
817 response described by queryMeta.
818
819 This is the set of all columns in the source table below
820 the verbosity defined in queryMeta, except that columns
821 with a displayHint of noxml present are thrown out, too.
822
823 When the service sets the votableRespectsOutputTable property to
824 "True", the column source is the service's output table rather
825 than the core's one.
826 """
827 verbLevel = queryMeta.get("verbosity")
828 if verbLevel=="HTML":
829 # SAMP transfers, typically: Pretend we're HTML
830 columnSource = self.getHTMLOutputFields(queryMeta)
831 verbLevel = 100 # column selection done by HTML, just filter noxml below
832
833 elif (self.getProperty("votableRespectsOutputTable", "").lower()=="true"
834 or queryMeta["columnSet"]):
835 columnSource = self.outputTable
836
837 else:
838 columnSource = self.getAllOutputFields()
839
840 fields = self._getFilteredColumns(
841 [f for f in columnSource
842 if f.displayHint.get("noxml")!="true"],
843 queryMeta,
844 verbLevel)
845
846 return rscdef.ColumnList(fields)
847
848 def getHTMLOutputFields(self, queryMeta, ignoreAdditionals=False,
849 raiseOnUnknown=True):
850 """returns a list of OutputFields suitable for an HTML response described
851 by queryMeta.
852
853 This is the service's output table if given, else the core's output
854 table at verbLevel 2. Additional fields can be set by the user.
855
856 raiseOnUnknown is used by customwidgets to avoid exceptions because of
857 bad additional fields during form construction (when they aren't
858 properly caught).
859 """
860 if self.outputTable:
861 columnSource, verbLevel = self.outputTable.columns, 20
862 else:
863 columnSource, verbLevel = self.core.outputTable.columns, 20
864
865 if queryMeta["verbosity"]!='HTML':
866 verbLevel = queryMeta["verbosity"]
867
868 fields = self._getFilteredColumns(columnSource, queryMeta, verbLevel)
869
870 # add user-selected fields
871 if not ignoreAdditionals and queryMeta["additionalFields"]:
872 try:
873 for fieldName in queryMeta["additionalFields"]:
874 col = self.core.outputTable.getColumnByName(fieldName)
875 if isinstance(col, outputdef.OutputField):
876 fields.append(col)
877 else:
878 fields.append(outputdef.OutputField.fromColumn(col))
879 except base.NotFoundError as msg:
880 if raiseOnUnknown:
881 raise base.ValidationError("The additional field %s you requested"
882 " does not exist"%repr(msg.lookedFor), colName="_OUTPUT")
883
884 return rscdef.ColumnList(fields)
885
886 def getCurOutputFields(self, queryMeta=None, raiseOnUnknown=True):
887 """returns a list of desired output fields for query meta.
888
889 This is for both the core and the formatter to figure out the
890 structure of the tables passed.
891 """
892 queryMeta = queryMeta or common.emptyQueryMeta
893
894 # "renderer" in queryMeta needs to be set in the run method below;
895 # the net effect is that format will come from RESPONSEFORMAT, _FORMAT,
896 # and the renderer default in sequence. If none of that is available,
897 # blindly go for default HTML (which in retrospect perhaps wasn't the
898 # best choice for DaCHS, but changing this now to VOTable would introduce
899 # needless breakage).
900 renderer = queryMeta.get("renderer")
901 format = queryMeta.get("format",
902 getattr(renderer, "defaultOutputFormat", None)) or "HTML"
903
904 if format in self.htmlLikeFormats:
905 return self.getHTMLOutputFields(queryMeta, raiseOnUnknown=raiseOnUnknown)
906 else:
907 return self._getVOTableOutputFields(queryMeta)
908
909 def getAllOutputFields(self):
910 """Returns a sequence of all available output fields.
911
912 This is what the core gives, and this is what will be declared
913 to the registry. Depending on the output format, the verbosity
914 level and perhaps other user settings, the actual columns produced
915 will be different.
916 """
917 return self.core.outputTable.columns
918
919 ################### running and input computation.
920
921 def getCoreFor(self, renderer, queryMeta):
922 """returns a core tailored for renderer.
923
924 See svcs.core's module docstring.
925
926 The argument can be a renderer or a renderer name.
927 """
928 if isinstance(renderer, str):
929 renderer = renderers.getRenderer(renderer)
930
931 # non-checked renderers use the core for info purposes only; don't
932 # bother for those
933 if not renderer.checkedRenderer:
934 return self.core
935
936 if renderer.name not in self._coresCache:
937 # Bad Hack: Tell datalink core what renderers are allowed on
938 # this service
939 allowedRendsForStealing = self.allowed #noflake: for stealVar downstack
940
941 res = self.core.adaptForRenderer(renderer, queryMeta)
942
943 # Hack: let the polymorphous datalink core suppress caching
944 if getattr(res, "nocache", False):
945 return res
946
947 self._coresCache[renderer.name] = res
948 return self._coresCache[renderer.name]
949
950 def getContextGrammarFor(self, renderer, queryMeta, core=None):
951 """returns an ContextGrammar appropriate for this renderer.
952
953 Pass in the core if you already have it as an optimisation (in
954 particular for datalink, where cores aren't automatically cached);
955 if you don't the core will be computed from the renderer.
956
957 In either case, the context grammar simply is built from the core's
958 inputTable.
959 """
960 if isinstance(renderer, str):
961 renderer = renderers.getRenderer(renderer)
962 if core is None:
963 core = self.getCoreFor(renderer, queryMeta)
964
965 serviceKeys = list(inputdef.filterInputKeys(self.serviceKeys,
966 renderer.name, inputdef.getRendererAdaptor(renderer)))
967
968 return MS(inputdef.ContextGrammar,
969 inputTD=core.inputTable,
970 inputKeys=serviceKeys)
971
972 def getInputKeysFor(self, renderer, queryMeta=common.emptyQueryMeta):
973 """returns a sequence of input keys, adapted for renderer.
974
975 The renderer argument may either be a renderer name, a renderer
976 class or a renderer instance.
977
978 This is the main interface for external entities to discover.
979 service metadata.
980 """
981 if isinstance(renderer, str):
982 renderer = renderers.getRenderer(renderer)
983 return list(self.getContextGrammarFor(
984 renderer, queryMeta).iterInputKeys())
985
986 def adaptCoreRes(self, coreRes, queryMeta):
987 """adapts a core result to the service's output table if appropriate.
988
989 Frankly, this was an early mis-design that complicates matters
990 unnecessarily, but I can't really drop it as long as some interesting
991 things are based on service's outputTables.
992
993 The adaptation works like this:
994
995 (0) if coreRes isn't a table, or that table has a noPostprocess
996 attribute, return coreRes and let the renderer worry about it.
997
998 (1) if names and units of newColumns the same as coreRes.columns,
999 accept coreRes as the new table
1000
1001 (2) if names of newColumns are a subset of coreRes.columns match
1002 but one or more units don't, set up a conversion routine and create
1003 new rows, combining them with newColumns to the result.
1004
1005 (3) else raise an error
1006
1007 (4) eventually, wrap everything up in a rsc.Data instance for
1008 compatibility with cores actually returning data items.
1009 """
1010 if not isinstance(coreRes, rsc.BaseTable):
1011 return coreRes
1012
1013 newTable = coreRes
1014 if "requestURI" in queryMeta:
1015 newTable.setMeta("request_uri", queryMeta["requestURI"])
1016
1017 if hasattr(coreRes, "noPostprocess"):
1018 colDiffs, swallowColumns = None, None
1019 else:
1020 newColumns = self.getCurOutputFields(queryMeta)
1021 swallowColumns = {c.name for c in coreRes.tableDef
1022 }-{c.name for c in newColumns}
1023 colDiffs = base.computeColumnConversions(
1024 newColumns, coreRes.tableDef.columns)
1025
1026 if colDiffs or swallowColumns:
1027 newTd = coreRes.tableDef.change(columns=newColumns)
1028 newTd.copyMetaFrom(coreRes.tableDef)
1029
1030 if colDiffs:
1031 rmk = rscdef.RowmakerDef(None)
1032 for col in newColumns:
1033 exprStart = ""
1034 if col.name in colDiffs:
1035 exprStart = "%s*"%colDiffs[col.name]
1036 rmk.feedObject("map", rmkdef.MapRule(rmk, dest=col.name,
1037 content_="%svars[%s]"%(exprStart, repr(col.name))
1038 ).finishElement(None))
1039 newTable = table.InMemoryTable(newTd, validate=False)
1040 mapper = rmk.finishElement(None).compileForTableDef(newTd)
1041 for r in coreRes:
1042 newTable.addRow(mapper(r, newTable))
1043
1044 else:
1045 newTable = rsc.TableForDef(newTd, rows=coreRes.rows)
1046
1047 newTable._params = coreRes._params
1048
1049 resData = rsc.wrapTable(newTable, rdSource=coreRes.tableDef)
1050
1051 return resData
1052
1053 def _runWithInputTable(self, core, inputTable, queryMeta):
1054 """runs the core and returns a service result.
1055 """
1056 queryMeta["inputTable"] = inputTable
1057 coreRes = core.run(self, inputTable, queryMeta)
1058 res = self.adaptCoreRes(coreRes, queryMeta)
1059
1060 return res
1061
1062 def run(self, renderer, args, queryMeta):
1063 """runs the service, returning a service result.
1064
1065 This is the main entry point for protocol renderers; args is
1066 a dict of lists as provided by request.strargs.
1067 """
1068 if isinstance(renderer, str):
1069 renderer = renderers.getRenderer(renderer)
1070
1071 core = self.getCoreFor(renderer, queryMeta)
1072 coreArgs = inputdef.CoreArgs.fromRawArgs(
1073 core.inputTable, args, self.getContextGrammarFor(
1074 renderer, queryMeta, core))
1075 queryMeta["renderer"] = renderer
1076
1077 return self._runWithInputTable(core, coreArgs, queryMeta)
1078
1079
1080 #################### meta and such
1081
1082 def _meta_available(self):
1083 # XXX TODO: have this ask the core
1084 return "true"
1085
1086 def _meta_sets(self):
1087 # this is the union of the sets of the publications; this
1088 # is a bit lame, but it's a consequence of our mismatch
1089 # between publications, capabilities, and services.
1090 # In practice, these sets are meaningless where they are
1091 # pulled from meta (everywhere except in service selection
1092 # and in list identifiers, both of which don't use this).
1093 # There's a copy of this in registry.nonservice.
1094 sets = set()
1095 for p in self.publications:
1096 sets |= p.sets
1097 if sets:
1098 return meta.MetaItem.fromSequence(
1099 [meta.MetaValue(s) for s in sets])
1100 else:
1101 return None
1102
1103 def macro_tablesForTAP(self):
1104 """returns a list of table names available for TAP querying.
1105
1106 This, really, is an implementation detail for the TAP service and
1107 might go away anytime.
1108 """
1109 # this is only used by tap.rd -- maybe it
1110 # should go there?
1111 from gavo.protocols import tap
1112
1113 schemas = {}
1114 for qname in tap.getAccessibleTables():
1115 try:
1116 schema, name = qname.split(".")
1117 except: # weird name
1118 continue
1119 schemas.setdefault(schema, []).append(name)
1120
1121 return ", ".join("%s from the %s schema"%(", ".join(tables), schema)
1122 for schema, tables in schemas.items())
1123
1124 def _meta_examplesLink(self):
1125 """returns a link to a examples for this service if any
1126 are available.
1127 """
1128 try:
1129 self.getMeta("_example", raiseOnFail=True)
1130 return base.META_CLASSES_FOR_KEYS["_related"](
1131 self.getURL("examples", False),
1132 title="DALI examples")
1133 except base.NoMetaKey:
1134 return None
1135
1136 def _meta_howtociteLink(self):
1137 """returns a link to a how-to-cite page for this service as an URL
1138 meta.
1139 """
1140 if self.getMeta("creationDate"):
1141 # depend on creationDate because to filter out totally whacko
1142 # RDs that will never make it to the Registry.
1143 return base.META_CLASSES_FOR_KEYS["_related"](
1144 self.getURL("howtocite", absolute=True),
1145 title="Advice on citing this resource")