Debian Codegraph @

gavo/user/validation.py

raw
1 """
2 A cli-facing module providing functionality to "validate" one or more
3 resource descriptors.
4
5 Validation means giving some prognosis as to whether RD will properly work
6 within both the DC and the VO.
7
8 While validation is active there's base.VALIDATING=True. If RDs
9 do anything expensive, they're advised to have something like::
10
11 if getattr(base, "VALIDATING", False):
12 (don't do the expensive thing)
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 argparse
22 import itertools
23 import re
24 import sys
25 import traceback
26
27
28 from gavo import api
29 from gavo import adql
30 from gavo import base
31 from gavo import svcs
32 from gavo import stc
33 from gavo import registry
34 from gavo import utils
35 from gavo.helpers import testtricks
36 from gavo.imp import astropyucd
37 from gavo.registry import builders
38 from gavo.protocols import datalink
39 from gavo.protocols import vocabularies
40 from gavo.user import errhandle
41 from gavo.web import htmltable
42
43 from gavo.web import examplesrender #noflake: for RST registration
44
45 builders.VALIDATING = True
46
47 # have some non-UAT keywords that we swallow for some reason or other
48 NON_UAT_SUBJECTS = {"stars", "DOI"}
49
50 # just accept some UCDs mentioned in standards; some of
51 # these have actually been made legal later, but we don't want to
52 # report them even with old astropys
53 UCD_WHITELIST = {'instr.fov', "em.line"}
54
55
56 class TestsCollector(object):
57 """a singleton that collects use cases to run.
58
59 Don't instantiate, this is a global singleton.
60
61 The testsToRun attribute contains the test suites to run.
62 """
63 testsToRun = []
64
65 @classmethod
66 def addRD(cls, rd):
67 """adds tests from rd.
68 """
69 for suite in rd.tests:
70 cls.testsToRun.append(suite)
71
72
73 def outputDependentMessage(aString):
74 """an output function for errhandle.raiseAndCatch.
75
76 It is used here to indent dependent error messages.
77 """
78 print(re.sub("(?m)^", " ", aString))
79
80
81 def outputError(rdId, message, verbose=False):
82 print("[ERROR] %s: %s"%(rdId, message))
83 if verbose:
84 errhandle.raiseAndCatch(output=outputDependentMessage)
85
86
87 def outputWarning(rdId, message, verbose=False):
88 print("[WARNING] %s: %s"%(rdId, message))
89 if verbose:
90 errhandle.raiseAndCatch(output=outputDependentMessage)
91
92
93 def loadRD(rdId):
94 """returns the RD identified by rdId.
95
96 If that fails, diagnostics are printed and None is returned.
97 """
98 try:
99 rd = api.getReferencedElement(rdId, doQueries=False)
100
101 # This is so we can validate userconfig.rd
102 if hasattr(rd, "getRealRD"):
103 rd = rd.getRealRD()
104
105 except api.RDNotFound:
106 outputError(rdId, "RD or dependency not found, message follows", True)
107 except api.LiteralParseError:
108 outputError(rdId, "Bad literal in RD, message follows", True)
109 except api.StructureError:
110 outputError(rdId, "Malformed RD input, message follows", True)
111 except api.Error:
112 outputError(rdId, "Syntax or internal error, message follows", True)
113 else:
114 return rd
115 # Fallthrough: RD could not be loaded
116 return None
117
118
119 _XSD_VALIDATOR = testtricks.XSDTestMixin()
120
121
122 def isIVOPublished(res):
123 """returns true if res has a publication facing the VO.
124 """
125 if hasattr(res, "registration"):
126 # it's a data item
127 return "ivo_managed" in res.registration.sets
128 else:
129 # it's a service:
130 for pub in res.publications:
131 if "ivo_managed" in pub.sets:
132 return True
133 else:
134 return False
135
136
137 def iterPublishedResources(rd, args):
138 for svc in rd.services:
139 if args.prePublication or svc.publications:
140 yield svc
141
142 for res in rd.resRecs:
143 yield res
144
145 for res in itertools.chain(rd.tables, rd.dds):
146 if res.registration:
147 yield res
148
149
150 def validateServices(rd, args):
151 """outputs to stdout various diagnostics about the services on rd.
152 """
153 validSoFar = True
154 for res in iterPublishedResources(rd, args):
155 try:
156 base.validateStructure(res)
157 except api.MetaValidationError as ex:
158 validSoFar = False
159 outputError(rd.sourceId, "Missing metadata for publication of"
160 " service %s:\n%s"%(res.id, str(ex)))
161 continue # further checks will just add verbosity
162
163 # see if subject keywords are from UAT
164 if isIVOPublished(res):
165 uat = vocabularies.get_vocabulary("uat")
166 for subject in res.iterMeta("subject", propagate=True):
167 if (str(subject) not in uat["terms"]
168 and str(subject) not in NON_UAT_SUBJECTS):
169 outputWarning(rd.sourceId, "Service %s has subject %s"
170 ", which is not from http://ivoa.net/rdf/uat."%(
171 res.id, subject))
172
173 if isinstance(res, svcs.Service):
174 if not (args.prePublication or isIVOPublished(res)):
175 # require sane metadata on services only if the VO will see the service
176 continue
177
178 # error out if the identifier cannot be generated
179 api.getMetaText(res, "identifier")
180 registryRecord = None
181 try:
182 registryRecord = builders.getVORMetadataElement(res)
183 except stc.STCSParseError as msg:
184 validSoFar = False
185 outputError(rd.sourceId, "Invalid STC-S (probably in coverage meta)"
186 ": %s"%str(msg))
187 except:
188 validSoFar = False
189 outputError(rd.sourceId, "Error when producing registry record"
190 " of service %s:"%res.id, True)
191
192 # make sure the registry record is XSD-valid
193 if registryRecord is not None:
194 try:
195 _XSD_VALIDATOR.assertValidates(
196 registryRecord.render(), leaveOffending=True)
197 except AssertionError as msg:
198 validSoFar = False
199 outputError(rd.sourceId, "Invalid registry record for service"
200 " %s:\n%s"%(res.id, str(msg)))
201
202 return validSoFar
203
204
205 def validateRST(rd, args):
206 """outputs diagnostics on RST formatting problems.
207 """
208 def validateRSTOne(el):
209 validSoFar = True
210
211 for key, val in getattr(el, "getAllMetaPairs", lambda: [])():
212 if val.format=='rst':
213 content = val.getExpandedContent(macroPackage=el)
214 _, msg = utils.rstxToHTMLWithWarning(content)
215 if msg:
216 outputWarning(rd.sourceId,
217 "%s metadata on %s (%s) has an RST problem: %s"%(
218 key, el, utils.makeEllipsis(content, 80), msg))
219
220 for child in el.iterChildren():
221 if child:
222 validSoFar = validSoFar and validateRSTOne(child)
223
224 return validSoFar
225
226 return validateRSTOne(rd)
227
228
229 def validateRowmakers(rd, args):
230 """tries to build all rowmakers mentioned in the RD and bails out
231 if one is bad.
232 """
233 for dd in rd:
234 for m in dd.makes:
235 isOnDisk = m.table.onDisk
236 m.table.onDisk = False
237 try:
238 api.TableForDef(m.table)
239 m.rowmaker.compileForTableDef(m.table)
240 finally:
241 m.table.onDisk = isOnDisk
242 return True
243
244
245 def validateOtherCode(rd, args):
246 """tries to compile other pieces of code in an RD and bails out
247 if one is bad.
248 """
249 retval = True
250
251 for suite in rd.tests:
252 for test in suite.tests:
253 try:
254 test.compile()
255 except Exception as msg:
256 outputError(rd.sourceId, "Bad test '%s': %s"%(test.title,
257 msg))
258 retval = False
259
260 for svc in rd.services:
261 for outputField in svc.getCurOutputFields():
262 if outputField.formatter:
263 try:
264 htmltable._compileRenderer(outputField.formatter, None, rd)
265 except Exception as msg:
266 outputError(rd.sourceId, "Bad formatter on output field '%s': %s"%(
267 outputField.name, msg))
268 retval = False
269
270 if isinstance(svc.core, datalink.DatalinkCore):
271 try:
272 if "dlmeta" in svc.allowed:
273 svc.core.descriptorGenerator.compile(svc.core)
274 if "dlget" in svc.allowed:
275 for df in svc.core.dataFunctions:
276 df.compile(svc.core)
277 svc.core.dataFormatter.compile(svc.core)
278 except Exception as msg:
279 outputError(rd.sourceId, "Bad datalink function in service '%s': %s"%(
280 svc.id, msg))
281 if isinstance(msg, base.BadCode):
282 outputError(rd.sourceId, "Bad code:\n%s"%msg.code)
283 retval = False
284
285 for job in rd.jobs:
286 try:
287 job.job.compile(parent=rd)
288 except Exception as msg:
289 outputError(rd.sourceId, "Bad code in job '%s': %s"%(
290 job.title, msg))
291 retval = False
292
293 # TODO: iterate over service/cores and standalone cores and
294 # fiddle out condDescs
295 # TODO: Iterate over scripts and data/make/scripts, see which
296 # are python and try to compile them
297 # TODO: Iterate over grammars and validate rowfilters
298
299 return retval
300
301
302 def validateTable(td, compareDB):
303 """sanity-checks the table described by td.
304
305 It is not an error if the table does not exist. The function will
306 yield diagnostics as ([warning, error], message).
307 """
308 tn = td.getQName()
309 identifierSymbol = adql.getSymbols()["identifier"]
310
311 try:
312 base.validateStructure(td)
313 except api.MetaValidationError as ex:
314 yield "error", f"Missing metadata in table {td.id}:\n{ex}"
315 return
316
317 for col in td:
318 try:
319 if col.unit:
320 parsedUnit = api.parseUnit(col.unit)
321 if not parsedUnit.isValid:
322 yield ("warning",
323 f"Column {tn}.{col.name}: Unit {col.unit} is"
324 " not interoperable (in VOUnit's list of recognised units)")
325
326 except api.BadUnit:
327 yield "error", f"Bad unit for table {tn}.{col.name}: {col.unit}"
328
329 if col.ucd and not col.ucd in UCD_WHITELIST:
330 try:
331 astropyucd.parse_ucd(col.ucd,
332 check_controlled_vocabulary=True, has_colon=True)
333 except ValueError as msg:
334 yield ("warning",
335 f"Column {tn}.{col.name}: UCD {col.ucd}"
336 f" not accepted by astropy ({msg}).")
337
338 try:
339 identifierSymbol.parseString(str(col.name), parseAll=True)
340 except base.ParseException:
341 yield ("warning", "Column %s.%s: Name is not a regular"
342 " ADQL identifier."%(td.id, col.name))
343
344 if td.onDisk and compareDB:
345 with base.getTableConn() as conn:
346 q = base.UnmanagedQuerier(conn)
347 if q.getTableType(tn) is not None:
348 tapSchemaColumns = None
349 if td.adql:
350 tapSchemaColumns = dict((r["column_name"], r)
351 for r in conn.queryToDicts(
352 "SELECT column_name, unit, ucd, datatype, arraysize, xtype"
353 " FROM TAP_SCHEMA.columns"
354 " WHERE table_name=%(table_name)s",
355 {"table_name": tn}))
356
357 t = api.TableForDef(td, connection=conn)
358 try:
359 t.ensureOnDiskMatches(tapSchemaColumns)
360 except api.DataError as msg:
361 yield "error", utils.makeEllipsis(str(msg), 160)
362
363
364 def validateTables(rd, args):
365 """does some sanity checks on the (top-level) tables within rd.
366 """
367 valid = True
368
369 for td in rd.tables:
370 for type, msg in validateTable(td, args.compareDB):
371 if type=="error":
372 valid = False
373 outputError(rd.sourceId, msg)
374 elif type=="warning":
375 outputWarning(rd.sourceId, msg)
376 else:
377 raise NotImplementedError(f"No such message type: {type}")
378
379 # associated datalink services and the columns must exist.
380 for dldef in td.iterMeta("_associatedDatalinkService"):
381 try:
382 _ = base.resolveId(td.rd,
383 base.getMetaText(dldef, "serviceId"))
384 _ = td.getColumnByName(base.getMetaText(dldef, "idColumn"))
385
386 except (base.NotFoundError, base.MetaError) as msg:
387 valid = False
388 outputError(rd.sourceId,
389 utils.makeEllipsis(utils.safe_str(msg), 160))
390
391 if td.registration:
392 registryRecord = None
393 try:
394 registryRecord = builders.getVORMetadataElement(td)
395 except Exception as msg:
396 valid = False
397 outputError(rd.sourceId,
398 "Table publication of %s could not be built: %s"%(
399 td.id, str(msg)))
400
401 if registryRecord is not None:
402 try:
403 _XSD_VALIDATOR.assertValidates(
404 registryRecord.render(), leaveOffending=True)
405 except AssertionError as msg:
406 valid = False
407 outputError(rd.sourceId, "Invalid registry record for table"
408 " %s:\n%s"%(td.id, str(msg)))
409
410 return valid
411
412
413 def _collectExamples(rd):
414 """returns a sequence of tapqueries from examples of rd and its services.
415 """
416 queries = []
417
418 def collectFrom(resob):
419 for m in resob.iterMeta("_example", propagate=False):
420 ex = examplesrender.Example(m)
421 try:
422 queries.append((f"TAP example: {ex.title}", ex.getTAPQuery()))
423 except ValueError:
424 # no tap query in this example, we don't validate that for now
425 pass
426
427 collectFrom(rd)
428 for svc in rd.services:
429 collectFrom(svc)
430
431 return list(sorted(set(queries)))
432
433
434 def validateExamples(rd, args):
435 """tries to run tapquery values in any _examples meta found in the
436 RD or its services against the local TAP server.
437
438 An example is considered bad if it returns nothing or an error.
439 """
440 from gavo.rscdef import regtest
441
442 tests = []
443 for title, ex in _collectExamples(rd):
444 destURL = base.makeStruct(regtest.DataURL,
445 parSet="TAP",
446 content_="/tap/sync")
447 att = destURL.getAttribute("QUERY")
448 att.feed(att, destURL, ex)
449 tests.append(base.makeStruct(regtest.RegTest,
450 title=title,
451 url=destURL,
452 code="rows = self.getVOTableRows()\nself.assertTrue(rows)\n"))
453 tests[-1].parent = rd
454
455 if not tests:
456 return True
457
458 suite = base.makeStruct(regtest.RegTestSuite,
459 title=f"{rd.sourceId} embedded TAP examples",
460 tests=tests)
461 runner = regtest.TestRunner.fromSuite(suite)
462 runner.runTests()
463
464 res = runner.stats.getFailures()
465 if res:
466 print(res)
467 return False
468 else:
469 return True
470
471
472 def validateOne(rdId, args):
473 """outputs to stdout various information on the RD identified by rdId.
474 """
475 with testtricks.collectedEvents("Info", "Warning") as warnings:
476 rd = loadRD(rdId)
477 if rd is None:
478 return
479
480 for warning in warnings:
481 outputWarning(rdId, warning[1])
482
483 if args.runTests:
484 TestsCollector.addRD(rd)
485
486 validSoFar = validateServices(rd, args)
487 validSoFar = validSoFar and validateRowmakers(rd, args)
488 validSoFar = validSoFar and validateTables(rd, args)
489 validSoFar = validSoFar and validateOtherCode(rd, args)
490 validSoFar = validSoFar and validateRST(rd, args)
491 if args.validateExamples:
492 validSoFar = validSoFar and validateExamples(rd, args)
493 return validSoFar
494
495
496 def validateAll(args):
497 """validates all accessible RDs.
498 """
499 if args.rd[0]=="ALL":
500 rdSource = registry.findPublishedRDs()
501 else:
502 rdSource = registry.findAllRDs()
503
504 for rdId in rdSource:
505 if args.verbose:
506 sys.stdout.write(rdId+" ")
507 sys.stdout.flush()
508 try:
509 validateOne(rdId, args)
510 except Exception:
511 sys.stderr.write("Severe error while validating %s:\n"%rdId)
512 traceback.print_exc()
513 if args.verbose:
514 sys.stdout.write("\n")
515
516
517 def parseCommandLine():
518 parser = argparse.ArgumentParser(description="Check RDs for well-formedness"
519 " and some aspects of VO-friendlyness")
520 parser.add_argument("rd", nargs="+", type=str,
521 help="RD identifier or file system path. Use magic value ALL to"
522 " check all published RDs, ALL_RECURSE to look for RDs in the file"
523 " system.")
524 parser.add_argument("-p", "--pre-publication", help="Validate"
525 " as if all services were IVOA published even if they are not"
526 " (this may produce spurious errors if unpublished services are in"
527 " the RD).",
528 action="store_true", dest="prePublication")
529 parser.add_argument("-v", "--verbose", help="Talk while working",
530 action="store_true", dest="verbose")
531 parser.add_argument("-t", "--run-tests", help="Run regression tests"
532 " embedded in the checked RDs", action="store_true", dest="runTests")
533 parser.add_argument("-T", "--timeout", help="When running tests, abort"
534 " and fail requests after inactivity of SECONDS",
535 action="store", dest="timeout", type=int, default=15, metavar="SECONDS")
536 parser.add_argument("-c", "--compare-db", help="Also make sure that"
537 " tables that are on disk (somewhat) match the definition in the RD.",
538 action="store_true", dest="compareDB")
539 parser.add_argument("-x", "--validate-examples", help="Also try to"
540 " run any embedded TAP examples against the local TAP server"
541 " and complain if that yields no results or an error",
542 action="store_true", dest="validateExamples")
543
544 return parser.parse_args()
545
546
547 def main():
548 base.VALIDATING = True
549 args = parseCommandLine()
550 if len(args.rd)==1 and args.rd[0] in ("ALL", "ALL_RECURSE"):
551 validateAll(args)
552 else:
553 for rd in args.rd:
554 print(rd, "--", end=' ')
555 sys.stdout.flush()
556 if validateOne(rd, args):
557 print("OK")
558 else:
559 print("Fail")
560
561 if args.runTests:
562 print("\nRunning regression tests\n")
563 from gavo.rscdef import regtest
564 runner = regtest.TestRunner(TestsCollector.testsToRun,
565 verbose=False, timeout=args.timeout)
566 runner.runTests(showDots=True)
567 print(runner.stats.getReport())
568 if runner.stats.fails:
569 print("\nThe following tests failed:\n")
570 print(runner.stats.getFailures())