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