Skip to content
Open
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
88 changes: 82 additions & 6 deletions e6data_python_connector/cluster_manager.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import hashlib
import logging
import os
import threading
import time
import e6data_python_connector.cluster_server.cluster_pb2 as cluster_pb2
Expand Down Expand Up @@ -72,6 +74,27 @@ def __init__(self):
self._status_thread_lock = threading.Lock()
self._status_multiprocessing_lock = multiprocessing.Semaphore()
self._is_active = False
# Both values are protected by the same semaphore as resume(). Forked
# workers inherit this storage, just as they inherit that semaphore.
self._resume_identity = multiprocessing.RawArray('B', 32)
self._resume_completed_at = multiprocessing.RawValue('d', 0.0)

@property
def _resume_completion(self):
"""Read only while holding both status locks."""
completed_at = self._resume_completed_at.value
if completed_at == 0:
return None
return bytes(self._resume_identity), completed_at

@_resume_completion.setter
def _resume_completion(self, completion):
"""Publish or invalidate only while holding both status locks."""
self._resume_completed_at.value = 0.0
if completion is not None:
identity, completed_at = completion
self._resume_identity[:] = identity
self._resume_completed_at.value = completed_at

@property
def is_active(self) -> bool:
Expand Down Expand Up @@ -107,8 +130,14 @@ def __enter__(self):
_StatusLock: The current instance of the lock, used for context management.
"""

self._status_thread_lock.acquire(timeout=self._LOCK_TIMEOUT)
self._status_multiprocessing_lock.acquire(timeout=self._LOCK_TIMEOUT)
if not self._status_thread_lock.acquire(timeout=self._LOCK_TIMEOUT):
raise TimeoutError('Cluster recovery timed out waiting for status lock.')
try:
if not self._status_multiprocessing_lock.acquire(timeout=self._LOCK_TIMEOUT):
raise TimeoutError('Cluster recovery timed out waiting for process lock.')
except BaseException:
self._status_thread_lock.release()
raise
return self

def __exit__(self, exc_type, exc_val, exc_tb):
Expand All @@ -125,8 +154,8 @@ def __exit__(self, exc_type, exc_val, exc_tb):
exc_tb (Traceback): The traceback object of the exception (if any).
"""

self._status_thread_lock.release()
self._status_multiprocessing_lock.release()
self._status_thread_lock.release()

@contextmanager
def hold_until(self, deadline):
Expand All @@ -147,6 +176,16 @@ def hold_until(self, deadline):
status_lock = _StatusLock()


def _reset_status_thread_lock_after_fork():
# A parent's locked threading.Lock has no owning thread in the child. Keep
# the inherited process semaphore and completion storage shared, however.
status_lock._status_thread_lock = threading.Lock()


if hasattr(os, 'register_at_fork'):
os.register_at_fork(after_in_child=_reset_status_thread_lock_after_fork)


class ClusterManager:
"""
A manager for handling operations and connections with a remote cluster infrastructure.
Expand Down Expand Up @@ -463,6 +502,34 @@ def _check_cluster_status(self):
logger.warning(f"Status check failed with error: {e}")
yield None

def _legacy_resume_identity(self):
"""Fingerprint exact connection inputs without retaining credentials.

Copy standard option containers. Unknown or mutable option values disable
sharing so their existing RPC behavior is preserved without guessing.
"""
values = (self._host, self._port, self.cluster_uuid, self._secure_channel,
self._ssl_cert, self._user, self._password)
scalar_types = (type(None), str, bytes, bool, int)
if any(type(value) not in scalar_types for value in values):
return None
options = self._grpc_options
if type(options) is dict:
pairs = tuple(options.items())
elif type(options) in (list, tuple):
pairs = tuple(options)
else:
return None
frozen_options = []
for pair in pairs:
if (type(pair) not in (tuple, list) or len(pair) != 2
or any(type(value) not in scalar_types for value in pair)):
return None
frozen_options.append(tuple((type(value).__name__, value) for value in pair))
identity = (tuple((type(value).__name__, value) for value in values),
type(options).__name__, tuple(frozen_options))
return hashlib.sha256(repr(identity).encode('utf-8')).digest()

def resume(self) -> bool:
"""
Resumes the cluster if it is currently suspended or not in the 'active' state.
Expand Down Expand Up @@ -492,14 +559,19 @@ def resume(self) -> bool:
"""
if self._metadata_provider is not None:
return self._resume_oauth()
call_started = time.monotonic()
if self._debug:
logger.info(f"Starting auto-resume for cluster {self.cluster_uuid} at {self._host}:{self._port}")

with status_lock as lock:
if lock.is_active:
if self._debug:
logger.info("Lock is already active, cluster appears to be running")
identity = self._legacy_resume_identity()
completion = lock._resume_completion
if (identity is not None and completion is not None
and completion[0] == identity and completion[1] > call_started):
return True
# A fresh attempt can observe a new failure before older waiters run.
# Invalidate first, including when the attempt later raises an error.
lock._resume_completion = None

# Retrieve the current cluster status with strategy header
if self._debug:
Expand Down Expand Up @@ -528,6 +600,8 @@ def resume(self) -> bool:
elif current_status.status == 'active':
if self._debug:
logger.info("Cluster is already active, no action needed")
if identity is not None:
lock._resume_completion = (identity, time.monotonic())
return True
elif current_status.status != 'resuming':
"""
Expand All @@ -546,6 +620,8 @@ def resume(self) -> bool:
if status == 'active':
if self._debug:
logger.info(f"Cluster became active after {check_count} status checks")
if identity is not None:
lock._resume_completion = (identity, time.monotonic())
return True
elif status == 'failed':
if self._debug:
Expand Down
Loading
Loading