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