1 | # -*- coding: utf-8 -*- |
||
2 | # |
||
3 | # This file is part of Glances. |
||
4 | # |
||
5 | # SPDX-FileCopyrightText: 2023 Nicolas Hennion <[email protected]> |
||
6 | # |
||
7 | # SPDX-License-Identifier: LGPL-3.0-only |
||
8 | # |
||
9 | |||
10 | """MongoDB interface class.""" |
||
11 | |||
12 | import sys |
||
13 | |||
14 | from glances.logger import logger |
||
15 | from glances.exports.glances_export import GlancesExport |
||
16 | |||
17 | import pymongo |
||
18 | from urllib.parse import quote_plus |
||
19 | |||
20 | |||
21 | class Export(GlancesExport): |
||
22 | |||
23 | """This class manages the MongoDB export module.""" |
||
24 | |||
25 | View Code Duplication | def __init__(self, config=None, args=None): |
|
0 ignored issues
–
show
Duplication
introduced
by
Loading history...
|
|||
26 | """Init the MongoDB export IF.""" |
||
27 | super(Export, self).__init__(config=config, args=args) |
||
28 | |||
29 | # Mandatory configuration keys (additional to host and port) |
||
30 | self.db = None |
||
31 | |||
32 | # Optional configuration keys |
||
33 | self.user = None |
||
34 | self.password = None |
||
35 | |||
36 | # Load the Cassandra configuration file section |
||
37 | self.export_enable = self.load_conf('mongodb', mandatories=['host', 'port', 'db'], options=['user', 'password']) |
||
38 | if not self.export_enable: |
||
39 | sys.exit(2) |
||
40 | |||
41 | # Init the CouchDB client |
||
42 | self.client = self.init() |
||
43 | |||
44 | def init(self): |
||
45 | """Init the connection to the CouchDB server.""" |
||
46 | if not self.export_enable: |
||
47 | return None |
||
48 | |||
49 | server_uri = 'mongodb://%s:%s@%s:%s' % (quote_plus(self.user), quote_plus(self.password), self.host, self.port) |
||
50 | |||
51 | try: |
||
52 | client = pymongo.MongoClient(server_uri) |
||
53 | client.admin.command('ping') |
||
54 | except Exception as e: |
||
55 | logger.critical("Cannot connect to MongoDB server %s:%s (%s)" % (self.host, self.port, e)) |
||
56 | sys.exit(2) |
||
57 | else: |
||
58 | logger.info("Connected to the MongoDB server") |
||
59 | |||
60 | return client |
||
61 | |||
62 | def database(self): |
||
63 | """Return the CouchDB database object""" |
||
64 | return self.client[self.db] |
||
65 | |||
66 | def export(self, name, columns, points): |
||
67 | """Write the points to the MongoDB server.""" |
||
68 | logger.debug("Export {} stats to MongoDB".format(name)) |
||
69 | |||
70 | # Create DB input |
||
71 | data = dict(zip(columns, points)) |
||
72 | |||
73 | # Write data to the MongoDB database |
||
74 | try: |
||
75 | self.database()[name].insert_one(data) |
||
76 | except Exception as e: |
||
77 | logger.error("Cannot export {} stats to MongoDB ({})".format(name, e)) |
||
78 |