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