Debian Codegraph @

cassandra/io/twistedreactor.py

raw
1 # Copyright DataStax, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """
15 Module that implements an event loop based on twisted
16 ( https://twistedmatrix.com ).
17 """
18 import atexit
19 import logging
20 import time
21 from functools import partial
22 from threading import Thread, Lock
23 import weakref
24
25 from twisted.internet import reactor, protocol
26 from twisted.internet.endpoints import connectProtocol, TCP4ClientEndpoint, SSL4ClientEndpoint
27 from twisted.internet.interfaces import IOpenSSLClientConnectionCreator
28 from twisted.python.failure import Failure
29 from zope.interface import implementer
30
31 from cassandra.connection import Connection, ConnectionShutdown, Timer, TimerManager, ConnectionException
32
33 try:
34 from OpenSSL import SSL
35 _HAS_SSL = True
36 except ImportError as e:
37 _HAS_SSL = False
38 import_exception = e
39 log = logging.getLogger(__name__)
40
41
42 def _cleanup(cleanup_weakref):
43 try:
44 cleanup_weakref()._cleanup()
45 except ReferenceError:
46 return
47
48
49 class TwistedConnectionProtocol(protocol.Protocol):
50 """
51 Twisted Protocol class for handling data received and connection
52 made events.
53 """
54
55 def __init__(self, connection):
56 self.connection = connection
57
58 def dataReceived(self, data):
59 """
60 Callback function that is called when data has been received
61 on the connection.
62
63 Reaches back to the Connection object and queues the data for
64 processing.
65 """
66 self.connection._iobuf.write(data)
67 self.connection.handle_read()
68
69 def connectionMade(self):
70 """
71 Callback function that is called when a connection has succeeded.
72
73 Reaches back to the Connection object and confirms that the connection
74 is ready.
75 """
76 self.connection.client_connection_made(self.transport)
77
78 def connectionLost(self, reason):
79 # reason is a Failure instance
80 log.debug("Connect lost: %s", reason)
81 self.connection.defunct(reason.value)
82
83
84 class TwistedLoop(object):
85
86 _lock = None
87 _thread = None
88 _timeout_task = None
89 _timeout = None
90
91 def __init__(self):
92 self._lock = Lock()
93 self._timers = TimerManager()
94
95 def maybe_start(self):
96 with self._lock:
97 if not reactor.running:
98 self._thread = Thread(target=reactor.run,
99 name="cassandra_driver_twisted_event_loop",
100 kwargs={'installSignalHandlers': False})
101 self._thread.daemon = True
102 self._thread.start()
103 atexit.register(partial(_cleanup, weakref.ref(self)))
104
105 def _reactor_stopped(self):
106 return reactor._stopped
107
108 def _cleanup(self):
109 if self._thread:
110 reactor.callFromThread(reactor.stop)
111 self._thread.join(timeout=1.0)
112 if self._thread.is_alive():
113 log.warning("Event loop thread could not be joined, so "
114 "shutdown may not be clean. Please call "
115 "Cluster.shutdown() to avoid this.")
116 log.debug("Event loop thread was joined")
117
118 def add_timer(self, timer):
119 self._timers.add_timer(timer)
120 # callFromThread to schedule from the loop thread, where
121 # the timeout task can safely be modified
122 reactor.callFromThread(self._schedule_timeout, timer.end)
123
124 def _schedule_timeout(self, next_timeout):
125 if next_timeout:
126 delay = max(next_timeout - time.time(), 0)
127 if self._timeout_task and self._timeout_task.active():
128 if next_timeout < self._timeout:
129 self._timeout_task.reset(delay)
130 self._timeout = next_timeout
131 else:
132 self._timeout_task = reactor.callLater(delay, self._on_loop_timer)
133 self._timeout = next_timeout
134
135 def _on_loop_timer(self):
136 self._timers.service_timeouts()
137 self._schedule_timeout(self._timers.next_timeout)
138
139
140 @implementer(IOpenSSLClientConnectionCreator)
141 class _SSLCreator(object):
142 def __init__(self, endpoint, ssl_context, ssl_options, check_hostname, timeout):
143 self.endpoint = endpoint
144 self.ssl_options = ssl_options
145 self.check_hostname = check_hostname
146 self.timeout = timeout
147
148 if ssl_context:
149 self.context = ssl_context
150 else:
151 self.context = SSL.Context(SSL.TLSv1_METHOD)
152 if "certfile" in self.ssl_options:
153 self.context.use_certificate_file(self.ssl_options["certfile"])
154 if "keyfile" in self.ssl_options:
155 self.context.use_privatekey_file(self.ssl_options["keyfile"])
156 if "ca_certs" in self.ssl_options:
157 self.context.load_verify_locations(self.ssl_options["ca_certs"])
158 if "cert_reqs" in self.ssl_options:
159 self.context.set_verify(
160 self.ssl_options["cert_reqs"],
161 callback=self.verify_callback
162 )
163 self.context.set_info_callback(self.info_callback)
164
165 def verify_callback(self, connection, x509, errnum, errdepth, ok):
166 return ok
167
168 def info_callback(self, connection, where, ret):
169 if where & SSL.SSL_CB_HANDSHAKE_DONE:
170 if self.check_hostname and self.endpoint.address != connection.get_peer_certificate().get_subject().commonName:
171 transport = connection.get_app_data()
172 transport.failVerification(Failure(ConnectionException("Hostname verification failed", self.endpoint)))
173
174 def clientConnectionForTLS(self, tlsProtocol):
175 connection = SSL.Connection(self.context, None)
176 connection.set_app_data(tlsProtocol)
177 if self.ssl_options and "server_hostname" in self.ssl_options:
178 connection.set_tlsext_host_name(self.ssl_options['server_hostname'].encode('ascii'))
179 return connection
180
181
182 class TwistedConnection(Connection):
183 """
184 An implementation of :class:`.Connection` that utilizes the
185 Twisted event loop.
186 """
187
188 _loop = None
189
190 @classmethod
191 def initialize_reactor(cls):
192 if not cls._loop:
193 cls._loop = TwistedLoop()
194
195 @classmethod
196 def create_timer(cls, timeout, callback):
197 timer = Timer(timeout, callback)
198 cls._loop.add_timer(timer)
199 return timer
200
201 def __init__(self, *args, **kwargs):
202 """
203 Initialization method.
204
205 Note that we can't call reactor methods directly here because
206 it's not thread-safe, so we schedule the reactor/connection
207 stuff to be run from the event loop thread when it gets the
208 chance.
209 """
210 Connection.__init__(self, *args, **kwargs)
211
212 self.is_closed = True
213 self.connector = None
214 self.transport = None
215
216 reactor.callFromThread(self.add_connection)
217 self._loop.maybe_start()
218
219 def _check_pyopenssl(self):
220 if self.ssl_context or self.ssl_options:
221 if not _HAS_SSL:
222 raise ImportError(
223 str(import_exception) +
224 ', pyOpenSSL must be installed to enable SSL support with the Twisted event loop'
225 )
226
227 def add_connection(self):
228 """
229 Convenience function to connect and store the resulting
230 connector.
231 """
232 host, port = self.endpoint.resolve()
233 if self.ssl_context or self.ssl_options:
234 # Can't use optionsForClientTLS here because it *forces* hostname verification.
235 # Cool they enforce strong security, but we have to be able to turn it off
236 self._check_pyopenssl()
237
238 ssl_connection_creator = _SSLCreator(
239 self.endpoint,
240 self.ssl_context if self.ssl_context else None,
241 self.ssl_options,
242 self._check_hostname,
243 self.connect_timeout,
244 )
245
246 endpoint = SSL4ClientEndpoint(
247 reactor,
248 host,
249 port,
250 sslContextFactory=ssl_connection_creator,
251 timeout=self.connect_timeout,
252 )
253 else:
254 endpoint = TCP4ClientEndpoint(
255 reactor,
256 host,
257 port,
258 timeout=self.connect_timeout
259 )
260 connectProtocol(endpoint, TwistedConnectionProtocol(self))
261
262 def client_connection_made(self, transport):
263 """
264 Called by twisted protocol when a connection attempt has
265 succeeded.
266 """
267 with self.lock:
268 self.is_closed = False
269 self.transport = transport
270 self._send_options_message()
271
272 def close(self):
273 """
274 Disconnect and error-out all requests.
275 """
276 with self.lock:
277 if self.is_closed:
278 return
279 self.is_closed = True
280
281 log.debug("Closing connection (%s) to %s", id(self), self.endpoint)
282 reactor.callFromThread(self.transport.connector.disconnect)
283 log.debug("Closed socket to %s", self.endpoint)
284
285 if not self.is_defunct:
286 self.error_all_requests(
287 ConnectionShutdown("Connection to %s was closed" % self.endpoint))
288 # don't leave in-progress operations hanging
289 self.connected_event.set()
290
291 def handle_read(self):
292 """
293 Process the incoming data buffer.
294 """
295 self.process_io_buffer()
296
297 def push(self, data):
298 """
299 This function is called when outgoing data should be queued
300 for sending.
301
302 Note that we can't call transport.write() directly because
303 it is not thread-safe, so we schedule it to run from within
304 the event loop when it gets the chance.
305 """
306 reactor.callFromThread(self.transport.write, data)