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