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