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