Issues (45)

glances/exports/glances_zeromq/__init__.py (1 issue)

1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <[email protected]>
6
#
7
# SPDX-License-Identifier: LGPL-3.0-only
8
#
9
10
"""ZeroMQ interface class."""
11
12
import sys
13
14
from glances.globals import b
15
from glances.logger import logger
16
from glances.exports.export import GlancesExport
17
from glances.globals import json_dumps
18
19
import zmq
20
from zmq.utils.strtypes import asbytes
21
22
23
class Export(GlancesExport):
24
25
    """This class manages the ZeroMQ export module."""
26
27 View Code Duplication
    def __init__(self, config=None, args=None):
28
        """Init the ZeroMQ export IF."""
29
        super(Export, self).__init__(config=config, args=args)
30
31
        # Mandatory configuration keys (additional to host and port)
32
        self.prefix = None
33
34
        # Optionals configuration keys
35
        # N/A
36
37
        # Load the ZeroMQ configuration file section ([export_zeromq])
38
        self.export_enable = self.load_conf('zeromq', mandatories=['host', 'port', 'prefix'], options=[])
39
        if not self.export_enable:
40
            exit('Missing ZEROMQ config')
41
42
        # Init the ZeroMQ context
43
        self.context = None
44
        self.client = self.init()
45
46
    def init(self):
47
        """Init the connection to the CouchDB server."""
48
        if not self.export_enable:
49
            return None
50
51
        server_uri = 'tcp://{}:{}'.format(self.host, self.port)
52
53
        try:
54
            self.context = zmq.Context()
55
            publisher = self.context.socket(zmq.PUB)
56
            publisher.bind(server_uri)
57
        except Exception as e:
58
            logger.critical("Cannot connect to ZeroMQ server %s (%s)" % (server_uri, e))
59
            sys.exit(2)
60
        else:
61
            logger.info("Connected to the ZeroMQ server %s" % server_uri)
62
63
        return publisher
0 ignored issues
show
The variable publisher does not seem to be defined for all execution paths.
Loading history...
64
65
    def exit(self):
66
        """Close the socket and context"""
67
        if self.client is not None:
68
            self.client.close()
69
        if self.context is not None:
70
            self.context.destroy()
71
72
    def export(self, name, columns, points):
73
        """Write the points to the ZeroMQ server."""
74
        logger.debug("Export {} stats to ZeroMQ".format(name))
75
76
        # Create DB input
77
        data = dict(zip(columns, points))
78
79
        # Do not publish empty stats
80
        if data == {}:
81
            return False
82
83
        # Glances envelopes the stats in a publish message with two frames:
84
        # - First frame containing the following prefix (STRING)
85
        # - Second frame with the Glances plugin name (STRING)
86
        # - Third frame with the Glances plugin stats (JSON)
87
        message = [b(self.prefix), b(name), asbytes(json_dumps(data))]
88
89
        # Write data to the ZeroMQ bus
90
        # Result can be view: tcp://host:port
91
        try:
92
            self.client.send_multipart(message)
93
        except Exception as e:
94
            logger.error("Cannot export {} stats to ZeroMQ ({})".format(name, e))
95
96
        return True
97