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