| 1 |
""" |
| 2 |
Renderers and helpers for asynchronous services. |
| 3 |
|
| 4 |
For TAP (which was the first prototype of these), there's a separate |
| 5 |
module using some of this; on the long run, it should probably be |
| 6 |
integrated here. |
| 7 |
""" |
| 8 |
|
| 9 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 10 |
#c |
| 11 |
#c This program is free software, covered by the GNU GPL. See the |
| 12 |
#c COPYING file in the source distribution. |
| 13 |
|
| 14 |
|
| 15 |
import functools |
| 16 |
|
| 17 |
from twisted.internet import defer |
| 18 |
from twisted.python import failure |
| 19 |
from twisted.web import resource |
| 20 |
from twisted.web import server |
| 21 |
|
| 22 |
from gavo import base |
| 23 |
from gavo import svcs |
| 24 |
from gavo import utils |
| 25 |
from gavo.protocols import dali |
| 26 |
from gavo.protocols import dlasync |
| 27 |
from gavo.protocols import uws |
| 28 |
from gavo.protocols import uwsactions |
| 29 |
from gavo.web import grend |
| 30 |
|
| 31 |
|
| 32 |
def redirectUWS(baseURL, location): |
| 33 |
"""raises an UWS-compatible (303) redirection. |
| 34 |
|
| 35 |
baseURL and location and then just raise svc.SeeOther |
| 36 |
The locations used here are relative to baseURL, which essentially |
| 37 |
has to be the the full absolute URL of the endpoint (i.e., |
| 38 |
service/renderer). As a special service, for TAP async is being |
| 39 |
added as long as the renderer isn't fixed to not do dispatching. |
| 40 |
|
| 41 |
This essentially just mogrifies SeeOther exceptions rendered elsewhere. |
| 42 |
It should therefore go at some point (probably when TAP uses the async |
| 43 |
renderer). |
| 44 |
""" |
| 45 |
# TODO: Temporary hack as long as TAP isn't modernized to use |
| 46 |
# an async renderer: fix the redirect to TAP's async endpoint if |
| 47 |
# baseURL is the TAP renderer: |
| 48 |
if baseURL.endswith("tap"): |
| 49 |
baseURL = baseURL+"/async" |
| 50 |
|
| 51 |
if location: |
| 52 |
if location.startswith("http://") or location.startswith("https://"): |
| 53 |
location = str(location) |
| 54 |
else: |
| 55 |
location = str("%s/%s"%(baseURL, location)) |
| 56 |
else: |
| 57 |
location = str(baseURL) |
| 58 |
|
| 59 |
raise svcs.SeeOther(location) |
| 60 |
|
| 61 |
|
| 62 |
class UWSResource(resource.Resource): |
| 63 |
"""a resource dealing with a UWS. |
| 64 |
|
| 65 |
It is constructed with a worker system, a concrete renderer, and |
| 66 |
the service that executes requests. |
| 67 |
|
| 68 |
It also delivers errors in UWS (well, TAP, actually) style. |
| 69 |
""" |
| 70 |
def __init__(self, workerSystem, renderer, service): |
| 71 |
self.workerSystem, self.service = workerSystem, service |
| 72 |
self.renderer = renderer |
| 73 |
resource.Resource.__init__(self) |
| 74 |
|
| 75 |
def _deliverError(self, flr, request, httpStatus=200): |
| 76 |
# auth requests and redirects handled by normal dc methods. |
| 77 |
if isinstance(flr.value, (svcs.Authenticate, svcs.SeeOther)): |
| 78 |
return svcs.renderDCErrorPage(flr, request) |
| 79 |
|
| 80 |
else: |
| 81 |
if isinstance(flr.value, uws.JobNotFound): |
| 82 |
httpStatus = 404 |
| 83 |
else: |
| 84 |
base.ui.notifyFailure(flr) |
| 85 |
return dali.serveDALIError(request, flr.value, httpStatus=httpStatus) |
| 86 |
|
| 87 |
def render(self, request): |
| 88 |
try: |
| 89 |
return resource.Resource.render(self, request) |
| 90 |
except Exception as ex: |
| 91 |
return self._deliverError(failure.Failure(ex), request, httpStatus=400) |
| 92 |
|
| 93 |
|
| 94 |
class JoblistResource(UWSResource): |
| 95 |
"""The web resource corresponding to async root. |
| 96 |
|
| 97 |
GET yields a job list, POST creates a job. |
| 98 |
|
| 99 |
There's an extra hack not in UWS: if get with something like |
| 100 |
dachs_authenticate=anything and haven't passed a user, this will ask |
| 101 |
for credentials. |
| 102 |
""" |
| 103 |
@functools.lru_cache(1) |
| 104 |
def getJoblistInputTD(self): |
| 105 |
return base.parseFromString(svcs.InputTD, |
| 106 |
""" |
| 107 |
<inputTable> |
| 108 |
<inputKey name="PHASE" type="text" multiplicity="single" |
| 109 |
description="Restrict result to jobs in this phase"> |
| 110 |
<values> |
| 111 |
<option>PENDING</option> |
| 112 |
<option>QUEUED</option> |
| 113 |
<option>EXECUTING</option> |
| 114 |
<option>COMPLETED</option> |
| 115 |
<option>ERROR</option> |
| 116 |
<option>ABORTED</option> |
| 117 |
<option>UNKNOWN</option> |
| 118 |
<option>HELD</option> |
| 119 |
<option>SUSPENDED</option> |
| 120 |
<option>ARCHIVED</option> |
| 121 |
</values> |
| 122 |
</inputKey> |
| 123 |
<inputKey name="AFTER" type="timestamp" multiplicity="single" |
| 124 |
description="Restrict result to jobs created |
| 125 |
after this point in time"/> |
| 126 |
<inputKey name="LAST" type="integer" multiplicity="single" |
| 127 |
description="Restrict output to this many records, and choose the |
| 128 |
most recent ones"/> |
| 129 |
</inputTable>""") |
| 130 |
|
| 131 |
def render_GET(self, request): |
| 132 |
if "dachs_authenticate" in request.strargs and not request.getUser(): |
| 133 |
raise svcs.Authenticate() |
| 134 |
|
| 135 |
request.setHeader("content-type", "text/xml") |
| 136 |
|
| 137 |
args = svcs.CoreArgs.fromRawArgs( |
| 138 |
self.getJoblistInputTD(), |
| 139 |
request.strargs).args |
| 140 |
|
| 141 |
res = uwsactions.getJobList(self.workerSystem, |
| 142 |
request.getAuthUser() or None, |
| 143 |
phase=args["PHASE"], |
| 144 |
last=args["LAST"], |
| 145 |
after=args["AFTER"]) |
| 146 |
return res |
| 147 |
|
| 148 |
def render_POST(self, request): |
| 149 |
jobId = self.workerSystem.getNewIdFromRequest(request) |
| 150 |
redirectUWS(self.service.getURL(self.renderer), str(jobId)) |
| 151 |
|
| 152 |
def _deliverResult(self, res, request): |
| 153 |
request.setHeader("content-type", "text/xml") |
| 154 |
return res |
| 155 |
|
| 156 |
|
| 157 |
class JobResource(UWSResource): |
| 158 |
"""The web resource corresponding to async requests for jobs. |
| 159 |
|
| 160 |
This currently uses a custom hack for resource resolution and method |
| 161 |
dispatch. Let's move it to using twisted resources one day. |
| 162 |
""" |
| 163 |
def __init__(self, workerSystem, renderer, service, segments): |
| 164 |
self.service, self.segments = service, segments |
| 165 |
self.workerSystem, self.renderer = workerSystem, renderer |
| 166 |
|
| 167 |
def render(self, request): |
| 168 |
defer.maybeDeferred( |
| 169 |
uwsactions.doJobAction, |
| 170 |
self.workerSystem, request, self.segments |
| 171 |
).addCallback(self._deliverResult, request |
| 172 |
).addErrback(self._redirectAsNecessary, request |
| 173 |
).addErrback(self._deliverError, request) |
| 174 |
return server.NOT_DONE_YET |
| 175 |
|
| 176 |
def _redirectAsNecessary(self, flr, request): |
| 177 |
flr.trap(svcs.SeeOther) |
| 178 |
redirectUWS(self.service.getURL(self.renderer), |
| 179 |
flr.value.rawDest) |
| 180 |
|
| 181 |
def _deliverResult(self, result, request): |
| 182 |
if result is server.NOT_DONE_YET: |
| 183 |
# the job action is rendering itself -- this is where we'd like |
| 184 |
# to go for non-XML replies. |
| 185 |
return result |
| 186 |
|
| 187 |
elif isinstance(result, resource.Resource): |
| 188 |
# nevow-style returned resource -- we'd like to get rid of that |
| 189 |
base.ui.notifyWarning("UWS job resource returned a resource rather than" |
| 190 |
" rendering itself. We'd like to stop this.") |
| 191 |
return result.render(request) |
| 192 |
|
| 193 |
else: |
| 194 |
# convenience function: result must be a stan tree we can just |
| 195 |
# render. the content-type is set by uwsaction._JobActions.dispatch |
| 196 |
request.write(utils.xmlrender(result)) |
| 197 |
request.finish() |
| 198 |
|
| 199 |
|
| 200 |
def getAsyncResource( |
| 201 |
request, workerSystem, renderer, service, firstSegment): |
| 202 |
"""returns a UWS-compliant resource for request. |
| 203 |
|
| 204 |
Note: This expects that the renderer has already called uws.prepareRequest. |
| 205 |
""" |
| 206 |
segments = request.popSegments(firstSegment) |
| 207 |
if segments==[""]: |
| 208 |
# redirect async/ to async so our style sheets work |
| 209 |
raise svcs.SeeOther(request.uri[:-1]) |
| 210 |
|
| 211 |
elif not segments: |
| 212 |
return JoblistResource(workerSystem, renderer, service) |
| 213 |
else: |
| 214 |
return JobResource(workerSystem, renderer, service, segments) |
| 215 |
|
| 216 |
|
| 217 |
class AsyncRendererBase(grend.ServiceBasedPage): |
| 218 |
"""An abstract renderer for things running in a UWS. |
| 219 |
|
| 220 |
To make these concrete, they need a name and a workerSystem attribute. |
| 221 |
""" |
| 222 |
parameterStyle = "pql" |
| 223 |
|
| 224 |
def render(self, request): |
| 225 |
# We don't do anything ourselves -- everything has to go through |
| 226 |
# getAsyncResource and hence getChild |
| 227 |
try: |
| 228 |
return self.getChild(None, request).render(request) |
| 229 |
except Exception as ex: |
| 230 |
base.ui.notifyError(f"UWS root render failed: {ex}") |
| 231 |
|
| 232 |
def getChild(self, name, request): |
| 233 |
from gavo.web import asyncrender |
| 234 |
|
| 235 |
if request.prepath[-1]==b"": |
| 236 |
# trailing slash: redirect away so our XSLT works properly |
| 237 |
raise svcs.SeeOther(b"/".join(request.prepath[:-1])) |
| 238 |
|
| 239 |
try: |
| 240 |
uws.prepareRequest(request, self.service) |
| 241 |
|
| 242 |
return asyncrender.getAsyncResource(request, |
| 243 |
self.workerSystem, |
| 244 |
self.name, |
| 245 |
self.service, |
| 246 |
name) |
| 247 |
except Exception as ex: |
| 248 |
base.ui.notifyError(f"UWS child construction failed: {ex}") |
| 249 |
return dali.DALIErrorResource(ex) |
| 250 |
|
| 251 |
|
| 252 |
class DatalinkAsyncRenderer(AsyncRendererBase): |
| 253 |
"""A renderer for asynchronous datalink. |
| 254 |
""" |
| 255 |
# we need a special case here because this needs to put the |
| 256 |
# id of the calling service into strargs. Note that this |
| 257 |
# cannot do any uploads in this form, as we are deferring all |
| 258 |
# inspection of the arguments to when the job actually runs. |
| 259 |
name = "dlasync" |
| 260 |
workerSystem = dlasync.DL_WORKER |
| 261 |
|
| 262 |
def render(self, request): |
| 263 |
# This sort of parameter re-packing quite certainly isn't what |
| 264 |
# we should be doing on the long run. Let's see what we come |
| 265 |
# up with the next time we revisit this. |
| 266 |
request._strargs = { |
| 267 |
"dlargs": request.strargs, |
| 268 |
"serviceid": [self.service.getFullId()]} |
| 269 |
return AsyncRendererBase.render(self, request) |
| 270 |
|
| 271 |
|
| 272 |
class DALIAsyncRenderer(AsyncRendererBase): |
| 273 |
"""A renderer speaking UWS. |
| 274 |
|
| 275 |
This is for asynchronous execution of larger jobs. This is what is executed |
| 276 |
by the async renderer. It requests the worker system required from the |
| 277 |
service, which in turn obtains it from the core; these must hence |
| 278 |
cooperate with this to allow async operation. |
| 279 |
|
| 280 |
See `Custom UWSes`_ for how to use this with your own cores. |
| 281 |
""" |
| 282 |
name = "async" |
| 283 |
aliases = frozenset(["uws.xml"]) |
| 284 |
|
| 285 |
@property |
| 286 |
def workerSystem(self): |
| 287 |
return self.service.getUWS() |