1
2
3
4
5
6
7
8
9
10
11
12 import sys, time
13
14 if sys.platform.startswith('win32'):
15 import pythoncom, wmi
16
17 from twisted.internet import reactor, defer, threads, task
18
19 from util import Util
23 '''
24 System information collector object.
25 '''
29
31 '''
32 Returns the cpu load.
33 '''
34 return self._cpuLoad
35
37 '''
38 Returns a total load number according to CPU, RAM and other
39 system stats.
40 '''
41 return self.cpuLoad()
42
43 @defer.inlineCallbacks
45 '''
46 CPU stats reader for linux platform.
47 '''
48 def getTimeList():
49 '''
50 Returns agregated information about cpu(s) state(s)
51 '''
52 statFile = file("/proc/stat", "r")
53 timeList = statFile.readline().split(" ")[2:6]
54 statFile.close()
55
56 for i in range(len(timeList)) :
57 timeList[i] = int(timeList[i])
58
59 return timeList
60
61 @defer.inlineCallbacks
62 def deltaTime(interval):
63 '''
64 Collects two data sets of CPU usage separated by an interval.
65 Returns the difference between two sets.
66 '''
67 x = getTimeList()
68 yield Util.deferredSleep(interval)
69 y = getTimeList()
70
71 for i in range(len(x)):
72 y[i] -= x[i]
73
74 defer.returnValue(y)
75
76 while True:
77 dt = yield deltaTime(1.0)
78 self._cpuLoad = 100 - (dt[len(dt) - 1] * 100.00 / sum(dt))
79
81 '''
82 CPU stats reader for win32 platform.
83 '''
84 def setCpuLoad(load):
85 '''
86 This function is used to set the cpu load of SysInfo class,
87 and called from a non-reactor thread.
88 '''
89 self._cpuLoad = load
90
91 def wmiCpuReader():
92 '''
93 Constantly collects processor usage information. Runs in a thread.
94 '''
95
96 pythoncom.CoInitialize()
97
98 info = wmi.WMI()
99 retval = 0
100
101 try:
102
103 while True:
104 cpuLoad = info.Win32_PerfFormattedData_PerfOS_Processor()[-1].PercentProcessorTime
105
106
107 reactor.callFromThread(setCpuLoad, cpuLoad)
108
109
110
111 if not reactor.running:
112 break
113
114 finally:
115
116 pythoncom.CoUninitialize()
117
118
119 threads.deferToThread(wmiCpuReader)
120
122 '''
123 Platform independent CPU stat monitor entry point.
124 '''
125 if sys.platform.startswith('linux'):
126 self.cpuLoadMeterLoopUnix()
127
128 elif sys.platform.startswith('win32'):
129 self.cpuLoadMeterLoopWin32()
130