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
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,22 @@ def _wait_for_placement(
metrics_collector_inst: Any = None,
start_time: float | None = None,
total_chips: int = 0,
placement_complete: threading.Event | None = None,
) -> None:
"""Waits for the placement to be complete by checking proxy logs."""
"""Waits for the placement to be complete by checking proxy logs.

Args:
log_process: The process streaming the proxy pod logs.
num_slices: The number of slices to wait for.
metrics_collector_inst: The metrics collector to report placement to.
start_time: The time at which the capacity request started.
total_chips: The total number of chips requested.
placement_complete: If given, set once all slices are placed and the
placement metrics are recorded.

Raises:
RuntimeError: If the log streaming process has no stdout.
"""
_logger.info("Streaming proxy logs until the placement is complete...")
keywords = [
"placement",
Expand Down Expand Up @@ -221,12 +235,15 @@ def _wait_for_placement(
)
else:
_logger.info("TPU placement for %d slice(s) complete!", num_slices)
metrics_collector_inst.record_user_waiting(False)
metrics_collector_inst.record_active_user(True)
metrics_collector_inst.record_capacity_in_use(total_chips)
if start_time:
duration = time.time() - start_time
metrics_collector_inst.record_assignment_time(duration)
metrics_collector_inst.record_successful_request()
if placement_complete is not None:
placement_complete.set()
break


Expand Down Expand Up @@ -262,6 +279,7 @@ class _ISCPathways:
metrics_collector: The metrics collector instance if enabled.
start_time: The start time of the TPU assignment.
total_chips: The total number of TPU chips expected across all instances.
placement_complete: Set once all TPU slices are placed.
"""

def __init__(
Expand Down Expand Up @@ -311,6 +329,7 @@ def __init__(
self._old_jax_backend_target_config = None
self.total_chips = self._get_total_chips()
self._proxy_deployed = False
self.placement_complete = threading.Event()
self._cleaned_up = False
self._cleanup_lock = threading.Lock()
self._original_signal_handlers: dict[signal.Signals, Any] = {}
Expand Down Expand Up @@ -498,6 +517,7 @@ def _cleanup(self) -> None:

atexit.unregister(self._cleanup)
self._restore_signal_handlers()
self._record_final_metrics()

# Clear JAX caches and run garbage collection.
_logger.info("Starting Pathways proxy cleanup.")
Expand Down Expand Up @@ -555,6 +575,23 @@ def _cleanup(self) -> None:
)
_logger.info("JAX variables restored.")

# Send the buffered metrics last, since this can wait for the Cloud
# Monitoring sampling window and should not delay releasing resources.
self.metrics_collector.close()

def _record_final_metrics(self) -> None:
"""Records the metric values for the end of this session.

Gauges keep their last value until the time series goes stale, so reset
the ones that this session set to a non-zero value.
"""
if self.placement_complete.is_set():
self.metrics_collector.record_active_user(False)
self.metrics_collector.record_capacity_in_use(0)
elif self._proxy_deployed:
# The user was waiting for capacity and never got it.
self.metrics_collector.record_user_waiting(False)


def _get_username() -> str:
"""Gets the username from the environment.
Expand Down Expand Up @@ -698,6 +735,7 @@ def connect(
t.metrics_collector,
t.start_time,
t.total_chips,
t.placement_complete,
),
daemon=True,
)
Expand Down
150 changes: 135 additions & 15 deletions pathwaysutils/experimental/shared_pathways_service/metrics_collector.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Metrics collector for Shared Pathways Service."""

import atexit
import dataclasses
import logging
import threading
import time
Expand Down Expand Up @@ -71,6 +72,42 @@
},
]

# Maximum number of times to try sending a metric point before dropping it.
_MAX_SEND_ATTEMPTS = 3

# Maximum time in seconds to wait for the background flusher thread to stop.
_FLUSHER_JOIN_TIMEOUT_S = 5


@dataclasses.dataclass
class _BufferedPoint:
"""A metric point waiting to be sent to Cloud Monitoring.

Attributes:
value: The value of the point.
value_type: The `TypedValue` field to set, for example "int64_value".
metric_labels: The labels to attach to the point.
attempts: The number of failed attempts to send the point so far.
"""

value: Any
value_type: str
metric_labels: Dict[str, str] | None
attempts: int = 0


def _is_retryable_error(error: Exception) -> bool:
"""Returns whether a failed Cloud Monitoring write may succeed if retried."""
return isinstance(
error,
(
exceptions.DeadlineExceeded,
exceptions.InternalServerError,
exceptions.ResourceExhausted,
exceptions.ServiceUnavailable,
),
)


class MetricsCollector:
"""Collects usage metrics for Shared Pathways Service and reports to Cloud Monitoring."""
Expand All @@ -87,17 +124,23 @@ def __init__(
self.client = monitoring_v3.MetricServiceClient()
self.project_name = f"projects/{self.project_id}"
self._lock = threading.Lock()
self._buffer: Dict[str, list[tuple[Any, str, Dict[str, str] | None]]] = {}
# Serializes flushes so that a point being sent, which may be put back in
# the buffer after a failure, is never skipped or overtaken by another
# flush. Held for all of `_shutdown()`.
self._flush_lock = threading.Lock()
self._buffer: Dict[str, list[_BufferedPoint]] = {}
self._last_sent_time: Dict[str, float] = {}
self._instance_id = str(uuid.uuid4())
self._running = True
self._stop_event = threading.Event()
self._close_lock = threading.Lock()
self._closed = False
for descriptor in _METRIC_DESCRIPTORS:
self._create_metric_descriptor(**descriptor)
self._flusher_thread = threading.Thread(
target=self._flush_loop, daemon=True
)
self._flusher_thread.start()
atexit.register(self._shutdown)
atexit.register(self.close)
_logger.info("Metrics collection initialized.")

def _create_time_series_object(
Expand Down Expand Up @@ -134,13 +177,18 @@ def _create_time_series_object(
return series

def _flush_loop(self):
"""Runs continuously to flush the metrics buffer."""
while self._running:
"""Runs continuously to flush the metrics buffer until stopped."""
while not self._stop_event.is_set():
self.flush()
time.sleep(1)
self._stop_event.wait(1)

def flush(self):
"""Sends any eligible buffered metrics to Cloud Monitoring."""
with self._flush_lock:
self._flush_locked()

def _flush_locked(self):
"""Implements `flush()`. The caller must hold `self._flush_lock`."""
with self._lock:
now = time.time()
to_send = []
Expand All @@ -151,18 +199,68 @@ def flush(self):
last_time = self._last_sent_time.get(metric_type, 0)
# Add a slight cushion (10.5s) to prevent sub-second drift errors.
if now - last_time >= 10.5 or last_time == 0:
item = queue.pop(0)
to_send.append((metric_type, *item))
point = queue.pop(0)
to_send.append((metric_type, point))
self._last_sent_time[metric_type] = now
if not queue:
del self._buffer[metric_type]

for metric_type, value, value_type, metric_labels in to_send:
self._transmit(metric_type, value, value_type, metric_labels)
for metric_type, point in to_send:
if self._transmit(
metric_type, point.value, point.value_type, point.metric_labels
):
continue
point.attempts += 1
if point.attempts >= _MAX_SEND_ATTEMPTS:
_logger.warning(
"Dropping metric %s after %d failed attempts.",
metric_type,
point.attempts,
)
continue
# Put the point back at the front of its queue so that it is retried
# before any newer points of the same metric. The retry waits for the
# next sampling window, which also spaces out the attempts.
with self._lock:
self._buffer.setdefault(metric_type, []).insert(0, point)

def close(self) -> None:
"""Stops background flushing and sends all buffered metrics.

Blocks until every buffered point is sent or dropped. Cloud Monitoring
accepts at most one point per time series every 10 seconds, so this can
take about 10.5 seconds for each point still queued for a metric. Metrics
recorded after this call are dropped.

This is safe to call more than once. If it is never called, it runs when
the interpreter exits.
"""
with self._close_lock:
if self._closed:
return
self._closed = True
atexit.unregister(self.close)
self._stop_event.set()
if self._flusher_thread is not threading.current_thread():
self._flusher_thread.join(timeout=_FLUSHER_JOIN_TIMEOUT_S)
if self._flusher_thread.is_alive():
_logger.warning(
"Metrics flusher thread did not stop within %s seconds.",
_FLUSHER_JOIN_TIMEOUT_S,
)
self._shutdown()

def _shutdown(self):
"""Synchronously drains the final state of the queue before exiting."""
self._running = False
self._stop_event.set()
# Holding the flush lock waits for any flush in progress on the flusher
# thread, so that a point it puts back after a failure is still drained
# here, and keeps that thread from flushing until the drain is done.
with self._flush_lock:
self._drain_locked()

def _drain_locked(self):
"""Implements `_shutdown()`. The caller must hold `self._flush_lock`."""
while True:
with self._lock:
if not any(self._buffer.values()):
Expand All @@ -181,7 +279,7 @@ def _shutdown(self):
"Waiting %.1fs for Cloud Monitoring sampling window...", min_wait
)
time.sleep(min_wait)
self.flush()
self._flush_locked()

def _send_metric(
self,
Expand All @@ -191,6 +289,13 @@ def _send_metric(
metric_labels: Dict[str, str] | None = None,
):
"""Queues a single metric in the buffer."""
if self._closed:
_logger.warning(
"Metrics collector is closed. Dropping metric %s: %s",
metric_type,
value,
)
return
default_labels = {"client_instance_id": self._instance_id}
default_labels["cluster_name"] = self.cluster_name
if self.job_name:
Expand All @@ -210,16 +315,29 @@ def _send_metric(
metric_type,
(value, value_type, default_labels),
)
self._buffer[metric_type].append((value, value_type, default_labels))
self._buffer[metric_type].append(
_BufferedPoint(value, value_type, default_labels)
)

def _transmit(
self,
metric_type: str,
value: Any,
value_type: str,
metric_labels: Dict[str, str] | None = None,
):
"""Physically transmits a TimeSeries to Cloud Monitoring."""
) -> bool:
"""Physically transmits a TimeSeries to Cloud Monitoring.

Args:
metric_type: The metric name, without `METRIC_PREFIX`.
value: The value of the point.
value_type: The `TypedValue` field to set, for example "int64_value".
metric_labels: The labels to attach to the point.

Returns:
False if the write failed with an error that may go away on retry, and
True otherwise, including when the write failed permanently.
"""
series = self._create_time_series_object(
metric_type, value, value_type, metric_labels
)
Expand All @@ -230,6 +348,8 @@ def _transmit(
_logger.info("Sent metric %s: %s", metric_type, value)
except exceptions.GoogleAPICallError as e:
_logger.warning("Failed to send metric %s: %s", metric_type, e)
return not _is_retryable_error(e)
return True

def _create_metric_descriptor(
self,
Expand Down
Loading
Loading