Debian Codegraph @

gavo/protocols/uws.py

raw
1 """
2 Support classes for the universal worker service.
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 contextlib
12 import datetime
13 import functools
14 import io
15 import os
16 import pickle
17 import shutil
18 import signal
19 import tempfile
20 import threading
21 import weakref
22
23 from twisted.internet import protocol
24 from twisted.internet import reactor
25
26 from gavo import base
27 from gavo import rsc
28 from gavo import rscdef
29 from gavo import svcs
30 from gavo import utils
31 from gavo.base import cron
32 from gavo.protocols import dali
33
34 # Ward against typos
35 from gavo.votable.tapquery import ( #noflake: exported names
36 PENDING, QUEUED, EXECUTING, COMPLETED, ERROR, ABORTED, UNKNOWN)
37
38 END_STATES = set([COMPLETED, ERROR, ABORTED])
39
40 # used in the computation of quote
41 EST_TIME_PER_JOB = datetime.timedelta(minutes=10)
42
43 _DEFAULT_LOCK_TIMEOUT = 0.1
44
45
46 class UWSError(base.Error):
47 """UWS-related errors, mainly to communicate with web renderers.
48
49 UWSErrors are constructed with a displayable message (may be None to
50 autogenerate one), a jobId (give one; the default None is only there
51 to avoid breaking legacy code) and optionally a source exception and a hint.
52 """
53 def __init__(self, msg, jobId=None, sourceEx=None, hint=None):
54 base.Error.__init__(self, msg, hint=hint)
55 self.msg = msg
56 self.jobId = jobId
57 self.sourceEx = sourceEx
58 self.args = [self.msg, self.jobId, self.sourceEx, self.hint]
59
60 def __str__(self):
61 if self.msg:
62 return self.msg
63 elif self.sourceEx:
64 return "UWS on job %s operation failed (%s, %s)"%(
65 self.jobId,
66 self.sourceEx.__class__.__name__,
67 str(self.sourceEx))
68 else:
69 return "Unspecified UWS related error (id: %s)"%self.jobId
70
71
72 class JobNotFound(base.NotFoundError, UWSError):
73 def __init__(self, jobId):
74 base.NotFoundError.__init__(self, str(jobId), "UWS job", "jobs table")
75
76 def __str__(self):
77 return base.NotFoundError.__str__(self)
78
79
80 class UWS(object):
81 """a facade for a universal worker service (UWS).
82
83 You must construct it with the job class (see UWSJob) and a
84 uwsactions.JobActions instance
85
86 The UWS then provides methods to access the jobs table,
87 create jobs and and deserialize jobs from the jobs table.
88
89 It also has a context grammar that parses the JCL parameters
90 from request.strargs. In this base class, that parses no
91 parameters at all, and you will almost certainly have to override this.
92
93 We have a "statements cache" in here, where we used the UWS table
94 definition to create query strings we can later pass to the database.
95 Don't worry about this any more. Just write text queries when adding
96 features. It's more readable and just about as stable against
97 code evolution.
98
99 You must override the getURLForId(jobId) method in your concrete
100 implementation.
101
102 You should also override jobdocPreamble and joblistPreamble. This
103 is raw XML that is prepended to job and list documents. This is primarily
104 for PIs giving stylesheets, but given we don't use doctypes you could
105 provide internal subsets there, too. Anyway, see the TAP UWS runner
106 for examples.
107 """
108 # how often should we check for jobs that wait for destruction?
109 cleanupInterval = 3600*12
110
111 # raw XML to prepend to joblist documents
112 joblistPreamble = ""
113 # raw XML to prepend to job documents
114 jobdocPreamble = ""
115 # the grammar to parse incoming parameters. This must be idempotent,
116 # because before starting the core, the parameters already parsed
117 # will be filtered through the grammar. That's necessary to catch
118 # incomplete parameter sets (which we can't do during individual
119 # posts).
120 parameterGrammar = base.makeStruct(svcs.ContextGrammar)
121
122 def __init__(self, jobClass, jobActions):
123 self.jobClass = jobClass
124 self.jobActions = jobActions
125 self._statementsCache = None
126 cron.runEvery(-self.cleanupInterval,
127 "UWS %s jobs table reaper"%str(self),
128 self.cleanupJobsTable)
129
130 def _makeMoreStatements(self, statements, jobsTable):
131 """adds custom statements to the canned query dict in derived
132 classes.
133 """
134 pass
135
136 def _makeStatementsCache(self):
137 """returns a dictionary containing canned queries to manipulate
138 the jobs table for this UWS.
139 """
140 res = {}
141 td = self.jobClass.jobsTD
142 with base.getTableConn() as conn:
143 jobsTable = rsc.TableForDef(td, connection=conn, exclusive=True)
144 res["getByIdEx"] = jobsTable.getQuery(td, "jobId=%(jobId)s", {"jobId": 0})
145 res["feedToIdEx"] = None, jobsTable.addCommand, None
146 res["deleteByIdEx"] = None, jobsTable.getDeleteQuery(
147 "jobId=%(jobId)s")[0], None
148
149 jobsTable = rsc.TableForDef(td, connection=conn)
150 res["getById"] = jobsTable.getQuery(td, "jobId=%(jobId)s", {"jobId": 0})
151 res["getAllIds"] = jobsTable.getQuery(
152 [td.getColumnByName("jobId")], "")
153
154 countField = base.makeStruct(
155 svcs.OutputField, name="count", type="integer", select="count(*)",
156 required=True)
157 res["countRunning"] = jobsTable.getQuery([countField],
158 "phase='EXECUTING'")
159 res["countQueued"] = jobsTable.getQuery([countField],
160 "phase='QUEUED'")
161
162 self._makeMoreStatements(res, jobsTable)
163 return res
164
165 @property
166 def _statements(self):
167 """returns a dictionary of canned statements manipulating the jobs
168 table.
169 """
170 if self._statementsCache is None:
171 self._statementsCache = self._makeStatementsCache()
172 return self._statementsCache
173
174 def runCanned(self, statementId, args, conn):
175 """runs the canned statement statementId with args through the
176 DB connection conn.
177
178 This will return row dictionaries of the result if there is a result.
179 """
180 resultTableDef, statement, _ = self._statements[statementId]
181 cursor = conn.cursor()
182
183 try:
184 cursor.execute(statement, args)
185 except base.QueryCanceledError:
186 conn.rollback()
187 raise base.ReportableError("Could not access the jobs table."
188 " This probably means there is a stale lock on it. Please"
189 " notify the service operators.")
190
191 res = None
192 if resultTableDef:
193 res = [resultTableDef.makeRowFromTuple(row)
194 for row in cursor]
195 cursor.close()
196 return res
197
198 def _serializeProps(self, props, writableConn):
199 """inserts (or overwrites) the job properties props through
200 wriableConn.
201 """
202 self.runCanned("feedToIdEx", props, writableConn)
203
204 def getNewJobId(self, **kws):
205 """creates a new job and returns its id.
206
207 kws can be properties of the new job or the special key timeout
208 giving after how many seconds we should give up trying to lock
209 the db.
210 """
211 timeout = kws.pop("timeout", _DEFAULT_LOCK_TIMEOUT)
212
213 try:
214 with base.getWritableTableConn() as conn:
215 # We fire off a quick pointless query to catch server restarts;
216 # if this fails, the connection pools are cleared and the next
217 # queries will run again.
218 conn.execute("SELECT table_name FROM TAP_SCHEMA.tables LIMIT 1")
219 except base.DBError:
220 pass
221
222 with base.getWritableTableConn() as conn:
223 with conn.parameters([
224 ("statement_timeout", "%s ms"%int(timeout*1000))]):
225 props = self.jobClass.getDefaults(conn)
226 props["jobId"] = self.jobClass.getNewId(self, conn)
227 job = self.jobClass(props, self, writable=True)
228 job.change(**kws)
229 self._serializeProps(job.getProperties(), conn)
230 return job.jobId
231
232 def getNewIdFromArgs(self, uwsArgs, paramDict, user=None):
233 """returns a new UWS id for a job processing paramDict.
234
235 paramDict need to be parsed already (typically, it's a
236 CoreArgs.getParamDict() result) using the workerSystem's
237 parameterGrammar.
238
239 Pass user to restrict the job to that user. No authentication
240 is done here, so make sure you actually authenticate user
241 (cf. getNewIdFromRequest for how this could be done).
242 """
243 jobId = self.getNewJobId()
244 try:
245 with self.changeableJob(jobId) as wjob:
246 wjob.setParamsFromDict(paramDict)
247 if user is not None:
248 wjob.change(owner=user)
249 except:
250 # something went wrong while setting up the request; do away with it
251 # again
252 self.destroy(jobId)
253 raise
254 return jobId
255
256 def getNewIdFromRequest(self, request):
257 """returns the id of a new TAP job created from request.
258
259 Request has to be a t.w request or similar, but preprocessed
260 by prepareRequest below to have the parsed UWS parameters in uwsArgs.
261 """
262 return self.getNewIdFromArgs(
263 request.uwsArgs,
264 self.parameterGrammar.parseStrargs(
265 request.strargs, ensureRequired=False),
266 request.getAuthUser())
267
268 def _getJob(self, jobId, conn, writable=False):
269 """helps getJob and getNewJob.
270 """
271 # Caution: this code is copied in useruws.UserUWS._getJob
272 # If you find you need to change this, this may be a good
273 # time to figure out how to refactor this method.
274 statementId = 'getById'
275 if writable:
276 statementId = 'getByIdEx'
277 res = self.runCanned(statementId, {"jobId": jobId}, conn)
278 if len(res)!=1:
279 raise JobNotFound(jobId)
280 return self.jobClass(res[0], self, writable)
281
282 def getJob(self, jobId):
283 """returns a read-only UWSJob for jobId.
284
285 Note that by the time you do something with the information here,
286 the "true" state in the database may already be different. There
287 should be no way to write whatever information you have in here,
288 so any "racing" here shouldn't hurt.
289 """
290 with base.getTableConn() as conn:
291 return self._getJob(jobId, conn)
292
293 def getNewJob(self, **kws):
294 """creates a new job and returns a read-only instance for it.
295 """
296 newId = self.getNewJobId(**kws)
297 return self.getJob(newId)
298
299 @contextlib.contextmanager
300 def changeableJob(self, jobId, timeout=_DEFAULT_LOCK_TIMEOUT):
301 """a context manager for job manipulation.
302
303 This is done such that any changes to the job's properties
304 within the controlled section get propagated to the database.
305 As long as you are in the controlled section, nobody else
306 can change the job.
307 """
308 with base.getWritableTableConn() as conn:
309 with conn.parameters([
310 ("statement_timeout", "%s ms"%int(timeout*1000))]):
311 job = self._getJob(jobId, conn, writable=True)
312 try:
313 yield job
314 except:
315 conn.rollback()
316 raise
317 else:
318 self._serializeProps(job.getProperties(), conn)
319 conn.commit()
320
321 def changeToPhase(self, jobId, newPhase, input=None,
322 timeout=_DEFAULT_LOCK_TIMEOUT):
323 with self.changeableJob(jobId, timeout=timeout) as wjob:
324 try:
325 transition = wjob.getTransitionTo(newPhase)
326 return transition(newPhase, wjob, input)
327 except Exception as exception:
328 # transition to error if possible. If that fails at well,
329 # blindly set error and give up.
330 try:
331 if newPhase!=ERROR:
332 return wjob.getTransitionTo(ERROR)(ERROR, wjob, exception)
333 except:
334 wjob.change(phase=ERROR, error=exception)
335 raise
336
337 def destroy(self, jobId):
338 """removes the job with jobId from the UWS.
339
340 This calls the job's prepareForDestruction method while the job is writable.
341 """
342 try:
343 try:
344 with self.changeableJob(jobId) as job:
345 job.prepareForDestruction()
346 except Exception as exc:
347 base.ui.notifyWarning(
348 "Ignored error while destroying UWS job %s: %s"%(jobId, exc))
349 finally:
350 with base.getWritableTableConn() as conn:
351 self.runCanned("deleteByIdEx", locals(), conn)
352
353 def _countUsingCanned(self, statementId):
354 """helps the count* methods.
355 """
356 with base.getTableConn() as conn:
357 return self.runCanned(statementId, {}, conn)[0]["count"]
358
359 def countRunningJobs(self):
360 """returns the number of EXECUTING jobs in the jobsTable.
361 """
362 return self._countUsingCanned('countRunning')
363
364 def countQueuedJobs(self):
365 """returns the number of QUEUED jobs in jobsTable.
366 """
367 return self._countUsingCanned('countQueued')
368
369 def getJobIds(self):
370 """returns a list of all currently existing job ids.
371 """
372 with base.getTableConn() as conn:
373 return [r["jobId"] for r in self.runCanned('getAllIds', {}, conn)]
374
375 def getIdsAndPhases(self, owner=None, phase=None, last=None, after=None,
376 initFragments=None, initPars=None):
377 """returns pairs for id and phase for all jobs in the UWS.
378
379 phase, last, after are the respective parameters from UWS 1.1.
380 """
381 pars = locals()
382 fragments = initFragments or []
383 pars.update(initPars or {})
384 limits = None
385
386 if owner is not None:
387 fragments.append("owner=%(owner)s")
388
389 if phase is not None:
390 fragments.append("phase=%(phase)s")
391
392 if last is not None:
393 limits = "ORDER BY creationTime DESC LIMIT %(limit)s"
394 pars['limit'] = last
395
396 if after is not None:
397 fragments.append("creationTime>%(after)s")
398
399 td = self.jobClass.jobsTD
400
401 with base.getTableConn() as conn:
402 return conn.query(td.getSimpleQuery(["jobId", "phase"],
403 fragments=base.joinOperatorExpr("AND", fragments),
404 postfix=limits), pars)
405
406 def cleanupJobsTable(self, includeFailed=False, includeCompleted=False,
407 includeAll=False, includeForgotten=False):
408 """removes expired jobs from the UWS jobs table.
409
410 The constructor arranged for this to be called now and then
411 (cleanupFrequency class attribute, defaulting to 12*3600).
412
413 The functionality is also exposed through gavo admin cleanuws; this
414 also lets you use the includeFailed and includeCompleted flags. These
415 should not be used on production services since you'd probably nuke
416 jobs still interesting to your users.
417 """
418 with base.AdhocQuerier() as q:
419 if not q.getTableType(self.jobClass.jobsTD.getQName()):
420 # no jobs table, nothing to clean up
421 return
422
423 phasesToKill = set()
424 if includeFailed or includeAll:
425 phasesToKill.add(ERROR)
426 phasesToKill.add(ABORTED)
427 if includeCompleted or includeAll:
428 phasesToKill.add(COMPLETED)
429 if includeAll:
430 phasesToKill.add(PENDING)
431 phasesToKill.add(QUEUED)
432 if includeForgotten:
433 phasesToKill.add(PENDING)
434
435 fragments = "destructionTime<%(now)s"
436 if phasesToKill:
437 fragments = "destructionTime<%(now)s or phase in %(ptk)s"
438
439 for row in self.jobClass.jobsTD.doSimpleQuery(
440 ['jobId'],
441 fragments,
442 {"now": datetime.datetime.utcnow(), "ptk": phasesToKill}):
443 jobId = row["jobId"]
444 try:
445 self.destroy(jobId)
446 except base.QueryCanceledError: # job locked by something, don't hang
447 base.ui.notifyWarning("Postponing destruction of %s: Locked"%
448 jobId)
449 except JobNotFound:
450 # Someone else has cleaned up -- that's ok
451 pass
452
453 def getURLForId(self, jobId): # pragma: no cover
454 """returns the handling URL for the job with jobId.
455
456 You must override this in deriving classes.
457 """
458 raise NotImplementedError("Incomplete UWS (getURLForId not overridden).")
459
460
461 class UWSWithQueueing(UWS):
462 """A UWS with support for queueing.
463
464 Queuing is done on UWS level rather than at transitions. With a plain
465 UWS, if something is put on the queue, it must be started by the
466 Transition's queueJob method.
467
468 With UWSWithQueuing, you just mark the job queued and the rest is
469 taken care of by the UWS itself.
470 """
471 # _processQueueDirty is managed through scheduleProcessQueueCheck
472 _processQueueDirty = False
473 # How many jobs will the UWS (try to) run at the same time?
474 runcountGoal = 1
475 # how often should we do an extra pass over the queue to
476 # see if we can run something? (under normal circumstances,
477 # the queue is checked when a job goes out of executing
478 # more or less immediately; this is just a last-resort thing
479 # -- and it seeds the queue runner after a restart with UWS jobs.
480 queueCheckInterval = 60
481
482 def __init__(self, jobClass, actions):
483 # processQueue shouldn't strictly need a lock. The lock mainly
484 # protects against running more unqueuers than necessary
485 self._processQueueLock = threading.Lock()
486 UWS.__init__(self, jobClass, actions)
487 cron.runEvery(-self.queueCheckInterval,
488 "UWS %s timed queue processor"%str(self),
489 self._processQueue)
490
491 def _makeMoreStatements(self, statements, jobsTable):
492 UWS._makeMoreStatements(self, statements, jobsTable)
493 td = jobsTable.tableDef
494
495 countField = base.makeStruct(
496 svcs.OutputField, name="count", type="integer", select="count(*)",
497 required=True)
498
499 statements["countQueuedBefore"] = jobsTable.getQuery(
500 [countField],
501 "phase='QUEUED' and destructionTime<=%(dt)s",
502 {"dt": None})
503
504 statements["getIdsScheduledNext"] = jobsTable.getQuery(
505 [jobsTable.tableDef.getColumnByName("jobId")],
506 "phase='QUEUED'",
507 limits=('ORDER BY destructionTime ASC', {}))
508
509 statements["getHungCandidates"] = jobsTable.getQuery([
510 td.getColumnByName("jobId"),
511 td.getColumnByName("pid")],
512 "phase='EXECUTING'")
513
514 def scheduleProcessQueueCheck(self):
515 """tells TAP UWS to try and dequeue jobs next time checkProcessQueue
516 is called.
517
518 This function exists since during the TAPTransistions there's
519 a writable job and processing the queue might deadlock. So, rather
520 than processing right away, we just note something may need to be
521 done.
522 """
523 self._processQueueDirty = True
524
525 def checkProcessQueue(self):
526 """sees if any QUEUED process can be made EXECUTING.
527
528 This must be called while you're not holding any changeableJob.
529 """
530 if self._processQueueDirty:
531 self._processQueueDirty = False
532 self._processQueue()
533
534 def _processQueue(self):
535 """tries to take jobs from the queue.
536
537 This function is called from checkProcessQueue when we think we
538 are transitioning from EXECUTING to something else.
539
540 Currently, the jobs with the earliest destructionTime are processed
541 first. That's, of course, completely ad-hoc.
542 """
543 if not self._processQueueLock.acquire(False):
544 # There's already an unqueuer running, don't need a second one
545 # Note that other processes (e.g., taprunner) might still be manipulating
546 # the jobs table, so don't rely on the tables not changing here.
547 return
548 else:
549 try:
550 if self.countQueuedJobs()==0:
551 return
552
553 try:
554 started = 0
555 with base.getTableConn() as conn:
556 toStart = [row["jobId"] for row in
557 self.runCanned('getIdsScheduledNext', {}, conn)]
558
559 while toStart:
560 if self.countRunningJobs()>=self.runcountGoal:
561 break
562 self.changeToPhase(toStart.pop(0), EXECUTING)
563 started += 1
564
565 if started==0:
566 # No jobs could be started. This may be fine when long-runnning
567 # jobs block job submission, but for catastrophic slave
568 # failures we want to make sure all jobs we think are executing
569 # actually are. If they've silently died, we log that and
570 # push them to error.
571 # We only want to do that if we're the server; and it shouldn't
572 # really happen in normal operation, so we only run this
573 # if zombies might block proper jobs.
574 if base.IS_DACHS_SERVER:
575 self._ensureJobsAreRunning()
576 except Exception:
577 base.ui.notifyError("Error during queue processing, "
578 " the UWS %s is probably botched now."%self.__class__.__name__)
579 finally:
580 self._processQueueLock.release()
581
582 def _ensureJobsAreRunning(self):
583 """pushes all executing slave jobs that silently died to ERROR.
584 """
585 with base.getTableConn() as conn:
586 for row in self.runCanned("getHungCandidates", {}, conn):
587 jobId, pid = row["jobId"], row["pid"]
588
589 if pid is None:
590 self.changeToPhase(jobId, "ERROR",
591 UWSError("EXECUTING job %s had no pid."%jobId, jobId))
592 base.ui.notifyError("Stillborn async slave %s"%jobId)
593
594 elif pid<2:
595 # these are jobs run within the server -- we can't do
596 # anything about them using process manipulation (if at all,
597 # they may be realised as threads). Skip them here.
598 continue
599
600 else:
601 # Guard against jobs not cleaning up behind themselves;
602 # If they're kill -9-ed, segfault or anything else, they
603 # won't fix their phase. We also can't be sure they are
604 # our children, as the server may have been restarted.
605 # Simple, somewhat ad-hoc solution: let's see if they're
606 # visible in /proc and push them to error otherwise.
607 # There are various ways in which this could go wrong
608 # (pid reuse, races), but it's still a lot better
609 # than nothing.
610 if not os.path.exists(f"/proc/{pid}"):
611 # the following doesn't hurt if the job has gone to COMPLETED
612 # in the meantime -- we don't transition *from* COMPLETED.
613 self.changeToPhase(jobId, "ERROR",
614 UWSError("EXECUTING job %s has silently died."%jobId, jobId))
615 base.ui.notifyError("Zombie UWS runner: %s"%jobId)
616
617 def changeToPhase(self, jobId, newPhase, input=None, timeout=10):
618 """overridden here to hook in queue management.
619 """
620 UWS.changeToPhase(self, jobId, newPhase, input, timeout)
621 self.checkProcessQueue()
622
623
624 class ParameterRef(object):
625 """A UWS parameter that is (in effect) a URL.
626
627 This always contains a URL. In case of uploads, the tap renderer makes
628 sure the upload is placed into the upload directory and generates a
629 URL; in that case, local is True.
630
631 You need this class when you want the byReference attribute in
632 the UWS.parameter element to be true.
633 """
634 def __init__(self, url, local=False):
635 self.local = local
636 self.url = url
637
638
639 class UWSJobType(type):
640 """The metaclass for UWS jobs.
641
642 We have the metaclass primarily because we want to delay loading
643 the actual definition until it is actually needed (otherwise we
644 might get interesting chicken-egg-problems with rscdesc at some point).
645
646 A welcome side effect is that we can do custom constructors and
647 similar cosmetic deviltry.
648 """
649 @property
650 def jobsTD(cls):
651 try:
652 return cls._jobsTDCache
653 except AttributeError:
654 cls._jobsTDCache = base.resolveCrossId(cls._jobsTDId, rscdef.TableDef)
655 return cls._jobsTDCache
656
657
658 class BaseUWSJob(object, metaclass=UWSJobType):
659 """An abstract UWS job.
660
661 UWS jobs are always instantiiated with a row from the associated
662 jobs table (i.e. a dictionary giving all the uws properties). You
663 can read the properties as attributes. UWSJobs also keep
664 a (weak) reference to the UWS that made them.
665
666 Make sure you don't confuse the UWS properties with the JCL parameters
667 (which are what the core receives). the latter are in the
668 parameters property.
669
670 To alter uws properties, use the change method. This will fail unless
671 the job was created giving writable=True.
672
673 To make it concrete, you need to define:
674
675 - a _jobsTDid attribute giving the (cross) id of the UWS jobs
676 table for this kind of job
677 - a _transitions attribute giving a UWSTransitions instance that defines
678 what to do on transitions
679 - as needed, class methods _default_<parName> if you need to default
680 job parameters in newly created jobs
681 - as needed, methods _decode_<parName> and _encode_<parName>
682 to bring uws parameters (i.e., everything that has a DB column)
683 from and to the DB representation from *python* values.
684
685 You may want to override:
686
687 - a class method getNewId(uws, writableConn) -> str, a method
688 allocating a unique id for a new job and returning it. Beware
689 of races here; if your allocation is through the database table,
690 you'll have to lock it *and* write a preliminary record with your new
691 id. The default implementation does this, but if you want
692 something in the file system, you probably don't want to
693 use that.
694 - a method prepareForDestruction() to do extra cleanup before
695 a job is destroyed.
696
697 The job parameters -- those eventually passed to the core
698 when the job runs -- are held in a dictionary parameters. You
699 should in general not do any parsing of them at the UWS level, as
700 that's really the job of the service/core, as in the sync case.
701
702 However, certain job parameters need handling at the async level,
703 in particular UPLOAD. In that case, define _preprocess_<parName>
704 methods receiving the value as parsed by the grammar and have to
705 return something that can be serialised to the database.
706
707 Note that when you assign to job.parameters yourself, these changes
708 will be ignored. Always use setPar to modify job.parameters.
709 Reading job.parameters is fine.
710
711 If you need to clean up before the job is torn down, redefine
712 the prepareForDestruction method.
713 """
714
715 def __init__(self, props, uws, writable=False):
716 object.__setattr__(self, "_props", props)
717 self.writable = writable
718 self.uws = weakref.proxy(uws)
719
720 def __getattr__(self, name):
721 if name in self._props:
722 return getattr(self, "_decode_"+name, utils.identity)(
723 self._props[name])
724 raise AttributeError("%s objects have no attribute '%s'"%(
725 self.__class__.__name__, name))
726
727 def __setattr__(self, name, value):
728 # ward against tempting bugs, disallow assigning to names in _props:
729 if name in self._props:
730 raise TypeError("Use the change method to change the %s"
731 " attribute."%name)
732 object.__setattr__(self, name, value)
733
734 @property
735 def quote(self):
736 """Always returns None.
737
738 Override if you have a queue management.
739 """
740 return None
741
742 @classmethod
743 def getNewId(cls, uws, conn):
744 cursor = conn.cursor()
745 tableName = cls.jobsTD.getQName()
746 cursor.execute("LOCK TABLE %s IN ACCESS SHARE MODE"%tableName)
747 try:
748 while True:
749 newId = utils.getRandomString(10)
750 cursor.execute("SELECT * FROM %s WHERE jobId=%%(jobId)s"%tableName,
751 {"jobId": newId})
752 if not list(cursor):
753 cursor.execute(
754 "INSERT INTO %s (jobId) VALUES (%%(jobId)s)"%tableName,
755 {"jobId": newId})
756 break
757 cursor.close()
758 conn.commit()
759 except:
760 conn.rollback()
761 raise
762 return newId
763
764 @classmethod
765 def getDefaults(cls, conn):
766 """returns a dictionary suitable for inserting into a jobsTD table.
767 """
768 res = {}
769 for column in cls.jobsTD:
770 name = column.name
771 res[name] = getattr(cls, "_default_"+name, lambda: None)()
772 return res
773
774 @classmethod
775 def _default_phase(cls):
776 return PENDING
777
778 @classmethod
779 def _default_executionDuration(cls):
780 return base.getConfig("async", "defaultExecTime")
781
782 @classmethod
783 def _default_creationTime(cls):
784 return datetime.datetime.utcnow()
785
786 @classmethod
787 def _default_destructionTime(cls):
788 return datetime.datetime.utcnow()+datetime.timedelta(
789 seconds=base.getConfig("async", "defaultLifetime"))
790
791 def _encode_error(self, value):
792 """returns a pickled dictionary with error information.
793
794 value can either be an exception object or a dictionary as
795 generated here.
796 """
797 if value is None:
798 return None
799 if not isinstance(value, dict):
800 value = {
801 "msg": str(value),
802 "hint": getattr(value, "hint", None),
803 }
804 return utils.getCleanBytes(pickle.dumps(value)).decode("ascii")
805
806 def _decode_error(self, value):
807 """returns the unpickled three-item dictionary from the database string.
808 """
809 if value is None:
810 return None
811 return pickle.loads(utils.getDirtyBytes(value))
812
813 @classmethod
814 def _default_parameters(cls):
815 return utils.getCleanBytes(pickle.dumps({}, protocol=2)).decode("ascii")
816
817 def _encode_parameters(self, value):
818 """(db format for parameters is a pickle)
819 """
820 return utils.getCleanBytes(pickle.dumps(value, protocol=2)).decode("ascii")
821
822 def _decode_parameters(self, value):
823 """(db format for parameters is a pickle)
824 """
825 return pickle.loads(utils.getDirtyBytes(value))
826
827 def setPar(self, parName, parValue):
828 """enters parName:parValue into self.parameters.
829 """
830 parName = parName.lower()
831 if parValue is None and self.parameters.get(parName):
832 # don't nuke a parameter that already exists.
833 return
834
835 if hasattr(self, "_preprocess_"+parName):
836 parValue = getattr(self, "_preprocess_"+parName)(parValue)
837 newPars = self.parameters.copy()
838
839 # We'll get DALI uploads as 2-tuples with a BytesIO in the
840 # second item. Save that before serialisation.
841 # Perhaps we should re-use this for TAP (where the analogous
842 # thing happens in _preprocess_upload).
843 if isinstance(parValue, tuple):
844 try:
845 if isinstance(parValue[1], io.BytesIO):
846 parValue = (parName, str(self._saveUpload(parName, parValue[1])))
847 except IndexError:
848 # parValue is too short, hence it's no upload
849 pass
850
851 # we had better check the multiplicity of the inputKey to decide
852 # between extending and overwriting; but for now that's about
853 # equivalent.
854 if isinstance(newPars.get(parName), list):
855 newPars[parName].extend(parValue)
856 elif isinstance(newPars.get(parName), dict):
857 # that's a temporary hack for dlasync until we get to properly
858 # review how to really do that kind of thing
859 newPars[parName].update(parName)
860 else:
861 newPars[parName] = parValue
862 self.change(parameters=newPars)
863
864 def iterSerializedPars(self):
865 """iterates over the serialized versions of the parameters.
866
867 This is, really for uwsactions.getParametersElement, and uses
868 a secret handshake to let this create ByReference links.
869 """
870 for key, value in self.parameters.items():
871 if (isinstance(value, list)
872 and len(value)>0
873 and isinstance(value[0], tuple)
874 and len(value[0])==2
875 and value[0][1].startswith("file://")):
876 # this quite certainly is one of our uploaded files
877 for upload in value:
878 yield key, ParameterRef(
879 LocalFile(self, self.getWD(), upload[1].split("/")[-1]
880 ).getURL())
881
882 elif (isinstance(value, tuple)
883 and len(value)==2
884 and value[1].startswith("file://")):
885 # same thing for DALI uploads
886 yield key, ParameterRef(
887 LocalFile(self, self.getWD(), value[1].split("/")[-1]
888 ).getURL())
889
890 elif isinstance(value, list):
891 # that's supposed to be an array; the following really only works
892 # for numbers; let's see what we do when we do need string arrays
893 # (they don't properly work in VOTable either...)
894 yield key, " ".join(str(v) for v in value)
895
896 else:
897 yield key, "" if value is None else str(value)
898
899 def setParamsFromDict(self, argDict):
900 """sets our parameters from a dictionary of parsed parameters.
901
902 self must be writeable for this to work.
903
904 argDict should in general be the result of a contextgrammar,
905 but, really, any dict will do.
906
907 We force-lowercase everything here. If that's a problem for your
908 protocol, you deserve no mercy.
909 """
910 for key, value in argDict.items():
911 self.setPar(key.lower(), value)
912
913 def setParamsFromRawDict(self, strargs):
914 """sets our parameters from a dictionary of string lists (i.e.,
915 requests.strargs).
916
917 The job must be writeable when you call this.
918
919 The arguments don't have to be complete by the parameterGrammar;
920 this also means that no defaults are inserted. Use job.completeParams()
921 for that (it's typically called when queuing a job).
922 """
923 self.setParamsFromDict(
924 self.uws.parameterGrammar.parseStrargs(strargs, ensureRequired=False))
925
926 def completeParams(self):
927 """completes self's parameters from the worker's context grammar.
928
929 Job must be writable for this to work.
930
931 This is necessary because in UWS operations, actions for
932 missing parameters are never executed; missing parameters
933 could still be provided later.
934
935 Worker systems hence must arrange for this to be called when queueing
936 a job; SimpleUWSTransitions.queueJob already does that. This may raise
937 an exception if parameters are missing.
938 """
939 pars = self.parameters
940 for ik in self.uws.parameterGrammar.iterInputKeys():
941 key = ik.name.lower()
942 val = pars.get(key)
943 if val is None or val==[]:
944 pars[key] = ik.computeCoreArgValue([])
945 self.change(parameters=pars)
946
947 def getTransitionTo(self, newPhase):
948 """returns the action prescribed to push self to newPhase.
949
950 A ValidationError is raised if no such transition is defined.
951 """
952 return self._transitions.getTransition(self.phase, newPhase)
953
954 def change(self, **kwargs):
955 """changes the property values to what's given by the keyword arguments.
956
957 It is an AttributeError to try and change a property that is not defined.
958 """
959 if not self.writable:
960 raise TypeError("Read-only UWS job (You can only change UWSJobs"
961 "obtained through changeableJob.")
962 for propName, propValue in kwargs.items():
963 if propName not in self._props:
964 raise AttributeError("%ss have no attribute %s"%(
965 self.__class__.__name__, propName))
966 self._props[propName] = getattr(self, "_encode_"+propName,
967 utils.identity)(propValue)
968
969 def getProperties(self):
970 """returns the properties of the job as they are stored in the
971 database.
972
973 Use attribute access to read them and change to change them. Do
974 *not* get values from the dictionary you get and do *not* change
975 the dictionary.
976 """
977 return self._props
978
979 def update(self):
980 """fetches a new copy of the job props from the DB.
981
982 You should in general not need this, since UWSJob objects are intended
983 to be short-lived ("for the duration of an async request"). Still,
984 for testing and similar, it's convenient to be able to update
985 a UWS job from the database.
986 """
987 self._props = self.uws.getJob(self.jobId)._props
988 return self
989
990 def prepareForDestruction(self):
991 """is called before the job's database row is torn down.
992
993 Self is writable at this point.
994 """
995
996 def getURL(self):
997 """returns the UWS URL for this job.
998 """
999 return self.uws.getURLForId(self.jobId)
1000
1001 @contextlib.contextmanager
1002 def getWritable(self):
1003 """a context manager for a writeable version of the job.
1004
1005 Changes will be written back at the end, and the job object itself
1006 will be updated from the database.
1007
1008 If self already is writable, it is returned unchanged, and changes
1009 are only persisted when the enclosing controlling block finishes.
1010 """
1011 if self.writable:
1012 yield self
1013 return
1014
1015 with self.uws.changeableJob(self.jobId) as wjob:
1016 yield wjob
1017 self.update()
1018
1019
1020 class LocalFile(object):
1021 """A sentinel class representing a file within a job work directory
1022 (as resulting from an upload).
1023 """
1024 def __init__(self, jobId, wd, fileName):
1025 self.job, self.fileName = weakref.proxy(jobId), fileName
1026 self.fullPath = os.path.join(wd, fileName)
1027
1028 def __str__(self):
1029 # This is mainly for serialisation of the upload parameter in the
1030 # UWS job.
1031 return f"file://{self.fileName}"
1032
1033 def getURL(self):
1034 """returns the URL the file is retrievable under for the life time of
1035 the job.
1036 """
1037 return self.job.getURL()+f"/results/{self.fileName}"
1038
1039
1040 class UWSJobWithWD(BaseUWSJob):
1041 """A UWS job with a working directory.
1042
1043 This generates ids from directory names in a directory (the
1044 uwsWD) shared for all UWSes on the system.
1045
1046 It also adds methods
1047
1048 - getWD() -> str returning the working directory
1049 - addResult(self, source, mimeType, name=None) to add a new
1050 result
1051 - openResult(self, mimeType, name) -> file to get an open file in the
1052 WD to write to in order to generate a result
1053 - getResult(self, resName) -> str to get the *path* of a result with
1054 resName
1055 - getResults(self) -> list-of-dicts to get dicts describing all
1056 results available
1057 - openFile(self) -> file to get a file letting you read an existing
1058 result.
1059 """
1060 @classmethod
1061 def getNewId(self, uws, conn):
1062 # our id is the base name of the jobs's temporary directory.
1063 uwsWD = base.getConfig("uwsWD")
1064 utils.ensureDir(uwsWD, mode=0o775, setGroupTo=base.getGroupId())
1065 jobDir = tempfile.mkdtemp("", "", dir=uwsWD)
1066 return os.path.basename(jobDir)
1067
1068 def getWD(self):
1069 return os.path.join(base.getConfig("uwsWD"), self.jobId)
1070
1071 def prepareForDestruction(self):
1072 shutil.rmtree(self.getWD())
1073
1074 # results management: We use a pickled list in the jobs dir to manage
1075 # the results. I once had a table of those in the DB and it just
1076 # wasn't worth it. One issue, though: this potentially races
1077 # if two different processes/threads were to update the results
1078 # at the same time. This could be worked around by writing
1079 # the results pickle only from within changeableJobs.
1080 #
1081 # The list contains dictionaries having resultName and resultType keys.
1082 @property
1083 def _resultsDirName(self):
1084 return os.path.join(self.getWD(), "__RESULTS__")
1085
1086 def _loadResults(self):
1087 try:
1088 with open(self._resultsDirName, "rb") as f:
1089 return pickle.load(f)
1090 except IOError:
1091 return []
1092
1093 def _saveResults(self, results):
1094 handle, srcName = tempfile.mkstemp(dir=self.getWD())
1095 with os.fdopen(handle, "wb") as f:
1096 pickle.dump(results, f)
1097 # The following operation will bomb on windows when the second
1098 # result is saved. Tough luck.
1099 os.rename(srcName, self._resultsDirName)
1100
1101 def _addResultInJobDir(self, mimeType, name):
1102 resTable = self._loadResults()
1103 newRec = {'resultName': name, 'resultType': mimeType}
1104
1105 for index, res in enumerate(resTable):
1106 if res["resultName"]==name:
1107 resTable[index] = newRec
1108 break
1109 else:
1110 resTable.append(
1111 {'resultName': name, 'resultType': mimeType})
1112
1113 self._saveResults(resTable)
1114
1115 def _preprocess_upload(self, uploadParam):
1116 """picks non-saved inline uploads from uploadParam and saves them.
1117
1118 This is done so we can serialise the uploads into the database; we
1119 wouldn't want to do that with the uploads.
1120
1121 Note that this is called by setPar("upload") by virtue of its
1122 magic name.
1123 """
1124 if not uploadParam:
1125 return None
1126
1127 processed = []
1128 for destTable, target in uploadParam:
1129 if isinstance(target, tuple):
1130 target = self._saveUpload(destTable, target[1])
1131 processed.append((destTable, str(target)))
1132 return processed
1133
1134 def _saveUpload(self, localName, uploadFile):
1135 """helps preprocess_upload.
1136 """
1137 with self.openFile(localName, "wb") as f:
1138 f.write(uploadFile.read())
1139 return LocalFile(self, self.getWD(), localName)
1140
1141 def fixTypeForResultName(self, resultName, mediaType):
1142 """sets the media type for result resultName.
1143
1144 It is not an error if no result with resultName exists.
1145 """
1146 resTable = self._loadResults()
1147 for row in resTable:
1148 if row["resultName"]==resultName:
1149 row["resultType"] = mediaType
1150 self._saveResults(resTable)
1151
1152 def addResult(self, source, mimeType, name=None):
1153 """adds a result, with data taken from source.
1154
1155 source may be a file-like object or a string, or bytes.
1156
1157 If no name is passed, a name is auto-generated.
1158 """
1159 if name is None:
1160 name = utils.intToFunnyName(id(source))
1161 with open(os.path.join(self.getWD(), name), "wb") as destF:
1162 if isinstance(source, str):
1163 source = utils.bytify(source)
1164 if isinstance(source, bytes):
1165 destF.write(source)
1166 else:
1167 utils.cat(source, destF)
1168 self._addResultInJobDir(mimeType, name)
1169
1170 def openResult(self, mimeType, name):
1171 """returns a writable file that adds a result.
1172 """
1173 self._addResultInJobDir(mimeType, name)
1174 return open(os.path.join(self.getWD(), name), "wb")
1175
1176 def getResult(self, resName):
1177 """returns a pair of file name and mime type for a named job result.
1178
1179 If the result does not exist, a NotFoundError is raised.
1180 """
1181 res = [r for r in self._loadResults() if resName==r["resultName"]]
1182 if not res:
1183 raise base.NotFoundError(resName, "job result",
1184 "uws job %s"%self.jobId)
1185 res = res[0]
1186 return os.path.join(self.getWD(), res["resultName"]), res["resultType"]
1187
1188 def getResults(self):
1189 """returns a list of this service's results.
1190
1191 The list contains dictionaries having at least resultName and resultType
1192 keys.
1193 """
1194 return self._loadResults()
1195
1196 def openFile(self, name, mode="rb"):
1197 """returns an open file object for a file within the job's work directory.
1198
1199 This will only use the last path component, everything else is
1200 discarded.
1201 """
1202 name = name.split("/")[-1]
1203 return open(os.path.join(self.getWD(), name), mode)
1204
1205
1206 class UWSTransitions(object):
1207 """An abstract base for classes defining the behaviour of a UWS.
1208
1209 This basically is the definition of a finite state machine with
1210 arbitrary input (which is to say: the input "alphabet" is up to
1211 the transitions).
1212
1213 A UWSTransitions instance is in the transitions attribute of a job
1214 class.
1215
1216 The main interface to UWSTransitions is getTransition(p1, p2) -> callable
1217 It returns a callable that should push the automaton from phase p1
1218 to phase p2 or raise an ValidationError for a field phase.
1219
1220 The callable has the signature f(desiredPhase, wjob, input) -> None.
1221 It must alter the uwsJob object as appropriate. input is some object
1222 defined by the the transition. The job passed is a changeable job,
1223 so the handlers actually hold locks to the job row. Thus, be brief.
1224
1225 The transitions are implemented as simple methods having the signature
1226 of the callables returned by getTransition.
1227
1228 To link transitions and methods, pass a vertices list to the constructor.
1229 This list consists of 3-tuples of strings (from, to, method-name). From and
1230 to are phase names (use the symbols from this module to ward against typos).
1231 """
1232 def __init__(self, name, vertices):
1233 self.name = name
1234 self._buildTransitions(vertices)
1235
1236 def _buildTransitions(self, vertices):
1237 self.transitions = {}
1238 # set some defaults
1239 for phase in [PENDING, QUEUED, EXECUTING, ERROR, ABORTED, COMPLETED]:
1240 self.transitions.setdefault(phase, {})[ERROR] = "flagError"
1241 self.transitions.setdefault(EXECUTING, {})[COMPLETED
1242 ] = "noteEndTime"
1243
1244 for fromPhase, toPhase, methodName in vertices:
1245 self.transitions.setdefault(fromPhase, {})[toPhase] = methodName
1246
1247 def getTransition(self, fromPhase, toPhase):
1248 if (fromPhase==toPhase or
1249 fromPhase in END_STATES):
1250 # ignore null or ignorable transitions
1251 return lambda p, job, input: None
1252 try:
1253 methodName = self.transitions[fromPhase][toPhase]
1254 except KeyError:
1255 raise base.ui.logOldExc(
1256 base.ValidationError("No transition from %s to %s defined"
1257 " for %s jobs"%(fromPhase, toPhase, self.name),
1258 "phase", hint="This almost always points to an implementation error"))
1259 try:
1260 return getattr(self, methodName)
1261 except AttributeError:
1262 raise base.ui.logOldExc(
1263 base.ValidationError("%s Transitions have no %s methods"%(self.name,
1264 methodName),
1265 "phase", hint="This is an error in an internal protocol definition."
1266 " There probably is nothing you can do but complain."))
1267
1268 def noOp(self, newPhase, job, ignored):
1269 """a sample action just setting the new phase.
1270
1271 This is a no-op baseline sometimes useful in user code.
1272 """
1273 job.change(phase=newPhase)
1274
1275 def flagError(self, newPhase, wjob, exception):
1276 """the default action when transitioning to an error: dump exception and
1277 mark phase as ERROR..
1278 """
1279 wjob.change(phase=ERROR)
1280 # Validation errors don't get logged -- for one, they probably
1281 # are the user's fault, and for a second, logging them upsets
1282 # trial during testing, since trial examines the log.
1283 if not isinstance(exception, base.ValidationError):
1284 base.ui.notifyError("Error during UWS execution of job %s"%wjob.jobId)
1285 wjob.change(error=exception)
1286 if wjob.endTime is None:
1287 wjob.change(endTime=datetime.datetime.utcnow())
1288
1289 def noteEndTime(self, newPhase, wjob, ignored):
1290 wjob.change(endTime=datetime.datetime.utcnow())
1291
1292
1293 class SimpleUWSTransitions(UWSTransitions):
1294 """A UWSTransitions with sensible transitions pre-defined.
1295
1296 See the source for what we consider sensible.
1297
1298 The idea here is that you simply override (and usually up-call)
1299 the methods queueJob, markAborted, startJob, completeJob,
1300 killJob, errorOutJob, and ignoreAndLog.
1301
1302 You will have to define startJob and provide some way to execute
1303 startJob on QUEUED jobs (there's nothing wrong with immediately
1304 calling self.startJob(...) if you don't mind the DoS danger).
1305
1306 Once you have startJob, you'll probably want to define killJob as
1307 well.
1308 """
1309 def __init__(self, name):
1310 UWSTransitions.__init__(self, name, [
1311 (PENDING, QUEUED, "queueJob"),
1312 (PENDING, ABORTED, "markAborted"),
1313 (QUEUED, ABORTED, "markAborted"),
1314 (QUEUED, EXECUTING, "startJob"),
1315 (EXECUTING, COMPLETED, "completeJob"),
1316 (EXECUTING, ABORTED, "killJob"),
1317 (EXECUTING, ERROR, "errorOutJob"),
1318 (COMPLETED, ERROR, "ignoreAndLog"),
1319 ])
1320
1321 def queueJob(self, newState, wjob, ignored):
1322 """puts a job on the queue.
1323 """
1324 wjob.completeParams()
1325 wjob.change(phase=QUEUED)
1326
1327 def markAborted(self, newState, wjob, ignored):
1328 """simply marks job as aborted.
1329
1330 This is what happens if you abort a job from QUEUED or
1331 PENDING.
1332 """
1333 wjob.change(phase=ABORTED,
1334 endTime=datetime.datetime.utcnow())
1335
1336 def ignoreAndLog(self, newState, wjob, exc):
1337 """logs an attempt to transition when it's impossible but
1338 shouldn't result in an error.
1339
1340 This is mainly so COMPLETED things don't fail just because of some
1341 mishap.
1342 """
1343 base.ui.logErrorOccurred("Request to push %s job to ERROR: %s"%(
1344 wjob.phase, str(exc)))
1345
1346 def errorOutJob(self, newPhase, wjob, exception):
1347 """pushes a job to an error state.
1348
1349 This is called by a worker; leaving the error message itself
1350 is part of the worker's duty; here, exception will just be logged.
1351 """
1352 wjob.change(phase=newPhase, endTime=datetime.datetime.utcnow())
1353 self.flagError(newPhase, wjob, exception)
1354
1355 def killJob(self, newPhase, wjob, ignored): # pragma: no cover
1356 """should abort a job.
1357
1358 There's really not much we can do here, so this is a no-op.
1359
1360 Do not up-call here, you'll get a (then spurious) warning
1361 if you do.
1362 """
1363 base.ui.notifyWarning("%s UWSes cannot kill jobs"%self.name)
1364
1365 def completeJob(self, newPhase, wjob, ignored):
1366 """pushes a job into the completed state.
1367 """
1368 wjob.change(phase=newPhase, endTime=datetime.datetime.utcnow())
1369
1370
1371 def _replaceFDs(inFName, outFName):
1372 # This is used for clean forking and doesn't actually belong here.
1373 # utils.ostricks should take this.
1374 """closes all (findable) file descriptors and replaces stdin with inF
1375 and stdout/err with outF.
1376 """
1377 for fd in range(255, -1, -1):
1378 try:
1379 os.close(fd)
1380 except os.error:
1381 pass
1382 inF, outF = open(inFName), open(outFName, "w")
1383 os.dup(inF.fileno())
1384 os.dup(outF.fileno())
1385 os.dup(outF.fileno())
1386
1387
1388 class _UWSBackendProtocol(protocol.ProcessProtocol):
1389 """The protocol used for taprunners when spawning them under a twisted
1390 reactor.
1391 """
1392 def __init__(self, jobId, workerSystem):
1393 self.jobId = jobId
1394 self.workerSystem = workerSystem
1395
1396 def outReceived(self, data):
1397 base.ui.notifyInfo("UWS worker %s produced output: %s"%(
1398 self.jobId, data))
1399
1400 def errReceived(self, data):
1401 base.ui.notifyInfo("UWS worker %s produced an error message: %s"%(
1402 self.jobId, data))
1403
1404 def processEnded(self, statusObject):
1405 """tries to ensure the job is in an admitted end state.
1406 """
1407 try:
1408 job = self.workerSystem.getJob(self.jobId)
1409 if job.phase==QUEUED or job.phase==EXECUTING:
1410 self.workerSystem.changeToPhase(self.jobId, ERROR,
1411 UWSError("Job hung in %s"%job.phase, job.jobId))
1412 except JobNotFound: # job already deleted
1413 pass
1414
1415
1416 class ProcessBasedUWSTransitions(SimpleUWSTransitions):
1417 """A SimpleUWSTransistions that processes its stuff in a child process.
1418
1419 Inheriting classes must implement the getCommandLine(wjob) method --
1420 it must return a command (suitable for reactor.spawnProcess and
1421 os.execlp) and a list of arguments suitable for reactor.spawnProcess.
1422
1423 They must also implement some sort of queue management. The the simplest
1424 case, override queueJob and start the job from there (but set
1425 to QUEUED in there anyway).
1426 """
1427 # 2019 trial (at least sometimes) starts the reactor too late for
1428 # us to notice it's running in startJob. The following attribute
1429 # lets the testing code force the use of twisted mechanismus.
1430 trial_forceTwisted = False
1431
1432 def getCommandLine(self, wjob):
1433 raise NotImplementedError("%s transitions do not define how"
1434 " to get a command line"%self.__class__.__name__)
1435
1436 def _startJobTwisted(self, wjob):
1437 """starts a job by forking a new process when we're running
1438 within a twisted reactor.
1439 """
1440 assert wjob.phase==QUEUED
1441 cmd, args = self.getCommandLine(wjob)
1442 pt = reactor.spawnProcess(_UWSBackendProtocol(wjob.jobId, wjob.uws),
1443 cmd, args=args,
1444 env=os.environ)
1445 wjob.change(pid=pt.pid, phase=EXECUTING)
1446
1447 def _startJobNonTwisted(self, wjob):
1448 """forks off a new process when (hopefully) a manual child reaper
1449 is in place.
1450 """
1451 cmd, args = self.getCommandLine(wjob)
1452 pid = os.fork()
1453 if pid==0:
1454 # in case of taprunner trouble, comment out the following;
1455 # you will then at least see the output of taprunner.
1456 #_replaceFDs("/dev/zero","/dev/null")
1457 os.execlp(cmd, *args)
1458 elif pid>0:
1459 wjob.change(pid=pid, phase=EXECUTING)
1460 else:
1461 raise Exception("Could not fork")
1462
1463 def startJob(self, newState, wjob, ignored):
1464 """causes a process to be started that executes job.
1465
1466 This dispatches according to whether or not we are within a twisted
1467 event loop, mostly for testing support.
1468 """
1469 withinTwisted = self.trial_forceTwisted or reactor.running
1470 # 2019 trial starts the reactor too late for us to notice we should
1471 # be using the twisted code. I hack around it by the trial code
1472 if withinTwisted:
1473 return self._startJobTwisted(wjob)
1474 else:
1475 return self._startJobNonTwisted(wjob)
1476
1477 def killJob(self, newState, wjob, ignored):
1478 """tries to kill/abort job.
1479
1480 Actually, there are two different scenarios here: Either the job has
1481 a non-NULL startTime. In that case, the child job is in control
1482 and will manage the state itself. Then kill -INT will do the right
1483 thing.
1484
1485 However, if startTime is NULL, the child is still starting up. Sending
1486 a kill -INT may do many things, and most of them we don't want.
1487 So, in this case we kill -TERM the child, do state management ourselves
1488 and hope for the best.
1489 """
1490 try:
1491 pid = wjob.pid
1492 if pid is None:
1493 raise UWSError("Job is not running")
1494 elif pid<2:
1495 raise UWSError("Job has unkillable PID")
1496
1497 if wjob.startTime is None:
1498 # the child job is not up yet, kill it brutally and manage
1499 # state ourselves
1500 os.kill(pid, signal.SIGTERM)
1501 self.markAborted(ABORTED, wjob, ignored)
1502 else:
1503 # child job is up, can manage state itself
1504 os.kill(pid, signal.SIGINT)
1505 except UWSError:
1506 raise
1507 except Exception as ex:
1508 raise UWSError(None, ex)
1509
1510
1511 @functools.lru_cache(None)
1512 def _getUWSGrammar():
1513 """returns the context grammar for the standard UWS parameters.
1514 """
1515 inputTD = base.parseFromString(svcs.InputTD,
1516 """<inputTable id="generic-uws-args">
1517 <inputKey name="upload" type="file"
1518 multiplicity="multiple"
1519 description="A DALI-type upload string"/>
1520 <inputKey name="runid" type="text"
1521 description="Ignored by this service."/>
1522 <inputKey name="action" type="text"
1523 multiplicity="single"
1524 description="On posts to the job URI, you can pass in DELETE here
1525 instead of using the standards-compliant DELETE method.
1526 Ignored otherwise."/>
1527 <inputKey name="wait" type="text"
1528 unit="s"
1529 multiplicity="single"
1530 description="On certain operations, pass a timeout here to
1531 have the server delay its response until there is a change
1532 to report."/>
1533 <inputKey name="phase" type="text"
1534 multiplicity="single"
1535 description="A UWS PHASE; the interpretation is different across
1536 the UWS operations."/>
1537 <inputKey name="executionduration" type="text"
1538 unit="s"
1539 multiplicity="single"
1540 description="When posting to the job resource, set the maximum
1541 run time of the query to this."/>
1542 <inputKey name="destruction" type="text"
1543 multiplicity="single"
1544 description="When posting to the job resource, adjust the
1545 time at which the job will be thrown away to this."/>
1546 </inputTable>""")
1547 return base.makeStruct(svcs.ContextGrammar, inputTD=inputTD)
1548
1549
1550 def prepareRequest(request, service):
1551 """prepares request for processing UWS requests.
1552
1553 In UWS, the service in general doesn't run, and hence there's no
1554 context grammar running. Also, there are the UWS-specific parameters,
1555 which the core shouldn't be seeing.
1556
1557 These latter ones are parsed into request.uwsArgs by this functions. This
1558 is what drives uwsactions. The function removes the corresponding keys from
1559 strargs so the core in question is not confused by them.
1560 """
1561 uwsGrammar = _getUWSGrammar()
1562 request.uwsArgs = uwsGrammar.parseStrargs(request.strargs)
1563 uwsKeys = [ik.name for ik in uwsGrammar.iterInputKeys()]
1564
1565 if service.core.name_=="tapCore":
1566 from gavo.protocols import tap
1567 tap.mangleUploads(request)
1568 # TAP needs to retain the upload parameter (in contrast to DALI,
1569 # where the keys already contain the uploads)
1570 uwsKeys.remove("upload")
1571 else:
1572 dali.mangleUploads(request)
1573
1574 # now remove the UWS arguments so they don't confuse any actual cores.
1575 for uwsInputName in uwsKeys:
1576 if uwsInputName in request.strargs:
1577 del request.strargs[uwsInputName]