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