summaryrefslogtreecommitdiffstats
path: root/python/knot_exporter/knot_exporter/knot_exporter.py
blob: 32f3339b175a07e3b55a632e15584b98578bda74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#!/usr/bin/env python3

import argparse
import http.server
import ipaddress
import psutil
import re
import socket
import subprocess

import libknot
import libknot.control

from prometheus_client.core import REGISTRY
from prometheus_client.core import GaugeMetricFamily
from prometheus_client.exposition import MetricsHandler


def memory_usage():
    out = dict()
    try:
        pids = subprocess.check_output(['pidof', 'knotd']).decode().split()
        for pid in pids:
            out[pid] = psutil.Process(int(pid)).memory_info()._asdict()['rss']
    finally:
        return out


class KnotCollector(object):
    def __init__(self, lib, sock, ttl,
            collect_meminfo : bool,
            collect_stats : bool,
            collect_zone_stats : bool,
            collect_zone_status : bool,
            collect_zone_timers : bool,
            collect_zone_serial : bool,):
        libknot.Knot(lib)
        self._sock = sock
        self._ttl = ttl
        self.collect_meminfo = collect_meminfo
        self.collect_stats = collect_stats
        self.collect_zone_stats = collect_zone_stats
        self.collect_zone_status = collect_zone_status
        self.collect_zone_timers = collect_zone_timers
        self.collect_zone_serial = collect_zone_serial

    def convert_state_time(time):
        if time == "pending" or time == "running" or time == "frozen":
            return 0
        elif time == "not scheduled" or time == "-":
            return None
        else:
            match = re.match("([+-])((\d+)D)?((\d+)h)?((\d+)m)?((\d+)s)?", time)
            seconds = -1 if match.group(1) == '-' else 1
            if match.group(3):
                seconds = seconds + 86400 * int(match.group(3))
            if match.group(5):
                seconds = seconds + 3600 * int(match.group(5))
            if match.group(7):
                seconds = seconds + 60 * int(match.group(7))
            if match.group(9):
                seconds = seconds + int(match.group(9))

        return seconds

    def collect(self):
        ctl = libknot.control.KnotCtl()
        ctl.connect(self._sock)
        ctl.set_timeout(self._ttl)
        metric_families = dict()

        def metric_families_append(family, labels, labels_val, data):
            m = metric_families.get(family, GaugeMetricFamily(family, '', labels=labels))
            m.add_metric(labels_val, data)
            metric_families[family] = m

        if self.collect_meminfo:
            # Get global metrics.
            for pid, usage in memory_usage().items():
                metric_families_append('knot_memory_usage', ['section', 'type'], ['server', str(pid)], usage)

        if self.collect_stats:
            ctl.send_block(cmd="stats", flags="")
            global_stats = ctl.receive_stats()

            for section, section_data in global_stats.items():
                for item, item_data in section_data.items():
                    name = ('knot_' + item).replace('-', '_')
                    try:
                        for kind, kind_data in item_data.items():
                            metric_families_append(name, ['section', 'type'], [section, kind], kind_data)

                    except AttributeError:
                        metric_families_append(name, ['section'], [section], item_data)

        if self.collect_zone_stats:
            # Get zone metrics.
            ctl.send_block(cmd="zone-stats", flags="")
            zone_stats = ctl.receive_stats()

            if "zone" in zone_stats:
                for zone, zone_data in zone_stats["zone"].items():
                    for section, section_data in zone_data.items():
                        for item, item_data in section_data.items():
                            name = ('knot_' + item).replace('-', '_')
                            try:
                                for kind, kind_data in item_data.items():
                                    metric_families_append(name, ['zone', 'section', 'type'], [zone, section, kind], kind_data)
                            except AttributeError:
                                metric_families_append(name, ['zone', 'section'], [zone, section], item_data)

        if self.collect_zone_status:
            # zone state metrics
            ctl.send_block(cmd="zone-status")
            zone_states = ctl.receive_block()

            for zone, info in zone_states.items():
                if self.collect_zone_serial:
                    serial = info.get('serial', False)
                    if serial and serial != "none" and serial != "-":
                        metric_families_append('knot_zone_serial', ['zone'], [zone], int(serial))

                metrics = ['expiration', 'refresh']

                for metric in metrics:
                    seconds = KnotCollector.convert_state_time(info[metric])
                    if seconds == None:
                        continue

                    metric_families_append('knot_zone_stats_' + metric, ['zone'], [zone], seconds)

        if self.collect_zone_timers:
            # zone configuration metrics
            ctl.send_block(cmd="zone-read", rtype="SOA")
            zones = ctl.receive_block()

            for name, params in zones.items():
                metrics = [
                    {"name": "knot_zone_refresh",    "index": 3},
                    {"name": "knot_zone_retry",      "index": 4},
                    {"name": "knot_zone_expiration", "index": 5},
                ]

                zone_config = params[name]['SOA']['data'][0].split(" ")

                for metric in metrics:
                    metric_families_append(metric['name'], ['zone'], [name], int(zone_config[metric['index']]))

        for val in metric_families.values():
            yield val


def main():
    parser = argparse.ArgumentParser(
        formatter_class = argparse.ArgumentDefaultsHelpFormatter,
    )

    parser.add_argument(
        "--web-listen-addr",
        default="127.0.0.1",
        help="address on which to expose metrics."
    )

    parser.add_argument(
        "--web-listen-port",
        type=int,
        default=9433,
        help="port on which to expose metrics."
    )

    parser.add_argument(
        "--knot-library-path",
        default=None,
        help="path to libknot."
    )

    parser.add_argument(
        "--knot-socket-path",
        default="/run/knot/knot.sock",
        help="path to knot control socket."
    )

    parser.add_argument(
        "--knot-socket-timeout",
        type=int,
        default=2000,
        help="timeout for Knot control socket operations."
    )

    parser.add_argument(
        "--no-meminfo",
        action='store_false',
        help="disable collection of memory usage"
    )

    parser.add_argument(
        "--no-global-stats",
        action='store_false',
        help="disable collection of global statistics"
    )

    parser.add_argument(
        "--no-zone-stats",
        action='store_false',
        help="disable collection of zone statistics"
    )

    parser.add_argument(
        "--no-zone-status",
        action='store_false',
        help="disable collection of zone status"
    )

    parser.add_argument(
        "--no-zone-timers",
        action='store_false',
        help="disable collection of zone timer settings"
    )

    parser.add_argument(
        "--no-zone-serial",
        action='store_false',
        help="disable collection of zone serial"
    )

    args = parser.parse_args()

    REGISTRY.register(KnotCollector(
        args.knot_library_path,
        args.knot_socket_path,
        args.knot_socket_timeout,
        args.no_meminfo,
        args.no_global_stats,
        args.no_zone_stats,
        args.no_zone_status,
        args.no_zone_timers,
        args.no_zone_serial,
    ))

    class Server(http.server.HTTPServer):
        def __init__(self, server_address, RequestHandlerClass):
            ip = ipaddress.ip_address(server_address[0])
            self.address_family = socket.AF_INET6 if ip.version == 6 else socket.AF_INET
            super().__init__(server_address, RequestHandlerClass)

    httpd = Server(
        (args.web_listen_addr, args.web_listen_port),
        MetricsHandler,
    )

    httpd.serve_forever()


if __name__ == '__main__':
    main()