Debian Codegraph @

gavo/protocols/taprunner.py

raw
1 """
2 Execution of UWS (right now, TAP only) requests.
3
4 This mainly intended to be exec'd (through some wrapper) by the queue
5 runner in the main server thread. The jobs executed have to be in
6 the database and have to have a job directory.
7
8 Primarily for testing an alternative interface rabRun exists that takes that
9 takes jobid, and parameters.
10
11 The tap runner takes the job to EXECUTING shortly before sending the
12 query to the DB server. When done, the job's state is one of COMPLETED,
13 ABORTED or ERROR.
14 """
15
16 #c Copyright 2008-2025, the GAVO project <[email protected]>
17 #c
18 #c This program is free software, covered by the GNU GPL. See the
19 #c COPYING file in the source distribution.
20
21
22 import datetime
23 import os
24 import sys
25 import time
26
27 from gavo import base
28 from gavo import formats
29 from gavo import rsc
30 from gavo import svcs
31 from gavo import utils
32 from gavo import votable
33 from gavo.base import valuemappers
34 from gavo.formats import texttable #noflake: format registration
35 from gavo.formats import csvtable #noflake: format registration
36 from gavo.formats import jsontable #noflake: format registration
37 from gavo.formats import geojson #noflake: format registration
38 from gavo.formats import votableread
39 from gavo.formats import votablewrite
40 from gavo.protocols import adqlglue
41 from gavo.protocols import simbadinterface #noflake: UDF registration
42 from gavo.protocols import tap
43 from gavo.protocols import uws
44
45
46 # set to true by the signal handler
47 EXIT_PLEASE = False
48
49
50 # The pid of the worker db backend. This is used in the signal handler
51 # when it tries to kill the running query.
52 _WORKER_PID = None
53
54
55 # test instrumentation
56 class _MessilyCrash(Exception):
57 pass
58
59
60
61 def _assertSupportedLanguage(jobId, langSpec):
62 """raises a UWSError if langSpec ("ADQL-3.1") cannot be processed by
63 this service.
64 """
65 if "-" in langSpec:
66 name, version = langSpec.split("-", 1)
67 else:
68 name, version = langSpec, None
69
70 if name not in tap.SUPPORTED_LANGUAGES:
71 raise uws.UWSError("This service does not support"
72 " the query language %s"%name, jobId)
73
74 if version is not None:
75 if version not in tap.SUPPORTED_LANGUAGES[name]["versions"]:
76 raise uws.UWSError("This service does not support"
77 " version %s of the query language %s (but some other version;"
78 " see capabilities)."%(version, name), jobId)
79
80
81 def _parseTAPParameters(jobId, parameters):
82 """gets and checks TAP parameters like version, request, and such.
83
84 The function returns a tuple of query and maxrec.
85
86 Since TAP is now a core, much of this is a no-op, as the parsing
87 has been done by the context grammar. However, since the lang
88 rules are a bit nightmarish, I still keep things in this extra
89 function.
90 """
91 try:
92 if parameters["request"]!="doQuery":
93 raise uws.UWSError("This service only supports REQUEST=doQuery", jobId)
94 _assertSupportedLanguage(jobId, parameters["lang"])
95 query = parameters["query"]
96 except KeyError as key:
97 raise base.ui.logOldExc(base.ValidationError(
98 "Required parameter '%s' missing."%key, key))
99
100 try:
101 if parameters["maxrec"] is None:
102 maxrec = base.getConfig("async", "defaultMAXREC")
103 else:
104 maxrec = parameters["maxrec"]
105
106 maxrec = min(base.getConfig("async", "hardMAXREC"), maxrec)
107 except ValueError:
108 raise base.ui.logOldError(
109 uws.UWSError("Invalid MAXREC literal '%s'."%parameters["maxrec"]))
110
111 return query, maxrec
112
113
114 def _makeDataFor(resultTable):
115 """returns an rsc.Data instance containing resultTable and some
116 additional metadata.
117 """
118 resData = rsc.wrapTable(resultTable)
119
120 resData.contributingMetaCarriers.append(base.resolveCrossId("//tap#run"))
121 # secret handshake with adqlglue: Add all tables of which we know that
122 # contributed to the query result to the meta sources for Data Origin
123 if hasattr(resultTable.tableDef, "contributingTables"):
124 resData.contributingMetaCarriers.extend(
125 resultTable.tableDef.contributingTables)
126
127 resData.addMeta("info", "Query successful",
128 infoName="QUERY_STATUS", infoValue="OK")
129 resData.setMeta("_type", "results")
130 resData.overflowLimit = resultTable.tableDef.overflowLimit
131 return resData
132
133
134 def writeResultTo(format, res, outF):
135 # special-case votable formats to handle overflow conditions and such
136 if format.startswith("votable"):
137 # the following duplicates a mapping from votablewrite; that's
138 # bad, and I should figure out a way to teach formats.format
139 # whatever is needed to let it do what we're doing here. Meanwhile:
140 enc = {
141 "votable": "binary",
142 "votableb2": "binary2",
143 "votabletd": "td",
144 }.get(format, "td")
145
146 oe = votable.OverflowElement(
147 res.getPrimaryTable().tableDef.overflowLimit,
148 votable.V.INFO(name="QUERY_STATUS", value="OVERFLOW"))
149 ctx = votablewrite.VOTableContext(
150 tablecoding=enc,
151 acquireSamples=False,
152 overflowElement=oe)
153 votablewrite.writeAsVOTable(res, outF, ctx)
154 else:
155 formats.formatData(format, res, outF, acquireSamples=False)
156
157
158 def _ingestUploads(job, uploads, connection):
159 """ingests uploads (in the format left by procotols.tap) into
160 temporary tables in connection.
161 """
162 tds = []
163 for destName, src in uploads or []:
164 if src.startswith("file://"):
165 # here, these are always direct children of the job directory;
166 # as a bit of defense, we only use the last path segment.
167 srcF = job.openFile(src.split("/")[-1])
168 else:
169 try:
170 srcF = utils.urlopenRemote(src)
171 except IOError as ex:
172 raise base.ui.logOldExc(
173 base.ValidationError("Upload '%s' cannot be retrieved"%(
174 src), "UPLOAD", hint="The I/O operation failed with the message: "+
175 str(ex)))
176 if valuemappers.needsQuoting(destName):
177 raise base.ValidationError("'%s' is not a valid table name on"
178 " this site"%destName, "UPLOAD", hint="It either contains"
179 " non-alphanumeric characters or conflicts with an ADQL"
180 " reserved word. Quoted table names are not supported"
181 " at this site.")
182 try:
183 uploadedTable = votableread.uploadVOTable(destName, srcF, connection,
184 nameMaker=votableread.AutoQuotedNameMaker())
185 except Exception as ex:
186 raise base.ui.logOldExc(
187 base.ReportableError(f"While ingesting upload {destName}: {ex}"))
188
189 if uploadedTable is not None:
190 tds.append(uploadedTable.tableDef)
191 srcF.close()
192 return tds
193
194
195 def _noteWorkerPID(conn):
196 """stores conn's worker PID in _WORKER_PID.
197 """
198 global _WORKER_PID
199 curs = conn.cursor()
200 curs.execute("SELECT pg_backend_pid()")
201 _WORKER_PID = curs.fetchall()[0][0]
202 curs.close()
203
204
205 def _hangIfMagic(jobId, parameters, timeout):
206 # Test instrumentation. There are more effective ways to DoS me.
207 if parameters.get("query")=="JUST HANG around":
208 with tap.WORKER_SYSTEM.changeableJob(jobId) as job:
209 job.change(executionDuration=timeout,
210 phase=uws.EXECUTING)
211
212 time.sleep(timeout)
213 with tap.WORKER_SYSTEM.changeableJob(jobId) as job:
214 job.change(phase=uws.COMPLETED,
215 endTime=datetime.datetime.utcnow())
216 sys.exit()
217
218 if parameters.get("query")=="MESSILY CRASH":
219 raise _MessilyCrash()
220
221
222 def getQTableFromJob(parameters, job, queryProfile, timeout):
223 """returns a QueryTable for a TAP job.
224 """
225 query, maxrec = _parseTAPParameters(job.jobId, parameters)
226 connectionForQuery = base.getDBConnection(queryProfile)
227
228 try:
229 _noteWorkerPID(connectionForQuery)
230 except: # Don't fail just because we can't kill workers
231 base.ui.notifyError(
232 f"Could not obtain PID for the worker, job {job.jobId}")
233 tdsForUploads = _ingestUploads(job, parameters["upload"],
234 connectionForQuery)
235
236 return adqlglue.runTAPQuery(query, timeout, connectionForQuery,
237 tdsForUploads, maxrec, forUser=job.owner or "anonymous")
238
239
240 def runTAPJobNoState(parameters, jobId, queryProfile, timeout):
241 """executes a TAP job defined by parameters and writes the
242 result to the job's working directory.
243
244 This does not do state management. Use runTAPJob if you need it.
245 """
246 _hangIfMagic(jobId, parameters, timeout)
247 # The following makes us bail out if a bad format was passed -- no
248 # sense spending the CPU on executing the query then, so we get the
249 # format here.
250 defaultFormat = "votable"
251 if base.getConfig("ivoa", "votDefaultEncoding")=="td":
252 defaultFormat = "votable/td"
253
254 rawFormat = (parameters.get("responseformat")
255 or parameters.get("format")
256 or defaultFormat)
257 format = formats.getKeyFor(rawFormat)
258
259 try:
260 job = tap.WORKER_SYSTEM.getJob(jobId)
261 res = _makeDataFor(getQTableFromJob(
262 parameters, job, queryProfile, timeout))
263
264 destF = job.openResult(
265 formats.getMIMEFor(
266 format,
267 rawFormat),
268 "result")
269 writeResultTo(format, res, destF)
270 destF.close()
271 except Exception:
272 # DB errors can occur here since we're streaming directly from
273 # the database.
274 svcs.mapDBErrors(*sys.exc_info())
275 # connectionForQuery closed by QueryTable
276
277
278 def runTAPJob(jobId, queryProfile="untrustedquery"):
279 """executes a TAP job defined by parameters and job id.
280
281 This assumes the job has already been put into executing, and the
282 appropriate pid has been entered. To indicate that actual processing
283 has started and the job is killable, the start time is recorded, though.
284 """
285 with tap.WORKER_SYSTEM.changeableJob(jobId) as job:
286 job.change(startTime=datetime.datetime.utcnow())
287 timeout = job.executionDuration
288 parameters = job.parameters
289 try:
290 runTAPJobNoState(parameters, jobId, queryProfile, timeout)
291 except Exception as ex:
292 if not isinstance(ex, base.Error):
293 base.ui.notifyError("While executing TAP job %s: %s"%(jobId, ex))
294 tap.WORKER_SYSTEM.changeToPhase(jobId, uws.ERROR, ex)
295 else:
296 tap.WORKER_SYSTEM.changeToPhase(jobId, uws.COMPLETED, None)
297
298
299 def runSyncTAPJob(jobId, queryMeta=None):
300 """executes a TAP job synchronously.
301
302 When this is done, the job will be in an end state, i.e., ERROR,
303 COMPLETED or perhaps ABORTED.
304
305 You must call tap.WORKER_SYSTEM.destroy(jobId) when done yourself.
306
307 Essentially, this puts the job into EXECUTING and declares the
308 pid as -1. The UWS machinery will happily kill a job with a pid
309 when asked to abort such a job, and since sync jobs run with the
310 server's pid, that's really not what we want (conversely: sync
311 jobs can't really be aborted). Anyway: Do *not* put anything
312 getpid returns into a sync job's pid field.
313 """
314 execTime = base.getConfig("async", "defaultExecTimeSync")
315
316 with tap.WORKER_SYSTEM.changeableJob(jobId) as job:
317 job.change(
318 executionDuration=execTime,
319 phase=uws.EXECUTING,
320 pid=-1)
321 runTAPJob(jobId)
322
323
324 ############### CLI
325
326
327 def setINTHandler(jobId):
328 """installs a signal handler that pushes our job to aborted on SIGINT.
329 """
330 import signal
331
332 def handler(signo, frame):
333 global EXIT_PLEASE
334 EXIT_PLEASE = True
335
336 signal.signal(signal.SIGINT, handler)
337
338
339 def _killWorker(jobId):
340 """tries to kill the postgres worker for this job.
341 """
342 with tap.WORKER_SYSTEM.changeableJob(jobId) as wjob:
343 wjob.change(phase=uws.ABORTED)
344
345 if _WORKER_PID:
346 base.ui.notifyInfo("Trying to abort %s, wpid %s"%(
347 jobId, _WORKER_PID))
348 with base.getUntrustedConn() as conn:
349 curs = conn.cursor()
350 curs.execute("SELECT pg_cancel_backend(%d)"%_WORKER_PID)
351 curs.close()
352
353
354 def joinInterruptibly(t, jobId):
355 while True:
356 t.join(timeout=0.5)
357 if not t.is_alive():
358 return
359 if EXIT_PLEASE:
360 _killWorker(jobId)
361 sys.exit(2)
362
363
364 def _runInThread(target, jobId):
365 # The standalone tap runner must run the query in a thread since
366 # it must be able to react to a SIGINT.
367 import threading
368 t = threading.Thread(target=target)
369 t.setDaemon(True)
370 t.start()
371 try:
372 joinInterruptibly(t, jobId)
373 except (SystemExit, Exception):
374 # give the thread a chance to quit cleanly
375 t.join(1)
376 raise
377
378
379 def parseCommandLine():
380 from optparse import OptionParser
381 parser = OptionParser(usage="%prog <jobid>",
382 description="runs the TAP job with <jobid> from the UWS table.")
383 opts, args = parser.parse_args()
384 if len(args)!=1:
385 parser.print_help(file=sys.stderr)
386 sys.exit(1)
387 return opts, args[0]
388
389
390 def main():
391 """causes the execution of the job with jobId sys.argv[0].
392 """
393 from gavo import rscdesc #noflake: cache registration
394
395 # there's a problem in CLI behaviour in that if anything goes wrong in
396 # main, a job that may have been created will remain QUEUED forever.
397 # There's little we can do about that, though, since we cannot put
398 # a job into ERROR when we don't know its id or cannot get it from the DB.
399 try:
400 base.DEBUG = False
401 opts, jobId = parseCommandLine()
402 setINTHandler(jobId)
403
404 try:
405 os.setsid() # we don't want to be killed if the server is restarted.
406 # The new server will pick us up.
407 except PermissionError:
408 # we already are the process group leader.
409 pass
410
411 try:
412 _runInThread(lambda: runTAPJob(jobId), jobId)
413 base.ui.notifyInfo("taprunner for %s finished"%jobId)
414 except SystemExit:
415 pass
416 except uws.JobNotFound: # someone destroyed the job before I was done
417 errmsg = "Giving up non-existing TAP job %s."%jobId
418 base.ui.notifyInfo(errmsg)
419 except _MessilyCrash:
420 # test instrumentation: simulate a severe internal error
421 base.ui.notifyInfo("taprunner was asked to crash messily")
422 sys.exit(1)
423 except Exception as ex:
424 base.ui.notifyError("taprunner %s major failure"%jobId)
425 # try to push job into the error state -- this may well fail given
426 # that we're quite hosed, but it's worth the try
427 tap.WORKER_SYSTEM.changeToPhase(jobId, uws.ERROR, ex)
428 raise
429 finally:
430 pass