Completed
Push — master ( 2b80fa...6ea077 )
by Nicolas
01:22
created

glances/exports/glances_opentsdb.py (2 issues)

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
"""OpenTSDB 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
import potsdb
30
31
32
class Export(GlancesExport):
33
34
    """This class manages the OpenTSDB export module."""
35
36 View Code Duplication
    def __init__(self, config=None, args=None):
37
        """Init the OpenTSDB 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.tags = None
45
        self.export_enable = self.load_conf()
46
        if not self.export_enable:
47
            sys.exit(2)
48
49
        # Default prefix for stats is 'glances'
50
        if self.prefix is None:
51
            self.prefix = 'glances'
52
53
        # Init the OpenTSDB client
54
        self.client = self.init()
55
56 View Code Duplication
    def load_conf(self, section="opentsdb"):
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
57
        """Load the OpenTSDB configuration in the Glances configuration file."""
58
        if self.config is None:
59
            return False
60
        try:
61
            self.host = self.config.get_value(section, 'host')
62
            self.port = self.config.get_value(section, 'port')
63
        except NoSectionError:
64
            logger.critical("No OpenTSDB configuration found")
65
            return False
66
        except NoOptionError as e:
67
            logger.critical("Error in the OpenTSDB configuration (%s)" % e)
68
            return False
69
        else:
70
            logger.debug("Load OpenTSDB from the Glances configuration file")
71
72
        # Prefix is optional
73
        try:
74
            self.prefix = self.config.get_value(section, 'prefix')
75
        except NoOptionError:
76
            pass
77
78
        # Tags are optional, comma separated key:value pairs.
79
        try:
80
            self.tags = self.config.get_value(section, 'tags')
81
        except NoOptionError:
82
            pass
83
84
        return True
85
86
    def init(self):
87
        """Init the connection to the OpenTSDB server."""
88
        if not self.export_enable:
89
            return None
90
91
        try:
92
            db = potsdb.Client(self.host,
93
                               port=int(self.port),
94
                               check_host=True)
95
        except Exception as e:
96
            logger.critical("Cannot connect to OpenTSDB server %s:%s (%s)" % (self.host, self.port, e))
97
            sys.exit(2)
98
99
        return db
100
101 View Code Duplication
    def export(self, name, columns, points):
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
102
        """Export the stats to the Statsd server."""
103
        for i in range(len(columns)):
104
            if not isinstance(points[i], Number):
105
                continue
106
            stat_name = '{}.{}.{}'.format(self.prefix, name, columns[i])
107
            stat_value = points[i]
108
            tags = self.parse_tags(self.tags)
109
            try:
110
                self.client.send(stat_name, stat_value, **tags)
111
            except Exception as e:
112
                logger.error("Can not export stats %s to OpenTSDB (%s)" % (name, e))
113
        logger.debug("Export {} stats to OpenTSDB".format(name))
114
115
    def exit(self):
116
        """Close the OpenTSDB export module."""
117
        # Waits for all outstanding metrics to be sent and background thread closes
118
        self.client.wait()
119
        # Call the father method
120
        super(Export, self).exit()
121