Test Failed
Push — develop ( abf64f...1d1151 )
by Nicolas
02:59
created

glances/exports/glances_statsd.py (2 issues)

1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2019 Nicolargo <[email protected]>
6
#
7
# Glances is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Glances is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
"""Statsd interface class."""
21
22
import sys
23
from numbers import Number
24
25
from glances.compat import range
26
from glances.logger import logger
27
from glances.exports.glances_export import GlancesExport
28
29
from statsd import StatsClient
30
31
32
class Export(GlancesExport):
33
34
    """This class manages the Statsd export module."""
35
36 View Code Duplication
    def __init__(self, config=None, args=None):
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
37
        """Init the Statsd export IF."""
38
        super(Export, self).__init__(config=config, args=args)
39
40
        # Mandatories configuration keys (additional to host and port)
41
        # N/A
42
43
        # Optionals configuration keys
44
        self.prefix = None
45
46
        # Load the InfluxDB configuration file
47
        self.export_enable = self.load_conf('statsd',
48
                                            mandatories=['host', 'port'],
49
                                            options=['prefix'])
50
        if not self.export_enable:
51
            sys.exit(2)
52
53
        # Default prefix for stats is 'glances'
54
        if self.prefix is None:
55
            self.prefix = 'glances'
56
57
        # Init the Statsd client
58
        self.client = self.init()
59
60
    def init(self):
61
        """Init the connection to the Statsd server."""
62
        if not self.export_enable:
63
            return None
64
        logger.info(
65
            "Stats will be exported to StatsD server: {}:{}".format(self.host,
66
                                                                    self.port))
67
        return StatsClient(self.host,
68
                           int(self.port),
69
                           prefix=self.prefix)
70
71 View Code Duplication
    def export(self, name, columns, points):
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
72
        """Export the stats to the Statsd server."""
73
        for i in range(len(columns)):
74
            if not isinstance(points[i], Number):
75
                continue
76
            stat_name = '{}.{}'.format(name, columns[i])
77
            stat_value = points[i]
78
            try:
79
                self.client.gauge(normalize(stat_name),
80
                                  stat_value)
81
            except Exception as e:
82
                logger.error("Can not export stats to Statsd (%s)" % e)
83
        logger.debug("Export {} stats to Statsd".format(name))
84
85
86
def normalize(name):
87
    """Normalize name for the Statsd convention"""
88
89
    # Name should not contain some specials chars (issue #1068)
90
    ret = name.replace(':', '')
91
    ret = ret.replace('%', '')
92
    ret = ret.replace(' ', '_')
93
94
    return ret
95