vlog: Make client supply semicolon for VLOG_DEFINE_THIS_MODULE.
[sliver-openvswitch.git] / vswitchd / system-stats.c
1 /* Copyright (c) 2010 Nicira Networks
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 <assert.h>
19 #include <ctype.h>
20 #include <dirent.h>
21 #include <errno.h>
22 #if HAVE_MNTENT_H
23 #include <mntent.h>
24 #endif
25 #include <signal.h>
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 "shash.h"
38 #include "system-stats.h"
39 #include "timeval.h"
40 #include "vlog.h"
41
42 VLOG_DEFINE_THIS_MODULE(system_stats);
43
44 /* #ifdefs make it a pain to maintain code: you have to try to build both ways.
45  * Thus, this file tries to compile as much of the code as possible regardless
46  * of the target, by writing "if (LINUX)" instead of "#ifdef __linux__" where
47  * this is possible. */
48 #ifdef __linux__
49 #include <asm/param.h>
50 #define LINUX 1
51 #else
52 #define LINUX 0
53 #endif
54
55 static void
56 get_cpu_cores(struct shash *stats)
57 {
58     long int n_cores = sysconf(_SC_NPROCESSORS_ONLN);
59     if (n_cores > 0) {
60         shash_add(stats, "cpu", xasprintf("%ld", n_cores));
61     }
62 }
63
64 static void
65 get_load_average(struct shash *stats OVS_UNUSED)
66 {
67 #if HAVE_GETLOADAVG
68     double loadavg[3];
69
70     if (getloadavg(loadavg, 3) == 3) {
71         shash_add(stats, "load_average",
72                   xasprintf("%.2f,%.2f,%.2f",
73                             loadavg[0], loadavg[1], loadavg[2]));
74     }
75 #endif
76 }
77
78 static unsigned int
79 get_page_size(void)
80 {
81     static unsigned int cached;
82
83     if (!cached) {
84         long int value = sysconf(_SC_PAGESIZE);
85         if (value >= 0) {
86             cached = value;
87         }
88     }
89
90     return cached;
91 }
92
93 static void
94 get_memory_stats(struct shash *stats)
95 {
96     if (!LINUX) {
97         unsigned int pagesize = get_page_size();
98         long int phys_pages = sysconf(_SC_PHYS_PAGES);
99         long int avphys_pages = sysconf(_SC_AVPHYS_PAGES);
100         int mem_total, mem_used;
101
102         if (pagesize <= 0 || phys_pages <= 0 || avphys_pages <= 0) {
103             return;
104         }
105
106         mem_total = phys_pages * (pagesize / 1024);
107         mem_used = (phys_pages - avphys_pages) * (pagesize / 1024);
108         shash_add(stats, "memory", xasprintf("%d,%d", mem_total, mem_used));
109     } else {
110         static const char file_name[] = "/proc/meminfo";
111         int mem_used, mem_cache, swap_used;
112         int mem_free = 0;
113         int buffers = 0;
114         int cached = 0;
115         int swap_free = 0;
116         int mem_total = 0;
117         int swap_total = 0;
118         struct shash dict;
119         char line[128];
120         FILE *stream;
121
122         stream = fopen(file_name, "r");
123         if (!stream) {
124             VLOG_WARN_ONCE("%s: open failed (%s)", file_name, strerror(errno));
125             return;
126         }
127
128         shash_init(&dict);
129         shash_add(&dict, "MemTotal", &mem_total);
130         shash_add(&dict, "MemFree", &mem_free);
131         shash_add(&dict, "Buffers", &buffers);
132         shash_add(&dict, "Cached", &cached);
133         shash_add(&dict, "SwapTotal", &swap_total);
134         shash_add(&dict, "SwapFree", &swap_free);
135         while (fgets(line, sizeof line, stream)) {
136             char key[16];
137             int value;
138
139             if (sscanf(line, "%15[^:]: %u", key, &value) == 2) {
140                 int *valuep = shash_find_data(&dict, key);
141                 if (valuep) {
142                     *valuep = value;
143                 }
144             }
145         }
146         fclose(stream);
147         shash_destroy(&dict);
148
149         mem_used = mem_total - mem_free;
150         mem_cache = buffers + cached;
151         swap_used = swap_total - swap_free;
152         shash_add(stats, "memory",
153                   xasprintf("%d,%d,%d,%d,%d", mem_total, mem_used, mem_cache,
154                             swap_total, swap_used));
155     }
156 }
157
158 /* Returns the time at which the system booted, as the number of milliseconds
159  * since the epoch, or 0 if the time of boot cannot be determined. */
160 static long long int
161 get_boot_time(void)
162 {
163     static long long int cache_expiration = LLONG_MIN;
164     static long long int boot_time;
165
166     assert(LINUX);
167
168     if (time_msec() >= cache_expiration) {
169         static const char stat_file[] = "/proc/stat";
170         char line[128];
171         FILE *stream;
172
173         cache_expiration = time_msec() + 5 * 1000;
174
175         stream = fopen(stat_file, "r");
176         if (!stream) {
177             VLOG_ERR_ONCE("%s: open failed (%s)", stat_file, strerror(errno));
178             return boot_time;
179         }
180
181         while (fgets(line, sizeof line, stream)) {
182             long long int btime;
183             if (sscanf(line, "btime %lld", &btime) == 1) {
184                 boot_time = btime * 1000;
185                 goto done;
186             }
187         }
188         VLOG_ERR_ONCE("%s: btime not found", stat_file);
189     done:
190         fclose(stream);
191     }
192     return boot_time;
193 }
194
195 static unsigned long long int
196 ticks_to_ms(unsigned long long int ticks)
197 {
198     assert(LINUX);
199
200 #ifndef USER_HZ
201 #define USER_HZ 100
202 #endif
203
204 #if USER_HZ == 100              /* Common case. */
205     return ticks * (1000 / USER_HZ);
206 #else  /* Alpha and some other architectures.  */
207     double factor = 1000.0 / USER_HZ;
208     return ticks * factor + 0.5;
209 #endif
210 }
211
212 struct raw_process_info {
213     unsigned long int vsz;      /* Virtual size, in kB. */
214     unsigned long int rss;      /* Resident set size, in kB. */
215     long long int uptime;       /* ms since started. */
216     long long int cputime;      /* ms of CPU used during 'uptime'. */
217     pid_t ppid;                 /* Parent. */
218     char name[18];              /* Name (surrounded by parentheses). */
219 };
220
221 static bool
222 get_raw_process_info(pid_t pid, struct raw_process_info *raw)
223 {
224     unsigned long long int vsize, rss, start_time, utime, stime;
225     long long int start_msec;
226     unsigned long ppid;
227     char file_name[128];
228     FILE *stream;
229     int n;
230
231     assert(LINUX);
232
233     sprintf(file_name, "/proc/%lu/stat", (unsigned long int) pid);
234     stream = fopen(file_name, "r");
235     if (!stream) {
236         VLOG_ERR_ONCE("%s: open failed (%s)", file_name, strerror(errno));
237         return false;
238     }
239
240     n = fscanf(stream,
241                "%*d "           /* (1. pid) */
242                "%17s "          /* 2. process name */
243                "%*c "           /* (3. state) */
244                "%lu "           /* 4. ppid */
245                "%*d "           /* (5. pgid) */
246                "%*d "           /* (6. sid) */
247                "%*d "           /* (7. tty_nr) */
248                "%*d "           /* (8. tty_pgrp) */
249                "%*u "           /* (9. flags) */
250                "%*u "           /* (10. min_flt) */
251                "%*u "           /* (11. cmin_flt) */
252                "%*u "           /* (12. maj_flt) */
253                "%*u "           /* (13. cmaj_flt) */
254                "%llu "          /* 14. utime */
255                "%llu "          /* 15. stime */
256                "%*d "           /* (16. cutime) */
257                "%*d "           /* (17. cstime) */
258                "%*d "           /* (18. priority) */
259                "%*d "           /* (19. nice) */
260                "%*d "           /* (20. num_threads) */
261                "%*d "           /* (21. always 0) */
262                "%llu "          /* 22. start_time */
263                "%llu "          /* 23. vsize */
264                "%llu "          /* 24. rss */
265 #if 0
266                /* These are here for documentation but #if'd out to save
267                 * actually parsing them from the stream for no benefit. */
268                "%*lu "          /* (25. rsslim) */
269                "%*lu "          /* (26. start_code) */
270                "%*lu "          /* (27. end_code) */
271                "%*lu "          /* (28. start_stack) */
272                "%*lu "          /* (29. esp) */
273                "%*lu "          /* (30. eip) */
274                "%*lu "          /* (31. pending signals) */
275                "%*lu "          /* (32. blocked signals) */
276                "%*lu "          /* (33. ignored signals) */
277                "%*lu "          /* (34. caught signals) */
278                "%*lu "          /* (35. whcan) */
279                "%*lu "          /* (36. always 0) */
280                "%*lu "          /* (37. always 0) */
281                "%*d "           /* (38. exit_signal) */
282                "%*d "           /* (39. task_cpu) */
283                "%*u "           /* (40. rt_priority) */
284                "%*u "           /* (41. policy) */
285                "%*llu "         /* (42. blkio_ticks) */
286                "%*lu "          /* (43. gtime) */
287                "%*ld"           /* (44. cgtime) */
288 #endif
289                , raw->name, &ppid, &utime, &stime, &start_time, &vsize, &rss);
290     fclose(stream);
291     if (n != 7) {
292         VLOG_ERR_ONCE("%s: fscanf failed", file_name);
293         return false;
294     }
295
296     start_msec = get_boot_time() + ticks_to_ms(start_time);
297
298     raw->vsz = vsize / 1024;
299     raw->rss = rss * (getpagesize() / 1024);
300     raw->uptime = time_wall_msec() - start_msec;
301     raw->cputime = ticks_to_ms(utime + stime);
302     raw->ppid = ppid;
303
304     return true;
305 }
306
307 static int
308 count_crashes(pid_t pid)
309 {
310     char file_name[128];
311     const char *paren;
312     char line[128];
313     int crashes = 0;
314     FILE *stream;
315
316     assert(LINUX);
317
318     sprintf(file_name, "/proc/%lu/cmdline", (unsigned long int) pid);
319     stream = fopen(file_name, "r");
320     if (!stream) {
321         VLOG_WARN_ONCE("%s: open failed (%s)", file_name, strerror(errno));
322         goto exit;
323     }
324
325     if (!fgets(line, sizeof line, stream)) {
326         VLOG_WARN_ONCE("%s: read failed (%s)", file_name,
327                        feof(stream) ? "end of file" : strerror(errno));
328         goto exit_close;
329     }
330
331     paren = strchr(line, '(');
332     if (paren) {
333         int x;
334         if (sscanf(paren + 1, "%d", &x) == 1) {
335             crashes = x;
336         }
337     }
338
339 exit_close:
340     fclose(stream);
341 exit:
342     return crashes;
343 }
344
345 struct process_info {
346     unsigned long int vsz;      /* Virtual size, in kB. */
347     unsigned long int rss;      /* Resident set size, in kB. */
348     long long int booted;       /* ms since monitor started. */
349     int crashes;                /* # of crashes (usually 0). */
350     long long int uptime;       /* ms since last (re)started by monitor. */
351     long long int cputime;      /* ms of CPU used during 'uptime'. */
352 };
353
354 static bool
355 get_process_info(pid_t pid, struct process_info *pinfo)
356 {
357     struct raw_process_info child;
358
359     assert(LINUX);
360     if (!get_raw_process_info(pid, &child)) {
361         return false;
362     }
363
364     pinfo->vsz = child.vsz;
365     pinfo->rss = child.rss;
366     pinfo->booted = child.uptime;
367     pinfo->crashes = 0;
368     pinfo->uptime = child.uptime;
369     pinfo->cputime = child.cputime;
370
371     if (child.ppid) {
372         struct raw_process_info parent;
373
374         get_raw_process_info(child.ppid, &parent);
375         if (!strcmp(child.name, parent.name)) {
376             pinfo->booted = parent.uptime;
377             pinfo->crashes = count_crashes(child.ppid);
378         }
379     }
380
381     return true;
382 }
383
384 static void
385 get_process_stats(struct shash *stats)
386 {
387     struct dirent *de;
388     DIR *dir;
389
390     dir = opendir(ovs_rundir);
391     if (!dir) {
392         VLOG_ERR_ONCE("%s: open failed (%s)", ovs_rundir, strerror(errno));
393         return;
394     }
395
396     while ((de = readdir(dir)) != NULL) {
397         struct process_info pinfo;
398         char *key, *value;
399         char *file_name;
400         char *extension;
401         pid_t pid;
402
403 #ifdef _DIRENT_HAVE_D_TYPE
404         if (de->d_type != DT_UNKNOWN && de->d_type != DT_REG) {
405             continue;
406         }
407 #endif
408
409         extension = strrchr(de->d_name, '.');
410         if (!extension || strcmp(extension, ".pid")) {
411             continue;
412         }
413
414         file_name = xasprintf("%s/%s", ovs_rundir, de->d_name);
415         pid = read_pidfile(file_name);
416         free(file_name);
417         if (pid < 0 || kill(pid, 0)) {
418             continue;
419         }
420
421         key = xasprintf("process_%.*s",
422                         (int) (extension - de->d_name), de->d_name);
423         if (shash_find(stats, key)) {
424             free(key);
425             continue;
426         }
427
428         if (LINUX && get_process_info(pid, &pinfo)) {
429             value = xasprintf("%lu,%lu,%lld,%d,%lld,%lld",
430                               pinfo.vsz, pinfo.rss, pinfo.cputime,
431                               pinfo.crashes, pinfo.booted, pinfo.uptime);
432         } else {
433             value = xstrdup("");
434         }
435
436         shash_add_nocopy(stats, key, value);
437     }
438
439     closedir(dir);
440 }
441
442 static void
443 get_filesys_stats(struct shash *stats OVS_UNUSED)
444 {
445 #if HAVE_SETMNTENT && HAVE_STATVFS
446     static const char file_name[] = "/etc/mtab";
447     struct mntent *me;
448     FILE *stream;
449     struct ds s;
450
451     stream = setmntent(file_name, "r");
452     if (!stream) {
453         VLOG_ERR_ONCE("%s: open failed (%s)", file_name, strerror(errno));
454         return;
455     }
456
457     ds_init(&s);
458     while ((me = getmntent(stream)) != NULL) {
459         unsigned long long int total, free;
460         struct statvfs vfs;
461         char *p;
462
463         /* Skip non-local and read-only filesystems. */
464         if (strncmp(me->mnt_fsname, "/dev", 4)
465             || !strstr(me->mnt_opts, "rw")) {
466             continue;
467         }
468
469         /* Given the mount point we can stat the file system. */
470         if (statvfs(me->mnt_dir, &vfs) && vfs.f_flag & ST_RDONLY) {
471             /* That's odd... */
472             continue;
473         }
474
475         /* Now format the data. */
476         if (s.length) {
477             ds_put_char(&s, ' ');
478         }
479         for (p = me->mnt_dir; *p != '\0'; p++) {
480             ds_put_char(&s, *p == ' ' || *p == ',' ? '_' : *p);
481         }
482         total = (unsigned long long int) vfs.f_frsize * vfs.f_blocks / 1024;
483         free = (unsigned long long int) vfs.f_frsize * vfs.f_bfree / 1024;
484         ds_put_format(&s, ",%llu,%llu", total, total - free);
485     }
486     endmntent(stream);
487
488     if (s.length) {
489         shash_add(stats, "file_systems", ds_steal_cstr(&s));
490     }
491     ds_destroy(&s);
492 #endif  /* HAVE_SETMNTENT && HAVE_STATVFS */
493 }
494
495 void
496 get_system_stats(struct shash *stats)
497 {
498     get_cpu_cores(stats);
499     get_load_average(stats);
500     get_memory_stats(stats);
501     get_process_stats(stats);
502     get_filesys_stats(stats);
503 }