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