dataproc-spark-connect 0.1.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.
- dataproc_spark_connect-0.1.0.dist-info/LICENSE +201 -0
- dataproc_spark_connect-0.1.0.dist-info/METADATA +11 -0
- dataproc_spark_connect-0.1.0.dist-info/RECORD +10 -0
- dataproc_spark_connect-0.1.0.dist-info/WHEEL +6 -0
- dataproc_spark_connect-0.1.0.dist-info/top_level.txt +1 -0
- google/cloud/dataproc_spark_connect/__init__.py +14 -0
- google/cloud/dataproc_spark_connect/client/__init__.py +14 -0
- google/cloud/dataproc_spark_connect/client/core.py +113 -0
- google/cloud/dataproc_spark_connect/client/proxy.py +227 -0
- google/cloud/dataproc_spark_connect/session.py +540 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: dataproc-spark-connect
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Dataproc client library for Spark Connect
|
|
5
|
+
License-File: LICENSE
|
|
6
|
+
Requires-Dist: wheel
|
|
7
|
+
Requires-Dist: websockets
|
|
8
|
+
Requires-Dist: pyspark >=3.5
|
|
9
|
+
Requires-Dist: pandas
|
|
10
|
+
Requires-Dist: pyarrow
|
|
11
|
+
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
google/cloud/dataproc_spark_connect/__init__.py,sha256=pybAofW6rmWI-4C8VYm1q0NOZD_sBvFQz43jUBSQW30,616
|
|
2
|
+
google/cloud/dataproc_spark_connect/session.py,sha256=XCOym1Llp_vXCgMQ0EMsORoImY1BSKfJrZpooGCurNc,23013
|
|
3
|
+
google/cloud/dataproc_spark_connect/client/__init__.py,sha256=6hCNSsgYlie6GuVpc5gjFsPnyeMTScTpXSPYqp1fplY,615
|
|
4
|
+
google/cloud/dataproc_spark_connect/client/core.py,sha256=7Wy6QwkcWxlHBdo4NsktJEknggPpGkx9F5CS5IpQ7iM,3630
|
|
5
|
+
google/cloud/dataproc_spark_connect/client/proxy.py,sha256=o5ppDkvUUQLy4uDMjW6roTMgRFKlVfQm5faC5b60rRk,7263
|
|
6
|
+
dataproc_spark_connect-0.1.0.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
7
|
+
dataproc_spark_connect-0.1.0.dist-info/METADATA,sha256=Ke0zfRLuybTquQJgm-Ve3t8tVMT26l6q5i3R8wUEwq4,261
|
|
8
|
+
dataproc_spark_connect-0.1.0.dist-info/WHEEL,sha256=ED2S3aolPA63OeAfpmbtiQd0NXmZX4SrTHXvXF6JNGc,109
|
|
9
|
+
dataproc_spark_connect-0.1.0.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7
|
|
10
|
+
dataproc_spark_connect-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
google
|
|
@@ -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 .session import DataprocSparkSession
|
|
@@ -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 DataprocChannelBuilder
|
|
@@ -0,0 +1,113 @@
|
|
|
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 google
|
|
15
|
+
import grpc
|
|
16
|
+
from pyspark.sql.connect.client import ChannelBuilder
|
|
17
|
+
|
|
18
|
+
from . import proxy
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class DataprocChannelBuilder(ChannelBuilder):
|
|
22
|
+
"""
|
|
23
|
+
This is a helper class that is used to create a GRPC channel based on the given
|
|
24
|
+
connection string per the documentation of Spark Connect.
|
|
25
|
+
|
|
26
|
+
This implementation of ChannelBuilder uses `secure_authorized_channel` from the
|
|
27
|
+
`google.auth.transport.grpc` package for authenticating secure channel.
|
|
28
|
+
|
|
29
|
+
Examples
|
|
30
|
+
--------
|
|
31
|
+
>>> cb = ChannelBuilder("sc://localhost")
|
|
32
|
+
... cb.endpoint
|
|
33
|
+
|
|
34
|
+
>>> cb = ChannelBuilder("sc://localhost/;use_ssl=true;token=aaa")
|
|
35
|
+
... cb.secure
|
|
36
|
+
True
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def toChannel(self) -> grpc.Channel:
|
|
40
|
+
"""
|
|
41
|
+
Applies the parameters of the connection string and creates a new
|
|
42
|
+
GRPC channel according to the configuration. Passes optional channel options to
|
|
43
|
+
construct the channel.
|
|
44
|
+
|
|
45
|
+
Returns
|
|
46
|
+
-------
|
|
47
|
+
GRPC Channel instance.
|
|
48
|
+
"""
|
|
49
|
+
# TODO: Replace with a direct channel once all compatibility issues with
|
|
50
|
+
# grpc have been resolved.
|
|
51
|
+
return self._proxied_channel()
|
|
52
|
+
|
|
53
|
+
def _proxied_channel(self) -> grpc.Channel:
|
|
54
|
+
return ProxiedChannel(self.host)
|
|
55
|
+
|
|
56
|
+
def _direct_channel(self) -> grpc.Channel:
|
|
57
|
+
destination = f"{self.host}:{self.port}"
|
|
58
|
+
|
|
59
|
+
credentials, project = google.auth.default(
|
|
60
|
+
scopes=["https://www.googleapis.com/auth/cloud-platform"]
|
|
61
|
+
)
|
|
62
|
+
# Get an HTTP request function to refresh credentials.
|
|
63
|
+
request = google.auth.transport.requests.Request()
|
|
64
|
+
# Create a channel.
|
|
65
|
+
|
|
66
|
+
return google.auth.transport.grpc.secure_authorized_channel(
|
|
67
|
+
credentials,
|
|
68
|
+
request,
|
|
69
|
+
destination,
|
|
70
|
+
None,
|
|
71
|
+
None,
|
|
72
|
+
options=self._channel_options,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ProxiedChannel(grpc.Channel):
|
|
77
|
+
|
|
78
|
+
def __init__(self, target_host):
|
|
79
|
+
self._proxy = proxy.DataprocSessionProxy(0, target_host)
|
|
80
|
+
self._proxy.start()
|
|
81
|
+
self._proxied_connect_url = f"sc://localhost:{self._proxy.port}"
|
|
82
|
+
self._wrapped = ChannelBuilder(self._proxied_connect_url).toChannel()
|
|
83
|
+
|
|
84
|
+
def __enter__(self):
|
|
85
|
+
return self
|
|
86
|
+
|
|
87
|
+
def __exit__(self, *args):
|
|
88
|
+
ret = self._wrapped.__exit__(*args)
|
|
89
|
+
self._proxy.stop()
|
|
90
|
+
return ret
|
|
91
|
+
|
|
92
|
+
def close(self):
|
|
93
|
+
ret = self._wrapped.close()
|
|
94
|
+
self._proxy.stop()
|
|
95
|
+
return ret
|
|
96
|
+
|
|
97
|
+
def stream_stream(self, *args, **kwargs):
|
|
98
|
+
return self._wrapped.stream_stream(*args, **kwargs)
|
|
99
|
+
|
|
100
|
+
def stream_unary(self, *args, **kwargs):
|
|
101
|
+
return self._wrapped.stream_unary(*args, **kwargs)
|
|
102
|
+
|
|
103
|
+
def subscribe(self, *args, **kwargs):
|
|
104
|
+
return self._wrapped.subscribe(*args, **kwargs)
|
|
105
|
+
|
|
106
|
+
def unary_stream(self, *args, **kwargs):
|
|
107
|
+
return self._wrapped.unary_stream(*args, **kwargs)
|
|
108
|
+
|
|
109
|
+
def unary_unary(self, *args, **kwargs):
|
|
110
|
+
return self._wrapped.unary_unary(*args, **kwargs)
|
|
111
|
+
|
|
112
|
+
def unsubscribe(self, *args, **kwargs):
|
|
113
|
+
return self._wrapped.unsubscribe(*args, **kwargs)
|
|
@@ -0,0 +1,227 @@
|
|
|
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
|
+
import time
|
|
22
|
+
|
|
23
|
+
import websockets.sync.client as websocketclient
|
|
24
|
+
|
|
25
|
+
from google import auth as googleauth
|
|
26
|
+
from google.auth.transport import requests as googleauthrequests
|
|
27
|
+
|
|
28
|
+
parser = argparse.ArgumentParser()
|
|
29
|
+
parser.add_argument("port")
|
|
30
|
+
parser.add_argument("target_host")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class bridged_socket(object):
|
|
37
|
+
"""Socket-like object that uses a websocket-over-TCP Bridge transport.
|
|
38
|
+
|
|
39
|
+
See: https://github.com/google/inverting-proxy/tree/master/utils/tcpbridge
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, websocket_conn):
|
|
43
|
+
self._conn = websocket_conn
|
|
44
|
+
|
|
45
|
+
def recv(self, buff_size):
|
|
46
|
+
msg = self._conn.recv()
|
|
47
|
+
return bytes.fromhex(msg)
|
|
48
|
+
|
|
49
|
+
def send(self, msg_bytes):
|
|
50
|
+
msg = bytes.hex(msg_bytes)
|
|
51
|
+
self._conn.send(msg)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def connect_tcp_bridge(hostname):
|
|
55
|
+
"""Create a socket-like connection to the given hostname using websocket.
|
|
56
|
+
|
|
57
|
+
The backend server connected to over the websocket connection must be
|
|
58
|
+
running the TCP-bridge backend corresponding to this frontend.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
hostname: The hostname of the server running the TCP-bridge backend.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
A socket-like object with `recv` and `send` methods.
|
|
65
|
+
"""
|
|
66
|
+
path = "tcp-over-websocket-bridge/35218cb7-1201-4940-89e8-48d8f03fed96"
|
|
67
|
+
creds, _ = googleauth.default(
|
|
68
|
+
scopes=["https://www.googleapis.com/auth/cloud-platform"]
|
|
69
|
+
)
|
|
70
|
+
creds.refresh(googleauthrequests.Request())
|
|
71
|
+
|
|
72
|
+
return websocketclient.connect(
|
|
73
|
+
f"wss://{hostname}/{path}",
|
|
74
|
+
additional_headers={"Authorization": f"Bearer {creds.token}"},
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def forward_bytes(name, from_sock, to_sock):
|
|
79
|
+
"""Continuously stream bytes from the `from_sock` to the `to_sock`.
|
|
80
|
+
|
|
81
|
+
This method terminates when either the `from_sock` is closed (causing
|
|
82
|
+
it to return a Falsy value from its `recv` method), or the first time
|
|
83
|
+
it hits an exception.
|
|
84
|
+
|
|
85
|
+
This method is intended to be run in a separate thread of execution.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
from_sock: A socket-like object to stream bytes from.
|
|
89
|
+
to_sock: A socket-like object to stream bytes to.
|
|
90
|
+
"""
|
|
91
|
+
while True:
|
|
92
|
+
try:
|
|
93
|
+
bs = from_sock.recv(1024)
|
|
94
|
+
if not bs:
|
|
95
|
+
return
|
|
96
|
+
to_sock.send(bs)
|
|
97
|
+
except Exception as ex:
|
|
98
|
+
logger.debug(f"[{name}] Exception forwarding bytes: {ex}")
|
|
99
|
+
return
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def forward_connection(conn_number, conn, addr, target_host):
|
|
103
|
+
"""Create a connection to the target and forward `conn` to it.
|
|
104
|
+
|
|
105
|
+
This method creates a socket-like object holding a connection to the given
|
|
106
|
+
target host, and then continuously streams bytes in both directions between
|
|
107
|
+
`conn` and that newly created connection.
|
|
108
|
+
|
|
109
|
+
Both the supplied incoming connection (`conn`) and the created outgoing
|
|
110
|
+
connection are automatically closed when this method terminates.
|
|
111
|
+
|
|
112
|
+
This method should be run inside of a daemon thread so that it will not
|
|
113
|
+
block program termination.
|
|
114
|
+
"""
|
|
115
|
+
with conn:
|
|
116
|
+
with connect_tcp_bridge(target_host) as websocket_conn:
|
|
117
|
+
backend_socket = bridged_socket(websocket_conn)
|
|
118
|
+
forward_name = f"{conn_number}-forward"
|
|
119
|
+
t1 = threading.Thread(
|
|
120
|
+
name=forward_name,
|
|
121
|
+
target=forward_bytes,
|
|
122
|
+
args=[forward_name, conn, backend_socket],
|
|
123
|
+
daemon=True,
|
|
124
|
+
)
|
|
125
|
+
t1.start()
|
|
126
|
+
backward_name = f"{conn_number}-backward"
|
|
127
|
+
t2 = threading.Thread(
|
|
128
|
+
name=backward_name,
|
|
129
|
+
target=forward_bytes,
|
|
130
|
+
args=[backward_name, backend_socket, conn],
|
|
131
|
+
daemon=True,
|
|
132
|
+
)
|
|
133
|
+
t2.start()
|
|
134
|
+
t1.join()
|
|
135
|
+
t2.join()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class DataprocSessionProxy(object):
|
|
139
|
+
"""A TCP proxy for forwarding requests to Dataproc Serverless Sessions.
|
|
140
|
+
|
|
141
|
+
Spark Connect clients connect to this proxy using the h2c (without-SSL)
|
|
142
|
+
protocol, and this proxy adds SSL by tunneling those connections over
|
|
143
|
+
an HTTPS/WebSocket connection to the backend server.
|
|
144
|
+
|
|
145
|
+
The tunneled requests are authenticated using the Google Application
|
|
146
|
+
Default Credentials.
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
def __init__(self, port, target_host):
|
|
150
|
+
self._port = port
|
|
151
|
+
self._target_host = target_host
|
|
152
|
+
self._started = False
|
|
153
|
+
self._killed = False
|
|
154
|
+
self._conn_number = 0
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def port(self):
|
|
158
|
+
"""The local port the proxy is listening on"""
|
|
159
|
+
return self._port
|
|
160
|
+
|
|
161
|
+
def start(self, daemon=True):
|
|
162
|
+
"""Start the proxy.
|
|
163
|
+
|
|
164
|
+
By the time this method returns the proxy has already started listening
|
|
165
|
+
on its local port will accept incoming connections.
|
|
166
|
+
"""
|
|
167
|
+
if self._started:
|
|
168
|
+
raise Exception("Dataproc session proxy already started")
|
|
169
|
+
self._started = True
|
|
170
|
+
s = threading.Semaphore(value=0)
|
|
171
|
+
t = threading.Thread(target=self._run, args=[s], daemon=daemon)
|
|
172
|
+
t.start()
|
|
173
|
+
s.acquire()
|
|
174
|
+
|
|
175
|
+
def _run(self, s):
|
|
176
|
+
with socket.create_server(("127.0.0.1", self._port)) as frontend_socket:
|
|
177
|
+
if self._port == 0:
|
|
178
|
+
self._port = frontend_socket.getsockname()[1]
|
|
179
|
+
s.release()
|
|
180
|
+
while not self._killed:
|
|
181
|
+
conn, addr = frontend_socket.accept()
|
|
182
|
+
logger.debug(f"Accepted a connection from {addr}...")
|
|
183
|
+
self._conn_number += 1
|
|
184
|
+
threading.Thread(
|
|
185
|
+
target=forward_connection,
|
|
186
|
+
args=[self._conn_number, conn, addr, self._target_host],
|
|
187
|
+
daemon=True,
|
|
188
|
+
).start()
|
|
189
|
+
|
|
190
|
+
def stop(self):
|
|
191
|
+
"""Stop the proxy."""
|
|
192
|
+
self._killed = True
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@contextlib.contextmanager
|
|
196
|
+
def dataproc_session_proxy(port, target_host):
|
|
197
|
+
"""Context manager for creating a Dataproc Session proxy.
|
|
198
|
+
|
|
199
|
+
Usage:
|
|
200
|
+
with dataproc_session_proxy(0, backend_hostname) as p:
|
|
201
|
+
local_port = p.port
|
|
202
|
+
...
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
port: The local port to listen on. Use `0` to pick a free port.
|
|
206
|
+
target_host: The backend to proxy connections to.
|
|
207
|
+
|
|
208
|
+
Returns:
|
|
209
|
+
A context manager wrapping a DataprocSessionProxy instance.
|
|
210
|
+
"""
|
|
211
|
+
proxy = DataprocSessionProxy(port, target_host)
|
|
212
|
+
try:
|
|
213
|
+
proxy.start(daemon=False)
|
|
214
|
+
yield proxy
|
|
215
|
+
finally:
|
|
216
|
+
proxy.stop()
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
if __name__ == "__main__":
|
|
220
|
+
args = parser.parse_args()
|
|
221
|
+
with dataproc_session_proxy(int(args.port), args.target_host) as p:
|
|
222
|
+
print(f"Proxy listening on port {p.port}")
|
|
223
|
+
try:
|
|
224
|
+
while True:
|
|
225
|
+
pass
|
|
226
|
+
except KeyboardInterrupt:
|
|
227
|
+
pass
|
|
@@ -0,0 +1,540 @@
|
|
|
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 json
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
import random
|
|
18
|
+
import string
|
|
19
|
+
import time
|
|
20
|
+
import datetime
|
|
21
|
+
from time import sleep
|
|
22
|
+
from typing import Any, cast, ClassVar, Dict, Optional
|
|
23
|
+
|
|
24
|
+
from google.api_core import retry
|
|
25
|
+
from google.api_core.future.polling import POLLING_PREDICATE
|
|
26
|
+
from google.api_core.client_options import ClientOptions
|
|
27
|
+
from google.api_core.exceptions import FailedPrecondition, InvalidArgument, NotFound
|
|
28
|
+
from google.cloud.dataproc_v1.types import sessions
|
|
29
|
+
|
|
30
|
+
from google.cloud.dataproc_spark_connect.client import DataprocChannelBuilder
|
|
31
|
+
from google.cloud.dataproc_v1 import (
|
|
32
|
+
CreateSessionRequest,
|
|
33
|
+
GetSessionRequest,
|
|
34
|
+
Session,
|
|
35
|
+
SessionControllerClient,
|
|
36
|
+
SessionTemplate,
|
|
37
|
+
TerminateSessionRequest,
|
|
38
|
+
)
|
|
39
|
+
from google.protobuf import text_format
|
|
40
|
+
from google.protobuf.text_format import ParseError
|
|
41
|
+
from pyspark.sql.connect.session import SparkSession
|
|
42
|
+
from pyspark.sql.utils import to_str
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# Set up logging
|
|
46
|
+
logging.basicConfig(level=logging.INFO)
|
|
47
|
+
logger = logging.getLogger(__name__)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class DataprocSparkSession(SparkSession):
|
|
51
|
+
"""The entry point to programming Spark with the Dataset and DataFrame API.
|
|
52
|
+
|
|
53
|
+
A DataprocRemoteSparkSession can be used to create :class:`DataFrame`, register :class:`DataFrame` as
|
|
54
|
+
tables, execute SQL over tables, cache tables, and read parquet files.
|
|
55
|
+
|
|
56
|
+
Examples
|
|
57
|
+
--------
|
|
58
|
+
|
|
59
|
+
Create a Spark session with Dataproc Spark Connect.
|
|
60
|
+
|
|
61
|
+
>>> spark = (
|
|
62
|
+
... DataprocSparkSession.builder
|
|
63
|
+
... .appName("Word Count")
|
|
64
|
+
... .dataprocConfig(Session())
|
|
65
|
+
... .getOrCreate()
|
|
66
|
+
... ) # doctest: +SKIP
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
_active_s8s_session_uuid: ClassVar[Optional[str]] = None
|
|
70
|
+
_project_id = None
|
|
71
|
+
_region = None
|
|
72
|
+
_client_options = None
|
|
73
|
+
_active_s8s_session_id: ClassVar[Optional[str]] = None
|
|
74
|
+
|
|
75
|
+
class Builder(SparkSession.Builder):
|
|
76
|
+
|
|
77
|
+
_dataproc_runtime_spark_version = {"3.0": "3.5.1", "2.2": "3.5.0"}
|
|
78
|
+
|
|
79
|
+
_session_static_configs = [
|
|
80
|
+
"spark.executor.cores",
|
|
81
|
+
"spark.executor.memoryOverhead",
|
|
82
|
+
"spark.executor.memory",
|
|
83
|
+
"spark.driver.memory",
|
|
84
|
+
"spark.driver.cores",
|
|
85
|
+
"spark.eventLog.dir",
|
|
86
|
+
"spark.history.fs.logDirectory",
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
def __init__(self):
|
|
90
|
+
self._options: Dict[str, Any] = {}
|
|
91
|
+
self._channel_builder: Optional[DataprocChannelBuilder] = None
|
|
92
|
+
self._dataproc_config: Optional[Session] = None
|
|
93
|
+
self._project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
|
|
94
|
+
self._region = os.environ.get("GOOGLE_CLOUD_REGION")
|
|
95
|
+
self._client_options = ClientOptions(
|
|
96
|
+
api_endpoint=os.environ.get(
|
|
97
|
+
"GOOGLE_CLOUD_DATAPROC_API_ENDPOINT",
|
|
98
|
+
f"{self._region}-dataproc.googleapis.com",
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
def __apply_options(self, session: "SparkSession") -> None:
|
|
103
|
+
with self._lock:
|
|
104
|
+
self._options = {
|
|
105
|
+
key: value
|
|
106
|
+
for key, value in self._options.items()
|
|
107
|
+
if key not in self._session_static_configs
|
|
108
|
+
}
|
|
109
|
+
self._apply_options(session)
|
|
110
|
+
|
|
111
|
+
def projectId(self, project_id):
|
|
112
|
+
self._project_id = project_id
|
|
113
|
+
return self
|
|
114
|
+
|
|
115
|
+
def region(self, region):
|
|
116
|
+
self._region = region
|
|
117
|
+
self._client_options.api_endpoint = os.environ.get(
|
|
118
|
+
"GOOGLE_CLOUD_DATAPROC_API_ENDPOINT",
|
|
119
|
+
f"{self._region}-dataproc.googleapis.com",
|
|
120
|
+
)
|
|
121
|
+
return self
|
|
122
|
+
|
|
123
|
+
def dataprocConfig(self, dataproc_config: Session):
|
|
124
|
+
with self._lock:
|
|
125
|
+
self._dataproc_config = dataproc_config
|
|
126
|
+
for k, v in dataproc_config.runtime_config.properties.items():
|
|
127
|
+
self._options[cast(str, k)] = to_str(v)
|
|
128
|
+
return self
|
|
129
|
+
|
|
130
|
+
def remote(self, url: Optional[str] = None) -> "SparkSession.Builder":
|
|
131
|
+
if url:
|
|
132
|
+
raise NotImplemented(
|
|
133
|
+
"DataprocSparkSession does not support connecting to an existing remote server"
|
|
134
|
+
)
|
|
135
|
+
else:
|
|
136
|
+
return self
|
|
137
|
+
|
|
138
|
+
def create(self) -> "SparkSession":
|
|
139
|
+
raise NotImplemented(
|
|
140
|
+
"DataprocSparkSession allows session creation only through getOrCreate"
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def __create_spark_connect_session_from_s8s(
|
|
144
|
+
self, session_response
|
|
145
|
+
) -> "SparkSession":
|
|
146
|
+
DataprocSparkSession._active_s8s_session_uuid = (
|
|
147
|
+
session_response.uuid
|
|
148
|
+
)
|
|
149
|
+
DataprocSparkSession._project_id = self._project_id
|
|
150
|
+
DataprocSparkSession._region = self._region
|
|
151
|
+
DataprocSparkSession._client_options = self._client_options
|
|
152
|
+
spark_connect_url = session_response.runtime_info.endpoints.get(
|
|
153
|
+
"Spark Connect Server"
|
|
154
|
+
)
|
|
155
|
+
spark_connect_url = spark_connect_url.replace("https", "sc")
|
|
156
|
+
url = f"{spark_connect_url.replace('.com/', '.com:443/')};session_id={session_response.uuid};use_ssl=true"
|
|
157
|
+
logger.debug(f"Spark Connect URL: {url}")
|
|
158
|
+
self._channel_builder = DataprocChannelBuilder(url)
|
|
159
|
+
|
|
160
|
+
assert self._channel_builder is not None
|
|
161
|
+
session = DataprocSparkSession(connection=self._channel_builder)
|
|
162
|
+
|
|
163
|
+
DataprocSparkSession._set_default_and_active_session(session)
|
|
164
|
+
self.__apply_options(session)
|
|
165
|
+
return session
|
|
166
|
+
|
|
167
|
+
def __create(self) -> "SparkSession":
|
|
168
|
+
with self._lock:
|
|
169
|
+
|
|
170
|
+
if self._options.get("spark.remote", False):
|
|
171
|
+
raise NotImplemented(
|
|
172
|
+
"DataprocSparkSession does not support connecting to an existing remote server"
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
from google.cloud.dataproc_v1 import SessionControllerClient
|
|
176
|
+
|
|
177
|
+
dataproc_config: Session = self._get_dataproc_config()
|
|
178
|
+
session_template: SessionTemplate = self._get_session_template()
|
|
179
|
+
|
|
180
|
+
self._get_and_validate_version(
|
|
181
|
+
dataproc_config, session_template
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
spark_connect_session = self._get_spark_connect_session(
|
|
185
|
+
dataproc_config, session_template
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
spark = self._get_spark(dataproc_config, session_template)
|
|
189
|
+
|
|
190
|
+
if not spark_connect_session:
|
|
191
|
+
dataproc_config.spark_connect_session = {}
|
|
192
|
+
if not spark:
|
|
193
|
+
dataproc_config.spark = {}
|
|
194
|
+
os.environ["SPARK_CONNECT_MODE_ENABLED"] = "1"
|
|
195
|
+
session_request = CreateSessionRequest()
|
|
196
|
+
session_id = self.generate_dataproc_session_id()
|
|
197
|
+
|
|
198
|
+
session_request.session_id = session_id
|
|
199
|
+
dataproc_config.name = f"projects/{self._project_id}/regions/{self._region}/sessions/{session_id}"
|
|
200
|
+
logger.debug(
|
|
201
|
+
f"Configurations used to create serverless session:\n {dataproc_config}"
|
|
202
|
+
)
|
|
203
|
+
session_request.session = dataproc_config
|
|
204
|
+
session_request.parent = (
|
|
205
|
+
f"projects/{self._project_id}/regions/{self._region}"
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
logger.debug("Creating serverless session")
|
|
209
|
+
DataprocSparkSession._active_s8s_session_id = session_id
|
|
210
|
+
s8s_creation_start_time = time.time()
|
|
211
|
+
try:
|
|
212
|
+
session_polling = retry.Retry(
|
|
213
|
+
predicate=POLLING_PREDICATE,
|
|
214
|
+
initial=5.0, # seconds
|
|
215
|
+
maximum=5.0, # seconds
|
|
216
|
+
multiplier=1.0,
|
|
217
|
+
timeout=600, # seconds
|
|
218
|
+
)
|
|
219
|
+
logger.info(
|
|
220
|
+
"Creating Spark session. It may take few minutes."
|
|
221
|
+
)
|
|
222
|
+
operation = SessionControllerClient(
|
|
223
|
+
client_options=self._client_options
|
|
224
|
+
).create_session(session_request)
|
|
225
|
+
print(
|
|
226
|
+
f"Interactive Session Detail View: https://console.cloud.google.com/dataproc/interactive/{self._region}/{session_id}"
|
|
227
|
+
)
|
|
228
|
+
session_response: Session = operation.result(
|
|
229
|
+
polling=session_polling
|
|
230
|
+
)
|
|
231
|
+
if (
|
|
232
|
+
"DATAPROC_SPARK_CONNECT_ACTIVE_SESSION_FILE_PATH"
|
|
233
|
+
in os.environ
|
|
234
|
+
):
|
|
235
|
+
file_path = os.environ[
|
|
236
|
+
"DATAPROC_SPARK_CONNECT_ACTIVE_SESSION_FILE_PATH"
|
|
237
|
+
]
|
|
238
|
+
try:
|
|
239
|
+
session_data = {
|
|
240
|
+
"session_name": session_response.name,
|
|
241
|
+
"session_uuid": session_response.uuid,
|
|
242
|
+
}
|
|
243
|
+
os.makedirs(
|
|
244
|
+
os.path.dirname(file_path), exist_ok=True
|
|
245
|
+
)
|
|
246
|
+
with open(file_path, "w") as json_file:
|
|
247
|
+
json.dump(session_data, json_file, indent=4)
|
|
248
|
+
except Exception as e:
|
|
249
|
+
logger.error(
|
|
250
|
+
f"Exception while writing active session to file {file_path} , {e}"
|
|
251
|
+
)
|
|
252
|
+
except InvalidArgument as e:
|
|
253
|
+
DataprocSparkSession._active_s8s_session_id = None
|
|
254
|
+
raise RuntimeError(
|
|
255
|
+
f"Error while creating serverless session: {e}"
|
|
256
|
+
) from None
|
|
257
|
+
except Exception as e:
|
|
258
|
+
DataprocSparkSession._active_s8s_session_id = None
|
|
259
|
+
raise RuntimeError(
|
|
260
|
+
f"Error while creating serverless session https://console.cloud.google.com/dataproc/interactive/{self._region}/{session_id} : {e}"
|
|
261
|
+
) from None
|
|
262
|
+
|
|
263
|
+
logger.debug(
|
|
264
|
+
f"Serverless session created: {session_id}, creation time taken: {int(time.time() - s8s_creation_start_time)} seconds"
|
|
265
|
+
)
|
|
266
|
+
return self.__create_spark_connect_session_from_s8s(
|
|
267
|
+
session_response
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
def _is_s8s_session_active(
|
|
271
|
+
self, s8s_session_id: str
|
|
272
|
+
) -> Optional[sessions.Session]:
|
|
273
|
+
session_name = f"projects/{self._project_id}/locations/{self._region}/sessions/{s8s_session_id}"
|
|
274
|
+
get_session_request = GetSessionRequest()
|
|
275
|
+
get_session_request.name = session_name
|
|
276
|
+
state = None
|
|
277
|
+
try:
|
|
278
|
+
get_session_response = SessionControllerClient(
|
|
279
|
+
client_options=self._client_options
|
|
280
|
+
).get_session(get_session_request)
|
|
281
|
+
state = get_session_response.state
|
|
282
|
+
except Exception as e:
|
|
283
|
+
logger.debug(f"{s8s_session_id} deleted: {e}")
|
|
284
|
+
return None
|
|
285
|
+
|
|
286
|
+
if state is not None and (
|
|
287
|
+
state == Session.State.ACTIVE or state == Session.State.CREATING
|
|
288
|
+
):
|
|
289
|
+
return get_session_response
|
|
290
|
+
return None
|
|
291
|
+
|
|
292
|
+
def _get_exiting_active_session(self) -> Optional["SparkSession"]:
|
|
293
|
+
s8s_session_id = DataprocSparkSession._active_s8s_session_id
|
|
294
|
+
session_response = self._is_s8s_session_active(s8s_session_id)
|
|
295
|
+
|
|
296
|
+
session = DataprocSparkSession.getActiveSession()
|
|
297
|
+
if session is None:
|
|
298
|
+
session = DataprocSparkSession._default_session
|
|
299
|
+
|
|
300
|
+
if session_response is not None:
|
|
301
|
+
print(
|
|
302
|
+
f"Using existing session: https://console.cloud.google.com/dataproc/interactive/{self._region}/{s8s_session_id}, configuration changes may not be applied."
|
|
303
|
+
)
|
|
304
|
+
if session is None:
|
|
305
|
+
session = self.__create_spark_connect_session_from_s8s(
|
|
306
|
+
session_response
|
|
307
|
+
)
|
|
308
|
+
return session
|
|
309
|
+
else:
|
|
310
|
+
logger.info(
|
|
311
|
+
f"Session: {s8s_session_id} not active, stopping previous spark session and creating new"
|
|
312
|
+
)
|
|
313
|
+
if session is not None:
|
|
314
|
+
session.stop()
|
|
315
|
+
|
|
316
|
+
return None
|
|
317
|
+
|
|
318
|
+
def getOrCreate(self) -> "SparkSession":
|
|
319
|
+
with DataprocSparkSession._lock:
|
|
320
|
+
session = self._get_exiting_active_session()
|
|
321
|
+
if session is None:
|
|
322
|
+
session = self.__create()
|
|
323
|
+
if session:
|
|
324
|
+
self.__apply_options(session)
|
|
325
|
+
return session
|
|
326
|
+
|
|
327
|
+
def _get_dataproc_config(self):
|
|
328
|
+
dataproc_config = Session()
|
|
329
|
+
if self._dataproc_config:
|
|
330
|
+
dataproc_config = self._dataproc_config
|
|
331
|
+
for k, v in self._options.items():
|
|
332
|
+
dataproc_config.runtime_config.properties[k] = v
|
|
333
|
+
elif "DATAPROC_SPARK_CONNECT_SESSION_DEFAULT_CONFIG" in os.environ:
|
|
334
|
+
filepath = os.environ[
|
|
335
|
+
"DATAPROC_SPARK_CONNECT_SESSION_DEFAULT_CONFIG"
|
|
336
|
+
]
|
|
337
|
+
try:
|
|
338
|
+
with open(filepath, "r") as f:
|
|
339
|
+
dataproc_config = Session.wrap(
|
|
340
|
+
text_format.Parse(
|
|
341
|
+
f.read(), Session.pb(dataproc_config)
|
|
342
|
+
)
|
|
343
|
+
)
|
|
344
|
+
except FileNotFoundError:
|
|
345
|
+
raise FileNotFoundError(f"File '{filepath}' not found")
|
|
346
|
+
except ParseError as e:
|
|
347
|
+
raise ParseError(f"Error parsing file '{filepath}': {e}")
|
|
348
|
+
if "COLAB_NOTEBOOK_RUNTIME_ID" in os.environ:
|
|
349
|
+
dataproc_config.labels["colab-notebook-runtime-id"] = (
|
|
350
|
+
os.environ["COLAB_NOTEBOOK_RUNTIME_ID"]
|
|
351
|
+
)
|
|
352
|
+
if "COLAB_NOTEBOOK_KERNEL_ID" in os.environ:
|
|
353
|
+
dataproc_config.labels["colab-notebook-kernel-id"] = os.environ[
|
|
354
|
+
"COLAB_NOTEBOOK_KERNEL_ID"
|
|
355
|
+
]
|
|
356
|
+
return dataproc_config
|
|
357
|
+
|
|
358
|
+
def _get_session_template(self):
|
|
359
|
+
from google.cloud.dataproc_v1 import (
|
|
360
|
+
GetSessionTemplateRequest,
|
|
361
|
+
SessionTemplateControllerClient,
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
session_template = None
|
|
365
|
+
if self._dataproc_config and self._dataproc_config.session_template:
|
|
366
|
+
session_template = self._dataproc_config.session_template
|
|
367
|
+
get_session_template_request = GetSessionTemplateRequest()
|
|
368
|
+
get_session_template_request.name = session_template
|
|
369
|
+
client = SessionTemplateControllerClient(
|
|
370
|
+
client_options=self._client_options
|
|
371
|
+
)
|
|
372
|
+
try:
|
|
373
|
+
session_template = client.get_session_template(
|
|
374
|
+
get_session_template_request
|
|
375
|
+
)
|
|
376
|
+
except Exception as e:
|
|
377
|
+
logger.error(
|
|
378
|
+
f"Failed to get session template {session_template}: {e}"
|
|
379
|
+
)
|
|
380
|
+
raise
|
|
381
|
+
return session_template
|
|
382
|
+
|
|
383
|
+
def _get_and_validate_version(self, dataproc_config, session_template):
|
|
384
|
+
trimmed_version = lambda v: ".".join(v.split(".")[:2])
|
|
385
|
+
version = None
|
|
386
|
+
if (
|
|
387
|
+
dataproc_config
|
|
388
|
+
and dataproc_config.runtime_config
|
|
389
|
+
and dataproc_config.runtime_config.version
|
|
390
|
+
):
|
|
391
|
+
version = dataproc_config.runtime_config.version
|
|
392
|
+
elif (
|
|
393
|
+
session_template
|
|
394
|
+
and session_template.runtime_config
|
|
395
|
+
and session_template.runtime_config.version
|
|
396
|
+
):
|
|
397
|
+
version = session_template.runtime_config.version
|
|
398
|
+
|
|
399
|
+
if not version:
|
|
400
|
+
version = "3.0"
|
|
401
|
+
dataproc_config.runtime_config.version = version
|
|
402
|
+
elif (
|
|
403
|
+
trimmed_version(version)
|
|
404
|
+
not in self._dataproc_runtime_spark_version
|
|
405
|
+
):
|
|
406
|
+
raise ValueError(
|
|
407
|
+
f"runtime_config.version {version} is not supported. "
|
|
408
|
+
f"Supported versions: {self._dataproc_runtime_spark_version.keys()}"
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
server_version = self._dataproc_runtime_spark_version[
|
|
412
|
+
trimmed_version(version)
|
|
413
|
+
]
|
|
414
|
+
import importlib.metadata
|
|
415
|
+
|
|
416
|
+
dataproc_connect_version = importlib.metadata.version(
|
|
417
|
+
"dataproc-spark-connect"
|
|
418
|
+
)
|
|
419
|
+
client_version = importlib.metadata.version("pyspark")
|
|
420
|
+
version_message = f"Dataproc Spark Connect: {dataproc_connect_version} (PySpark: {client_version}) Dataproc Session Runtime: {version} (Spark: {server_version})"
|
|
421
|
+
logger.info(version_message)
|
|
422
|
+
if trimmed_version(client_version) != trimmed_version(
|
|
423
|
+
server_version
|
|
424
|
+
):
|
|
425
|
+
logger.warning(
|
|
426
|
+
f"client and server on different versions: {version_message}"
|
|
427
|
+
)
|
|
428
|
+
return version
|
|
429
|
+
|
|
430
|
+
def _get_spark_connect_session(self, dataproc_config, session_template):
|
|
431
|
+
spark_connect_session = None
|
|
432
|
+
if dataproc_config and dataproc_config.spark_connect_session:
|
|
433
|
+
spark_connect_session = dataproc_config.spark_connect_session
|
|
434
|
+
elif session_template and session_template.spark_connect_session:
|
|
435
|
+
spark_connect_session = session_template.spark_connect_session
|
|
436
|
+
return spark_connect_session
|
|
437
|
+
|
|
438
|
+
def _get_spark(self, dataproc_config, session_template):
|
|
439
|
+
spark = None
|
|
440
|
+
if dataproc_config and dataproc_config.spark:
|
|
441
|
+
spark = dataproc_config.spark
|
|
442
|
+
elif session_template and session_template.spark:
|
|
443
|
+
spark = session_template.spark
|
|
444
|
+
return spark
|
|
445
|
+
|
|
446
|
+
def generate_dataproc_session_id(self):
|
|
447
|
+
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
448
|
+
suffix_length = 6
|
|
449
|
+
random_suffix = "".join(
|
|
450
|
+
random.choices(
|
|
451
|
+
string.ascii_lowercase + string.digits, k=suffix_length
|
|
452
|
+
)
|
|
453
|
+
)
|
|
454
|
+
return f"sc-{timestamp}-{random_suffix}"
|
|
455
|
+
|
|
456
|
+
def _repr_html_(self) -> str:
|
|
457
|
+
if not self._active_s8s_session_id:
|
|
458
|
+
return """
|
|
459
|
+
<div>No Active Dataproc Spark Session</div>
|
|
460
|
+
"""
|
|
461
|
+
|
|
462
|
+
s8s_session = f"https://console.cloud.google.com/dataproc/interactive/{self._region}/{self._active_s8s_session_id}"
|
|
463
|
+
ui = f"{s8s_session}/sparkApplications/applications"
|
|
464
|
+
version = ""
|
|
465
|
+
return f"""
|
|
466
|
+
<div>
|
|
467
|
+
<p><b>Spark Connect</b></p>
|
|
468
|
+
|
|
469
|
+
<p><a href="{s8s_session}">Dataproc Session</a></p>
|
|
470
|
+
<p><a href="{ui}">Spark UI</a></p>
|
|
471
|
+
</div>
|
|
472
|
+
"""
|
|
473
|
+
|
|
474
|
+
def _remove_stoped_session_from_file(self):
|
|
475
|
+
if "DATAPROC_SPARK_CONNECT_ACTIVE_SESSION_FILE_PATH" in os.environ:
|
|
476
|
+
file_path = os.environ[
|
|
477
|
+
"DATAPROC_SPARK_CONNECT_ACTIVE_SESSION_FILE_PATH"
|
|
478
|
+
]
|
|
479
|
+
try:
|
|
480
|
+
with open(file_path, "w"):
|
|
481
|
+
pass
|
|
482
|
+
except Exception as e:
|
|
483
|
+
logger.error(
|
|
484
|
+
f"Exception while removing active session in file {file_path} , {e}"
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
def stop(self) -> None:
|
|
488
|
+
with DataprocSparkSession._lock:
|
|
489
|
+
if DataprocSparkSession._active_s8s_session_id is not None:
|
|
490
|
+
from google.cloud.dataproc_v1 import SessionControllerClient
|
|
491
|
+
|
|
492
|
+
logger.debug(
|
|
493
|
+
f"Terminating serverless session: {DataprocSparkSession._active_s8s_session_id}"
|
|
494
|
+
)
|
|
495
|
+
terminate_session_request = TerminateSessionRequest()
|
|
496
|
+
session_name = f"projects/{DataprocSparkSession._project_id}/locations/{DataprocSparkSession._region}/sessions/{DataprocSparkSession._active_s8s_session_id}"
|
|
497
|
+
terminate_session_request.name = session_name
|
|
498
|
+
state = None
|
|
499
|
+
try:
|
|
500
|
+
SessionControllerClient(
|
|
501
|
+
client_options=self._client_options
|
|
502
|
+
).terminate_session(terminate_session_request)
|
|
503
|
+
get_session_request = GetSessionRequest()
|
|
504
|
+
get_session_request.name = session_name
|
|
505
|
+
state = Session.State.ACTIVE
|
|
506
|
+
while (
|
|
507
|
+
state != Session.State.TERMINATING
|
|
508
|
+
and state != Session.State.TERMINATED
|
|
509
|
+
and state != Session.State.FAILED
|
|
510
|
+
):
|
|
511
|
+
session = SessionControllerClient(
|
|
512
|
+
client_options=self._client_options
|
|
513
|
+
).get_session(get_session_request)
|
|
514
|
+
state = session.state
|
|
515
|
+
sleep(1)
|
|
516
|
+
except NotFound:
|
|
517
|
+
logger.debug(
|
|
518
|
+
f"Session {DataprocSparkSession._active_s8s_session_id} already deleted"
|
|
519
|
+
)
|
|
520
|
+
except FailedPrecondition:
|
|
521
|
+
logger.debug(
|
|
522
|
+
f"Session {DataprocSparkSession._active_s8s_session_id} already terminated manually or terminated automatically through session ttl limits"
|
|
523
|
+
)
|
|
524
|
+
if state is not None and state == Session.State.FAILED:
|
|
525
|
+
raise RuntimeError("Serverless session termination failed")
|
|
526
|
+
|
|
527
|
+
self._remove_stoped_session_from_file()
|
|
528
|
+
DataprocSparkSession._active_s8s_session_uuid = None
|
|
529
|
+
DataprocSparkSession._active_s8s_session_id = None
|
|
530
|
+
DataprocSparkSession._project_id = None
|
|
531
|
+
DataprocSparkSession._region = None
|
|
532
|
+
DataprocSparkSession._client_options = None
|
|
533
|
+
|
|
534
|
+
self.client.close()
|
|
535
|
+
if self is DataprocSparkSession._default_session:
|
|
536
|
+
DataprocSparkSession._default_session = None
|
|
537
|
+
if self is getattr(
|
|
538
|
+
DataprocSparkSession._active_session, "session", None
|
|
539
|
+
):
|
|
540
|
+
DataprocSparkSession._active_session.session = None
|