Debian Codegraph @

gavo/protocols/tap.py

raw
1 """
2 TAP: schema maintenance, job/parameter definition incl. upload and UWS actions.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import datetime
12 import functools
13 import os
14 import signal
15
16 from twisted.internet import threads
17
18 from gavo import base
19 from gavo import formats
20 from gavo import rsc
21 from gavo import svcs
22 from gavo import utils
23 from gavo.protocols import taprunner
24 from gavo.protocols import uws
25 from gavo.protocols import uwsactions
26 from gavo.utils.parsetricks import ParseException
27
28
29 TAP_VERSION = "1.1"
30
31 RD_ID = "__system__/tap"
32
33 # used in the computation of quote
34 EST_TIME_PER_JOB = datetime.timedelta(minutes=10)
35
36
37 def _R(**kws): return kws
38
39 # this is used below in for registry purposes (values are pairs of
40 # IVOA id and a human-readable label).
41 SUPPORTED_LANGUAGES = {
42 "ADQL": _R(versions={
43 "2.0": "ivo://ivoa.net/std/ADQL#v2.0",
44 "2.1": "ivo://ivoa.net/std/ADQL#v2.1"},
45 description="The Astronomical Data Query Language is the standard"
46 " IVOA dialect of SQL; it contains a very general SELECT statement"
47 " as well as some extensions for spherical geometry and higher"
48 " mathematics.")}
49
50
51 # A list of supported upload methods. This is only used in the registry
52 # interface right now.
53 UPLOAD_METHODS = {
54 "upload-inline": "POST inline upload",
55 "upload-http": "http URL",
56 "upload-https": "https URL",
57 "upload-ftp": "ftp URL",
58 }
59
60
61 class TAPError(uws.UWSError):
62 """here for backward compatibility.
63
64 Deprecated.
65 """
66
67
68 ######################## registry interface helpers
69
70 def getSupportedLanguages():
71 """returns a list of tuples for the supported languages.
72
73 This is SUPPORTED_LANGUAGES in a format suitable for the
74 TAP capabilities element.
75
76 Each tuple returned is made up of
77 (name, description, [(version, ivo-id)...]).
78 """
79 for name, desc in SUPPORTED_LANGUAGES.items():
80 yield (name, desc["description"], list(desc["versions"].items()))
81
82
83 def getSupportedOutputFormats():
84 """yields tuples for the supported output formats.
85
86 This is OUTPUT_FORMATS in a format suitable for the
87 TAP capabilities element.
88
89 Each tuple is made up of (mime, aliases, description, ivoId).
90 """
91 for key in formats.iterFormats():
92 outputMime = formats.getMIMEFor(key)
93 descr = formats.getLabelFor(key)
94 ivoid = formats.getTAPIdFor(key)
95 yield outputMime, formats.getAliasesFor(key), descr, ivoid
96
97
98 ######################## maintaining TAP schema
99
100 def _insertRDIntoTAP_SCHEMA(rd, connection):
101 """helps publishToTAP.
102
103 Actually, it does all its work, except not rejecting //tap itself.
104 This is an implementation detail of letting //tap#createSchema's
105 postCreation script do its work.
106 """
107 # first check if we have any adql tables at all, and don't attempt
108 # anything if we don't (this is cheap optimizing and keeps TAP_SCHEMA
109 # from being created on systems that don't do ADQL).
110 for table in rd.tables:
111 # the readProfile condition in the next line is a proxy for adql=hidden.
112 if table.adql or "untrustedquery" in table.readProfiles:
113 break
114 else:
115 return
116
117 tapRD = base.caches.getRD(RD_ID)
118 for ddId in ["importTablesFromRD", "importDMsFromRD", "importColumnsFromRD",
119 "importFkeysFromRD", "importGroupsFromRD"]:
120 dd = tapRD.getById(ddId)
121 rsc.makeData(dd, forceSource=rd, parseOptions=rsc.parseValidating,
122 connection=connection, runCommit=False)
123
124 # finally, remove schemas that don't have any tables (which happens
125 # with adql-hidden tables, when moving RDs, etc. Such leftovers
126 # are trouble because they're in TAP_SCHEMA but not in /tables any more.
127 connection.execute("""
128 DELETE FROM tap_schema.schemas
129 WHERE
130 schema_name IN (
131 SELECT schema_name
132 FROM tap_schema.schemas
133 LEFT OUTER JOIN tap_schema.tables USING (schema_name)
134 WHERE table_name IS NULL)""")
135
136
137 def publishToTAP(rd, connection):
138 """publishes info for all ADQL-enabled tables of rd to the TAP_SCHEMA.
139 """
140 if rd.sourceId=='__system__/tap':
141 # if we're being built ourselves, skip this; tap's tap_schema
142 # maintenance is manual.
143 return
144 _insertRDIntoTAP_SCHEMA(rd, connection)
145
146
147 def unpublishFromTAP(rd, connection):
148 """removes all information originating from rd from TAP_SCHEMA.
149 """
150 if rd.sourceId=='__system__/tap':
151 # if we're being built ourselves, skip this; tap's tap_schema
152 # maintenance is manual.
153 return
154
155 rd.setProperty("moribund", "True") # the embedded grammar takes this
156 # to mean "kill this"
157 publishToTAP(rd, connection)
158
159 # as usual, dataModel is completely irregular.
160 if base.UnmanagedQuerier(connection
161 ).getTableType("tap_schema.supportedmodels"):
162 connection.execute(
163 "DELETE FROM tap_schema.supportedmodels"
164 " WHERE sourcerd=%(sourcerd)s",
165 {"sourcerd": rd.sourceId})
166
167 rd.clearProperty("moribund")
168
169
170 def getAccessibleTables():
171 """returns a list of qualified table names for the TAP-published tables.
172 """
173 with base.getTableConn() as conn:
174 return [r[0]
175 for r in conn.query("select table_name from tap_schema.tables"
176 " order by table_name")]
177
178
179 ########################## Maintaining TAP jobs
180
181
182 class TAPTransitions(uws.ProcessBasedUWSTransitions):
183 """The transition function for TAP jobs.
184
185 There's a hack here: After each transition, when you've released
186 your lock on the job, call checkProcessQueue (in reality, only
187 PhaseAction does this).
188 """
189 def __init__(self):
190 uws.SimpleUWSTransitions.__init__(self, "TAP")
191
192 def getCommandLine(self, wjob):
193 return "dachs", ["dachs", "--ui", "stingy", "taprun", "--", str(wjob.jobId)]
194
195 def queueJob(self, newState, wjob, ignored):
196 """puts a job on the queue.
197 """
198 uws.ProcessBasedUWSTransitions.queueJob(self, newState, wjob, ignored)
199 wjob.uws.scheduleProcessQueueCheck()
200
201 def errorOutJob(self, newPhase, wjob, ignored):
202 uws.SimpleUWSTransitions.errorOutJob(self, newPhase, wjob, ignored)
203 wjob.uws.scheduleProcessQueueCheck()
204
205 def completeJob(self, newPhase, wjob, ignored):
206 uws.SimpleUWSTransitions.completeJob(self, newPhase, wjob, ignored)
207 wjob.uws.scheduleProcessQueueCheck()
208
209 def killJob(self, newPhase, wjob, ignored):
210 try:
211 uws.ProcessBasedUWSTransitions.killJob(self, newPhase, wjob, ignored)
212 finally:
213 wjob.uws.scheduleProcessQueueCheck()
214
215
216 ########################## The TAP UWS job
217
218
219 @functools.lru_cache(1)
220 def getUploadGrammar():
221 from gavo.utils.parsetricks import (Word, ZeroOrMore, Suppress, StringEnd,
222 alphas, alphanums, CharsNotIn, pyparsingWhitechars)
223 # Should we allow more tableNames?
224 with pyparsingWhitechars(" \t"):
225 tableName = Word( alphas+"_", alphanums+"_" )
226 # What should we allow/forbid in terms of URIs?
227 uri = CharsNotIn(" ;,")
228 uploadSpec = tableName("name") + "," + uri("uri")
229 uploads = uploadSpec + ZeroOrMore(
230 Suppress(";") + uploadSpec) + StringEnd()
231 uploadSpec.addParseAction(lambda s,p,t: (t["name"], t["uri"]))
232 return uploads
233
234
235 def parseUploadString(uploadString):
236 """iterates over pairs of tableName, uploadSource from a TAP upload string.
237 """
238 try:
239 res = utils.pyparseString(getUploadGrammar(), uploadString).asList()
240 return res
241 except ParseException as ex:
242 raise base.ValidationError(
243 "Syntax error in UPLOAD parameter (near %s)"%(ex.loc), "UPLOAD",
244 hint="Note that we only allow regular SQL identifiers as table names,"
245 " i.e., basically only alphanumerics are allowed.")
246
247
248 class LocalFile(object):
249 """A sentinel class representing a file within a job work directory
250 (as resulting from an upload).
251 """
252 # TODO: unify with uws.LocalFile
253 def __init__(self, jobId, wd, fileName):
254 self.jobId, self.fileName = jobId, fileName
255 self.fullPath = os.path.join(wd, fileName)
256
257 def __str__(self):
258 # This is mainly for serialisation of the upload parameter in the
259 # UWS job.
260 return f"file://{self.fileName}"
261
262 def getURL(self):
263 """returns the URL the file is retrievable under for the life time of
264 the job.
265 """
266 return base.caches.getRD(RD_ID).getById("run").getURL("async",
267 absolute=True)+"/%s/results/%s"%(
268 self.jobId,
269 self.fileName)
270
271
272 def mangleUploads(request):
273 """parses TAP-compliant UPLOAD specifications in request and return
274 something that the core can handle.
275
276 This is being executed from the sync/async renderers and probably can't be
277 used anywhere else.
278
279 The underlying trouble is that the core cannot see the request any more,
280 and thus could not resolve param: uploads.
281
282 Since this is different in TAP than in DALI, we have extra code here
283 vs. dali.mangleUploads.
284 """
285 uploadSpec = request.strargs.pop("upload", [])
286 uploadSpec = ";".join(uploadSpec)
287 if not uploadSpec:
288 return
289
290 parsed = []
291 for tableName, upload in parseUploadString(uploadSpec):
292 if upload.startswith("param:"):
293 try:
294 upload = request.files[upload[6:]][0]
295 parsed.append(
296 (tableName, (upload.file_name, upload.file_object)))
297 except KeyError:
298 raise base.ui.logOldExc(
299 base.ValidationError(f"No inline upload '{upload[6:]}' found",
300 "UPLOAD"))
301 except AttributeError:
302 raise base.ui.logOldExc(
303 base.ValidationError(
304 f"Upload parameter references non-file '{upload[6:]}'",
305 "UPLOAD"))
306
307 else:
308 parsed.append((tableName, upload))
309
310 request.strargs["upload"] = parsed
311
312
313 class TAPJob(uws.UWSJobWithWD):
314 _jobsTDId = "//tap#tapjobs"
315 _transitions = TAPTransitions()
316
317 @property
318 def quote(self):
319 """returns an estimation of the job completion.
320
321 This currently is very naive: we give each job that's going to run
322 before this one 10 minutes.
323
324 This method needs to be changed when the dequeueing algorithm
325 is changed.
326 """
327 with base.getTableConn() as conn:
328 nBefore = self.uws.runCanned('countQueuedBefore',
329 {'dt': self.destructionTime}, conn)[0]["count"]
330 return datetime.datetime.utcnow()+nBefore*EST_TIME_PER_JOB
331
332 def prepareForDestruction(self):
333 if self.phase==uws.EXECUTING:
334 # since we're about to kill all state anyway, we're just TERM-ing
335 # the child rather than ask it politely.
336 # Let's just hope self.phase isn't lying; if it is, we'll possibly
337 # kill something else...
338 os.kill(self.pid, signal.SIGTERM)
339 super().prepareForDestruction()
340
341
342 #################### The TAP worker system
343
344 class PlanAction(uwsactions.JobAction):
345 """retrieve a query plan.
346
347 This is actually a TAP action; as we add UWSes, we'll need to think
348 about how we can customize uwsactions my UWS type.
349 """
350 name = "plan"
351
352 def formatPlan(self, qTableAndPlan):
353 qTable, plan = qTableAndPlan
354 return plan.encode("utf-8")
355
356 def getPlan(self, job, request):
357 from gavo.protocols import taprunner
358 qTable = taprunner.getQTableFromJob(job.parameters,
359 job, "untrustedquery", 1)
360 request.setHeader("content-type", "text/plain;charset=utf-8")
361 return qTable, qTable.getPlan()
362
363 def doGET(self, job, request):
364 return threads.deferToThread(self.getPlan, job, request
365 ).addCallback(
366 self.formatPlan)
367
368
369 class TAPUWS(uws.UWSWithQueueing):
370 """The UWS responsible for processing async TAP requests.
371 """
372 _baseURLCache = None
373
374 joblistPreamble = ("<?xml-stylesheet href='/static"
375 "/xsl/tap-joblist-to-html.xsl' type='text/xsl'?>")
376 jobdocPreamble = ("<?xml-stylesheet href='/static/xsl/"
377 "tap-job-to-html.xsl' type='text/xsl'?>")
378
379 def __init__(self):
380 self.runcountGoal = base.getConfig("async", "maxTAPRunning")
381 uws.UWSWithQueueing.__init__(self, TAPJob, uwsactions.JobActions(
382 PlanAction))
383
384 @functools.cached_property
385 def parameterGrammar(self):
386 """A grammar to be used to process parameters in UWS calls.
387 """
388 return base.makeStruct(
389 svcs.ContextGrammar,
390 inputTD=base.resolveCrossId("//tap#run").core.inputTable)
391
392 @property
393 def baseURL(self):
394 if self._baseURLCache is None:
395 self._baseURLCache = base.caches.getRD(
396 RD_ID).getById("run").getURL("sync")[:-5]
397 return self._baseURLCache
398
399 def getURLForId(self, jobId):
400 """returns a fully qualified URL for the job with jobId.
401 """
402 return "%s/%s/%s"%(self.baseURL, "async", jobId)
403
404 WORKER_SYSTEM = TAPUWS()
405
406
407 ######################### The TAP core
408
409 class TAPCore(svcs.Core):
410 """A core for the TAP renderer.
411 """
412 name_ = "tapCore"
413 workerSystem = WORKER_SYSTEM
414
415 inputTableXML = f"""
416 <inputTable>
417 <inputKey name="request" type="text" required="True"
418 std="True" multiplicity="force-single"
419 description="Type of operation requested; this can be doQuery
420 or getCapabilities. Preferably, don't pass it at all.">
421 <values default="doQuery"/>
422 </inputKey>
423 <inputKey name="lang" type="text" required="True"
424 std="True" multiplicity="force-single"
425 description="A name of a language that QUERY should be parsed as.
426 See capabilities for what you can pass in here.">
427 </inputKey>
428 <inputKey name="query" type="text" required="True"
429 std="True" multiplicity="force-single"
430 description="The query to be executed.">
431 </inputKey>
432 <inputKey name="version" type="text"
433 std="True"
434 description="Don't use this parameter. You'll only break stuff.">
435 <values default="{TAP_VERSION}"/>
436 <preparse>
437 if input!="{TAP_VERSION}":
438 raise ValueError(
439 "Version mismatch; this service only supports"
440 " TAP version {TAP_VERSION}.")
441 </preparse>
442 </inputKey>
443 <inputKey name="format" type="text"
444 description="Deprecated alias of RESPONSEFORMAT"/>
445 <inputKey name="upload" type="raw"
446 description="A TAP-compliant upload; roughly:
447 (tablename,source-uri), where source-uri can also have
448 a param: scheme.">
449 </inputKey>
450 <FEED source="//pql#DALIPars">
451 <PRUNE name="VERB"/>
452 </FEED>
453 </inputTable>"""
454
455 # The output table is ignored.
456
457 def run(self, service, inputTable, queryMeta):
458 authUser = None
459 if queryMeta["user_pretend"]:
460 authUser = queryMeta.getAuthUser()
461
462 jobId = WORKER_SYSTEM.getNewIdFromArgs(
463 {}, inputTable.getParamDict(), user=authUser)
464
465 try:
466 taprunner.runSyncTAPJob(jobId, queryMeta)
467
468 job = WORKER_SYSTEM.getJob(jobId)
469 if job.phase==uws.COMPLETED:
470 # This is TAP, so there's exactly one result
471 res = job.getResults()[0]
472 name, type = res["resultName"], res["resultType"]
473 # hold on to the result fd so its inode is not lost when we delete
474 # the job.
475 f = open(os.path.join(job.getWD(), name), "rb")
476 return (f, type)
477 elif job.phase==uws.ERROR:
478 exc = job.error
479 raise base.Error(exc["msg"], hint=exc["hint"])
480 elif job.phase==uws.ABORTED:
481 raise uws.UWSError("Job was manually aborted. For synchronous"
482 " jobs, this probably means the operators killed it.",
483 jobId)
484 else:
485 raise uws.UWSError("Internal error. Invalid UWS phase.", jobId)
486 finally:
487 WORKER_SYSTEM.destroy(jobId)
488
489 def getRelevantTables(self):
490 tables = []
491
492 with base.getTableConn() as conn:
493 for tableName, in conn.query("SELECT table_name"
494 " FROM TAP_SCHEMA.tables"):
495 try:
496 tables.append(base.getTableDefForTable(conn, tableName))
497 except:
498 base.ui.notifyError("Failure trying to retrieve table definition"
499 " for table %s. Please fix the corresponding RD."%tableName)
500
501 return [t for t in tables if t is not None and t.rd is not None]