|
13 | 13 | # limitations under the License. |
14 | 14 |
|
15 | 15 | from collections import OrderedDict |
| 16 | +from datetime import datetime |
16 | 17 | import six |
17 | 18 | import threading |
18 | 19 |
|
19 | 20 | from opencensus.common import utils |
20 | 21 | from opencensus.metrics.export import metric |
21 | 22 | from opencensus.metrics.export import metric_descriptor |
| 23 | +from opencensus.metrics.export import metric_producer |
22 | 24 | from opencensus.metrics.export import point as point_module |
23 | 25 | from opencensus.metrics.export import time_series |
24 | 26 | from opencensus.metrics.export import value as value_module |
@@ -430,3 +432,57 @@ class DerivedLongGauge(LongGaugeMixin, DerivedGauge): |
430 | 432 |
|
431 | 433 | class DerivedDoubleGauge(DoubleGaugeMixin, DerivedGauge): |
432 | 434 | """Gauge for derived float-valued measurements.""" |
| 435 | + |
| 436 | + |
| 437 | +class Registry(metric_producer.MetricProducer): |
| 438 | + """A collection of gauges to be exported together. |
| 439 | +
|
| 440 | + Each registered gauge must have a unique `descriptor.name`. |
| 441 | + """ |
| 442 | + |
| 443 | + def __init__(self): |
| 444 | + self.gauges = {} |
| 445 | + self._gauges_lock = threading.Lock() |
| 446 | + |
| 447 | + def __repr__(self): |
| 448 | + return ('{}(gauges={}' |
| 449 | + .format( |
| 450 | + type(self).__name__, |
| 451 | + self.gauges |
| 452 | + )) |
| 453 | + |
| 454 | + def add_gauge(self, gauge): |
| 455 | + """Add `gauge` to the registry and return it. |
| 456 | +
|
| 457 | + Raises a `ValueError` if another gauge with the same name already |
| 458 | + exists in the registry. |
| 459 | +
|
| 460 | + :type gauge: class:`LongGauge`, class:`DoubleGauge`, |
| 461 | + :class:`DerivedLongGauge`, or :class:`DerivedDoubleGauge` |
| 462 | + :param gauge: The gauge to add to the registry. |
| 463 | +
|
| 464 | + :type gauge: class:`LongGauge`, class:`DoubleGauge`, |
| 465 | + :class:`DerivedLongGauge`, or :class:`DerivedDoubleGauge` |
| 466 | + :return: The gauge that was added to the registry. |
| 467 | + """ |
| 468 | + if gauge is None: |
| 469 | + raise ValueError |
| 470 | + name = gauge.descriptor.name |
| 471 | + with self._gauges_lock: |
| 472 | + if name in self.gauges: |
| 473 | + raise ValueError( |
| 474 | + 'Another gauge named "{}" is already registered' |
| 475 | + .format(name)) |
| 476 | + self.gauges[name] = gauge |
| 477 | + |
| 478 | + def get_metrics(self): |
| 479 | + """Get a metric for each gauge in the registry at the current time. |
| 480 | +
|
| 481 | + :rtype: set(:class:`opencensus.metrics.export.metric.Metric`) |
| 482 | + :return: A set of `Metric`s, one for each registered gauge. |
| 483 | + """ |
| 484 | + now = datetime.now() |
| 485 | + metrics = set() |
| 486 | + for gauge in self.gauges.values(): |
| 487 | + metrics.add(gauge.get_metric(now)) |
| 488 | + return metrics |
0 commit comments