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

glances/exports/glances_couchdb.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
"""CouchDB interface class."""
21
22
import sys
23
from datetime import datetime
24
25
from glances.logger import logger
26
from glances.exports.glances_export import GlancesExport
27
28
import couchdb
29
import couchdb.mapping
30
31
32
class Export(GlancesExport):
33
34
    """This class manages the CouchDB export module."""
35
36
    def __init__(self, config=None, args=None):
37 View Code Duplication
        """Init the CouchDB export IF."""
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
38
        super(Export, self).__init__(config=config, args=args)
39
40
        # Mandatories configuration keys (additional to host and port)
41
        self.db = None
42
43
        # Optionals configuration keys
44
        self.user = None
45
        self.password = None
46
47
        # Load the Cassandra configuration file section
48
        self.export_enable = self.load_conf('couchdb',
49
                                            mandatories=['host', 'port', 'db'],
50
                                            options=['user', 'password'])
51
        if not self.export_enable:
52
            sys.exit(2)
53
54
        # Init the CouchDB client
55
        self.client = self.init()
56
57
    def init(self):
58
        """Init the connection to the CouchDB server."""
59
        if not self.export_enable:
60
            return None
61
62
        if self.user is None:
63
            server_uri = 'http://{}:{}/'.format(self.host,
64
                                                self.port)
65
        else:
66
            server_uri = 'http://{}:{}@{}:{}/'.format(self.user,
67
                                                      self.password,
68
                                                      self.host,
69
                                                      self.port)
70
71
        try:
72
            s = couchdb.Server(server_uri)
73
        except Exception as e:
74
            logger.critical("Cannot connect to CouchDB server %s (%s)" % (server_uri, e))
75
            sys.exit(2)
76
        else:
77
            logger.info("Connected to the CouchDB server %s" % server_uri)
78
79
        try:
80
            s[self.db]
81
        except Exception as e:
82
            # Database did not exist
83
            # Create it...
84
            s.create(self.db)
85
        else:
86
            logger.info("There is already a %s database" % self.db)
87
88
        return s
89
90
    def database(self):
91
        """Return the CouchDB database object"""
92
        return self.client[self.db]
93
94
    def export(self, name, columns, points):
95
        """Write the points to the CouchDB server."""
96
        logger.debug("Export {} stats to CouchDB".format(name))
97
98
        # Create DB input
99
        data = dict(zip(columns, points))
100
101
        # Set the type to the current stat name
102
        data['type'] = name
103
        data['time'] = couchdb.mapping.DateTimeField()._to_json(datetime.now())
104
105
        # Write input to the CouchDB database
106
        # Result can be view: http://127.0.0.1:5984/_utils
107
        try:
108
            self.client[self.db].save(data)
109
        except Exception as e:
110
            logger.error("Cannot export {} stats to CouchDB ({})".format(name, e))
111