| 1 |
""" |
| 2 |
Support for IVOA DAL and registry protocols. |
| 3 |
|
| 4 |
DALI-specified protocols are in dalirender, UWS/async is in asyncrender. |
| 5 |
""" |
| 6 |
|
| 7 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 8 |
#c |
| 9 |
#c This program is free software, covered by the GNU GPL. See the |
| 10 |
#c COPYING file in the source distribution. |
| 11 |
|
| 12 |
|
| 13 |
import datetime |
| 14 |
import json |
| 15 |
import os |
| 16 |
|
| 17 |
from twisted.internet import defer |
| 18 |
from twisted.web import server |
| 19 |
|
| 20 |
from gavo import base |
| 21 |
from gavo import formats |
| 22 |
from gavo import registry |
| 23 |
from gavo import rscdef |
| 24 |
from gavo import rsc |
| 25 |
from gavo import svcs |
| 26 |
from gavo import utils |
| 27 |
from gavo import votable |
| 28 |
from gavo.protocols import dali |
| 29 |
from gavo.protocols import soda |
| 30 |
from gavo.protocols import ssap |
| 31 |
from gavo.svcs import streaming |
| 32 |
from gavo.svcs import weberrors |
| 33 |
from gavo.votable import V |
| 34 |
from gavo.web import grend |
| 35 |
|
| 36 |
|
| 37 |
MS = base.makeStruct |
| 38 |
|
| 39 |
|
| 40 |
class DALRenderer(grend.ServiceBasedPage): |
| 41 |
"""A base class for renderers for the usual IVOA DAL protocols. |
| 42 |
|
| 43 |
This is for simple, GET-based DAL renderers (where we allow POST as |
| 44 |
well). They work using nevow forms, but with standard-compliant error |
| 45 |
reporting (i.e., in VOTables). |
| 46 |
|
| 47 |
Since DALRenderer mixes in FormMixin, it always has the form genFrom. |
| 48 |
""" |
| 49 |
resultType = base.votableType |
| 50 |
urlUse = "base" |
| 51 |
standardId = None |
| 52 |
defaultOutputFormat = "votable" |
| 53 |
|
| 54 |
def __init__(self, request, *args, **kwargs): |
| 55 |
grend.ServiceBasedPage.__init__(self, request, *args, **kwargs) |
| 56 |
self.defaultLimit = base.getConfig("ivoa", "dalDefaultLimit") |
| 57 |
|
| 58 |
@classmethod |
| 59 |
def makeAccessURL(cls, baseURL): |
| 60 |
return "%s/%s?"%(baseURL, cls.name) |
| 61 |
|
| 62 |
@classmethod |
| 63 |
def isBrowseable(self, service): |
| 64 |
return False |
| 65 |
|
| 66 |
def render(self, request, sync=False): |
| 67 |
"""runs the service and arranges for output to be produced. |
| 68 |
|
| 69 |
This will in general result in a deferred, except if you pass sync=True, |
| 70 |
in which case the thing tries to run everything in one go. |
| 71 |
|
| 72 |
Don't do that outside of unit tests. |
| 73 |
""" |
| 74 |
if sync: |
| 75 |
runner = self.runSync |
| 76 |
else: |
| 77 |
runner = self.runAsync |
| 78 |
|
| 79 |
# overwrite previous query meta for new limit |
| 80 |
self.queryMeta = svcs.QueryMeta.fromRequest(request, |
| 81 |
defaultLimit=self.defaultLimit) |
| 82 |
|
| 83 |
def execRunner(): |
| 84 |
if (self.queryMeta["dbLimit"]==0 |
| 85 |
or self.queryMeta.ctxArgs.get("FORMAT", "").lower()=="metadata"): |
| 86 |
return self._produceMetadata(request) |
| 87 |
else: |
| 88 |
dali.mangleUploads(request) |
| 89 |
return runner(request.strargs) |
| 90 |
|
| 91 |
defer.maybeDeferred(execRunner |
| 92 |
).addCallback(self._formatOutput, request, stream=not sync |
| 93 |
).addErrback(self._handleInputErrors, request |
| 94 |
).addErrback(self._handleRandomFailure, request |
| 95 |
).addErrback(request.finishCallback) |
| 96 |
|
| 97 |
return server.NOT_DONE_YET |
| 98 |
|
| 99 |
def renderSync(self, request): |
| 100 |
# This does essentially what render does, but synchronously. |
| 101 |
# This *should* work for DAL protocols, but it's really only |
| 102 |
# intended for unit testing. It's not a bug in a renderer or |
| 103 |
# core if renderSync doesn't work for it. |
| 104 |
# Also, this only has sense with a FakeRequest, as that's where |
| 105 |
# we take our result data from. |
| 106 |
res = self.render(request, sync=True) |
| 107 |
if res==server.NOT_DONE_YET: |
| 108 |
# well, we assume things really ran sync and let it go. |
| 109 |
pass |
| 110 |
elif res: |
| 111 |
request.write(res) |
| 112 |
return request.accumulator |
| 113 |
|
| 114 |
def _getMetadataData(self): |
| 115 |
"""returns a SIAP-style metadata data item. |
| 116 |
""" |
| 117 |
inputFields = [] |
| 118 |
for param in self.service.getInputKeysFor(self): |
| 119 |
# Caution: UPLOAD mangling is a *renderer* thing -- the service |
| 120 |
# doesn't know anything about it. Hence, parameter adaption |
| 121 |
# is *not* done by adapting the real service metadata. Instead: |
| 122 |
if param.type=="file": |
| 123 |
param = dali.getUploadKeyFor(param) |
| 124 |
inputFields.append(param.change(name="INPUT:"+param.name)) |
| 125 |
|
| 126 |
outputTD = self.service.core.outputTable.change(id="results") |
| 127 |
for param in outputTD.params: |
| 128 |
param.name = "OUTPUT:"+param.name |
| 129 |
|
| 130 |
nullRowmaker = MS(rscdef.RowmakerDef) |
| 131 |
dataDesc = MS(rscdef.DataDescriptor, makes=[ |
| 132 |
MS(rscdef.Make, table=outputTD, rowmaker=nullRowmaker)], |
| 133 |
params=inputFields, |
| 134 |
parent_=self.service.rd) |
| 135 |
|
| 136 |
data = rsc.makeData(dataDesc) |
| 137 |
data.contributingMetaCarriers.append(self.service) |
| 138 |
data.tables["results"].votCasts = self._outputTableCasts |
| 139 |
data.setMeta("_type", "meta") |
| 140 |
data.addMeta("info", |
| 141 |
base.getMetaText(self.service, "title") or "Unnamed", |
| 142 |
infoName="serviceInfo", |
| 143 |
infoValue=str(self.service.getURL(self.name))) |
| 144 |
|
| 145 |
return data |
| 146 |
|
| 147 |
def _produceMetadata(self, request): |
| 148 |
metaData = self._getMetadataData() |
| 149 |
metaData.addMeta("info", "OK", |
| 150 |
infoName="QUERY_STATUS", infoValue="OK") |
| 151 |
request.setHeader("content-type", "text/xml") |
| 152 |
votLit = formats.getFormatted("votable", metaData) |
| 153 |
# maybe provide a better way to attach stylesheet info? |
| 154 |
splitPos = votLit.find(b"?>")+2 |
| 155 |
|
| 156 |
return base.votableType, (votLit[:splitPos]+( |
| 157 |
b"<?xml-stylesheet href='/static" |
| 158 |
b"/xsl/meta-votable-to-html.xsl' type='text/xsl'?>" |
| 159 |
)+votLit[splitPos:]) |
| 160 |
|
| 161 |
def _writeErrorTable(self, |
| 162 |
request, |
| 163 |
errmsg, |
| 164 |
httpStatus=200, |
| 165 |
queryStatus="ERROR"): |
| 166 |
# Unfortunately, most legacy DAL specs say the error messages must |
| 167 |
# be delivered with a 200 response code. I hope this is going |
| 168 |
# to change at some point, so I let renderers order sane response |
| 169 |
# codes. |
| 170 |
if not request.client: |
| 171 |
# remote side has gone away -- avoid triggering ugly errors |
| 172 |
return |
| 173 |
|
| 174 |
return dali.serveDALIError(request, errmsg, |
| 175 |
httpStatus=httpStatus, queryStatus=queryStatus) |
| 176 |
|
| 177 |
def _formatOutput(self, data, request, stream=True): |
| 178 |
if isinstance(data, tuple): |
| 179 |
# core returned a complete document (mime and string) |
| 180 |
mime, payload = data |
| 181 |
request.setHeader("content-type", mime) |
| 182 |
|
| 183 |
if stream: |
| 184 |
return streaming.streamOut( |
| 185 |
lambda f: f.write(payload), request, self.queryMeta) |
| 186 |
else: |
| 187 |
request.write(payload) |
| 188 |
request.finish() |
| 189 |
return server.NOT_DONE_YET |
| 190 |
|
| 191 |
data.contributingMetaCarriers.append(self.service) |
| 192 |
|
| 193 |
data.getPrimaryTable().setMeta("request_uri", request.asGETURI()) |
| 194 |
|
| 195 |
data.addMeta("info", "", infoName="QUERY_STATUS", |
| 196 |
infoValue=base.getMetaText(data.getPrimaryTable(), |
| 197 |
"_queryStatus")) |
| 198 |
|
| 199 |
if self.standardId: |
| 200 |
data.addMeta("info", |
| 201 |
"Written by DaCHS %s %s"%(base.getVersion(), self.__class__.__name__), |
| 202 |
infoName="standardID", |
| 203 |
infoValue=self.standardId) |
| 204 |
|
| 205 |
destFormat = self.defaultOutputFormat |
| 206 |
if "responseformat" in self.queryMeta.ctxArgs: |
| 207 |
# This is our DALI RESPONSEFORMAT implementation; the corresponding |
| 208 |
# parameter is declared automatically in Service.completeElement |
| 209 |
# from pql#DALIPars. |
| 210 |
destFormat = self.queryMeta.ctxArgs["responseformat"] |
| 211 |
requestedType = formats.getMIMEFor(destFormat, destFormat) |
| 212 |
else: |
| 213 |
requestedType = self.resultType |
| 214 |
|
| 215 |
request.setHeader("content-type", requestedType) |
| 216 |
request.setHeader('content-disposition', |
| 217 |
'attachment; filename="result%s"'% |
| 218 |
formats.getExtensionFor(requestedType)) |
| 219 |
|
| 220 |
formatterArgs = {} |
| 221 |
|
| 222 |
if stream: |
| 223 |
|
| 224 |
def writeStuff(outputFile): |
| 225 |
formats.formatData(destFormat, |
| 226 |
data, outputFile, acquireSamples=False, **formatterArgs) |
| 227 |
|
| 228 |
return streaming.streamOut(writeStuff, request, self.queryMeta) |
| 229 |
|
| 230 |
else: |
| 231 |
return formats.formatData(destFormat, |
| 232 |
data, request, acquireSamples=False, **formatterArgs) |
| 233 |
|
| 234 |
def _handleRandomFailure(self, failure, request): |
| 235 |
base.ui.notifyFailure(failure) |
| 236 |
return self._writeErrorTable(request, failure.value, 500) |
| 237 |
|
| 238 |
def _handleInputErrors(self, failure, request): |
| 239 |
httpStatus, queryStatus = 200, "ERROR" |
| 240 |
|
| 241 |
if base.DEBUG: |
| 242 |
base.ui.notifyFailure(failure) |
| 243 |
|
| 244 |
if isinstance(failure.value, base.EmptyData): |
| 245 |
httpStatus, queryStatus = 400, "EMPTY" |
| 246 |
|
| 247 |
return self._writeErrorTable( |
| 248 |
request, |
| 249 |
failure.value, |
| 250 |
httpStatus=httpStatus, |
| 251 |
queryStatus=queryStatus) |
| 252 |
|
| 253 |
|
| 254 |
class SCSRenderer(DALRenderer): |
| 255 |
""" |
| 256 |
A renderer for the Simple Cone Search protocol. |
| 257 |
|
| 258 |
These do their error signaling in the value attribute of an |
| 259 |
INFO child of RESOURCE. |
| 260 |
|
| 261 |
You must set the following metadata items on services using |
| 262 |
this renderer if you want to register them: |
| 263 |
|
| 264 |
* testQuery.ra, testQuery.dec -- A position for which an object is present |
| 265 |
within 0.001 degrees. |
| 266 |
""" |
| 267 |
name = "scs.xml" |
| 268 |
version = "1.0" |
| 269 |
parameterStyle = "dali" |
| 270 |
standardId = "ivo://ivoa.net/std/ConeSearch" |
| 271 |
|
| 272 |
# move the ucdCasts from formatOutput here. |
| 273 |
_outputTableCasts = {} |
| 274 |
|
| 275 |
def __init__(self, request, *args, **kwargs): |
| 276 |
DALRenderer.__init__(self, request, *args, **kwargs) |
| 277 |
self.defaultLimit = base.getConfig("ivoa", "dalDefaultLimit")*10 |
| 278 |
|
| 279 |
def _writeErrorTable(self, request, msg, httpStatus=200, queryStatus="ERROR"): |
| 280 |
if not request.client: |
| 281 |
# remote side has gone away -- avoid triggering ugly errors |
| 282 |
return |
| 283 |
|
| 284 |
request.setHeader("content-type", base.votableType) |
| 285 |
votable.write(V.VOTABLE[ |
| 286 |
V.DESCRIPTION[base.getMetaText(self.service, "description")], |
| 287 |
V.RESOURCE(type="results")[ |
| 288 |
V.INFO(ID="Error", name="Error", |
| 289 |
value=str(msg).replace('"', '\\"')), |
| 290 |
V.INFO(name="request", value=request.asGETURI())]], request) |
| 291 |
request.write("\n") |
| 292 |
request.finish() |
| 293 |
|
| 294 |
def _formatOutput(self, data, request, stream=True): |
| 295 |
"""makes output SCS 1.02 compatible or causes the service to error out. |
| 296 |
|
| 297 |
This comprises mapping meta.id;meta.main to ID_MAIN and |
| 298 |
pos.eq* to POS_EQ*. |
| 299 |
""" |
| 300 |
if isinstance(data, tuple): |
| 301 |
return DALRenderer._formatOutput(self, data, request, stream) |
| 302 |
|
| 303 |
ucdCasts = { |
| 304 |
"meta.id;meta.main": {"ucd": "ID_MAIN", "datatype": "char", |
| 305 |
"arraysize": "*"}, |
| 306 |
"pos.eq.ra;meta.main": {"ucd": "POS_EQ_RA_MAIN", |
| 307 |
"datatype": "double"}, |
| 308 |
"pos.eq.dec;meta.main": {"ucd": "POS_EQ_DEC_MAIN", |
| 309 |
"datatype": "double"}, |
| 310 |
} |
| 311 |
realCasts = {} |
| 312 |
table = data.getPrimaryTable() |
| 313 |
for ind, ofield in enumerate(table.tableDef.columns): |
| 314 |
if ofield.ucd in ucdCasts: |
| 315 |
realCasts[ofield.name] = ucdCasts.pop(ofield.ucd) |
| 316 |
if ucdCasts: |
| 317 |
return self._writeErrorTable(request, "Table cannot be formatted for" |
| 318 |
" SCS. Column(s) with the following new UCD(s) were missing in" |
| 319 |
" output table: %s"%', '.join(ucdCasts)) |
| 320 |
|
| 321 |
# allow integers as ID_MAIN [HACK -- this needs to become saner. |
| 322 |
# conditional cast functions?] |
| 323 |
idCol = table.tableDef.getColumnByUCD("meta.id;meta.main") |
| 324 |
if idCol.type in set(["integer", "bigint", "smallint"]): |
| 325 |
realCasts[idCol.name]["castFunction"] = str |
| 326 |
table.votCasts = realCasts |
| 327 |
|
| 328 |
return DALRenderer._formatOutput(self, |
| 329 |
data, request, stream=stream) |
| 330 |
|
| 331 |
|
| 332 |
class SIAPRenderer(DALRenderer): |
| 333 |
"""A renderer for a the Simple Image Access Protocol. |
| 334 |
|
| 335 |
These have errors in the content of an info element, and they support |
| 336 |
metadata queries. |
| 337 |
|
| 338 |
For registration, services using this renderer must set the following |
| 339 |
metadata items: |
| 340 |
|
| 341 |
- sia.type -- one of Cutout, Mosaic, Atlas, Pointed, see SIAP spec |
| 342 |
|
| 343 |
You should set the following metadata items: |
| 344 |
|
| 345 |
- testQuery.pos.ra, testQuery.pos.dec -- RA and Dec for a query that |
| 346 |
yields at least one image |
| 347 |
- testQuery.size.ra, testQuery.size.dec -- RoI extent for a query that |
| 348 |
yields at least one image. |
| 349 |
|
| 350 |
You can set the following metadata items (there are defaults on them |
| 351 |
that basically communicate there are no reasonable limits on them): |
| 352 |
|
| 353 |
- sia.maxQueryRegionSize.(long|lat) |
| 354 |
- sia.maxImageExtent.(long|lat) |
| 355 |
- sia.maxFileSize |
| 356 |
- sia.maxRecord (default dalHardLimit global meta) |
| 357 |
""" |
| 358 |
version = "1.0" |
| 359 |
name = "siap.xml" |
| 360 |
parameterStyle = "pql" |
| 361 |
standardId = "ivo://ivoa.net/std/sia" |
| 362 |
|
| 363 |
_outputTableCasts = { |
| 364 |
"pixelScale": { |
| 365 |
"datatype": "double", |
| 366 |
"arraysize": "*", |
| 367 |
"ucd": "VOX:Image_Scale"}, |
| 368 |
"wcs_cdmatrix": { |
| 369 |
"datatype": "double", |
| 370 |
"arraysize": "*", |
| 371 |
"ucd": "VOX:WCS_CDMatrix"}, |
| 372 |
"wcs_refValues": { |
| 373 |
"datatype": "double", |
| 374 |
"arraysize": "*", |
| 375 |
"ucd": "VOX:WCS_CoordRefValue"}, |
| 376 |
"bandpassHi": { |
| 377 |
"datatype": "double", |
| 378 |
"ucd": "VOX:BandPass_HiLimit"}, |
| 379 |
"bandpassLo": { |
| 380 |
"datatype": "double", |
| 381 |
"ucd": "VOX:BandPass_LoLimit"}, |
| 382 |
"bandpassRefval": { |
| 383 |
"datatype": "double", |
| 384 |
"ucd": "VOX:BandPass_RefValue"}, |
| 385 |
"wcs_refPixel": { |
| 386 |
"datatype": "double", |
| 387 |
"arraysize": "*", |
| 388 |
"ucd": "VOX:WCS_CoordRefPixel"}, |
| 389 |
"wcs_projection": { |
| 390 |
"arraysize": "3", |
| 391 |
"castFunction": lambda s: s[:3], |
| 392 |
"ucd": "VOX:WCS_CoordProjection"}, |
| 393 |
"mime": {"ucd": "VOX:Image_Format"}, |
| 394 |
"accref": {"ucd": "VOX:Image_AccessReference"}, |
| 395 |
"accsize": {"datatype": "int"}, |
| 396 |
"centerAlpha": {"ucd": "POS_EQ_RA_MAIN"}, |
| 397 |
"centerDelta": {"ucd": "POS_EQ_DEC_MAIN"}, |
| 398 |
"imageTitle": {"ucd": "VOX:Image_Title"}, |
| 399 |
"instId": {"ucd": "INST_ID"}, |
| 400 |
"dateObs": {"ucd": "VOX:Image_MJDateObs"}, |
| 401 |
"nAxes": {"ucd": "VOX:Image_Naxes"}, |
| 402 |
"pixelSize": {"ucd": "VOX:Image_Naxis"}, |
| 403 |
"refFrame": {"ucd": "VOX:STC_CoordRefFrame"}, |
| 404 |
"wcs_equinox": {"ucd": "VOX:STC_CoordEquinox"}, |
| 405 |
"bandpassId": {"ucd": "VOX:BandPass_ID"}, |
| 406 |
"bandpassUnit": {"ucd": "VOX:BandPass_Unit"}, |
| 407 |
"pixflags": {"ucd": "VOX:Image_PixFlags"}, |
| 408 |
} |
| 409 |
|
| 410 |
def _formatOutput(self, data, request, stream=True): |
| 411 |
if hasattr(data, "setMeta"): |
| 412 |
# let (media-type, payload) results pass by |
| 413 |
data.setMeta("_type", "results") |
| 414 |
data.getPrimaryTable().votCasts = self._outputTableCasts |
| 415 |
|
| 416 |
return DALRenderer._formatOutput(self, |
| 417 |
data, request, |
| 418 |
stream=stream) |
| 419 |
|
| 420 |
def _makeErrorTable(self, request, msg, queryStatus="ERROR"): |
| 421 |
return V.VOTABLE[ |
| 422 |
V.RESOURCE(type="results")[ |
| 423 |
V.INFO(name="QUERY_STATUS", value=queryStatus)[ |
| 424 |
str(msg)]]] |
| 425 |
|
| 426 |
|
| 427 |
class UnifiedDALRenderer(DALRenderer): |
| 428 |
"""A renderer for new-style simple DAL protocols. |
| 429 |
|
| 430 |
All input processing (e.g., metadata queries and the like) are considered |
| 431 |
part of the individual protocol and thus left to the core. |
| 432 |
|
| 433 |
The error style is that of SSAP (which, hopefully, will be kept |
| 434 |
for the other DAL2 protocols, too). |
| 435 |
|
| 436 |
To define actual renderers, inherit from this and set the name attribute |
| 437 |
(plus _outputTableCasts if necessary). Also, explain any protocol-specific |
| 438 |
metadata in the docstring. |
| 439 |
""" |
| 440 |
|
| 441 |
# TODO: merge this into DALRenderer and make legacy classes override |
| 442 |
# whatever they need differently. |
| 443 |
_outputTableCasts = {} |
| 444 |
|
| 445 |
def _formatOutput(self, data, request, stream=True): |
| 446 |
request.setHeader("content-type", "text/xml+votable") |
| 447 |
|
| 448 |
if hasattr(data, "setMeta"): |
| 449 |
data.setMeta("_type", "results") |
| 450 |
data.getPrimaryTable().votCasts = self._outputTableCasts |
| 451 |
|
| 452 |
return DALRenderer._formatOutput(self, |
| 453 |
data, request, stream=stream) |
| 454 |
|
| 455 |
def _makeErrorTable(self, request, msg, queryStatus="ERROR"): |
| 456 |
return V.VOTABLE11[ |
| 457 |
V.RESOURCE(type="results")[ |
| 458 |
V.INFO(name="QUERY_STATUS", value=queryStatus)[ |
| 459 |
str(msg)]]] |
| 460 |
|
| 461 |
|
| 462 |
class SIAP2Renderer(UnifiedDALRenderer): |
| 463 |
"""A renderer for SIAPv2. |
| 464 |
|
| 465 |
In general, if you want a SIAP2 service, you'll need something like the |
| 466 |
obscore view in the underlying table. |
| 467 |
""" |
| 468 |
parameterStyle = "dali" |
| 469 |
name = "siap2.xml" |
| 470 |
standardId = "ivo://ivoa.net/std/sia" |
| 471 |
|
| 472 |
def _makeErrorTable(self, request, msg, queryStatus="ERROR"): |
| 473 |
# FatalFault, DefaultFault |
| 474 |
return V.VOTABLE[ |
| 475 |
V.RESOURCE(type="results")[ |
| 476 |
V.INFO(name="QUERY_STATUS", value=queryStatus)[ |
| 477 |
str(msg)]]] |
| 478 |
|
| 479 |
def _handleRandomFailure(self, failure, request): |
| 480 |
base.ui.notifyFailure(failure) |
| 481 |
return self._writeErrorTable(request, |
| 482 |
"DefaultFault: "+failure.getErrorMessage(), |
| 483 |
httpStatus=500) |
| 484 |
|
| 485 |
def _handleInputErrors(self, failure, request): |
| 486 |
httpStatus, queryStatus = 200, "ERROR" |
| 487 |
|
| 488 |
if isinstance(failure.value, base.EmptyData): |
| 489 |
httpStatus, queryStatus = 400, "EMPTY" |
| 490 |
|
| 491 |
return self._writeErrorTable(request, |
| 492 |
"UsageFault: "+failure.getErrorMessage(), |
| 493 |
httpStatus=httpStatus, |
| 494 |
queryStatus=queryStatus) |
| 495 |
|
| 496 |
|
| 497 |
class SSAPRenderer(UnifiedDALRenderer): |
| 498 |
"""A renderer for the simple spectral access protocol. |
| 499 |
|
| 500 |
For registration, you must set the following metadata |
| 501 |
for the ssap.xml renderer: |
| 502 |
|
| 503 |
- ssap.dataSource -- survey, pointed, custom, theory, artificial |
| 504 |
- ssap.testQuery -- a query string that returns some data; REQUEST=queryData |
| 505 |
is added automatically |
| 506 |
that describe the type of data served through the service. Will |
| 507 |
usually by ``spectrum``, but ``timeseries`` is a realistic option. |
| 508 |
|
| 509 |
Other SSA metadata includes: |
| 510 |
|
| 511 |
- ssap.creationType -- archival, cutout, filtered, mosaic, |
| 512 |
projection, spectralExtraction, catalogExtraction (defaults to archival) |
| 513 |
- ssap.complianceLevel -- set to "query" when you don't deliver |
| 514 |
SDM compliant spectra; otherwise don't say anything, DaCHS will fill |
| 515 |
in the right value. |
| 516 |
|
| 517 |
It is recommended to set this metadata globally on the RD, as the |
| 518 |
SSA mixin can use that metadata to fill tables with sensible values |
| 519 |
without operator intervention. |
| 520 |
|
| 521 |
Properties supported by this renderer: |
| 522 |
|
| 523 |
- datalink -- if present, this must be the id of a datalink service |
| 524 |
that can work with the pubDIDs in this table (don't use this any more, |
| 525 |
datalink is handled through table-level metadata now) |
| 526 |
- defaultRequest -- by default, requests without a REQUEST parameter |
| 527 |
will be rejected. If you set defaultRequest to querydata, such |
| 528 |
requests will be processed as if REQUEST were given (which is of |
| 529 |
course sane but is a violation of the standard). |
| 530 |
""" |
| 531 |
version = "1.04" |
| 532 |
name = "ssap.xml" |
| 533 |
parameterStyle = "pql" |
| 534 |
standardId = "ivo://ivoa.net/std/ssap" |
| 535 |
defaultOutputFormat = "votabletd" |
| 536 |
|
| 537 |
def _getMetadataData(self): |
| 538 |
data = UnifiedDALRenderer._getMetadataData(self) |
| 539 |
data.dd.addMeta( |
| 540 |
"info", "SSAP", infoName="SERVICE_PROTOCOL", infoValue="1.04") |
| 541 |
return data |
| 542 |
|
| 543 |
def _formatOutput(self, data, request, stream=True): |
| 544 |
# for SSA, we need some funny attributes on the root resource |
| 545 |
if hasattr(data, "setMeta"): |
| 546 |
# the thing isn't already rendered, so we can add some additional |
| 547 |
# metadata |
| 548 |
|
| 549 |
data.contributingMetaCarriers.append(self.service) |
| 550 |
|
| 551 |
data.setMeta("_type", "results") |
| 552 |
data.addMeta("info", "SSAP", |
| 553 |
infoName="SERVICE_PROTOCOL", |
| 554 |
infoValue=self.version) |
| 555 |
|
| 556 |
# In SSA, we want a "direct" SODA block if we have a dlget-capable |
| 557 |
# datalink service. |
| 558 |
sodaGenerators = [] |
| 559 |
for table in data: |
| 560 |
if not table.rows: |
| 561 |
continue |
| 562 |
for svcMeta in table.iterMeta("_associatedDatalinkService"): |
| 563 |
dlService = base.resolveId(table.tableDef.rd, |
| 564 |
base.getMetaText(svcMeta, "serviceId")) |
| 565 |
if "dlget" not in dlService.allowed: |
| 566 |
continue |
| 567 |
if utils.looksLikeURLPat.match(table.rows[0]["accref"]): |
| 568 |
# we need the product table for direct processing |
| 569 |
# (if we ever want this, we'd have to discover the |
| 570 |
# descriptor class from the datalink service) |
| 571 |
continue |
| 572 |
|
| 573 |
core = ssap.getDatalinkCore(dlService, table) |
| 574 |
sodaGenerators.append( |
| 575 |
lambda ctx, core=core, svcMeta=svcMeta, table=table: |
| 576 |
core.datalinkEndpoints[0].asVOT( |
| 577 |
ctx, |
| 578 |
linkIdTo=ctx.getOrMakeIdFor( |
| 579 |
table.tableDef.getByName( |
| 580 |
base.getMetaText(svcMeta, "idColumn"))))) |
| 581 |
if sodaGenerators: |
| 582 |
data.sodaGenerators = sodaGenerators |
| 583 |
|
| 584 |
return UnifiedDALRenderer._formatOutput(self, |
| 585 |
data, request, stream=stream) |
| 586 |
|
| 587 |
|
| 588 |
class SLAPRenderer(UnifiedDALRenderer): |
| 589 |
"""A renderer for the simple line access protocol SLAP. |
| 590 |
|
| 591 |
For registration, you must set the following metadata on services |
| 592 |
using the slap.xml renderer: |
| 593 |
|
| 594 |
There's two mandatory metadata items for these: |
| 595 |
|
| 596 |
- slap.dataSource -- one of observational/astrophysical, |
| 597 |
observational/laboratory, or theoretical |
| 598 |
- slap.testQuery -- parameters that lead to a non-empty response. |
| 599 |
The way things are written in DaCHS, MAXREC=1 should in general |
| 600 |
work. |
| 601 |
""" |
| 602 |
version = "1.0" |
| 603 |
name = "slap.xml" |
| 604 |
parameterStyle = "pql" |
| 605 |
standardId = "ivo://ivoa.net/std/ssap" |
| 606 |
|
| 607 |
def _formatOutput(self, data, request, stream=True): |
| 608 |
if hasattr(data, "addMeta"): |
| 609 |
# SLAP 1.0 requires QUERY_STATUS OK (rather than OVERFLOW). Oh my. |
| 610 |
data.getPrimaryTable().setMeta("_queryStatus", "OK") |
| 611 |
data.addMeta("_votableRootAttributes", |
| 612 |
'xmlns:ssldm="http://www.ivoa.net/xml/SimpleSpectrumLineDM' |
| 613 |
'/SimpleSpectrumLineDM-v1.0.xsd"') |
| 614 |
|
| 615 |
return UnifiedDALRenderer._formatOutput(self, |
| 616 |
data, request, stream=stream) |
| 617 |
|
| 618 |
|
| 619 |
class APIRenderer(UnifiedDALRenderer): |
| 620 |
"""A renderer that works like a VO standard renderer but that doesn't |
| 621 |
actually follow a given protocol. |
| 622 |
|
| 623 |
Use this for improvised APIs. The default output format is a VOTable, |
| 624 |
and the errors come in VOSI VOTables. The renderer does, however, |
| 625 |
evaluate basic DALI parameters. You can declare that by |
| 626 |
including <FEED source="//pql#DALIPars"/> in your service. |
| 627 |
|
| 628 |
These will return basic service metadata if passed MAXREC=0. |
| 629 |
""" |
| 630 |
name = "api" |
| 631 |
parameterStyle = "dali" |
| 632 |
|
| 633 |
|
| 634 |
class RegistryRenderer(grend.ServiceBasedPage): |
| 635 |
"""A renderer that works with registry.oaiinter to provide an OAI-PMH |
| 636 |
interface. |
| 637 |
|
| 638 |
The core is expected to return a stanxml tree. |
| 639 |
""" |
| 640 |
name = "pubreg.xml" |
| 641 |
urlUse = "base" |
| 642 |
resultType = "text/xml" |
| 643 |
|
| 644 |
def render(self, request): |
| 645 |
# Make a robust (unchecked) pars dict for error rendering; real |
| 646 |
# parameter checking happens in getPMHResponse |
| 647 |
inData = {"args": request.strargs} |
| 648 |
|
| 649 |
streamResponse = request.strargs.get("verb")==["ListRecords"] |
| 650 |
|
| 651 |
self.runAsync(inData, |
| 652 |
).addCallback(self._renderXML, request, streamResponse |
| 653 |
).addErrback(self._renderError, request, inData["args"]) |
| 654 |
return server.NOT_DONE_YET |
| 655 |
|
| 656 |
def _renderXML(self, resultTree, request, streamResponse=False): |
| 657 |
request.setHeader("content-type", "text/xml") |
| 658 |
|
| 659 |
def writeTo(f): |
| 660 |
utils.xmlwrite(resultTree, f, |
| 661 |
xmlDecl=True, |
| 662 |
prolog="<?xml-stylesheet href='/static/xsl/oai.xsl' type='text/xsl'?>") |
| 663 |
|
| 664 |
if streamResponse: |
| 665 |
streaming.streamOut(writeTo, request, self.queryMeta) |
| 666 |
else: |
| 667 |
writeTo(request) |
| 668 |
request.finish() |
| 669 |
|
| 670 |
def _getErrorTree(self, exception, pars): |
| 671 |
"""returns an ElementTree containing an OAI-PMH error response. |
| 672 |
|
| 673 |
If exception is one of "our" exceptions, we translate them to error messages. |
| 674 |
Otherwise, we reraise the exception to an enclosing |
| 675 |
function may "handle" it. |
| 676 |
|
| 677 |
Contrary to the recommendation in the OAI-PMH spec, this will only |
| 678 |
return one error at a time. |
| 679 |
""" |
| 680 |
from gavo.registry.model import OAI |
| 681 |
|
| 682 |
if isinstance(exception, registry.OAIError): |
| 683 |
code = exception.__class__.__name__ |
| 684 |
code = code[0].lower()+code[1:] |
| 685 |
message = str(exception) |
| 686 |
else: |
| 687 |
code = "badArgument" # Why the hell don't they have a serverError? |
| 688 |
message = "Internal Error: "+str(exception) |
| 689 |
return OAI.PMH[ |
| 690 |
OAI.responseDate[datetime.datetime.utcnow().strftime( |
| 691 |
utils.isoTimestampFmt)], |
| 692 |
OAI.request(metadataPrefix=pars.get("metadataPrefix", [None])[0]), |
| 693 |
OAI.error(code=code)[ |
| 694 |
message |
| 695 |
] |
| 696 |
] |
| 697 |
|
| 698 |
def _renderError(self, failure, request, pars): |
| 699 |
if getattr(request, "channel", None) is None: |
| 700 |
# remote has hung up; don't try to write to them. |
| 701 |
return |
| 702 |
|
| 703 |
try: |
| 704 |
if not isinstance(failure.value, |
| 705 |
(registry.OAIError, base.ValidationError)): |
| 706 |
base.ui.notifyFailure(failure) |
| 707 |
return self._renderXML(self._getErrorTree(failure.value, pars), |
| 708 |
request) |
| 709 |
except: |
| 710 |
base.ui.notifyError("Cannot create registry error document") |
| 711 |
request.setResponseCode(400) |
| 712 |
request.setHeader("content-type", "text/plain") |
| 713 |
request.write("Internal error. Please notify site maintainer") |
| 714 |
request.finish() |
| 715 |
|
| 716 |
|
| 717 |
class BiblinksRenderer(grend.ServiceBasedPage): |
| 718 |
"""A renderer to put out bibliography links. |
| 719 |
|
| 720 |
This would work with a constant-query dbCore, typically against |
| 721 |
dc.biblinks. |
| 722 |
|
| 723 |
(Since 2.8.2) |
| 724 |
""" |
| 725 |
name = "biblinks.json" |
| 726 |
urlUse = "full" |
| 727 |
resultType = "application/json" |
| 728 |
|
| 729 |
def render(self, request): |
| 730 |
self.runAsync(request.strargs, |
| 731 |
).addCallback(self._renderResult, request) |
| 732 |
return server.NOT_DONE_YET |
| 733 |
|
| 734 |
def _renderResult(self, result, request): |
| 735 |
request.setHeader("content-type", "application/json") |
| 736 |
|
| 737 |
def writeTo(f): |
| 738 |
outRecs = [] |
| 739 |
for inRec in result.getPrimaryTable().rows: |
| 740 |
outRec = { |
| 741 |
"bib-ref": inRec["bib_ref"], |
| 742 |
"relationship": inRec["relationship"], |
| 743 |
"dataset-ref": inRec["dataset_ref"], |
| 744 |
} |
| 745 |
if inRec.get("bib_format"): |
| 746 |
outRec["bib-format"] = inRec["bib_format"] |
| 747 |
if inRec.get("cardinality"): |
| 748 |
outRec["cardinality"] = inRec["cardinality"] |
| 749 |
|
| 750 |
outRecs.append(outRec) |
| 751 |
|
| 752 |
json.dump(outRecs, f) |
| 753 |
|
| 754 |
return streaming.streamOut(writeTo, request, None) |
| 755 |
|
| 756 |
|
| 757 |
def addAttachmentHeaders(request, mime=None): |
| 758 |
"""adds a content-disposition header to request with a filename guessed |
| 759 |
based on datalink arguments. |
| 760 |
|
| 761 |
This tries a number of heuristics to try and preserve a bit of the |
| 762 |
provenance in the name, mainly to make saving these things simpler. |
| 763 |
""" |
| 764 |
try: |
| 765 |
if mime is None: |
| 766 |
mime = request.getHeader('content-type') |
| 767 |
if mime is None: |
| 768 |
# this is an error, really. This should only be called when |
| 769 |
# request is ready for serving. But let's be generous. |
| 770 |
mime = "application/octet-stream" |
| 771 |
ext = formats.getExtensionFor(mime) |
| 772 |
|
| 773 |
basicId = request.strargs["ID"][0] |
| 774 |
if '?' in basicId: |
| 775 |
# presumably the query part is the path |
| 776 |
stem = os.path.splitext( |
| 777 |
basicId.split('?')[-1].replace("/", "_"))[0] |
| 778 |
else: |
| 779 |
# who knows? Whatever comes after the last slash is |
| 780 |
# probably a better bet than anything else |
| 781 |
stem = basicId.split("/")[-1] |
| 782 |
|
| 783 |
if len(stem)<3: # this cannot be right |
| 784 |
stem = "result"+stem |
| 785 |
|
| 786 |
# if there's any arguments we suspect have changed the contents |
| 787 |
argkeys = [k for k in |
| 788 |
set(request.strargs.keys()) - set(["ID", "RESPONSEFORMAT"]) |
| 789 |
if request.strargs[k]] |
| 790 |
if argkeys: |
| 791 |
stem = stem+"_proc" |
| 792 |
|
| 793 |
request.setHeader('content-disposition', |
| 794 |
'attachment; filename=%s%s'%(stem, ext)) |
| 795 |
except: |
| 796 |
# if all fails, use a safe, if dumb, fallback |
| 797 |
request.setHeader('content-disposition', |
| 798 |
'attachment; filename=result.dat') |
| 799 |
|
| 800 |
|
| 801 |
class _DatalinkRendererBase(grend.ServiceBasedPage): |
| 802 |
"""the base class of the two datalink sync renderers. |
| 803 |
""" |
| 804 |
urlUse = "base" |
| 805 |
|
| 806 |
# send out files as attachments with separate file names? |
| 807 |
attachResult = False |
| 808 |
|
| 809 |
def render(self, request): |
| 810 |
self.runAsync(request.strargs, |
| 811 |
).addCallback(self._formatData, request |
| 812 |
).addErrback(self._reportError, request |
| 813 |
).addErrback(weberrors.renderDCErrorPage, request) |
| 814 |
return server.NOT_DONE_YET |
| 815 |
|
| 816 |
def _formatData(self, data, request): |
| 817 |
# the core returns mime, data or a resource. So, if it's a pair, |
| 818 |
# do something myself, else let twisted sort it out |
| 819 |
|
| 820 |
if isinstance(data, tuple): |
| 821 |
# XXX TODO: the same thing is in formrender. Refactor; since this is |
| 822 |
# something most renderers should be able to do, ServiceBasedPage would be |
| 823 |
# a good place |
| 824 |
mime, payload = data |
| 825 |
request.setHeader("content-type", mime) |
| 826 |
|
| 827 |
if self.attachResult: |
| 828 |
addAttachmentHeaders(request, mime) |
| 829 |
|
| 830 |
return streaming.streamOut( |
| 831 |
lambda f: f.write(payload), request, self.queryMeta) |
| 832 |
|
| 833 |
else: |
| 834 |
if self.attachResult: |
| 835 |
# the following getattr is for when data is a nevow.static.File |
| 836 |
addAttachmentHeaders(request, getattr(data, "type", None)) |
| 837 |
|
| 838 |
data.render(request) |
| 839 |
|
| 840 |
failureNameMap = { |
| 841 |
'ValidationError': 'UsageError', |
| 842 |
'MultiplicityError': 'MultiValuedParamNotSupported', |
| 843 |
} |
| 844 |
|
| 845 |
def _reportError(self, failure, request): |
| 846 |
# Do not trap svcs.WebRedirect here! |
| 847 |
failure.trap(base.ValidationError, soda.EmptyData) |
| 848 |
|
| 849 |
request.setHeader("content-type", "text/plain") |
| 850 |
|
| 851 |
if hasattr(failure.value, "responseCode"): |
| 852 |
request.setResponseCode(failure.value.responseCode) |
| 853 |
else: |
| 854 |
request.setResponseCode(422) |
| 855 |
|
| 856 |
if hasattr(failure.value, "responsePayload"): |
| 857 |
request.write(failure.value.responsePayload) |
| 858 |
else: |
| 859 |
request.write("%s: %s\n"%( |
| 860 |
self.failureNameMap.get(failure.value.__class__.__name__, "Error"), |
| 861 |
utils.safe_str(failure.value))) |
| 862 |
|
| 863 |
request.finish() |
| 864 |
return server.NOT_DONE_YET |
| 865 |
|
| 866 |
|
| 867 |
def _doDatalinkXSLT(data, _cache={}): |
| 868 |
"""a temporary hack to do server-side XSLT while the browser implementations |
| 869 |
apparently suck. |
| 870 |
|
| 871 |
Remove this once we've worked out how to make the datalink-to-xml |
| 872 |
stylesheet compatible with actual browsers. |
| 873 |
""" |
| 874 |
if "etree" not in _cache: |
| 875 |
from lxml import etree as lxmletree |
| 876 |
_cache["etree"] = lxmletree |
| 877 |
if "style" not in _cache: |
| 878 |
with base.openDistFile("web/xsl/datalink-to-html.xsl", "rb") as f: |
| 879 |
_cache["style"] = _cache["etree"].XSLT( |
| 880 |
_cache["etree"].XML(f.read())) |
| 881 |
return bytes(_cache["style"](_cache["etree"].XML(data))) |
| 882 |
|
| 883 |
|
| 884 |
class DatalinkGetDataRenderer(_DatalinkRendererBase): |
| 885 |
"""A renderer for data processing by datalink cores. |
| 886 |
|
| 887 |
This must go together with a datalink core, nothing else will do. |
| 888 |
|
| 889 |
This renderer will actually produce the processed data. It must be |
| 890 |
complemented by the dlmeta renderer which allows retrieving metadata. |
| 891 |
""" |
| 892 |
name = "dlget" |
| 893 |
attachResult = True |
| 894 |
standardId = "ivo://ivoa.net/std/soda#sync-1.0" |
| 895 |
# This shouldn't have parameterStyle for now, as it would |
| 896 |
# add DALI parameters (MAXREC etc) which are probably inappropriate |
| 897 |
# here. |
| 898 |
|
| 899 |
|
| 900 |
class DatalinkGetMetaRenderer(_DatalinkRendererBase): |
| 901 |
"""A renderer for data processing by datalink cores. |
| 902 |
|
| 903 |
This must go together with a datalink core, nothing else will do. |
| 904 |
|
| 905 |
This renderer will return the links and services applicable to |
| 906 |
one or more pubDIDs. |
| 907 |
|
| 908 |
See `Datalink and SODA`_ for more information. |
| 909 |
""" |
| 910 |
name = "dlmeta" |
| 911 |
resultType = "application/x-votable+xml;content=datalink" |
| 912 |
standardId = "ivo://ivoa.net/std/datalink" |
| 913 |
parameterStyle = "dali" |
| 914 |
|
| 915 |
def _formatData(self, svcResult, request): |
| 916 |
# this is a (hopefully temporary) hack that does XSLT server-side |
| 917 |
# if we think we're talking to a browser. The reason I'm doing |
| 918 |
# this is that several browsers were confused when doing both |
| 919 |
# XSLT and non-trivial javascript. |
| 920 |
# |
| 921 |
# remove this method once we've figured out how to placate these browsers. |
| 922 |
mime, data = svcResult |
| 923 |
# acceptDict = utils.parseAccept(request.getHeader("accept")) |
| 924 |
ua = request.getHeader("user-agent") or "" |
| 925 |
if "Mozilla" in ua or "Lynx" in ua: |
| 926 |
# it's a browser, do server-side XSLT |
| 927 |
request.setHeader("content-type", "text/html;charset=utf-8") |
| 928 |
request.write(_doDatalinkXSLT(data)) |
| 929 |
|
| 930 |
else: |
| 931 |
# no browser, do the right thing |
| 932 |
request.setHeader("content-type", mime) |
| 933 |
request.write(data) |
| 934 |
|
| 935 |
request.finish() |