glances.exports.glances_zeromq.Export.__init__()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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