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