kibana_prometheus_exporter.helpers.url_join()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 11
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 11
rs 10
c 0
b 0
f 0
cc 1
nop 2
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