31ba96e8102f79236c2523618f754118f3a6c421
[sliver-openvswitch.git] / lib / vlog.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
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 <fcntl.h>
23 #include <stdarg.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <syslog.h>
29 #include <time.h>
30 #include <unistd.h>
31 #include "dirs.h"
32 #include "dynamic-string.h"
33 #include "ofpbuf.h"
34 #include "sat-math.h"
35 #include "svec.h"
36 #include "timeval.h"
37 #include "unixctl.h"
38 #include "util.h"
39 #include "worker.h"
40
41 VLOG_DEFINE_THIS_MODULE(vlog);
42
43 /* Name for each logging level. */
44 static const char *level_names[VLL_N_LEVELS] = {
45 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
46     VLOG_LEVELS
47 #undef VLOG_LEVEL
48 };
49
50 /* Syslog value for each logging level. */
51 static int syslog_levels[VLL_N_LEVELS] = {
52 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) SYSLOG_LEVEL,
53     VLOG_LEVELS
54 #undef VLOG_LEVEL
55 };
56
57 /* The log modules. */
58 #if USE_LINKER_SECTIONS
59 extern struct vlog_module *__start_vlog_modules[];
60 extern struct vlog_module *__stop_vlog_modules[];
61 #define vlog_modules __start_vlog_modules
62 #define n_vlog_modules (__stop_vlog_modules - __start_vlog_modules)
63 #else
64 #define VLOG_MODULE VLOG_DEFINE_MODULE__
65 #include "vlog-modules.def"
66 #undef VLOG_MODULE
67
68 struct vlog_module *vlog_modules[] = {
69 #define VLOG_MODULE(NAME) &VLM_##NAME,
70 #include "vlog-modules.def"
71 #undef VLOG_MODULE
72 };
73 #define n_vlog_modules ARRAY_SIZE(vlog_modules)
74 #endif
75
76 /* Information about each facility. */
77 struct facility {
78     const char *name;           /* Name. */
79     char *pattern;              /* Current pattern. */
80     bool default_pattern;       /* Whether current pattern is the default. */
81 };
82 static struct facility facilities[VLF_N_FACILITIES] = {
83 #define VLOG_FACILITY(NAME, PATTERN) {#NAME, PATTERN, true},
84     VLOG_FACILITIES
85 #undef VLOG_FACILITY
86 };
87
88 /* VLF_FILE configuration. */
89 static char *log_file_name;
90 static int log_fd = -1;
91
92 /* vlog initialized? */
93 static bool vlog_inited;
94
95 static void format_log_message(const struct vlog_module *, enum vlog_level,
96                                enum vlog_facility, unsigned int msg_num,
97                                const char *message, va_list, struct ds *)
98     PRINTF_FORMAT(5, 0);
99 static void vlog_write_file(struct ds *);
100 static void vlog_update_async_log_fd(void);
101
102 /* Searches the 'n_names' in 'names'.  Returns the index of a match for
103  * 'target', or 'n_names' if no name matches. */
104 static size_t
105 search_name_array(const char *target, const char **names, size_t n_names)
106 {
107     size_t i;
108
109     for (i = 0; i < n_names; i++) {
110         assert(names[i]);
111         if (!strcasecmp(names[i], target)) {
112             break;
113         }
114     }
115     return i;
116 }
117
118 /* Returns the name for logging level 'level'. */
119 const char *
120 vlog_get_level_name(enum vlog_level level)
121 {
122     assert(level < VLL_N_LEVELS);
123     return level_names[level];
124 }
125
126 /* Returns the logging level with the given 'name', or VLL_N_LEVELS if 'name'
127  * is not the name of a logging level. */
128 enum vlog_level
129 vlog_get_level_val(const char *name)
130 {
131     return search_name_array(name, level_names, ARRAY_SIZE(level_names));
132 }
133
134 /* Returns the name for logging facility 'facility'. */
135 const char *
136 vlog_get_facility_name(enum vlog_facility facility)
137 {
138     assert(facility < VLF_N_FACILITIES);
139     return facilities[facility].name;
140 }
141
142 /* Returns the logging facility named 'name', or VLF_N_FACILITIES if 'name' is
143  * not the name of a logging facility. */
144 enum vlog_facility
145 vlog_get_facility_val(const char *name)
146 {
147     size_t i;
148
149     for (i = 0; i < VLF_N_FACILITIES; i++) {
150         if (!strcasecmp(facilities[i].name, name)) {
151             break;
152         }
153     }
154     return i;
155 }
156
157 /* Returns the name for logging module 'module'. */
158 const char *
159 vlog_get_module_name(const struct vlog_module *module)
160 {
161     return module->name;
162 }
163
164 /* Returns the logging module named 'name', or NULL if 'name' is not the name
165  * of a logging module. */
166 struct vlog_module *
167 vlog_module_from_name(const char *name)
168 {
169     struct vlog_module **mp;
170
171     for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
172         if (!strcasecmp(name, (*mp)->name)) {
173             return *mp;
174         }
175     }
176     return NULL;
177 }
178
179 /* Returns the current logging level for the given 'module' and 'facility'. */
180 enum vlog_level
181 vlog_get_level(const struct vlog_module *module, enum vlog_facility facility)
182 {
183     assert(facility < VLF_N_FACILITIES);
184     return module->levels[facility];
185 }
186
187 static void
188 update_min_level(struct vlog_module *module)
189 {
190     enum vlog_facility facility;
191
192     module->min_level = VLL_OFF;
193     for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
194         if (log_fd >= 0 || facility != VLF_FILE) {
195             enum vlog_level level = module->levels[facility];
196             if (level > module->min_level) {
197                 module->min_level = level;
198             }
199         }
200     }
201 }
202
203 static void
204 set_facility_level(enum vlog_facility facility, struct vlog_module *module,
205                    enum vlog_level level)
206 {
207     assert(facility >= 0 && facility < VLF_N_FACILITIES);
208     assert(level < VLL_N_LEVELS);
209
210     if (!module) {
211         struct vlog_module **mp;
212
213         for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
214             (*mp)->levels[facility] = level;
215             update_min_level(*mp);
216         }
217     } else {
218         module->levels[facility] = level;
219         update_min_level(module);
220     }
221 }
222
223 /* Sets the logging level for the given 'module' and 'facility' to 'level'.  A
224  * null 'module' or a 'facility' of VLF_ANY_FACILITY is treated as a wildcard
225  * across all modules or facilities, respectively. */
226 void
227 vlog_set_levels(struct vlog_module *module, enum vlog_facility facility,
228                 enum vlog_level level)
229 {
230     assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
231     if (facility == VLF_ANY_FACILITY) {
232         for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
233             set_facility_level(facility, module, level);
234         }
235     } else {
236         set_facility_level(facility, module, level);
237     }
238 }
239
240 static void
241 do_set_pattern(enum vlog_facility facility, const char *pattern)
242 {
243     struct facility *f = &facilities[facility];
244     if (!f->default_pattern) {
245         free(f->pattern);
246     } else {
247         f->default_pattern = false;
248     }
249     f->pattern = xstrdup(pattern);
250 }
251
252 /* Sets the pattern for the given 'facility' to 'pattern'. */
253 void
254 vlog_set_pattern(enum vlog_facility facility, const char *pattern)
255 {
256     assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
257     if (facility == VLF_ANY_FACILITY) {
258         for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
259             do_set_pattern(facility, pattern);
260         }
261     } else {
262         do_set_pattern(facility, pattern);
263     }
264 }
265
266 /* Returns the name of the log file used by VLF_FILE, or a null pointer if no
267  * log file has been set.  (A non-null return value does not assert that the
268  * named log file is in use: if vlog_set_log_file() or vlog_reopen_log_file()
269  * fails, it still sets the log file name.) */
270 const char *
271 vlog_get_log_file(void)
272 {
273     return log_file_name;
274 }
275
276 /* Sets the name of the log file used by VLF_FILE to 'file_name', or to the
277  * default file name if 'file_name' is null.  Returns 0 if successful,
278  * otherwise a positive errno value. */
279 int
280 vlog_set_log_file(const char *file_name)
281 {
282     char *old_log_file_name;
283     struct vlog_module **mp;
284     int error;
285
286     /* Close old log file. */
287     if (log_fd >= 0) {
288         VLOG_INFO("closing log file");
289         close(log_fd);
290         log_fd = -1;
291     }
292
293     /* Update log file name and free old name.  The ordering is important
294      * because 'file_name' might be 'log_file_name' or some suffix of it. */
295     old_log_file_name = log_file_name;
296     log_file_name = (file_name
297                      ? xstrdup(file_name)
298                      : xasprintf("%s/%s.log", ovs_logdir(), program_name));
299     free(old_log_file_name);
300     file_name = NULL;           /* Might have been freed. */
301
302     /* Open new log file and update min_levels[] to reflect whether we actually
303      * have a log_file. */
304     log_fd = open(log_file_name, O_WRONLY | O_CREAT | O_APPEND, 0666);
305     if (log_fd >= 0) {
306         vlog_update_async_log_fd();
307     }
308     for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
309         update_min_level(*mp);
310     }
311
312     /* Log success or failure. */
313     if (log_fd < 0) {
314         VLOG_WARN("failed to open %s for logging: %s",
315                   log_file_name, strerror(errno));
316         error = errno;
317     } else {
318         VLOG_INFO("opened log file %s", log_file_name);
319         error = 0;
320     }
321
322     return error;
323 }
324
325 /* Closes and then attempts to re-open the current log file.  (This is useful
326  * just after log rotation, to ensure that the new log file starts being used.)
327  * Returns 0 if successful, otherwise a positive errno value. */
328 int
329 vlog_reopen_log_file(void)
330 {
331     struct stat old, new;
332
333     /* Skip re-opening if there's nothing to reopen. */
334     if (!log_file_name) {
335         return 0;
336     }
337
338     /* Skip re-opening if it would be a no-op because the old and new files are
339      * the same.  (This avoids writing "closing log file" followed immediately
340      * by "opened log file".) */
341     if (log_fd >= 0
342         && !fstat(log_fd, &old)
343         && !stat(log_file_name, &new)
344         && old.st_dev == new.st_dev
345         && old.st_ino == new.st_ino) {
346         return 0;
347     }
348
349     return vlog_set_log_file(log_file_name);
350 }
351
352 /* Set debugging levels.  Returns null if successful, otherwise an error
353  * message that the caller must free(). */
354 char *
355 vlog_set_levels_from_string(const char *s_)
356 {
357     char *s = xstrdup(s_);
358     char *save_ptr = NULL;
359     char *msg = NULL;
360     char *word;
361
362     word = strtok_r(s, " ,:\t", &save_ptr);
363     if (word && !strcasecmp(word, "PATTERN")) {
364         enum vlog_facility facility;
365
366         word = strtok_r(NULL, " ,:\t", &save_ptr);
367         if (!word) {
368             msg = xstrdup("missing facility");
369             goto exit;
370         }
371
372         facility = (!strcasecmp(word, "ANY")
373                     ? VLF_ANY_FACILITY
374                     : vlog_get_facility_val(word));
375         if (facility == VLF_N_FACILITIES) {
376             msg = xasprintf("unknown facility \"%s\"", word);
377             goto exit;
378         }
379         vlog_set_pattern(facility, save_ptr);
380     } else {
381         struct vlog_module *module = NULL;
382         enum vlog_level level = VLL_N_LEVELS;
383         enum vlog_facility facility = VLF_N_FACILITIES;
384
385         for (; word != NULL; word = strtok_r(NULL, " ,:\t", &save_ptr)) {
386             if (!strcasecmp(word, "ANY")) {
387                 continue;
388             } else if (vlog_get_facility_val(word) != VLF_N_FACILITIES) {
389                 if (facility != VLF_N_FACILITIES) {
390                     msg = xstrdup("cannot specify multiple facilities");
391                     goto exit;
392                 }
393                 facility = vlog_get_facility_val(word);
394             } else if (vlog_get_level_val(word) != VLL_N_LEVELS) {
395                 if (level != VLL_N_LEVELS) {
396                     msg = xstrdup("cannot specify multiple levels");
397                     goto exit;
398                 }
399                 level = vlog_get_level_val(word);
400             } else if (vlog_module_from_name(word)) {
401                 if (module) {
402                     msg = xstrdup("cannot specify multiple modules");
403                     goto exit;
404                 }
405                 module = vlog_module_from_name(word);
406             } else {
407                 msg = xasprintf("no facility, level, or module \"%s\"", word);
408                 goto exit;
409             }
410         }
411
412         if (facility == VLF_N_FACILITIES) {
413             facility = VLF_ANY_FACILITY;
414         }
415         if (level == VLL_N_LEVELS) {
416             level = VLL_DBG;
417         }
418         vlog_set_levels(module, facility, level);
419     }
420
421 exit:
422     free(s);
423     return msg;
424 }
425
426 /* If 'arg' is null, configure maximum verbosity.  Otherwise, sets
427  * configuration according to 'arg' (see vlog_set_levels_from_string()). */
428 void
429 vlog_set_verbosity(const char *arg)
430 {
431     if (arg) {
432         char *msg = vlog_set_levels_from_string(arg);
433         if (msg) {
434             ovs_fatal(0, "processing \"%s\": %s", arg, msg);
435         }
436     } else {
437         vlog_set_levels(NULL, VLF_ANY_FACILITY, VLL_DBG);
438     }
439 }
440
441 static void
442 vlog_unixctl_set(struct unixctl_conn *conn, int argc, const char *argv[],
443                  void *aux OVS_UNUSED)
444 {
445     int i;
446
447     for (i = 1; i < argc; i++) {
448         char *msg = vlog_set_levels_from_string(argv[i]);
449         if (msg) {
450             unixctl_command_reply_error(conn, msg);
451             free(msg);
452             return;
453         }
454     }
455     unixctl_command_reply(conn, NULL);
456 }
457
458 static void
459 vlog_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
460                   const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
461 {
462     char *msg = vlog_get_levels();
463     unixctl_command_reply(conn, msg);
464     free(msg);
465 }
466
467 static void
468 vlog_unixctl_reopen(struct unixctl_conn *conn, int argc OVS_UNUSED,
469                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
470 {
471     if (log_file_name) {
472         int error = vlog_reopen_log_file();
473         if (error) {
474             unixctl_command_reply_error(conn, strerror(errno));
475         } else {
476             unixctl_command_reply(conn, NULL);
477         }
478     } else {
479         unixctl_command_reply_error(conn, "Logging to file not configured");
480     }
481 }
482
483 static void
484 set_all_rate_limits(bool enable)
485 {
486     struct vlog_module **mp;
487
488     for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
489         (*mp)->honor_rate_limits = enable;
490     }
491 }
492
493 static void
494 set_rate_limits(struct unixctl_conn *conn, int argc,
495                 const char *argv[], bool enable)
496 {
497     if (argc > 1) {
498         int i;
499
500         for (i = 1; i < argc; i++) {
501             if (!strcasecmp(argv[i], "ANY")) {
502                 set_all_rate_limits(enable);
503             } else {
504                 struct vlog_module *module = vlog_module_from_name(argv[i]);
505                 if (!module) {
506                     unixctl_command_reply_error(conn, "unknown module");
507                     return;
508                 }
509                 module->honor_rate_limits = enable;
510             }
511         }
512     } else {
513         set_all_rate_limits(enable);
514     }
515     unixctl_command_reply(conn, NULL);
516 }
517
518 static void
519 vlog_enable_rate_limit(struct unixctl_conn *conn, int argc,
520                        const char *argv[], void *aux OVS_UNUSED)
521 {
522     set_rate_limits(conn, argc, argv, true);
523 }
524
525 static void
526 vlog_disable_rate_limit(struct unixctl_conn *conn, int argc,
527                        const char *argv[], void *aux OVS_UNUSED)
528 {
529     set_rate_limits(conn, argc, argv, false);
530 }
531
532 /* Initializes the logging subsystem and registers its unixctl server
533  * commands. */
534 void
535 vlog_init(void)
536 {
537     static char *program_name_copy;
538     time_t now;
539
540     if (vlog_inited) {
541         return;
542     }
543     vlog_inited = true;
544
545     /* openlog() is allowed to keep the pointer passed in, without making a
546      * copy.  The daemonize code sometimes frees and replaces 'program_name',
547      * so make a private copy just for openlog().  (We keep a pointer to the
548      * private copy to suppress memory leak warnings in case openlog() does
549      * make its own copy.) */
550     program_name_copy = program_name ? xstrdup(program_name) : NULL;
551     openlog(program_name_copy, LOG_NDELAY, LOG_DAEMON);
552
553     now = time_wall();
554     if (now < 0) {
555         struct tm tm;
556         char s[128];
557
558         gmtime_r(&now, &tm);
559         strftime(s, sizeof s, "%a, %d %b %Y %H:%M:%S", &tm);
560         VLOG_ERR("current time is negative: %s (%ld)", s, (long int) now);
561     }
562
563     unixctl_command_register(
564         "vlog/set", "{spec | PATTERN:facility:pattern}",
565         1, INT_MAX, vlog_unixctl_set, NULL);
566     unixctl_command_register("vlog/list", "", 0, 0, vlog_unixctl_list, NULL);
567     unixctl_command_register("vlog/enable-rate-limit", "[module]...",
568                              0, INT_MAX, vlog_enable_rate_limit, NULL);
569     unixctl_command_register("vlog/disable-rate-limit", "[module]...",
570                              0, INT_MAX, vlog_disable_rate_limit, NULL);
571     unixctl_command_register("vlog/reopen", "", 0, 0,
572                              vlog_unixctl_reopen, NULL);
573 }
574
575 /* Closes the logging subsystem. */
576 void
577 vlog_exit(void)
578 {
579     if (vlog_inited) {
580         closelog();
581         vlog_inited = false;
582     }
583 }
584
585 /* Print the current logging level for each module. */
586 char *
587 vlog_get_levels(void)
588 {
589     struct ds s = DS_EMPTY_INITIALIZER;
590     struct vlog_module **mp;
591     struct svec lines = SVEC_EMPTY_INITIALIZER;
592     char *line;
593     size_t i;
594
595     ds_put_format(&s, "                 console    syslog    file\n");
596     ds_put_format(&s, "                 -------    ------    ------\n");
597
598     for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
599         struct ds line;
600
601         ds_init(&line);
602         ds_put_format(&line, "%-16s  %4s       %4s       %4s",
603                       vlog_get_module_name(*mp),
604                       vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
605                       vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
606                       vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
607         if (!(*mp)->honor_rate_limits) {
608             ds_put_cstr(&line, "    (rate limiting disabled)");
609         }
610         ds_put_char(&line, '\n');
611
612         svec_add_nocopy(&lines, ds_steal_cstr(&line));
613     }
614
615     svec_sort(&lines);
616     SVEC_FOR_EACH (i, line, &lines) {
617         ds_put_cstr(&s, line);
618     }
619     svec_destroy(&lines);
620
621     return ds_cstr(&s);
622 }
623
624 /* Returns true if a log message emitted for the given 'module' and 'level'
625  * would cause some log output, false if that module and level are completely
626  * disabled. */
627 bool
628 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
629 {
630     return module->min_level >= level;
631 }
632
633 static const char *
634 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
635 {
636     if (*p == '{') {
637         size_t n = strcspn(p + 1, "}");
638         size_t n_copy = MIN(n, out_size - 1);
639         memcpy(out, p + 1, n_copy);
640         out[n_copy] = '\0';
641         p += n + 2;
642     } else {
643         ovs_strlcpy(out, def, out_size);
644     }
645     return p;
646 }
647
648 static void
649 format_log_message(const struct vlog_module *module, enum vlog_level level,
650                    enum vlog_facility facility, unsigned int msg_num,
651                    const char *message, va_list args_, struct ds *s)
652 {
653     char tmp[128];
654     va_list args;
655     const char *p;
656
657     ds_clear(s);
658     for (p = facilities[facility].pattern; *p != '\0'; ) {
659         enum { LEFT, RIGHT } justify = RIGHT;
660         int pad = '0';
661         size_t length, field, used;
662
663         if (*p != '%') {
664             ds_put_char(s, *p++);
665             continue;
666         }
667
668         p++;
669         if (*p == '-') {
670             justify = LEFT;
671             p++;
672         }
673         if (*p == '0') {
674             pad = '0';
675             p++;
676         }
677         field = 0;
678         while (isdigit((unsigned char)*p)) {
679             field = (field * 10) + (*p - '0');
680             p++;
681         }
682
683         length = s->length;
684         switch (*p++) {
685         case 'A':
686             ds_put_cstr(s, program_name);
687             break;
688         case 'c':
689             p = fetch_braces(p, "", tmp, sizeof tmp);
690             ds_put_cstr(s, vlog_get_module_name(module));
691             break;
692         case 'd':
693             p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
694             ds_put_strftime(s, tmp, false);
695             break;
696         case 'D':
697             p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
698             ds_put_strftime(s, tmp, true);
699             break;
700         case 'm':
701             /* Format user-supplied log message and trim trailing new-lines. */
702             length = s->length;
703             va_copy(args, args_);
704             ds_put_format_valist(s, message, args);
705             va_end(args);
706             while (s->length > length && s->string[s->length - 1] == '\n') {
707                 s->length--;
708             }
709             break;
710         case 'N':
711             ds_put_format(s, "%u", msg_num);
712             break;
713         case 'n':
714             ds_put_char(s, '\n');
715             break;
716         case 'p':
717             ds_put_cstr(s, vlog_get_level_name(level));
718             break;
719         case 'P':
720             ds_put_format(s, "%ld", (long int) getpid());
721             break;
722         case 'r':
723             ds_put_format(s, "%lld", time_msec() - time_boot_msec());
724             break;
725         case 't':
726             ds_put_cstr(s, subprogram_name[0] ? subprogram_name : "main");
727             break;
728         case 'T':
729             if (subprogram_name[0]) {
730                 ds_put_format(s, "(%s)", subprogram_name);
731             }
732             break;
733         default:
734             ds_put_char(s, p[-1]);
735             break;
736         }
737         used = s->length - length;
738         if (used < field) {
739             size_t n_pad = field - used;
740             if (justify == RIGHT) {
741                 ds_put_uninit(s, n_pad);
742                 memmove(&s->string[length + n_pad], &s->string[length], used);
743                 memset(&s->string[length], pad, n_pad);
744             } else {
745                 ds_put_char_multiple(s, pad, n_pad);
746             }
747         }
748     }
749 }
750
751 /* Writes 'message' to the log at the given 'level' and as coming from the
752  * given 'module'.
753  *
754  * Guaranteed to preserve errno. */
755 void
756 vlog_valist(const struct vlog_module *module, enum vlog_level level,
757             const char *message, va_list args)
758 {
759     bool log_to_console = module->levels[VLF_CONSOLE] >= level;
760     bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
761     bool log_to_file = module->levels[VLF_FILE] >= level && log_fd >= 0;
762     if (log_to_console || log_to_syslog || log_to_file) {
763         int save_errno = errno;
764         static unsigned int msg_num;
765         struct ds s;
766
767         vlog_init();
768
769         ds_init(&s);
770         ds_reserve(&s, 1024);
771         msg_num++;
772
773         if (log_to_console) {
774             format_log_message(module, level, VLF_CONSOLE, msg_num,
775                                message, args, &s);
776             ds_put_char(&s, '\n');
777             fputs(ds_cstr(&s), stderr);
778         }
779
780         if (log_to_syslog) {
781             int syslog_level = syslog_levels[level];
782             char *save_ptr = NULL;
783             char *line;
784
785             format_log_message(module, level, VLF_SYSLOG, msg_num,
786                                message, args, &s);
787             for (line = strtok_r(s.string, "\n", &save_ptr); line;
788                  line = strtok_r(NULL, "\n", &save_ptr)) {
789                 syslog(syslog_level, "%s", line);
790             }
791         }
792
793         if (log_to_file) {
794             format_log_message(module, level, VLF_FILE, msg_num,
795                                message, args, &s);
796             ds_put_char(&s, '\n');
797             vlog_write_file(&s);
798         }
799
800         ds_destroy(&s);
801         errno = save_errno;
802     }
803 }
804
805 void
806 vlog(const struct vlog_module *module, enum vlog_level level,
807      const char *message, ...)
808 {
809     va_list args;
810
811     va_start(args, message);
812     vlog_valist(module, level, message, args);
813     va_end(args);
814 }
815
816 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
817  * exit code.  Always writes the message to stderr, even if the console
818  * facility is disabled.
819  *
820  * Choose this function instead of vlog_abort_valist() if the daemon monitoring
821  * facility shouldn't automatically restart the current daemon.  */
822 void
823 vlog_fatal_valist(const struct vlog_module *module_,
824                   const char *message, va_list args)
825 {
826     struct vlog_module *module = CONST_CAST(struct vlog_module *, module_);
827
828     /* Don't log this message to the console to avoid redundancy with the
829      * message written by the later ovs_fatal_valist(). */
830     module->levels[VLF_CONSOLE] = VLL_OFF;
831
832     vlog_valist(module, VLL_EMER, message, args);
833     ovs_fatal_valist(0, message, args);
834 }
835
836 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
837  * exit code.  Always writes the message to stderr, even if the console
838  * facility is disabled.
839  *
840  * Choose this function instead of vlog_abort() if the daemon monitoring
841  * facility shouldn't automatically restart the current daemon.  */
842 void
843 vlog_fatal(const struct vlog_module *module, const char *message, ...)
844 {
845     va_list args;
846
847     va_start(args, message);
848     vlog_fatal_valist(module, message, args);
849     va_end(args);
850 }
851
852 /* Logs 'message' to 'module' at maximum verbosity, then calls abort().  Always
853  * writes the message to stderr, even if the console facility is disabled.
854  *
855  * Choose this function instead of vlog_fatal_valist() if the daemon monitoring
856  * facility should automatically restart the current daemon.  */
857 void
858 vlog_abort_valist(const struct vlog_module *module_,
859                   const char *message, va_list args)
860 {
861     struct vlog_module *module = (struct vlog_module *) module_;
862
863     /* Don't log this message to the console to avoid redundancy with the
864      * message written by the later ovs_abort_valist(). */
865     module->levels[VLF_CONSOLE] = VLL_OFF;
866
867     vlog_valist(module, VLL_EMER, message, args);
868     ovs_abort_valist(0, message, args);
869 }
870
871 /* Logs 'message' to 'module' at maximum verbosity, then calls abort().  Always
872  * writes the message to stderr, even if the console facility is disabled.
873  *
874  * Choose this function instead of vlog_fatal() if the daemon monitoring
875  * facility should automatically restart the current daemon.  */
876 void
877 vlog_abort(const struct vlog_module *module, const char *message, ...)
878 {
879     va_list args;
880
881     va_start(args, message);
882     vlog_abort_valist(module, message, args);
883     va_end(args);
884 }
885
886 bool
887 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
888                  struct vlog_rate_limit *rl)
889 {
890     if (!module->honor_rate_limits) {
891         return false;
892     }
893
894     if (!vlog_is_enabled(module, level)) {
895         return true;
896     }
897
898     if (!token_bucket_withdraw(&rl->token_bucket, VLOG_MSG_TOKENS)) {
899         time_t now = time_now();
900         if (!rl->n_dropped) {
901             rl->first_dropped = now;
902         }
903         rl->last_dropped = now;
904         rl->n_dropped++;
905         return true;
906     }
907
908     if (rl->n_dropped) {
909         time_t now = time_now();
910         unsigned int first_dropped_elapsed = now - rl->first_dropped;
911         unsigned int last_dropped_elapsed = now - rl->last_dropped;
912
913         vlog(module, level,
914              "Dropped %u log messages in last %u seconds (most recently, "
915              "%u seconds ago) due to excessive rate",
916              rl->n_dropped, first_dropped_elapsed, last_dropped_elapsed);
917
918         rl->n_dropped = 0;
919     }
920     return false;
921 }
922
923 void
924 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
925                 struct vlog_rate_limit *rl, const char *message, ...)
926 {
927     if (!vlog_should_drop(module, level, rl)) {
928         va_list args;
929
930         va_start(args, message);
931         vlog_valist(module, level, message, args);
932         va_end(args);
933     }
934 }
935
936 void
937 vlog_usage(void)
938 {
939     printf("\nLogging options:\n"
940            "  -v, --verbose=[SPEC]    set logging levels\n"
941            "  -v, --verbose           set maximum verbosity level\n"
942            "  --log-file[=FILE]       enable logging to specified FILE\n"
943            "                          (default: %s/%s.log)\n",
944            ovs_logdir(), program_name);
945 }
946 \f
947 static bool vlog_async_inited = false;
948
949 static worker_request_func vlog_async_write_request_cb;
950
951 static void
952 vlog_write_file(struct ds *s)
953 {
954     if (worker_is_running()) {
955         worker_request(s->string, s->length,
956                        &log_fd, vlog_async_inited ? 0 : 1,
957                        vlog_async_write_request_cb, NULL, NULL);
958         vlog_async_inited = true;
959     } else {
960         ignore(write(log_fd, s->string, s->length));
961     }
962 }
963
964 static void
965 vlog_update_async_log_fd(void)
966 {
967     if (worker_is_running()) {
968         worker_request(NULL, 0, &log_fd, 1, vlog_async_write_request_cb,
969                        NULL, NULL);
970         vlog_async_inited = true;
971     }
972 }
973
974 static void
975 vlog_async_write_request_cb(struct ofpbuf *request,
976                             const int *fd, size_t n_fds)
977 {
978     if (n_fds > 0) {
979         if (log_fd >= 0) {
980             close(log_fd);
981         }
982         log_fd = *fd;
983     }
984
985     if (request->size > 0) {
986         ignore(write(log_fd, request->data, request->size));
987     }
988 }