1 | # |
||
2 | # This file is part of Glances. |
||
3 | # |
||
4 | # SPDX-FileCopyrightText: 2022 Nicolas Hennion <[email protected]> |
||
5 | # |
||
6 | # SPDX-License-Identifier: LGPL-3.0-only |
||
7 | # |
||
8 | |||
9 | """Statsd interface class.""" |
||
10 | |||
11 | from numbers import Number |
||
12 | |||
13 | from statsd import StatsClient |
||
14 | |||
15 | from glances.exports.export import GlancesExport |
||
16 | from glances.logger import logger |
||
17 | |||
18 | |||
19 | class Export(GlancesExport): |
||
20 | """This class manages the Statsd export module.""" |
||
21 | |||
22 | View Code Duplication | def __init__(self, config=None, args=None): |
|
0 ignored issues
–
show
Duplication
introduced
by
Loading history...
|
|||
23 | """Init the Statsd export IF.""" |
||
24 | super().__init__(config=config, args=args) |
||
25 | |||
26 | # Mandatory configuration keys (additional to host and port) |
||
27 | # N/A |
||
28 | |||
29 | # Optional configuration keys |
||
30 | self.prefix = None |
||
31 | |||
32 | # Load the configuration file |
||
33 | self.export_enable = self.load_conf('statsd', mandatories=['host', 'port'], options=['prefix']) |
||
34 | if not self.export_enable: |
||
35 | exit('Missing STATSD config') |
||
36 | |||
37 | # Default prefix for stats is 'glances' |
||
38 | if self.prefix is None: |
||
39 | self.prefix = 'glances' |
||
40 | |||
41 | # Init the Statsd client |
||
42 | self.client = self.init() |
||
43 | |||
44 | def init(self): |
||
45 | """Init the connection to the Statsd server.""" |
||
46 | if not self.export_enable: |
||
47 | return None |
||
48 | logger.info(f"Stats will be exported to StatsD server: {self.host}:{self.port}") |
||
49 | return StatsClient(self.host, int(self.port), prefix=self.prefix) |
||
50 | |||
51 | View Code Duplication | def export(self, name, columns, points): |
|
0 ignored issues
–
show
|
|||
52 | """Export the stats to the Statsd server.""" |
||
53 | for i in range(len(columns)): |
||
54 | if not isinstance(points[i], Number): |
||
55 | continue |
||
56 | stat_name = f'{name}.{columns[i]}' |
||
57 | stat_value = points[i] |
||
58 | try: |
||
59 | self.client.gauge(normalize(stat_name), stat_value) |
||
60 | except Exception as e: |
||
61 | logger.error(f"Can not export stats to Statsd ({e})") |
||
62 | logger.debug(f"Export {name} stats to Statsd") |
||
63 | |||
64 | |||
65 | def normalize(name): |
||
66 | """Normalize name for the Statsd convention""" |
||
67 | |||
68 | # Name should not contain some specials chars (issue #1068) |
||
69 | ret = name.replace(':', '') |
||
70 | ret = ret.replace('%', '') |
||
71 | return ret.replace(' ', '_') |
||
72 |