kibana_prometheus_exporter.helpers   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 22
dl 0
loc 47
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A TimestampMixin.add_metric() 0 4 2
A TimestampMixin.__init__() 0 6 2

1 Function

Rating   Name   Duplication   Size   Complexity  
A url_join() 0 11 1
1
from urllib.parse import urljoin
2
3
from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily
4
5
6
class TimestampMixin(object):
7
    """Add timestamps to *MetricFamily
8
9
    The goal is to be a generic drop-in replacement for *MetricFamily.
10
    That means that we can be called with the exact same signature as the original class.
11
    We don't care about any other argument.
12
    The sole assumption is that timestamp is not an argument expected by *MetricFamily.
13
    """
14
15
    def __init__(self, *args, **kwargs):
16
        try:
17
            self._timestamp = kwargs.pop("timestamp")
18
        except KeyError:
19
            self._timestamp = None
20
        super(TimestampMixin, self).__init__(*args, **kwargs)
21
22
    def add_metric(self, *args, **kwargs):
23
        if "timestamp" not in kwargs:
24
            kwargs["timestamp"] = self._timestamp
25
        super(TimestampMixin, self).add_metric(*args, **kwargs)
26
27
28
class TimestampGaugeMetricFamily(TimestampMixin, GaugeMetricFamily):
29
    pass
30
31
32
class TimestampCounterMetricFamily(TimestampMixin, CounterMetricFamily):
33
    pass
34
35
36
def url_join(host: str, path: str) -> str:
37
    """Produce an URL as expected when the host part has a path.
38
39
    The idea is to always have the host end with a `/` and the path be relative. This way `urljoin` keeps both.
40
    As `urljoin` removes superfluous slashes, there's no need to check wether `host` ends with one.
41
42
    This addresses https://github.com/vladvasiliu/kibana-prometheus-exporter-py/issues/4
43
    """
44
    host += "/"
45
    path = path.lstrip("/")
46
    return urljoin(host, path)
47