|
| 1 | +"""AWS CloudWatch metrics client for workflow submission tracking.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | + |
| 7 | +import boto3 |
| 8 | + |
| 9 | +from dsc.config import METRICS, METRICS_NAMESPACE |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +UNIT_VALUES = frozenset( |
| 15 | + [ |
| 16 | + "Seconds", |
| 17 | + "Microseconds", |
| 18 | + "Milliseconds", |
| 19 | + "Bytes", |
| 20 | + "Kilobytes", |
| 21 | + "Megabytes", |
| 22 | + "Gigabytes", |
| 23 | + "Terabytes", |
| 24 | + "Bits", |
| 25 | + "Kilobits", |
| 26 | + "Megabits", |
| 27 | + "Gigabits", |
| 28 | + "Terabits", |
| 29 | + "Percent", |
| 30 | + "Count", |
| 31 | + "Bytes/Second", |
| 32 | + "Kilobytes/Second", |
| 33 | + "Megabytes/Second", |
| 34 | + "Gigabytes/Second", |
| 35 | + "Terabytes/Second", |
| 36 | + "Bits/Second", |
| 37 | + "Kilobits/Second", |
| 38 | + "Megabits/Second", |
| 39 | + "Gigabits/Second", |
| 40 | + "Terabits/Second", |
| 41 | + "Count/Second", |
| 42 | + ] |
| 43 | +) |
| 44 | + |
| 45 | + |
| 46 | +class MetricsClient: |
| 47 | + """A simple client to record metrics to AWS CloudWatch.""" |
| 48 | + |
| 49 | + def __init__(self) -> None: |
| 50 | + """Initialize the MetricsClient.""" |
| 51 | + self.cloudwatch = boto3.client("cloudwatch") |
| 52 | + self.batch_metrics: list[dict] = [] |
| 53 | + |
| 54 | + def publish_single_metric( |
| 55 | + self, |
| 56 | + metric_name: str, |
| 57 | + value: int, |
| 58 | + unit: str, |
| 59 | + metric_dimensions: dict[str, str] | None = None, |
| 60 | + ) -> None: |
| 61 | + """Publish a single metric to CloudWatch. |
| 62 | +
|
| 63 | + Args: |
| 64 | + metric_name: The name of the metric to publish. |
| 65 | + value: The value of the metric. |
| 66 | + unit: The unit of the metric. |
| 67 | + metric_dimensions: Optional dictionary of dimension names and values. |
| 68 | +
|
| 69 | + Raises: |
| 70 | + ValueError: If unit is invalid. |
| 71 | + """ |
| 72 | + metric_data = self._validate_and_build_metric_data( |
| 73 | + metric_name, value, unit, metric_dimensions |
| 74 | + ) |
| 75 | + self._push_metric_data([metric_data]) |
| 76 | + |
| 77 | + def _validate_and_build_metric_data( |
| 78 | + self, |
| 79 | + metric_name: str, |
| 80 | + value: int, |
| 81 | + unit: str, |
| 82 | + metric_dimensions: dict[str, str] | None = None, |
| 83 | + ) -> dict: |
| 84 | + """Validate and build a metric data dictionary for CloudWatch. |
| 85 | +
|
| 86 | + Args: |
| 87 | + metric_name: The name of the metric. |
| 88 | + value: The value of the metric. |
| 89 | + unit: The unit of the metric. |
| 90 | + metric_dimensions: Optional dictionary of dimension names and values. |
| 91 | +
|
| 92 | + Returns: |
| 93 | + A metric data dictionary formatted for CloudWatch. |
| 94 | + """ |
| 95 | + self._approved_metric(metric_name) |
| 96 | + self._validate_unit(unit) |
| 97 | + dimensions = [ |
| 98 | + {"Name": name, "Value": dim_value} |
| 99 | + for name, dim_value in ( |
| 100 | + metric_dimensions.items() if metric_dimensions else [] |
| 101 | + ) |
| 102 | + ] |
| 103 | + return { |
| 104 | + "MetricName": metric_name, |
| 105 | + "Value": value, |
| 106 | + "Unit": unit, |
| 107 | + "Dimensions": dimensions, |
| 108 | + } |
| 109 | + |
| 110 | + def _approved_metric(self, metric_name: str) -> bool: |
| 111 | + """Check if a metric name is in the approved list of metrics for the application. |
| 112 | +
|
| 113 | + Args: |
| 114 | + metric_name: The name of the metric to check. |
| 115 | + """ |
| 116 | + if metric_name not in METRICS: |
| 117 | + raise ValueError( |
| 118 | + f"Metric name '{metric_name}' is not in the approved list of metrics: " |
| 119 | + f"{', '.join(METRICS)}" |
| 120 | + ) |
| 121 | + return True |
| 122 | + |
| 123 | + def _validate_unit(self, unit: str) -> None: |
| 124 | + """Validate that metric unit is allowed by AWS CloudWatch. |
| 125 | +
|
| 126 | + Args: |
| 127 | + unit: The unit to validate. |
| 128 | +
|
| 129 | + Raises: |
| 130 | + ValueError: If unit is not allowed by AWS CloudWatch. |
| 131 | + """ |
| 132 | + if unit not in UNIT_VALUES: |
| 133 | + raise ValueError( |
| 134 | + f"Invalid unit '{unit}'. Must be one of: {', '.join(UNIT_VALUES)}" |
| 135 | + ) |
| 136 | + |
| 137 | + def _push_metric_data(self, metric_data: list[dict]) -> None: |
| 138 | + """Push metric data to CloudWatch. |
| 139 | +
|
| 140 | + Args: |
| 141 | + metric_data: List of metric dictionaries to push. |
| 142 | + """ |
| 143 | + try: |
| 144 | + self.cloudwatch.put_metric_data( |
| 145 | + Namespace=METRICS_NAMESPACE, MetricData=metric_data |
| 146 | + ) |
| 147 | + logger.info(f"Published metric with {metric_data} to CloudWatch.") |
| 148 | + except Exception: |
| 149 | + logger.exception( |
| 150 | + f"Failed to publish metric with {metric_data} to CloudWatch." |
| 151 | + ) |
| 152 | + |
| 153 | + def add_metric_to_batch( |
| 154 | + self, |
| 155 | + metric_name: str, |
| 156 | + value: int, |
| 157 | + unit: str, |
| 158 | + metric_dimensions: dict[str, str] | None = None, |
| 159 | + ) -> None: |
| 160 | + """Add a metric to the batch for later publishing. |
| 161 | +
|
| 162 | + Args: |
| 163 | + metric_name: The name of the metric. |
| 164 | + value: The value of the metric. |
| 165 | + unit: The unit of the metric. |
| 166 | + metric_dimensions: Optional dictionary of dimension names and values. |
| 167 | +
|
| 168 | + Raises: |
| 169 | + ValueError: If unit is invalid. |
| 170 | + """ |
| 171 | + metric_data = self._validate_and_build_metric_data( |
| 172 | + metric_name, value, unit, metric_dimensions |
| 173 | + ) |
| 174 | + self.batch_metrics.append(metric_data) |
| 175 | + |
| 176 | + def publish_batch_metrics(self, batch_size: int = 20) -> None: |
| 177 | + """Publish all accumulated batch metrics to CloudWatch. |
| 178 | +
|
| 179 | + Raises: |
| 180 | + ValueError: If any metric has an invalid unit or missing required fields. |
| 181 | + """ |
| 182 | + if not self.batch_metrics: |
| 183 | + logger.info("No metrics to publish.") |
| 184 | + return |
| 185 | + |
| 186 | + # Validate all metrics before publishing |
| 187 | + for metric in self.batch_metrics: |
| 188 | + if not all(key in metric for key in ["MetricName", "Value", "Unit"]): |
| 189 | + raise ValueError( |
| 190 | + f"Each metric must contain 'MetricName', 'Value', and 'Unit'. " |
| 191 | + f"Invalid metric: {metric}" |
| 192 | + ) |
| 193 | + self._approved_metric(metric["MetricName"]) |
| 194 | + self._validate_unit(metric["Unit"]) |
| 195 | + |
| 196 | + for x in range(0, len(self.batch_metrics), batch_size): |
| 197 | + self._push_metric_data(self.batch_metrics[x : x + batch_size]) |
| 198 | + self.batch_metrics.clear() |
0 commit comments