glances_csv.py 3.4 KB
Newer Older
N
Nicolargo 已提交
1 2 3 4
# -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
5
# Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com>
N
Nicolargo 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

A
PEP 257  
Alessio Sergi 已提交
20 21
"""CSV interface class."""

N
Nicolas Hennion 已提交
22
import csv
23
import sys
24
import time
N
Nicolargo 已提交
25

26 27
from glances.compat import PY3, iterkeys, itervalues
from glances.logger import logger
28
from glances.exports.glances_export import GlancesExport
N
Nicolargo 已提交
29 30


31
class Export(GlancesExport):
A
PEP 257  
Alessio Sergi 已提交
32

33
    """This class manages the CSV export module."""
N
Nicolargo 已提交
34

35
    def __init__(self, config=None, args=None):
36
        """Init the CSV export IF."""
A
Alessio Sergi 已提交
37
        super(Export, self).__init__(config=config, args=args)
38

N
Nicolargo 已提交
39
        # CSV file name
40
        self.csv_filename = args.export_csv
N
Nicolargo 已提交
41 42 43

        # Set the CSV output file
        try:
A
Alessio Sergi 已提交
44
            if PY3:
A
Alessio Sergi 已提交
45
                self.csv_file = open(self.csv_filename, 'w', newline='')
N
Nicolargo 已提交
46
            else:
A
Alessio Sergi 已提交
47 48 49
                self.csv_file = open(self.csv_filename, 'wb')
            self.writer = csv.writer(self.csv_file)
        except IOError as e:
A
Alessio Sergi 已提交
50
            logger.critical("Cannot create the CSV file: {0}".format(e))
N
Nicolargo 已提交
51 52
            sys.exit(2)

53 54
        logger.info("Stats exported to CSV file: {0}".format(self.csv_filename))

N
Nicolargo 已提交
55 56
        self.export_enable = True

57
        self.first_line = True
N
Nicolargo 已提交
58 59

    def exit(self):
A
PEP 257  
Alessio Sergi 已提交
60
        """Close the CSV file."""
N
Nicolargo 已提交
61
        logger.debug("Finalise export interface %s" % self.export_name)
A
Alessio Sergi 已提交
62
        self.csv_file.close()
N
Nicolargo 已提交
63 64

    def update(self, stats):
A
PEP 257  
Alessio Sergi 已提交
65
        """Update stats in the CSV output file."""
66
        # Get the stats
67
        all_stats = stats.getAllExports()
A
Alessio Sergi 已提交
68
        plugins = stats.getAllPlugins()
N
Nicolargo 已提交
69

70 71 72 73
        # Init data with timestamp (issue#708)
        csv_header = ['timestamp']
        csv_data = [time.strftime('%Y-%m-%d %H:%M:%S')]

N
Nicolargo 已提交
74
        # Loop over available plugin
75
        for i, plugin in enumerate(plugins):
N
Nicolargo 已提交
76
            if plugin in self.plugins_to_export():
A
Alessio Sergi 已提交
77
                if isinstance(all_stats[i], list):
78
                    for stat in all_stats[i]:
79 80
                        # First line: header
                        if self.first_line:
81
                            csv_header += ('{0}_{1}_{2}'.format(
82
                                plugin, self.get_item_key(stat), item) for item in stat)
83
                        # Others lines: stats
A
Alessio Sergi 已提交
84
                        csv_data += itervalues(stat)
A
Alessio Sergi 已提交
85
                elif isinstance(all_stats[i], dict):
86 87
                    # First line: header
                    if self.first_line:
A
Alessio Sergi 已提交
88
                        fieldnames = iterkeys(all_stats[i])
89 90
                        csv_header += ('{0}_{1}'.format(plugin, fieldname)
                                       for fieldname in fieldnames)
91
                    # Others lines: stats
A
Alessio Sergi 已提交
92
                    csv_data += itervalues(all_stats[i])
A
Alessio Sergi 已提交
93

94 95 96 97 98
        # Export to CSV
        if self.first_line:
            self.writer.writerow(csv_header)
            self.first_line = False
        self.writer.writerow(csv_data)
A
Alessio Sergi 已提交
99
        self.csv_file.flush()