6c7393368becd921f362e34e8d07abb6b0e51de2
[sliver-openvswitch.git] / vswitchd / system-stats.c
1 /* Copyright (c) 2010, 2012, 2013, 2014 Nicira, Inc.
2  *
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:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
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.
14  */
15
16 #include <config.h>
17
18 #include "system-stats.h"
19
20 #include <ctype.h>
21 #include <dirent.h>
22 #include <errno.h>
23 #if HAVE_MNTENT_H
24 #include <mntent.h>
25 #endif
26 #include <stdint.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #if HAVE_SYS_STATVFS_H
30 #include <sys/statvfs.h>
31 #endif
32 #include <unistd.h>
33
34 #include "daemon.h"
35 #include "dirs.h"
36 #include "dynamic-string.h"
37 #include "json.h"
38 #include "latch.h"
39 #include "ofpbuf.h"
40 #include "ovs-thread.h"
41 #include "poll-loop.h"
42 #include "shash.h"
43 #include "smap.h"
44 #include "timeval.h"
45 #include "vlog.h"
46
47 VLOG_DEFINE_THIS_MODULE(system_stats);
48
49 /* #ifdefs make it a pain to maintain code: you have to try to build both ways.
50  * Thus, this file tries to compile as much of the code as possible regardless
51  * of the target, by writing "if (LINUX)" instead of "#ifdef __linux__" where
52  * this is possible. */
53 #ifdef __linux__
54 #define LINUX 1
55 #include <asm/param.h>
56 #else
57 #define LINUX 0
58 #endif
59
60 static void
61 get_cpu_cores(struct smap *stats)
62 {
63     long int n_cores = count_cpu_cores();
64     if (n_cores > 0) {
65         smap_add_format(stats, "cpu", "%ld", n_cores);
66     }
67 }
68
69 static void
70 get_load_average(struct smap *stats OVS_UNUSED)
71 {
72 #if HAVE_GETLOADAVG
73     double loadavg[3];
74
75     if (getloadavg(loadavg, 3) == 3) {
76         smap_add_format(stats, "load_average", "%.2f,%.2f,%.2f",
77                         loadavg[0], loadavg[1], loadavg[2]);
78     }
79 #endif
80 }
81
82 static unsigned int
83 get_page_size(void)
84 {
85     static unsigned int cached;
86
87     if (!cached) {
88 #ifndef _WIN32
89         long int value = sysconf(_SC_PAGESIZE);
90 #else
91         long int value;
92         SYSTEM_INFO sysinfo;
93         GetSystemInfo(&sysinfo);
94         value = sysinfo.dwPageSize;
95 #endif
96         if (value >= 0) {
97             cached = value;
98         }
99     }
100
101     return cached;
102 }
103
104 static void
105 get_memory_stats(struct smap *stats)
106 {
107     if (!LINUX) {
108         unsigned int pagesize = get_page_size();
109 #ifdef _SC_PHYS_PAGES
110         long int phys_pages = sysconf(_SC_PHYS_PAGES);
111 #else
112         long int phys_pages = 0;
113 #endif
114 #ifdef _SC_AVPHYS_PAGES
115         long int avphys_pages = sysconf(_SC_AVPHYS_PAGES);
116 #else
117         long int avphys_pages = 0;
118 #endif
119         int mem_total, mem_used;
120
121 #ifndef _WIN32
122         if (pagesize <= 0 || phys_pages <= 0 || avphys_pages <= 0) {
123             return;
124         }
125
126         mem_total = phys_pages * (pagesize / 1024);
127         mem_used = (phys_pages - avphys_pages) * (pagesize / 1024);
128 #else
129         MEMORYSTATUS memory_status;
130         GlobalMemoryStatus(&memory_status);
131
132         mem_total = memory_status.dwTotalPhys;
133         mem_used = memory_status.dwTotalPhys - memory_status.dwAvailPhys;
134 #endif
135         smap_add_format(stats, "memory", "%d,%d", mem_total, mem_used);
136     } else {
137         static const char file_name[] = "/proc/meminfo";
138         int mem_used, mem_cache, swap_used;
139         int mem_free = 0;
140         int buffers = 0;
141         int cached = 0;
142         int swap_free = 0;
143         int mem_total = 0;
144         int swap_total = 0;
145         struct shash dict;
146         char line[128];
147         FILE *stream;
148
149         stream = fopen(file_name, "r");
150         if (!stream) {
151             VLOG_WARN_ONCE("%s: open failed (%s)",
152                            file_name, ovs_strerror(errno));
153             return;
154         }
155
156         shash_init(&dict);
157         shash_add(&dict, "MemTotal", &mem_total);
158         shash_add(&dict, "MemFree", &mem_free);
159         shash_add(&dict, "Buffers", &buffers);
160         shash_add(&dict, "Cached", &cached);
161         shash_add(&dict, "SwapTotal", &swap_total);
162         shash_add(&dict, "SwapFree", &swap_free);
163         while (fgets(line, sizeof line, stream)) {
164             char key[16];
165             int value;
166
167             if (ovs_scan(line, "%15[^:]: %u", key, &value)) {
168                 int *valuep = shash_find_data(&dict, key);
169                 if (valuep) {
170                     *valuep = value;
171                 }
172             }
173         }
174         fclose(stream);
175         shash_destroy(&dict);
176
177         mem_used = mem_total - mem_free;
178         mem_cache = buffers + cached;
179         swap_used = swap_total - swap_free;
180         smap_add_format(stats, "memory", "%d,%d,%d,%d,%d",
181                         mem_total, mem_used, mem_cache, swap_total, swap_used);
182     }
183 }
184
185 /* Returns the time at which the system booted, as the number of milliseconds
186  * since the epoch, or 0 if the time of boot cannot be determined. */
187 static long long int
188 get_boot_time(void)
189 {
190     static long long int cache_expiration = LLONG_MIN;
191     static long long int boot_time;
192
193     ovs_assert(LINUX);
194
195     if (time_msec() >= cache_expiration) {
196         static const char stat_file[] = "/proc/stat";
197         char line[128];
198         FILE *stream;
199
200         cache_expiration = time_msec() + 5 * 1000;
201
202         stream = fopen(stat_file, "r");
203         if (!stream) {
204             VLOG_ERR_ONCE("%s: open failed (%s)",
205                           stat_file, ovs_strerror(errno));
206             return boot_time;
207         }
208
209         while (fgets(line, sizeof line, stream)) {
210             long long int btime;
211             if (ovs_scan(line, "btime %lld", &btime)) {
212                 boot_time = btime * 1000;
213                 goto done;
214             }
215         }
216         VLOG_ERR_ONCE("%s: btime not found", stat_file);
217     done:
218         fclose(stream);
219     }
220     return boot_time;
221 }
222
223 static unsigned long long int
224 ticks_to_ms(unsigned long long int ticks)
225 {
226     ovs_assert(LINUX);
227
228 #ifndef USER_HZ
229 #define USER_HZ 100
230 #endif
231
232 #if USER_HZ == 100              /* Common case. */
233     return ticks * (1000 / USER_HZ);
234 #else  /* Alpha and some other architectures.  */
235     double factor = 1000.0 / USER_HZ;
236     return ticks * factor + 0.5;
237 #endif
238 }
239
240 struct raw_process_info {
241     unsigned long int vsz;      /* Virtual size, in kB. */
242     unsigned long int rss;      /* Resident set size, in kB. */
243     long long int uptime;       /* ms since started. */
244     long long int cputime;      /* ms of CPU used during 'uptime'. */
245     pid_t ppid;                 /* Parent. */
246     char name[18];              /* Name (surrounded by parentheses). */
247 };
248
249 static bool
250 get_raw_process_info(pid_t pid, struct raw_process_info *raw)
251 {
252     unsigned long long int vsize, rss, start_time, utime, stime;
253     long long int start_msec;
254     unsigned long ppid;
255     char file_name[128];
256     FILE *stream;
257     int n;
258
259     ovs_assert(LINUX);
260
261     sprintf(file_name, "/proc/%lu/stat", (unsigned long int) pid);
262     stream = fopen(file_name, "r");
263     if (!stream) {
264         VLOG_ERR_ONCE("%s: open failed (%s)",
265                       file_name, ovs_strerror(errno));
266         return false;
267     }
268
269     n = fscanf(stream,
270                "%*d "           /* (1. pid) */
271                "%17s "          /* 2. process name */
272                "%*c "           /* (3. state) */
273                "%lu "           /* 4. ppid */
274                "%*d "           /* (5. pgid) */
275                "%*d "           /* (6. sid) */
276                "%*d "           /* (7. tty_nr) */
277                "%*d "           /* (8. tty_pgrp) */
278                "%*u "           /* (9. flags) */
279                "%*u "           /* (10. min_flt) */
280                "%*u "           /* (11. cmin_flt) */
281                "%*u "           /* (12. maj_flt) */
282                "%*u "           /* (13. cmaj_flt) */
283                "%llu "          /* 14. utime */
284                "%llu "          /* 15. stime */
285                "%*d "           /* (16. cutime) */
286                "%*d "           /* (17. cstime) */
287                "%*d "           /* (18. priority) */
288                "%*d "           /* (19. nice) */
289                "%*d "           /* (20. num_threads) */
290                "%*d "           /* (21. always 0) */
291                "%llu "          /* 22. start_time */
292                "%llu "          /* 23. vsize */
293                "%llu "          /* 24. rss */
294 #if 0
295                /* These are here for documentation but #if'd out to save
296                 * actually parsing them from the stream for no benefit. */
297                "%*lu "          /* (25. rsslim) */
298                "%*lu "          /* (26. start_code) */
299                "%*lu "          /* (27. end_code) */
300                "%*lu "          /* (28. start_stack) */
301                "%*lu "          /* (29. esp) */
302                "%*lu "          /* (30. eip) */
303                "%*lu "          /* (31. pending signals) */
304                "%*lu "          /* (32. blocked signals) */
305                "%*lu "          /* (33. ignored signals) */
306                "%*lu "          /* (34. caught signals) */
307                "%*lu "          /* (35. whcan) */
308                "%*lu "          /* (36. always 0) */
309                "%*lu "          /* (37. always 0) */
310                "%*d "           /* (38. exit_signal) */
311                "%*d "           /* (39. task_cpu) */
312                "%*u "           /* (40. rt_priority) */
313                "%*u "           /* (41. policy) */
314                "%*llu "         /* (42. blkio_ticks) */
315                "%*lu "          /* (43. gtime) */
316                "%*ld"           /* (44. cgtime) */
317 #endif
318                , raw->name, &ppid, &utime, &stime, &start_time, &vsize, &rss);
319     fclose(stream);
320     if (n != 7) {
321         VLOG_ERR_ONCE("%s: fscanf failed", file_name);
322         return false;
323     }
324
325     start_msec = get_boot_time() + ticks_to_ms(start_time);
326
327     raw->vsz = vsize / 1024;
328     raw->rss = rss * (getpagesize() / 1024);
329     raw->uptime = time_wall_msec() - start_msec;
330     raw->cputime = ticks_to_ms(utime + stime);
331     raw->ppid = ppid;
332
333     return true;
334 }
335
336 static int
337 count_crashes(pid_t pid)
338 {
339     char file_name[128];
340     const char *paren;
341     char line[128];
342     int crashes = 0;
343     FILE *stream;
344
345     ovs_assert(LINUX);
346
347     sprintf(file_name, "/proc/%lu/cmdline", (unsigned long int) pid);
348     stream = fopen(file_name, "r");
349     if (!stream) {
350         VLOG_WARN_ONCE("%s: open failed (%s)", file_name, ovs_strerror(errno));
351         goto exit;
352     }
353
354     if (!fgets(line, sizeof line, stream)) {
355         VLOG_WARN_ONCE("%s: read failed (%s)", file_name,
356                        feof(stream) ? "end of file" : ovs_strerror(errno));
357         goto exit_close;
358     }
359
360     paren = strchr(line, '(');
361     if (paren) {
362         int x;
363         if (ovs_scan(paren + 1, "%d", &x)) {
364             crashes = x;
365         }
366     }
367
368 exit_close:
369     fclose(stream);
370 exit:
371     return crashes;
372 }
373
374 struct process_info {
375     unsigned long int vsz;      /* Virtual size, in kB. */
376     unsigned long int rss;      /* Resident set size, in kB. */
377     long long int booted;       /* ms since monitor started. */
378     int crashes;                /* # of crashes (usually 0). */
379     long long int uptime;       /* ms since last (re)started by monitor. */
380     long long int cputime;      /* ms of CPU used during 'uptime'. */
381 };
382
383 static bool
384 get_process_info(pid_t pid, struct process_info *pinfo)
385 {
386     struct raw_process_info child;
387
388     ovs_assert(LINUX);
389     if (!get_raw_process_info(pid, &child)) {
390         return false;
391     }
392
393     pinfo->vsz = child.vsz;
394     pinfo->rss = child.rss;
395     pinfo->booted = child.uptime;
396     pinfo->crashes = 0;
397     pinfo->uptime = child.uptime;
398     pinfo->cputime = child.cputime;
399
400     if (child.ppid) {
401         struct raw_process_info parent;
402
403         get_raw_process_info(child.ppid, &parent);
404         if (!strcmp(child.name, parent.name)) {
405             pinfo->booted = parent.uptime;
406             pinfo->crashes = count_crashes(child.ppid);
407         }
408     }
409
410     return true;
411 }
412
413 static void
414 get_process_stats(struct smap *stats)
415 {
416 #ifndef _WIN32
417     struct dirent *de;
418     DIR *dir;
419
420     dir = opendir(ovs_rundir());
421     if (!dir) {
422         VLOG_ERR_ONCE("%s: open failed (%s)",
423                       ovs_rundir(), ovs_strerror(errno));
424         return;
425     }
426
427     while ((de = readdir(dir)) != NULL) {
428         struct process_info pinfo;
429         char *file_name;
430         char *extension;
431         char *key;
432         pid_t pid;
433
434 #ifdef _DIRENT_HAVE_D_TYPE
435         if (de->d_type != DT_UNKNOWN && de->d_type != DT_REG) {
436             continue;
437         }
438 #endif
439
440         extension = strrchr(de->d_name, '.');
441         if (!extension || strcmp(extension, ".pid")) {
442             continue;
443         }
444
445         file_name = xasprintf("%s/%s", ovs_rundir(), de->d_name);
446         pid = read_pidfile(file_name);
447         free(file_name);
448         if (pid < 0) {
449             continue;
450         }
451
452         key = xasprintf("process_%.*s",
453                         (int) (extension - de->d_name), de->d_name);
454         if (!smap_get(stats, key)) {
455             if (LINUX && get_process_info(pid, &pinfo)) {
456                 smap_add_format(stats, key, "%lu,%lu,%lld,%d,%lld,%lld",
457                                 pinfo.vsz, pinfo.rss, pinfo.cputime,
458                                 pinfo.crashes, pinfo.booted, pinfo.uptime);
459             } else {
460                 smap_add(stats, key, "");
461             }
462         }
463         free(key);
464     }
465
466     closedir(dir);
467 #endif /* _WIN32 */
468 }
469
470 static void
471 get_filesys_stats(struct smap *stats OVS_UNUSED)
472 {
473 #if HAVE_GETMNTENT_R && HAVE_STATVFS
474     static const char file_name[] = "/etc/mtab";
475     struct mntent mntent;
476     struct mntent *me;
477     char buf[4096];
478     FILE *stream;
479     struct ds s;
480
481     stream = setmntent(file_name, "r");
482     if (!stream) {
483         VLOG_ERR_ONCE("%s: open failed (%s)", file_name, ovs_strerror(errno));
484         return;
485     }
486
487     ds_init(&s);
488     while ((me = getmntent_r(stream, &mntent, buf, sizeof buf)) != NULL) {
489         unsigned long long int total, free;
490         struct statvfs vfs;
491         char *p;
492
493         /* Skip non-local and read-only filesystems. */
494         if (strncmp(me->mnt_fsname, "/dev", 4)
495             || !strstr(me->mnt_opts, "rw")) {
496             continue;
497         }
498
499         /* Given the mount point we can stat the file system. */
500         if (statvfs(me->mnt_dir, &vfs) && vfs.f_flag & ST_RDONLY) {
501             /* That's odd... */
502             continue;
503         }
504
505         /* Now format the data. */
506         if (s.length) {
507             ds_put_char(&s, ' ');
508         }
509         for (p = me->mnt_dir; *p != '\0'; p++) {
510             ds_put_char(&s, *p == ' ' || *p == ',' ? '_' : *p);
511         }
512         total = (unsigned long long int) vfs.f_frsize * vfs.f_blocks / 1024;
513         free = (unsigned long long int) vfs.f_frsize * vfs.f_bfree / 1024;
514         ds_put_format(&s, ",%llu,%llu", total, total - free);
515     }
516     endmntent(stream);
517
518     if (s.length) {
519         smap_add(stats, "file_systems", ds_cstr(&s));
520     }
521     ds_destroy(&s);
522 #endif  /* HAVE_GETMNTENT_R && HAVE_STATVFS */
523 }
524 \f
525 #define SYSTEM_STATS_INTERVAL (5 * 1000) /* In milliseconds. */
526
527 static struct ovs_mutex mutex = OVS_MUTEX_INITIALIZER;
528 static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
529 static struct latch latch OVS_GUARDED_BY(mutex);
530 static bool enabled;
531 static bool started OVS_GUARDED_BY(mutex);
532 static struct smap *system_stats OVS_GUARDED_BY(mutex);
533
534 static void *system_stats_thread_func(void *);
535 static void discard_stats(void);
536
537 /* Enables or disables system stats collection, according to 'enable'. */
538 void
539 system_stats_enable(bool enable)
540 {
541     if (enabled != enable) {
542         ovs_mutex_lock(&mutex);
543         if (enable) {
544             if (!started) {
545                 xpthread_create(NULL, NULL, system_stats_thread_func, NULL);
546                 latch_init(&latch);
547                 started = true;
548             }
549             discard_stats();
550             xpthread_cond_signal(&cond);
551         }
552         enabled = enable;
553         ovs_mutex_unlock(&mutex);
554     }
555 }
556
557 /* Tries to obtain a new snapshot of system stats every SYSTEM_STATS_INTERVAL
558  * milliseconds.
559  *
560  * When a new snapshot is available (which only occurs if system stats are
561  * enabled), returns it as an smap owned by the caller.  The caller must use
562  * both smap_destroy() and free() to completely free the returned data.
563  *
564  * When no new snapshot is available, returns NULL. */
565 struct smap *
566 system_stats_run(void)
567 {
568     struct smap *stats = NULL;
569
570     ovs_mutex_lock(&mutex);
571     if (system_stats) {
572         latch_poll(&latch);
573
574         if (enabled) {
575             stats = system_stats;
576             system_stats = NULL;
577         } else {
578             discard_stats();
579         }
580     }
581     ovs_mutex_unlock(&mutex);
582
583     return stats;
584 }
585
586 /* Causes poll_block() to wake up when system_stats_run() needs to be
587  * called. */
588 void
589 system_stats_wait(void)
590 {
591     if (enabled) {
592         latch_wait(&latch);
593     }
594 }
595
596 static void
597 discard_stats(void) OVS_REQUIRES(mutex)
598 {
599     if (system_stats) {
600         smap_destroy(system_stats);
601         free(system_stats);
602         system_stats = NULL;
603     }
604 }
605
606 static void * NO_RETURN
607 system_stats_thread_func(void *arg OVS_UNUSED)
608 {
609     pthread_detach(pthread_self());
610
611     for (;;) {
612         long long int next_refresh;
613         struct smap *stats;
614
615         ovs_mutex_lock(&mutex);
616         while (!enabled) {
617             ovs_mutex_cond_wait(&cond, &mutex);
618         }
619         ovs_mutex_unlock(&mutex);
620
621         stats = xmalloc(sizeof *stats);
622         smap_init(stats);
623         get_cpu_cores(stats);
624         get_load_average(stats);
625         get_memory_stats(stats);
626         get_process_stats(stats);
627         get_filesys_stats(stats);
628
629         ovs_mutex_lock(&mutex);
630         discard_stats();
631         system_stats = stats;
632         latch_set(&latch);
633         ovs_mutex_unlock(&mutex);
634
635         next_refresh = time_msec() + SYSTEM_STATS_INTERVAL;
636         do {
637             poll_timer_wait_until(next_refresh);
638             poll_block();
639         } while (time_msec() < next_refresh);
640     }
641 }