Debian Codegraph @

gavo/protocols/useruws.py

raw
1 """
2 Support for UWSes defined in user RDs.
3
4 To understand this, start at makeUWSForService.
5 """
6
7 #c Copyright 2008-2025, the GAVO project <[email protected]>
8 #c
9 #c This program is free software, covered by the GNU GPL. See the
10 #c COPYING file in the source distribution.
11
12
13 import datetime
14 import weakref
15
16 from gavo import base
17 from gavo import formats
18 from gavo import rsc
19 from gavo import rscdesc #noflake: for registration
20 from gavo import svcs
21 from gavo.protocols import uws
22 from gavo.protocols import uwsactions
23
24
25 class UserUWSTransitions(uws.ProcessBasedUWSTransitions):
26 """The transition function for user-defined UWSes.
27 """
28 def __init__(self):
29 uws.ProcessBasedUWSTransitions.__init__(self, "User")
30
31 def queueJob(self, newState, wjob, ignored):
32 """puts a job on the queue.
33 """
34 uws.ProcessBasedUWSTransitions.queueJob(self, newState, wjob, ignored)
35 wjob.uws.scheduleProcessQueueCheck()
36
37 def getCommandLine(self, wjob):
38 args = ["dachs", "uwsrun", "--", str(wjob.jobId)]
39 if base.DEBUG:
40 args[1:1] = ["--debug", "--traceback"]
41 return "gavo", args
42
43
44 class UserUWSJobBase(uws.UWSJobWithWD):
45 """The base class for the service-specific user UWS jobs.
46
47 (i.e., the things that the UserUWSJobFactory spits out)
48 """
49 _transitions = UserUWSTransitions()
50 _jobsTDId = "//uws#userjobs"
51
52
53 def makeUserUWSJobClass(service):
54 """returns a class object for representing UWS jobs processing requests
55 for service
56 """
57 class UserUWSJob(UserUWSJobBase):
58 pass
59
60 UserUWSJob._default_jobClass = classmethod(
61 lambda _, v=service.getFullId(): v)
62
63 return UserUWSJob
64
65
66 class UserUWS(uws.UWSWithQueueing):
67 """A UWS for "user jobs", i.e., generic things an a core.
68
69 These dynamically create job classes based on the processing core's
70 parameters. To make this happen, we'll need to override some of the
71 common UWS functions.
72
73 Note: For async operation (without a custom UWS), you can only have
74 uploads in the upload parameter.
75 """
76 joblistPreamble = ("<?xml-stylesheet href='/static"
77 "/xsl/useruws-joblist-to-html.xsl' type='text/xsl'?>")
78 jobdocPreamble = ("<?xml-stylesheet href='/static/xsl/"
79 "useruws-job-to-html.xsl' type='text/xsl'?>")
80
81 def __init__(self, service, jobActions, parameterGrammar):
82 self.runcountGoal = base.getConfig("async", "maxUserUWSRunningDefault")
83 self.service = weakref.proxy(service)
84 uws.UWSWithQueueing.__init__(self,
85 makeUserUWSJobClass(service), jobActions)
86 self.parameterGrammar = parameterGrammar
87
88 def getURLForId(self, jobId):
89 return self.service.getURL("uws.xml")+"/"+jobId
90
91 def _getJob(self, jobId, conn, writable=False):
92 """returns the named job as uws.UWS._getJob.
93
94 However, in a user UWS, there can be jobs from multiple services.
95 It would be nonsense to load another UWS's job's parameters into our
96 job class. To prevent this, we redirect if we find the new job's
97 class isn't ours. On the web interface, that should do the trick.
98 Everywhere else, this may not be entirely clear but still prevent
99 major confusion.
100
101 This is repeating code from uws.UWS._getJob; some refactoring at
102 some point would be nice.
103 """
104 statementId = 'getById'
105 if writable:
106 statementId = 'getByIdEx'
107 res = self.runCanned(statementId, {"jobId": jobId}, conn)
108 if len(res)!=1:
109 raise uws.JobNotFound(jobId)
110
111 if res[0]["jobClass"]!=self.service.getFullId():
112 raise svcs.WebRedirect(
113 base.resolveCrossId(res[0]["jobClass"]).getUWS().getURLForId(jobId))
114
115 return self.jobClass(res[0], self, writable)
116
117 def getIdsAndPhases(self, *args, **kwargs):
118 # for user UWSes, we only want jobs from our service in the job
119 # list resource. We insert extra conditions to the basic queries.
120 # getById and getAllIds don't change, though, as they're used internally
121 # and could influence, e.g., queueing and such.
122 return uws.UWSWithQueueing.getIdsAndPhases(self, *args,
123 initFragments=["jobClass=%(jobClass)s"],
124 initPars={"jobClass": self.service.getFullId()},
125 **kwargs)
126
127
128 def makeUWSForService(service):
129 """returns a UserUWS instance tailored to service.
130
131 All these share a jobs table, but the all have different job
132 classes with the parameters custom-made for the service's core.
133
134 A drawback of this is that each UWS created in this way runs the
135 job table purger again. That shouldn't be a problem per se but
136 may become cumbersome at some point. We can always introduce a
137 class Attribute on UserUWS to keep additional UWSes from starting
138 cron jobs of their own.
139 """
140 return UserUWS(
141 service,
142 uwsactions.JobActions(),
143 base.makeStruct(svcs.ContextGrammar, inputTD=service.core.inputTable))
144
145
146 ####################### CLI
147
148 def parseCommandLine():
149 import argparse
150 parser = argparse.ArgumentParser(description="Run an asynchronous"
151 " generic job (used internally)")
152 parser.add_argument("jobId", type=str, help="UWS id of the job to run")
153 return parser.parse_args()
154
155
156 def main():
157 args = parseCommandLine()
158 jobId = args.jobId
159 with base.getTableConn() as conn:
160 svcId = list(
161 conn.query("SELECT jobclass FROM uws.userjobs WHERE jobId=%(jobId)s",
162 {"jobId": jobId}))[0][0]
163 service = base.resolveCrossId(svcId)
164
165 # we're the only ones running, so we're safe using this.
166 queryMeta = svcs.emptyQueryMeta
167
168 try:
169 job = service.getUWS().getJob(jobId)
170 with job.getWritable() as wjob:
171 wjob.change(phase=uws.EXECUTING, startTime=datetime.datetime.utcnow())
172
173 service = base.resolveCrossId(job.jobClass)
174 inputTable = svcs.CoreArgs(service.core.inputTable,
175 job.parameters, job.parameters)
176 inputTable.job = job
177
178 data = service._runWithInputTable(
179 service.core, inputTable, queryMeta)
180
181 # Our cores either return a table, a pair of mime and data,
182 # or None (in which case they added the results themselves)
183 if isinstance(data, tuple):
184 mime, payload = data
185 with job.openResult(mime, "result") as destF:
186 destF.write(payload)
187
188 elif isinstance(data, rsc.Data):
189 destFmt = inputTable.getParam("responseformat"
190 ) or "application/x-votable+xml"
191 with job.openResult(destFmt, "result") as destF:
192 formats.formatData(destFmt, data, destF, False)
193
194 elif data is None:
195 pass
196
197 else:
198 raise NotImplementedError("Cannot handle a service %s result yet."%
199 repr(data))
200
201 with job.getWritable() as wjob:
202 wjob.change(phase=uws.COMPLETED)
203
204 except SystemExit:
205 pass
206 except uws.JobNotFound:
207 base.ui.notifyInfo("Giving up non-existing UWS job %s."%jobId)
208 except Exception as ex:
209 base.ui.notifyError("UWS runner %s major failure"%jobId)
210 # try to push job into the error state -- this may well fail given
211 # that we're quite hosed, but it's worth the try
212 service.getUWS().changeToPhase(jobId, uws.ERROR, ex)
213 raise