glances_percpu.py 7.1 KB
Newer Older
A
Alessio Sergi 已提交
1 2
# -*- coding: utf-8 -*-
#
3
# This file is part of Glances.
A
Alessio Sergi 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# 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 已提交
19 20

"""Per-CPU plugin."""
A
Alessio Sergi 已提交
21

A
Alessio Sergi 已提交
22 23
import psutil

24 25
from glances.plugins.glances_plugin import GlancesPlugin

A
Alessio Sergi 已提交
26 27

class Plugin(GlancesPlugin):
A
PEP 257  
Alessio Sergi 已提交
28 29

    """Glances' per-CPU plugin.
A
Alessio Sergi 已提交
30 31 32 33

    stats is a list
    """

34
    def __init__(self, args=None):
A
PEP 257  
Alessio Sergi 已提交
35
        """Init the plugin."""
36
        GlancesPlugin.__init__(self, args=args)
A
Alessio Sergi 已提交
37 38 39 40

        # We want to display the stat in the curse interface
        self.display_curse = True

N
Nicolas Hennion 已提交
41
        # Init stats
42
        self.reset()
N
Nicolas Hennion 已提交
43 44 45
        self.percputime_total_new = []
        self.percputime_new = []

46
    def reset(self):
A
PEP 257  
Alessio Sergi 已提交
47
        """Reset/init the stats."""
48 49
        self.stats = []

A
Alessio Sergi 已提交
50
    def update(self):
A
PEP 257  
Alessio Sergi 已提交
51
        """Update per-CPU stats using the input method."""
52 53 54
        # Reset stats
        self.reset()

55
        if self.get_input() == 'local':
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
            # Update stats using the standard system lib

            # Grab CPU using the PSUtil cpu_times method
            # Per-CPU
            percputime = psutil.cpu_times(percpu=True)
            percputime_total = []
            for i in range(len(percputime)):
                percputime_total.append(percputime[i].user +
                                        percputime[i].system +
                                        percputime[i].idle)

            # Only available on some OS
            for i in range(len(percputime)):
                if hasattr(percputime[i], 'nice'):
                    percputime_total[i] += percputime[i].nice
            for i in range(len(percputime)):
                if hasattr(percputime[i], 'iowait'):
                    percputime_total[i] += percputime[i].iowait
            for i in range(len(percputime)):
                if hasattr(percputime[i], 'irq'):
                    percputime_total[i] += percputime[i].irq
            for i in range(len(percputime)):
                if hasattr(percputime[i], 'softirq'):
                    percputime_total[i] += percputime[i].softirq
            for i in range(len(percputime)):
                if hasattr(percputime[i], 'steal'):
                    percputime_total[i] += percputime[i].steal
            if not hasattr(self, 'percputime_old'):
                self.percputime_old = percputime
                self.percputime_total_old = percputime_total
            else:
                self.percputime_new = percputime
                self.percputime_total_new = percputime_total
                perpercent = []
                try:
                    for i in range(len(self.percputime_new)):
                        perpercent.append(100 / (self.percputime_total_new[i] -
                                                 self.percputime_total_old[i]))
                        cpu = {'user': (self.percputime_new[i].user -
                                        self.percputime_old[i].user) * perpercent[i],
                               'system': (self.percputime_new[i].system -
                                          self.percputime_old[i].system) * perpercent[i],
                               'idle': (self.percputime_new[i].idle -
                                        self.percputime_old[i].idle) * perpercent[i]}
                        if hasattr(self.percputime_new[i], 'nice'):
                            cpu['nice'] = (self.percputime_new[i].nice -
                                           self.percputime_old[i].nice) * perpercent[i]
                        if hasattr(self.percputime_new[i], 'iowait'):
                            cpu['iowait'] = (self.percputime_new[i].iowait -
                                             self.percputime_old[i].iowait) * perpercent[i]
                        if hasattr(self.percputime_new[i], 'irq'):
                            cpu['irq'] = (self.percputime_new[i].irq -
                                          self.percputime_old[i].irq) * perpercent[i]
                        if hasattr(self.percputime_new[i], 'softirq'):
                            cpu['softirq'] = (self.percputime_new[i].softirq -
                                              self.percputime_old[i].softirq) * perpercent[i]
                        if hasattr(self.percputime_new[i], 'steal'):
                            cpu['steal'] = (self.percputime_new[i].steal -
                                            self.percputime_old[i].steal) * perpercent[i]
                        self.stats.append(cpu)
                    self.percputime_old = self.percputime_new
                    self.percputime_total_old = self.percputime_total_new
                except Exception:
                    self.reset()

A
Alessio Sergi 已提交
121
        else:
122 123 124 125
            # Update stats using SNMP
            pass

        return self.stats
A
Alessio Sergi 已提交
126 127

    def msg_curse(self, args=None):
A
PEP 257  
Alessio Sergi 已提交
128
        """Return the dict to display in the curse interface."""
A
Alessio Sergi 已提交
129 130 131
        # Init the return message
        ret = []

132 133
        # No per CPU stat ? Exit...
        if self.stats == []:
A
Alessio Sergi 已提交
134
            msg = _("PER CPU not available")
135 136 137
            ret.append(self.curse_add_line(msg, "TITLE"))
            return ret

A
Alessio Sergi 已提交
138 139
        # Build the string message
        # Header
A
Alessio Sergi 已提交
140
        msg = '{0:8}'.format(_("PER CPU"))
A
Alessio Sergi 已提交
141 142 143 144
        ret.append(self.curse_add_line(msg, "TITLE"))

        # Total CPU usage
        for cpu in self.stats:
A
Alessio Sergi 已提交
145
            msg = ' {0:>6.1%}'.format((100 - cpu['idle']) / 100)
A
Alessio Sergi 已提交
146 147 148
            ret.append(self.curse_add_line(msg))

        # User CPU
149
        if 'user' in self.stats[0]:
A
Alessio Sergi 已提交
150 151
            # New line
            ret.append(self.curse_new_line())
A
Alessio Sergi 已提交
152
            msg = '{0:8}'.format(_("user:"))
A
Alessio Sergi 已提交
153 154
            ret.append(self.curse_add_line(msg))
            for cpu in self.stats:
A
Alessio Sergi 已提交
155
                msg = ' {0:>6.1%}'.format(cpu['user'] / 100)
A
Alessio Sergi 已提交
156 157 158
                ret.append(self.curse_add_line(msg, self.get_alert(cpu['user'], header="user")))

        # System CPU
159
        if 'user' in self.stats[0]:
A
Alessio Sergi 已提交
160 161
            # New line
            ret.append(self.curse_new_line())
A
Alessio Sergi 已提交
162
            msg = '{0:8}'.format(_("system:"))
A
Alessio Sergi 已提交
163 164
            ret.append(self.curse_add_line(msg))
            for cpu in self.stats:
A
Alessio Sergi 已提交
165
                msg = ' {0:>6.1%}'.format(cpu['system'] / 100)
A
Alessio Sergi 已提交
166 167
                ret.append(self.curse_add_line(msg, self.get_alert(cpu['system'], header="system")))

168
        # Idle CPU
169
        if 'user' in self.stats[0]:
A
Alessio Sergi 已提交
170 171
            # New line
            ret.append(self.curse_new_line())
172
            msg = '{0:8}'.format(_("idle:"))
A
Alessio Sergi 已提交
173 174
            ret.append(self.curse_add_line(msg))
            for cpu in self.stats:
175 176
                msg = ' {0:>6.1%}'.format(cpu['idle'] / 100)
                ret.append(self.curse_add_line(msg))
A
Alessio Sergi 已提交
177 178 179

        # Return the message with decoration
        return ret