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