Completed
Push — master ( 12bab0...1806d1 )
by Nicolas
01:07
created

glances.exports.Export.load_conf()   B

Complexity

Conditions 6

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 6
dl 0
loc 21
rs 7.8867
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2015 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 NoOptionError, NoSectionError, 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
    def __init__(self, config=None, args=None):
37
        """Init the Statsd export IF."""
38
        super(Export, self).__init__(config=config, args=args)
39
40
        # Load the InfluxDB configuration file
41
        self.host = None
42
        self.port = None
43
        self.prefix = None
44
        self.export_enable = self.load_conf()
45
        if not self.export_enable:
46
            sys.exit(2)
47
48
        # Default prefix for stats is 'glances'
49
        if self.prefix is None:
50
            self.prefix = 'glances'
51
52
        # Init the Statsd client
53
        self.client = StatsClient(self.host,
54
                                  int(self.port),
55
                                  prefix=self.prefix)
56
57
    def load_conf(self, section="statsd"):
58
        """Load the Statsd configuration in the Glances configuration file."""
59
        if self.config is None:
60
            return False
61
        try:
62
            self.host = self.config.get_value(section, 'host')
63
            self.port = self.config.get_value(section, 'port')
64
        except NoSectionError:
65
            logger.critical("No Statsd configuration found")
66
            return False
67
        except NoOptionError as e:
68
            logger.critical("Error in the Statsd configuration (%s)" % e)
69
            return False
70
        else:
71
            logger.debug("Load Statsd from the Glances configuration file")
72
        # Prefix is optional
73
        try:
74
            self.prefix = self.config.get_value(section, 'prefix')
75
        except NoOptionError:
76
            pass
77
        return True
78
79
    def init(self, prefix='glances'):
80
        """Init the connection to the Statsd server."""
81
        if not self.export_enable:
82
            return None
83
        return StatsClient(self.host,
84
                           self.port,
85
                           prefix=prefix)
86
87
    def export(self, name, columns, points):
88
        """Export the stats to the Statsd server."""
89
        for i in range(len(columns)):
90
            if not isinstance(points[i], Number):
91
                continue
92
            stat_name = '{0}.{1}'.format(name, columns[i])
93
            stat_value = points[i]
94
            try:
95
                self.client.gauge(stat_name, stat_value)
96
            except Exception as e:
97
                logger.error("Can not export stats to Statsd (%s)" % e)
98
        logger.debug("Export {0} stats to Statsd".format(name))
99