Completed
Push — master ( 233ebc...7fc0f8 )
by Nicolas
01:24 queued 50s
created

Export.export()   A

Complexity

Conditions 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 1
Metric Value
cc 3
c 8
b 0
f 1
dl 0
loc 21
rs 9.3142
1
"""JSON interface class."""
2
3
import sys
4
import json
5
6
from glances.compat import PY3, listkeys
7
from glances.logger import logger
8
from glances.exports.glances_export import GlancesExport
9
10
11
class Export(GlancesExport):
12
13
    """This class manages the JSON export module."""
14
15
    def __init__(self, config=None, args=None):
16
        """Init the JSON export IF."""
17
        super(Export, self).__init__(config=config, args=args)
18
19
        # JSON file name
20
        self.json_filename = args.export_json
21
22
        # Set the JSON output file
23
        try:
24
            if PY3:
25
                self.json_file = open(self.json_filename, 'w')
26
            else:
27
                self.json_file = open(self.json_filename, 'wb')
28
        except IOError as e:
29
            logger.critical("Cannot create the JSON file: {}".format(e))
30
            sys.exit(2)
31
32
        logger.info("Exporting stats to file: {}".format(self.json_filename))
33
34
        self.export_enable = True
35
36
        # Buffer for dict of stats
37
        self.buffer = {}
38
39
    def exit(self):
40
        """Close the JSON file."""
41
        logger.debug("Finalise export interface %s" % self.export_name)
42
        self.json_file.close()
43
44
    def export(self, name, columns, points):
45
        """Export the stats to the JSON file."""
46
47
        # Check for completion of loop for all exports
48
        if name == self.plugins_to_export()[0] and self.buffer != {}:
49
            # One whole loop has been completed
50
            # Flush stats to file
51
            logger.debug("Exporting stats ({}) to JSON file ({})".format(
52
                listkeys(self.buffer),
53
                self.json_filename)
54
            )
55
56
            # Export stats to JSON file
57
            data_json = json.dumps(self.buffer)
58
            self.json_file.write("{}\n".format(data_json))
59
60
            # Reset buffer
61
            self.buffer = {}
62
63
        # Add current stat to the buffer
64
        self.buffer[name] = dict(zip(columns, points))
65