Skip to content

Commit 72fc3c8

Browse files
committed
feat(psycopg): add support for Windows via TCP loopback proxy
1 parent 257407a commit 72fc3c8

4 files changed

Lines changed: 129 additions & 95 deletions

File tree

‎google/cloud/sql/connector/psycopg.py‎

Lines changed: 49 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import logging
1616
import os
17+
import platform
1718
import selectors
1819
import socket
1920
import ssl
@@ -123,9 +124,9 @@ def connect(
123124
"""Create a psycopg DBAPI connection object.
124125
125126
Because psycopg does not accept a pre-connected socket, this function
126-
creates a temporary Unix domain socket, tells psycopg to connect there,
127-
and runs a background proxy that forwards bytes between that socket and
128-
the already-established Cloud SQL TLS connection.
127+
creates a local listener (Unix domain socket on Unix, TCP loopback on Windows),
128+
tells psycopg to connect there, and runs a background proxy that forwards bytes
129+
between that socket and the already-established Cloud SQL TLS connection.
129130
130131
Args:
131132
ip_address (str): IP address of the Cloud SQL instance.
@@ -142,37 +143,48 @@ def connect(
142143
'Unable to import module "psycopg." Please install and try again.'
143144
)
144145

145-
if not hasattr(socket, "AF_UNIX"):
146-
raise NotImplementedError(
147-
"Unix domain sockets (AF_UNIX) are not supported on this platform"
148-
)
149-
150-
tmpdir = tempfile.mkdtemp()
151-
socket_path = os.path.join(tmpdir, ".s.PGSQL.5432")
152-
logger.debug("psycopg: created Unix socket at %s", socket_path)
153-
154-
local_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
155-
local_sock.bind(socket_path)
156-
local_sock.listen(1)
146+
is_windows = platform.system() == "Windows"
147+
148+
if is_windows:
149+
# On Windows, libpq does not support Unix domain sockets.
150+
# Use a local TCP loopback socket on an ephemeral port.
151+
local_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
152+
local_sock.bind(("127.0.0.1", 0))
153+
local_sock.listen(1)
154+
host = "127.0.0.1"
155+
port = local_sock.getsockname()[1]
156+
tmpdir = None
157+
socket_path = None
158+
logger.debug("psycopg: created TCP loopback listener on 127.0.0.1:%d", port)
159+
else:
160+
tmpdir = tempfile.mkdtemp()
161+
socket_path = os.path.join(tmpdir, ".s.PGSQL.5432")
162+
logger.debug("psycopg: created Unix socket at %s", socket_path)
163+
164+
local_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
165+
local_sock.bind(socket_path)
166+
local_sock.listen(1)
167+
host = tmpdir
168+
port = 5432
157169

158170
def _accept_and_proxy() -> None:
159171
"""Accept one connection then proxy bytes until the connection closes."""
160-
unix_conn = None
172+
local_conn = None
161173
try:
162-
unix_conn, _ = local_sock.accept()
174+
local_conn, _ = local_sock.accept()
163175
local_sock.close()
164176
logger.debug("psycopg proxy: accepted connection, starting proxy")
165-
_proxy(unix_conn, remote_sock)
177+
_proxy(local_conn, remote_sock)
166178
except Exception as e: # noqa: BLE001
167179
logger.debug("psycopg proxy: error in accept/proxy thread: %s", e)
168180
# Ensure cleanup on any exception
169-
if unix_conn:
181+
if local_conn:
170182
try:
171-
unix_conn.shutdown(socket.SHUT_RDWR)
183+
local_conn.shutdown(socket.SHUT_RDWR)
172184
except OSError:
173185
pass
174186
try:
175-
unix_conn.close()
187+
local_conn.close()
176188
except OSError:
177189
pass
178190
try:
@@ -190,20 +202,22 @@ def _accept_and_proxy() -> None:
190202
db = kwargs.pop("db")
191203
passwd = kwargs.pop("password", None)
192204
# SSL is already handled by the underlying SSLSocket; disable it on the
193-
# Unix socket so psycopg does not attempt a second TLS handshake.
205+
# local socket so psycopg does not attempt a second TLS handshake.
194206
kwargs.pop("sslmode", None)
195207
timeout = kwargs.pop("timeout", None)
196208
if timeout is not None:
197209
kwargs["connect_timeout"] = int(timeout)
198210

199-
logger.debug("psycopg: connecting as user=%s dbname=%s", user, db)
211+
logger.debug(
212+
"psycopg: connecting as user=%s dbname=%s to %s:%s", user, db, host, port
213+
)
200214
try:
201215
conn = psycopg.connect(
202216
user=user,
203217
dbname=db,
204218
password=passwd,
205-
host=tmpdir,
206-
port=5432,
219+
host=host,
220+
port=port,
207221
sslmode="disable",
208222
**kwargs,
209223
)
@@ -225,11 +239,13 @@ def _accept_and_proxy() -> None:
225239
finally:
226240
# The socket file and its parent directory are only needed during the
227241
# initial connect() call; remove them now regardless of outcome.
228-
try:
229-
os.remove(socket_path)
230-
except OSError:
231-
pass
232-
try:
233-
os.rmdir(tmpdir)
234-
except OSError:
235-
pass
242+
if socket_path:
243+
try:
244+
os.remove(socket_path)
245+
except OSError:
246+
pass
247+
if tmpdir:
248+
try:
249+
os.rmdir(tmpdir)
250+
except OSError:
251+
pass

‎tests/system/test_psycopg_connection.py‎

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@
1313
See the License for the specific language governing permissions and
1414
limitations under the License.
1515
"""
16+
1617
from __future__ import annotations
1718

1819
import asyncio
1920
from datetime import datetime
2021
import os
21-
import socket
2222

2323
import pytest
2424
import sqlalchemy
@@ -27,11 +27,6 @@
2727
from google.cloud.sql.connector import DefaultResolver
2828
from google.cloud.sql.connector import DnsResolver
2929

30-
pytestmark = pytest.mark.skipif(
31-
not hasattr(socket, "AF_UNIX"),
32-
reason="Unix domain sockets (AF_UNIX) not available on this platform",
33-
)
34-
3530

3631
def create_sqlalchemy_engine(
3732
instance_connection_name: str,
@@ -131,7 +126,9 @@ def test_customer_managed_CAS_psycopg_connection() -> None:
131126
ip_type = os.environ.get("IP_TYPE", "public")
132127

133128
if not inst_conn_name or not password:
134-
pytest.skip("POSTGRES_CUSTOMER_CAS_CONNECTION_NAME or POSTGRES_CUSTOMER_CAS_PASS not set")
129+
pytest.skip(
130+
"POSTGRES_CUSTOMER_CAS_CONNECTION_NAME or POSTGRES_CUSTOMER_CAS_PASS not set"
131+
)
135132

136133
engine, connector = create_sqlalchemy_engine(
137134
inst_conn_name, user, password, db, ip_type
@@ -153,7 +150,9 @@ def test_custom_SAN_with_dns_psycopg_connection() -> None:
153150
ip_type = os.environ.get("IP_TYPE", "public")
154151

155152
if not inst_conn_name or not password:
156-
pytest.skip("POSTGRES_CUSTOMER_CAS_PASS_VALID_DOMAIN_NAME or POSTGRES_CUSTOMER_CAS_PASS not set")
153+
pytest.skip(
154+
"POSTGRES_CUSTOMER_CAS_PASS_VALID_DOMAIN_NAME or POSTGRES_CUSTOMER_CAS_PASS not set"
155+
)
157156

158157
engine, connector = create_sqlalchemy_engine(
159158
inst_conn_name, user, password, db, ip_type, resolver=DnsResolver

‎tests/system/test_psycopg_iam_auth.py‎

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,24 +16,17 @@
1616

1717
from datetime import datetime
1818
import os
19-
import socket
2019

2120
import pytest
2221
import sqlalchemy
2322

2423
from google.cloud.sql.connector import Connector
2524

26-
# Skip all tests in this file if POSTGRES_IAM_USER is not set or AF_UNIX is not available
27-
pytestmark = [
28-
pytest.mark.skipif(
29-
not os.environ.get("POSTGRES_IAM_USER"),
30-
reason="POSTGRES_IAM_USER env var not set for IAM Authn tests",
31-
),
32-
pytest.mark.skipif(
33-
not hasattr(socket, "AF_UNIX"),
34-
reason="Unix domain sockets (AF_UNIX) not available on this platform",
35-
),
36-
]
25+
# Skip all tests in this file if POSTGRES_IAM_USER is not set
26+
pytestmark = pytest.mark.skipif(
27+
not os.environ.get("POSTGRES_IAM_USER"),
28+
reason="POSTGRES_IAM_USER env var not set for IAM Authn tests",
29+
)
3730

3831

3932
def create_sqlalchemy_engine(

0 commit comments

Comments
 (0)