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
@@ -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,39 @@
},
]

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


@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,7 +121,7 @@ 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]]] = {}
self._buffer: Dict[str, list[_BufferedPoint]] = {}
self._last_sent_time: Dict[str, float] = {}
self._instance_id = str(uuid.uuid4())
self._running = True
Expand Down Expand Up @@ -151,14 +185,30 @@ 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 _shutdown(self):
"""Synchronously drains the final state of the queue before exiting."""
Expand Down Expand Up @@ -210,16 +260,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 +293,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
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,119 @@ def mock_time_func():
self.assertEqual(mock_client.create_time_series.call_count, 2)
mock_sleep.assert_called()

def _create_collector_without_flusher(self, mock_client_class):
"""Creates a collector whose background flusher thread is stopped."""
mock_client = mock.Mock()
mock_client_class.return_value = mock_client
collector = metrics_collector.MetricsCollector("gcp_project", "gke_cluster")
collector._running = False
collector._flusher_thread.join()
return collector, mock_client

def _flush_after_sampling_window(self, collector, metric_type):
"""Flushes as if the Cloud Monitoring sampling window has passed."""
with mock.patch(
"time.time",
return_value=collector._last_sent_time[metric_type] + 11.0,
):
collector.flush()

@mock.patch(
"pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient"
)
def test_flush_retries_point_after_transient_error(self, mock_client_class):
collector, mock_client = self._create_collector_without_flusher(
mock_client_class
)
mock_client.create_time_series.side_effect = [
metrics_collector.exceptions.ServiceUnavailable("unavailable"),
None,
]
collector.record_capacity_in_use(16)
collector.record_capacity_in_use(0)

collector.flush()

# The failed point goes back to the front of the queue.
queue = collector._buffer["capacity_in_use"]
self.assertEqual([point.value for point in queue], [16, 0])
self.assertEqual(queue[0].attempts, 1)

self._flush_after_sampling_window(collector, "capacity_in_use")

self.assertEqual(mock_client.create_time_series.call_count, 2)
_, kwargs = mock_client.create_time_series.call_args
self.assertEqual(
kwargs["time_series"][0].points[0].value.int64_value, 16
)
self.assertEqual(
[point.value for point in collector._buffer["capacity_in_use"]], [0]
)

@mock.patch(
"pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient"
)
def test_flush_drops_point_after_permanent_error(self, mock_client_class):
collector, mock_client = self._create_collector_without_flusher(
mock_client_class
)
mock_client.create_time_series.side_effect = (
metrics_collector.exceptions.InvalidArgument("written too frequently")
)
collector.record_capacity_in_use(16)

collector.flush()

mock_client.create_time_series.assert_called_once()
self.assertNotIn("capacity_in_use", collector._buffer)

@mock.patch(
"pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient"
)
def test_flush_drops_point_after_max_attempts(self, mock_client_class):
collector, mock_client = self._create_collector_without_flusher(
mock_client_class
)
mock_client.create_time_series.side_effect = (
metrics_collector.exceptions.ServiceUnavailable("unavailable")
)
collector.record_capacity_in_use(16)

collector.flush()
for _ in range(metrics_collector._MAX_SEND_ATTEMPTS - 1):
self._flush_after_sampling_window(collector, "capacity_in_use")

self.assertEqual(
mock_client.create_time_series.call_count,
metrics_collector._MAX_SEND_ATTEMPTS,
)
self.assertNotIn("capacity_in_use", collector._buffer)

@mock.patch(
"pathwaysutils.experimental.shared_pathways_service.metrics_collector.monitoring_v3.MetricServiceClient"
)
def test_shutdown_retries_transient_errors(self, mock_client_class):
collector, mock_client = self._create_collector_without_flusher(
mock_client_class
)
mock_client.create_time_series.side_effect = [
metrics_collector.exceptions.DeadlineExceeded("deadline"),
None,
]
collector.record_capacity_in_use(0)

current_time = [1000.0]

def mock_sleep_func(seconds):
current_time[0] += seconds

with mock.patch("time.sleep", side_effect=mock_sleep_func):
with mock.patch("time.time", side_effect=lambda: current_time[0]):
collector._shutdown()

self.assertEqual(mock_client.create_time_series.call_count, 2)
self.assertNotIn("capacity_in_use", collector._buffer)


if __name__ == "__main__":
absltest.main()
Loading