summaryrefslogtreecommitdiffstats
path: root/glances/exports/glances_json/__init__.py
blob: b637d6137581ce337854bac8a03504c016a16697 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""JSON interface class."""

import sys

from glances.globals import listkeys, json_dumps
from glances.logger import logger
from glances.exports.export import GlancesExport


class Export(GlancesExport):

    """This class manages the JSON export module."""

    def __init__(self, config=None, args=None):
        """Init the JSON export IF."""
        super(Export, self).__init__(config=config, args=args)

        # JSON file name
        self.json_filename = args.export_json_file

        # Set the JSON output file
        try:
            self.json_file = open(self.json_filename, 'w')
            self.json_file.close()
        except IOError as e:
            logger.critical("Cannot create the JSON file: {}".format(e))
            sys.exit(2)

        logger.info("Exporting stats to file: {}".format(self.json_filename))

        self.export_enable = True

        # Buffer for dict of stats
        self.buffer = {}

    def exit(self):
        """Close the JSON file."""
        logger.debug("Finalise export interface %s" % self.export_name)
        self.json_file.close()

    def export(self, name, columns, points):
        """Export the stats to the JSON file."""

        # Check for completion of loop for all exports
        if name == self.last_exported_list()[0] and self.buffer != {}:
            # One whole loop has been completed
            # Flush stats to file
            logger.debug("Exporting stats ({}) to JSON file ({})".format(listkeys(self.buffer), self.json_filename))

            # Export stats to JSON file
            with open(self.json_filename, "w") as self.json_file:
                self.json_file.write("{}\n".format(json_dumps(self.buffer)))

            # Reset buffer
            self.buffer = {}

        # Add current stat to the buffer
        self.buffer[name] = dict(zip(columns, points))