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