Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ These environment variables change how the client behaves.
| `MANAGED_SPARK_CONNECT_WS_SILENCE_LIMIT_S` | `150` | Cut the proxy WebSocket connection if a query's result stream (a reattachable `ExecutePlan` or `ReattachExecute`) has been waiting this many seconds for its next response and nothing at all was received, so a wedged stream behind an open WebSocket fails and pyspark reattaches instead of hanging or hitting `INVALID_HANDLE.OPERATION_ABANDONED`. By default the server sends progress updates while tasks run and ends these streams every 2 minutes (`spark.connect.execute.reattachable.senderMaxStreamDuration`) even when it has nothing to send; keep custom values above `senderMaxStreamDuration` so idle streams are not cut prematurely. Other RPCs, such as a long `AnalyzePlan`, and result streams that nobody is reading from don't count. The check runs on each 60 s WebSocket receive poll, so the cut happens between this limit and the limit plus 60 s (150–210 s by default, before Spark's 5-minute default `detachedTimeout`). Set to `0` to disable. |
| `MANAGED_SPARK_CONNECT_LIVENESS_TTL_SECONDS` | unset | Before an RPC, the client checks that the Dataproc session is still alive. Once a check finds it `ACTIVE`, that answer is reused for this many seconds: unset or negative reuses it until an RPC fails, `0` checks before every RPC. A failed RPC always triggers a fresh check. The session only counts as gone when Dataproc reports it not found or in a terminal state; when the check itself fails (for example during a control-plane outage), the RPC proceeds. An RPC on a gone session raises `SessionNotActiveError` (a `RuntimeError`, from `google.cloud.managed_spark_connect.exceptions`) saying what Dataproc reported, e.g. `FAILED` and why. |
| `MANAGED_SPARK_CONNECT_SESSION_START_RETRIES` | `1` | `getOrCreate()` makes a new session's first RPC itself, and if that fails and Dataproc reports the session gone (failed or terminated before it could be used), creates another session in its place, this many times, logging a `WARNING`. Only for generated session IDs: a session created with `sessionId()` raises `SessionNotActiveError` instead. `0` disables retrying. |
| `GRPC_VERBOSITY` | `ERROR` | gRPC's own variable. If it is unset when this package is imported, and gRPC hasn't been imported yet, the package sets it to `ERROR` for the whole process to silence gRPC's informational fork messages. Set it yourself to override. |
| `GRPC_VERBOSITY` | `ERROR` | gRPC's own variable. If it is unset when this package is imported, and gRPC hasn't initialized a channel or server yet (including when another package such as `google.cloud.dataproc_v1` was imported first), the package sets it to `ERROR` for the whole process to silence gRPC's informational fork messages. Set it yourself to override. |
| `MANAGED_SPARK_CONNECT_LOG_LEVEL` | unset | A level name (`DEBUG`, `INFO`, ...) or a positive number for the `google.cloud.managed_spark_connect` loggers. If the root logger has no handlers when the package is imported, the library logs to stderr itself, and its records then don't reach root handlers configured later: configure logging before importing the package to send them elsewhere. The library never configures the root logger. Setting it also lets pyspark print its query-context JSON for failed queries (see `SPARK_CONNECT_LOG_LEVEL`). |
| `SPARK_CONNECT_LOG_LEVEL` | unset | pyspark's own variable. Unless it or `MANAGED_SPARK_CONNECT_LOG_LEVEL` is set, creating a session silences pyspark's `SQLQueryContextLogger` and `DataFrameQueryContextLogger`, which otherwise print a JSON dump to stderr for every failed query. This applies to the whole process. |
| `MANAGED_SPARK_CONNECT_SHOW_OPERATION_LINKS` | `true` | Default for `showOperationLinks()`. |
Expand Down
90 changes: 85 additions & 5 deletions google/cloud/managed_spark_connect/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,93 @@
import importlib.util
import os
import sys
import threading
import warnings

# gRPC C-core logs fork-handler noise at INFO; default it to ERROR. gRPC reads
# the variable once, when it is first imported, so this only applies when this
# package is imported before grpc; an explicit GRPC_VERBOSITY always wins.
if "grpc" not in sys.modules:
os.environ.setdefault("GRPC_VERBOSITY", "ERROR")

def _has_grpc_core_threads() -> bool:
"""Return True if Linux /proc reports active gRPC C-core background threads."""
if not sys.platform.startswith("linux"):
return False
try:
tids = os.listdir("/proc/self/task")
except OSError:
return False
for tid in tids:
try:
with open(
f"/proc/self/task/{tid}/comm",
"r",
encoding="utf-8",
errors="replace",
) as f:
comm = f.read().strip()
except OSError:
continue
if comm.startswith("grpc") or comm in ("event_engine", "lifeguard"):
return True
return False


def _grpc_runtime_started(cygrpc: object) -> bool:
"""Return True if gRPC C-core may already have been initialized."""
if (
"grpc._channel" in sys.modules
or "grpc._server" in sys.modules
or "grpc._auth" in sys.modules
):
return True
if getattr(cygrpc, "g_shutdown_handler_registered", False):
return True
if getattr(getattr(cygrpc, "_fork_state", None), "channels", None):
return True
poller_cls = getattr(cygrpc, "PollerCompletionQueue", None)
if isinstance(poller_cls, type):
for thread in threading.enumerate():
target = getattr(thread, "_target", None)
if isinstance(getattr(target, "__self__", None), poller_cls):
return True
if _has_grpc_core_threads():
return True
return False


def _configure_default_grpc_verbosity() -> None:
"""Default GRPC_VERBOSITY to ERROR before gRPC C-core initializes.
gRPC C-core logs fork-handler noise at INFO. When ``grpc`` is imported
ahead of this package (for example via ``from google.cloud.dataproc_v1
import Session``), ``grpc._cython.cygrpc`` caches ``ConfigVars`` on import,
so setting ``os.environ["GRPC_VERBOSITY"]`` alone has no effect. However,
C-core's ``grpc_init()`` (and ``gpr_log_verbosity_init()``) does not run
until the first channel, server, or call-credentials object is created, so
resetting ``ConfigVars`` before that point lets the default take effect.
An explicit ``GRPC_VERBOSITY`` always wins, and ``ConfigVars`` is never
reset once gRPC channels, servers, or aio pollers may already be running.
"""
if "GRPC_VERBOSITY" in os.environ:
return
if "grpc" not in sys.modules:
os.environ["GRPC_VERBOSITY"] = "ERROR"
return
cygrpc = sys.modules.get("grpc._cython.cygrpc")
if cygrpc is None:
os.environ["GRPC_VERBOSITY"] = "ERROR"
return
if _grpc_runtime_started(cygrpc):
return
reset = getattr(cygrpc, "reset_grpc_config_vars", None)
if not callable(reset):
return
os.environ["GRPC_VERBOSITY"] = "ERROR"
try:
reset()
except Exception:
os.environ.pop("GRPC_VERBOSITY", None)


_configure_default_grpc_verbosity()

from . import _logging

Expand Down
23 changes: 19 additions & 4 deletions google/cloud/managed_spark_connect/ide.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@
import json
import logging
import os
import shutil
import subprocess
import sys
from typing import (
Any,
Callable,
Dict,
Iterable,
Expand Down Expand Up @@ -227,13 +229,26 @@ def _ps_proc_lookup(run=subprocess.run) -> _ProcLookup:

def load() -> Dict[int, _ProcInfo]:
result: Dict[int, _ProcInfo] = {}
run_kwargs: Dict[str, Any] = {
"capture_output": True,
"text": True,
"timeout": _PS_TIMEOUT_SECONDS,
"check": False,
}
# Resolve `ps` to an explicit path and leave `close_fds=False` on POSIX
# so Python takes `os.posix_spawn()` instead of `fork()`. `fork()` runs
# gRPC's pthread_atfork handlers (which log at INFO when a gRPC channel
# is active), whereas `posix_spawn()` bypasses them; Python creates FDs
# with O_CLOEXEC by default.
if os.name == "posix":
ps_exe = shutil.which("ps")
if ps_exe and os.path.isabs(ps_exe):
run_kwargs["executable"] = ps_exe
run_kwargs["close_fds"] = False
try:
out = run(
["ps", "-axo", "pid=,ppid=,comm="],
capture_output=True,
text=True,
timeout=_PS_TIMEOUT_SECONDS,
check=False,
**run_kwargs,
).stdout
except Exception:
return result
Expand Down
42 changes: 39 additions & 3 deletions google/cloud/managed_spark_connect/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
clear_credentials_cache,
file_stat_stamp,
get_default_credentials,
get_refreshed_credentials,
)
from google.cloud.managed_spark_connect.client.reattach_patch import (
install_operation_abandoned_handler,
Expand Down Expand Up @@ -471,9 +472,25 @@ def clear_dataproc_caches() -> None:
invalidate_s8s_session_active()


def _prewarm_dataproc_credentials(creds: Any, recorder: Any = NOOP_RECORDER):
"""Best-effort refresh cached ADC before opening a gRPC channel.
Refreshing synchronously on the calling thread prevents gRPC's
``AuthMetadataPlugin`` from invoking ``creds.refresh()`` (which may fork
``gcloud`` for external/workforce credentials) on a background thread while
an active RPC holds a gRPC ``ExecCtx``.
"""
try:
return get_refreshed_credentials(recorder=recorder)
except Exception:
logger.debug("Credential pre-warm failed", exc_info=True)
return creds


def _create_dataproc_client(
client_cls: Any,
client_options: Optional[ClientOptions] = None,
recorder: Any = NOOP_RECORDER,
) -> Any:
"""Create or return a cached Dataproc control-plane client instance."""
resolved_transport = _resolve_dataproc_transport()
Expand Down Expand Up @@ -531,6 +548,19 @@ def _create_dataproc_client(
_CLIENT_CACHE[cache_key] = (stamp, client)
return client
creds, _ = get_default_credentials()
if (
entry is not None
and entry[0] is creds
and getattr(creds, "valid", True)
and getattr(creds, "token", True)
):
return entry[1]
# Refresh outside _CLIENT_CACHE_LOCK so token refresh I/O does not block
# unrelated client cache lookups; also refreshes expired cached credentials
# synchronously on the calling thread before the next gRPC RPC.
creds = _prewarm_dataproc_credentials(creds, recorder=recorder)
with _CLIENT_CACHE_LOCK:
entry = _CLIENT_CACHE.get(cache_key)
if entry is not None and entry[0] is creds:
return entry[1]
client = client_cls(
Expand All @@ -544,11 +574,13 @@ def _create_dataproc_client(

def _create_session_controller_client(
client_options: Optional[ClientOptions] = None,
recorder: Any = NOOP_RECORDER,
) -> SessionControllerClient:
"""Create or return a cached Dataproc SessionControllerClient instance."""
return _create_dataproc_client(
dataproc_v1.SessionControllerClient,
client_options=client_options,
recorder=recorder,
)


Expand Down Expand Up @@ -1134,7 +1166,8 @@ def session_controller_client(self) -> SessionControllerClient:
if self._session_controller_client is not None:
return self._session_controller_client
client = _create_session_controller_client(
client_options=self._client_options
client_options=self._client_options,
recorder=self._recorder,
)
if _has_uncacheable_client_cert_options(self._client_options):
self._session_controller_client = client
Expand All @@ -1148,6 +1181,7 @@ def session_template_controller_client(self):
client = _create_dataproc_client(
dataproc_v1.SessionTemplateControllerClient,
client_options=self._client_options,
recorder=self._recorder,
)
if _has_uncacheable_client_cert_options(self._client_options):
self._session_template_controller_client = client
Expand Down Expand Up @@ -3231,7 +3265,8 @@ def terminate_s8s_session(
state = None
try:
session_client = _create_session_controller_client(
client_options=client_options
client_options=client_options,
recorder=recorder,
)
with recorder.span("session.terminate_rpc"):
session_client.terminate_session(terminate_session_request)
Expand Down Expand Up @@ -3468,7 +3503,8 @@ def _dead_session_detail(
"dataproc.get_session", reason="check_new", new_client=True
):
response = _create_session_controller_client(
client_options=client_options
client_options=client_options,
recorder=recorder,
).get_session(get_session_request)
except NotFound:
detail = _describe_inactive_session(session_name)
Expand Down
7 changes: 4 additions & 3 deletions tests/unit/test_dataproc.py
Original file line number Diff line number Diff line change
Expand Up @@ -643,7 +643,7 @@ def test_client_cache_rebuilds_when_credentials_cache_cleared_or_refresh_fails(
monkeypatch,
):
creds_list = [
_FakeRealCredentials(valid=False, token=None),
_FakeRealCredentials(valid=True, token="tok-1"),
_FakeRealCredentials(valid=True, token="tok-2"),
_FakeRealCredentials(valid=True, token="tok-3"),
]
Expand Down Expand Up @@ -672,8 +672,9 @@ def __init__(self, client_options=None, credentials=None):
c1 = session_mod._create_session_controller_client(client_options=opts)
assert c1.credentials is creds_list[0]

# A refresh failure in proxy.get_refreshed_credentials() clears
# _CREDENTIALS_CACHE, which must also force _CLIENT_CACHE to rebuild.
# Token later expires; a refresh failure in proxy.get_refreshed_credentials()
# clears _CREDENTIALS_CACHE, which must also force _CLIENT_CACHE to rebuild.
creds_list[0].valid = False
with pytest.raises(RefreshError):
proxy_mod.get_refreshed_credentials()

Expand Down
Loading
Loading