1 /* Copyright (c) 2010, 2012, 2013, 2014 Nicira, Inc.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
18 #include "system-stats.h"
29 #if HAVE_SYS_STATVFS_H
30 #include <sys/statvfs.h>
36 #include "openvswitch/dynamic-string.h"
39 #include "openvswitch/ofpbuf.h"
41 #include "ovs-thread.h"
42 #include "poll-loop.h"
46 #include "openvswitch/vlog.h"
48 VLOG_DEFINE_THIS_MODULE(system_stats);
50 /* #ifdefs make it a pain to maintain code: you have to try to build both ways.
51 * Thus, this file tries to compile as much of the code as possible regardless
52 * of the target, by writing "if (LINUX)" instead of "#ifdef __linux__" where
53 * this is possible. */
56 #include <asm/param.h>
62 get_cpu_cores(struct smap *stats)
64 long int n_cores = count_cpu_cores();
66 smap_add_format(stats, "cpu", "%ld", n_cores);
71 get_load_average(struct smap *stats OVS_UNUSED)
76 if (getloadavg(loadavg, 3) == 3) {
77 smap_add_format(stats, "load_average", "%.2f,%.2f,%.2f",
78 loadavg[0], loadavg[1], loadavg[2]);
86 static unsigned int cached;
90 long int value = sysconf(_SC_PAGESIZE);
94 GetSystemInfo(&sysinfo);
95 value = sysinfo.dwPageSize;
106 get_memory_stats(struct smap *stats)
109 unsigned int pagesize = get_page_size();
110 #ifdef _SC_PHYS_PAGES
111 long int phys_pages = sysconf(_SC_PHYS_PAGES);
113 long int phys_pages = 0;
115 #ifdef _SC_AVPHYS_PAGES
116 long int avphys_pages = sysconf(_SC_AVPHYS_PAGES);
118 long int avphys_pages = 0;
120 int mem_total, mem_used;
123 if (pagesize <= 0 || phys_pages <= 0 || avphys_pages <= 0) {
127 mem_total = phys_pages * (pagesize / 1024);
128 mem_used = (phys_pages - avphys_pages) * (pagesize / 1024);
130 MEMORYSTATUS memory_status;
131 GlobalMemoryStatus(&memory_status);
133 mem_total = memory_status.dwTotalPhys;
134 mem_used = memory_status.dwTotalPhys - memory_status.dwAvailPhys;
136 smap_add_format(stats, "memory", "%d,%d", mem_total, mem_used);
138 static const char file_name[] = "/proc/meminfo";
139 int mem_used, mem_cache, swap_used;
150 stream = fopen(file_name, "r");
152 VLOG_WARN_ONCE("%s: open failed (%s)",
153 file_name, ovs_strerror(errno));
158 shash_add(&dict, "MemTotal", &mem_total);
159 shash_add(&dict, "MemFree", &mem_free);
160 shash_add(&dict, "Buffers", &buffers);
161 shash_add(&dict, "Cached", &cached);
162 shash_add(&dict, "SwapTotal", &swap_total);
163 shash_add(&dict, "SwapFree", &swap_free);
164 while (fgets(line, sizeof line, stream)) {
168 if (ovs_scan(line, "%15[^:]: %u", key, &value)) {
169 int *valuep = shash_find_data(&dict, key);
176 shash_destroy(&dict);
178 mem_used = mem_total - mem_free;
179 mem_cache = buffers + cached;
180 swap_used = swap_total - swap_free;
181 smap_add_format(stats, "memory", "%d,%d,%d,%d,%d",
182 mem_total, mem_used, mem_cache, swap_total, swap_used);
186 /* Returns the time at which the system booted, as the number of milliseconds
187 * since the epoch, or 0 if the time of boot cannot be determined. */
191 static long long int cache_expiration = LLONG_MIN;
192 static long long int boot_time;
196 if (time_msec() >= cache_expiration) {
197 static const char stat_file[] = "/proc/stat";
201 cache_expiration = time_msec() + 5 * 1000;
203 stream = fopen(stat_file, "r");
205 VLOG_ERR_ONCE("%s: open failed (%s)",
206 stat_file, ovs_strerror(errno));
210 while (fgets(line, sizeof line, stream)) {
212 if (ovs_scan(line, "btime %lld", &btime)) {
213 boot_time = btime * 1000;
217 VLOG_ERR_ONCE("%s: btime not found", stat_file);
224 static unsigned long long int
225 ticks_to_ms(unsigned long long int ticks)
233 #if USER_HZ == 100 /* Common case. */
234 return ticks * (1000 / USER_HZ);
235 #else /* Alpha and some other architectures. */
236 double factor = 1000.0 / USER_HZ;
237 return ticks * factor + 0.5;
241 struct raw_process_info {
242 unsigned long int vsz; /* Virtual size, in kB. */
243 unsigned long int rss; /* Resident set size, in kB. */
244 long long int uptime; /* ms since started. */
245 long long int cputime; /* ms of CPU used during 'uptime'. */
246 pid_t ppid; /* Parent. */
247 char name[18]; /* Name (surrounded by parentheses). */
251 get_raw_process_info(pid_t pid, struct raw_process_info *raw)
253 unsigned long long int vsize, rss, start_time, utime, stime;
254 long long int start_msec;
262 sprintf(file_name, "/proc/%lu/stat", (unsigned long int) pid);
263 stream = fopen(file_name, "r");
265 VLOG_ERR_ONCE("%s: open failed (%s)",
266 file_name, ovs_strerror(errno));
271 "%*d " /* (1. pid) */
272 "%17s " /* 2. process name */
273 "%*c " /* (3. state) */
275 "%*d " /* (5. pgid) */
276 "%*d " /* (6. sid) */
277 "%*d " /* (7. tty_nr) */
278 "%*d " /* (8. tty_pgrp) */
279 "%*u " /* (9. flags) */
280 "%*u " /* (10. min_flt) */
281 "%*u " /* (11. cmin_flt) */
282 "%*u " /* (12. maj_flt) */
283 "%*u " /* (13. cmaj_flt) */
284 "%llu " /* 14. utime */
285 "%llu " /* 15. stime */
286 "%*d " /* (16. cutime) */
287 "%*d " /* (17. cstime) */
288 "%*d " /* (18. priority) */
289 "%*d " /* (19. nice) */
290 "%*d " /* (20. num_threads) */
291 "%*d " /* (21. always 0) */
292 "%llu " /* 22. start_time */
293 "%llu " /* 23. vsize */
294 "%llu " /* 24. rss */
296 /* These are here for documentation but #if'd out to save
297 * actually parsing them from the stream for no benefit. */
298 "%*lu " /* (25. rsslim) */
299 "%*lu " /* (26. start_code) */
300 "%*lu " /* (27. end_code) */
301 "%*lu " /* (28. start_stack) */
302 "%*lu " /* (29. esp) */
303 "%*lu " /* (30. eip) */
304 "%*lu " /* (31. pending signals) */
305 "%*lu " /* (32. blocked signals) */
306 "%*lu " /* (33. ignored signals) */
307 "%*lu " /* (34. caught signals) */
308 "%*lu " /* (35. whcan) */
309 "%*lu " /* (36. always 0) */
310 "%*lu " /* (37. always 0) */
311 "%*d " /* (38. exit_signal) */
312 "%*d " /* (39. task_cpu) */
313 "%*u " /* (40. rt_priority) */
314 "%*u " /* (41. policy) */
315 "%*llu " /* (42. blkio_ticks) */
316 "%*lu " /* (43. gtime) */
317 "%*ld" /* (44. cgtime) */
319 , raw->name, &ppid, &utime, &stime, &start_time, &vsize, &rss);
322 VLOG_ERR_ONCE("%s: fscanf failed", file_name);
326 start_msec = get_boot_time() + ticks_to_ms(start_time);
328 raw->vsz = vsize / 1024;
329 raw->rss = rss * (getpagesize() / 1024);
330 raw->uptime = time_wall_msec() - start_msec;
331 raw->cputime = ticks_to_ms(utime + stime);
338 count_crashes(pid_t pid)
348 sprintf(file_name, "/proc/%lu/cmdline", (unsigned long int) pid);
349 stream = fopen(file_name, "r");
351 VLOG_WARN_ONCE("%s: open failed (%s)", file_name, ovs_strerror(errno));
355 if (!fgets(line, sizeof line, stream)) {
356 VLOG_WARN_ONCE("%s: read failed (%s)", file_name,
357 feof(stream) ? "end of file" : ovs_strerror(errno));
361 paren = strchr(line, '(');
364 if (ovs_scan(paren + 1, "%d", &x)) {
375 struct process_info {
376 unsigned long int vsz; /* Virtual size, in kB. */
377 unsigned long int rss; /* Resident set size, in kB. */
378 long long int booted; /* ms since monitor started. */
379 int crashes; /* # of crashes (usually 0). */
380 long long int uptime; /* ms since last (re)started by monitor. */
381 long long int cputime; /* ms of CPU used during 'uptime'. */
385 get_process_info(pid_t pid, struct process_info *pinfo)
387 struct raw_process_info child;
390 if (!get_raw_process_info(pid, &child)) {
394 pinfo->vsz = child.vsz;
395 pinfo->rss = child.rss;
396 pinfo->booted = child.uptime;
398 pinfo->uptime = child.uptime;
399 pinfo->cputime = child.cputime;
402 struct raw_process_info parent;
404 get_raw_process_info(child.ppid, &parent);
405 if (!strcmp(child.name, parent.name)) {
406 pinfo->booted = parent.uptime;
407 pinfo->crashes = count_crashes(child.ppid);
415 get_process_stats(struct smap *stats)
421 dir = opendir(ovs_rundir());
423 VLOG_ERR_ONCE("%s: open failed (%s)",
424 ovs_rundir(), ovs_strerror(errno));
428 while ((de = readdir(dir)) != NULL) {
429 struct process_info pinfo;
435 #ifdef _DIRENT_HAVE_D_TYPE
436 if (de->d_type != DT_UNKNOWN && de->d_type != DT_REG) {
441 extension = strrchr(de->d_name, '.');
442 if (!extension || strcmp(extension, ".pid")) {
446 file_name = xasprintf("%s/%s", ovs_rundir(), de->d_name);
447 pid = read_pidfile(file_name);
453 key = xasprintf("process_%.*s",
454 (int) (extension - de->d_name), de->d_name);
455 if (!smap_get(stats, key)) {
456 if (LINUX && get_process_info(pid, &pinfo)) {
457 smap_add_format(stats, key, "%lu,%lu,%lld,%d,%lld,%lld",
458 pinfo.vsz, pinfo.rss, pinfo.cputime,
459 pinfo.crashes, pinfo.booted, pinfo.uptime);
461 smap_add(stats, key, "");
472 get_filesys_stats(struct smap *stats OVS_UNUSED)
474 #if HAVE_GETMNTENT_R && HAVE_STATVFS
475 static const char file_name[] = "/etc/mtab";
476 struct mntent mntent;
482 stream = setmntent(file_name, "r");
484 VLOG_ERR_ONCE("%s: open failed (%s)", file_name, ovs_strerror(errno));
489 while ((me = getmntent_r(stream, &mntent, buf, sizeof buf)) != NULL) {
490 unsigned long long int total, free;
494 /* Skip non-local and read-only filesystems. */
495 if (strncmp(me->mnt_fsname, "/dev", 4)
496 || !strstr(me->mnt_opts, "rw")) {
500 /* Given the mount point we can stat the file system. */
501 if (statvfs(me->mnt_dir, &vfs) && vfs.f_flag & ST_RDONLY) {
506 /* Now format the data. */
508 ds_put_char(&s, ' ');
510 for (p = me->mnt_dir; *p != '\0'; p++) {
511 ds_put_char(&s, *p == ' ' || *p == ',' ? '_' : *p);
513 total = (unsigned long long int) vfs.f_frsize * vfs.f_blocks / 1024;
514 free = (unsigned long long int) vfs.f_frsize * vfs.f_bfree / 1024;
515 ds_put_format(&s, ",%llu,%llu", total, total - free);
520 smap_add(stats, "file_systems", ds_cstr(&s));
523 #endif /* HAVE_GETMNTENT_R && HAVE_STATVFS */
526 #define SYSTEM_STATS_INTERVAL (5 * 1000) /* In milliseconds. */
528 static struct ovs_mutex mutex = OVS_MUTEX_INITIALIZER;
529 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
530 static struct latch latch OVS_GUARDED_BY(mutex);
532 static bool started OVS_GUARDED_BY(mutex);
533 static struct smap *system_stats OVS_GUARDED_BY(mutex);
535 OVS_NO_RETURN static void *system_stats_thread_func(void *);
536 static void discard_stats(void);
538 /* Enables or disables system stats collection, according to 'enable'. */
540 system_stats_enable(bool enable)
542 if (enabled != enable) {
543 ovs_mutex_lock(&mutex);
546 ovs_thread_create("system_stats",
547 system_stats_thread_func, NULL);
552 xpthread_cond_signal(&cond);
555 ovs_mutex_unlock(&mutex);
559 /* Tries to obtain a new snapshot of system stats every SYSTEM_STATS_INTERVAL
562 * When a new snapshot is available (which only occurs if system stats are
563 * enabled), returns it as an smap owned by the caller. The caller must use
564 * both smap_destroy() and free() to completely free the returned data.
566 * When no new snapshot is available, returns NULL. */
568 system_stats_run(void)
570 struct smap *stats = NULL;
572 ovs_mutex_lock(&mutex);
577 stats = system_stats;
583 ovs_mutex_unlock(&mutex);
588 /* Causes poll_block() to wake up when system_stats_run() needs to be
591 system_stats_wait(void)
599 discard_stats(void) OVS_REQUIRES(mutex)
602 smap_destroy(system_stats);
609 system_stats_thread_func(void *arg OVS_UNUSED)
611 pthread_detach(pthread_self());
614 long long int next_refresh;
617 ovs_mutex_lock(&mutex);
619 /* The thread is sleeping, potentially for a long time, and it's
620 * not holding RCU protected references, so it makes sense to
622 ovsrcu_quiesce_start();
623 ovs_mutex_cond_wait(&cond, &mutex);
624 ovsrcu_quiesce_end();
626 ovs_mutex_unlock(&mutex);
628 stats = xmalloc(sizeof *stats);
630 get_cpu_cores(stats);
631 get_load_average(stats);
632 get_memory_stats(stats);
633 get_process_stats(stats);
634 get_filesys_stats(stats);
636 ovs_mutex_lock(&mutex);
638 system_stats = stats;
640 ovs_mutex_unlock(&mutex);
642 next_refresh = time_msec() + SYSTEM_STATS_INTERVAL;
644 poll_timer_wait_until(next_refresh);
646 } while (time_msec() < next_refresh);