Test Failed
Push — master ( 69b639...e7fa0a )
by Nicolas
04:05 queued 01:05
created

glances.cpu_percent.CpuPercent.get()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nop 2
dl 0
loc 7
rs 10
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
        self.cpu_percent = 0
35
        self.percpu_percent = []
36
37
        # Get CPU name
38
        self.__get_cpu_name()
39
40
        # cached_timer_cpu is the minimum time interval between stats updates
41
        # since last update is passed (will retrieve old cached info instead)
42
        self.cached_timer_cpu = cached_timer_cpu
43
        self.timer_cpu = Timer(0)
44
        self.timer_percpu = Timer(0)
45
46
        # psutil.cpu_freq() consumes lots of CPU
47
        # So refresh the stats every refresh*2 (6 seconds)
48
        self.cached_timer_cpu_info = cached_timer_cpu * 2
49
        self.timer_cpu_info = Timer(0)
50
51
    def get_key(self):
52
        """Return the key of the per CPU list."""
53
        return 'cpu_number'
54
55
    def get(self, percpu=False):
56
        """Update and/or return the CPU using the psutil library.
57
        If percpu, return the percpu stats"""
58
        if percpu:
59
            return self.__get_percpu()
60
        else:
61
            return self.__get_cpu()
62
63
    def get_info(self):
64
        """Get additional informations about the CPU"""
65
        # Never update more than 1 time per cached_timer_cpu_info
66
        if self.timer_cpu_info.finished() and hasattr(psutil, 'cpu_freq'):
67
            # Get the CPU freq current/max
68
            cpu_freq = psutil.cpu_freq()
69
            if hasattr(cpu_freq, 'current'):
70
                self.cpu_info['cpu_hz_current'] = cpu_freq.current
71
            else:
72
                self.cpu_info['cpu_hz_current'] = None
73
            if hasattr(cpu_freq, 'max'):
74
                self.cpu_info['cpu_hz'] = cpu_freq.max
75
            else:
76
                self.cpu_info['cpu_hz'] = None
77
            # Reset timer for cache
78
            self.timer_cpu_info.reset(duration=self.cached_timer_cpu_info)
79
        return self.cpu_info
80
81
    def __get_cpu_name(self):
82
        # Get the CPU name once from the /proc/cpuinfo file
83
        # @TODO: Multisystem...
84
        try:
85
            self.cpu_info['cpu_name'] = open('/proc/cpuinfo', 'r').readlines()[4].split(':')[1][1:-2]
86
        except:
87
            self.cpu_info['cpu_name'] = 'CPU'
88
        return self.cpu_info['cpu_name']
89
90
    def __get_cpu(self):
91
        """Update and/or return the CPU using the psutil library."""
92
        # Never update more than 1 time per cached_timer_cpu
93
        if self.timer_cpu.finished():
94
            self.cpu_percent = psutil.cpu_percent(interval=0.0)
95
            # Reset timer for cache
96
            self.timer_cpu.reset(duration=self.cached_timer_cpu)
97
        return self.cpu_percent
98
99
    def __get_percpu(self):
100
        """Update and/or return the per CPU list using the psutil library."""
101
        # Never update more than 1 time per cached_timer_cpu
102
        if self.timer_percpu.finished():
103
            self.percpu_percent = []
104
            for cpu_number, cputimes in enumerate(psutil.cpu_times_percent(interval=0.0,
105
                                                                           percpu=True)):
106
                cpu = {'key': self.get_key(),
107
                       'cpu_number': cpu_number,
108
                       'total': round(100 - cputimes.idle, 1),
109
                       'user': cputimes.user,
110
                       'system': cputimes.system,
111
                       'idle': cputimes.idle}
112
                # The following stats are for API purposes only
113
                if hasattr(cputimes, 'nice'):
114
                    cpu['nice'] = cputimes.nice
115
                if hasattr(cputimes, 'iowait'):
116
                    cpu['iowait'] = cputimes.iowait
117
                if hasattr(cputimes, 'irq'):
118
                    cpu['irq'] = cputimes.irq
119
                if hasattr(cputimes, 'softirq'):
120
                    cpu['softirq'] = cputimes.softirq
121
                if hasattr(cputimes, 'steal'):
122
                    cpu['steal'] = cputimes.steal
123
                if hasattr(cputimes, 'guest'):
124
                    cpu['guest'] = cputimes.guest
125
                if hasattr(cputimes, 'guest_nice'):
126
                    cpu['guest_nice'] = cputimes.guest_nice
127
                # Append new CPU to the list
128
                self.percpu_percent.append(cpu)
129
                # Reset timer for cache
130
                self.timer_percpu.reset(duration=self.cached_timer_cpu)
131
        return self.percpu_percent
132
133
134
# CpuPercent instance shared between plugins
135
cpu_percent = CpuPercent()
136