Debian Codegraph @

gavo/svcs/streaming.py

raw
1 """
2 Streaming out large computed things using twisted and threads.
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 time
12 import threading
13
14 from twisted.internet import reactor
15 from twisted.internet.interfaces import IPushProducer
16 from twisted.python import threadable
17 from twisted.web import server
18
19 from zope.interface import implementer
20
21 from gavo import base
22 from gavo import utils
23 from gavo.formats import votablewrite
24
25
26 class StopWriting(IOError):
27 """clients can raise this when they want the stream to abort.
28 """
29
30
31 @implementer(IPushProducer)
32 class DataStreamer(threading.Thread):
33 """is a twisted-enabled Thread to stream out large files produced
34 on the fly.
35
36 It is basically a push producer. To use it, construct it with
37 a data source and a twisted request (or any IFinishableConsumer)
38 If in a twisted resource, you should arrange a deferred and return
39 NOT_DONE_YET; really, just use streamOut below.
40
41 The data source simply is a function writeStreamTo taking one
42 argument, which is file-like (i.e., use its write method to deliver
43 data). There's no need to close anything, just let your function
44 return.
45
46 writeStream will be run in a thread to avoid blocking the reactor.
47 """
48 # we shouldn't really do this kind of thing, but writing the stuff that
49 # we want to produce asynchronously is typically still a bigger pain.
50
51 def __init__(self, writeStreamTo, consumer, queryMeta=None):
52 threading.Thread.__init__(self)
53 self.writeStreamTo, self.consumer = writeStreamTo, consumer
54 self.queryMeta = queryMeta
55 self.paused, self.exceptionToRaise = False, None
56 self.consumer.registerProducer(self, True)
57 self.connectionLive = True
58 self.consumer.notifyFinish().addErrback(self._abortProducing)
59 self.setDaemon(True) # kill transfers on server restart
60 self.buffer = utils.StreamBuffer()
61
62 def _abortProducing(self, res):
63 # this errback is called when the request is finishing after an error. The
64 # request, here, still is there as self.consumer; this code runs in the
65 # main thread.
66 self.connectionLive = False
67 if getattr(self.consumer, "channel", None):
68 self.consumer.unregisterProducer()
69 self.exceptionToRaise = StopWriting("Client has hung up")
70
71 def resumeProducing(self):
72 self.paused = False
73
74 def pauseProducing(self):
75 self.paused = True
76
77 def stopProducing(self):
78 self.exceptionToRaise = StopWriting("Stop writing, please")
79
80 def _deliverBuffer(self):
81 """causes the accumulated data to be written if enough
82 data is there.
83
84 This must be called at least once after buffer.doneWriting()
85 as been called.
86 """
87 while self.connectionLive and not self.exceptionToRaise:
88 data = self.buffer.get()
89 if data is None: # nothing to write yet/any more
90 return
91 while self.paused and not self.exceptionToRaise:
92 # consumer has requested a pause; let's busy-loop;
93 # doesn't cost much and is easier than semaphores.
94 time.sleep(0.1)
95
96 reactor.callFromThread(self._writeToConsumer, data)
97
98 def write(self, data):
99 """schedules data to be written to the consumer.
100 """
101 if self.exceptionToRaise:
102 raise self.exceptionToRaise
103
104 # Allow unicode data in as long as it's actually ascii:
105 if isinstance(data, str):
106 data = data.encode("ascii")
107
108 self.buffer.add(data)
109 self._deliverBuffer()
110
111 def _writeToConsumer(self, data):
112 # We want to catch errors occurring during writes. This method
113 # is called from the reactor (main) thread.
114 # We assign to the exceptionToRaise instance variable, and this
115 # races with stopProducing. This race is harmless, though, since
116 # in any case writing stops, and the exception raised is of secondary
117 # importance.
118
119 # when the remote end has hung up, this can still be called from
120 # twisted's belly, but the consumer's channel will be None by then.
121 # I don't want ugly mess in the logs in that case, so I catch this
122 # case, hoping I don't ignore any actual problems in this way:
123 if self.consumer.channel is None:
124 return
125
126 try:
127 self.consumer.write(data)
128 except IOError as ex:
129 self.exceptionToRaise = ex
130 except Exception as ex:
131 base.ui.notifyError("Exception during streamed write.")
132 self.exceptionToRaise = ex
133
134 def cleanup(self, result=None):
135 # Must be callFromThread'ed
136 self.exceptionToRaise = None
137 self.join(0.01)
138 if self.is_alive():
139 base.ui.notifyError("Streaming thread couldn't be joined?")
140
141 if self.connectionLive:
142 # I have no idea why channel would be None here with a live conn,
143 # but it happens on stretch, so let's protect unregisterProducer.
144 if getattr(self.consumer, "channel", None):
145 self.consumer.unregisterProducer()
146 else:
147 self.consumer.producer = None
148 # Clean up the request; don't make this conditional, as
149 # that would prevent important callbacks from running
150 self.consumer.finish()
151
152 def run(self):
153 # the request variable is stolen for http/https discrimination
154 # far downstack
155 request = self.consumer #noflake: for stealing
156
157 try:
158 try:
159 self.writeStreamTo(self)
160 self.buffer.doneWriting()
161 self._deliverBuffer()
162 except StopWriting:
163 pass
164 except IOError:
165 # I/O errors are most likely not our fault, and I don't want
166 # to make matters worse by pushing any dumps into a line
167 # that's probably closed anyway.
168 base.ui.notifyError("I/O Error while streaming:")
169 except:
170 base.ui.notifyError("Exception while streaming"
171 " (closing connection):\n")
172 self.consumer.write("\n\n\nXXXXXX Internal error in DaCHS software.\n"
173 "If you are seeing this, please notify [email protected]\n"
174 "with as many details (like a URL) as possible.\n"
175 "Also, the following traceback may help people there figure out\n"
176 "the problem:\n"+
177 utils.getTracebackAsString())
178 # All producing is done in the thread, so when no one's writing any
179 # more, we should have delivered everything to the consumer
180 finally:
181 reactor.callFromThread(self.cleanup)
182
183 synchronized = ['resumeProducing', 'pauseProducing', 'stopProducing']
184
185 threadable.synchronize(DataStreamer)
186
187
188 def streamOut(writeStreamTo, request, queryMeta=None):
189 """sets up the thread to have writeStreamTo write to request from
190 a thread.
191
192 For convenience, this function returns server.NOT_DONE_YET, so
193 in a t.w render method you can just say ``return streamOut()``.
194
195 We manage all necessary callbacks and errback ourselves.
196 """
197 if request.channel is None:
198 base.ui.notifyWarning("Not streaming to a dead connection.")
199 return
200
201 t = DataStreamer(writeStreamTo, request, queryMeta)
202 t.start()
203 return server.NOT_DONE_YET
204
205
206 def streamVOTable(request, data, queryMeta=None, **contextOpts):
207 """streams out the payload of a data item as a VOTable.
208 """
209 def writeVOTable(outputFile):
210 """writes a VOTable representation of a data item or table data
211 to request.
212 """
213 if queryMeta is not None:
214 if "tablecoding" not in contextOpts:
215 contextOpts["tablecoding"] = {
216 True: "td", False: "binary"}[queryMeta["tdEnc"]]
217 if "version" not in contextOpts:
218 contextOpts["version"] = queryMeta.get("VOTableVersion")
219
220 votablewrite.writeAsVOTable(
221 data, outputFile,
222 ctx=votablewrite.VOTableContext(**contextOpts))
223 return ""
224
225 return streamOut(writeVOTable, request)