|
| 1 | +import logging |
| 2 | +from typing import Optional, Sequence |
| 3 | + |
| 4 | +import google.auth |
| 5 | +from google.api.label_pb2 import LabelDescriptor |
| 6 | +from google.api.metric_pb2 import MetricDescriptor |
| 7 | +from google.cloud.monitoring_v3 import MetricServiceClient |
| 8 | +from google.cloud.monitoring_v3.proto.metric_pb2 import TimeSeries |
| 9 | + |
| 10 | +from opentelemetry.sdk.metrics.export import ( |
| 11 | + MetricRecord, |
| 12 | + MetricsExporter, |
| 13 | + MetricsExportResult, |
| 14 | +) |
| 15 | +from opentelemetry.sdk.metrics.export.aggregate import CounterAggregator |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | +MAX_BATCH_WRITE = 200 |
| 19 | +WRITE_INTERVAL = 10 |
| 20 | + |
| 21 | + |
| 22 | +# pylint is unable to resolve members of protobuf objects |
| 23 | +# pylint: disable=no-member |
| 24 | +class CloudMonitoringMetricsExporter(MetricsExporter): |
| 25 | + """ Implementation of Metrics Exporter to Google Cloud Monitoring""" |
| 26 | + |
| 27 | + def __init__(self, project_id=None, client=None): |
| 28 | + self.client = client or MetricServiceClient() |
| 29 | + if not project_id: |
| 30 | + _, self.project_id = google.auth.default() |
| 31 | + else: |
| 32 | + self.project_id = project_id |
| 33 | + self.project_name = self.client.project_path(self.project_id) |
| 34 | + self._metric_descriptors = {} |
| 35 | + self._last_updated = {} |
| 36 | + |
| 37 | + def _add_resource_info(self, series: TimeSeries) -> None: |
| 38 | + """Add Google resource specific information (e.g. instance id, region). |
| 39 | +
|
| 40 | + Args: |
| 41 | + series: ProtoBuf TimeSeries |
| 42 | + """ |
| 43 | + # TODO: Leverage this better |
| 44 | + |
| 45 | + def _batch_write(self, series: TimeSeries) -> None: |
| 46 | + """ Cloud Monitoring allows writing up to 200 time series at once |
| 47 | +
|
| 48 | + :param series: ProtoBuf TimeSeries |
| 49 | + :return: |
| 50 | + """ |
| 51 | + write_ind = 0 |
| 52 | + while write_ind < len(series): |
| 53 | + self.client.create_time_series( |
| 54 | + self.project_name, |
| 55 | + series[write_ind : write_ind + MAX_BATCH_WRITE], |
| 56 | + ) |
| 57 | + write_ind += MAX_BATCH_WRITE |
| 58 | + |
| 59 | + def _get_metric_descriptor( |
| 60 | + self, record: MetricRecord |
| 61 | + ) -> Optional[MetricDescriptor]: |
| 62 | + """ We can map Metric to MetricDescriptor using Metric.name or |
| 63 | + MetricDescriptor.type. We create the MetricDescriptor if it doesn't |
| 64 | + exist already and cache it. Note that recreating MetricDescriptors is |
| 65 | + a no-op if it already exists. |
| 66 | +
|
| 67 | + :param record: |
| 68 | + :return: |
| 69 | + """ |
| 70 | + descriptor_type = "custom.googleapis.com/OpenTelemetry/{}".format( |
| 71 | + record.metric.name |
| 72 | + ) |
| 73 | + if descriptor_type in self._metric_descriptors: |
| 74 | + return self._metric_descriptors[descriptor_type] |
| 75 | + descriptor = { |
| 76 | + "name": None, |
| 77 | + "type": descriptor_type, |
| 78 | + "display_name": record.metric.name, |
| 79 | + "description": record.metric.description, |
| 80 | + "labels": [], |
| 81 | + } |
| 82 | + for key, value in record.labels: |
| 83 | + if isinstance(value, str): |
| 84 | + descriptor["labels"].append( |
| 85 | + LabelDescriptor(key=key, value_type="STRING") |
| 86 | + ) |
| 87 | + elif isinstance(value, bool): |
| 88 | + descriptor["labels"].append( |
| 89 | + LabelDescriptor(key=key, value_type="BOOL") |
| 90 | + ) |
| 91 | + elif isinstance(value, int): |
| 92 | + descriptor["labels"].append( |
| 93 | + LabelDescriptor(key=key, value_type="INT64") |
| 94 | + ) |
| 95 | + else: |
| 96 | + logger.warning( |
| 97 | + "Label value %s is not a string, bool or integer", value |
| 98 | + ) |
| 99 | + if isinstance(record.aggregator, CounterAggregator): |
| 100 | + descriptor["metric_kind"] = MetricDescriptor.MetricKind.GAUGE |
| 101 | + else: |
| 102 | + logger.warning( |
| 103 | + "Unsupported aggregation type %s, ignoring it", |
| 104 | + type(record.aggregator).__name__, |
| 105 | + ) |
| 106 | + return None |
| 107 | + if record.metric.value_type == int: |
| 108 | + descriptor["value_type"] = MetricDescriptor.ValueType.INT64 |
| 109 | + elif record.metric.value_type == float: |
| 110 | + descriptor["value_type"] = MetricDescriptor.ValueType.DOUBLE |
| 111 | + proto_descriptor = MetricDescriptor(**descriptor) |
| 112 | + try: |
| 113 | + descriptor = self.client.create_metric_descriptor( |
| 114 | + self.project_name, proto_descriptor |
| 115 | + ) |
| 116 | + # pylint: disable=broad-except |
| 117 | + except Exception as ex: |
| 118 | + logger.error( |
| 119 | + "Failed to create metric descriptor %s", |
| 120 | + proto_descriptor, |
| 121 | + exc_info=ex, |
| 122 | + ) |
| 123 | + return None |
| 124 | + self._metric_descriptors[descriptor_type] = descriptor |
| 125 | + return descriptor |
| 126 | + |
| 127 | + def export( |
| 128 | + self, metric_records: Sequence[MetricRecord] |
| 129 | + ) -> "MetricsExportResult": |
| 130 | + all_series = [] |
| 131 | + for record in metric_records: |
| 132 | + metric_descriptor = self._get_metric_descriptor(record) |
| 133 | + if not metric_descriptor: |
| 134 | + continue |
| 135 | + |
| 136 | + series = TimeSeries() |
| 137 | + self._add_resource_info(series) |
| 138 | + series.metric.type = metric_descriptor.type |
| 139 | + for key, value in record.labels: |
| 140 | + series.metric.labels[key] = str(value) |
| 141 | + |
| 142 | + point = series.points.add() |
| 143 | + if record.metric.value_type == int: |
| 144 | + point.value.int64_value = record.aggregator.checkpoint |
| 145 | + elif record.metric.value_type == float: |
| 146 | + point.value.double_value = record.aggregator.checkpoint |
| 147 | + seconds, nanos = divmod( |
| 148 | + record.aggregator.last_update_timestamp, 1e9 |
| 149 | + ) |
| 150 | + |
| 151 | + # Cloud Monitoring API allows, for any combination of labels and |
| 152 | + # metric name, one update per WRITE_INTERVAL seconds |
| 153 | + updated_key = (metric_descriptor.type, record.labels) |
| 154 | + last_updated_seconds = self._last_updated.get(updated_key, 0) |
| 155 | + if seconds <= last_updated_seconds + WRITE_INTERVAL: |
| 156 | + continue |
| 157 | + self._last_updated[updated_key] = seconds |
| 158 | + point.interval.end_time.seconds = int(seconds) |
| 159 | + point.interval.end_time.nanos = int(nanos) |
| 160 | + all_series.append(series) |
| 161 | + try: |
| 162 | + self._batch_write(all_series) |
| 163 | + # pylint: disable=broad-except |
| 164 | + except Exception as ex: |
| 165 | + logger.error( |
| 166 | + "Error while writing to Cloud Monitoring", exc_info=ex |
| 167 | + ) |
| 168 | + return MetricsExportResult.FAILURE |
| 169 | + return MetricsExportResult.SUCCESS |
0 commit comments