Completed
Push — develop ( 8b5b19...8ebade )
by Nicolas
05:17 queued 02:08
created

glances.exports.glances_rabbitmq.Export.export()   A

Complexity

Conditions 4

Size

Total Lines 14
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 12
nop 4
dl 0
loc 14
rs 9.8
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2019 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
"""JMS interface class."""
21
22
import datetime
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
23
import socket
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
24
import sys
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
25
from numbers import Number
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
26
27
from glances.compat import range
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in range.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
introduced by
import missing from __future__ import absolute_import
Loading history...
28
from glances.logger import logger
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
29
from glances.exports.glances_export import GlancesExport
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
30
31
# Import pika for RabbitMQ
32
import pika
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
introduced by
Unable to import 'pika'
Loading history...
33
34
35
class Export(GlancesExport):
36
37
    """This class manages the rabbitMQ export module."""
38
39
    def __init__(self, config=None, args=None):
40
        """Init the RabbitMQ export IF."""
41
        super(Export, self).__init__(config=config, args=args)
42
43
        # Mandatories configuration keys (additional to host and port)
44
        self.user = None
45
        self.password = None
46
        self.queue = None
47
48
        # Optionals configuration keys
49
        # N/A
50
51
        # Load the rabbitMQ configuration file
52
        self.export_enable = self.load_conf('rabbitmq',
53
                                            mandatories=['host', 'port',
54
                                                         'user', 'password',
55
                                                         'queue'],
56
                                            options=[])
57
        if not self.export_enable:
58
            sys.exit(2)
59
60
        # Get the current hostname
61
        self.hostname = socket.gethostname()
62
63
        # Init the rabbitmq client
64
        self.client = self.init()
65
66
    def init(self):
67
        """Init the connection to the rabbitmq server."""
68
        if not self.export_enable:
69
            return None
70
        try:
71
            parameters = pika.URLParameters(
72
                'amqp://' + self.user +
73
                ':' + self.password +
74
                '@' + self.host +
75
                ':' + self.port + '/')
76
            connection = pika.BlockingConnection(parameters)
77
            channel = connection.channel()
78
            return channel
79
        except Exception as e:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
Coding Style Naming introduced by
The name e does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
80
            logger.critical("Connection to rabbitMQ failed : %s " % e)
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
81
            return None
82
83
    def export(self, name, columns, points):
84
        """Write the points in RabbitMQ."""
85
        data = ('hostname=' + self.hostname + ', name=' + name +
86
                ', dateinfo=' + datetime.datetime.utcnow().isoformat())
87
        for i in range(len(columns)):
88
            if not isinstance(points[i], Number):
89
                continue
90
            else:
91
                data += ", " + columns[i] + "=" + str(points[i])
92
        logger.debug(data)
93
        try:
94
            self.client.basic_publish(exchange='', routing_key=self.queue, body=data)
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (85/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
95
        except Exception as e:
0 ignored issues
show
Best Practice introduced by
Catching very general exceptions such as Exception is usually not recommended.

Generally, you would want to handle very specific errors in the exception handler. This ensure that you do not hide other types of errors which should be fixed.

So, unless you specifically plan to handle any error, consider adding a more specific exception.

Loading history...
Coding Style Naming introduced by
The name e does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
96
            logger.error("Can not export stats to RabbitMQ (%s)" % e)
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
97