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