| 1 |
""" |
| 2 |
Manipulating UWS jobs through a REST interface. |
| 3 |
|
| 4 |
The result documents are defined through the schema uws-1.0.xsd. |
| 5 |
|
| 6 |
Instead of returning XML, they can also raise svcs.SeeOther exceptions. |
| 7 |
However, these are caught in JobResource._redirectAsNecessary and appended |
| 8 |
to the base URL auf the TAP service, so you must only give URIs relative |
| 9 |
to the TAP service's root URL. |
| 10 |
|
| 11 |
This UWS system should adapt to concrete UWSes; the UWS in use is passed |
| 12 |
into the top-level functions (doJobAction , getJobList). |
| 13 |
|
| 14 |
The actions pretty much resemble twisted.web Resources; perhaps this |
| 15 |
should be refactored to use them. For now, however, we don't pass around |
| 16 |
resources, we pass around callables that are used within renderers |
| 17 |
in asyncrender, which lets asyncrender factor out a bit of common |
| 18 |
functionality. Hm. |
| 19 |
""" |
| 20 |
|
| 21 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 22 |
#c |
| 23 |
#c This program is free software, covered by the GNU GPL. See the |
| 24 |
#c COPYING file in the source distribution. |
| 25 |
|
| 26 |
|
| 27 |
import os |
| 28 |
|
| 29 |
from twisted.internet import reactor |
| 30 |
from twisted.internet import defer |
| 31 |
from twisted.web import server |
| 32 |
from twisted.web import static |
| 33 |
|
| 34 |
from gavo import base |
| 35 |
from gavo import svcs |
| 36 |
from gavo import utils |
| 37 |
from gavo.protocols import dali |
| 38 |
from gavo.protocols import uws |
| 39 |
from gavo.utils import stanxml |
| 40 |
|
| 41 |
|
| 42 |
UWSNamespace = 'http://www.ivoa.net/xml/UWS/v1.0' |
| 43 |
XlinkNamespace = "http://www.w3.org/1999/xlink" |
| 44 |
stanxml.registerPrefix("uws", UWSNamespace, |
| 45 |
stanxml.schemaURL("UWS-1.1.xsd")) |
| 46 |
stanxml.registerPrefix("xlink", XlinkNamespace, |
| 47 |
stanxml.schemaURL("xlink.xsd")) |
| 48 |
|
| 49 |
|
| 50 |
class UWS(object): |
| 51 |
"""the container for elements from the uws namespace. |
| 52 |
""" |
| 53 |
class UWSElement(stanxml.Element): |
| 54 |
_prefix = "uws" |
| 55 |
|
| 56 |
@staticmethod |
| 57 |
def makeRoot(ob): |
| 58 |
ob._additionalPrefixes = stanxml.xsiPrefix |
| 59 |
ob._mayBeEmpty = True |
| 60 |
return ob |
| 61 |
|
| 62 |
class job(UWSElement): |
| 63 |
_a_version = "1.1" |
| 64 |
|
| 65 |
class jobs(UWSElement): |
| 66 |
_mayBeEmpty = True |
| 67 |
_a_version = "1.1" |
| 68 |
|
| 69 |
class parameters(UWSElement): pass |
| 70 |
|
| 71 |
class destruction(UWSElement): pass |
| 72 |
class endTime(stanxml.NillableMixin, UWSElement): pass |
| 73 |
class creationTime(UWSElement): pass |
| 74 |
class executionDuration(UWSElement): pass |
| 75 |
class jobId(UWSElement): pass |
| 76 |
class jobInfo(UWSElement): pass |
| 77 |
class message(UWSElement): pass |
| 78 |
class ownerId(stanxml.NillableMixin, UWSElement): pass |
| 79 |
class phase(UWSElement): pass |
| 80 |
class quote(stanxml.NillableMixin, UWSElement): pass |
| 81 |
class runId(UWSElement): pass |
| 82 |
class startTime(stanxml.NillableMixin, UWSElement): pass |
| 83 |
|
| 84 |
class detail(UWSElement): |
| 85 |
_a_href = None |
| 86 |
_a_type = None |
| 87 |
_name_a_href = "xlink:href" |
| 88 |
_name_a_type = "xlink:type" |
| 89 |
|
| 90 |
class errorSummary(UWSElement): |
| 91 |
_a_type = None # transient | fatal |
| 92 |
_a_hasDetail = None |
| 93 |
|
| 94 |
class jobref(UWSElement): |
| 95 |
_additionalPrefixes = frozenset(["xlink"]) |
| 96 |
_a_id = None |
| 97 |
_a_href = None |
| 98 |
_a_type = None |
| 99 |
_name_a_href = "xlink:href" |
| 100 |
_name_a_type = "xlink:type" |
| 101 |
|
| 102 |
class parameter(UWSElement): |
| 103 |
_mayBeEmpty = True |
| 104 |
_a_byReference = None |
| 105 |
_a_id = None |
| 106 |
_a_isPost = None |
| 107 |
|
| 108 |
class result(UWSElement): |
| 109 |
_additionalPrefixes = frozenset(["xlink"]) |
| 110 |
_mayBeEmpty = True |
| 111 |
_a_id = None |
| 112 |
_a_href = None |
| 113 |
_a_type = None |
| 114 |
_name_a_href = "xlink:href" |
| 115 |
_name_a_type = "xlink:type" |
| 116 |
|
| 117 |
class results(UWSElement): |
| 118 |
_mayBeEmpty = True |
| 119 |
|
| 120 |
|
| 121 |
def getJobList(workerSystem, |
| 122 |
forOwner=None, |
| 123 |
phase=None, |
| 124 |
last=None, |
| 125 |
after=None): |
| 126 |
result = UWS.jobs() |
| 127 |
for jobId, phase in workerSystem.getIdsAndPhases( |
| 128 |
forOwner, phase, last, after): |
| 129 |
result[ |
| 130 |
UWS.jobref(id=jobId, href=workerSystem.getURLForId(jobId))[ |
| 131 |
UWS.phase[phase]]] |
| 132 |
return stanxml.xmlrender(result, workerSystem.joblistPreamble) |
| 133 |
|
| 134 |
|
| 135 |
def getErrorSummary(job): |
| 136 |
# all our errors are fatal, and for now .../error yields the same thing |
| 137 |
# as we include here, so we hardcode the attributes. |
| 138 |
errDesc = job.error |
| 139 |
if not errDesc: |
| 140 |
return None |
| 141 |
msg = errDesc["msg"] |
| 142 |
if errDesc["hint"]: |
| 143 |
msg = msg+"\n\n -- Hint: "+errDesc["hint"] |
| 144 |
return UWS.errorSummary(type="fatal", hasDetail="false")[ |
| 145 |
UWS.message[msg]] |
| 146 |
|
| 147 |
|
| 148 |
def getParametersElement(job): |
| 149 |
"""returns a UWS.parameters element for job. |
| 150 |
""" |
| 151 |
res = UWS.parameters() |
| 152 |
for key, value in job.iterSerializedPars(): |
| 153 |
if isinstance(value, uws.ParameterRef): |
| 154 |
res[UWS.parameter(id=key, byReference=True)[value.url]] |
| 155 |
else: |
| 156 |
res[UWS.parameter(id=key)[str(value)]] |
| 157 |
return res |
| 158 |
|
| 159 |
|
| 160 |
class JobActions(object): |
| 161 |
"""A collection of "actions" performed on UWS jobs. |
| 162 |
|
| 163 |
Their names are the names of the child resources of UWS jobs. The basic UWS |
| 164 |
actions are built in. When constructing those, you can pass in as many |
| 165 |
additional JobAction subclasses as you want. Set their names to |
| 166 |
one of UWS standard actions to override UWS behaviour if you think |
| 167 |
that's wise. |
| 168 |
""" |
| 169 |
_standardActions = {} |
| 170 |
|
| 171 |
def __init__(self, *additionalActions): |
| 172 |
self.actions = {} |
| 173 |
self.actions.update(self._standardActions) |
| 174 |
for actionClass in additionalActions: |
| 175 |
self.actions[actionClass.name] = actionClass() |
| 176 |
|
| 177 |
@classmethod |
| 178 |
def addStandardAction(cls, actionClass): |
| 179 |
cls._standardActions[actionClass.name] = actionClass() |
| 180 |
|
| 181 |
def dispatch(self, action, job, request, segments): |
| 182 |
if job.owner: |
| 183 |
if request.getAuthUser()!=job.owner: |
| 184 |
raise svcs.Authenticate() |
| 185 |
|
| 186 |
try: |
| 187 |
resFactory = self.actions[action] |
| 188 |
except KeyError: |
| 189 |
raise base.ui.logOldExc( |
| 190 |
svcs.UnknownURI("Invalid UWS action '%s'"%action)) |
| 191 |
request.setHeader("content-type", resFactory.mime) |
| 192 |
return resFactory.getResource(job, request, segments) |
| 193 |
|
| 194 |
|
| 195 |
class JobAction(object): |
| 196 |
"""an action done to a job. |
| 197 |
|
| 198 |
It defines methods do<METHOD> that are dispatched through JobActions. |
| 199 |
|
| 200 |
It must have a name corresponding to the child resource names from |
| 201 |
the UWS spec. |
| 202 |
""" |
| 203 |
name = None |
| 204 |
mime = "text/xml" |
| 205 |
|
| 206 |
def getResource(self, job, request, segments): |
| 207 |
if segments: |
| 208 |
raise svcs.UnknownURI("Too many segments") |
| 209 |
try: |
| 210 |
handler = getattr(self, "do"+utils.debytify(request.method)) |
| 211 |
except AttributeError: |
| 212 |
raise base.ui.logOldExc(svcs.BadMethod(request.method)) |
| 213 |
return handler(job, request) |
| 214 |
|
| 215 |
|
| 216 |
class ErrorAction(JobAction): |
| 217 |
name = "error" |
| 218 |
mime = "text/plain" |
| 219 |
|
| 220 |
def doGET(self, job, request): |
| 221 |
if job.error is None: |
| 222 |
return b"" |
| 223 |
|
| 224 |
return dali.serveDALIError(request, job.error, httpStatus=200) |
| 225 |
|
| 226 |
doPOST = doGET |
| 227 |
JobActions.addStandardAction(ErrorAction) |
| 228 |
|
| 229 |
|
| 230 |
class StartTimeAction(JobAction): |
| 231 |
# This an extension over plain UWS allowing users to retrieve when |
| 232 |
# their job started. In the DaCHS' TAP implementation, this lets |
| 233 |
# you discern whether the taprunner is already processing an EXECUTING |
| 234 |
# job (startTime!=NULL) or whether it's still coming up (else) |
| 235 |
name = "startTime" |
| 236 |
mime = "text/plain" |
| 237 |
|
| 238 |
def doGET(self, job, request): |
| 239 |
if job.startTime is None: |
| 240 |
return b"NULL" |
| 241 |
else: |
| 242 |
return utils.formatISODT(job.startTime).encode("ascii") |
| 243 |
|
| 244 |
doPOST = doGET |
| 245 |
JobActions.addStandardAction(StartTimeAction) |
| 246 |
|
| 247 |
|
| 248 |
class ParameterAction(JobAction): |
| 249 |
name = "parameters" |
| 250 |
|
| 251 |
def doGET(self, job, request): |
| 252 |
request.setHeader("content-type", "text/xml") |
| 253 |
return UWS.makeRoot(getParametersElement(job)) |
| 254 |
|
| 255 |
def doPOST(self, job, request): |
| 256 |
if job.phase!=uws.PENDING: |
| 257 |
raise base.ValidationError( |
| 258 |
"Parameters cannot be changed in phase %s"%job.phase, "phase") |
| 259 |
with job.getWritable() as wjob: |
| 260 |
wjob.setParamsFromRawDict(request.strargs) |
| 261 |
raise svcs.SeeOther(job.jobId) |
| 262 |
|
| 263 |
JobActions.addStandardAction(ParameterAction) |
| 264 |
|
| 265 |
class PhaseAction(JobAction): |
| 266 |
name = "phase" |
| 267 |
mime = "text/plain" |
| 268 |
timeout = 10 # this is here for testing |
| 269 |
|
| 270 |
def doPOST(self, job, request): |
| 271 |
newPhase = request.uwsArgs["phase"] |
| 272 |
if newPhase=="RUN": |
| 273 |
job.uws.changeToPhase(job.jobId, uws.QUEUED, timeout=self.timeout) |
| 274 |
elif newPhase=="ABORT": |
| 275 |
job.uws.changeToPhase(job.jobId, uws.ABORTED, timeout=self.timeout) |
| 276 |
else: |
| 277 |
raise base.ValidationError("Bad phase: %s"%newPhase, "phase") |
| 278 |
raise svcs.SeeOther(job.jobId) |
| 279 |
|
| 280 |
def doGET(self, job, request): |
| 281 |
request.setHeader("content-type", "text/plain") |
| 282 |
return job.phase |
| 283 |
JobActions.addStandardAction(PhaseAction) |
| 284 |
|
| 285 |
|
| 286 |
class _SettableAction(JobAction): |
| 287 |
"""Abstract base for ExecDAction and DestructionAction. |
| 288 |
""" |
| 289 |
mime = "text/plain" |
| 290 |
|
| 291 |
def doPOST(self, job, request): |
| 292 |
raw = request.uwsArgs[self.name.lower()] |
| 293 |
if raw is None: # with no parameter, fall back to GET |
| 294 |
return self.doGET(job, request) |
| 295 |
try: |
| 296 |
val = self.deserializeValue(raw) |
| 297 |
except ValueError: |
| 298 |
raise base.ui.logOldExc(uws.UWSError("Invalid %s value: %s."%( |
| 299 |
self.name.upper(), repr(raw)), job.jobId)) |
| 300 |
with job.getWritable() as wjob: |
| 301 |
args = {self.attName: val} |
| 302 |
wjob.change(**args) |
| 303 |
raise svcs.SeeOther(job.jobId) |
| 304 |
|
| 305 |
def doGET(self, job, request): |
| 306 |
request.setHeader("content-type", "text/plain") |
| 307 |
return self.serializeValue(getattr(job, self.attName)) |
| 308 |
|
| 309 |
|
| 310 |
class ExecDAction(_SettableAction): |
| 311 |
name = "executionduration" |
| 312 |
attName = 'executionDuration' |
| 313 |
serializeValue = str |
| 314 |
deserializeValue = float |
| 315 |
JobActions.addStandardAction(ExecDAction) |
| 316 |
|
| 317 |
|
| 318 |
class DestructionAction(_SettableAction): |
| 319 |
name = "destruction" |
| 320 |
attName = "destructionTime" |
| 321 |
serializeValue = staticmethod(utils.formatISODT) |
| 322 |
deserializeValue = staticmethod(utils.parseISODT) |
| 323 |
JobActions.addStandardAction(DestructionAction) |
| 324 |
|
| 325 |
|
| 326 |
class QuoteAction(JobAction): |
| 327 |
name = "quote" |
| 328 |
mime = "text/plain" |
| 329 |
|
| 330 |
def doGET(self, job, request): |
| 331 |
request.setHeader("content-type", "text/plain") |
| 332 |
if job.quote is None: |
| 333 |
quote = "" |
| 334 |
else: |
| 335 |
quote = utils.formatISODT(job.quote) |
| 336 |
return quote |
| 337 |
|
| 338 |
JobActions.addStandardAction(QuoteAction) |
| 339 |
|
| 340 |
|
| 341 |
class OwnerAction(JobAction): |
| 342 |
name = "owner" |
| 343 |
mime = "text/plain" |
| 344 |
|
| 345 |
def doGET(self, job, request): |
| 346 |
request.setHeader("content-type", "text/plain") |
| 347 |
if job.owner is None: |
| 348 |
request.write("NULL") |
| 349 |
else: |
| 350 |
request.write(job.owner) |
| 351 |
return b"" |
| 352 |
|
| 353 |
JobActions.addStandardAction(OwnerAction) |
| 354 |
|
| 355 |
|
| 356 |
def _getResultsElement(job): |
| 357 |
baseURL = job.getURL()+"/results/" |
| 358 |
return UWS.results[[ |
| 359 |
UWS.result(id=res["resultName"], href=baseURL+res["resultName"]) |
| 360 |
for res in job.getResults()]] |
| 361 |
|
| 362 |
|
| 363 |
class ResultsAction(JobAction): |
| 364 |
"""Access result (Extension: and other) files in job directory. |
| 365 |
""" |
| 366 |
name = "results" |
| 367 |
|
| 368 |
def getResource(self, job, request, segments): |
| 369 |
if not segments: |
| 370 |
return JobAction.getResource(self, job, request, segments) |
| 371 |
|
| 372 |
res = None |
| 373 |
# first try a "real" UWS result from the job |
| 374 |
if len(segments)==1: |
| 375 |
try: |
| 376 |
fName, resultType = job.getResult(segments[0]) |
| 377 |
res = static.File(fName, defaultType=str(resultType)) |
| 378 |
res.encoding = None |
| 379 |
except base.NotFoundError: # segments[0] does not name a result |
| 380 |
pass # fall through to other files |
| 381 |
|
| 382 |
if res is None: |
| 383 |
# if that doesn't work, try to return some other file from the |
| 384 |
# job directory. This is so we can deliver uploads. |
| 385 |
filePath = os.path.join(job.getWD(), *segments) |
| 386 |
if not os.path.abspath(filePath).startswith( |
| 387 |
os.path.abspath(job.getWD())): |
| 388 |
raise svcs.ForbiddenURI("Not serving files outside of job directory.") |
| 389 |
|
| 390 |
if not os.path.exists(filePath): |
| 391 |
raise svcs.UnknownURI("File not found") |
| 392 |
|
| 393 |
res = static.File(filePath, defaultType="application/octet-stream") |
| 394 |
|
| 395 |
# now render whatever we have found |
| 396 |
res.render(request) |
| 397 |
return server.NOT_DONE_YET |
| 398 |
|
| 399 |
def doGET(self, job, request): |
| 400 |
return _getResultsElement(job) |
| 401 |
|
| 402 |
JobActions.addStandardAction(ResultsAction) |
| 403 |
|
| 404 |
|
| 405 |
def _serializeTime(element, dt): |
| 406 |
if dt is None: |
| 407 |
return element() |
| 408 |
return element[utils.formatISODT(dt)] |
| 409 |
|
| 410 |
|
| 411 |
class RootAction(JobAction): |
| 412 |
"""Actions for async/jobId. |
| 413 |
""" |
| 414 |
name = "" |
| 415 |
|
| 416 |
def doDELETE(self, job, request): |
| 417 |
"""Implements DELETE on a job resource. |
| 418 |
|
| 419 |
This is the UWS-compliant way to delete a job. |
| 420 |
""" |
| 421 |
job.uws.destroy(job.jobId) |
| 422 |
raise svcs.SeeOther("") |
| 423 |
|
| 424 |
def doPOST(self, wjob, request): |
| 425 |
"""Implements POST on a job resource. |
| 426 |
|
| 427 |
This is a DaCHS extension to UWS in order to let web browsers |
| 428 |
delete jobs by passing action=DELETE. |
| 429 |
""" |
| 430 |
if request.uwsArgs.get("action")=="DELETE": |
| 431 |
self.doDELETE(wjob, request) |
| 432 |
else: |
| 433 |
raise svcs.BadMethod("POST") |
| 434 |
|
| 435 |
def _stopWaiting(self, result, request): |
| 436 |
"""a callback for notifyFinish that will stop our polling loop. |
| 437 |
""" |
| 438 |
request._REMOTE_HUNG_UP = True |
| 439 |
return result |
| 440 |
|
| 441 |
def _delayIfWAIT(self, job, request): |
| 442 |
"""delays if request has UWS 1.1 "slow poll" arguments, returns None |
| 443 |
otherwise. |
| 444 |
|
| 445 |
This is a helper for doGET. |
| 446 |
""" |
| 447 |
# This is the implementation of UWS 1.1 "slow polling". |
| 448 |
# We still do polling internally rather than use postgres' |
| 449 |
# LISTEN/NOTIFY since the overhead seems rather moderate and |
| 450 |
# the added complexity of setting up notifications appeared not |
| 451 |
# proportional to saving it. |
| 452 |
args = request.uwsArgs |
| 453 |
|
| 454 |
if args.get("wait") is None: |
| 455 |
return |
| 456 |
|
| 457 |
waitFor = int(args["wait"]) |
| 458 |
if waitFor==-1: |
| 459 |
waitFor = base.getConfig("async", "maxslowpollwait") |
| 460 |
|
| 461 |
if args.get("phase") is not None and args["phase"]!=job.phase: |
| 462 |
return |
| 463 |
|
| 464 |
if job.phase not in ["PENDING", "QUEUED", "EXECUTING"]: |
| 465 |
return |
| 466 |
|
| 467 |
d = defer.Deferred().addCallback( |
| 468 |
self._recheck, job.uws, job.jobId, waitFor-1, job.phase) |
| 469 |
reactor.callLater(1, d.callback, request) |
| 470 |
request.notifyFinish().addBoth(self._stopWaiting, request) |
| 471 |
return d |
| 472 |
|
| 473 |
def _recheck(self, |
| 474 |
request, workerSystem, jobId, remainingWait, originalPhase): |
| 475 |
"""the callback for doing slow polls. |
| 476 |
""" |
| 477 |
if hasattr(request, "_REMOTE_HUNG_UP"): |
| 478 |
# the other side has given up on us, all is done; return |
| 479 |
# NOT_DONE_YET to keep twisted from finishing the request again. |
| 480 |
return server.NOT_DONE_YET |
| 481 |
|
| 482 |
job = workerSystem.getJob(jobId) |
| 483 |
if originalPhase!=job.phase or remainingWait<=0: |
| 484 |
request.uwsArgs.pop("wait", None) |
| 485 |
request.uwsArgs.pop("phase", None) |
| 486 |
return self.doGET(job, request) |
| 487 |
|
| 488 |
d = defer.Deferred().addCallback( |
| 489 |
self._recheck, workerSystem, jobId, remainingWait-1, originalPhase) |
| 490 |
reactor.callLater(1, d.callback, request) |
| 491 |
return d |
| 492 |
|
| 493 |
def doGET(self, job, request): |
| 494 |
"""Implements GET on a job resource: return the current job metadata. |
| 495 |
""" |
| 496 |
delay = self._delayIfWAIT(job, request) |
| 497 |
if delay: |
| 498 |
return delay |
| 499 |
request.setHeader("content-type", "text/xml") |
| 500 |
|
| 501 |
tree = UWS.makeRoot(UWS.job[ |
| 502 |
UWS.jobId[job.jobId], |
| 503 |
UWS.runId[job.runId], |
| 504 |
UWS.ownerId[job.owner], |
| 505 |
UWS.phase[job.phase], |
| 506 |
UWS.quote[utils.formatISODT(job.quote)], |
| 507 |
UWS.creationTime[utils.formatISODT(job.creationTime)], |
| 508 |
_serializeTime(UWS.startTime, job.startTime), |
| 509 |
_serializeTime(UWS.endTime, job.endTime), |
| 510 |
UWS.executionDuration[str(job.executionDuration)], |
| 511 |
UWS.destruction[utils.formatISODT(job.destructionTime)], |
| 512 |
getParametersElement(job), |
| 513 |
_getResultsElement(job), |
| 514 |
getErrorSummary(job)]) |
| 515 |
return stanxml.xmlrender(tree, job.uws.jobdocPreamble) |
| 516 |
|
| 517 |
|
| 518 |
JobActions.addStandardAction(RootAction) |
| 519 |
|
| 520 |
|
| 521 |
def doJobAction(workerSystem, request, segments): |
| 522 |
"""handles the async UI of UWS. |
| 523 |
|
| 524 |
Depending on method and segments, it will return various XML strings |
| 525 |
and may cause certain actions. |
| 526 |
|
| 527 |
Segments must be a tuple with at least one element, the job id. |
| 528 |
""" |
| 529 |
jobId, segments = segments[0], segments[1:] |
| 530 |
if not segments: |
| 531 |
action = "" |
| 532 |
else: |
| 533 |
action, segments = segments[0], segments[1:] |
| 534 |
return workerSystem.jobActions.dispatch(action, |
| 535 |
workerSystem.getJob(jobId), request, segments) |