Test Failed
Push — master ( 7e7379...128504 )
by Nicolas
03:31
created

glances.exports.glances_rabbitmq   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 101
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 48
dl 0
loc 101
rs 10
c 0
b 0
f 0
wmc 11

3 Methods

Rating   Name   Duplication   Size   Complexity  
A Export.export() 0 13 4
A Export.__init__() 0 25 2
A Export.init() 0 22 5
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
23
import socket
24
import sys
25
from numbers import Number
26
27
from glances.compat import range
28
from glances.logger import logger
29
from glances.exports.glances_export import GlancesExport
30
31
# Import pika for RabbitMQ
32
import pika
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
        # Mandatory configuration keys (additional to host and port)
44
        self.user = None
45
        self.password = None
46
        self.queue = None
47
        self.protocol = None
48
49
        # Optionals configuration keys
50
        # N/A
51
52
        # Load the rabbitMQ configuration file
53
        self.export_enable = self.load_conf(
54
            'rabbitmq', mandatories=['host', 'port', 'user', 'password', 'queue'], options=['protocol']
55
        )
56
        if not self.export_enable:
57
            sys.exit(2)
58
59
        # Get the current hostname
60
        self.hostname = socket.gethostname()
61
62
        # Init the rabbitmq client
63
        self.client = self.init()
64
65
    def init(self):
66
        """Init the connection to the rabbitmq server."""
67
        if not self.export_enable:
68
            return None
69
70
        # Needed for when protocol is not specified and when protocol is upper case
71
        # only amqp and amqps supported
72
        if self.protocol is not None and (self.protocol.lower() == 'amqps'):
73
            self.protocol = 'amqps'
74
        else:
75
            self.protocol = 'amqp'
76
77
        try:
78
            parameters = pika.URLParameters(
79
                self.protocol + '://' + self.user + ':' + self.password + '@' + self.host + ':' + self.port + '/'
80
            )
81
            connection = pika.BlockingConnection(parameters)
82
            channel = connection.channel()
83
            return channel
84
        except Exception as e:
85
            logger.critical("Connection to rabbitMQ failed : %s " % e)
86
            return None
87
88
    def export(self, name, columns, points):
89
        """Write the points in RabbitMQ."""
90
        data = 'hostname=' + self.hostname + ', name=' + name + ', dateinfo=' + datetime.datetime.utcnow().isoformat()
91
        for i in range(len(columns)):
92
            if not isinstance(points[i], Number):
93
                continue
94
            else:
95
                data += ", " + columns[i] + "=" + str(points[i])
96
        logger.debug(data)
97
        try:
98
            self.client.basic_publish(exchange='', routing_key=self.queue, body=data)
99
        except Exception as e:
100
            logger.error("Can not export stats to RabbitMQ (%s)" % e)
101