Test Failed
Push — master ( b164e3...65b0d8 )
by Nicolas
03:39
created

glances.cpu_percent.CpuPercent.get_info()   B

Complexity

Conditions 7

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 14
nop 1
dl 0
loc 21
rs 8
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2021 Nicolargo <[email protected]>
6
#
7
# Glances is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Glances is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
"""CPU percent stats shared between CPU and Quicklook plugins."""
21
22
from glances.logger import logger
23
from glances.timer import Timer
24
25
import psutil
26
27
28
class CpuPercent(object):
29
30
    """Get and store the CPU percent."""
31
32
    def __init__(self, cached_timer_cpu=3):
33
        self.cpu_info = {
34
            'cpu_name': None,
35
            'cpu_hz_current': None,
36
            'cpu_hz': None
37
        }
38
        self.cpu_percent = 0
39
        self.percpu_percent = []
40
41
        # Get CPU name
42
        self.__get_cpu_name()
43
44
        # cached_timer_cpu is the minimum time interval between stats updates
45
        # since last update is passed (will retrieve old cached info instead)
46
        self.cached_timer_cpu = cached_timer_cpu
47
        self.timer_cpu = Timer(0)
48
        self.timer_percpu = Timer(0)
49
50
        # psutil.cpu_freq() consumes lots of CPU
51
        # So refresh the stats every refresh*2 (6 seconds)
52
        self.cached_timer_cpu_info = cached_timer_cpu * 2
53
        self.timer_cpu_info = Timer(0)
54
55
    def get_key(self):
56
        """Return the key of the per CPU list."""
57
        return 'cpu_number'
58
59
    def get(self, percpu=False):
60
        """Update and/or return the CPU using the psutil library.
61
        If percpu, return the percpu stats"""
62
        if percpu:
63
            return self.__get_percpu()
64
        else:
65
            return self.__get_cpu()
66
67
    def get_info(self):
68
        """Get additional informations about the CPU"""
69
        # Never update more than 1 time per cached_timer_cpu_info
70
        if self.timer_cpu_info.finished() and hasattr(psutil, 'cpu_freq'):
71
            # Get the CPU freq current/max
72
            try:
73
                cpu_freq = psutil.cpu_freq()
74
            except Exception as e:
75
                logger.debug('Can not grab CPU information ({})'.format(e))
76
            else:
77
                if hasattr(cpu_freq, 'current'):
78
                    self.cpu_info['cpu_hz_current'] = cpu_freq.current
79
                else:
80
                    self.cpu_info['cpu_hz_current'] = None
81
                if hasattr(cpu_freq, 'max'):
82
                    self.cpu_info['cpu_hz'] = cpu_freq.max
83
                else:
84
                    self.cpu_info['cpu_hz'] = None
85
                # Reset timer for cache
86
                self.timer_cpu_info.reset(duration=self.cached_timer_cpu_info)
87
        return self.cpu_info
88
89
    def __get_cpu_name(self):
90
        # Get the CPU name once from the /proc/cpuinfo file
91
        # @TODO: Multisystem...
92
        try:
93
            self.cpu_info['cpu_name'] = open('/proc/cpuinfo', 'r').readlines()[4].split(':')[1].strip()
94
        except:
95
            self.cpu_info['cpu_name'] = 'CPU'
96
        return self.cpu_info['cpu_name']
97
98
    def __get_cpu(self):
99
        """Update and/or return the CPU using the psutil library."""
100
        # Never update more than 1 time per cached_timer_cpu
101
        if self.timer_cpu.finished():
102
            self.cpu_percent = psutil.cpu_percent(interval=0.0)
103
            # Reset timer for cache
104
            self.timer_cpu.reset(duration=self.cached_timer_cpu)
105
        return self.cpu_percent
106
107
    def __get_percpu(self):
108
        """Update and/or return the per CPU list using the psutil library."""
109
        # Never update more than 1 time per cached_timer_cpu
110
        if self.timer_percpu.finished():
111
            self.percpu_percent = []
112
            for cpu_number, cputimes in enumerate(psutil.cpu_times_percent(interval=0.0,
113
                                                                           percpu=True)):
114
                cpu = {'key': self.get_key(),
115
                       'cpu_number': cpu_number,
116
                       'total': round(100 - cputimes.idle, 1),
117
                       'user': cputimes.user,
118
                       'system': cputimes.system,
119
                       'idle': cputimes.idle}
120
                # The following stats are for API purposes only
121
                if hasattr(cputimes, 'nice'):
122
                    cpu['nice'] = cputimes.nice
123
                if hasattr(cputimes, 'iowait'):
124
                    cpu['iowait'] = cputimes.iowait
125
                if hasattr(cputimes, 'irq'):
126
                    cpu['irq'] = cputimes.irq
127
                if hasattr(cputimes, 'softirq'):
128
                    cpu['softirq'] = cputimes.softirq
129
                if hasattr(cputimes, 'steal'):
130
                    cpu['steal'] = cputimes.steal
131
                if hasattr(cputimes, 'guest'):
132
                    cpu['guest'] = cputimes.guest
133
                if hasattr(cputimes, 'guest_nice'):
134
                    cpu['guest_nice'] = cputimes.guest_nice
135
                # Append new CPU to the list
136
                self.percpu_percent.append(cpu)
137
                # Reset timer for cache
138
                self.timer_percpu.reset(duration=self.cached_timer_cpu)
139
        return self.percpu_percent
140
141
142
# CpuPercent instance shared between plugins
143
cpu_percent = CpuPercent()
144