| Mark Slee | 89e2bb8 | 2007-03-01 00:20:36 +0000 | [diff] [blame] | 1 | # |
| David Reiss | ea2cba8 | 2009-03-30 21:35:00 +0000 | [diff] [blame] | 2 | # Licensed to the Apache Software Foundation (ASF) under one |
| 3 | # or more contributor license agreements. See the NOTICE file |
| 4 | # distributed with this work for additional information |
| 5 | # regarding copyright ownership. The ASF licenses this file |
| 6 | # to you under the Apache License, Version 2.0 (the |
| 7 | # "License"); you may not use this file except in compliance |
| 8 | # with the License. You may obtain a copy of the License at |
| 9 | # |
| 10 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | # |
| 12 | # Unless required by applicable law or agreed to in writing, |
| 13 | # software distributed under the License is distributed on an |
| 14 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | # KIND, either express or implied. See the License for the |
| 16 | # specific language governing permissions and limitations |
| 17 | # under the License. |
| 18 | # |
| Mark Slee | 89e2bb8 | 2007-03-01 00:20:36 +0000 | [diff] [blame] | 19 | |
| David Reiss | e29995e | 2008-07-31 20:15:17 +0000 | [diff] [blame] | 20 | import errno |
| Nobuaki Sukegawa | 1c8b5cb | 2016-02-14 22:04:38 +0900 | [diff] [blame] | 21 | import logging |
| Bryan Duxbury | 6972041 | 2012-01-03 17:32:30 +0000 | [diff] [blame] | 22 | import os |
| Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 23 | import socket |
| David Reiss | 73af3b7 | 2010-08-30 21:57:07 +0000 | [diff] [blame] | 24 | import sys |
| Carel | e720e6f | 2025-11-07 10:48:27 +0200 | [diff] [blame] | 25 | import platform |
| Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 26 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 27 | from .TTransport import TTransportBase, TTransportException, TServerTransportBase |
| Bryan Duxbury | 6972041 | 2012-01-03 17:32:30 +0000 | [diff] [blame] | 28 | |
| Nobuaki Sukegawa | 1c8b5cb | 2016-02-14 22:04:38 +0900 | [diff] [blame] | 29 | logger = logging.getLogger(__name__) |
| 30 | |
| Bryan Duxbury | 6972041 | 2012-01-03 17:32:30 +0000 | [diff] [blame] | 31 | |
| David Reiss | e29995e | 2008-07-31 20:15:17 +0000 | [diff] [blame] | 32 | class TSocketBase(TTransportBase): |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 33 | def _resolveAddr(self): |
| 34 | if self._unix_socket is not None: |
| 35 | return [(socket.AF_UNIX, socket.SOCK_STREAM, None, None, |
| 36 | self._unix_socket)] |
| 37 | else: |
| 38 | return socket.getaddrinfo(self.host, |
| 39 | self.port, |
| 40 | self._socket_family, |
| 41 | socket.SOCK_STREAM, |
| 42 | 0, |
| max ulidtko | 9b9567b | 2020-04-27 16:04:27 +0300 | [diff] [blame] | 43 | socket.AI_PASSIVE) |
| Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 44 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 45 | def close(self): |
| 46 | if self.handle: |
| 47 | self.handle.close() |
| 48 | self.handle = None |
| David Reiss | e29995e | 2008-07-31 20:15:17 +0000 | [diff] [blame] | 49 | |
| Bryan Duxbury | 6972041 | 2012-01-03 17:32:30 +0000 | [diff] [blame] | 50 | |
| David Reiss | e29995e | 2008-07-31 20:15:17 +0000 | [diff] [blame] | 51 | class TSocket(TSocketBase): |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 52 | """Socket implementation of TTransport base.""" |
| Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 53 | |
| Jun | f6511c9 | 2019-02-01 12:07:58 +0800 | [diff] [blame] | 54 | def __init__(self, host='localhost', port=9090, unix_socket=None, |
| 55 | socket_family=socket.AF_UNSPEC, |
| 56 | socket_keepalive=False): |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 57 | """Initialize a TSocket |
| David Reiss | c16a8f6 | 2007-12-14 23:46:47 +0000 | [diff] [blame] | 58 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 59 | @param host(str) The host to connect to. |
| 60 | @param port(int) The (TCP) port to connect to. |
| 61 | @param unix_socket(str) The filename of a unix socket to connect to. |
| 62 | (host and port will be ignored.) |
| 63 | @param socket_family(int) The socket family to use with this socket. |
| Jun | f6511c9 | 2019-02-01 12:07:58 +0800 | [diff] [blame] | 64 | @param socket_keepalive(bool) enable TCP keepalive, default off. |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 65 | """ |
| 66 | self.host = host |
| 67 | self.port = port |
| 68 | self.handle = None |
| 69 | self._unix_socket = unix_socket |
| 70 | self._timeout = None |
| 71 | self._socket_family = socket_family |
| Jun | f6511c9 | 2019-02-01 12:07:58 +0800 | [diff] [blame] | 72 | self._socket_keepalive = socket_keepalive |
| David Reiss | 0c90f6f | 2008-02-06 22:18:40 +0000 | [diff] [blame] | 73 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 74 | def setHandle(self, h): |
| 75 | self.handle = h |
| Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 76 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 77 | def isOpen(self): |
| Neil Williams | 01d53f4 | 2020-07-07 07:27:29 -0700 | [diff] [blame] | 78 | if self.handle is None: |
| 79 | return False |
| 80 | |
| 81 | # this lets us cheaply see if the other end of the socket is still |
| 82 | # connected. if disconnected, we'll get EOF back (expressed as zero |
| 83 | # bytes of data) otherwise we'll get one byte or an error indicating |
| 84 | # we'd have to block for data. |
| 85 | # |
| 86 | # note that we're not doing this with socket.MSG_DONTWAIT because 1) |
| 87 | # it's linux-specific and 2) gevent-patched sockets hide EAGAIN from us |
| 88 | # when timeout is non-zero. |
| 89 | original_timeout = self.handle.gettimeout() |
| 90 | try: |
| 91 | self.handle.settimeout(0) |
| 92 | try: |
| 93 | peeked_bytes = self.handle.recv(1, socket.MSG_PEEK) |
| Csaba Ringhofer | efe5e02 | 2024-08-23 14:08:35 +0200 | [diff] [blame] | 94 | # the length will be zero if we got EOF (indicating connection closed) |
| 95 | if len(peeked_bytes) == 1: |
| 96 | return True |
| Neil Williams | 01d53f4 | 2020-07-07 07:27:29 -0700 | [diff] [blame] | 97 | except (socket.error, OSError) as exc: # on modern python this is just BlockingIOError |
| 98 | if exc.errno in (errno.EWOULDBLOCK, errno.EAGAIN): |
| 99 | return True |
| Michael Smith | e3eb9af | 2022-06-08 17:23:27 -0700 | [diff] [blame] | 100 | except ValueError: |
| 101 | # SSLSocket fails on recv with non-zero flags; fallback to the old behavior |
| 102 | return True |
| Neil Williams | 01d53f4 | 2020-07-07 07:27:29 -0700 | [diff] [blame] | 103 | finally: |
| 104 | self.handle.settimeout(original_timeout) |
| 105 | |
| Csaba Ringhofer | efe5e02 | 2024-08-23 14:08:35 +0200 | [diff] [blame] | 106 | # The caller may assume that after isOpen() returns False, calling close() |
| 107 | # is not needed, so it is safer to close the socket here. |
| 108 | self.close() |
| 109 | return False |
| Aditya Agarwal | f954f97 | 2007-02-06 01:26:12 +0000 | [diff] [blame] | 110 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 111 | def setTimeout(self, ms): |
| 112 | if ms is None: |
| 113 | self._timeout = None |
| 114 | else: |
| 115 | self._timeout = ms / 1000.0 |
| David Reiss | 0c90f6f | 2008-02-06 22:18:40 +0000 | [diff] [blame] | 116 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 117 | if self.handle is not None: |
| 118 | self.handle.settimeout(self._timeout) |
| Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 119 | |
| Nobuaki Sukegawa | 1c8b5cb | 2016-02-14 22:04:38 +0900 | [diff] [blame] | 120 | def _do_open(self, family, socktype): |
| 121 | return socket.socket(family, socktype) |
| 122 | |
| 123 | @property |
| 124 | def _address(self): |
| 125 | return self._unix_socket if self._unix_socket else '%s:%d' % (self.host, self.port) |
| 126 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 127 | def open(self): |
| Nobuaki Sukegawa | 1c8b5cb | 2016-02-14 22:04:38 +0900 | [diff] [blame] | 128 | if self.handle: |
| James E. King III | 3131fe9 | 2019-07-02 14:21:05 -0400 | [diff] [blame] | 129 | raise TTransportException(type=TTransportException.ALREADY_OPEN, message="already open") |
| Mark Slee | 2297460 | 2007-07-06 22:20:19 +0000 | [diff] [blame] | 130 | try: |
| Nobuaki Sukegawa | 1c8b5cb | 2016-02-14 22:04:38 +0900 | [diff] [blame] | 131 | addrs = self._resolveAddr() |
| James E. King III | 3131fe9 | 2019-07-02 14:21:05 -0400 | [diff] [blame] | 132 | except socket.gaierror as gai: |
| Nobuaki Sukegawa | 1c8b5cb | 2016-02-14 22:04:38 +0900 | [diff] [blame] | 133 | msg = 'failed to resolve sockaddr for ' + str(self._address) |
| 134 | logger.exception(msg) |
| James E. King III | 3131fe9 | 2019-07-02 14:21:05 -0400 | [diff] [blame] | 135 | raise TTransportException(type=TTransportException.NOT_OPEN, message=msg, inner=gai) |
| Michael Smith | 8707949 | 2025-11-14 13:47:42 -0800 | [diff] [blame] | 136 | # Preserve the last exception to report if all addresses fail. |
| 137 | last_exc = None |
| Nobuaki Sukegawa | 1c8b5cb | 2016-02-14 22:04:38 +0900 | [diff] [blame] | 138 | for family, socktype, _, _, sockaddr in addrs: |
| 139 | handle = self._do_open(family, socktype) |
| Jun | f6511c9 | 2019-02-01 12:07:58 +0800 | [diff] [blame] | 140 | |
| Nick Withers | e0ee2c7 | 2022-08-31 16:22:27 +1000 | [diff] [blame] | 141 | # TCP keep-alive |
| Jun | f6511c9 | 2019-02-01 12:07:58 +0800 | [diff] [blame] | 142 | if self._socket_keepalive: |
| Nick Withers | e0ee2c7 | 2022-08-31 16:22:27 +1000 | [diff] [blame] | 143 | handle.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) |
| Jun | f6511c9 | 2019-02-01 12:07:58 +0800 | [diff] [blame] | 144 | |
| Nobuaki Sukegawa | 1c8b5cb | 2016-02-14 22:04:38 +0900 | [diff] [blame] | 145 | handle.settimeout(self._timeout) |
| 146 | try: |
| 147 | handle.connect(sockaddr) |
| 148 | self.handle = handle |
| 149 | return |
| Michael Smith | 8707949 | 2025-11-14 13:47:42 -0800 | [diff] [blame] | 150 | except socket.error as e: |
| Nobuaki Sukegawa | 1c8b5cb | 2016-02-14 22:04:38 +0900 | [diff] [blame] | 151 | handle.close() |
| 152 | logger.info('Could not connect to %s', sockaddr, exc_info=True) |
| Michael Smith | 8707949 | 2025-11-14 13:47:42 -0800 | [diff] [blame] | 153 | last_exc = e |
| Nobuaki Sukegawa | 1c8b5cb | 2016-02-14 22:04:38 +0900 | [diff] [blame] | 154 | msg = 'Could not connect to any of %s' % list(map(lambda a: a[4], |
| 155 | addrs)) |
| 156 | logger.error(msg) |
| Michael Smith | 8707949 | 2025-11-14 13:47:42 -0800 | [diff] [blame] | 157 | raise TTransportException(type=TTransportException.NOT_OPEN, message=msg, inner=last_exc) |
| Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 158 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 159 | def read(self, sz): |
| 160 | try: |
| 161 | buff = self.handle.recv(sz) |
| bwangelme | d66ce92 | 2024-07-02 10:40:58 +0800 | [diff] [blame^] | 162 | # TODO: remove socket.timeout when 3.10 becomes the earliest version of python supported. |
| 163 | except (socket.timeout, TimeoutError) as e: |
| bwangelme | 0ed4a1d | 2024-04-15 12:17:40 +0800 | [diff] [blame] | 164 | raise TTransportException(type=TTransportException.TIMED_OUT, message="read timeout", inner=e) |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 165 | except socket.error as e: |
| 166 | if (e.args[0] == errno.ECONNRESET and |
| 167 | (sys.platform == 'darwin' or sys.platform.startswith('freebsd'))): |
| 168 | # freebsd and Mach don't follow POSIX semantic of recv |
| 169 | # and fail with ECONNRESET if peer performed shutdown. |
| 170 | # See corresponding comment and code in TSocket::read() |
| 171 | # in lib/cpp/src/transport/TSocket.cpp. |
| 172 | self.close() |
| 173 | # Trigger the check to raise the END_OF_FILE exception below. |
| 174 | buff = '' |
| 175 | else: |
| James E. King III | 3131fe9 | 2019-07-02 14:21:05 -0400 | [diff] [blame] | 176 | raise TTransportException(message="unexpected exception", inner=e) |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 177 | if len(buff) == 0: |
| 178 | raise TTransportException(type=TTransportException.END_OF_FILE, |
| 179 | message='TSocket read 0 bytes') |
| 180 | return buff |
| Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 181 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 182 | def write(self, buff): |
| 183 | if not self.handle: |
| 184 | raise TTransportException(type=TTransportException.NOT_OPEN, |
| 185 | message='Transport not open') |
| 186 | sent = 0 |
| 187 | have = len(buff) |
| 188 | while sent < have: |
| James E. King III | 3131fe9 | 2019-07-02 14:21:05 -0400 | [diff] [blame] | 189 | try: |
| 190 | plus = self.handle.send(buff) |
| 191 | if plus == 0: |
| 192 | raise TTransportException(type=TTransportException.END_OF_FILE, |
| 193 | message='TSocket sent 0 bytes') |
| 194 | sent += plus |
| 195 | buff = buff[plus:] |
| 196 | except socket.error as e: |
| 197 | raise TTransportException(message="unexpected exception", inner=e) |
| Mark Slee | cde2b61 | 2006-09-03 21:13:07 +0000 | [diff] [blame] | 198 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 199 | def flush(self): |
| 200 | pass |
| Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 201 | |
| Bryan Duxbury | 6972041 | 2012-01-03 17:32:30 +0000 | [diff] [blame] | 202 | |
| David Reiss | d73255d | 2009-03-24 22:51:02 +0000 | [diff] [blame] | 203 | class TServerSocket(TSocketBase, TServerTransportBase): |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 204 | """Socket implementation of TServerTransport base.""" |
| Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 205 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 206 | def __init__(self, host=None, port=9090, unix_socket=None, socket_family=socket.AF_UNSPEC): |
| 207 | self.host = host |
| 208 | self.port = port |
| 209 | self._unix_socket = unix_socket |
| 210 | self._socket_family = socket_family |
| 211 | self.handle = None |
| lshgdut | 7af79c8 | 2018-11-21 10:09:42 +0800 | [diff] [blame] | 212 | self._backlog = 128 |
| 213 | |
| 214 | def setBacklog(self, backlog=None): |
| 215 | if not self.handle: |
| 216 | self._backlog = backlog |
| 217 | else: |
| 218 | # We cann't update backlog when it is already listening, since the |
| 219 | # handle has been created. |
| Alexander Shadchin | 0bc2cb9 | 2024-07-21 23:27:26 +0300 | [diff] [blame] | 220 | logger.warning('You have to set backlog before listen.') |
| Mark Slee | 256bdc4 | 2007-11-27 08:42:19 +0000 | [diff] [blame] | 221 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 222 | def listen(self): |
| 223 | res0 = self._resolveAddr() |
| 224 | socket_family = self._socket_family == socket.AF_UNSPEC and socket.AF_INET6 or self._socket_family |
| 225 | for res in res0: |
| 226 | if res[0] is socket_family or res is res0[-1]: |
| 227 | break |
| Mark Slee | 2297460 | 2007-07-06 22:20:19 +0000 | [diff] [blame] | 228 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 229 | # We need remove the old unix socket if the file exists and |
| 230 | # nobody is listening on it. |
| 231 | if self._unix_socket: |
| 232 | tmp = socket.socket(res[0], res[1]) |
| 233 | try: |
| 234 | tmp.connect(res[4]) |
| 235 | except socket.error as err: |
| 236 | eno, message = err.args |
| 237 | if eno == errno.ECONNREFUSED: |
| 238 | os.unlink(res[4]) |
| David Reiss | e29995e | 2008-07-31 20:15:17 +0000 | [diff] [blame] | 239 | |
| Ling Li | ae3e96b | 2023-03-16 17:34:51 -0700 | [diff] [blame] | 240 | self.handle = s = socket.socket(res[0], res[1]) |
| 241 | if s.family is socket.AF_INET6: |
| Carel | e720e6f | 2025-11-07 10:48:27 +0200 | [diff] [blame] | 242 | if platform.system() == 'Windows' and sys.version_info < (3, 8): |
| 243 | logger.warning('Windows socket defaulting to IPv4 for Python < 3.8: See https://github.com/python/cpython/issues/73701') |
| 244 | else: |
| 245 | s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) |
| Ling Li | ae3e96b | 2023-03-16 17:34:51 -0700 | [diff] [blame] | 246 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 247 | if hasattr(s, 'settimeout'): |
| 248 | s.settimeout(None) |
| 249 | s.bind(res[4]) |
| 250 | s.listen(self._backlog) |
| Mark Slee | c967656 | 2006-09-05 17:34:52 +0000 | [diff] [blame] | 251 | |
| Nobuaki Sukegawa | 10308cb | 2016-02-03 01:57:03 +0900 | [diff] [blame] | 252 | def accept(self): |
| 253 | client, addr = self.handle.accept() |
| 254 | result = TSocket() |
| 255 | result.setHandle(client) |
| 256 | return result |