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