1 /*
2 * libjingle
3 * Copyright 2010 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28 #include "talk/base/cpumonitor.h"
29
30 #include <string>
31
32 #include "talk/base/common.h"
33 #include "talk/base/logging.h"
34 #include "talk/base/scoped_ptr.h"
35 #include "talk/base/systeminfo.h"
36 #include "talk/base/thread.h"
37 #include "talk/base/timeutils.h"
38
39 #ifdef WIN32
40 #include "talk/base/win32.h"
41 #include <winternl.h>
42 #endif
43
44 #ifdef POSIX
45 #include <sys/time.h>
46 #endif
47
48 #if defined(IOS) || defined(OSX)
49 #include <mach/mach_host.h>
50 #include <mach/mach_init.h>
51 #include <mach/host_info.h>
52 #include <mach/task.h>
53 #endif // defined(IOS) || defined(OSX)
54
55 #if defined(LINUX) || defined(ANDROID)
56 #include <sys/resource.h>
57 #include <errno.h>
58 #include <stdio.h>
59 #include "talk/base/fileutils.h"
60 #include "talk/base/pathutils.h"
61 #endif // defined(LINUX) || defined(ANDROID)
62
63 #if defined(IOS) || defined(OSX)
TimeValueTToInt64(const time_value_t & time_value)64 static uint64 TimeValueTToInt64(const time_value_t &time_value) {
65 return talk_base::kNumMicrosecsPerSec * time_value.seconds +
66 time_value.microseconds;
67 }
68 #endif // defined(IOS) || defined(OSX)
69
70 // How CpuSampler works
71 // When threads switch, the time they spent is accumulated to system counters.
72 // The time can be treated as user, kernel or idle.
73 // user time is applications.
74 // kernel time is the OS, including the thread switching code itself.
75 // typically kernel time indicates IO.
76 // idle time is a process that wastes time when nothing is ready to run.
77 //
78 // User time is broken down by process (application). One of the applications
79 // is the current process. When you add up all application times, this is
80 // system time. If only your application is running, system time should be the
81 // same as process time.
82 //
83 // All cores contribute to these accumulators. A dual core process is able to
84 // process twice as many cycles as a single core. The actual code efficiency
85 // may be worse, due to contention, but the available cycles is exactly twice
86 // as many, and the cpu load will reflect the efficiency. Hyperthreads behave
87 // the same way. The load will reflect 200%, but the actual amount of work
88 // completed will be much less than a true dual core.
89 //
90 // Total available performance is the sum of all accumulators.
91 // If you tracked this for 1 second, it would essentially give you the clock
92 // rate - number of cycles per second.
93 // Speed step / Turbo Boost is not considered, so infact more processing time
94 // may be available.
95
96 namespace talk_base {
97
98 // Note Tests on Windows show 600 ms is minimum stable interval for Windows 7.
99 static const int32 kDefaultInterval = 950; // Slightly under 1 second.
100
CpuSampler()101 CpuSampler::CpuSampler()
102 : min_load_interval_(kDefaultInterval)
103 #ifdef WIN32
104 , get_system_times_(NULL),
105 nt_query_system_information_(NULL),
106 force_fallback_(false)
107 #endif
108 {
109 }
110
~CpuSampler()111 CpuSampler::~CpuSampler() {
112 }
113
114 // Set minimum interval in ms between computing new load values. Default 950.
set_load_interval(int min_load_interval)115 void CpuSampler::set_load_interval(int min_load_interval) {
116 min_load_interval_ = min_load_interval;
117 }
118
Init()119 bool CpuSampler::Init() {
120 sysinfo_.reset(new SystemInfo);
121 cpus_ = sysinfo_->GetMaxCpus();
122 if (cpus_ == 0) {
123 return false;
124 }
125 #ifdef WIN32
126 // Note that GetSystemTimes is available in Windows XP SP1 or later.
127 // http://msdn.microsoft.com/en-us/library/ms724400.aspx
128 // NtQuerySystemInformation is used as a fallback.
129 if (!force_fallback_) {
130 get_system_times_ = GetProcAddress(GetModuleHandle(L"kernel32.dll"),
131 "GetSystemTimes");
132 }
133 nt_query_system_information_ = GetProcAddress(GetModuleHandle(L"ntdll.dll"),
134 "NtQuerySystemInformation");
135 if ((get_system_times_ == NULL) && (nt_query_system_information_ == NULL)) {
136 return false;
137 }
138 #endif
139 #if defined(LINUX) || defined(ANDROID)
140 Pathname sname("/proc/stat");
141 sfile_.reset(Filesystem::OpenFile(sname, "rb"));
142 if (!sfile_) {
143 LOG_ERR(LS_ERROR) << "open proc/stat failed:";
144 return false;
145 }
146 if (!sfile_->DisableBuffering()) {
147 LOG_ERR(LS_ERROR) << "could not disable buffering for proc/stat";
148 return false;
149 }
150 #endif // defined(LINUX) || defined(ANDROID)
151 GetProcessLoad(); // Initialize values.
152 GetSystemLoad();
153 // Help next user call return valid data by recomputing load.
154 process_.prev_load_time_ = 0u;
155 system_.prev_load_time_ = 0u;
156 return true;
157 }
158
UpdateCpuLoad(uint64 current_total_times,uint64 current_cpu_times,uint64 * prev_total_times,uint64 * prev_cpu_times)159 float CpuSampler::UpdateCpuLoad(uint64 current_total_times,
160 uint64 current_cpu_times,
161 uint64 *prev_total_times,
162 uint64 *prev_cpu_times) {
163 float result = 0.f;
164 if (current_total_times < *prev_total_times ||
165 current_cpu_times < *prev_cpu_times) {
166 LOG(LS_ERROR) << "Inconsistent time values are passed. ignored";
167 } else {
168 const uint64 cpu_diff = current_cpu_times - *prev_cpu_times;
169 const uint64 total_diff = current_total_times - *prev_total_times;
170 result = (total_diff == 0ULL ? 0.f :
171 static_cast<float>(1.0f * cpu_diff / total_diff));
172 if (result > static_cast<float>(cpus_)) {
173 result = static_cast<float>(cpus_);
174 }
175 *prev_total_times = current_total_times;
176 *prev_cpu_times = current_cpu_times;
177 }
178 return result;
179 }
180
GetSystemLoad()181 float CpuSampler::GetSystemLoad() {
182 uint32 timenow = Time();
183 int elapsed = static_cast<int>(TimeDiff(timenow, system_.prev_load_time_));
184 if (min_load_interval_ != 0 && system_.prev_load_time_ != 0u &&
185 elapsed < min_load_interval_) {
186 return system_.prev_load_;
187 }
188 #ifdef WIN32
189 uint64 total_times, cpu_times;
190
191 typedef BOOL (_stdcall *GST_PROC)(LPFILETIME, LPFILETIME, LPFILETIME);
192 typedef NTSTATUS (WINAPI *QSI_PROC)(SYSTEM_INFORMATION_CLASS,
193 PVOID, ULONG, PULONG);
194
195 GST_PROC get_system_times = reinterpret_cast<GST_PROC>(get_system_times_);
196 QSI_PROC nt_query_system_information = reinterpret_cast<QSI_PROC>(
197 nt_query_system_information_);
198
199 if (get_system_times) {
200 FILETIME idle_time, kernel_time, user_time;
201 if (!get_system_times(&idle_time, &kernel_time, &user_time)) {
202 LOG(LS_ERROR) << "::GetSystemTimes() failed: " << ::GetLastError();
203 return 0.f;
204 }
205 // kernel_time includes Kernel idle time, so no need to
206 // include cpu_time as total_times
207 total_times = ToUInt64(kernel_time) + ToUInt64(user_time);
208 cpu_times = total_times - ToUInt64(idle_time);
209
210 } else {
211 if (nt_query_system_information) {
212 ULONG returned_length = 0;
213 scoped_ptr<SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[]> processor_info(
214 new SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION[cpus_]);
215 nt_query_system_information(
216 ::SystemProcessorPerformanceInformation,
217 reinterpret_cast<void*>(processor_info.get()),
218 cpus_ * sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION),
219 &returned_length);
220
221 if (returned_length !=
222 (cpus_ * sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION))) {
223 LOG(LS_ERROR) << "NtQuerySystemInformation has unexpected size";
224 return 0.f;
225 }
226
227 uint64 current_idle = 0;
228 uint64 current_kernel = 0;
229 uint64 current_user = 0;
230 for (int ix = 0; ix < cpus_; ++ix) {
231 current_idle += processor_info[ix].IdleTime.QuadPart;
232 current_kernel += processor_info[ix].UserTime.QuadPart;
233 current_user += processor_info[ix].KernelTime.QuadPart;
234 }
235 total_times = current_kernel + current_user;
236 cpu_times = total_times - current_idle;
237 } else {
238 return 0.f;
239 }
240 }
241 #endif // WIN32
242
243 #if defined(IOS) || defined(OSX)
244 host_cpu_load_info_data_t cpu_info;
245 mach_msg_type_number_t info_count = HOST_CPU_LOAD_INFO_COUNT;
246 if (KERN_SUCCESS != host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO,
247 reinterpret_cast<host_info_t>(&cpu_info),
248 &info_count)) {
249 LOG(LS_ERROR) << "::host_statistics() failed";
250 return 0.f;
251 }
252
253 const uint64 cpu_times = cpu_info.cpu_ticks[CPU_STATE_NICE] +
254 cpu_info.cpu_ticks[CPU_STATE_SYSTEM] +
255 cpu_info.cpu_ticks[CPU_STATE_USER];
256 const uint64 total_times = cpu_times + cpu_info.cpu_ticks[CPU_STATE_IDLE];
257 #endif // defined(IOS) || defined(OSX)
258
259 #if defined(LINUX) || defined(ANDROID)
260 if (!sfile_) {
261 LOG(LS_ERROR) << "Invalid handle for proc/stat";
262 return 0.f;
263 }
264 std::string statbuf;
265 sfile_->SetPosition(0);
266 if (!sfile_->ReadLine(&statbuf)) {
267 LOG_ERR(LS_ERROR) << "Could not read proc/stat file";
268 return 0.f;
269 }
270
271 unsigned long long user;
272 unsigned long long nice;
273 unsigned long long system;
274 unsigned long long idle;
275 if (sscanf(statbuf.c_str(), "cpu %Lu %Lu %Lu %Lu",
276 &user, &nice,
277 &system, &idle) != 4) {
278 LOG_ERR(LS_ERROR) << "Could not parse cpu info";
279 return 0.f;
280 }
281 const uint64 cpu_times = nice + system + user;
282 const uint64 total_times = cpu_times + idle;
283 #endif // defined(LINUX) || defined(ANDROID)
284
285 #if defined(__native_client__)
286 // TODO(ryanpetrie): Implement this via PPAPI when it's available.
287 const uint64 cpu_times = 0;
288 const uint64 total_times = 0;
289 #endif // defined(__native_client__)
290
291 system_.prev_load_time_ = timenow;
292 system_.prev_load_ = UpdateCpuLoad(total_times,
293 cpu_times * cpus_,
294 &system_.prev_total_times_,
295 &system_.prev_cpu_times_);
296 return system_.prev_load_;
297 }
298
GetProcessLoad()299 float CpuSampler::GetProcessLoad() {
300 uint32 timenow = Time();
301 int elapsed = static_cast<int>(TimeDiff(timenow, process_.prev_load_time_));
302 if (min_load_interval_ != 0 && process_.prev_load_time_ != 0u &&
303 elapsed < min_load_interval_) {
304 return process_.prev_load_;
305 }
306 #ifdef WIN32
307 FILETIME current_file_time;
308 ::GetSystemTimeAsFileTime(¤t_file_time);
309
310 FILETIME create_time, exit_time, kernel_time, user_time;
311 if (!::GetProcessTimes(::GetCurrentProcess(),
312 &create_time, &exit_time, &kernel_time, &user_time)) {
313 LOG(LS_ERROR) << "::GetProcessTimes() failed: " << ::GetLastError();
314 return 0.f;
315 }
316
317 const uint64 total_times =
318 ToUInt64(current_file_time) - ToUInt64(create_time);
319 const uint64 cpu_times =
320 (ToUInt64(kernel_time) + ToUInt64(user_time));
321 #endif // WIN32
322
323 #ifdef POSIX
324 // Common to both OSX and Linux.
325 struct timeval tv;
326 gettimeofday(&tv, NULL);
327 const uint64 total_times = tv.tv_sec * kNumMicrosecsPerSec + tv.tv_usec;
328 #endif
329
330 #if defined(IOS) || defined(OSX)
331 // Get live thread usage.
332 task_thread_times_info task_times_info;
333 mach_msg_type_number_t info_count = TASK_THREAD_TIMES_INFO_COUNT;
334
335 if (KERN_SUCCESS != task_info(mach_task_self(), TASK_THREAD_TIMES_INFO,
336 reinterpret_cast<task_info_t>(&task_times_info),
337 &info_count)) {
338 LOG(LS_ERROR) << "::task_info(TASK_THREAD_TIMES_INFO) failed";
339 return 0.f;
340 }
341
342 // Get terminated thread usage.
343 task_basic_info task_term_info;
344 info_count = TASK_BASIC_INFO_COUNT;
345 if (KERN_SUCCESS != task_info(mach_task_self(), TASK_BASIC_INFO,
346 reinterpret_cast<task_info_t>(&task_term_info),
347 &info_count)) {
348 LOG(LS_ERROR) << "::task_info(TASK_BASIC_INFO) failed";
349 return 0.f;
350 }
351
352 const uint64 cpu_times = (TimeValueTToInt64(task_times_info.user_time) +
353 TimeValueTToInt64(task_times_info.system_time) +
354 TimeValueTToInt64(task_term_info.user_time) +
355 TimeValueTToInt64(task_term_info.system_time));
356 #endif // defined(IOS) || defined(OSX)
357
358 #if defined(LINUX) || defined(ANDROID)
359 rusage usage;
360 if (getrusage(RUSAGE_SELF, &usage) < 0) {
361 LOG_ERR(LS_ERROR) << "getrusage failed";
362 return 0.f;
363 }
364
365 const uint64 cpu_times =
366 (usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) * kNumMicrosecsPerSec +
367 usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
368 #endif // defined(LINUX) || defined(ANDROID)
369
370 #if defined(__native_client__)
371 // TODO(ryanpetrie): Implement this via PPAPI when it's available.
372 const uint64 cpu_times = 0;
373 #endif // defined(__native_client__)
374
375 process_.prev_load_time_ = timenow;
376 process_.prev_load_ = UpdateCpuLoad(total_times,
377 cpu_times,
378 &process_.prev_total_times_,
379 &process_.prev_cpu_times_);
380 return process_.prev_load_;
381 }
382
GetMaxCpus() const383 int CpuSampler::GetMaxCpus() const {
384 return cpus_;
385 }
386
GetCurrentCpus()387 int CpuSampler::GetCurrentCpus() {
388 return sysinfo_->GetCurCpus();
389 }
390
391 ///////////////////////////////////////////////////////////////////
392 // Implementation of class CpuMonitor.
CpuMonitor(Thread * thread)393 CpuMonitor::CpuMonitor(Thread* thread)
394 : monitor_thread_(thread) {
395 }
396
~CpuMonitor()397 CpuMonitor::~CpuMonitor() {
398 Stop();
399 }
400
set_thread(Thread * thread)401 void CpuMonitor::set_thread(Thread* thread) {
402 ASSERT(monitor_thread_ == NULL || monitor_thread_ == thread);
403 monitor_thread_ = thread;
404 }
405
Start(int period_ms)406 bool CpuMonitor::Start(int period_ms) {
407 if (!monitor_thread_ || !sampler_.Init()) return false;
408
409 monitor_thread_->SignalQueueDestroyed.connect(
410 this, &CpuMonitor::OnMessageQueueDestroyed);
411
412 period_ms_ = period_ms;
413 monitor_thread_->PostDelayed(period_ms_, this);
414
415 return true;
416 }
417
Stop()418 void CpuMonitor::Stop() {
419 if (monitor_thread_) {
420 monitor_thread_->Clear(this);
421 }
422 }
423
OnMessage(Message * msg)424 void CpuMonitor::OnMessage(Message* msg) {
425 int max_cpus = sampler_.GetMaxCpus();
426 int current_cpus = sampler_.GetCurrentCpus();
427 float process_load = sampler_.GetProcessLoad();
428 float system_load = sampler_.GetSystemLoad();
429 SignalUpdate(current_cpus, max_cpus, process_load, system_load);
430
431 if (monitor_thread_) {
432 monitor_thread_->PostDelayed(period_ms_, this);
433 }
434 }
435
436 } // namespace talk_base
437