vlog: Make the vlog module catalog program-specific.
[sliver-openvswitch.git] / lib / vlog.c
1 /*
2  * Copyright (c) 2008, 2009, 2010 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "vlog.h"
19 #include <assert.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #include <stdarg.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/types.h>
26 #include <syslog.h>
27 #include <time.h>
28 #include <unistd.h>
29 #include "dirs.h"
30 #include "dynamic-string.h"
31 #include "sat-math.h"
32 #include "timeval.h"
33 #include "unixctl.h"
34 #include "util.h"
35
36 VLOG_DEFINE_THIS_MODULE(vlog)
37
38 /* Name for each logging level. */
39 static const char *level_names[VLL_N_LEVELS] = {
40 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
41     VLOG_LEVELS
42 #undef VLOG_LEVEL
43 };
44
45 /* Syslog value for each logging level. */
46 static int syslog_levels[VLL_N_LEVELS] = {
47 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) SYSLOG_LEVEL,
48     VLOG_LEVELS
49 #undef VLOG_LEVEL
50 };
51
52 /* The log modules. */
53 #if USE_LINKER_SECTIONS
54 extern struct vlog_module *__start_vlog_modules[];
55 extern struct vlog_module *__stop_vlog_modules[];
56 #define vlog_modules __start_vlog_modules
57 #define n_vlog_modules (__stop_vlog_modules - __start_vlog_modules)
58 #else
59 #define VLOG_MODULE VLOG_DEFINE_MODULE__
60 #include "vlog-modules.def"
61 #undef VLOG_MODULE
62
63 struct vlog_module *vlog_modules[] = {
64 #define VLOG_MODULE(NAME) &VLM_##NAME,
65 #include "vlog-modules.def"
66 #undef VLOG_MODULE
67 };
68 #define n_vlog_modules ARRAY_SIZE(vlog_modules)
69 #endif
70
71 /* Information about each facility. */
72 struct facility {
73     const char *name;           /* Name. */
74     char *pattern;              /* Current pattern. */
75     bool default_pattern;       /* Whether current pattern is the default. */
76 };
77 static struct facility facilities[VLF_N_FACILITIES] = {
78 #define VLOG_FACILITY(NAME, PATTERN) {#NAME, PATTERN, true},
79     VLOG_FACILITIES
80 #undef VLOG_FACILITY
81 };
82
83 /* Time at which vlog was initialized, in milliseconds. */
84 static long long int boot_time;
85
86 /* VLF_FILE configuration. */
87 static char *log_file_name;
88 static FILE *log_file;
89
90 /* vlog initialized? */
91 static bool vlog_inited;
92
93 static void format_log_message(const struct vlog_module *, enum vlog_level,
94                                enum vlog_facility, unsigned int msg_num,
95                                const char *message, va_list, struct ds *)
96     PRINTF_FORMAT(5, 0);
97
98 /* Searches the 'n_names' in 'names'.  Returns the index of a match for
99  * 'target', or 'n_names' if no name matches. */
100 static size_t
101 search_name_array(const char *target, const char **names, size_t n_names) 
102 {
103     size_t i;
104
105     for (i = 0; i < n_names; i++) {
106         assert(names[i]);
107         if (!strcasecmp(names[i], target)) {
108             break;
109         }
110     }
111     return i;
112 }
113
114 /* Returns the name for logging level 'level'. */
115 const char *
116 vlog_get_level_name(enum vlog_level level)
117 {
118     assert(level < VLL_N_LEVELS);
119     return level_names[level];
120 }
121
122 /* Returns the logging level with the given 'name', or VLL_N_LEVELS if 'name'
123  * is not the name of a logging level. */
124 enum vlog_level
125 vlog_get_level_val(const char *name) 
126 {
127     return search_name_array(name, level_names, ARRAY_SIZE(level_names));
128 }
129
130 /* Returns the name for logging facility 'facility'. */
131 const char *
132 vlog_get_facility_name(enum vlog_facility facility) 
133 {
134     assert(facility < VLF_N_FACILITIES);
135     return facilities[facility].name;
136 }
137
138 /* Returns the logging facility named 'name', or VLF_N_FACILITIES if 'name' is
139  * not the name of a logging facility. */
140 enum vlog_facility
141 vlog_get_facility_val(const char *name) 
142 {
143     size_t i;
144
145     for (i = 0; i < VLF_N_FACILITIES; i++) {
146         if (!strcasecmp(facilities[i].name, name)) {
147             break;
148         }
149     }
150     return i;
151 }
152
153 /* Returns the name for logging module 'module'. */
154 const char *
155 vlog_get_module_name(const struct vlog_module *module)
156 {
157     return module->name;
158 }
159
160 /* Returns the logging module named 'name', or NULL if 'name' is not the name
161  * of a logging module. */
162 struct vlog_module *
163 vlog_module_from_name(const char *name)
164 {
165     struct vlog_module **mp;
166
167     for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
168         if (!strcasecmp(name, (*mp)->name)) {
169             return *mp;
170         }
171     }
172     return NULL;
173 }
174
175 /* Returns the current logging level for the given 'module' and 'facility'. */
176 enum vlog_level
177 vlog_get_level(const struct vlog_module *module, enum vlog_facility facility) 
178 {
179     assert(facility < VLF_N_FACILITIES);
180     return module->levels[facility];
181 }
182
183 static void
184 update_min_level(struct vlog_module *module)
185 {
186     enum vlog_facility facility;
187
188     module->min_level = VLL_EMER;
189     for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
190         if (log_file || facility != VLF_FILE) {
191             enum vlog_level level = module->levels[facility];
192             if (level < module->min_level) {
193                 module->min_level = level;
194             }
195         }
196     }
197 }
198
199 static void
200 set_facility_level(enum vlog_facility facility, struct vlog_module *module,
201                    enum vlog_level level)
202 {
203     assert(facility >= 0 && facility < VLF_N_FACILITIES);
204     assert(level < VLL_N_LEVELS);
205
206     if (!module) {
207         struct vlog_module **mp;
208
209         for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
210             (*mp)->levels[facility] = level;
211             update_min_level(*mp);
212         }
213     } else {
214         module->levels[facility] = level;
215         update_min_level(module);
216     }
217 }
218
219 /* Sets the logging level for the given 'module' and 'facility' to 'level'.  A
220  * null 'module' or a 'facility' of VLF_ANY_FACILITY is treated as a wildcard
221  * across all modules or facilities, respectively. */
222 void
223 vlog_set_levels(struct vlog_module *module, enum vlog_facility facility,
224                 enum vlog_level level) 
225 {
226     assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
227     if (facility == VLF_ANY_FACILITY) {
228         for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
229             set_facility_level(facility, module, level);
230         }
231     } else {
232         set_facility_level(facility, module, level);
233     }
234 }
235
236 static void
237 do_set_pattern(enum vlog_facility facility, const char *pattern) 
238 {
239     struct facility *f = &facilities[facility];
240     if (!f->default_pattern) {
241         free(f->pattern);
242     } else {
243         f->default_pattern = false;
244     }
245     f->pattern = xstrdup(pattern);
246 }
247
248 /* Sets the pattern for the given 'facility' to 'pattern'. */
249 void
250 vlog_set_pattern(enum vlog_facility facility, const char *pattern)
251 {
252     assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
253     if (facility == VLF_ANY_FACILITY) {
254         for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
255             do_set_pattern(facility, pattern);
256         }
257     } else {
258         do_set_pattern(facility, pattern);
259     }
260 }
261
262 /* Returns the name of the log file used by VLF_FILE, or a null pointer if no
263  * log file has been set.  (A non-null return value does not assert that the
264  * named log file is in use: if vlog_set_log_file() or vlog_reopen_log_file()
265  * fails, it still sets the log file name.) */
266 const char *
267 vlog_get_log_file(void)
268 {
269     return log_file_name;
270 }
271
272 /* Sets the name of the log file used by VLF_FILE to 'file_name', or to the
273  * default file name if 'file_name' is null.  Returns 0 if successful,
274  * otherwise a positive errno value. */
275 int
276 vlog_set_log_file(const char *file_name)
277 {
278     char *old_log_file_name;
279     struct vlog_module **mp;
280     int error;
281
282     /* Close old log file. */
283     if (log_file) {
284         VLOG_INFO("closing log file");
285         fclose(log_file);
286         log_file = NULL;
287     }
288
289     /* Update log file name and free old name.  The ordering is important
290      * because 'file_name' might be 'log_file_name' or some suffix of it. */
291     old_log_file_name = log_file_name;
292     log_file_name = (file_name
293                      ? xstrdup(file_name)
294                      : xasprintf("%s/%s.log", ovs_logdir, program_name));
295     free(old_log_file_name);
296     file_name = NULL;           /* Might have been freed. */
297
298     /* Open new log file and update min_levels[] to reflect whether we actually
299      * have a log_file. */
300     log_file = fopen(log_file_name, "a");
301     for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
302         update_min_level(*mp);
303     }
304
305     /* Log success or failure. */
306     if (!log_file) {
307         VLOG_WARN("failed to open %s for logging: %s",
308                   log_file_name, strerror(errno));
309         error = errno;
310     } else {
311         VLOG_INFO("opened log file %s", log_file_name);
312         error = 0;
313     }
314
315     return error;
316 }
317
318 /* Closes and then attempts to re-open the current log file.  (This is useful
319  * just after log rotation, to ensure that the new log file starts being used.)
320  * Returns 0 if successful, otherwise a positive errno value. */
321 int
322 vlog_reopen_log_file(void)
323 {
324     return log_file_name ? vlog_set_log_file(log_file_name) : 0;
325 }
326
327 /* Set debugging levels:
328  *
329  *  mod[:facility[:level]] mod2[:facility[:level]] ...
330  *
331  * Return null if successful, otherwise an error message that the caller must
332  * free().
333  */
334 char *
335 vlog_set_levels_from_string(const char *s_)
336 {
337     char *save_ptr = NULL;
338     char *s = xstrdup(s_);
339     char *module, *facility;
340
341     for (module = strtok_r(s, ": \t", &save_ptr); module != NULL;
342          module = strtok_r(NULL, ": \t", &save_ptr)) {
343         struct vlog_module *e_module;
344         enum vlog_facility e_facility;
345
346         facility = strtok_r(NULL, ":", &save_ptr);
347
348         if (!facility || !strcmp(facility, "ANY")) {
349             e_facility = VLF_ANY_FACILITY;
350         } else {
351             e_facility = vlog_get_facility_val(facility);
352             if (e_facility >= VLF_N_FACILITIES) {
353                 char *msg = xasprintf("unknown facility \"%s\"", facility);
354                 free(s);
355                 return msg;
356             }
357         }
358
359         if (!strcmp(module, "PATTERN")) {
360             vlog_set_pattern(e_facility, save_ptr);
361             break;
362         } else {
363             char *level;
364             enum vlog_level e_level;
365
366             if (!strcmp(module, "ANY")) {
367                 e_module = NULL;
368             } else {
369                 e_module = vlog_module_from_name(module);
370                 if (!e_module) {
371                     char *msg = xasprintf("unknown module \"%s\"", module);
372                     free(s);
373                     return msg;
374                 }
375             }
376
377             level = strtok_r(NULL, ":", &save_ptr);
378             e_level = level ? vlog_get_level_val(level) : VLL_DBG;
379             if (e_level >= VLL_N_LEVELS) {
380                 char *msg = xasprintf("unknown level \"%s\"", level);
381                 free(s);
382                 return msg;
383             }
384
385             vlog_set_levels(e_module, e_facility, e_level);
386         }
387     }
388     free(s);
389     return NULL;
390 }
391
392 /* If 'arg' is null, configure maximum verbosity.  Otherwise, sets
393  * configuration according to 'arg' (see vlog_set_levels_from_string()). */
394 void
395 vlog_set_verbosity(const char *arg)
396 {
397     if (arg) {
398         char *msg = vlog_set_levels_from_string(arg);
399         if (msg) {
400             ovs_fatal(0, "processing \"%s\": %s", arg, msg);
401         }
402     } else {
403         vlog_set_levels(NULL, VLF_ANY_FACILITY, VLL_DBG);
404     }
405 }
406
407 static void
408 vlog_unixctl_set(struct unixctl_conn *conn,
409                  const char *args, void *aux OVS_UNUSED)
410 {
411     char *msg = vlog_set_levels_from_string(args);
412     unixctl_command_reply(conn, msg ? 501 : 202, msg);
413     free(msg);
414 }
415
416 static void
417 vlog_unixctl_list(struct unixctl_conn *conn,
418                   const char *args OVS_UNUSED, void *aux OVS_UNUSED)
419 {
420     char *msg = vlog_get_levels();
421     unixctl_command_reply(conn, 200, msg);
422     free(msg);
423 }
424
425 static void
426 vlog_unixctl_reopen(struct unixctl_conn *conn,
427                     const char *args OVS_UNUSED, void *aux OVS_UNUSED)
428 {
429     if (log_file_name) {
430         int error = vlog_reopen_log_file();
431         if (error) {
432             unixctl_command_reply(conn, 503, strerror(errno));
433         } else {
434             unixctl_command_reply(conn, 202, NULL);
435         }
436     } else {
437         unixctl_command_reply(conn, 403, "Logging to file not configured");
438     }
439 }
440
441 /* Initializes the logging subsystem. */
442 void
443 vlog_init(void) 
444 {
445     time_t now;
446
447     if (vlog_inited) {
448         return;
449     }
450     vlog_inited = true;
451
452     openlog(program_name, LOG_NDELAY, LOG_DAEMON);
453
454     boot_time = time_msec();
455     now = time_wall();
456     if (now < 0) {
457         struct tm tm;
458         char s[128];
459
460         localtime_r(&now, &tm);
461         strftime(s, sizeof s, "%a, %d %b %Y %H:%M:%S %z", &tm);
462         VLOG_ERR("current time is negative: %s (%ld)", s, (long int) now);
463     }
464
465     unixctl_command_register("vlog/set", vlog_unixctl_set, NULL);
466     unixctl_command_register("vlog/list", vlog_unixctl_list, NULL);
467     unixctl_command_register("vlog/reopen", vlog_unixctl_reopen, NULL);
468 }
469
470 /* Closes the logging subsystem. */
471 void
472 vlog_exit(void) 
473 {
474     if (vlog_inited) {
475         closelog();
476         vlog_inited = false;
477     }
478 }
479
480 /* Print the current logging level for each module. */
481 char *
482 vlog_get_levels(void)
483 {
484     struct ds s = DS_EMPTY_INITIALIZER;
485     struct vlog_module **mp;
486
487     ds_put_format(&s, "                 console    syslog    file\n");
488     ds_put_format(&s, "                 -------    ------    ------\n");
489
490     for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
491         ds_put_format(&s, "%-16s  %4s       %4s       %4s\n",
492            vlog_get_module_name(*mp),
493            vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
494            vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
495            vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
496     }
497
498     return ds_cstr(&s);
499 }
500
501 /* Returns true if a log message emitted for the given 'module' and 'level'
502  * would cause some log output, false if that module and level are completely
503  * disabled. */
504 bool
505 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
506 {
507     return module->min_level >= level;
508 }
509
510 static const char *
511 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
512 {
513     if (*p == '{') {
514         size_t n = strcspn(p + 1, "}");
515         size_t n_copy = MIN(n, out_size - 1);
516         memcpy(out, p + 1, n_copy);
517         out[n_copy] = '\0';
518         p += n + 2;
519     } else {
520         ovs_strlcpy(out, def, out_size);
521     }
522     return p;
523 }
524
525 static void
526 format_log_message(const struct vlog_module *module, enum vlog_level level,
527                    enum vlog_facility facility, unsigned int msg_num,
528                    const char *message, va_list args_, struct ds *s)
529 {
530     char tmp[128];
531     va_list args;
532     const char *p;
533
534     ds_clear(s);
535     for (p = facilities[facility].pattern; *p != '\0'; ) {
536         enum { LEFT, RIGHT } justify = RIGHT;
537         int pad = '0';
538         size_t length, field, used;
539
540         if (*p != '%') {
541             ds_put_char(s, *p++);
542             continue;
543         }
544
545         p++;
546         if (*p == '-') {
547             justify = LEFT;
548             p++;
549         }
550         if (*p == '0') {
551             pad = '0';
552             p++;
553         }
554         field = 0;
555         while (isdigit((unsigned char)*p)) {
556             field = (field * 10) + (*p - '0');
557             p++;
558         }
559
560         length = s->length;
561         switch (*p++) {
562         case 'A':
563             ds_put_cstr(s, program_name);
564             break;
565         case 'c':
566             p = fetch_braces(p, "", tmp, sizeof tmp);
567             ds_put_cstr(s, vlog_get_module_name(module));
568             break;
569         case 'd':
570             p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
571             ds_put_strftime(s, tmp, NULL);
572             break;
573         case 'm':
574             /* Format user-supplied log message and trim trailing new-lines. */
575             length = s->length;
576             va_copy(args, args_);
577             ds_put_format_valist(s, message, args);
578             va_end(args);
579             while (s->length > length && s->string[s->length - 1] == '\n') {
580                 s->length--;
581             }
582             break;
583         case 'N':
584             ds_put_format(s, "%u", msg_num);
585             break;
586         case 'n':
587             ds_put_char(s, '\n');
588             break;
589         case 'p':
590             ds_put_cstr(s, vlog_get_level_name(level));
591             break;
592         case 'P':
593             ds_put_format(s, "%ld", (long int) getpid());
594             break;
595         case 'r':
596             ds_put_format(s, "%lld", time_msec() - boot_time);
597             break;
598         default:
599             ds_put_char(s, p[-1]);
600             break;
601         }
602         used = s->length - length;
603         if (used < field) {
604             size_t n_pad = field - used;
605             if (justify == RIGHT) {
606                 ds_put_uninit(s, n_pad);
607                 memmove(&s->string[length + n_pad], &s->string[length], used);
608                 memset(&s->string[length], pad, n_pad);
609             } else {
610                 ds_put_char_multiple(s, pad, n_pad);
611             }
612         }
613     }
614 }
615
616 /* Writes 'message' to the log at the given 'level' and as coming from the
617  * given 'module'.
618  *
619  * Guaranteed to preserve errno. */
620 void
621 vlog_valist(const struct vlog_module *module, enum vlog_level level,
622             const char *message, va_list args)
623 {
624     bool log_to_console = module->levels[VLF_CONSOLE] >= level;
625     bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
626     bool log_to_file = module->levels[VLF_FILE] >= level && log_file;
627     if (log_to_console || log_to_syslog || log_to_file) {
628         int save_errno = errno;
629         static unsigned int msg_num;
630         struct ds s;
631
632         vlog_init();
633
634         ds_init(&s);
635         ds_reserve(&s, 1024);
636         msg_num++;
637
638         if (log_to_console) {
639             format_log_message(module, level, VLF_CONSOLE, msg_num,
640                                message, args, &s);
641             ds_put_char(&s, '\n');
642             fputs(ds_cstr(&s), stderr);
643         }
644
645         if (log_to_syslog) {
646             int syslog_level = syslog_levels[level];
647             char *save_ptr = NULL;
648             char *line;
649
650             format_log_message(module, level, VLF_SYSLOG, msg_num,
651                                message, args, &s);
652             for (line = strtok_r(s.string, "\n", &save_ptr); line;
653                  line = strtok_r(NULL, "\n", &save_ptr)) {
654                 syslog(syslog_level, "%s", line);
655             }
656         }
657
658         if (log_to_file) {
659             format_log_message(module, level, VLF_FILE, msg_num,
660                                message, args, &s);
661             ds_put_char(&s, '\n');
662             fputs(ds_cstr(&s), log_file);
663             fflush(log_file);
664         }
665
666         ds_destroy(&s);
667         errno = save_errno;
668     }
669 }
670
671 void
672 vlog(const struct vlog_module *module, enum vlog_level level,
673      const char *message, ...)
674 {
675     va_list args;
676
677     va_start(args, message);
678     vlog_valist(module, level, message, args);
679     va_end(args);
680 }
681
682 bool
683 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
684                  struct vlog_rate_limit *rl)
685 {
686     if (!vlog_is_enabled(module, level)) {
687         return true;
688     }
689
690     if (rl->tokens < VLOG_MSG_TOKENS) {
691         time_t now = time_now();
692         if (rl->last_fill > now) {
693             /* Last filled in the future?  Time must have gone backward, or
694              * 'rl' has not been used before. */
695             rl->tokens = rl->burst;
696         } else if (rl->last_fill < now) {
697             unsigned int add = sat_mul(rl->rate, now - rl->last_fill);
698             unsigned int tokens = sat_add(rl->tokens, add);
699             rl->tokens = MIN(tokens, rl->burst);
700             rl->last_fill = now;
701         }
702         if (rl->tokens < VLOG_MSG_TOKENS) {
703             if (!rl->n_dropped) {
704                 rl->first_dropped = now;
705             }
706             rl->n_dropped++;
707             return true;
708         }
709     }
710     rl->tokens -= VLOG_MSG_TOKENS;
711
712     if (rl->n_dropped) {
713         vlog(module, level,
714              "Dropped %u log messages in last %u seconds "
715              "due to excessive rate",
716              rl->n_dropped, (unsigned int) (time_now() - rl->first_dropped));
717         rl->n_dropped = 0;
718     }
719     return false;
720 }
721
722 void
723 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
724                 struct vlog_rate_limit *rl, const char *message, ...)
725 {
726     if (!vlog_should_drop(module, level, rl)) {
727         va_list args;
728
729         va_start(args, message);
730         vlog_valist(module, level, message, args);
731         va_end(args);
732     }
733 }
734
735 void
736 vlog_usage(void) 
737 {
738     printf("\nLogging options:\n"
739            "  -v, --verbose=MODULE[:FACILITY[:LEVEL]]  set logging levels\n"
740            "  -v, --verbose           set maximum verbosity level\n"
741            "  --log-file[=FILE]       enable logging to specified FILE\n"
742            "                          (default: %s/%s.log)\n",
743            ovs_logdir, program_name);
744 }