| 1 |
""" |
| 2 |
A UWS-based interface to datalink. |
| 3 |
|
| 4 |
TODO: There's quite a bit of parallel between this and useruws. This |
| 5 |
should probably be reformulated along the lines of useruws. |
| 6 |
""" |
| 7 |
|
| 8 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 9 |
#c |
| 10 |
#c This program is free software, covered by the GNU GPL. See the |
| 11 |
#c COPYING file in the source distribution. |
| 12 |
|
| 13 |
|
| 14 |
import functools |
| 15 |
import datetime |
| 16 |
|
| 17 |
from twisted.web import server |
| 18 |
|
| 19 |
from gavo import base |
| 20 |
from gavo import svcs |
| 21 |
from gavo import rscdesc #noflake: cache registration |
| 22 |
from gavo.protocols import products |
| 23 |
from gavo.protocols import uws |
| 24 |
from gavo.protocols import uwsactions |
| 25 |
|
| 26 |
# TODO: We're not supposed to import from helpers in main code. Fix |
| 27 |
# this. |
| 28 |
from gavo.helpers import testtricks |
| 29 |
|
| 30 |
|
| 31 |
class DLTransitions(uws.ProcessBasedUWSTransitions): |
| 32 |
"""The transition function for datalink jobs. |
| 33 |
""" |
| 34 |
def __init__(self): |
| 35 |
uws.ProcessBasedUWSTransitions.__init__(self, "DL") |
| 36 |
|
| 37 |
def queueJob(self, newState, wjob, ignored): |
| 38 |
uws.ProcessBasedUWSTransitions.queueJob(self, newState, wjob, ignored) |
| 39 |
return self.startJob(uws.EXECUTING, wjob, ignored) |
| 40 |
|
| 41 |
def getCommandLine(self, wjob): |
| 42 |
return "gavo", ["gavo", "dlrun", "--", str(wjob.jobId)] |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
class DLJob(uws.UWSJobWithWD): |
| 47 |
"""a UWS job performing some datalink data preparation. |
| 48 |
|
| 49 |
In addition to UWS parameters, it has |
| 50 |
|
| 51 |
* serviceid -- the fully qualified id of the service that will process |
| 52 |
the request |
| 53 |
* datalinkargs -- the parameters (in request.args form) of the |
| 54 |
datalink request. |
| 55 |
""" |
| 56 |
_jobsTDId = "//datalink#datalinkjobs" |
| 57 |
_transitions = DLTransitions() |
| 58 |
|
| 59 |
|
| 60 |
class DLUWS(uws.UWS): |
| 61 |
"""the worker system for datalink jobs. |
| 62 |
""" |
| 63 |
joblistPreamble = ("<?xml-stylesheet href='/static" |
| 64 |
"/xsl/dlasync-joblist-to-html.xsl' type='text/xsl'?>") |
| 65 |
jobdocPreamble = ("<?xml-stylesheet href='/static/xsl/" |
| 66 |
"dlasync-job-to-html.xsl' type='text/xsl'?>") |
| 67 |
|
| 68 |
_baseURLCache = None |
| 69 |
|
| 70 |
def __init__(self): |
| 71 |
uws.UWS.__init__(self, DLJob, uwsactions.JobActions()) |
| 72 |
|
| 73 |
@property |
| 74 |
def baseURL(self): |
| 75 |
return base.makeAbsoluteURL("datalinkuws") |
| 76 |
|
| 77 |
@functools.cached_property |
| 78 |
def parameterGrammar(self): |
| 79 |
return base.parseFromString(svcs.ContextGrammar, |
| 80 |
"""<contextGrammar> |
| 81 |
<inputKey name="dlargs" type="raw" |
| 82 |
description="All datalink parameters. These will only |
| 83 |
be validated on execution. See the datalink descriptor |
| 84 |
for the actual parameters usable here. You cannot pass |
| 85 |
this in." |
| 86 |
multiplicity="forced-single"/> |
| 87 |
<inputKey name="serviceid" type="text" |
| 88 |
description="The id of the service processing this. You |
| 89 |
cannot pass this in; it is overridden by the renderer." |
| 90 |
multiplicity="forced-single"/> |
| 91 |
</contextGrammar>""") |
| 92 |
|
| 93 |
def getURLForId(self, jobId): |
| 94 |
"""returns a fully qualified URL for the job with jobId. |
| 95 |
""" |
| 96 |
return "%s/%s"%(self.baseURL, jobId) |
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
DL_WORKER = DLUWS() |
| 101 |
|
| 102 |
####################### twisted.web simulation |
| 103 |
# This is so we can handle t.w resources coming back from datalink. |
| 104 |
# Factor this out? This is essentially stolen from trialhelpers, |
| 105 |
# and we might just put that somewhere where it's useful. |
| 106 |
|
| 107 |
import warnings |
| 108 |
from twisted.internet import defer |
| 109 |
from twisted.internet import reactor |
| 110 |
|
| 111 |
|
| 112 |
def _requestDone(result, request): |
| 113 |
"""essentially calls render on result and stops the reactor. |
| 114 |
|
| 115 |
This is a helper for our t.w simulation. |
| 116 |
""" |
| 117 |
if isinstance(result, str): |
| 118 |
if result: |
| 119 |
request.write(result) |
| 120 |
else: |
| 121 |
warnings.warn("Unsupported async datalink render result: %s"%repr(result)) |
| 122 |
request.deferred.callback(request.accumulator) |
| 123 |
reactor.stop() |
| 124 |
return request.accumulator, request |
| 125 |
|
| 126 |
|
| 127 |
class WritingFakeRequest(testtricks.FakeRequest): |
| 128 |
"""a simulator for actual t.w requests. |
| 129 |
|
| 130 |
We want this here as we're rendering to a UWS result file |
| 131 |
with the same code that renders to web requests. |
| 132 |
|
| 133 |
One could probably go a lot simpler than testtricks.FakeRequest, |
| 134 |
but since the code is there anyway, it probably doesn't hurt |
| 135 |
to use it in case we want to do fancier things in the future. |
| 136 |
|
| 137 |
The one thing I have to change vs. testtricks is that we want |
| 138 |
to write to files. |
| 139 |
""" |
| 140 |
def __init__(self, destFile): |
| 141 |
self.destFile = destFile |
| 142 |
testtricks.FakeRequest.__init__(self, "") |
| 143 |
|
| 144 |
def write(self, stuff): |
| 145 |
self.destFile.write(stuff) |
| 146 |
|
| 147 |
def finish(self): |
| 148 |
self.deferred.callback(None) |
| 149 |
self.destFile.close() |
| 150 |
reactor.stop() |
| 151 |
|
| 152 |
|
| 153 |
def writeResultTo(page, destFile): |
| 154 |
"""arranges for the result of rendering the twisted.web resource |
| 155 |
to be written to destFile. |
| 156 |
|
| 157 |
This uses a very simple simulation of t.w rendering, so a few |
| 158 |
tricks are possible. Also, it actually runs a reactor to do its magic. |
| 159 |
|
| 160 |
Do not run this in a running DaCHS server; it has its own reactor |
| 161 |
running. This is only for dachs dlrun code. |
| 162 |
|
| 163 |
TODO: There's proabably code for this in t.w. |
| 164 |
""" |
| 165 |
def _(func, req): |
| 166 |
try: |
| 167 |
res = func(req) |
| 168 |
except Exception: |
| 169 |
request.finish() |
| 170 |
raise |
| 171 |
|
| 172 |
if res==server.NOT_DONE_YET: |
| 173 |
# resource will finish the request itself later |
| 174 |
return |
| 175 |
|
| 176 |
try: |
| 177 |
if res: |
| 178 |
req.write(res) |
| 179 |
finally: |
| 180 |
req.finish() |
| 181 |
|
| 182 |
request = WritingFakeRequest(destFile) |
| 183 |
reactor.callWhenRunning(_, page.render, request) |
| 184 |
reactor.run() |
| 185 |
return request |
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
####################### CLI |
| 190 |
|
| 191 |
def parseCommandLine(): |
| 192 |
import argparse |
| 193 |
parser = argparse.ArgumentParser(description="Run an asynchronous datalink" |
| 194 |
" job (used internally)") |
| 195 |
parser.add_argument("jobId", type=str, help="UWS id of the job to run") |
| 196 |
return parser.parse_args() |
| 197 |
|
| 198 |
|
| 199 |
def main(): |
| 200 |
args = parseCommandLine() |
| 201 |
jobId = args.jobId |
| 202 |
try: |
| 203 |
job = DL_WORKER.getJob(jobId) |
| 204 |
with job.getWritable() as wjob: |
| 205 |
wjob.change(phase=uws.EXECUTING, startTime=datetime.datetime.utcnow()) |
| 206 |
|
| 207 |
args = job.parameters["dlargs"] |
| 208 |
service = base.resolveCrossId(job.parameters["serviceid"]) |
| 209 |
data = service.run("dlget", args, svcs.emptyQueryMeta) |
| 210 |
|
| 211 |
# Unfortunately, datalink cores can in principle return all kinds |
| 212 |
# of messy things that may not even be representable in plain files |
| 213 |
# (e.g., t.w resources returning redirects). We hence only |
| 214 |
# handle (mime, payload) and (certain) Product instances here |
| 215 |
# and error out otherwise. |
| 216 |
if isinstance(data, tuple): |
| 217 |
mime, payload = data |
| 218 |
with job.openResult(mime, "result") as destF: |
| 219 |
destF.write(payload) |
| 220 |
|
| 221 |
elif isinstance(data, products.ProductBase): |
| 222 |
# We could run render and grab the content-type from there |
| 223 |
# (which probably would be better all around). For now, don't |
| 224 |
# care: |
| 225 |
with job.openResult("application/octet-stream", "result") as destF: |
| 226 |
for chunk in data.iterData(): |
| 227 |
destF.write(chunk) |
| 228 |
|
| 229 |
elif hasattr(data, "render"): |
| 230 |
# these are t.w. resources. Let's run a reactor so these properly |
| 231 |
# work. |
| 232 |
with job.openResult(type, "result") as destF: |
| 233 |
req = writeResultTo(data, destF) |
| 234 |
job.fixTypeForResultName("result", |
| 235 |
req.responseHeaders.getRawHeaders("content-type")[0]) |
| 236 |
|
| 237 |
else: |
| 238 |
raise NotImplementedError("Cannot handle a service %s result yet."% |
| 239 |
repr(data)) |
| 240 |
|
| 241 |
with job.getWritable() as wjob: |
| 242 |
wjob.change(phase=uws.COMPLETED) |
| 243 |
|
| 244 |
except SystemExit: |
| 245 |
pass |
| 246 |
except uws.JobNotFound: |
| 247 |
base.ui.notifyInfo("Giving up non-existing datalink job %s."%jobId) |
| 248 |
except Exception as ex: |
| 249 |
base.ui.notifyError("Datalink runner %s major failure"%jobId) |
| 250 |
# try to push job into the error state -- this may well fail given |
| 251 |
# that we're quite hosed, but it's worth the try |
| 252 |
DL_WORKER.changeToPhase(jobId, uws.ERROR, ex) |
| 253 |
raise |
| 254 |
|
| 255 |
|
| 256 |
if __name__=="__main__": # pagma: no cover |
| 257 |
# silly test code, not normally reached |
| 258 |
from twisted.web import resource |
| 259 |
import os |
| 260 |
class _Foo(resource.Resource): |
| 261 |
def __init__(self, stuff): |
| 262 |
self.stuff = stuff |
| 263 |
|
| 264 |
def render(self, request): |
| 265 |
if self.stuff=="booga": |
| 266 |
return b"abc" |
| 267 |
else: |
| 268 |
return defer.maybeDeferred(_Foo, "booga").addBoth(self.cleanup) |
| 269 |
|
| 270 |
def cleanup(self, res): |
| 271 |
print("cleaning up") |
| 272 |
return res |
| 273 |
|
| 274 |
with open("bla", "w") as f: |
| 275 |
writeResultTo(_Foo("ork"), f) |
| 276 |
with open("bla") as f: |
| 277 |
print(f.read()) |
| 278 |
os.unlink("bla") |