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