Completed
Pull Request — master (#963)
by
unknown
01:02
created

Export.database()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2016 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.compat import NoOptionError, NoSectionError
26
from glances.logger import logger
27
from glances.exports.glances_export import GlancesExport
28
29
import couchdb
30
import couchdb.mapping
31
32
33
class Export(GlancesExport):
34
35
    """This class manages the CouchDB export module."""
36
37 View Code Duplication
    def __init__(self, config=None, args=None):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
38
        """Init the CouchDB export IF."""
39
        super(Export, self).__init__(config=config, args=args)
40
41
        # Load the Couchdb configuration file section ([export_couchdb])
42
        self.host = None
43
        self.port = None
44
        self.user = None
45
        self.password = None
46
        self.db = None
47
        self.export_enable = self.load_conf()
48
        if not self.export_enable:
49
            sys.exit(2)
50
51
        # Init the CouchDB client
52
        self.client = self.init()
53
54 View Code Duplication
    def load_conf(self, section="couchdb"):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
55
        """Load the CouchDB configuration in the Glances configuration file."""
56
        if self.config is None:
57
            return False
58
        try:
59
            self.host = self.config.get_value(section, 'host')
60
            self.port = self.config.get_value(section, 'port')
61
            self.db = self.config.get_value(section, 'db')
62
        except NoSectionError:
63
            logger.critical("No CouchDB configuration found")
64
            return False
65
        except NoOptionError as e:
66
            logger.critical("Error in the CouchDB configuration (%s)" % e)
67
            return False
68
        else:
69
            logger.debug("Load CouchDB from the Glances configuration file")
70
71
        # user and password are optional
72
        try:
73
            self.user = self.config.get_value(section, 'user')
74
            self.password = self.config.get_value(section, 'password')
75
        except NoOptionError:
76
            pass
77
78
        return True
79
80
    def init(self):
81
        """Init the connection to the CouchDB server."""
82
        if not self.export_enable:
83
            return None
84
85
        if self.user is None:
86
            server_uri = 'http://{}:{}/'.format(self.host,
87
                                                self.port)
88
        else:
89
            server_uri = 'http://{}:{}@{}:{}/'.format(self.user,
90
                                                      self.password,
91
                                                      self.host,
92
                                                      self.port)
93
94
        try:
95
            s = couchdb.Server(server_uri)
96
        except Exception as e:
97
            logger.critical("Cannot connect to CouchDB server %s (%s)" % (server_uri, e))
98
            sys.exit(2)
99
        else:
100
            logger.info("Connected to the CouchDB server %s" % server_uri)
101
102
        try:
103
            s[self.db]
104
        except Exception as e:
105
            # Database did not exist
106
            # Create it...
107
            s.create(self.db)
108
        else:
109
            logger.info("There is already a %s database" % self.db)
110
111
        return s
112
113
    def database(self):
114
        """Return the CouchDB database object"""
115
        return self.client[self.db]
116
117
    def export(self, name, columns, points):
118
        """Write the points to the CouchDB server."""
119
        logger.debug("Export {} stats to CouchDB".format(name))
120
121
        # Create DB input
122
        data = dict(zip(columns, points))
123
124
        # Set the type to the current stat name
125
        data['type'] = name
126
        data['time'] = couchdb.mapping.DateTimeField()._to_json(datetime.now())
127
128
        # Write input to the CouchDB database
129
        # Result can be view: http://127.0.0.1:5984/_utils
130
        try:
131
            self.client[self.db].save(data)
132
        except Exception as e:
133
            logger.error("Cannot export {} stats to CouchDB ({})".format(name, e))
134