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

glances/exports/glances_zeromq.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
"""ZeroMQ interface class."""
21
22
import sys
23
import json
24
25
from glances.compat import b
26
from glances.logger import logger
27
from glances.exports.glances_export import GlancesExport
28
29
import zmq
30
from zmq.utils.strtypes import asbytes
31
32
33
class Export(GlancesExport):
34
35
    """This class manages the ZeroMQ export module."""
36 View Code Duplication
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
37
    def __init__(self, config=None, args=None):
38
        """Init the ZeroMQ export IF."""
39
        super(Export, self).__init__(config=config, args=args)
40
41
        # Mandatories configuration keys (additional to host and port)
42
        self.prefix = None
43
44
        # Optionals configuration keys
45
        # N/A
46
47
        # Load the ZeroMQ configuration file section ([export_zeromq])
48
        self.export_enable = self.load_conf('zeromq',
49
                                            mandatories=['host', 'port', 'prefix'],
50
                                            options=[])
51
        if not self.export_enable:
52
            sys.exit(2)
53
54
        # Init the ZeroMQ context
55
        self.context = None
56
        self.client = self.init()
57
58
    def init(self):
59
        """Init the connection to the CouchDB server."""
60
        if not self.export_enable:
61
            return None
62
63
        server_uri = 'tcp://{}:{}'.format(self.host, self.port)
64
65
        try:
66
            self.context = zmq.Context()
67
            publisher = self.context.socket(zmq.PUB)
68
            publisher.bind(server_uri)
69
        except Exception as e:
70
            logger.critical("Cannot connect to ZeroMQ server %s (%s)" % (server_uri, e))
71
            sys.exit(2)
72
        else:
73
            logger.info("Connected to the ZeroMQ server %s" % server_uri)
74
75
        return publisher
76
77
    def exit(self):
78
        """Close the socket and context"""
79
        if self.client is not None:
80
            self.client.close()
81
        if self.context is not None:
82
            self.context.destroy()
83
84
    def export(self, name, columns, points):
85
        """Write the points to the ZeroMQ server."""
86
        logger.debug("Export {} stats to ZeroMQ".format(name))
87
88
        # Create DB input
89
        data = dict(zip(columns, points))
90
91
        # Do not publish empty stats
92
        if data == {}:
93
            return False
94
95
        # Glances envelopes the stats in a publish message with two frames:
96
        # - First frame containing the following prefix (STRING)
97
        # - Second frame with the Glances plugin name (STRING)
98
        # - Third frame with the Glances plugin stats (JSON)
99
        message = [b(self.prefix),
100
                   b(name),
101
                   asbytes(json.dumps(data))]
102
103
        # Write data to the ZeroMQ bus
104
        # Result can be view: tcp://host:port
105
        try:
106
            self.client.send_multipart(message)
107
        except Exception as e:
108
            logger.error("Cannot export {} stats to ZeroMQ ({})".format(name, e))
109
110
        return True
111