google-cloud-spark-connect 1.0.0__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- google/cloud/managed_spark_connect/__init__.py +30 -0
- google/cloud/managed_spark_connect/client/__init__.py +14 -0
- google/cloud/managed_spark_connect/client/core.py +141 -0
- google/cloud/managed_spark_connect/client/proxy.py +269 -0
- google/cloud/managed_spark_connect/environment.py +190 -0
- google/cloud/managed_spark_connect/exceptions.py +27 -0
- google/cloud/managed_spark_connect/pypi_artifacts.py +48 -0
- google/cloud/managed_spark_connect/session.py +1383 -0
- google/cloud/managed_spark_magics/__init__.py +19 -0
- google/cloud/managed_spark_magics/magics.py +76 -0
- google_cloud_spark_connect-1.0.0.dist-info/METADATA +268 -0
- google_cloud_spark_connect-1.0.0.dist-info/RECORD +15 -0
- google_cloud_spark_connect-1.0.0.dist-info/WHEEL +6 -0
- google_cloud_spark_connect-1.0.0.dist-info/licenses/LICENSE +201 -0
- google_cloud_spark_connect-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
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
|
+
import importlib.metadata
|
|
15
|
+
import warnings
|
|
16
|
+
|
|
17
|
+
from .session import ManagedSparkSession
|
|
18
|
+
|
|
19
|
+
old_package_names = ["google-spark-connect", "dataproc-spark-connect"]
|
|
20
|
+
current_package_name = "google-cloud-spark-connect"
|
|
21
|
+
for old_package_name in old_package_names:
|
|
22
|
+
try:
|
|
23
|
+
importlib.metadata.distribution(old_package_name)
|
|
24
|
+
warnings.warn(
|
|
25
|
+
f"Package '{old_package_name}' is already installed in your environment. "
|
|
26
|
+
f"This might cause conflicts with '{current_package_name}'. "
|
|
27
|
+
f"Consider uninstalling '{old_package_name}' and only install '{current_package_name}'."
|
|
28
|
+
)
|
|
29
|
+
except Exception:
|
|
30
|
+
pass
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
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
|
+
from .core import ManagedSparkChannelBuilder
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# Copyright 2024 Google LLC
|
|
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
|
+
import logging
|
|
15
|
+
|
|
16
|
+
import google
|
|
17
|
+
import grpc
|
|
18
|
+
from pyspark.sql.connect.client import DefaultChannelBuilder
|
|
19
|
+
|
|
20
|
+
from . import proxy
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ManagedSparkChannelBuilder(DefaultChannelBuilder):
|
|
26
|
+
"""
|
|
27
|
+
This is a helper class that is used to create a GRPC channel based on the given
|
|
28
|
+
connection string per the documentation of Spark Connect.
|
|
29
|
+
|
|
30
|
+
This implementation of ChannelBuilder uses `secure_authorized_channel` from the
|
|
31
|
+
`google.auth.transport.grpc` package for authenticating secure channel.
|
|
32
|
+
|
|
33
|
+
Examples
|
|
34
|
+
--------
|
|
35
|
+
>>> cb = ChannelBuilder("sc://localhost")
|
|
36
|
+
... cb.endpoint
|
|
37
|
+
|
|
38
|
+
>>> cb = ChannelBuilder("sc://localhost/;use_ssl=true;token=aaa")
|
|
39
|
+
... cb.secure
|
|
40
|
+
True
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, url, is_active_callback=None):
|
|
44
|
+
self._is_active_callback = is_active_callback
|
|
45
|
+
super().__init__(url)
|
|
46
|
+
|
|
47
|
+
def toChannel(self) -> grpc.Channel:
|
|
48
|
+
"""
|
|
49
|
+
Applies the parameters of the connection string and creates a new
|
|
50
|
+
GRPC channel according to the configuration. Passes optional channel options to
|
|
51
|
+
construct the channel.
|
|
52
|
+
|
|
53
|
+
Returns
|
|
54
|
+
-------
|
|
55
|
+
GRPC Channel instance.
|
|
56
|
+
"""
|
|
57
|
+
# TODO: Replace with a direct channel once all compatibility issues with
|
|
58
|
+
# grpc have been resolved.
|
|
59
|
+
return self._proxied_channel()
|
|
60
|
+
|
|
61
|
+
def _proxied_channel(self) -> grpc.Channel:
|
|
62
|
+
return ProxiedChannel(self.host, self._is_active_callback)
|
|
63
|
+
|
|
64
|
+
def _direct_channel(self) -> grpc.Channel:
|
|
65
|
+
destination = f"{self.host}:{self.port}"
|
|
66
|
+
|
|
67
|
+
credentials, project = google.auth.default(
|
|
68
|
+
scopes=["https://www.googleapis.com/auth/cloud-platform"]
|
|
69
|
+
)
|
|
70
|
+
# Get an HTTP request function to refresh credentials.
|
|
71
|
+
request = google.auth.transport.requests.Request()
|
|
72
|
+
# Create a channel.
|
|
73
|
+
|
|
74
|
+
return google.auth.transport.grpc.secure_authorized_channel(
|
|
75
|
+
credentials,
|
|
76
|
+
request,
|
|
77
|
+
destination,
|
|
78
|
+
None,
|
|
79
|
+
None,
|
|
80
|
+
options=self._channel_options,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class ProxiedChannel(grpc.Channel):
|
|
85
|
+
|
|
86
|
+
def __init__(self, target_host, is_active_callback):
|
|
87
|
+
self._is_active_callback = is_active_callback
|
|
88
|
+
self._proxy = proxy.ManagedSparkSessionProxy(0, target_host)
|
|
89
|
+
self._proxy.start()
|
|
90
|
+
self._proxied_connect_url = f"sc://localhost:{self._proxy.port}"
|
|
91
|
+
self._wrapped = DefaultChannelBuilder(
|
|
92
|
+
self._proxied_connect_url
|
|
93
|
+
).toChannel()
|
|
94
|
+
|
|
95
|
+
def __enter__(self):
|
|
96
|
+
return self
|
|
97
|
+
|
|
98
|
+
def __exit__(self, *args):
|
|
99
|
+
ret = self._wrapped.__exit__(*args)
|
|
100
|
+
self._proxy.stop()
|
|
101
|
+
return ret
|
|
102
|
+
|
|
103
|
+
def close(self):
|
|
104
|
+
ret = self._wrapped.close()
|
|
105
|
+
self._proxy.stop()
|
|
106
|
+
return ret
|
|
107
|
+
|
|
108
|
+
def _wrap_method(self, wrapped_method):
|
|
109
|
+
if self._is_active_callback is None:
|
|
110
|
+
return wrapped_method
|
|
111
|
+
|
|
112
|
+
def checked_method(*margs, **mkwargs):
|
|
113
|
+
if (
|
|
114
|
+
self._is_active_callback is not None
|
|
115
|
+
and not self._is_active_callback()
|
|
116
|
+
):
|
|
117
|
+
logger.warning(f"Session is no longer active")
|
|
118
|
+
raise RuntimeError(
|
|
119
|
+
"Session not active. Please create a new session"
|
|
120
|
+
)
|
|
121
|
+
return wrapped_method(*margs, **mkwargs)
|
|
122
|
+
|
|
123
|
+
return checked_method
|
|
124
|
+
|
|
125
|
+
def stream_stream(self, *args, **kwargs):
|
|
126
|
+
return self._wrap_method(self._wrapped.stream_stream(*args, **kwargs))
|
|
127
|
+
|
|
128
|
+
def stream_unary(self, *args, **kwargs):
|
|
129
|
+
return self._wrap_method(self._wrapped.stream_unary(*args, **kwargs))
|
|
130
|
+
|
|
131
|
+
def subscribe(self, *args, **kwargs):
|
|
132
|
+
return self._wrap_method(self._wrapped.subscribe(*args, **kwargs))
|
|
133
|
+
|
|
134
|
+
def unary_stream(self, *args, **kwargs):
|
|
135
|
+
return self._wrap_method(self._wrapped.unary_stream(*args, **kwargs))
|
|
136
|
+
|
|
137
|
+
def unary_unary(self, *args, **kwargs):
|
|
138
|
+
return self._wrap_method(self._wrapped.unary_unary(*args, **kwargs))
|
|
139
|
+
|
|
140
|
+
def unsubscribe(self, *args, **kwargs):
|
|
141
|
+
return self._wrap_method(self._wrapped.unsubscribe(*args, **kwargs))
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
#!/bin/env python
|
|
2
|
+
|
|
3
|
+
# Copyright 2024 Google LLC
|
|
4
|
+
#
|
|
5
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# you may not use this file except in compliance with the License.
|
|
7
|
+
# You may obtain a copy of the License at
|
|
8
|
+
#
|
|
9
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
#
|
|
11
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# See the License for the specific language governing permissions and
|
|
15
|
+
# limitations under the License.
|
|
16
|
+
import argparse
|
|
17
|
+
import contextlib
|
|
18
|
+
import logging
|
|
19
|
+
import socket
|
|
20
|
+
import threading
|
|
21
|
+
|
|
22
|
+
import websockets.sync.client as websocketclient
|
|
23
|
+
|
|
24
|
+
from google import auth as googleauth
|
|
25
|
+
from google.auth.transport import requests as googleauthrequests
|
|
26
|
+
|
|
27
|
+
parser = argparse.ArgumentParser()
|
|
28
|
+
parser.add_argument("port")
|
|
29
|
+
parser.add_argument("target_host")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class bridged_socket(object):
|
|
36
|
+
"""Socket-like object that uses a websocket-over-TCP Bridge transport.
|
|
37
|
+
|
|
38
|
+
See: https://github.com/google/inverting-proxy/tree/master/utils/tcpbridge
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, websocket_conn):
|
|
42
|
+
self._conn = websocket_conn
|
|
43
|
+
|
|
44
|
+
def recv(self, buff_size):
|
|
45
|
+
# N.B. The websockets [recv method](https://websockets.readthedocs.io/en/stable/reference/sync/client.html#websockets.sync.client.ClientConnection.recv)
|
|
46
|
+
# does not support the buff_size parameter, but it does add a `timeout` keyword parameter not supported by normal
|
|
47
|
+
# socket objects.
|
|
48
|
+
#
|
|
49
|
+
# We set that timeout to 60 seconds to prevent any scenarios where we wind up stuck waiting for a message from a websocket connection
|
|
50
|
+
# that never comes.
|
|
51
|
+
msg = self._conn.recv(timeout=60)
|
|
52
|
+
return bytes.fromhex(msg)
|
|
53
|
+
|
|
54
|
+
def send(self, msg_bytes):
|
|
55
|
+
msg = bytes.hex(msg_bytes)
|
|
56
|
+
self._conn.send(msg)
|
|
57
|
+
|
|
58
|
+
def close(self):
|
|
59
|
+
return self._conn.close()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def connect_tcp_bridge(hostname):
|
|
63
|
+
"""Create a socket-like connection to the given hostname using websocket.
|
|
64
|
+
|
|
65
|
+
The backend server connected to over the websocket connection must be
|
|
66
|
+
running the TCP-bridge backend corresponding to this frontend.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
hostname: The hostname of the server running the TCP-bridge backend.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
A socket-like object with `recv` and `send` methods.
|
|
73
|
+
"""
|
|
74
|
+
path = "tcp-over-websocket-bridge/35218cb7-1201-4940-89e8-48d8f03fed96"
|
|
75
|
+
creds, _ = googleauth.default(
|
|
76
|
+
scopes=["https://www.googleapis.com/auth/cloud-platform"]
|
|
77
|
+
)
|
|
78
|
+
creds.refresh(googleauthrequests.Request())
|
|
79
|
+
|
|
80
|
+
return websocketclient.connect(
|
|
81
|
+
f"wss://{hostname}/{path}",
|
|
82
|
+
additional_headers={"Authorization": f"Bearer {creds.token}"},
|
|
83
|
+
open_timeout=30,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def forward_bytes(name, from_sock, to_sock):
|
|
88
|
+
"""Continuously stream bytes from the `from_sock` to the `to_sock`.
|
|
89
|
+
|
|
90
|
+
This method terminates when either the `from_sock` is closed (causing
|
|
91
|
+
it to return a Falsy value from its `recv` method), or the first time
|
|
92
|
+
it hits an exception.
|
|
93
|
+
|
|
94
|
+
This method is intended to be run in a separate thread of execution.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
name: forwarding thread name
|
|
98
|
+
from_sock: A socket-like object to stream bytes from.
|
|
99
|
+
to_sock: A socket-like object to stream bytes to.
|
|
100
|
+
"""
|
|
101
|
+
while True:
|
|
102
|
+
try:
|
|
103
|
+
bs = from_sock.recv(1024)
|
|
104
|
+
if not bs:
|
|
105
|
+
to_sock.close()
|
|
106
|
+
return
|
|
107
|
+
attempt = 0
|
|
108
|
+
while bs and (attempt < 10):
|
|
109
|
+
attempt += 1
|
|
110
|
+
try:
|
|
111
|
+
to_sock.send(bs)
|
|
112
|
+
bs = None
|
|
113
|
+
except TimeoutError:
|
|
114
|
+
# On timeouts during a send, we retry just the send
|
|
115
|
+
# to make sure we don't lose any bytes.
|
|
116
|
+
pass
|
|
117
|
+
if bs:
|
|
118
|
+
raise Exception(f"Failed to forward bytes for {name}")
|
|
119
|
+
except TimeoutError:
|
|
120
|
+
# On timeouts during a receive, we retry the entire flow.
|
|
121
|
+
pass
|
|
122
|
+
except Exception as ex:
|
|
123
|
+
logger.debug(f"[{name}] Exception forwarding bytes: {ex}")
|
|
124
|
+
to_sock.close()
|
|
125
|
+
return
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def connect_sockets(conn_number, from_sock, to_sock):
|
|
129
|
+
"""Create a connection between the two given ports.
|
|
130
|
+
|
|
131
|
+
This method continuously streams bytes in both directions between the
|
|
132
|
+
given `from_sock` and `to_sock` socket-like objects.
|
|
133
|
+
|
|
134
|
+
The caller is responsible for creating and closing the supplied sockets.
|
|
135
|
+
"""
|
|
136
|
+
forward_name = f"{conn_number}-forward"
|
|
137
|
+
t1 = threading.Thread(
|
|
138
|
+
name=forward_name,
|
|
139
|
+
target=forward_bytes,
|
|
140
|
+
args=[forward_name, from_sock, to_sock],
|
|
141
|
+
daemon=True,
|
|
142
|
+
)
|
|
143
|
+
t1.start()
|
|
144
|
+
backward_name = f"{conn_number}-backward"
|
|
145
|
+
t2 = threading.Thread(
|
|
146
|
+
name=backward_name,
|
|
147
|
+
target=forward_bytes,
|
|
148
|
+
args=[backward_name, to_sock, from_sock],
|
|
149
|
+
daemon=True,
|
|
150
|
+
)
|
|
151
|
+
t2.start()
|
|
152
|
+
t1.join()
|
|
153
|
+
t2.join()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def forward_connection(conn_number, conn, addr, target_host):
|
|
157
|
+
"""Create a connection to the target and forward `conn` to it.
|
|
158
|
+
|
|
159
|
+
This method creates a socket-like object holding a connection to the given
|
|
160
|
+
target host, and then continuously streams bytes in both directions between
|
|
161
|
+
`conn` and that newly created connection.
|
|
162
|
+
|
|
163
|
+
Both the supplied incoming connection (`conn`) and the created outgoing
|
|
164
|
+
connection are automatically closed when this method terminates.
|
|
165
|
+
|
|
166
|
+
This method should be run inside a daemon thread so that it will not
|
|
167
|
+
block program termination.
|
|
168
|
+
"""
|
|
169
|
+
with conn:
|
|
170
|
+
with connect_tcp_bridge(target_host) as websocket_conn:
|
|
171
|
+
backend_socket = bridged_socket(websocket_conn)
|
|
172
|
+
# Set a timeout on how long we will allow send/recv calls to block
|
|
173
|
+
#
|
|
174
|
+
# The code that reads and writes to this connection will retry
|
|
175
|
+
# on timeouts, so this is a safe change.
|
|
176
|
+
conn.settimeout(10)
|
|
177
|
+
connect_sockets(conn_number, conn, backend_socket)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class ManagedSparkSessionProxy(object):
|
|
181
|
+
"""A TCP proxy for forwarding requests to Dataproc Serverless Sessions.
|
|
182
|
+
|
|
183
|
+
Spark Connect clients connect to this proxy using the h2c (without-SSL)
|
|
184
|
+
protocol, and this proxy adds SSL by tunneling those connections over
|
|
185
|
+
an HTTPS/WebSocket connection to the backend server.
|
|
186
|
+
|
|
187
|
+
The tunneled requests are authenticated using the Google Application
|
|
188
|
+
Default Credentials.
|
|
189
|
+
"""
|
|
190
|
+
|
|
191
|
+
def __init__(self, port, target_host):
|
|
192
|
+
self._port = port
|
|
193
|
+
self._target_host = target_host
|
|
194
|
+
self._started = False
|
|
195
|
+
self._killed = False
|
|
196
|
+
self._conn_number = 0
|
|
197
|
+
|
|
198
|
+
@property
|
|
199
|
+
def port(self):
|
|
200
|
+
"""The local port the proxy is listening on"""
|
|
201
|
+
return self._port
|
|
202
|
+
|
|
203
|
+
def start(self, daemon=True):
|
|
204
|
+
"""Start the proxy.
|
|
205
|
+
|
|
206
|
+
By the time this method returns the proxy has already started listening
|
|
207
|
+
on its local port will accept incoming connections.
|
|
208
|
+
"""
|
|
209
|
+
if self._started:
|
|
210
|
+
raise Exception("Managed Spark session proxy already started")
|
|
211
|
+
self._started = True
|
|
212
|
+
s = threading.Semaphore(value=0)
|
|
213
|
+
t = threading.Thread(target=self._run, args=[s], daemon=daemon)
|
|
214
|
+
t.start()
|
|
215
|
+
s.acquire()
|
|
216
|
+
|
|
217
|
+
def _run(self, s):
|
|
218
|
+
with socket.create_server(("127.0.0.1", self._port)) as frontend_socket:
|
|
219
|
+
if self._port == 0:
|
|
220
|
+
self._port = frontend_socket.getsockname()[1]
|
|
221
|
+
s.release()
|
|
222
|
+
while not self._killed:
|
|
223
|
+
conn, addr = frontend_socket.accept()
|
|
224
|
+
logger.debug(f"Accepted a connection from {addr}...")
|
|
225
|
+
self._conn_number += 1
|
|
226
|
+
threading.Thread(
|
|
227
|
+
target=forward_connection,
|
|
228
|
+
args=[self._conn_number, conn, addr, self._target_host],
|
|
229
|
+
daemon=True,
|
|
230
|
+
).start()
|
|
231
|
+
|
|
232
|
+
def stop(self):
|
|
233
|
+
"""Stop the proxy."""
|
|
234
|
+
self._killed = True
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@contextlib.contextmanager
|
|
238
|
+
def managed_spark_session_proxy(port, target_host):
|
|
239
|
+
"""Context manager for creating a Managed Spark session proxy.
|
|
240
|
+
|
|
241
|
+
Usage:
|
|
242
|
+
with managed_spark_session_proxy(0, backend_hostname) as p:
|
|
243
|
+
local_port = p.port
|
|
244
|
+
...
|
|
245
|
+
|
|
246
|
+
Args:
|
|
247
|
+
port: The local port to listen on. Use `0` to pick a free port.
|
|
248
|
+
target_host: The backend to proxy connections to.
|
|
249
|
+
|
|
250
|
+
Returns:
|
|
251
|
+
A context manager wrapping a ManagedSparkSessionProxy instance.
|
|
252
|
+
"""
|
|
253
|
+
proxy = ManagedSparkSessionProxy(port, target_host)
|
|
254
|
+
try:
|
|
255
|
+
proxy.start(daemon=False)
|
|
256
|
+
yield proxy
|
|
257
|
+
finally:
|
|
258
|
+
proxy.stop()
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
if __name__ == "__main__":
|
|
262
|
+
args = parser.parse_args()
|
|
263
|
+
with managed_spark_session_proxy(int(args.port), args.target_host) as p:
|
|
264
|
+
print(f"Proxy listening on port {p.port}")
|
|
265
|
+
try:
|
|
266
|
+
while True:
|
|
267
|
+
pass
|
|
268
|
+
except KeyboardInterrupt:
|
|
269
|
+
pass
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
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
|
+
# https://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
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
from typing import Callable, Tuple, List
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def is_antigravity() -> bool:
|
|
21
|
+
"""True if running inside the Antigravity environment."""
|
|
22
|
+
return "antigravity" in os.getenv("__CFBundleIdentifier", "").lower()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def is_vscode() -> bool:
|
|
26
|
+
"""True if running inside VS Code at all."""
|
|
27
|
+
return os.getenv("VSCODE_PID") is not None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def is_jupyter() -> bool:
|
|
31
|
+
"""True if running in a Jupyter environment."""
|
|
32
|
+
return os.getenv("JPY_PARENT_PID") is not None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def is_colab_enterprise() -> bool:
|
|
36
|
+
"""True if running in Colab Enterprise (Vertex AI)."""
|
|
37
|
+
return os.getenv("VERTEX_PRODUCT") == "COLAB_ENTERPRISE"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def is_colab() -> bool:
|
|
41
|
+
"""True if running in Google Colab."""
|
|
42
|
+
return os.getenv("COLAB_RELEASE_TAG") is not None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def is_workbench() -> bool:
|
|
46
|
+
"""True if running in Vertex Workbench Instance (managed Jupyter)."""
|
|
47
|
+
return os.getenv("VERTEX_PRODUCT") == "WORKBENCH_INSTANCE"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def is_kaggle() -> bool:
|
|
51
|
+
"""True if running in Kaggle Notebooks."""
|
|
52
|
+
return os.getenv("KAGGLE_KERNEL_RUN_TYPE") is not None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def is_databricks() -> bool:
|
|
56
|
+
"""True if running in Databricks."""
|
|
57
|
+
return os.getenv("DATABRICKS_RUNTIME_VERSION") is not None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def is_sagemaker() -> bool:
|
|
61
|
+
"""True if running in AWS SageMaker."""
|
|
62
|
+
return os.getenv("SAGEMAKER_INTERNAL_IMAGE_URI") is not None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def is_deepnote() -> bool:
|
|
66
|
+
"""True if running in Deepnote."""
|
|
67
|
+
return os.getenv("DEEPNOTE_PROJECT_ID") is not None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def is_datalore() -> bool:
|
|
71
|
+
"""True if running in JetBrains Datalore."""
|
|
72
|
+
return os.getenv("DATALORE_USER") is not None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def is_spyder() -> bool:
|
|
76
|
+
"""True if running inside Spyder IDE."""
|
|
77
|
+
return any(k.startswith("SPYDER") for k in os.environ)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def is_cloud_shell() -> bool:
|
|
81
|
+
"""True if running in Google Cloud Shell."""
|
|
82
|
+
return os.getenv("CLOUD_SHELL") is not None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def is_codespaces() -> bool:
|
|
86
|
+
"""True if running in GitHub Codespaces."""
|
|
87
|
+
return os.getenv("CODESPACES") is not None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def is_jetbrains_ide() -> bool:
|
|
91
|
+
"""True if running inside JetBrains IDE."""
|
|
92
|
+
return (
|
|
93
|
+
"jetbrains" in os.getenv("TERMINAL_EMULATOR", "").lower()
|
|
94
|
+
or "PYCHARM_HOSTED" in os.environ
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def is_hex() -> bool:
|
|
99
|
+
"""True if running in Hex."""
|
|
100
|
+
return os.getenv("HEX_PROJECT_ID") is not None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def is_polynote() -> bool:
|
|
104
|
+
"""True if running in Polynote."""
|
|
105
|
+
return os.getenv("POLYNOTE_VERSION") is not None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def is_eclipse() -> bool:
|
|
109
|
+
"""True if running inside Eclipse IDE."""
|
|
110
|
+
return "ECLIPSE_HOME" in os.environ or any(
|
|
111
|
+
k.startswith("ECLIPSE") for k in os.environ
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def is_interactive() -> bool:
|
|
116
|
+
try:
|
|
117
|
+
from IPython import get_ipython
|
|
118
|
+
|
|
119
|
+
if get_ipython() is not None:
|
|
120
|
+
return True
|
|
121
|
+
except ImportError:
|
|
122
|
+
pass
|
|
123
|
+
|
|
124
|
+
return hasattr(sys, "ps1") or bool(sys.flags.interactive)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def is_terminal() -> bool:
|
|
128
|
+
return sys.stdin.isatty()
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def is_interactive_terminal() -> bool:
|
|
132
|
+
return is_interactive() and is_terminal()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def is_dataproc_batch() -> bool:
|
|
136
|
+
return os.getenv("DATAPROC_WORKLOAD_TYPE") == "batch"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def get_client_environment_label() -> str:
|
|
140
|
+
"""
|
|
141
|
+
Map current environment to a standardized client label.
|
|
142
|
+
|
|
143
|
+
Priority order:
|
|
144
|
+
1. Colab Enterprise ("colab-enterprise")
|
|
145
|
+
2. Colab ("colab")
|
|
146
|
+
3. Vertex Workbench Instance ("workbench-jupyter")
|
|
147
|
+
4. Kaggle ("kaggle")
|
|
148
|
+
5. AWS SageMaker ("sagemaker")
|
|
149
|
+
6. Databricks ("databricks")
|
|
150
|
+
7. Deepnote ("deepnote")
|
|
151
|
+
8. JetBrains Datalore ("datalore")
|
|
152
|
+
9. GitHub Codespaces ("codespaces")
|
|
153
|
+
10. Google Cloud Shell ("cloud-shell")
|
|
154
|
+
11. Hex ("hex")
|
|
155
|
+
12. Polynote ("polynote")
|
|
156
|
+
13. Antigravity ("antigravity")
|
|
157
|
+
14. VS Code ("vscode")
|
|
158
|
+
15. JetBrains IDE ("jetbrains")
|
|
159
|
+
16. Spyder ("spyder")
|
|
160
|
+
17. Eclipse ("eclipse")
|
|
161
|
+
18. Jupyter ("jupyter")
|
|
162
|
+
19. Unknown ("unknown")
|
|
163
|
+
"""
|
|
164
|
+
checks: List[Tuple[Callable[[], bool], str]] = [
|
|
165
|
+
(is_colab_enterprise, "colab-enterprise"),
|
|
166
|
+
(is_colab, "colab"),
|
|
167
|
+
(is_workbench, "workbench-jupyter"),
|
|
168
|
+
(is_kaggle, "kaggle"),
|
|
169
|
+
(is_sagemaker, "sagemaker"),
|
|
170
|
+
(is_databricks, "databricks"),
|
|
171
|
+
(is_deepnote, "deepnote"),
|
|
172
|
+
(is_datalore, "datalore"),
|
|
173
|
+
(is_codespaces, "codespaces"),
|
|
174
|
+
(is_cloud_shell, "cloud-shell"),
|
|
175
|
+
(is_hex, "hex"),
|
|
176
|
+
(is_polynote, "polynote"),
|
|
177
|
+
(is_antigravity, "antigravity"),
|
|
178
|
+
(is_vscode, "vscode"),
|
|
179
|
+
(is_jetbrains_ide, "jetbrains"),
|
|
180
|
+
(is_spyder, "spyder"),
|
|
181
|
+
(is_eclipse, "eclipse"),
|
|
182
|
+
(is_jupyter, "jupyter"),
|
|
183
|
+
]
|
|
184
|
+
for detector, label in checks:
|
|
185
|
+
try:
|
|
186
|
+
if detector():
|
|
187
|
+
return label
|
|
188
|
+
except Exception:
|
|
189
|
+
pass
|
|
190
|
+
return "unknown"
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
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
|
+
|
|
16
|
+
class ManagedSparkConnectException(Exception):
|
|
17
|
+
"""A custom exception class to only print the error messages.
|
|
18
|
+
This would be used for exceptions where the stack trace
|
|
19
|
+
doesn't provide any additional information.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, message):
|
|
23
|
+
self.message = message
|
|
24
|
+
super().__init__(message)
|
|
25
|
+
|
|
26
|
+
def _render_traceback_(self):
|
|
27
|
+
return [self.message]
|