da31e6f0f7f9ca181d8fad4954fe33338d5ac05a
[cascardo/ovs.git] / lib / vlog.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2015 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 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);
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 /* Set debugging levels.  Returns null if successful, otherwise an error
434  * message that the caller must free(). */
435 char *
436 vlog_set_levels_from_string(const char *s_)
437 {
438     char *s = xstrdup(s_);
439     char *save_ptr = NULL;
440     char *msg = NULL;
441     char *word;
442
443     word = strtok_r(s, " ,:\t", &save_ptr);
444     if (word && !strcasecmp(word, "PATTERN")) {
445         enum vlog_destination destination;
446
447         word = strtok_r(NULL, " ,:\t", &save_ptr);
448         if (!word) {
449             msg = xstrdup("missing destination");
450             goto exit;
451         }
452
453         destination = (!strcasecmp(word, "ANY")
454                        ? VLF_ANY_DESTINATION
455                        : vlog_get_destination_val(word));
456         if (destination == VLF_N_DESTINATIONS) {
457             msg = xasprintf("unknown destination \"%s\"", word);
458             goto exit;
459         }
460         vlog_set_pattern(destination, save_ptr);
461     } else if (word && !strcasecmp(word, "FACILITY")) {
462         int value;
463
464         if (!vlog_facility_exists(save_ptr, &value)) {
465             msg = xstrdup("invalid facility");
466             goto exit;
467         }
468         atomic_store_explicit(&log_facility, value, memory_order_relaxed);
469     } else {
470         struct vlog_module *module = NULL;
471         enum vlog_level level = VLL_N_LEVELS;
472         enum vlog_destination destination = VLF_N_DESTINATIONS;
473
474         for (; word != NULL; word = strtok_r(NULL, " ,:\t", &save_ptr)) {
475             if (!strcasecmp(word, "ANY")) {
476                 continue;
477             } else if (vlog_get_destination_val(word) != VLF_N_DESTINATIONS) {
478                 if (destination != VLF_N_DESTINATIONS) {
479                     msg = xstrdup("cannot specify multiple destinations");
480                     goto exit;
481                 }
482                 destination = vlog_get_destination_val(word);
483             } else if (vlog_get_level_val(word) != VLL_N_LEVELS) {
484                 if (level != VLL_N_LEVELS) {
485                     msg = xstrdup("cannot specify multiple levels");
486                     goto exit;
487                 }
488                 level = vlog_get_level_val(word);
489             } else if (vlog_module_from_name(word)) {
490                 if (module) {
491                     msg = xstrdup("cannot specify multiple modules");
492                     goto exit;
493                 }
494                 module = vlog_module_from_name(word);
495             } else {
496                 msg = xasprintf("no destination, level, or module \"%s\"",
497                                 word);
498                 goto exit;
499             }
500         }
501
502         if (destination == VLF_N_DESTINATIONS) {
503             destination = VLF_ANY_DESTINATION;
504         }
505         if (level == VLL_N_LEVELS) {
506             level = VLL_DBG;
507         }
508         vlog_set_levels(module, destination, level);
509     }
510
511 exit:
512     free(s);
513     return msg;
514 }
515
516 /* Set debugging levels.  Abort with an error message if 's' is invalid. */
517 void
518 vlog_set_levels_from_string_assert(const char *s)
519 {
520     char *error = vlog_set_levels_from_string(s);
521     if (error) {
522         ovs_fatal(0, "%s", error);
523     }
524 }
525
526 /* If 'arg' is null, configure maximum verbosity.  Otherwise, sets
527  * configuration according to 'arg' (see vlog_set_levels_from_string()). */
528 void
529 vlog_set_verbosity(const char *arg)
530 {
531     if (arg) {
532         char *msg = vlog_set_levels_from_string(arg);
533         if (msg) {
534             ovs_fatal(0, "processing \"%s\": %s", arg, msg);
535         }
536     } else {
537         vlog_set_levels(NULL, VLF_ANY_DESTINATION, VLL_DBG);
538     }
539 }
540
541 void
542 vlog_set_syslog_method(const char *method)
543 {
544     if (syslogger) {
545         /* Set syslogger only, if one is not already set.  This effectively
546          * means that only the first --syslog-method argument is honored. */
547         return;
548     }
549
550     if (!strcmp(method, "libc")) {
551         syslogger = syslog_libc_create();
552     } else if (!strncmp(method, "udp:", 4) || !strncmp(method, "unix:", 5)) {
553         syslogger = syslog_direct_create(method);
554     } else {
555         ovs_fatal(0, "unsupported syslog method '%s'", method);
556     }
557 }
558
559 /* Set the vlog udp syslog target. */
560 void
561 vlog_set_syslog_target(const char *target)
562 {
563     int new_fd;
564
565     inet_open_active(SOCK_DGRAM, target, 0, NULL, &new_fd, 0);
566
567     ovs_rwlock_wrlock(&pattern_rwlock);
568     if (syslog_fd >= 0) {
569         close(syslog_fd);
570     }
571     syslog_fd = new_fd;
572     ovs_rwlock_unlock(&pattern_rwlock);
573 }
574
575 /* Returns 'false' if 'facility' is not a valid string. If 'facility'
576  * is a valid string, sets 'value' with the integer value of 'facility'
577  * and returns 'true'. */
578 static bool
579 vlog_facility_exists(const char* facility, int *value)
580 {
581     size_t i;
582     for (i = 0; i < ARRAY_SIZE(vlog_facilities); i++) {
583         if (!strcasecmp(vlog_facilities[i].name, facility)) {
584             *value = vlog_facilities[i].value;
585             return true;
586         }
587     }
588     return false;
589 }
590
591 static void
592 vlog_unixctl_set(struct unixctl_conn *conn, int argc, const char *argv[],
593                  void *aux OVS_UNUSED)
594 {
595     int i;
596
597     for (i = 1; i < argc; i++) {
598         char *msg = vlog_set_levels_from_string(argv[i]);
599         if (msg) {
600             unixctl_command_reply_error(conn, msg);
601             free(msg);
602             return;
603         }
604     }
605     unixctl_command_reply(conn, NULL);
606 }
607
608 static void
609 vlog_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
610                   const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
611 {
612     char *msg = vlog_get_levels();
613     unixctl_command_reply(conn, msg);
614     free(msg);
615 }
616
617 static void
618 vlog_unixctl_list_pattern(struct unixctl_conn *conn, int argc OVS_UNUSED,
619                           const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
620 {
621     char *msg;
622
623     msg = vlog_get_patterns();
624     unixctl_command_reply(conn, msg);
625     free(msg);
626 }
627
628 static void
629 vlog_unixctl_reopen(struct unixctl_conn *conn, int argc OVS_UNUSED,
630                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
631 {
632     bool has_log_file;
633
634     ovs_mutex_lock(&log_file_mutex);
635     has_log_file = log_file_name != NULL;
636     ovs_mutex_unlock(&log_file_mutex);
637
638     if (has_log_file) {
639         int error = vlog_reopen_log_file();
640         if (error) {
641             unixctl_command_reply_error(conn, ovs_strerror(errno));
642         } else {
643             unixctl_command_reply(conn, NULL);
644         }
645     } else {
646         unixctl_command_reply_error(conn, "Logging to file not configured");
647     }
648 }
649
650 static void
651 set_all_rate_limits(bool enable)
652 {
653     struct vlog_module *mp;
654
655     LIST_FOR_EACH (mp, list, &vlog_modules) {
656         mp->honor_rate_limits = enable;
657     }
658 }
659
660 static void
661 set_rate_limits(struct unixctl_conn *conn, int argc,
662                 const char *argv[], bool enable)
663 {
664     if (argc > 1) {
665         int i;
666
667         for (i = 1; i < argc; i++) {
668             if (!strcasecmp(argv[i], "ANY")) {
669                 set_all_rate_limits(enable);
670             } else {
671                 struct vlog_module *module = vlog_module_from_name(argv[i]);
672                 if (!module) {
673                     unixctl_command_reply_error(conn, "unknown module");
674                     return;
675                 }
676                 module->honor_rate_limits = enable;
677             }
678         }
679     } else {
680         set_all_rate_limits(enable);
681     }
682     unixctl_command_reply(conn, NULL);
683 }
684
685 static void
686 vlog_enable_rate_limit(struct unixctl_conn *conn, int argc,
687                        const char *argv[], void *aux OVS_UNUSED)
688 {
689     set_rate_limits(conn, argc, argv, true);
690 }
691
692 static void
693 vlog_disable_rate_limit(struct unixctl_conn *conn, int argc,
694                        const char *argv[], void *aux OVS_UNUSED)
695 {
696     set_rate_limits(conn, argc, argv, false);
697 }
698
699 /* Initializes the logging subsystem and registers its unixctl server
700  * commands. */
701 void
702 vlog_init(void)
703 {
704     static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
705
706     if (ovsthread_once_start(&once)) {
707         long long int now;
708         int facility;
709         bool print_syslog_target_deprecation;
710
711         /* Do initialization work that needs to be done before any logging
712          * occurs.  We want to keep this really minimal because any attempt to
713          * log anything before calling ovsthread_once_done() will deadlock. */
714         atomic_read_explicit(&log_facility, &facility, memory_order_relaxed);
715         if (!syslogger) {
716             syslogger = syslog_libc_create();
717         }
718         syslogger->class->openlog(syslogger, facility ? facility : LOG_DAEMON);
719         ovsthread_once_done(&once);
720
721         /* Now do anything that we want to happen only once but doesn't have to
722          * finish before we start logging. */
723
724         now = time_wall_msec();
725         if (now < 0) {
726             char *s = xastrftime_msec("%a, %d %b %Y %H:%M:%S", now, true);
727             VLOG_ERR("current time is negative: %s (%lld)", s, now);
728             free(s);
729         }
730
731         unixctl_command_register(
732             "vlog/set", "{spec | PATTERN:destination:pattern}",
733             1, INT_MAX, vlog_unixctl_set, NULL);
734         unixctl_command_register("vlog/list", "", 0, 0, vlog_unixctl_list,
735                                  NULL);
736         unixctl_command_register("vlog/list-pattern", "", 0, 0,
737                                  vlog_unixctl_list_pattern, NULL);
738         unixctl_command_register("vlog/enable-rate-limit", "[module]...",
739                                  0, INT_MAX, vlog_enable_rate_limit, NULL);
740         unixctl_command_register("vlog/disable-rate-limit", "[module]...",
741                                  0, INT_MAX, vlog_disable_rate_limit, NULL);
742         unixctl_command_register("vlog/reopen", "", 0, 0,
743                                  vlog_unixctl_reopen, NULL);
744
745         ovs_rwlock_rdlock(&pattern_rwlock);
746         print_syslog_target_deprecation = syslog_fd >= 0;
747         ovs_rwlock_unlock(&pattern_rwlock);
748
749         if (print_syslog_target_deprecation) {
750             VLOG_WARN("--syslog-target flag is deprecated, use "
751                       "--syslog-method instead");
752         }
753     }
754 }
755
756 /* Enables VLF_FILE log output to be written asynchronously to disk.
757  * Asynchronous file writes avoid blocking the process in the case of a busy
758  * disk, but on the other hand they are less robust: there is a chance that the
759  * write will not make it to the log file if the process crashes soon after the
760  * log call. */
761 void
762 vlog_enable_async(void)
763 {
764     ovs_mutex_lock(&log_file_mutex);
765     log_async = true;
766     if (log_fd >= 0 && !log_writer) {
767         log_writer = async_append_create(log_fd);
768     }
769     ovs_mutex_unlock(&log_file_mutex);
770 }
771
772 /* Print the current logging level for each module. */
773 char *
774 vlog_get_levels(void)
775 {
776     struct ds s = DS_EMPTY_INITIALIZER;
777     struct vlog_module *mp;
778     struct svec lines = SVEC_EMPTY_INITIALIZER;
779     char *line;
780     size_t i;
781
782     ds_put_format(&s, "                 console    syslog    file\n");
783     ds_put_format(&s, "                 -------    ------    ------\n");
784
785     LIST_FOR_EACH (mp, list, &vlog_modules) {
786         struct ds line;
787
788         ds_init(&line);
789         ds_put_format(&line, "%-16s  %4s       %4s       %4s",
790                       vlog_get_module_name(mp),
791                       vlog_get_level_name(vlog_get_level(mp, VLF_CONSOLE)),
792                       vlog_get_level_name(vlog_get_level(mp, VLF_SYSLOG)),
793                       vlog_get_level_name(vlog_get_level(mp, VLF_FILE)));
794         if (!mp->honor_rate_limits) {
795             ds_put_cstr(&line, "    (rate limiting disabled)");
796         }
797         ds_put_char(&line, '\n');
798
799         svec_add_nocopy(&lines, ds_steal_cstr(&line));
800     }
801
802     svec_sort(&lines);
803     SVEC_FOR_EACH (i, line, &lines) {
804         ds_put_cstr(&s, line);
805     }
806     svec_destroy(&lines);
807
808     return ds_cstr(&s);
809 }
810
811 /* Returns as a string current logging patterns for each destination.
812  * This string must be released by caller. */
813 char *
814 vlog_get_patterns(void)
815 {
816     struct ds ds = DS_EMPTY_INITIALIZER;
817     enum vlog_destination destination;
818
819     ovs_rwlock_rdlock(&pattern_rwlock);
820     ds_put_format(&ds, "         prefix                            format\n");
821     ds_put_format(&ds, "         ------                            ------\n");
822
823     for (destination = 0; destination < VLF_N_DESTINATIONS; destination++) {
824         struct destination *f = &destinations[destination];
825         const char *prefix = "none";
826
827         if (destination == VLF_SYSLOG && syslogger) {
828             prefix = syslog_get_prefix(syslogger);
829         }
830         ds_put_format(&ds, "%-7s  %-32s  %s\n", f->name, prefix, f->pattern);
831     }
832     ovs_rwlock_unlock(&pattern_rwlock);
833
834     return ds_cstr(&ds);
835 }
836
837 /* Returns true if a log message emitted for the given 'module' and 'level'
838  * would cause some log output, false if that module and level are completely
839  * disabled. */
840 bool
841 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
842 {
843     return module->min_level >= level;
844 }
845
846 static const char *
847 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
848 {
849     if (*p == '{') {
850         size_t n = strcspn(p + 1, "}");
851         size_t n_copy = MIN(n, out_size - 1);
852         memcpy(out, p + 1, n_copy);
853         out[n_copy] = '\0';
854         p += n + 2;
855     } else {
856         ovs_strlcpy(out, def, out_size);
857     }
858     return p;
859 }
860
861 static void
862 format_log_message(const struct vlog_module *module, enum vlog_level level,
863                    const char *pattern, const char *message,
864                    va_list args_, struct ds *s)
865 {
866     char tmp[128];
867     va_list args;
868     const char *p;
869     int facility;
870
871     ds_clear(s);
872     for (p = pattern; *p != '\0'; ) {
873         const char *subprogram_name;
874         enum { LEFT, RIGHT } justify = RIGHT;
875         int pad = '0';
876         size_t length, field, used;
877
878         if (*p != '%') {
879             ds_put_char(s, *p++);
880             continue;
881         }
882
883         p++;
884         if (*p == '-') {
885             justify = LEFT;
886             p++;
887         }
888         if (*p == '0') {
889             pad = '0';
890             p++;
891         }
892         field = 0;
893         while (isdigit((unsigned char)*p)) {
894             field = (field * 10) + (*p - '0');
895             p++;
896         }
897
898         length = s->length;
899         switch (*p++) {
900         case 'A':
901             ds_put_cstr(s, program_name);
902             break;
903         case 'B':
904             atomic_read_explicit(&log_facility, &facility,
905                                  memory_order_relaxed);
906             facility = facility ? facility : LOG_LOCAL0;
907             ds_put_format(s, "%d", facility + syslog_levels[level]);
908             break;
909         case 'c':
910             p = fetch_braces(p, "", tmp, sizeof tmp);
911             ds_put_cstr(s, vlog_get_module_name(module));
912             break;
913         case 'd':
914             p = fetch_braces(p, "%Y-%m-%d %H:%M:%S.###", tmp, sizeof tmp);
915             ds_put_strftime_msec(s, tmp, time_wall_msec(), false);
916             break;
917         case 'D':
918             p = fetch_braces(p, "%Y-%m-%d %H:%M:%S.###", tmp, sizeof tmp);
919             ds_put_strftime_msec(s, tmp, time_wall_msec(), true);
920             break;
921         case 'E':
922             gethostname(tmp, sizeof tmp);
923             tmp[sizeof tmp - 1] = '\0';
924             ds_put_cstr(s, tmp);
925             break;
926         case 'm':
927             /* Format user-supplied log message and trim trailing new-lines. */
928             length = s->length;
929             va_copy(args, args_);
930             ds_put_format_valist(s, message, args);
931             va_end(args);
932             while (s->length > length && s->string[s->length - 1] == '\n') {
933                 s->length--;
934             }
935             break;
936         case 'N':
937             ds_put_format(s, "%u", *msg_num_get_unsafe());
938             break;
939         case 'n':
940             ds_put_char(s, '\n');
941             break;
942         case 'p':
943             ds_put_cstr(s, vlog_get_level_name(level));
944             break;
945         case 'P':
946             ds_put_format(s, "%ld", (long int) getpid());
947             break;
948         case 'r':
949             ds_put_format(s, "%lld", time_msec() - time_boot_msec());
950             break;
951         case 't':
952             subprogram_name = get_subprogram_name();
953             ds_put_cstr(s, subprogram_name[0] ? subprogram_name : "main");
954             break;
955         case 'T':
956             subprogram_name = get_subprogram_name();
957             if (subprogram_name[0]) {
958                 ds_put_format(s, "(%s)", subprogram_name);
959             }
960             break;
961         default:
962             ds_put_char(s, p[-1]);
963             break;
964         }
965         used = s->length - length;
966         if (used < field) {
967             size_t n_pad = field - used;
968             if (justify == RIGHT) {
969                 ds_put_uninit(s, n_pad);
970                 memmove(&s->string[length + n_pad], &s->string[length], used);
971                 memset(&s->string[length], pad, n_pad);
972             } else {
973                 ds_put_char_multiple(s, pad, n_pad);
974             }
975         }
976     }
977 }
978
979 /* Exports the given 'syslog_message' to the configured udp syslog sink. */
980 static void
981 send_to_syslog_fd(const char *s, size_t length)
982     OVS_REQ_RDLOCK(pattern_rwlock)
983 {
984     static size_t max_length = SIZE_MAX;
985     size_t send_len = MIN(length, max_length);
986
987     while (write(syslog_fd, s, send_len) < 0 && errno == EMSGSIZE) {
988         send_len -= send_len / 20;
989         max_length = send_len;
990     }
991 }
992
993 /* Writes 'message' to the log at the given 'level' and as coming from the
994  * given 'module'.
995  *
996  * Guaranteed to preserve errno. */
997 void
998 vlog_valist(const struct vlog_module *module, enum vlog_level level,
999             const char *message, va_list args)
1000 {
1001     bool log_to_console = module->levels[VLF_CONSOLE] >= level;
1002     bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
1003     bool log_to_file;
1004
1005     ovs_mutex_lock(&log_file_mutex);
1006     log_to_file = module->levels[VLF_FILE] >= level && log_fd >= 0;
1007     ovs_mutex_unlock(&log_file_mutex);
1008     if (log_to_console || log_to_syslog || log_to_file) {
1009         int save_errno = errno;
1010         struct ds s;
1011
1012         vlog_init();
1013
1014         ds_init(&s);
1015         ds_reserve(&s, 1024);
1016         ++*msg_num_get();
1017
1018         ovs_rwlock_rdlock(&pattern_rwlock);
1019         if (log_to_console) {
1020             format_log_message(module, level,
1021                                destinations[VLF_CONSOLE].pattern, message,
1022                                args, &s);
1023             ds_put_char(&s, '\n');
1024             fputs(ds_cstr(&s), stderr);
1025         }
1026
1027         if (log_to_syslog) {
1028             int syslog_level = syslog_levels[level];
1029             char *save_ptr = NULL;
1030             char *line;
1031             int facility;
1032
1033             format_log_message(module, level, destinations[VLF_SYSLOG].pattern,
1034                                message, args, &s);
1035             for (line = strtok_r(s.string, "\n", &save_ptr); line;
1036                  line = strtok_r(NULL, "\n", &save_ptr)) {
1037                 atomic_read_explicit(&log_facility, &facility,
1038                                      memory_order_relaxed);
1039                 syslogger->class->syslog(syslogger, syslog_level|facility, line);
1040             }
1041
1042             if (syslog_fd >= 0) {
1043                 format_log_message(module, level,
1044                                    "<%B>1 %D{%Y-%m-%dT%H:%M:%S.###Z} "
1045                                    "%E %A %P %c - \xef\xbb\xbf%m",
1046                                    message, args, &s);
1047                 send_to_syslog_fd(ds_cstr(&s), s.length);
1048             }
1049         }
1050
1051         if (log_to_file) {
1052             format_log_message(module, level, destinations[VLF_FILE].pattern,
1053                                message, args, &s);
1054             ds_put_char(&s, '\n');
1055
1056             ovs_mutex_lock(&log_file_mutex);
1057             if (log_fd >= 0) {
1058                 if (log_writer) {
1059                     async_append_write(log_writer, s.string, s.length);
1060                     if (level == VLL_EMER) {
1061                         async_append_flush(log_writer);
1062                     }
1063                 } else {
1064                     ignore(write(log_fd, s.string, s.length));
1065                 }
1066             }
1067             ovs_mutex_unlock(&log_file_mutex);
1068         }
1069         ovs_rwlock_unlock(&pattern_rwlock);
1070
1071         ds_destroy(&s);
1072         errno = save_errno;
1073     }
1074 }
1075
1076 void
1077 vlog(const struct vlog_module *module, enum vlog_level level,
1078      const char *message, ...)
1079 {
1080     va_list args;
1081
1082     va_start(args, message);
1083     vlog_valist(module, level, message, args);
1084     va_end(args);
1085 }
1086
1087 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
1088  * exit code.  Always writes the message to stderr, even if the console
1089  * destination is disabled.
1090  *
1091  * Choose this function instead of vlog_abort_valist() if the daemon monitoring
1092  * facility shouldn't automatically restart the current daemon.  */
1093 void
1094 vlog_fatal_valist(const struct vlog_module *module_,
1095                   const char *message, va_list args)
1096 {
1097     struct vlog_module *module = CONST_CAST(struct vlog_module *, module_);
1098
1099     /* Don't log this message to the console to avoid redundancy with the
1100      * message written by the later ovs_fatal_valist(). */
1101     module->levels[VLF_CONSOLE] = VLL_OFF;
1102
1103     vlog_valist(module, VLL_EMER, message, args);
1104     ovs_fatal_valist(0, message, args);
1105 }
1106
1107 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
1108  * exit code.  Always writes the message to stderr, even if the console
1109  * destination is disabled.
1110  *
1111  * Choose this function instead of vlog_abort() if the daemon monitoring
1112  * facility shouldn't automatically restart the current daemon.  */
1113 void
1114 vlog_fatal(const struct vlog_module *module, const char *message, ...)
1115 {
1116     va_list args;
1117
1118     va_start(args, message);
1119     vlog_fatal_valist(module, message, args);
1120     va_end(args);
1121 }
1122
1123 /* Logs 'message' to 'module' at maximum verbosity, then calls abort().  Always
1124  * writes the message to stderr, even if the console destination is disabled.
1125  *
1126  * Choose this function instead of vlog_fatal_valist() if the daemon monitoring
1127  * facility should automatically restart the current daemon.  */
1128 void
1129 vlog_abort_valist(const struct vlog_module *module_,
1130                   const char *message, va_list args)
1131 {
1132     struct vlog_module *module = (struct vlog_module *) module_;
1133
1134     /* Don't log this message to the console to avoid redundancy with the
1135      * message written by the later ovs_abort_valist(). */
1136     module->levels[VLF_CONSOLE] = VLL_OFF;
1137
1138     vlog_valist(module, VLL_EMER, message, args);
1139     ovs_abort_valist(0, message, args);
1140 }
1141
1142 /* Logs 'message' to 'module' at maximum verbosity, then calls abort().  Always
1143  * writes the message to stderr, even if the console destination is disabled.
1144  *
1145  * Choose this function instead of vlog_fatal() if the daemon monitoring
1146  * facility should automatically restart the current daemon.  */
1147 void
1148 vlog_abort(const struct vlog_module *module, const char *message, ...)
1149 {
1150     va_list args;
1151
1152     va_start(args, message);
1153     vlog_abort_valist(module, message, args);
1154     va_end(args);
1155 }
1156
1157 bool
1158 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
1159                  struct vlog_rate_limit *rl)
1160 {
1161     if (!module->honor_rate_limits) {
1162         return false;
1163     }
1164
1165     if (!vlog_is_enabled(module, level)) {
1166         return true;
1167     }
1168
1169     ovs_mutex_lock(&rl->mutex);
1170     if (!token_bucket_withdraw(&rl->token_bucket, VLOG_MSG_TOKENS)) {
1171         time_t now = time_now();
1172         if (!rl->n_dropped) {
1173             rl->first_dropped = now;
1174         }
1175         rl->last_dropped = now;
1176         rl->n_dropped++;
1177         ovs_mutex_unlock(&rl->mutex);
1178         return true;
1179     }
1180
1181     if (!rl->n_dropped) {
1182         ovs_mutex_unlock(&rl->mutex);
1183     } else {
1184         time_t now = time_now();
1185         unsigned int n_dropped = rl->n_dropped;
1186         unsigned int first_dropped_elapsed = now - rl->first_dropped;
1187         unsigned int last_dropped_elapsed = now - rl->last_dropped;
1188         rl->n_dropped = 0;
1189         ovs_mutex_unlock(&rl->mutex);
1190
1191         vlog(module, level,
1192              "Dropped %u log messages in last %u seconds (most recently, "
1193              "%u seconds ago) due to excessive rate",
1194              n_dropped, first_dropped_elapsed, last_dropped_elapsed);
1195     }
1196
1197     return false;
1198 }
1199
1200 void
1201 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
1202                 struct vlog_rate_limit *rl, const char *message, ...)
1203 {
1204     if (!vlog_should_drop(module, level, rl)) {
1205         va_list args;
1206
1207         va_start(args, message);
1208         vlog_valist(module, level, message, args);
1209         va_end(args);
1210     }
1211 }
1212
1213 void
1214 vlog_usage(void)
1215 {
1216     printf("\n\
1217 Logging options:\n\
1218   -vSPEC, --verbose=SPEC   set logging levels\n\
1219   -v, --verbose            set maximum verbosity level\n\
1220   --log-file[=FILE]        enable logging to specified FILE\n\
1221                            (default: %s/%s.log)\n\
1222   --syslog-method=(libc|unix:file|udp:ip:port)\n\
1223                            specify how to send messages to syslog daemon\n\
1224   --syslog-target=HOST:PORT  also send syslog msgs to HOST:PORT via UDP\n",
1225            ovs_logdir(), program_name);
1226 }