glances_influxdb.py 4.9 KB
Newer Older
N
Nicolargo 已提交
1 2 3 4
# -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
5
# Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com>
N
Nicolargo 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

"""InfluxDB interface class."""

# Import sys libs
import sys
24 25 26 27
try:
    from configparser import NoOptionError, NoSectionError
except ImportError:  # Python 2
    from ConfigParser import NoOptionError, NoSectionError
N
Nicolargo 已提交
28 29 30 31 32

# Import Glances lib
from glances.core.glances_logging import logger
from glances.exports.glances_export import GlancesExport

33
from influxdb import InfluxDBClient, client
34
from influxdb.influxdb08 import InfluxDBClient as InfluxDBClient_Legacy
35

N
Nicolargo 已提交
36 37 38 39 40

class Export(GlancesExport):

    """This class manages the InfluxDB export module."""

41
    def __init__(self, config=None, args=None):
N
Nicolargo 已提交
42
        """Init the InfluxDB export IF."""
43
        GlancesExport.__init__(self, config=config, args=args)
N
Nicolargo 已提交
44

45
        # Load the InfluxDB configuration file
46 47 48 49 50 51
        self.host = None
        self.port = None
        self.user = None
        self.password = None
        self.db = None
        self.prefix = None
52 53 54
        self.export_enable = self.load_conf()
        if not self.export_enable:
            sys.exit(2)
N
Nicolargo 已提交
55 56

        # Init the InfluxDB client
57
        self.client = self.init()
N
Nicolargo 已提交
58

59
    def load_conf(self, section="influxdb"):
A
PEP 257  
Alessio Sergi 已提交
60
        """Load the InfluxDb configuration in the Glances configuration file."""
61 62 63
        if self.config is None:
            return False
        try:
64 65 66 67 68
            self.host = self.config.get_value(section, 'host')
            self.port = self.config.get_value(section, 'port')
            self.user = self.config.get_value(section, 'user')
            self.password = self.config.get_value(section, 'password')
            self.db = self.config.get_value(section, 'db')
69 70 71 72 73 74 75 76
        except NoSectionError:
            logger.critical("No InfluxDB configuration found")
            return False
        except NoOptionError as e:
            logger.critical("Error in the InfluxDB configuration (%s)" % e)
            return False
        else:
            logger.debug("Load InfluxDB from the Glances configuration file")
77 78
        # Prefix is optional
        try:
79
            self.prefix = self.config.get_value(section, 'prefix')
80 81
        except NoOptionError as e:
            pass
82 83 84
        return True

    def init(self):
A
PEP 257  
Alessio Sergi 已提交
85
        """Init the connection to the InfluxDB server."""
86 87
        if not self.export_enable:
            return None
88

89
        try:
90 91 92 93 94 95
            db = InfluxDBClient(host=self.host,
                                port=self.port,
                                username=self.user,
                                password=self.password,
                                database=self.db)
            get_all_db = [i['name'] for i in db.get_list_database()]
96
        except client.InfluxDBClientError as e:
97 98
            try:
                # https://github.com/influxdb/influxdb-python/issues/138
99
                logger.info("Trying fallback to InfluxDB v0.8")
100 101 102 103 104 105
                db = InfluxDBClient_Legacy(host=self.host,
                                           port=self.port,
                                           username=self.user,
                                           password=self.password,
                                           database=self.db)
                get_all_db = [i['name'] for i in db.get_list_database()]
A
flake8  
Alessio Sergi 已提交
106
            except Exception:
107 108
                logger.critical("Can not connect to InfluxDB database '%s' (%s)" % (self.db, e))
                sys.exit(2)
109

110
        if self.db in get_all_db:
111 112 113
            logger.info(
                "Stats will be exported to InfluxDB server: {0}".format(db._baseurl))
        else:
114
            logger.critical("InfluxDB database '%s' did not exist. Please create it" % self.db)
115 116
            sys.exit(2)
        return db
N
Nicolargo 已提交
117

N
Nicolargo 已提交
118
    def export(self, name, columns, points):
A
PEP 257  
Alessio Sergi 已提交
119
        """Write the points to the InfluxDB server."""
120 121 122
        # Manage prefix
        if self.prefix is not None:
            name = self.prefix + '.' + name
N
nicolargo 已提交
123
        # logger.info(self.prefix)
124
        # Create DB input
N
Nicolargo 已提交
125 126 127 128 129 130
        data = [
            {
                "name": name,
                "columns": columns,
                "points": [points]
            }]
131
        # Write input to the InfluxDB database
N
Nicolargo 已提交
132 133 134
        try:
            self.client.write_points(data)
        except Exception as e:
N
Nicolargo 已提交
135
            logger.error("Can not export stats to InfluxDB (%s)" % e)