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

glances/exports/glances_cassandra.py (1 issue)

1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2017 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
"""Cassandra/Scylla interface class."""
21
22
import sys
23
from datetime import datetime
24
from numbers import Number
25
26
from glances.logger import logger
27
from glances.exports.glances_export import GlancesExport
28
29
from cassandra.cluster import Cluster
30
from cassandra.util import uuid_from_time
31
from cassandra import InvalidRequest
32
33
34
class Export(GlancesExport):
35
36
    """This class manages the Cassandra/Scylla export module."""
37
38
    def __init__(self, config=None, args=None):
39 View Code Duplication
        """Init the Cassandra export IF."""
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
40
        super(Export, self).__init__(config=config, args=args)
41
42
        # Mandatories configuration keys (additional to host and port)
43
        self.keyspace = None
44
45
        # Optionals configuration keys
46
        self.protocol_version = 3
47
        self.replication_factor = 2
48
        self.table = None
49
50
        # Load the Cassandra configuration file section
51
        self.export_enable = self.load_conf('cassandra',
52
                                            mandatories=['host', 'port', 'keyspace'],
53
                                            options=['protocol_version',
54
                                                     'replication_factor',
55
                                                     'table'])
56
        if not self.export_enable:
57
            sys.exit(2)
58
59
        # Init the Cassandra client
60
        self.cluster, self.session = self.init()
61
62
    def init(self):
63
        """Init the connection to the InfluxDB server."""
64
        if not self.export_enable:
65
            return None
66
67
        # Cluster
68
        try:
69
            cluster = Cluster([self.host],
70
                              port=int(self.port),
71
                              protocol_version=int(self.protocol_version))
72
            session = cluster.connect()
73
        except Exception as e:
74
            logger.critical("Cannot connect to Cassandra cluster '%s:%s' (%s)" % (self.host, self.port, e))
75
            sys.exit(2)
76
77
        # Keyspace
78
        try:
79
            session.set_keyspace(self.keyspace)
80
        except InvalidRequest as e:
81
            logger.info("Create keyspace {} on the Cassandra cluster".format(self.keyspace))
82
            c = "CREATE KEYSPACE %s WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '%s' }" % (self.keyspace, self.replication_factor)
83
            session.execute(c)
84
            session.set_keyspace(self.keyspace)
85
86
        logger.info(
87
            "Stats will be exported to Cassandra cluster {} ({}) in keyspace {}".format(
88
                cluster.metadata.cluster_name, cluster.metadata.all_hosts(), self.keyspace))
89
90
        # Table
91
        try:
92
            session.execute("CREATE TABLE %s (plugin text, time timeuuid, stat map<text,float>, PRIMARY KEY (plugin, time)) WITH CLUSTERING ORDER BY (time DESC)" % self.table)
93
        except Exception:
94
            logger.debug("Cassandra table %s already exist" % self.table)
95
96
        return cluster, session
97
98
    def export(self, name, columns, points):
99
        """Write the points to the Cassandra cluster."""
100
        logger.debug("Export {} stats to Cassandra".format(name))
101
102
        # Remove non number stats and convert all to float (for Boolean)
103
        data = {k: float(v) for (k, v) in dict(zip(columns, points)).iteritems() if isinstance(v, Number)}
104
105
        # Write input to the Cassandra table
106
        try:
107
            self.session.execute(
108
                """
109
                INSERT INTO localhost (plugin, time, stat)
110
                VALUES (%s, %s, %s)
111
                """,
112
                (name, uuid_from_time(datetime.now()), data)
113
            )
114
        except Exception as e:
115
            logger.error("Cannot export {} stats to Cassandra ({})".format(name, e))
116
117
    def exit(self):
118
        """Close the Cassandra export module."""
119
        # To ensure all connections are properly closed
120
        self.session.shutdown()
121
        self.cluster.shutdown()
122
        # Call the father method
123
        super(Export, self).exit()
124