Debian Codegraph @

cassandra/io/eventletreactor.py

raw
1 # Copyright 2014 Symantec Corporation
2 # Copyright DataStax, Inc.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 # Originally derived from MagnetoDB source:
17 # https://github.com/stackforge/magnetodb/blob/2015.1.0b1/magnetodb/common/cassandra/io/eventletreactor.py
18 import eventlet
19 from eventlet.green import socket
20 from eventlet.queue import Queue
21 from greenlet import GreenletExit
22 import logging
23 from threading import Event
24 import time
25
26 from cassandra.connection import Connection, ConnectionShutdown, Timer, TimerManager
27 try:
28 from eventlet.green.OpenSSL import SSL
29 _PYOPENSSL = True
30 except ImportError as e:
31 _PYOPENSSL = False
32 no_pyopenssl_error = e
33
34
35 log = logging.getLogger(__name__)
36
37
38 def _check_pyopenssl():
39 if not _PYOPENSSL:
40 raise ImportError(
41 "{}, pyOpenSSL must be installed to enable "
42 "SSL support with the Eventlet event loop".format(str(no_pyopenssl_error))
43 )
44
45
46 class EventletConnection(Connection):
47 """
48 An implementation of :class:`.Connection` that utilizes ``eventlet``.
49
50 This implementation assumes all eventlet monkey patching is active. It is not tested with partial patching.
51 """
52
53 _read_watcher = None
54 _write_watcher = None
55
56 _socket_impl = eventlet.green.socket
57 _ssl_impl = eventlet.green.ssl
58
59 _timers = None
60 _timeout_watcher = None
61 _new_timer = None
62
63 @classmethod
64 def initialize_reactor(cls):
65 eventlet.monkey_patch()
66 if not cls._timers:
67 cls._timers = TimerManager()
68 cls._timeout_watcher = eventlet.spawn(cls.service_timeouts)
69 cls._new_timer = Event()
70
71 @classmethod
72 def create_timer(cls, timeout, callback):
73 timer = Timer(timeout, callback)
74 cls._timers.add_timer(timer)
75 cls._new_timer.set()
76 return timer
77
78 @classmethod
79 def service_timeouts(cls):
80 """
81 cls._timeout_watcher runs in this loop forever.
82 It is usually waiting for the next timeout on the cls._new_timer Event.
83 When new timers are added, that event is set so that the watcher can
84 wake up and possibly set an earlier timeout.
85 """
86 timer_manager = cls._timers
87 while True:
88 next_end = timer_manager.service_timeouts()
89 sleep_time = max(next_end - time.time(), 0) if next_end else 10000
90 cls._new_timer.wait(sleep_time)
91 cls._new_timer.clear()
92
93 def __init__(self, *args, **kwargs):
94 Connection.__init__(self, *args, **kwargs)
95 self.uses_legacy_ssl_options = self.ssl_options and not self.ssl_context
96 self._write_queue = Queue()
97
98 self._connect_socket()
99
100 self._read_watcher = eventlet.spawn(lambda: self.handle_read())
101 self._write_watcher = eventlet.spawn(lambda: self.handle_write())
102 self._send_options_message()
103
104 def _wrap_socket_from_context(self):
105 _check_pyopenssl()
106 rv = SSL.Connection(self.ssl_context, self._socket)
107 rv.set_connect_state()
108 if self.ssl_options and 'server_hostname' in self.ssl_options:
109 # This is necessary for SNI
110 rv.set_tlsext_host_name(self.ssl_options['server_hostname'].encode('ascii'))
111 return rv
112
113 def _initiate_connection(self, sockaddr):
114 if self.uses_legacy_ssl_options:
115 super(EventletConnection, self)._initiate_connection(sockaddr)
116 else:
117 self._socket.connect(sockaddr)
118 if self.ssl_context or self.ssl_options:
119 self._socket.do_handshake()
120
121 def _validate_hostname(self):
122 if not self.uses_legacy_ssl_options:
123 cert_name = self._socket.get_peer_certificate().get_subject().commonName
124 if cert_name != self.endpoint.address:
125 raise Exception("Hostname verification failed! Certificate name '{}' "
126 "doesn't match endpoint '{}'".format(cert_name, self.endpoint.address))
127
128 def close(self):
129 with self.lock:
130 if self.is_closed:
131 return
132 self.is_closed = True
133
134 log.debug("Closing connection (%s) to %s" % (id(self), self.endpoint))
135
136 cur_gthread = eventlet.getcurrent()
137
138 if self._read_watcher and self._read_watcher != cur_gthread:
139 self._read_watcher.kill()
140 if self._write_watcher and self._write_watcher != cur_gthread:
141 self._write_watcher.kill()
142 if self._socket:
143 self._socket.close()
144 log.debug("Closed socket to %s" % (self.endpoint,))
145
146 if not self.is_defunct:
147 self.error_all_requests(
148 ConnectionShutdown("Connection to %s was closed" % self.endpoint))
149 # don't leave in-progress operations hanging
150 self.connected_event.set()
151
152 def handle_close(self):
153 log.debug("connection closed by server")
154 self.close()
155
156 def handle_write(self):
157 while True:
158 try:
159 next_msg = self._write_queue.get()
160 self._socket.sendall(next_msg)
161 except socket.error as err:
162 log.debug("Exception during socket send for %s: %s", self, err)
163 self.defunct(err)
164 return # Leave the write loop
165 except GreenletExit: # graceful greenthread exit
166 return
167
168 def handle_read(self):
169 while True:
170 try:
171 buf = self._socket.recv(self.in_buffer_size)
172 self._iobuf.write(buf)
173 except socket.error as err:
174 log.debug("Exception during socket recv for %s: %s",
175 self, err)
176 self.defunct(err)
177 return # leave the read loop
178 except GreenletExit: # graceful greenthread exit
179 return
180
181 if buf and self._iobuf.tell():
182 self.process_io_buffer()
183 else:
184 log.debug("Connection %s closed by server", self)
185 self.close()
186 return
187
188 def push(self, data):
189 chunk_size = self.out_buffer_size
190 for i in range(0, len(data), chunk_size):
191 self._write_queue.put(data[i:i + chunk_size])