]> git.proxmox.com Git - mirror_ovs.git/blob - lib/vlog.c
vlog: Make thread-safe.
[mirror_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 "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 "svec.h"
39 #include "timeval.h"
40 #include "unixctl.h"
41 #include "util.h"
42
43 VLOG_DEFINE_THIS_MODULE(vlog);
44
45 COVERAGE_DEFINE(vlog_recursive);
46
47 /* ovs_assert() logs the assertion message, so using ovs_assert() in this
48 * source file could cause recursion. */
49 #undef ovs_assert
50 #define ovs_assert use_assert_instead_of_ovs_assert_in_this_module
51
52 /* Name for each logging level. */
53 static const char *const level_names[VLL_N_LEVELS] = {
54 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
55 VLOG_LEVELS
56 #undef VLOG_LEVEL
57 };
58
59 /* Syslog value for each logging level. */
60 static const int syslog_levels[VLL_N_LEVELS] = {
61 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) SYSLOG_LEVEL,
62 VLOG_LEVELS
63 #undef VLOG_LEVEL
64 };
65
66 /* The log modules. */
67 #if USE_LINKER_SECTIONS
68 extern struct vlog_module *__start_vlog_modules[];
69 extern struct vlog_module *__stop_vlog_modules[];
70 #define vlog_modules __start_vlog_modules
71 #define n_vlog_modules (__stop_vlog_modules - __start_vlog_modules)
72 #else
73 #define VLOG_MODULE VLOG_DEFINE_MODULE__
74 #include "vlog-modules.def"
75 #undef VLOG_MODULE
76
77 struct vlog_module *vlog_modules[] = {
78 #define VLOG_MODULE(NAME) &VLM_##NAME,
79 #include "vlog-modules.def"
80 #undef VLOG_MODULE
81 };
82 #define n_vlog_modules ARRAY_SIZE(vlog_modules)
83 #endif
84
85 /* Information about each facility. */
86 struct facility {
87 const char *name; /* Name. */
88 char *pattern; /* Current pattern (see 'pattern_rwlock'). */
89 bool default_pattern; /* Whether current pattern is the default. */
90 };
91 static struct facility facilities[VLF_N_FACILITIES] = {
92 #define VLOG_FACILITY(NAME, PATTERN) {#NAME, PATTERN, true},
93 VLOG_FACILITIES
94 #undef VLOG_FACILITY
95 };
96
97 /* Protects the 'pattern' in all "struct facility"s, so that a race between
98 * changing and reading the pattern does not cause an access to freed
99 * memory. */
100 static pthread_rwlock_t pattern_rwlock = PTHREAD_RWLOCK_INITIALIZER;
101
102 /* Sequence number for the message currently being composed. */
103 DEFINE_PER_THREAD_DATA(unsigned int, msg_num, 0);
104
105 /* VLF_FILE configuration.
106 *
107 * All of the following is protected by 'log_file_mutex', which nests inside
108 * pattern_rwlock. */
109 static pthread_mutex_t log_file_mutex = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER;
110 static char *log_file_name;
111 static int log_fd = -1;
112 static struct async_append *log_writer;
113
114 static void format_log_message(const struct vlog_module *, enum vlog_level,
115 enum vlog_facility,
116 const char *message, va_list, struct ds *)
117 PRINTF_FORMAT(4, 0);
118
119 /* Searches the 'n_names' in 'names'. Returns the index of a match for
120 * 'target', or 'n_names' if no name matches. */
121 static size_t
122 search_name_array(const char *target, const char *const *names, size_t n_names)
123 {
124 size_t i;
125
126 for (i = 0; i < n_names; i++) {
127 assert(names[i]);
128 if (!strcasecmp(names[i], target)) {
129 break;
130 }
131 }
132 return i;
133 }
134
135 /* Returns the name for logging level 'level'. */
136 const char *
137 vlog_get_level_name(enum vlog_level level)
138 {
139 assert(level < VLL_N_LEVELS);
140 return level_names[level];
141 }
142
143 /* Returns the logging level with the given 'name', or VLL_N_LEVELS if 'name'
144 * is not the name of a logging level. */
145 enum vlog_level
146 vlog_get_level_val(const char *name)
147 {
148 return search_name_array(name, level_names, ARRAY_SIZE(level_names));
149 }
150
151 /* Returns the name for logging facility 'facility'. */
152 const char *
153 vlog_get_facility_name(enum vlog_facility facility)
154 {
155 assert(facility < VLF_N_FACILITIES);
156 return facilities[facility].name;
157 }
158
159 /* Returns the logging facility named 'name', or VLF_N_FACILITIES if 'name' is
160 * not the name of a logging facility. */
161 enum vlog_facility
162 vlog_get_facility_val(const char *name)
163 {
164 size_t i;
165
166 for (i = 0; i < VLF_N_FACILITIES; i++) {
167 if (!strcasecmp(facilities[i].name, name)) {
168 break;
169 }
170 }
171 return i;
172 }
173
174 /* Returns the name for logging module 'module'. */
175 const char *
176 vlog_get_module_name(const struct vlog_module *module)
177 {
178 return module->name;
179 }
180
181 /* Returns the logging module named 'name', or NULL if 'name' is not the name
182 * of a logging module. */
183 struct vlog_module *
184 vlog_module_from_name(const char *name)
185 {
186 struct vlog_module **mp;
187
188 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
189 if (!strcasecmp(name, (*mp)->name)) {
190 return *mp;
191 }
192 }
193 return NULL;
194 }
195
196 /* Returns the current logging level for the given 'module' and 'facility'. */
197 enum vlog_level
198 vlog_get_level(const struct vlog_module *module, enum vlog_facility facility)
199 {
200 assert(facility < VLF_N_FACILITIES);
201 return module->levels[facility];
202 }
203
204 static void OVS_MUST_HOLD(log_file_mutex)
205 update_min_level(struct vlog_module *module)
206 {
207 enum vlog_facility facility;
208
209 module->min_level = VLL_OFF;
210 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
211 if (log_fd >= 0 || facility != VLF_FILE) {
212 enum vlog_level level = module->levels[facility];
213 if (level > module->min_level) {
214 module->min_level = level;
215 }
216 }
217 }
218 }
219
220 static void
221 set_facility_level(enum vlog_facility facility, struct vlog_module *module,
222 enum vlog_level level)
223 {
224 assert(facility >= 0 && facility < VLF_N_FACILITIES);
225 assert(level < VLL_N_LEVELS);
226
227 xpthread_mutex_lock(&log_file_mutex);
228 if (!module) {
229 struct vlog_module **mp;
230
231 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
232 (*mp)->levels[facility] = level;
233 update_min_level(*mp);
234 }
235 } else {
236 module->levels[facility] = level;
237 update_min_level(module);
238 }
239 xpthread_mutex_unlock(&log_file_mutex);
240 }
241
242 /* Sets the logging level for the given 'module' and 'facility' to 'level'. A
243 * null 'module' or a 'facility' of VLF_ANY_FACILITY is treated as a wildcard
244 * across all modules or facilities, respectively. */
245 void
246 vlog_set_levels(struct vlog_module *module, enum vlog_facility facility,
247 enum vlog_level level)
248 {
249 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
250 if (facility == VLF_ANY_FACILITY) {
251 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
252 set_facility_level(facility, module, level);
253 }
254 } else {
255 set_facility_level(facility, module, level);
256 }
257 }
258
259 static void
260 do_set_pattern(enum vlog_facility facility, const char *pattern)
261 {
262 struct facility *f = &facilities[facility];
263
264 xpthread_rwlock_wrlock(&pattern_rwlock);
265 if (!f->default_pattern) {
266 free(f->pattern);
267 } else {
268 f->default_pattern = false;
269 }
270 f->pattern = xstrdup(pattern);
271 xpthread_rwlock_unlock(&pattern_rwlock);
272 }
273
274 /* Sets the pattern for the given 'facility' to 'pattern'. */
275 void
276 vlog_set_pattern(enum vlog_facility facility, const char *pattern)
277 {
278 assert(facility < VLF_N_FACILITIES || facility == VLF_ANY_FACILITY);
279 if (facility == VLF_ANY_FACILITY) {
280 for (facility = 0; facility < VLF_N_FACILITIES; facility++) {
281 do_set_pattern(facility, pattern);
282 }
283 } else {
284 do_set_pattern(facility, pattern);
285 }
286 }
287
288 /* Sets the name of the log file used by VLF_FILE to 'file_name', or to the
289 * default file name if 'file_name' is null. Returns 0 if successful,
290 * otherwise a positive errno value. */
291 int
292 vlog_set_log_file(const char *file_name)
293 {
294 char *new_log_file_name;
295 struct vlog_module **mp;
296 struct stat old_stat;
297 struct stat new_stat;
298 int new_log_fd;
299 bool same_file;
300
301 /* Open new log file. */
302 new_log_file_name = (file_name
303 ? xstrdup(file_name)
304 : xasprintf("%s/%s.log", ovs_logdir(), program_name));
305 new_log_fd = open(new_log_file_name, O_WRONLY | O_CREAT | O_APPEND, 0666);
306 if (new_log_fd < 0) {
307 VLOG_WARN("failed to open %s for logging: %s",
308 new_log_file_name, ovs_strerror(errno));
309 free(new_log_file_name);
310 return errno;
311 }
312
313 /* If the new log file is the same one we already have open, bail out. */
314 xpthread_mutex_lock(&log_file_mutex);
315 same_file = (log_fd >= 0
316 && new_log_fd >= 0
317 && !fstat(log_fd, &old_stat)
318 && !fstat(new_log_fd, &new_stat)
319 && old_stat.st_dev == new_stat.st_dev
320 && old_stat.st_ino == new_stat.st_ino);
321 xpthread_mutex_unlock(&log_file_mutex);
322 if (same_file) {
323 close(new_log_fd);
324 free(new_log_file_name);
325 return 0;
326 }
327
328 /* Log closing old log file (we can't log while holding log_file_mutex). */
329 if (log_fd >= 0) {
330 VLOG_INFO("closing log file");
331 }
332
333 /* Close old log file, if any, and install new one. */
334 xpthread_mutex_lock(&log_file_mutex);
335 if (log_fd >= 0) {
336 free(log_file_name);
337 close(log_fd);
338 async_append_destroy(log_writer);
339 }
340
341 log_file_name = xstrdup(new_log_file_name);
342 log_fd = new_log_fd;
343 log_writer = async_append_create(new_log_fd);
344
345 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
346 update_min_level(*mp);
347 }
348 xpthread_mutex_unlock(&log_file_mutex);
349
350 /* Log opening new log file (we can't log while holding log_file_mutex). */
351 VLOG_INFO("opened log file %s", new_log_file_name);
352 free(new_log_file_name);
353
354 return 0;
355 }
356
357 /* Closes and then attempts to re-open the current log file. (This is useful
358 * just after log rotation, to ensure that the new log file starts being used.)
359 * Returns 0 if successful, otherwise a positive errno value. */
360 int
361 vlog_reopen_log_file(void)
362 {
363 char *fn;
364
365 xpthread_mutex_lock(&log_file_mutex);
366 fn = log_file_name ? xstrdup(log_file_name) : NULL;
367 xpthread_mutex_unlock(&log_file_mutex);
368
369 if (fn) {
370 int error = vlog_set_log_file(fn);
371 free(fn);
372 return error;
373 } else {
374 return 0;
375 }
376 }
377
378 /* Set debugging levels. Returns null if successful, otherwise an error
379 * message that the caller must free(). */
380 char *
381 vlog_set_levels_from_string(const char *s_)
382 {
383 char *s = xstrdup(s_);
384 char *save_ptr = NULL;
385 char *msg = NULL;
386 char *word;
387
388 word = strtok_r(s, " ,:\t", &save_ptr);
389 if (word && !strcasecmp(word, "PATTERN")) {
390 enum vlog_facility facility;
391
392 word = strtok_r(NULL, " ,:\t", &save_ptr);
393 if (!word) {
394 msg = xstrdup("missing facility");
395 goto exit;
396 }
397
398 facility = (!strcasecmp(word, "ANY")
399 ? VLF_ANY_FACILITY
400 : vlog_get_facility_val(word));
401 if (facility == VLF_N_FACILITIES) {
402 msg = xasprintf("unknown facility \"%s\"", word);
403 goto exit;
404 }
405 vlog_set_pattern(facility, save_ptr);
406 } else {
407 struct vlog_module *module = NULL;
408 enum vlog_level level = VLL_N_LEVELS;
409 enum vlog_facility facility = VLF_N_FACILITIES;
410
411 for (; word != NULL; word = strtok_r(NULL, " ,:\t", &save_ptr)) {
412 if (!strcasecmp(word, "ANY")) {
413 continue;
414 } else if (vlog_get_facility_val(word) != VLF_N_FACILITIES) {
415 if (facility != VLF_N_FACILITIES) {
416 msg = xstrdup("cannot specify multiple facilities");
417 goto exit;
418 }
419 facility = vlog_get_facility_val(word);
420 } else if (vlog_get_level_val(word) != VLL_N_LEVELS) {
421 if (level != VLL_N_LEVELS) {
422 msg = xstrdup("cannot specify multiple levels");
423 goto exit;
424 }
425 level = vlog_get_level_val(word);
426 } else if (vlog_module_from_name(word)) {
427 if (module) {
428 msg = xstrdup("cannot specify multiple modules");
429 goto exit;
430 }
431 module = vlog_module_from_name(word);
432 } else {
433 msg = xasprintf("no facility, level, or module \"%s\"", word);
434 goto exit;
435 }
436 }
437
438 if (facility == VLF_N_FACILITIES) {
439 facility = VLF_ANY_FACILITY;
440 }
441 if (level == VLL_N_LEVELS) {
442 level = VLL_DBG;
443 }
444 vlog_set_levels(module, facility, level);
445 }
446
447 exit:
448 free(s);
449 return msg;
450 }
451
452 /* Set debugging levels. Abort with an error message if 's' is invalid. */
453 void
454 vlog_set_levels_from_string_assert(const char *s)
455 {
456 char *error = vlog_set_levels_from_string(s);
457 if (error) {
458 ovs_fatal(0, "%s", error);
459 }
460 }
461
462 /* If 'arg' is null, configure maximum verbosity. Otherwise, sets
463 * configuration according to 'arg' (see vlog_set_levels_from_string()). */
464 void
465 vlog_set_verbosity(const char *arg)
466 {
467 if (arg) {
468 char *msg = vlog_set_levels_from_string(arg);
469 if (msg) {
470 ovs_fatal(0, "processing \"%s\": %s", arg, msg);
471 }
472 } else {
473 vlog_set_levels(NULL, VLF_ANY_FACILITY, VLL_DBG);
474 }
475 }
476
477 static void
478 vlog_unixctl_set(struct unixctl_conn *conn, int argc, const char *argv[],
479 void *aux OVS_UNUSED)
480 {
481 int i;
482
483 for (i = 1; i < argc; i++) {
484 char *msg = vlog_set_levels_from_string(argv[i]);
485 if (msg) {
486 unixctl_command_reply_error(conn, msg);
487 free(msg);
488 return;
489 }
490 }
491 unixctl_command_reply(conn, NULL);
492 }
493
494 static void
495 vlog_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
496 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
497 {
498 char *msg = vlog_get_levels();
499 unixctl_command_reply(conn, msg);
500 free(msg);
501 }
502
503 static void
504 vlog_unixctl_reopen(struct unixctl_conn *conn, int argc OVS_UNUSED,
505 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
506 {
507 if (log_file_name) {
508 int error = vlog_reopen_log_file();
509 if (error) {
510 unixctl_command_reply_error(conn, ovs_strerror(errno));
511 } else {
512 unixctl_command_reply(conn, NULL);
513 }
514 } else {
515 unixctl_command_reply_error(conn, "Logging to file not configured");
516 }
517 }
518
519 static void
520 set_all_rate_limits(bool enable)
521 {
522 struct vlog_module **mp;
523
524 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
525 (*mp)->honor_rate_limits = enable;
526 }
527 }
528
529 static void
530 set_rate_limits(struct unixctl_conn *conn, int argc,
531 const char *argv[], bool enable)
532 {
533 if (argc > 1) {
534 int i;
535
536 for (i = 1; i < argc; i++) {
537 if (!strcasecmp(argv[i], "ANY")) {
538 set_all_rate_limits(enable);
539 } else {
540 struct vlog_module *module = vlog_module_from_name(argv[i]);
541 if (!module) {
542 unixctl_command_reply_error(conn, "unknown module");
543 return;
544 }
545 module->honor_rate_limits = enable;
546 }
547 }
548 } else {
549 set_all_rate_limits(enable);
550 }
551 unixctl_command_reply(conn, NULL);
552 }
553
554 static void
555 vlog_enable_rate_limit(struct unixctl_conn *conn, int argc,
556 const char *argv[], void *aux OVS_UNUSED)
557 {
558 set_rate_limits(conn, argc, argv, true);
559 }
560
561 static void
562 vlog_disable_rate_limit(struct unixctl_conn *conn, int argc,
563 const char *argv[], void *aux OVS_UNUSED)
564 {
565 set_rate_limits(conn, argc, argv, false);
566 }
567
568 static void
569 vlog_init__(void)
570 {
571 static char *program_name_copy;
572 time_t now;
573
574 /* openlog() is allowed to keep the pointer passed in, without making a
575 * copy. The daemonize code sometimes frees and replaces 'program_name',
576 * so make a private copy just for openlog(). (We keep a pointer to the
577 * private copy to suppress memory leak warnings in case openlog() does
578 * make its own copy.) */
579 program_name_copy = program_name ? xstrdup(program_name) : NULL;
580 openlog(program_name_copy, LOG_NDELAY, LOG_DAEMON);
581
582 now = time_wall();
583 if (now < 0) {
584 char *s = xastrftime("%a, %d %b %Y %H:%M:%S", now, true);
585 VLOG_ERR("current time is negative: %s (%ld)", s, (long int) now);
586 free(s);
587 }
588
589 unixctl_command_register(
590 "vlog/set", "{spec | PATTERN:facility:pattern}",
591 1, INT_MAX, vlog_unixctl_set, NULL);
592 unixctl_command_register("vlog/list", "", 0, 0, vlog_unixctl_list, NULL);
593 unixctl_command_register("vlog/enable-rate-limit", "[module]...",
594 0, INT_MAX, vlog_enable_rate_limit, NULL);
595 unixctl_command_register("vlog/disable-rate-limit", "[module]...",
596 0, INT_MAX, vlog_disable_rate_limit, NULL);
597 unixctl_command_register("vlog/reopen", "", 0, 0,
598 vlog_unixctl_reopen, NULL);
599 }
600
601 /* Initializes the logging subsystem and registers its unixctl server
602 * commands. */
603 void
604 vlog_init(void)
605 {
606 static pthread_once_t once = PTHREAD_ONCE_INIT;
607 pthread_once(&once, vlog_init__);
608 }
609
610 /* Print the current logging level for each module. */
611 char *
612 vlog_get_levels(void)
613 {
614 struct ds s = DS_EMPTY_INITIALIZER;
615 struct vlog_module **mp;
616 struct svec lines = SVEC_EMPTY_INITIALIZER;
617 char *line;
618 size_t i;
619
620 ds_put_format(&s, " console syslog file\n");
621 ds_put_format(&s, " ------- ------ ------\n");
622
623 for (mp = vlog_modules; mp < &vlog_modules[n_vlog_modules]; mp++) {
624 struct ds line;
625
626 ds_init(&line);
627 ds_put_format(&line, "%-16s %4s %4s %4s",
628 vlog_get_module_name(*mp),
629 vlog_get_level_name(vlog_get_level(*mp, VLF_CONSOLE)),
630 vlog_get_level_name(vlog_get_level(*mp, VLF_SYSLOG)),
631 vlog_get_level_name(vlog_get_level(*mp, VLF_FILE)));
632 if (!(*mp)->honor_rate_limits) {
633 ds_put_cstr(&line, " (rate limiting disabled)");
634 }
635 ds_put_char(&line, '\n');
636
637 svec_add_nocopy(&lines, ds_steal_cstr(&line));
638 }
639
640 svec_sort(&lines);
641 SVEC_FOR_EACH (i, line, &lines) {
642 ds_put_cstr(&s, line);
643 }
644 svec_destroy(&lines);
645
646 return ds_cstr(&s);
647 }
648
649 /* Returns true if a log message emitted for the given 'module' and 'level'
650 * would cause some log output, false if that module and level are completely
651 * disabled. */
652 bool
653 vlog_is_enabled(const struct vlog_module *module, enum vlog_level level)
654 {
655 return module->min_level >= level;
656 }
657
658 static const char *
659 fetch_braces(const char *p, const char *def, char *out, size_t out_size)
660 {
661 if (*p == '{') {
662 size_t n = strcspn(p + 1, "}");
663 size_t n_copy = MIN(n, out_size - 1);
664 memcpy(out, p + 1, n_copy);
665 out[n_copy] = '\0';
666 p += n + 2;
667 } else {
668 ovs_strlcpy(out, def, out_size);
669 }
670 return p;
671 }
672
673 static void
674 format_log_message(const struct vlog_module *module, enum vlog_level level,
675 enum vlog_facility facility,
676 const char *message, va_list args_, struct ds *s)
677 {
678 char tmp[128];
679 va_list args;
680 const char *p;
681
682 ds_clear(s);
683 for (p = facilities[facility].pattern; *p != '\0'; ) {
684 const char *subprogram_name;
685 enum { LEFT, RIGHT } justify = RIGHT;
686 int pad = '0';
687 size_t length, field, used;
688
689 if (*p != '%') {
690 ds_put_char(s, *p++);
691 continue;
692 }
693
694 p++;
695 if (*p == '-') {
696 justify = LEFT;
697 p++;
698 }
699 if (*p == '0') {
700 pad = '0';
701 p++;
702 }
703 field = 0;
704 while (isdigit((unsigned char)*p)) {
705 field = (field * 10) + (*p - '0');
706 p++;
707 }
708
709 length = s->length;
710 switch (*p++) {
711 case 'A':
712 ds_put_cstr(s, program_name);
713 break;
714 case 'c':
715 p = fetch_braces(p, "", tmp, sizeof tmp);
716 ds_put_cstr(s, vlog_get_module_name(module));
717 break;
718 case 'd':
719 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
720 ds_put_strftime(s, tmp, time_wall(), false);
721 break;
722 case 'D':
723 p = fetch_braces(p, "%Y-%m-%d %H:%M:%S", tmp, sizeof tmp);
724 ds_put_strftime(s, tmp, time_wall(), true);
725 break;
726 case 'm':
727 /* Format user-supplied log message and trim trailing new-lines. */
728 length = s->length;
729 va_copy(args, args_);
730 ds_put_format_valist(s, message, args);
731 va_end(args);
732 while (s->length > length && s->string[s->length - 1] == '\n') {
733 s->length--;
734 }
735 break;
736 case 'N':
737 ds_put_format(s, "%u", *msg_num_get_unsafe());
738 break;
739 case 'n':
740 ds_put_char(s, '\n');
741 break;
742 case 'p':
743 ds_put_cstr(s, vlog_get_level_name(level));
744 break;
745 case 'P':
746 ds_put_format(s, "%ld", (long int) getpid());
747 break;
748 case 'r':
749 ds_put_format(s, "%lld", time_msec() - time_boot_msec());
750 break;
751 case 't':
752 subprogram_name = get_subprogram_name();
753 ds_put_cstr(s, subprogram_name[0] ? subprogram_name : "main");
754 break;
755 case 'T':
756 subprogram_name = get_subprogram_name();
757 if (subprogram_name[0]) {
758 ds_put_format(s, "(%s)", subprogram_name);
759 }
760 break;
761 default:
762 ds_put_char(s, p[-1]);
763 break;
764 }
765 used = s->length - length;
766 if (used < field) {
767 size_t n_pad = field - used;
768 if (justify == RIGHT) {
769 ds_put_uninit(s, n_pad);
770 memmove(&s->string[length + n_pad], &s->string[length], used);
771 memset(&s->string[length], pad, n_pad);
772 } else {
773 ds_put_char_multiple(s, pad, n_pad);
774 }
775 }
776 }
777 }
778
779 /* Writes 'message' to the log at the given 'level' and as coming from the
780 * given 'module'.
781 *
782 * Guaranteed to preserve errno. */
783 void
784 vlog_valist(const struct vlog_module *module, enum vlog_level level,
785 const char *message, va_list args)
786 {
787 bool log_to_console = module->levels[VLF_CONSOLE] >= level;
788 bool log_to_syslog = module->levels[VLF_SYSLOG] >= level;
789 bool log_to_file = module->levels[VLF_FILE] >= level && log_fd >= 0;
790 if (log_to_console || log_to_syslog || log_to_file) {
791 int save_errno = errno;
792 struct ds s;
793
794 vlog_init();
795
796 ds_init(&s);
797 ds_reserve(&s, 1024);
798 ++*msg_num_get();
799
800 xpthread_rwlock_rdlock(&pattern_rwlock);
801 if (log_to_console) {
802 format_log_message(module, level, VLF_CONSOLE, message, args, &s);
803 ds_put_char(&s, '\n');
804 fputs(ds_cstr(&s), stderr);
805 }
806
807 if (log_to_syslog) {
808 int syslog_level = syslog_levels[level];
809 char *save_ptr = NULL;
810 char *line;
811
812 format_log_message(module, level, VLF_SYSLOG, message, args, &s);
813 for (line = strtok_r(s.string, "\n", &save_ptr); line;
814 line = strtok_r(NULL, "\n", &save_ptr)) {
815 syslog(syslog_level, "%s", line);
816 }
817 }
818
819 if (log_to_file) {
820 format_log_message(module, level, VLF_FILE, message, args, &s);
821 ds_put_char(&s, '\n');
822
823 xpthread_mutex_lock(&log_file_mutex);
824 if (log_fd >= 0) {
825 async_append_write(log_writer, s.string, s.length);
826 if (level == VLL_EMER) {
827 async_append_flush(log_writer);
828 }
829 }
830 xpthread_mutex_unlock(&log_file_mutex);
831 }
832 xpthread_rwlock_unlock(&pattern_rwlock);
833
834 ds_destroy(&s);
835 errno = save_errno;
836 }
837 }
838
839 void
840 vlog(const struct vlog_module *module, enum vlog_level level,
841 const char *message, ...)
842 {
843 va_list args;
844
845 va_start(args, message);
846 vlog_valist(module, level, message, args);
847 va_end(args);
848 }
849
850 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
851 * exit code. Always writes the message to stderr, even if the console
852 * facility is disabled.
853 *
854 * Choose this function instead of vlog_abort_valist() if the daemon monitoring
855 * facility shouldn't automatically restart the current daemon. */
856 void
857 vlog_fatal_valist(const struct vlog_module *module_,
858 const char *message, va_list args)
859 {
860 struct vlog_module *module = CONST_CAST(struct vlog_module *, module_);
861
862 /* Don't log this message to the console to avoid redundancy with the
863 * message written by the later ovs_fatal_valist(). */
864 module->levels[VLF_CONSOLE] = VLL_OFF;
865
866 vlog_valist(module, VLL_EMER, message, args);
867 ovs_fatal_valist(0, message, args);
868 }
869
870 /* Logs 'message' to 'module' at maximum verbosity, then exits with a failure
871 * exit code. Always writes the message to stderr, even if the console
872 * facility is disabled.
873 *
874 * Choose this function instead of vlog_abort() if the daemon monitoring
875 * facility shouldn't automatically restart the current daemon. */
876 void
877 vlog_fatal(const struct vlog_module *module, const char *message, ...)
878 {
879 va_list args;
880
881 va_start(args, message);
882 vlog_fatal_valist(module, message, args);
883 va_end(args);
884 }
885
886 /* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
887 * writes the message to stderr, even if the console facility is disabled.
888 *
889 * Choose this function instead of vlog_fatal_valist() if the daemon monitoring
890 * facility should automatically restart the current daemon. */
891 void
892 vlog_abort_valist(const struct vlog_module *module_,
893 const char *message, va_list args)
894 {
895 struct vlog_module *module = (struct vlog_module *) module_;
896
897 /* Don't log this message to the console to avoid redundancy with the
898 * message written by the later ovs_abort_valist(). */
899 module->levels[VLF_CONSOLE] = VLL_OFF;
900
901 vlog_valist(module, VLL_EMER, message, args);
902 ovs_abort_valist(0, message, args);
903 }
904
905 /* Logs 'message' to 'module' at maximum verbosity, then calls abort(). Always
906 * writes the message to stderr, even if the console facility is disabled.
907 *
908 * Choose this function instead of vlog_fatal() if the daemon monitoring
909 * facility should automatically restart the current daemon. */
910 void
911 vlog_abort(const struct vlog_module *module, const char *message, ...)
912 {
913 va_list args;
914
915 va_start(args, message);
916 vlog_abort_valist(module, message, args);
917 va_end(args);
918 }
919
920 bool
921 vlog_should_drop(const struct vlog_module *module, enum vlog_level level,
922 struct vlog_rate_limit *rl)
923 {
924 if (!module->honor_rate_limits) {
925 return false;
926 }
927
928 if (!vlog_is_enabled(module, level)) {
929 return true;
930 }
931
932 xpthread_mutex_lock(&rl->mutex);
933 if (!token_bucket_withdraw(&rl->token_bucket, VLOG_MSG_TOKENS)) {
934 time_t now = time_now();
935 if (!rl->n_dropped) {
936 rl->first_dropped = now;
937 }
938 rl->last_dropped = now;
939 rl->n_dropped++;
940 xpthread_mutex_unlock(&rl->mutex);
941 return true;
942 }
943
944 if (!rl->n_dropped) {
945 xpthread_mutex_unlock(&rl->mutex);
946 } else {
947 time_t now = time_now();
948 unsigned int n_dropped = rl->n_dropped;
949 unsigned int first_dropped_elapsed = now - rl->first_dropped;
950 unsigned int last_dropped_elapsed = now - rl->last_dropped;
951 rl->n_dropped = 0;
952 xpthread_mutex_unlock(&rl->mutex);
953
954 vlog(module, level,
955 "Dropped %u log messages in last %u seconds (most recently, "
956 "%u seconds ago) due to excessive rate",
957 n_dropped, first_dropped_elapsed, last_dropped_elapsed);
958 }
959
960 return false;
961 }
962
963 void
964 vlog_rate_limit(const struct vlog_module *module, enum vlog_level level,
965 struct vlog_rate_limit *rl, const char *message, ...)
966 {
967 if (!vlog_should_drop(module, level, rl)) {
968 va_list args;
969
970 va_start(args, message);
971 vlog_valist(module, level, message, args);
972 va_end(args);
973 }
974 }
975
976 void
977 vlog_usage(void)
978 {
979 printf("\nLogging options:\n"
980 " -v, --verbose=[SPEC] set logging levels\n"
981 " -v, --verbose set maximum verbosity level\n"
982 " --log-file[=FILE] enable logging to specified FILE\n"
983 " (default: %s/%s.log)\n",
984 ovs_logdir(), program_name);
985 }