]> git.proxmox.com Git - ovs.git/blame - lib/vlog.c
tnl-arp-cache: Remove spurious OVS_UNUSED from tnl_arp_cache_flush().
[ovs.git] / lib / vlog.c
CommitLineData
064af421 1/*
4958e3ee 2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
064af421 3 *
a14bc59f
BP
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:
064af421 7 *
a14bc59f
BP
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.
064af421
BP
15 */
16
17#include <config.h>
e6211adc 18#include "openvswitch/vlog.h"
064af421
BP
19#include <assert.h>
20#include <ctype.h>
21#include <errno.h>
9eb94563 22#include <fcntl.h>
064af421
BP
23#include <stdarg.h>
24#include <stdlib.h>
25#include <string.h>
68cb8aaf 26#include <sys/stat.h>
064af421
BP
27#include <sys/types.h>
28#include <syslog.h>
29#include <time.h>
30#include <unistd.h>
a5fb0e29 31#include "async-append.h"
4958e3ee 32#include "coverage.h"
064af421
BP
33#include "dirs.h"
34#include "dynamic-string.h"
cbb13e8e 35#include "ofpbuf.h"
81d6495f 36#include "ovs-thread.h"
064af421 37#include "sat-math.h"
afc9f547 38#include "socket-util.h"
8628b0b7 39#include "svec.h"
fe089c0d
AA
40#include "syslog-direct.h"
41#include "syslog-libc.h"
42#include "syslog-provider.h"
064af421
BP
43#include "timeval.h"
44#include "unixctl.h"
45#include "util.h"
46
d98e6007 47VLOG_DEFINE_THIS_MODULE(vlog);
064af421 48
4958e3ee
BP
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
064af421 54/* Name for each logging level. */
4b5f1d2c 55static const char *const level_names[VLL_N_LEVELS] = {
afc9f547 56#define VLOG_LEVEL(NAME, SYSLOG_LEVEL, RFC5424) #NAME,
064af421
BP
57 VLOG_LEVELS
58#undef VLOG_LEVEL
59};
60
61/* Syslog value for each logging level. */
4b5f1d2c 62static const int syslog_levels[VLL_N_LEVELS] = {
afc9f547 63#define VLOG_LEVEL(NAME, SYSLOG_LEVEL, RFC5424) SYSLOG_LEVEL,
064af421
BP
64 VLOG_LEVELS
65#undef VLOG_LEVEL
66};
67
afc9f547
HM
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);
73VLOG_LEVELS
74#undef VLOG_LEVELS
75
76/* Similarly, RFC 5424 defines the local0 facility with the value ordinarily
77 * used for LOG_LOCAL0. */
78BUILD_ASSERT_DECL(LOG_LOCAL0 == (16 << 3));
79
480ce8ab 80/* The log modules. */
55951e15 81struct ovs_list vlog_modules = OVS_LIST_INITIALIZER(&vlog_modules);
064af421 82
d5460484 83/* Protects the 'pattern' in all "struct destination"s, so that a race between
97be1538
EJ
84 * changing and reading the pattern does not cause an access to freed
85 * memory. */
86static struct ovs_rwlock pattern_rwlock = OVS_RWLOCK_INITIALIZER;
87
d5460484
GS
88/* Information about each destination. */
89struct destination {
064af421 90 const char *name; /* Name. */
97be1538 91 char *pattern OVS_GUARDED_BY(pattern_rwlock); /* Current pattern. */
064af421
BP
92 bool default_pattern; /* Whether current pattern is the default. */
93};
d5460484
GS
94static struct destination destinations[VLF_N_DESTINATIONS] = {
95#define VLOG_DESTINATION(NAME, PATTERN) {#NAME, PATTERN, true},
96 VLOG_DESTINATIONS
97#undef VLOG_DESTINATION
064af421
BP
98};
99
81d6495f 100/* Sequence number for the message currently being composed. */
2ba4f163 101DEFINE_STATIC_PER_THREAD_DATA(unsigned int, msg_num, 0);
81d6495f
BP
102
103/* VLF_FILE configuration.
104 *
105 * All of the following is protected by 'log_file_mutex', which nests inside
106 * pattern_rwlock. */
834d6caf 107static struct ovs_mutex log_file_mutex = OVS_MUTEX_INITIALIZER;
97be1538
EJ
108static char *log_file_name OVS_GUARDED_BY(log_file_mutex);
109static int log_fd OVS_GUARDED_BY(log_file_mutex) = -1;
110static struct async_append *log_writer OVS_GUARDED_BY(log_file_mutex);
888e0cf4 111static bool log_async OVS_GUARDED_BY(log_file_mutex);
fe089c0d 112static struct syslogger *syslogger = NULL;
064af421 113
afc9f547
HM
114/* Syslog export configuration. */
115static int syslog_fd OVS_GUARDED_BY(pattern_rwlock) = -1;
116
d69d61c7
GS
117/* Log facility configuration. */
118static atomic_int log_facility = ATOMIC_VAR_INIT(0);
119
120/* Facility name and its value. */
121struct vlog_facility {
122 char *name; /* Name. */
123 unsigned int value; /* Facility associated with 'name'. */
124};
125static 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};
150static bool vlog_facility_exists(const char* facility, int *value);
151
480ce8ab 152static void format_log_message(const struct vlog_module *, enum vlog_level,
afc9f547 153 const char *pattern,
064af421 154 const char *message, va_list, struct ds *)
cab50449 155 OVS_PRINTF_FORMAT(4, 0);
064af421
BP
156
157/* Searches the 'n_names' in 'names'. Returns the index of a match for
158 * 'target', or 'n_names' if no name matches. */
159static size_t
4b5f1d2c 160search_name_array(const char *target, const char *const *names, size_t n_names)
064af421
BP
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'. */
174const char *
175vlog_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. */
183enum vlog_level
d295e8e9 184vlog_get_level_val(const char *name)
064af421
BP
185{
186 return search_name_array(name, level_names, ARRAY_SIZE(level_names));
187}
188
d5460484 189/* Returns the name for logging destination 'destination'. */
064af421 190const char *
d5460484 191vlog_get_destination_name(enum vlog_destination destination)
064af421 192{
d5460484
GS
193 assert(destination < VLF_N_DESTINATIONS);
194 return destinations[destination].name;
064af421
BP
195}
196
d5460484
GS
197/* Returns the logging destination named 'name', or VLF_N_DESTINATIONS if
198 * 'name' is not the name of a logging destination. */
199enum vlog_destination
200vlog_get_destination_val(const char *name)
064af421
BP
201{
202 size_t i;
203
d5460484
GS
204 for (i = 0; i < VLF_N_DESTINATIONS; i++) {
205 if (!strcasecmp(destinations[i].name, name)) {
064af421
BP
206 break;
207 }
208 }
209 return i;
210}
211
e6211adc
TG
212void vlog_insert_module(struct ovs_list *vlog)
213{
214 list_insert(&vlog_modules, vlog);
215}
216
064af421 217/* Returns the name for logging module 'module'. */
480ce8ab
BP
218const char *
219vlog_get_module_name(const struct vlog_module *module)
064af421 220{
480ce8ab 221 return module->name;
064af421
BP
222}
223
480ce8ab
BP
224/* Returns the logging module named 'name', or NULL if 'name' is not the name
225 * of a logging module. */
226struct vlog_module *
227vlog_module_from_name(const char *name)
064af421 228{
86e504e1 229 struct vlog_module *mp;
480ce8ab 230
86e504e1
HS
231 LIST_FOR_EACH (mp, list, &vlog_modules) {
232 if (!strcasecmp(name, mp->name)) {
233 return mp;
480ce8ab
BP
234 }
235 }
86e504e1 236
480ce8ab 237 return NULL;
064af421
BP
238}
239
d5460484
GS
240/* Returns the current logging level for the given 'module' and
241 * 'destination'. */
064af421 242enum vlog_level
d5460484
GS
243vlog_get_level(const struct vlog_module *module,
244 enum vlog_destination destination)
064af421 245{
d5460484
GS
246 assert(destination < VLF_N_DESTINATIONS);
247 return module->levels[destination];
064af421
BP
248}
249
97be1538
EJ
250static void
251update_min_level(struct vlog_module *module) OVS_REQUIRES(&log_file_mutex)
064af421 252{
d5460484 253 enum vlog_destination destination;
064af421 254
c1a543a8 255 module->min_level = VLL_OFF;
d5460484
GS
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];
56cee53b 259 if (level > module->min_level) {
480ce8ab
BP
260 module->min_level = level;
261 }
064af421
BP
262 }
263 }
064af421
BP
264}
265
266static void
d5460484
GS
267set_destination_level(enum vlog_destination destination,
268 struct vlog_module *module, enum vlog_level level)
064af421 269{
d5460484 270 assert(destination >= 0 && destination < VLF_N_DESTINATIONS);
064af421
BP
271 assert(level < VLL_N_LEVELS);
272
97be1538 273 ovs_mutex_lock(&log_file_mutex);
480ce8ab 274 if (!module) {
86e504e1
HS
275 struct vlog_module *mp;
276 LIST_FOR_EACH (mp, list, &vlog_modules) {
d5460484 277 mp->levels[destination] = level;
86e504e1 278 update_min_level(mp);
064af421
BP
279 }
280 } else {
d5460484 281 module->levels[destination] = level;
064af421
BP
282 update_min_level(module);
283 }
97be1538 284 ovs_mutex_unlock(&log_file_mutex);
064af421
BP
285}
286
d5460484
GS
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. */
064af421 290void
d5460484 291vlog_set_levels(struct vlog_module *module, enum vlog_destination destination,
d295e8e9 292 enum vlog_level level)
064af421 293{
d5460484
GS
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);
064af421
BP
300 }
301 } else {
d5460484 302 set_destination_level(destination, module, level);
064af421
BP
303 }
304}
305
306static void
d5460484 307do_set_pattern(enum vlog_destination destination, const char *pattern)
064af421 308{
d5460484 309 struct destination *f = &destinations[destination];
81d6495f 310
97be1538 311 ovs_rwlock_wrlock(&pattern_rwlock);
064af421
BP
312 if (!f->default_pattern) {
313 free(f->pattern);
314 } else {
315 f->default_pattern = false;
316 }
317 f->pattern = xstrdup(pattern);
97be1538 318 ovs_rwlock_unlock(&pattern_rwlock);
064af421
BP
319}
320
d5460484 321/* Sets the pattern for the given 'destination' to 'pattern'. */
064af421 322void
d5460484
GS
323vlog_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);
064af421
BP
331 }
332 } else {
d5460484 333 do_set_pattern(destination, pattern);
064af421
BP
334 }
335}
336
064af421
BP
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. */
340int
341vlog_set_log_file(const char *file_name)
342{
81d6495f 343 char *new_log_file_name;
86e504e1 344 struct vlog_module *mp;
81d6495f
BP
345 struct stat old_stat;
346 struct stat new_stat;
347 int new_log_fd;
348 bool same_file;
97be1538 349 bool log_close;
81d6495f
BP
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. */
97be1538 364 ovs_mutex_lock(&log_file_mutex);
81d6495f
BP
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);
97be1538 371 ovs_mutex_unlock(&log_file_mutex);
81d6495f
BP
372 if (same_file) {
373 close(new_log_fd);
374 free(new_log_file_name);
375 return 0;
376 }
064af421 377
81d6495f 378 /* Log closing old log file (we can't log while holding log_file_mutex). */
97be1538
EJ
379 ovs_mutex_lock(&log_file_mutex);
380 log_close = log_fd >= 0;
381 ovs_mutex_unlock(&log_file_mutex);
382 if (log_close) {
064af421 383 VLOG_INFO("closing log file");
81d6495f 384 }
a5fb0e29 385
81d6495f 386 /* Close old log file, if any, and install new one. */
97be1538 387 ovs_mutex_lock(&log_file_mutex);
81d6495f
BP
388 if (log_fd >= 0) {
389 free(log_file_name);
9eb94563 390 close(log_fd);
81d6495f 391 async_append_destroy(log_writer);
064af421
BP
392 }
393
81d6495f
BP
394 log_file_name = xstrdup(new_log_file_name);
395 log_fd = new_log_fd;
888e0cf4
BP
396 if (log_async) {
397 log_writer = async_append_create(new_log_fd);
398 }
81d6495f 399
86e504e1
HS
400 LIST_FOR_EACH (mp, list, &vlog_modules) {
401 update_min_level(mp);
064af421 402 }
97be1538 403 ovs_mutex_unlock(&log_file_mutex);
064af421 404
81d6495f
BP
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);
064af421 408
81d6495f 409 return 0;
064af421
BP
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. */
415int
416vlog_reopen_log_file(void)
417{
81d6495f 418 char *fn;
68cb8aaf 419
97be1538 420 ovs_mutex_lock(&log_file_mutex);
81d6495f 421 fn = log_file_name ? xstrdup(log_file_name) : NULL;
97be1538 422 ovs_mutex_unlock(&log_file_mutex);
68cb8aaf 423
81d6495f
BP
424 if (fn) {
425 int error = vlog_set_log_file(fn);
426 free(fn);
427 return error;
428 } else {
68cb8aaf
BP
429 return 0;
430 }
064af421
BP
431}
432
2a3e30b2
BP
433/* Set debugging levels. Returns null if successful, otherwise an error
434 * message that the caller must free(). */
064af421
BP
435char *
436vlog_set_levels_from_string(const char *s_)
437{
064af421 438 char *s = xstrdup(s_);
2a3e30b2
BP
439 char *save_ptr = NULL;
440 char *msg = NULL;
441 char *word;
064af421 442
2a3e30b2
BP
443 word = strtok_r(s, " ,:\t", &save_ptr);
444 if (word && !strcasecmp(word, "PATTERN")) {
d5460484 445 enum vlog_destination destination;
064af421 446
2a3e30b2
BP
447 word = strtok_r(NULL, " ,:\t", &save_ptr);
448 if (!word) {
d5460484 449 msg = xstrdup("missing destination");
2a3e30b2 450 goto exit;
064af421
BP
451 }
452
d5460484
GS
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);
2a3e30b2
BP
458 goto exit;
459 }
d5460484 460 vlog_set_pattern(destination, save_ptr);
d69d61c7
GS
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);
2a3e30b2
BP
469 } else {
470 struct vlog_module *module = NULL;
471 enum vlog_level level = VLL_N_LEVELS;
d5460484 472 enum vlog_destination destination = VLF_N_DESTINATIONS;
2a3e30b2
BP
473
474 for (; word != NULL; word = strtok_r(NULL, " ,:\t", &save_ptr)) {
475 if (!strcasecmp(word, "ANY")) {
476 continue;
d5460484
GS
477 } else if (vlog_get_destination_val(word) != VLF_N_DESTINATIONS) {
478 if (destination != VLF_N_DESTINATIONS) {
479 msg = xstrdup("cannot specify multiple destinations");
2a3e30b2 480 goto exit;
064af421 481 }
d5460484 482 destination = vlog_get_destination_val(word);
2a3e30b2
BP
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 {
d5460484
GS
496 msg = xasprintf("no destination, level, or module \"%s\"",
497 word);
2a3e30b2 498 goto exit;
064af421 499 }
2a3e30b2 500 }
064af421 501
d5460484
GS
502 if (destination == VLF_N_DESTINATIONS) {
503 destination = VLF_ANY_DESTINATION;
2a3e30b2
BP
504 }
505 if (level == VLL_N_LEVELS) {
506 level = VLL_DBG;
064af421 507 }
d5460484 508 vlog_set_levels(module, destination, level);
064af421 509 }
2a3e30b2
BP
510
511exit:
064af421 512 free(s);
2a3e30b2 513 return msg;
064af421
BP
514}
515
316bd0f8
BP
516/* Set debugging levels. Abort with an error message if 's' is invalid. */
517void
518vlog_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
064af421
BP
526/* If 'arg' is null, configure maximum verbosity. Otherwise, sets
527 * configuration according to 'arg' (see vlog_set_levels_from_string()). */
528void
529vlog_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 {
d5460484 537 vlog_set_levels(NULL, VLF_ANY_DESTINATION, VLL_DBG);
064af421
BP
538 }
539}
540
fe089c0d
AA
541void
542vlog_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
afc9f547
HM
559/* Set the vlog udp syslog target. */
560void
561vlog_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
d69d61c7
GS
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'. */
578static bool
579vlog_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
064af421 591static void
0e15264f
BP
592vlog_unixctl_set(struct unixctl_conn *conn, int argc, const char *argv[],
593 void *aux OVS_UNUSED)
064af421 594{
0e15264f
BP
595 int i;
596
597 for (i = 1; i < argc; i++) {
598 char *msg = vlog_set_levels_from_string(argv[i]);
599 if (msg) {
bde9f75d 600 unixctl_command_reply_error(conn, msg);
0e15264f
BP
601 free(msg);
602 return;
603 }
604 }
bde9f75d 605 unixctl_command_reply(conn, NULL);
064af421
BP
606}
607
608static void
0e15264f
BP
609vlog_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
610 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
064af421
BP
611{
612 char *msg = vlog_get_levels();
bde9f75d 613 unixctl_command_reply(conn, msg);
064af421
BP
614 free(msg);
615}
616
532e1463
AA
617static void
618vlog_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
064af421 628static void
0e15264f
BP
629vlog_unixctl_reopen(struct unixctl_conn *conn, int argc OVS_UNUSED,
630 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
064af421 631{
97be1538
EJ
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) {
064af421
BP
639 int error = vlog_reopen_log_file();
640 if (error) {
10a89ef0 641 unixctl_command_reply_error(conn, ovs_strerror(errno));
064af421 642 } else {
bde9f75d 643 unixctl_command_reply(conn, NULL);
064af421
BP
644 }
645 } else {
bde9f75d 646 unixctl_command_reply_error(conn, "Logging to file not configured");
064af421
BP
647 }
648}
649
4958e3ee
BP
650static void
651set_all_rate_limits(bool enable)
652{
86e504e1 653 struct vlog_module *mp;
4958e3ee 654
86e504e1
HS
655 LIST_FOR_EACH (mp, list, &vlog_modules) {
656 mp->honor_rate_limits = enable;
4958e3ee
BP
657 }
658}
659
660static void
661set_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
685static void
686vlog_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
692static void
693vlog_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
81d6495f
BP
699/* Initializes the logging subsystem and registers its unixctl server
700 * commands. */
701void
702vlog_init(void)
703{
c3b758f6
BP
704 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
705
706 if (ovsthread_once_start(&once)) {
c3b758f6 707 long long int now;
d69d61c7 708 int facility;
c3b758f6
BP
709
710 /* Do initialization work that needs to be done before any logging
711 * occurs. We want to keep this really minimal because any attempt to
712 * log anything before calling ovsthread_once_done() will deadlock. */
d69d61c7 713 atomic_read_explicit(&log_facility, &facility, memory_order_relaxed);
fe089c0d
AA
714 if (!syslogger) {
715 syslogger = syslog_libc_create();
716 }
717 syslogger->class->openlog(syslogger, facility ? facility : LOG_DAEMON);
c3b758f6
BP
718 ovsthread_once_done(&once);
719
720 /* Now do anything that we want to happen only once but doesn't have to
721 * finish before we start logging. */
722
723 now = time_wall_msec();
724 if (now < 0) {
725 char *s = xastrftime_msec("%a, %d %b %Y %H:%M:%S", now, true);
726 VLOG_ERR("current time is negative: %s (%lld)", s, now);
727 free(s);
728 }
729
730 unixctl_command_register(
d5460484 731 "vlog/set", "{spec | PATTERN:destination:pattern}",
c3b758f6
BP
732 1, INT_MAX, vlog_unixctl_set, NULL);
733 unixctl_command_register("vlog/list", "", 0, 0, vlog_unixctl_list,
734 NULL);
532e1463
AA
735 unixctl_command_register("vlog/list-pattern", "", 0, 0,
736 vlog_unixctl_list_pattern, NULL);
c3b758f6
BP
737 unixctl_command_register("vlog/enable-rate-limit", "[module]...",
738 0, INT_MAX, vlog_enable_rate_limit, NULL);
739 unixctl_command_register("vlog/disable-rate-limit", "[module]...",
740 0, INT_MAX, vlog_disable_rate_limit, NULL);
741 unixctl_command_register("vlog/reopen", "", 0, 0,
742 vlog_unixctl_reopen, NULL);
743 }
81d6495f
BP
744}
745
888e0cf4
BP
746/* Enables VLF_FILE log output to be written asynchronously to disk.
747 * Asynchronous file writes avoid blocking the process in the case of a busy
748 * disk, but on the other hand they are less robust: there is a chance that the
749 * write will not make it to the log file if the process crashes soon after the
750 * log call. */
751void
752vlog_enable_async(void)
753{
754 ovs_mutex_lock(&log_file_mutex);
755 log_async = true;
756 if (log_fd >= 0 && !log_writer) {
757 log_writer = async_append_create(log_fd);
758 }
759 ovs_mutex_unlock(&log_file_mutex);
760}
761
064af421
BP
762/* Print the current logging level for each module. */
763char *
764vlog_get_levels(void)
765{
766 struct ds s = DS_EMPTY_INITIALIZER;
86e504e1 767 struct vlog_module *mp;
8628b0b7
JP
768 struct svec lines = SVEC_EMPTY_INITIALIZER;
769 char *line;
770 size_t i;
064af421
BP
771
772 ds_put_format(&s, " console syslog file\n");
773 ds_put_format(&s, " ------- ------ ------\n");
774
86e504e1 775 LIST_FOR_EACH (mp, list, &vlog_modules) {
4958e3ee
BP
776 struct ds line;
777
778 ds_init(&line);
779 ds_put_format(&line, "%-16s %4s %4s %4s",
86e504e1
HS
780 vlog_get_module_name(mp),
781 vlog_get_level_name(vlog_get_level(mp, VLF_CONSOLE)),
782 vlog_get_level_name(vlog_get_level(mp, VLF_SYSLOG)),
783 vlog_get_level_name(vlog_get_level(mp, VLF_FILE)));
784 if (!mp->honor_rate_limits) {
4958e3ee
BP
785 ds_put_cstr(&line, " (rate limiting disabled)");
786 }
787 ds_put_char(&line, '\n');
788
789 svec_add_nocopy(&lines, ds_steal_cstr(&line));
8628b0b7
JP
790 }
791
792 svec_sort(&lines);
793 SVEC_FOR_EACH (i, line, &lines) {
794 ds_put_cstr(&s, line);
064af421 795 }
8628b0b7 796 svec_destroy(&lines);
064af421
BP
797
798 return ds_cstr(&s);
799}
800
532e1463
AA
801/* Returns as a string current logging patterns for each destination.
802 * This string must be released by caller. */
803char *
804vlog_get_patterns(void)
805{
806 struct ds ds = DS_EMPTY_INITIALIZER;
807 enum vlog_destination destination;
808
809 ovs_rwlock_rdlock(&pattern_rwlock);
810 ds_put_format(&ds, " prefix format\n");
811 ds_put_format(&ds, " ------ ------\n");
812
813 for (destination = 0; destination < VLF_N_DESTINATIONS; destination++) {
814 struct destination *f = &destinations[destination];;
815 const char *prefix = "none";
816
817 if (destination == VLF_SYSLOG && syslogger) {
818 prefix = syslog_get_prefix(syslogger);
819 }
820 ds_put_format(&ds, "%-7s %-32s %s\n", f->name, prefix, f->pattern);
821 }
822 ovs_rwlock_unlock(&pattern_rwlock);
823
824 return ds_cstr(&ds);
825}
826
064af421
BP
827/* Returns true if a log message emitted for the given 'module' and 'level'
828 * would cause some log output, false if that module and level are completely
829 * disabled. */
830bool
480ce8ab 831vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
064af421 832{
480ce8ab 833 return module->min_level >= level;
064af421
BP
834}
835
836static const char *
837fetch_braces(const char *p, const char *def, char *out, size_t out_size)
838{
839 if (*p == '{') {
840 size_t n = strcspn(p + 1, "}");
841 size_t n_copy = MIN(n, out_size - 1);
842 memcpy(out, p + 1, n_copy);
843 out[n_copy] = '\0';
844 p += n + 2;
845 } else {
846 ovs_strlcpy(out, def, out_size);
847 }
848 return p;
849}
850
851static void
480ce8ab 852format_log_message(const struct vlog_module *module, enum vlog_level level,
afc9f547
HM
853 const char *pattern, const char *message,
854 va_list args_, struct ds *s)
064af421
BP
855{
856 char tmp[128];
857 va_list args;
858 const char *p;
d69d61c7 859 int facility;
064af421
BP
860
861 ds_clear(s);
afc9f547 862 for (p = pattern; *p != '\0'; ) {
bc9fb3a9 863 const char *subprogram_name;
064af421
BP
864 enum { LEFT, RIGHT } justify = RIGHT;
865 int pad = '0';
866 size_t length, field, used;
867
868 if (*p != '%') {
869 ds_put_char(s, *p++);
870 continue;
871 }
872
873 p++;
874 if (*p == '-') {
875 justify = LEFT;
876 p++;
877 }
878 if (*p == '0') {
879 pad = '0';
880 p++;
881 }
882 field = 0;
be2c418b 883 while (isdigit((unsigned char)*p)) {
064af421
BP
884 field = (field * 10) + (*p - '0');
885 p++;
886 }
887
888 length = s->length;
889 switch (*p++) {
890 case 'A':
891 ds_put_cstr(s, program_name);
892 break;
afc9f547 893 case 'B':
d69d61c7
GS
894 atomic_read_explicit(&log_facility, &facility,
895 memory_order_relaxed);
896 facility = facility ? facility : LOG_LOCAL0;
897 ds_put_format(s, "%d", facility + syslog_levels[level]);
afc9f547 898 break;
064af421
BP
899 case 'c':
900 p = fetch_braces(p, "", tmp, sizeof tmp);
901 ds_put_cstr(s, vlog_get_module_name(module));
902 break;
903 case 'd':
2b31d8e7
PI
904 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S.###", tmp, sizeof tmp);
905 ds_put_strftime_msec(s, tmp, time_wall_msec(), false);
b5d29991
GS
906 break;
907 case 'D':
2b31d8e7
PI
908 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S.###", tmp, sizeof tmp);
909 ds_put_strftime_msec(s, tmp, time_wall_msec(), true);
064af421 910 break;
afc9f547
HM
911 case 'E':
912 gethostname(tmp, sizeof tmp);
913 tmp[sizeof tmp - 1] = '\0';
914 ds_put_cstr(s, tmp);
915 break;
064af421
BP
916 case 'm':
917 /* Format user-supplied log message and trim trailing new-lines. */
918 length = s->length;
919 va_copy(args, args_);
920 ds_put_format_valist(s, message, args);
921 va_end(args);
922 while (s->length > length && s->string[s->length - 1] == '\n') {
923 s->length--;
924 }
925 break;
926 case 'N':
81d6495f 927 ds_put_format(s, "%u", *msg_num_get_unsafe());
064af421
BP
928 break;
929 case 'n':
930 ds_put_char(s, '\n');
931 break;
932 case 'p':
933 ds_put_cstr(s, vlog_get_level_name(level));
934 break;
935 case 'P':
936 ds_put_format(s, "%ld", (long int) getpid());
937 break;
938 case 'r':
4ae90ff9 939 ds_put_format(s, "%lld", time_msec() - time_boot_msec());
064af421 940 break;
781dee08 941 case 't':
bc9fb3a9 942 subprogram_name = get_subprogram_name();
781dee08
BP
943 ds_put_cstr(s, subprogram_name[0] ? subprogram_name : "main");
944 break;
945 case 'T':
bc9fb3a9 946 subprogram_name = get_subprogram_name();
781dee08
BP
947 if (subprogram_name[0]) {
948 ds_put_format(s, "(%s)", subprogram_name);
949 }
950 break;
064af421
BP
951 default:
952 ds_put_char(s, p[-1]);
953 break;
954 }
955 used = s->length - length;
956 if (used < field) {
957 size_t n_pad = field - used;
958 if (justify == RIGHT) {
959 ds_put_uninit(s, n_pad);
960 memmove(&s->string[length + n_pad], &s->string[length], used);
961 memset(&s->string[length], pad, n_pad);
962 } else {
963 ds_put_char_multiple(s, pad, n_pad);
964 }
965 }
966 }
967}
968
afc9f547
HM
969/* Exports the given 'syslog_message' to the configured udp syslog sink. */
970static void
971send_to_syslog_fd(const char *s, size_t length)
972 OVS_REQ_RDLOCK(pattern_rwlock)
973{
974 static size_t max_length = SIZE_MAX;
975 size_t send_len = MIN(length, max_length);
976
977 while (write(syslog_fd, s, send_len) < 0 && errno == EMSGSIZE) {
978 send_len -= send_len / 20;
979 max_length = send_len;
980 }
981}
982
064af421
BP
983/* Writes 'message' to the log at the given 'level' and as coming from the
984 * given 'module'.
985 *
986 * Guaranteed to preserve errno. */
987void
480ce8ab 988vlog_valist(const struct vlog_module *module, enum vlog_level level,
064af421
BP
989 const char *message, va_list args)
990{
480ce8ab
BP
991 bool log_to_console = module->levels[VLF_CONSOLE] >= level;
992 bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
97be1538
EJ
993 bool log_to_file;
994
995 ovs_mutex_lock(&log_file_mutex);
996 log_to_file = module->levels[VLF_FILE] >= level && log_fd >= 0;
997 ovs_mutex_unlock(&log_file_mutex);
064af421
BP
998 if (log_to_console || log_to_syslog || log_to_file) {
999 int save_errno = errno;
064af421
BP
1000 struct ds s;
1001
1e8cf0f7
BP
1002 vlog_init();
1003
064af421
BP
1004 ds_init(&s);
1005 ds_reserve(&s, 1024);
81d6495f 1006 ++*msg_num_get();
064af421 1007
97be1538 1008 ovs_rwlock_rdlock(&pattern_rwlock);
064af421 1009 if (log_to_console) {
d5460484
GS
1010 format_log_message(module, level,
1011 destinations[VLF_CONSOLE].pattern, message,
1012 args, &s);
064af421
BP
1013 ds_put_char(&s, '\n');
1014 fputs(ds_cstr(&s), stderr);
1015 }
1016
1017 if (log_to_syslog) {
1018 int syslog_level = syslog_levels[level];
1019 char *save_ptr = NULL;
1020 char *line;
d69d61c7 1021 int facility;
064af421 1022
d5460484 1023 format_log_message(module, level, destinations[VLF_SYSLOG].pattern,
afc9f547 1024 message, args, &s);
064af421
BP
1025 for (line = strtok_r(s.string, "\n", &save_ptr); line;
1026 line = strtok_r(NULL, "\n", &save_ptr)) {
d69d61c7
GS
1027 atomic_read_explicit(&log_facility, &facility,
1028 memory_order_relaxed);
fe089c0d 1029 syslogger->class->syslog(syslogger, syslog_level|facility, line);
064af421 1030 }
afc9f547
HM
1031
1032 if (syslog_fd >= 0) {
1033 format_log_message(module, level,
1034 "<%B>1 %D{%Y-%m-%dT%H:%M:%S.###Z} "
1035 "%E %A %P %c - \xef\xbb\xbf%m",
1036 message, args, &s);
1037 send_to_syslog_fd(ds_cstr(&s), s.length);
1038 }
064af421
BP
1039 }
1040
1041 if (log_to_file) {
d5460484 1042 format_log_message(module, level, destinations[VLF_FILE].pattern,
afc9f547 1043 message, args, &s);
064af421 1044 ds_put_char(&s, '\n');
81d6495f 1045
97be1538 1046 ovs_mutex_lock(&log_file_mutex);
81d6495f 1047 if (log_fd >= 0) {
888e0cf4
BP
1048 if (log_writer) {
1049 async_append_write(log_writer, s.string, s.length);
1050 if (level == VLL_EMER) {
1051 async_append_flush(log_writer);
1052 }
1053 } else {
1054 ignore(write(log_fd, s.string, s.length));
81d6495f 1055 }
a5fb0e29 1056 }
97be1538 1057 ovs_mutex_unlock(&log_file_mutex);
064af421 1058 }
97be1538 1059 ovs_rwlock_unlock(&pattern_rwlock);
064af421
BP
1060
1061 ds_destroy(&s);
1062 errno = save_errno;
1063 }
1064}
1065
1066void
480ce8ab
BP
1067vlog(const struct vlog_module *module, enum vlog_level level,
1068 const char *message, ...)
064af421
BP
1069{
1070 va_list args;
1071
1072 va_start(args, message);
1073 vlog_valist(module, level, message, args);
1074 va_end(args);
1075}
1076
d41d4b71
BP
1077/* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
1078 * exit code. Always writes the message to stderr, even if the console
d5460484 1079 * destination is disabled.
d41d4b71
BP
1080 *
1081 * Choose this function instead of vlog_abort_valist() if the daemon monitoring
1082 * facility shouldn't automatically restart the current daemon. */
279c9e03 1083void
c1a543a8 1084vlog_fatal_valist(const struct vlog_module *module_,
279c9e03
BP
1085 const char *message, va_list args)
1086{
ebc56baa 1087 struct vlog_module *module = CONST_CAST(struct vlog_module *, module_);
279c9e03
BP
1088
1089 /* Don't log this message to the console to avoid redundancy with the
1090 * message written by the later ovs_fatal_valist(). */
c1a543a8 1091 module->levels[VLF_CONSOLE] = VLL_OFF;
279c9e03 1092
c1a543a8 1093 vlog_valist(module, VLL_EMER, message, args);
279c9e03
BP
1094 ovs_fatal_valist(0, message, args);
1095}
1096
d41d4b71
BP
1097/* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
1098 * exit code. Always writes the message to stderr, even if the console
d5460484 1099 * destination is disabled.
d41d4b71
BP
1100 *
1101 * Choose this function instead of vlog_abort() if the daemon monitoring
1102 * facility shouldn't automatically restart the current daemon. */
279c9e03 1103void
c1a543a8 1104vlog_fatal(const struct vlog_module *module, const char *message, ...)
279c9e03
BP
1105{
1106 va_list args;
1107
1108 va_start(args, message);
c1a543a8 1109 vlog_fatal_valist(module, message, args);
279c9e03
BP
1110 va_end(args);
1111}
1112
d41d4b71 1113/* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
d5460484 1114 * writes the message to stderr, even if the console destination is disabled.
d41d4b71
BP
1115 *
1116 * Choose this function instead of vlog_fatal_valist() if the daemon monitoring
1117 * facility should automatically restart the current daemon. */
1118void
1119vlog_abort_valist(const struct vlog_module *module_,
1120 const char *message, va_list args)
1121{
1122 struct vlog_module *module = (struct vlog_module *) module_;
1123
1124 /* Don't log this message to the console to avoid redundancy with the
1125 * message written by the later ovs_abort_valist(). */
1126 module->levels[VLF_CONSOLE] = VLL_OFF;
1127
1128 vlog_valist(module, VLL_EMER, message, args);
1129 ovs_abort_valist(0, message, args);
1130}
1131
1132/* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
d5460484 1133 * writes the message to stderr, even if the console destination is disabled.
d41d4b71
BP
1134 *
1135 * Choose this function instead of vlog_fatal() if the daemon monitoring
1136 * facility should automatically restart the current daemon. */
1137void
1138vlog_abort(const struct vlog_module *module, const char *message, ...)
1139{
1140 va_list args;
1141
1142 va_start(args, message);
1143 vlog_abort_valist(module, message, args);
1144 va_end(args);
1145}
1146
064af421 1147bool
480ce8ab 1148vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
064af421
BP
1149 struct vlog_rate_limit *rl)
1150{
4958e3ee
BP
1151 if (!module->honor_rate_limits) {
1152 return false;
1153 }
1154
064af421
BP
1155 if (!vlog_is_enabled(module, level)) {
1156 return true;
1157 }
1158
97be1538 1159 ovs_mutex_lock(&rl->mutex);
648f4f1f 1160 if (!token_bucket_withdraw(&rl->token_bucket, VLOG_MSG_TOKENS)) {
064af421 1161 time_t now = time_now();
648f4f1f
BP
1162 if (!rl->n_dropped) {
1163 rl->first_dropped = now;
064af421 1164 }
648f4f1f
BP
1165 rl->last_dropped = now;
1166 rl->n_dropped++;
97be1538 1167 ovs_mutex_unlock(&rl->mutex);
648f4f1f 1168 return true;
064af421 1169 }
064af421 1170
fda28014 1171 if (!rl->n_dropped) {
97be1538 1172 ovs_mutex_unlock(&rl->mutex);
fda28014 1173 } else {
e2eed6a7 1174 time_t now = time_now();
fda28014 1175 unsigned int n_dropped = rl->n_dropped;
e2eed6a7
BP
1176 unsigned int first_dropped_elapsed = now - rl->first_dropped;
1177 unsigned int last_dropped_elapsed = now - rl->last_dropped;
fda28014 1178 rl->n_dropped = 0;
97be1538 1179 ovs_mutex_unlock(&rl->mutex);
e2eed6a7 1180
064af421 1181 vlog(module, level,
e2eed6a7
BP
1182 "Dropped %u log messages in last %u seconds (most recently, "
1183 "%u seconds ago) due to excessive rate",
fda28014 1184 n_dropped, first_dropped_elapsed, last_dropped_elapsed);
064af421 1185 }
fda28014 1186
064af421
BP
1187 return false;
1188}
1189
1190void
480ce8ab 1191vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
064af421
BP
1192 struct vlog_rate_limit *rl, const char *message, ...)
1193{
1194 if (!vlog_should_drop(module, level, rl)) {
1195 va_list args;
1196
1197 va_start(args, message);
1198 vlog_valist(module, level, message, args);
1199 va_end(args);
1200 }
1201}
1202
1203void
d295e8e9 1204vlog_usage(void)
064af421 1205{
afc9f547
HM
1206 printf("\n\
1207Logging options:\n\
1208 -vSPEC, --verbose=SPEC set logging levels\n\
1209 -v, --verbose set maximum verbosity level\n\
1210 --log-file[=FILE] enable logging to specified FILE\n\
1211 (default: %s/%s.log)\n\
fe089c0d
AA
1212 --syslog-method=(libc|unix:file|udp:ip:port)\n\
1213 specify how to send messages to syslog daemon\n\
afc9f547 1214 --syslog-target=HOST:PORT also send syslog msgs to HOST:PORT via UDP\n",
b43c6fe2 1215 ovs_logdir(), program_name);
064af421 1216}