Global replace of Nicira Networks.
[sliver-openvswitch.git] / vswitchd / system-stats.c
1 /* Copyright (c) 2010 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 <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 #ifdef _SC_AVPHYS_PAGES
99         long int avphys_pages = sysconf(_SC_AVPHYS_PAGES);
100 #else
101         long int avphys_pages = 0;
102 #endif
103         int mem_total, mem_used;
104
105         if (pagesize <= 0 || phys_pages <= 0 || avphys_pages <= 0) {
106             return;
107         }
108
109         mem_total = phys_pages * (pagesize / 1024);
110         mem_used = (phys_pages - avphys_pages) * (pagesize / 1024);
111         shash_add(stats, "memory", xasprintf("%d,%d", mem_total, mem_used));
112     } else {
113         static const char file_name[] = "/proc/meminfo";
114         int mem_used, mem_cache, swap_used;
115         int mem_free = 0;
116         int buffers = 0;
117         int cached = 0;
118         int swap_free = 0;
119         int mem_total = 0;
120         int swap_total = 0;
121         struct shash dict;
122         char line[128];
123         FILE *stream;
124
125         stream = fopen(file_name, "r");
126         if (!stream) {
127             VLOG_WARN_ONCE("%s: open failed (%s)", file_name, strerror(errno));
128             return;
129         }
130
131         shash_init(&dict);
132         shash_add(&dict, "MemTotal", &mem_total);
133         shash_add(&dict, "MemFree", &mem_free);
134         shash_add(&dict, "Buffers", &buffers);
135         shash_add(&dict, "Cached", &cached);
136         shash_add(&dict, "SwapTotal", &swap_total);
137         shash_add(&dict, "SwapFree", &swap_free);
138         while (fgets(line, sizeof line, stream)) {
139             char key[16];
140             int value;
141
142             if (sscanf(line, "%15[^:]: %u", key, &value) == 2) {
143                 int *valuep = shash_find_data(&dict, key);
144                 if (valuep) {
145                     *valuep = value;
146                 }
147             }
148         }
149         fclose(stream);
150         shash_destroy(&dict);
151
152         mem_used = mem_total - mem_free;
153         mem_cache = buffers + cached;
154         swap_used = swap_total - swap_free;
155         shash_add(stats, "memory",
156                   xasprintf("%d,%d,%d,%d,%d", mem_total, mem_used, mem_cache,
157                             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 shash *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 *key, *value;
402         char *file_name;
403         char *extension;
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 (shash_find(stats, key)) {
427             free(key);
428             continue;
429         }
430
431         if (LINUX && get_process_info(pid, &pinfo)) {
432             value = xasprintf("%lu,%lu,%lld,%d,%lld,%lld",
433                               pinfo.vsz, pinfo.rss, pinfo.cputime,
434                               pinfo.crashes, pinfo.booted, pinfo.uptime);
435         } else {
436             value = xstrdup("");
437         }
438
439         shash_add_nocopy(stats, key, value);
440     }
441
442     closedir(dir);
443 }
444
445 static void
446 get_filesys_stats(struct shash *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         shash_add(stats, "file_systems", ds_steal_cstr(&s));
493     }
494     ds_destroy(&s);
495 #endif  /* HAVE_SETMNTENT && HAVE_STATVFS */
496 }
497
498 void
499 get_system_stats(struct shash *stats)
500 {
501     get_cpu_cores(stats);
502     get_load_average(stats);
503     get_memory_stats(stats);
504     get_process_stats(stats);
505     get_filesys_stats(stats);
506 }