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
3 changes: 3 additions & 0 deletions google/cloud/managed_spark_connect/_session_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ def fetch_session_template(
*,
project_id: Optional[str],
region: Optional[str],
on_error: Optional[Callable[[Exception], None]] = None,
) -> Optional[SessionTemplate]:
"""Fetch a ``SessionTemplate`` best-effort, returning ``None`` on error."""
if not template_name:
Expand All @@ -95,6 +96,8 @@ def fetch_session_template(
request = GetSessionTemplateRequest(name=qualified_name)
return get_client().get_session_template(request)
except Exception as e:
if on_error is not None:
on_error(e)
logger.debug(
"Could not read session template %s: %s", qualified_name, e
)
Expand Down
84 changes: 77 additions & 7 deletions google/cloud/managed_spark_connect/client/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,73 @@
_DEFAULT_SILENCE_LIMIT_S = 150.0


def file_stat_stamp(path):
"""Return a lightweight stat fingerprint for ``path``, or ``None`` if absent."""
if not path:
return None
try:
st = os.stat(path)
except OSError:
return None
return (st.st_mtime_ns, st.st_ctime_ns, st.st_size, st.st_ino, st.st_dev)


def _default_adc_file_path():
"""Return the credentials file path consulted by ``google.auth.default()``.

Pure Python (environment variables and path joins only); never spawns a
subprocess.
"""
explicit = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") or ""
if explicit:
return explicit
try:
from google.auth import _cloud_sdk

return _cloud_sdk.get_application_default_credentials_path()
except Exception:
pass
config_dir = os.environ.get("CLOUDSDK_CONFIG")
if not config_dir:
if os.name == "nt":
appdata = os.environ.get("APPDATA")
if appdata:
config_dir = os.path.join(appdata, "gcloud")
else:
config_dir = os.path.join(
os.environ.get("SystemDrive", "C:"), "\\", "gcloud"
)
else:
config_dir = os.path.join(
os.path.expanduser("~"), ".config", "gcloud"
)
return os.path.join(config_dir, "application_default_credentials.json")


def adc_file_stamp():
"""Return ``(abs_path, file_stat_stamp)`` for the current default ADC file."""
adc_path = _default_adc_file_path()
return (os.path.abspath(adc_path), file_stat_stamp(adc_path))
Comment thread
dborowitz marked this conversation as resolved.
Resolved


def clear_credentials_cache():
"""Clear process-wide cached Application Default Credentials."""
with _AUTH_LOCK:
_CREDENTIALS_CACHE.clear()


def _evict_credentials(creds):
"""Remove cached entries pointing to ``creds`` without disturbing newer loads."""
with _AUTH_LOCK:
stale_keys = [
key
for key, (_, loaded) in _CREDENTIALS_CACHE.items()
if loaded[0] is creds
]
for key in stale_keys:
del _CREDENTIALS_CACHE[key]


def get_default_credentials(scopes=None):
"""Obtain Application Default Credentials with Cloud Platform scopes."""
scopes_tuple = tuple(scopes) if scopes is not None else _DEFAULT_SCOPES
Expand All @@ -87,16 +148,21 @@ def get_default_credentials(scopes=None):
os.environ.get("CLOUDSDK_CONFIG"),
os.environ.get("APPDATA"),
os.environ.get("GOOGLE_CLOUD_PROJECT"),
os.environ.get("GOOGLE_CLOUD_QUOTA_PROJECT"),
os.environ.get("GCLOUD_PROJECT"),
os.environ.get("DEVSHELL_PROJECT_ID"),
os.environ.get("HOME"),
)
with _AUTH_LOCK:
cached = _CREDENTIALS_CACHE.get(cache_key)
if cached is None:
cached = auth_default(scopes=list(scopes_tuple))
_CREDENTIALS_CACHE[cache_key] = cached
return cached
# Stat before reading so a concurrent credential file rewrite is never
# tagged with a newer post-read fingerprint.
adc_stamp = adc_file_stamp()
entry = _CREDENTIALS_CACHE.get(cache_key)
if entry is not None and entry[0] == adc_stamp:
return entry[1]
loaded = auth_default(scopes=list(scopes_tuple))
_CREDENTIALS_CACHE[cache_key] = (adc_stamp, loaded)
return loaded


def _expiry_wall_ns(creds):
Expand Down Expand Up @@ -130,7 +196,7 @@ def get_refreshed_credentials(recorder=NOOP_RECORDER, scopes=None):
try:
creds.refresh(googleauthrequests.Request())
except Exception:
_CREDENTIALS_CACHE.clear()
_evict_credentials(creds)
raise
if recorder.enabled:
refreshed_attrs = (
Expand Down Expand Up @@ -250,6 +316,7 @@ def connect_tcp_bridge(hostname, recorder=NOOP_RECORDER, conn_number=None):
"""
path = "tcp-over-websocket-bridge/35218cb7-1201-4940-89e8-48d8f03fed96"
with recorder.span("proxy.ws_connect", conn=conn_number, host=hostname):
creds = None
try:
creds = get_refreshed_credentials(recorder=recorder)

Expand Down Expand Up @@ -280,12 +347,15 @@ def connect_tcp_bridge(hostname, recorder=NOOP_RECORDER, conn_number=None):
ping_timeout=60,
)
except Exception as exc:
http_status = _http_status_of(exc)
if http_status == 401 and creds is not None:
_evict_credentials(creds)
if recorder.enabled:
recorder.event(
"proxy.ws_connect_failed",
conn=conn_number,
error_type=type(exc).__name__,
http_status=_http_status_of(exc),
http_status=http_status,
)
raise

Expand Down
Loading
Loading