virlog.c 43.7 KB
Newer Older
1
/*
2
 * virlog.c: internal logging and debugging
3
 *
4
 * Copyright (C) 2008, 2010-2013 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22 23
 *
 */

#include <config.h>

D
Daniel Veillard 已提交
24 25 26 27 28 29 30 31
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
32
#include <unistd.h>
33
#include <signal.h>
34
#include <execinfo.h>
35
#include <regex.h>
D
Daniel Veillard 已提交
36
#if HAVE_SYSLOG_H
37
# include <syslog.h>
D
Daniel Veillard 已提交
38
#endif
D
Daniel P. Berrange 已提交
39 40 41 42
#include <sys/socket.h>
#if HAVE_SYS_UN_H
# include <sys/un.h>
#endif
D
Daniel Veillard 已提交
43

44
#include "virerror.h"
45
#include "virlog.h"
46
#include "viralloc.h"
47
#include "virutil.h"
48
#include "virbuffer.h"
49
#include "virthread.h"
E
Eric Blake 已提交
50
#include "virfile.h"
51
#include "virtime.h"
D
Daniel P. Berrange 已提交
52
#include "intprops.h"
53
#include "virstring.h"
54

E
Eric Blake 已提交
55 56 57 58 59 60
/* Journald output is only supported on Linux new enough to expose
 * htole64.  */
#if HAVE_SYSLOG_H && defined(__linux__) && HAVE_DECL_HTOLE64
# define USE_JOURNALD 1
#endif

61 62
#define VIR_FROM_THIS VIR_FROM_NONE

63 64 65 66 67 68 69 70
VIR_ENUM_DECL(virLogSource)
VIR_ENUM_IMPL(virLogSource, VIR_LOG_FROM_LAST,
              "file",
              "error",
              "audit",
              "trace",
              "library");

D
Daniel Veillard 已提交
71 72 73 74
/*
 * A logging buffer to keep some history over logs
 */

75 76
static int virLogSize = 64 * 1024;
static char *virLogBuffer = NULL;
D
Daniel Veillard 已提交
77 78 79
static int virLogLen = 0;
static int virLogStart = 0;
static int virLogEnd = 0;
80 81 82
static regex_t *virLogRegex = NULL;


83 84
#define VIR_LOG_DATE_REGEX "[0-9]{4}-[0-9]{2}-[0-9]{2}"
#define VIR_LOG_TIME_REGEX "[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}\\+[0-9]{4}"
85
#define VIR_LOG_PID_REGEX "[0-9]+"
86
#define VIR_LOG_LEVEL_REGEX "(debug|info|warning|error)"
87 88 89 90

#define VIR_LOG_REGEX \
    VIR_LOG_DATE_REGEX " " VIR_LOG_TIME_REGEX ": " \
    VIR_LOG_PID_REGEX ": " VIR_LOG_LEVEL_REGEX " : "
D
Daniel Veillard 已提交
91 92 93 94 95 96

/*
 * Filters are used to refine the rules on what to keep or drop
 * based on a matching pattern (currently a substring)
 */
struct _virLogFilter {
97
    char *match;
98
    virLogPriority priority;
99
    unsigned int flags;
D
Daniel Veillard 已提交
100 101 102 103 104 105 106 107 108 109 110 111
};
typedef struct _virLogFilter virLogFilter;
typedef virLogFilter *virLogFilterPtr;

static virLogFilterPtr virLogFilters = NULL;
static int virLogNbFilters = 0;

/*
 * Outputs are used to emit the messages retained
 * after filtering, multiple output can be used simultaneously
 */
struct _virLogOutput {
112
    bool logVersion;
D
Daniel Veillard 已提交
113 114 115
    void *data;
    virLogOutputFunc f;
    virLogCloseFunc c;
116
    virLogPriority priority;
117
    virLogDestination dest;
118
    char *name;
D
Daniel Veillard 已提交
119 120 121 122 123 124 125 126 127 128
};
typedef struct _virLogOutput virLogOutput;
typedef virLogOutput *virLogOutputPtr;

static virLogOutputPtr virLogOutputs = NULL;
static int virLogNbOutputs = 0;

/*
 * Default priorities
 */
129
static virLogPriority virLogDefaultPriority = VIR_LOG_DEFAULT;
D
Daniel Veillard 已提交
130 131 132

static int virLogResetFilters(void);
static int virLogResetOutputs(void);
133
static void virLogOutputToFd(virLogSource src,
134
                             virLogPriority priority,
135
                             const char *filename,
136
                             int linenr,
137
                             const char *funcname,
138
                             const char *timestamp,
M
Miloslav Trmač 已提交
139
                             virLogMetadataPtr metadata,
140
                             unsigned int flags,
141 142
                             const char *rawstr,
                             const char *str,
143
                             void *data);
D
Daniel Veillard 已提交
144 145 146 147

/*
 * Logs accesses must be serialized though a mutex
 */
148
virMutex virLogMutex;
D
Daniel Veillard 已提交
149

150 151
void
virLogLock(void)
D
Daniel Veillard 已提交
152
{
153
    virMutexLock(&virLogMutex);
D
Daniel Veillard 已提交
154
}
155 156 157 158


void
virLogUnlock(void)
D
Daniel Veillard 已提交
159
{
160
    virMutexUnlock(&virLogMutex);
D
Daniel Veillard 已提交
161 162
}

163 164 165 166

static const char *
virLogOutputString(virLogDestination ldest)
{
167
    switch (ldest) {
168 169 170 171 172 173
    case VIR_LOG_TO_STDERR:
        return "stderr";
    case VIR_LOG_TO_SYSLOG:
        return "syslog";
    case VIR_LOG_TO_FILE:
        return "file";
D
Daniel P. Berrange 已提交
174 175
    case VIR_LOG_TO_JOURNALD:
        return "journald";
176
    }
177
    return "unknown";
178
}
D
Daniel Veillard 已提交
179

180 181 182 183

static const char *
virLogPriorityString(virLogPriority lvl)
{
D
Daniel Veillard 已提交
184
    switch (lvl) {
185 186 187 188 189 190 191 192
    case VIR_LOG_DEBUG:
        return "debug";
    case VIR_LOG_INFO:
        return "info";
    case VIR_LOG_WARN:
        return "warning";
    case VIR_LOG_ERROR:
        return "error";
D
Daniel Veillard 已提交
193
    }
194
    return "unknown";
D
Daniel Veillard 已提交
195 196 197
}


198 199
static int
virLogOnceInit(void)
200
{
201 202
    const char *pbm = NULL;

203 204 205
    if (virMutexInit(&virLogMutex) < 0)
        return -1;

D
Daniel Veillard 已提交
206
    virLogLock();
207
    if (VIR_ALLOC_N_QUIET(virLogBuffer, virLogSize + 1) < 0) {
208 209 210 211 212 213
        /*
         * The debug buffer is not a critical component, allow startup
         * even in case of failure to allocate it in case of a
         * configuration mistake.
         */
        virLogSize = 64 * 1024;
214
        if (VIR_ALLOC_N_QUIET(virLogBuffer, virLogSize + 1) < 0) {
215 216 217 218 219 220
            pbm = "Failed to allocate debug buffer: deactivating debug log\n";
            virLogSize = 0;
        } else {
            pbm = "Failed to allocate debug buffer: reduced to 64 kB\n";
        }
    }
D
Daniel Veillard 已提交
221 222 223
    virLogLen = 0;
    virLogStart = 0;
    virLogEnd = 0;
224
    virLogDefaultPriority = VIR_LOG_DEFAULT;
225

226
    if (VIR_ALLOC_QUIET(virLogRegex) >= 0) {
227 228 229 230
        if (regcomp(virLogRegex, VIR_LOG_REGEX, REG_EXTENDED) != 0)
            VIR_FREE(virLogRegex);
    }

D
Daniel Veillard 已提交
231
    virLogUnlock();
232
    if (pbm)
233
        VIR_WARN("%s", pbm);
234
    return 0;
D
Daniel Veillard 已提交
235 236
}

237 238
VIR_ONCE_GLOBAL_INIT(virLog)

239

240 241 242 243 244 245 246 247 248 249
/**
 * virLogSetBufferSize:
 * @size: size of the buffer in kilobytes or <= 0 to deactivate
 *
 * Dynamically set the size or deactivate the logging buffer used to keep
 * a trace of all recent debug output. Note that the content of the buffer
 * is lost if it gets reallocated.
 *
 * Return -1 in case of failure or 0 in case of success
 */
250 251 252
int
virLogSetBufferSize(int size)
{
253 254 255 256 257 258 259 260
    int ret = 0;
    int oldsize;
    char *oldLogBuffer;
    const char *pbm = NULL;

    if (size < 0)
        size = 0;

261 262 263 264
    if (virLogInitialize() < 0)
        return -1;

    if (size * 1024 == virLogSize)
265 266 267 268 269 270 271
        return ret;

    virLogLock();

    oldsize = virLogSize;
    oldLogBuffer = virLogBuffer;

272
    if (INT_MAX / 1024 <= size) {
273 274 275 276 277 278
        pbm = "Requested log size of %d kB too large\n";
        ret = -1;
        goto error;
    }

    virLogSize = size * 1024;
279
    if (VIR_ALLOC_N_QUIET(virLogBuffer, virLogSize + 1) < 0) {
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
        pbm = "Failed to allocate debug buffer of %d kB\n";
        virLogBuffer = oldLogBuffer;
        virLogSize = oldsize;
        ret = -1;
        goto error;
    }
    VIR_FREE(oldLogBuffer);
    virLogLen = 0;
    virLogStart = 0;
    virLogEnd = 0;

error:
    virLogUnlock();
    if (pbm)
        VIR_ERROR(pbm, size);
    return ret;
}

298

D
Daniel Veillard 已提交
299 300 301 302 303 304 305
/**
 * virLogReset:
 *
 * Reset the logging module to its default initial state
 *
 * Returns 0 if successful, and -1 in case or error
 */
306 307 308
int
virLogReset(void)
{
309 310
    if (virLogInitialize() < 0)
        return -1;
D
Daniel Veillard 已提交
311 312 313 314 315 316 317

    virLogLock();
    virLogResetFilters();
    virLogResetOutputs();
    virLogLen = 0;
    virLogStart = 0;
    virLogEnd = 0;
318
    virLogDefaultPriority = VIR_LOG_DEFAULT;
D
Daniel Veillard 已提交
319
    virLogUnlock();
320
    return 0;
D
Daniel Veillard 已提交
321 322
}

323

D
Daniel Veillard 已提交
324 325 326
/*
 * Store a string in the ring buffer
 */
327 328
static void
virLogStr(const char *str)
329
{
D
Daniel Veillard 已提交
330
    int tmp;
331
    int len;
D
Daniel Veillard 已提交
332

333
    if ((str == NULL) || (virLogBuffer == NULL) || (virLogSize <= 0))
D
Daniel Veillard 已提交
334
        return;
335
    len = strlen(str);
E
Eric Blake 已提交
336
    if (len >= virLogSize)
D
Daniel Veillard 已提交
337 338 339 340 341
        return;

    /*
     * copy the data and reset the end, we cycle over the end of the buffer
     */
342 343
    if (virLogEnd + len >= virLogSize) {
        tmp = virLogSize - virLogEnd;
D
Daniel Veillard 已提交
344
        memcpy(&virLogBuffer[virLogEnd], str, tmp);
345
        memcpy(&virLogBuffer[0], &str[tmp], len - tmp);
D
Daniel Veillard 已提交
346 347 348 349 350
        virLogEnd = len - tmp;
    } else {
        memcpy(&virLogBuffer[virLogEnd], str, len);
        virLogEnd += len;
    }
E
Eric Blake 已提交
351
    virLogBuffer[virLogEnd] = 0;
D
Daniel Veillard 已提交
352 353 354 355
    /*
     * Update the log length, and if full move the start index
     */
    virLogLen += len;
356 357 358
    if (virLogLen > virLogSize) {
        tmp = virLogLen - virLogSize;
        virLogLen = virLogSize;
D
Daniel Veillard 已提交
359
        virLogStart += tmp;
360 361
        if (virLogStart >= virLogSize)
            virLogStart -= virLogSize;
D
Daniel Veillard 已提交
362 363 364
    }
}

365 366 367 368

static void
virLogDumpAllFD(const char *msg, int len)
{
369
    size_t i;
370
    bool found = false;
371

372 373 374
    if (len <= 0)
        len = strlen(msg);

375
    for (i = 0; i < virLogNbOutputs; i++) {
376
        if (virLogOutputs[i].f == virLogOutputToFd) {
377
            int fd = (intptr_t) virLogOutputs[i].data;
378 379

            if (fd >= 0) {
380
                ignore_value(safewrite(fd, msg, len));
381
                found = true;
382 383 384 385
            }
        }
    }
    if (!found)
386
        ignore_value(safewrite(STDERR_FILENO, msg, len));
387 388
}

389

390 391 392 393 394 395 396 397
/**
 * virLogEmergencyDumpAll:
 * @signum: the signal number
 *
 * Emergency function called, possibly from a signal handler.
 * It need to output the debug ring buffer through the log
 * output which are safe to use from a signal handler.
 * In case none is found it is emitted to standard error.
D
Daniel Veillard 已提交
398
 */
399
void
400 401
virLogEmergencyDumpAll(int signum)
{
402
    int len;
C
Christophe Fergeau 已提交
403
    int oldLogStart, oldLogLen;
D
Daniel Veillard 已提交
404

405
    switch (signum) {
D
Daniel Veillard 已提交
406
#ifdef SIGFPE
407
        case SIGFPE:
408
            virLogDumpAllFD("Caught signal Floating-point exception", -1);
409
            break;
D
Daniel Veillard 已提交
410 411
#endif
#ifdef SIGSEGV
412
        case SIGSEGV:
413
            virLogDumpAllFD("Caught Segmentation violation", -1);
414
            break;
D
Daniel Veillard 已提交
415 416
#endif
#ifdef SIGILL
417
        case SIGILL:
418
            virLogDumpAllFD("Caught illegal instruction", -1);
419
            break;
D
Daniel Veillard 已提交
420 421
#endif
#ifdef SIGABRT
422
        case SIGABRT:
423
            virLogDumpAllFD("Caught abort signal", -1);
424
            break;
D
Daniel Veillard 已提交
425 426
#endif
#ifdef SIGBUS
427
        case SIGBUS:
428
            virLogDumpAllFD("Caught bus error", -1);
429
            break;
D
Daniel Veillard 已提交
430 431
#endif
#ifdef SIGUSR2
432
        case SIGUSR2:
433
            virLogDumpAllFD("Caught User-defined signal 2", -1);
434
            break;
D
Daniel Veillard 已提交
435
#endif
436
        default:
437
            virLogDumpAllFD("Caught unexpected signal", -1);
438 439
            break;
    }
440 441
    if ((virLogBuffer == NULL) || (virLogSize <= 0)) {
        virLogDumpAllFD(" internal log buffer deactivated\n", -1);
442
        return;
443
    }
444

445 446
    virLogDumpAllFD(" dumping internal log buffer:\n", -1);
    virLogDumpAllFD("\n\n    ====== start of log =====\n\n", -1);
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468

    /*
     * Since we can't lock the buffer safely from a signal handler
     * we mark it as empty in case of concurrent access, and proceed
     * with the data, at worse we will output something a bit weird
     * if another thread start logging messages at the same time.
     * Note that virLogStr() uses virLogEnd for the computations and
     * writes to the buffer and only then updates virLogLen and virLogStart
     * so it's best to reset it first.
     */
    oldLogStart = virLogStart;
    oldLogLen = virLogLen;
    virLogEnd = 0;
    virLogLen = 0;
    virLogStart = 0;

    while (oldLogLen > 0) {
        if (oldLogStart + oldLogLen < virLogSize) {
            virLogBuffer[oldLogStart + oldLogLen] = 0;
            virLogDumpAllFD(&virLogBuffer[oldLogStart], oldLogLen);
            oldLogStart += oldLogLen;
            oldLogLen = 0;
D
Daniel Veillard 已提交
469
        } else {
470
            len = virLogSize - oldLogStart;
471
            virLogBuffer[virLogSize] = 0;
472 473 474
            virLogDumpAllFD(&virLogBuffer[oldLogStart], len);
            oldLogLen -= len;
            oldLogStart = 0;
D
Daniel Veillard 已提交
475 476
        }
    }
477
    virLogDumpAllFD("\n\n     ====== end of log =====\n\n", -1);
D
Daniel Veillard 已提交
478
}
479

480

D
Daniel Veillard 已提交
481 482 483 484 485 486 487 488 489 490
/**
 * virLogSetDefaultPriority:
 * @priority: the default priority level
 *
 * Set the default priority level, i.e. any logged data of a priority
 * equal or superior to this level will be logged, unless a specific rule
 * was defined for the log category of the message.
 *
 * Returns 0 if successful, -1 in case of error.
 */
491 492 493
int
virLogSetDefaultPriority(virLogPriority priority)
{
494
    if ((priority < VIR_LOG_DEBUG) || (priority > VIR_LOG_ERROR)) {
495
        VIR_WARN("Ignoring invalid log level setting.");
496
        return -1;
497
    }
498 499 500
    if (virLogInitialize() < 0)
        return -1;

D
Daniel Veillard 已提交
501
    virLogDefaultPriority = priority;
502
    return 0;
D
Daniel Veillard 已提交
503 504
}

505

D
Daniel Veillard 已提交
506 507 508 509 510 511 512
/**
 * virLogResetFilters:
 *
 * Removes the set of logging filters defined.
 *
 * Returns the number of filters removed
 */
513 514 515
static int
virLogResetFilters(void)
{
516
    size_t i;
D
Daniel Veillard 已提交
517

518
    for (i = 0; i < virLogNbFilters; i++)
D
Daniel Veillard 已提交
519 520 521
        VIR_FREE(virLogFilters[i].match);
    VIR_FREE(virLogFilters);
    virLogNbFilters = 0;
522
    return i;
D
Daniel Veillard 已提交
523 524
}

525

D
Daniel Veillard 已提交
526 527 528 529
/**
 * virLogDefineFilter:
 * @match: the pattern to match
 * @priority: the priority to give to messages matching the pattern
530
 * @flags: extra flags, see virLogFilterFlags enum
D
Daniel Veillard 已提交
531 532 533 534 535 536 537 538
 *
 * Defines a pattern used for log filtering, it allow to select or
 * reject messages independently of the default priority.
 * The filter defines a rules that will apply only to messages matching
 * the pattern (currently if @match is a substring of the message category)
 *
 * Returns -1 in case of failure or the filter number if successful
 */
539 540 541 542
int
virLogDefineFilter(const char *match,
                   virLogPriority priority,
                   unsigned int flags)
543
{
544 545
    size_t i;
    int ret = -1;
D
Daniel Veillard 已提交
546 547
    char *mdup = NULL;

548
    virCheckFlags(VIR_LOG_STACK_TRACE, -1);
549

550 551 552
    if (virLogInitialize() < 0)
        return -1;

D
Daniel Veillard 已提交
553 554
    if ((match == NULL) || (priority < VIR_LOG_DEBUG) ||
        (priority > VIR_LOG_ERROR))
555
        return -1;
D
Daniel Veillard 已提交
556 557

    virLogLock();
558
    for (i = 0; i < virLogNbFilters; i++) {
D
Daniel Veillard 已提交
559 560
        if (STREQ(virLogFilters[i].match, match)) {
            virLogFilters[i].priority = priority;
561
            ret = i;
D
Daniel Veillard 已提交
562 563 564 565
            goto cleanup;
        }
    }

566
    if (VIR_STRDUP_QUIET(mdup, match) < 0)
D
Daniel Veillard 已提交
567
        goto cleanup;
568
    if (VIR_REALLOC_N_QUIET(virLogFilters, virLogNbFilters + 1)) {
D
Daniel Veillard 已提交
569 570 571
        VIR_FREE(mdup);
        goto cleanup;
    }
572
    ret = virLogNbFilters;
D
Daniel Veillard 已提交
573 574
    virLogFilters[i].match = mdup;
    virLogFilters[i].priority = priority;
575
    virLogFilters[i].flags = flags;
D
Daniel Veillard 已提交
576 577 578
    virLogNbFilters++;
cleanup:
    virLogUnlock();
579
    if (ret < 0)
580
        virReportOOMError();
581
    return ret;
D
Daniel Veillard 已提交
582 583
}

584

D
Daniel Veillard 已提交
585 586 587 588 589 590 591 592 593 594
/**
 * virLogFiltersCheck:
 * @input: the input string
 *
 * Check the input of the message against the existing filters. Currently
 * the match is just a substring check of the category used as the input
 * string, a more subtle approach could be used instead
 *
 * Returns 0 if not matched or the new priority if found.
 */
595 596 597 598
static int
virLogFiltersCheck(const char *input,
                   unsigned int *flags)
{
D
Daniel Veillard 已提交
599
    int ret = 0;
600
    size_t i;
D
Daniel Veillard 已提交
601 602

    virLogLock();
603
    for (i = 0; i < virLogNbFilters; i++) {
D
Daniel Veillard 已提交
604 605
        if (strstr(input, virLogFilters[i].match)) {
            ret = virLogFilters[i].priority;
606
            *flags = virLogFilters[i].flags;
D
Daniel Veillard 已提交
607 608 609 610
            break;
        }
    }
    virLogUnlock();
611
    return ret;
D
Daniel Veillard 已提交
612 613
}

614

D
Daniel Veillard 已提交
615 616 617 618 619 620 621
/**
 * virLogResetOutputs:
 *
 * Removes the set of logging output defined.
 *
 * Returns the number of output removed
 */
622 623 624
static int
virLogResetOutputs(void)
{
625
    size_t i;
D
Daniel Veillard 已提交
626

627
    for (i = 0; i < virLogNbOutputs; i++) {
D
Daniel Veillard 已提交
628 629
        if (virLogOutputs[i].c != NULL)
            virLogOutputs[i].c(virLogOutputs[i].data);
630
        VIR_FREE(virLogOutputs[i].name);
D
Daniel Veillard 已提交
631 632 633 634
    }
    VIR_FREE(virLogOutputs);
    i = virLogNbOutputs;
    virLogNbOutputs = 0;
635
    return i;
D
Daniel Veillard 已提交
636 637
}

638

D
Daniel Veillard 已提交
639 640 641
/**
 * virLogDefineOutput:
 * @f: the function to call to output a message
642
 * @c: the function to call to close the output (or NULL)
D
Daniel Veillard 已提交
643 644
 * @data: extra data passed as first arg to the function
 * @priority: minimal priority for this filter, use 0 for none
645 646
 * @dest: where to send output of this priority
 * @name: optional name data associated with an output
D
Daniel Veillard 已提交
647 648 649 650 651 652 653
 * @flags: extra flag, currently unused
 *
 * Defines an output function for log messages. Each message once
 * gone though filtering is emitted through each registered output.
 *
 * Returns -1 in case of failure or the output number if successful
 */
654 655 656 657 658 659 660 661
int
virLogDefineOutput(virLogOutputFunc f,
                   virLogCloseFunc c,
                   void *data,
                   virLogPriority priority,
                   virLogDestination dest,
                   const char *name,
                   unsigned int flags)
662
{
D
Daniel Veillard 已提交
663
    int ret = -1;
664
    char *ndup = NULL;
D
Daniel Veillard 已提交
665

666 667
    virCheckFlags(0, -1);

668 669 670
    if (virLogInitialize() < 0)
        return -1;

D
Daniel Veillard 已提交
671
    if (f == NULL)
672
        return -1;
D
Daniel Veillard 已提交
673

674
    if (dest == VIR_LOG_TO_SYSLOG || dest == VIR_LOG_TO_FILE) {
675 676
        if (!name) {
            virReportOOMError();
677
            return -1;
678 679
        }
        if (VIR_STRDUP(ndup, name) < 0)
680
            return -1;
681 682
    }

D
Daniel Veillard 已提交
683
    virLogLock();
684
    if (VIR_REALLOC_N_QUIET(virLogOutputs, virLogNbOutputs + 1)) {
685
        VIR_FREE(ndup);
D
Daniel Veillard 已提交
686 687 688
        goto cleanup;
    }
    ret = virLogNbOutputs++;
689
    virLogOutputs[ret].logVersion = true;
D
Daniel Veillard 已提交
690 691 692 693
    virLogOutputs[ret].f = f;
    virLogOutputs[ret].c = c;
    virLogOutputs[ret].data = data;
    virLogOutputs[ret].priority = priority;
694 695
    virLogOutputs[ret].dest = dest;
    virLogOutputs[ret].name = ndup;
D
Daniel Veillard 已提交
696 697
cleanup:
    virLogUnlock();
698
    return ret;
D
Daniel Veillard 已提交
699 700
}

701

702 703
static int
virLogFormatString(char **msg,
704
                   int linenr,
705
                   const char *funcname,
706
                   virLogPriority priority,
707 708 709
                   const char *str)
{
    int ret;
710 711 712 713 714 715 716 717

    /*
     * Be careful when changing the following log message formatting, we rely
     * on it when stripping libvirt debug messages from qemu log files. So when
     * changing this, you might also need to change the code there.
     * virLogFormatString() function name is mentioned there so it's sufficient
     * to just grep for it to find the right place.
     */
718
    if ((funcname != NULL)) {
719 720 721
        ret = virAsprintfQuiet(msg, "%llu: %s : %s:%d : %s\n",
                               virThreadSelfID(), virLogPriorityString(priority),
                               funcname, linenr, str);
722
    } else {
723 724 725
        ret = virAsprintfQuiet(msg, "%llu: %s : %s\n",
                               virThreadSelfID(), virLogPriorityString(priority),
                               str);
726 727 728 729
    }
    return ret;
}

730

731
static int
732 733
virLogVersionString(const char **rawmsg,
                    char **msg)
734 735 736 737 738 739 740 741 742 743 744 745 746 747
{
#ifdef PACKAGER_VERSION
# ifdef PACKAGER
#  define LOG_VERSION_STRING \
    "libvirt version: " VERSION ", package: " PACKAGER_VERSION " (" PACKAGER ")"
# else
#  define LOG_VERSION_STRING \
    "libvirt version: " VERSION ", package: " PACKAGER_VERSION
# endif
#else
# define LOG_VERSION_STRING  \
    "libvirt version: " VERSION
#endif

748
    *rawmsg = LOG_VERSION_STRING;
749
    return virLogFormatString(msg, 0, NULL, VIR_LOG_INFO, LOG_VERSION_STRING);
750 751
}

752

D
Daniel Veillard 已提交
753 754
/**
 * virLogMessage:
755
 * @source: where is that message coming from
D
Daniel Veillard 已提交
756
 * @priority: the priority level
757
 * @filename: file where the message was emitted
758
 * @linenr: line where the message was emitted
759
 * @funcname: the function emitting the (debug) message
760
 * @metadata: NULL or metadata array, terminated by an item with NULL key
D
Daniel Veillard 已提交
761 762 763
 * @fmt: the string format
 * @...: the arguments
 *
E
Eric Blake 已提交
764
 * Call the libvirt logger with some information. Based on the configuration
D
Daniel Veillard 已提交
765 766
 * the message may be stored, sent to output or just discarded
 */
767
void
768
virLogMessage(virLogSource source,
769
              virLogPriority priority,
770
              const char *filename,
771
              int linenr,
772
              const char *funcname,
773
              virLogMetadataPtr metadata,
774
              const char *fmt, ...)
775 776 777
{
    va_list ap;
    va_start(ap, fmt);
778
    virLogVMessage(source, priority,
779
                   filename, linenr, funcname,
780
                   metadata, fmt, ap);
781 782 783
    va_end(ap);
}

784

785 786
/**
 * virLogVMessage:
787
 * @source: where is that message coming from
788
 * @priority: the priority level
789
 * @filename: file where the message was emitted
790
 * @linenr: line where the message was emitted
791
 * @funcname: the function emitting the (debug) message
792
 * @metadata: NULL or metadata array, terminated by an item with NULL key
793 794 795 796 797 798
 * @fmt: the string format
 * @vargs: format args
 *
 * Call the libvirt logger with some information. Based on the configuration
 * the message may be stored, sent to output or just discarded
 */
799
void
800
virLogVMessage(virLogSource source,
801
               virLogPriority priority,
802
               const char *filename,
803
               int linenr,
804
               const char *funcname,
M
Miloslav Trmač 已提交
805
               virLogMetadataPtr metadata,
806 807
               const char *fmt,
               va_list vargs)
808
{
809
    static bool logVersionStderr = true;
D
Daniel Veillard 已提交
810
    char *str = NULL;
811
    char *msg = NULL;
812
    char timestamp[VIR_TIME_STRING_BUFLEN];
813 814
    int fprio, ret;
    size_t i;
815
    int saved_errno = errno;
816
    bool emit = true;
817
    unsigned int filterflags = 0;
D
Daniel Veillard 已提交
818

819 820
    if (virLogInitialize() < 0)
        return;
D
Daniel Veillard 已提交
821 822

    if (fmt == NULL)
823
        goto cleanup;
D
Daniel Veillard 已提交
824 825 826 827

    /*
     * check against list of specific logging patterns
     */
828
    fprio = virLogFiltersCheck(filename, &filterflags);
D
Daniel Veillard 已提交
829 830
    if (fprio == 0) {
        if (priority < virLogDefaultPriority)
831
            emit = false;
832
    } else if (priority < fprio) {
833
        emit = false;
834
    }
D
Daniel Veillard 已提交
835

836
    if (!emit)
837 838
        goto cleanup;

D
Daniel Veillard 已提交
839 840 841
    /*
     * serialize the error message, add level and timestamp
     */
842
    if (virVasprintfQuiet(&str, fmt, vargs) < 0) {
843
        goto cleanup;
E
Eric Blake 已提交
844
    }
D
Daniel Veillard 已提交
845

846
    ret = virLogFormatString(&msg, linenr, funcname, priority, str);
847 848
    if (ret < 0)
        goto cleanup;
D
Daniel Veillard 已提交
849

850 851
    if (virTimeStringNowRaw(timestamp) < 0)
        timestamp[0] = '\0';
852

D
Daniel Veillard 已提交
853
    /*
854 855
     * Log based on defaults, first store in the history buffer,
     * then if emit push the message on the outputs defined, if none
D
Daniel Veillard 已提交
856 857 858 859 860
     * use stderr.
     * NOTE: the locking is a single point of contention for multiple
     *       threads, but avoid intermixing. Maybe set up locks per output
     *       to improve paralellism.
     */
861 862
    virLogLock();
    virLogStr(timestamp);
863
    virLogStr(": ");
864
    virLogStr(msg);
865

866
    for (i = 0; i < virLogNbOutputs; i++) {
867 868
        if (priority >= virLogOutputs[i].priority) {
            if (virLogOutputs[i].logVersion) {
869
                const char *rawver;
870
                char *ver = NULL;
871
                if (virLogVersionString(&rawver, &ver) >= 0)
872
                    virLogOutputs[i].f(VIR_LOG_FROM_FILE, VIR_LOG_INFO,
873
                                       __FILE__, __LINE__, __func__,
M
Miloslav Trmač 已提交
874
                                       timestamp, NULL, 0, rawver, ver,
875 876 877 878
                                       virLogOutputs[i].data);
                VIR_FREE(ver);
                virLogOutputs[i].logVersion = false;
            }
879
            virLogOutputs[i].f(source, priority,
880
                               filename, linenr, funcname,
M
Miloslav Trmač 已提交
881
                               timestamp, metadata, filterflags,
882
                               str, msg, virLogOutputs[i].data);
883
        }
D
Daniel Veillard 已提交
884
    }
885
    if (virLogNbOutputs == 0) {
886
        if (logVersionStderr) {
887
            const char *rawver;
888
            char *ver = NULL;
889
            if (virLogVersionString(&rawver, &ver) >= 0)
890
                virLogOutputToFd(VIR_LOG_FROM_FILE, VIR_LOG_INFO,
891
                                 __FILE__, __LINE__, __func__,
M
Miloslav Trmač 已提交
892
                                 timestamp, NULL, 0, rawver, ver,
893
                                 (void *) STDERR_FILENO);
894 895 896
            VIR_FREE(ver);
            logVersionStderr = false;
        }
897
        virLogOutputToFd(source, priority,
898
                         filename, linenr, funcname,
M
Miloslav Trmač 已提交
899
                         timestamp, metadata, filterflags,
900
                         str, msg, (void *) STDERR_FILENO);
901
    }
D
Daniel Veillard 已提交
902 903
    virLogUnlock();

904
cleanup:
905
    VIR_FREE(str);
906
    VIR_FREE(msg);
907
    errno = saved_errno;
D
Daniel Veillard 已提交
908 909
}

910

911 912
static void
virLogStackTraceToFd(int fd)
913 914 915 916 917
{
    void *array[100];
    int size;
    static bool doneWarning = false;
    const char *msg = "Stack trace not available on this platform\n";
918 919 920 921 922 923 924

#define STRIP_DEPTH 3
    size = backtrace(array, ARRAY_CARDINALITY(array));
    if (size) {
        backtrace_symbols_fd(array +  STRIP_DEPTH, size - STRIP_DEPTH, fd);
        ignore_value(safewrite(fd, "\n", 1));
    } else if (!doneWarning) {
925 926 927
        ignore_value(safewrite(fd, msg, strlen(msg)));
        doneWarning = true;
    }
928
#undef STRIP_DEPTH
929 930
}

931
static void
932
virLogOutputToFd(virLogSource source ATTRIBUTE_UNUSED,
933
                 virLogPriority priority ATTRIBUTE_UNUSED,
934
                 const char *filename ATTRIBUTE_UNUSED,
935
                 int linenr ATTRIBUTE_UNUSED,
936
                 const char *funcname ATTRIBUTE_UNUSED,
937
                 const char *timestamp,
M
Miloslav Trmač 已提交
938
                 virLogMetadataPtr metadata ATTRIBUTE_UNUSED,
939 940 941 942
                 unsigned int flags,
                 const char *rawstr ATTRIBUTE_UNUSED,
                 const char *str,
                 void *data)
943
{
944
    int fd = (intptr_t) data;
945
    char *msg;
D
Daniel Veillard 已提交
946 947

    if (fd < 0)
948
        return;
949

950
    if (virAsprintfQuiet(&msg, "%s: %s", timestamp, str) < 0)
951
        return;
952

953
    ignore_value(safewrite(fd, msg, strlen(msg)));
954 955
    VIR_FREE(msg);

956 957
    if (flags & VIR_LOG_STACK_TRACE)
        virLogStackTraceToFd(fd);
D
Daniel Veillard 已提交
958 959
}

960 961 962

static void
virLogCloseFd(void *data)
963
{
964
    int fd = (intptr_t) data;
D
Daniel Veillard 已提交
965

966
    VIR_LOG_CLOSE(fd);
D
Daniel Veillard 已提交
967 968
}

969 970 971 972

static int
virLogAddOutputToStderr(virLogPriority priority)
{
973 974
    if (virLogDefineOutput(virLogOutputToFd, NULL, (void *)2L, priority,
                           VIR_LOG_TO_STDERR, NULL, 0) < 0)
975 976
        return -1;
    return 0;
D
Daniel Veillard 已提交
977 978
}

979 980 981 982 983

static int
virLogAddOutputToFile(virLogPriority priority,
                      const char *file)
{
D
Daniel Veillard 已提交
984 985
    int fd;

986
    fd = open(file, O_CREAT | O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR);
D
Daniel Veillard 已提交
987
    if (fd < 0)
988
        return -1;
989 990
    if (virLogDefineOutput(virLogOutputToFd, virLogCloseFd,
                           (void *)(intptr_t)fd,
991
                           priority, VIR_LOG_TO_FILE, file, 0) < 0) {
992
        VIR_FORCE_CLOSE(fd);
993
        return -1;
D
Daniel Veillard 已提交
994
    }
995
    return 0;
D
Daniel Veillard 已提交
996 997
}

998

999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
#if HAVE_SYSLOG_H || USE_JOURNALD

/* Compat in case we build with journald, but no syslog */
# ifndef LOG_DEBUG
#  define LOG_DEBUG 7
# endif
# ifndef LOG_INFO
#  define LOG_INFO 6
# endif
# ifndef LOG_WARNING
#  define LOG_WARNING 4
# endif
# ifndef LOG_ERR
#  define LOG_ERR 3
# endif

1015 1016
static int
virLogPrioritySyslog(virLogPriority priority)
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
{
    switch (priority) {
    case VIR_LOG_DEBUG:
        return LOG_DEBUG;
    case VIR_LOG_INFO:
        return LOG_INFO;
    case VIR_LOG_WARN:
        return LOG_WARNING;
    case VIR_LOG_ERROR:
        return LOG_ERR;
    default:
        return LOG_ERR;
    }
}
1031
#endif /* HAVE_SYSLOG_H || USE_JOURNALD */
1032

1033

1034
#if HAVE_SYSLOG_H
1035
static void
1036
virLogOutputToSyslog(virLogSource source ATTRIBUTE_UNUSED,
1037
                     virLogPriority priority,
1038
                     const char *filename ATTRIBUTE_UNUSED,
1039
                     int linenr ATTRIBUTE_UNUSED,
1040
                     const char *funcname ATTRIBUTE_UNUSED,
1041
                     const char *timestamp ATTRIBUTE_UNUSED,
M
Miloslav Trmač 已提交
1042
                     virLogMetadataPtr metadata ATTRIBUTE_UNUSED,
1043 1044 1045 1046
                     unsigned int flags,
                     const char *rawstr ATTRIBUTE_UNUSED,
                     const char *str,
                     void *data ATTRIBUTE_UNUSED)
1047
{
1048
    virCheckFlags(VIR_LOG_STACK_TRACE,);
1049

1050
    syslog(virLogPrioritySyslog(priority), "%s", str);
D
Daniel Veillard 已提交
1051 1052
}

1053 1054
static char *current_ident = NULL;

1055 1056 1057 1058

static void
virLogCloseSyslog(void *data ATTRIBUTE_UNUSED)
{
D
Daniel Veillard 已提交
1059
    closelog();
1060
    VIR_FREE(current_ident);
D
Daniel Veillard 已提交
1061 1062
}

1063 1064 1065 1066 1067

static int
virLogAddOutputToSyslog(virLogPriority priority,
                        const char *ident)
{
1068 1069 1070 1071
    /*
     * ident needs to be kept around on Solaris
     */
    VIR_FREE(current_ident);
1072
    if (VIR_STRDUP(current_ident, ident) < 0)
1073
        return -1;
1074 1075

    openlog(current_ident, 0, 0);
D
Daniel Veillard 已提交
1076
    if (virLogDefineOutput(virLogOutputToSyslog, virLogCloseSyslog, NULL,
1077
                           priority, VIR_LOG_TO_SYSLOG, ident, 0) < 0) {
D
Daniel Veillard 已提交
1078
        closelog();
1079
        VIR_FREE(current_ident);
1080
        return -1;
D
Daniel Veillard 已提交
1081
    }
1082
    return 0;
D
Daniel Veillard 已提交
1083
}
D
Daniel P. Berrange 已提交
1084 1085


E
Eric Blake 已提交
1086
# if USE_JOURNALD
1087 1088 1089 1090 1091
#  define IOVEC_SET(iov, data, size)            \
    do {                                        \
        struct iovec *_i = &(iov);              \
        _i->iov_base = (void*)(data);           \
        _i->iov_len = (size);                   \
D
Daniel P. Berrange 已提交
1092 1093
    } while (0)

1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
#  define IOVEC_SET_STRING(iov, str) IOVEC_SET(iov, str, strlen(str))

/* Used for conversion of numbers to strings, and for length of binary data */
#  define JOURNAL_BUF_SIZE (MAX(INT_BUFSIZE_BOUND(int), sizeof(uint64_t)))

struct journalState
{
    struct iovec *iov, *iov_end;
    char (*bufs)[JOURNAL_BUF_SIZE], (*bufs_end)[JOURNAL_BUF_SIZE];
};

static void
journalAddString(struct journalState *state, const char *field,
                 const char *value)
{
    static const char newline = '\n', equals = '=';

    if (strchr(value, '\n') != NULL) {
        uint64_t nstr;

        /* If 'str' contains a newline, then we must
         * encode the string length, since we can't
         * rely on the newline for the field separator
         */
        if (state->iov_end - state->iov < 5 || state->bufs == state->bufs_end)
            return; /* Silently drop */
        nstr = htole64(strlen(value));
        memcpy(state->bufs[0], &nstr, sizeof(nstr));

        IOVEC_SET_STRING(state->iov[0], field);
        IOVEC_SET(state->iov[1], &newline, sizeof(newline));
        IOVEC_SET(state->iov[2], state->bufs[0], sizeof(nstr));
        state->bufs++;
        state->iov += 3;
    } else {
        if (state->iov_end - state->iov < 4)
            return; /* Silently drop */
        IOVEC_SET_STRING(state->iov[0], field);
        IOVEC_SET(state->iov[1], (void *)&equals, sizeof(equals));
        state->iov += 2;
    }
    IOVEC_SET_STRING(state->iov[0], value);
    IOVEC_SET(state->iov[1], (void *)&newline, sizeof(newline));
    state->iov += 2;
}

static void
journalAddInt(struct journalState *state, const char *field, int value)
{
    static const char newline = '\n', equals = '=';

    char *num;

    if (state->iov_end - state->iov < 4 || state->bufs == state->bufs_end)
        return; /* Silently drop */

    num = virFormatIntDecimal(state->bufs[0], sizeof(state->bufs[0]), value);

    IOVEC_SET_STRING(state->iov[0], field);
    IOVEC_SET(state->iov[1], (void *)&equals, sizeof(equals));
    IOVEC_SET_STRING(state->iov[2], num);
    IOVEC_SET(state->iov[3], (void *)&newline, sizeof(newline));
    state->bufs++;
    state->iov += 4;
}
D
Daniel P. Berrange 已提交
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168

static int journalfd = -1;

static void
virLogOutputToJournald(virLogSource source,
                       virLogPriority priority,
                       const char *filename,
                       int linenr,
                       const char *funcname,
                       const char *timestamp ATTRIBUTE_UNUSED,
1169
                       virLogMetadataPtr metadata,
D
Daniel P. Berrange 已提交
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
                       unsigned int flags,
                       const char *rawstr,
                       const char *str ATTRIBUTE_UNUSED,
                       void *data ATTRIBUTE_UNUSED)
{
    virCheckFlags(VIR_LOG_STACK_TRACE,);
    int buffd = -1;
    struct msghdr mh;
    struct sockaddr_un sa;
    union {
        struct cmsghdr cmsghdr;
        uint8_t buf[CMSG_SPACE(sizeof(int))];
    } control;
    struct cmsghdr *cmsg;
    /* We use /dev/shm instead of /tmp here, since we want this to
     * be a tmpfs, and one that is available from early boot on
     * and where unprivileged users can create files. */
    char path[] = "/dev/shm/journal.XXXXXX";
1188
    size_t nmetadata = 0;
D
Daniel P. Berrange 已提交
1189

1190 1191 1192
#  define NUM_FIELDS_CORE 6
#  define NUM_FIELDS_META 5
#  define NUM_FIELDS (NUM_FIELDS_CORE + NUM_FIELDS_META)
1193 1194 1195
    struct iovec iov[NUM_FIELDS * 5];
    char iov_bufs[NUM_FIELDS][JOURNAL_BUF_SIZE];
    struct journalState state;
D
Daniel P. Berrange 已提交
1196

1197 1198 1199 1200
    state.iov = iov;
    state.iov_end = iov + ARRAY_CARDINALITY(iov);
    state.bufs = iov_bufs;
    state.bufs_end = iov_bufs + ARRAY_CARDINALITY(iov_bufs);
D
Daniel P. Berrange 已提交
1201

E
Eric Blake 已提交
1202
    journalAddString(&state, "MESSAGE", rawstr);
1203 1204
    journalAddInt(&state, "PRIORITY",
                  virLogPrioritySyslog(priority));
1205 1206
    journalAddString(&state, "LIBVIRT_SOURCE",
                     virLogSourceTypeToString(source));
1207 1208
    if (filename)
        journalAddString(&state, "CODE_FILE", filename);
1209
    journalAddInt(&state, "CODE_LINE", linenr);
1210 1211
    if (funcname)
        journalAddString(&state, "CODE_FUNC", funcname);
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
    if (metadata != NULL) {
        while (metadata->key != NULL &&
               nmetadata < NUM_FIELDS_META) {
            if (metadata->s != NULL)
                journalAddString(&state, metadata->key, metadata->s);
            else
                journalAddInt(&state, metadata->key, metadata->iv);
            metadata++;
            nmetadata++;
        }
    }
D
Daniel P. Berrange 已提交
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232

    memset(&sa, 0, sizeof(sa));
    sa.sun_family = AF_UNIX;
    if (!virStrcpy(sa.sun_path, "/run/systemd/journal/socket", sizeof(sa.sun_path)))
        return;

    memset(&mh, 0, sizeof(mh));
    mh.msg_name = &sa;
    mh.msg_namelen = offsetof(struct sockaddr_un, sun_path) + strlen(sa.sun_path);
    mh.msg_iov = iov;
1233
    mh.msg_iovlen = state.iov - iov;
D
Daniel P. Berrange 已提交
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256

    if (sendmsg(journalfd, &mh, MSG_NOSIGNAL) >= 0)
        return;

    if (errno != EMSGSIZE && errno != ENOBUFS)
        return;

    /* Message was too large, so dump to temporary file
     * and pass an FD to the journal
     */

    /* NB: mkostemp is not declared async signal safe by
     * POSIX, but this is Linux only code and the GLibc
     * impl is safe enough, only using open() and inline
     * asm to read a timestamp (falling back to gettimeofday
     * on some arches
     */
    if ((buffd = mkostemp(path, O_CLOEXEC|O_RDWR)) < 0)
        return;

    if (unlink(path) < 0)
        goto cleanup;

1257
    if (writev(buffd, iov, state.iov - iov) < 0)
D
Daniel P. Berrange 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
        goto cleanup;

    mh.msg_iov = NULL;
    mh.msg_iovlen = 0;

    memset(&control, 0, sizeof(control));
    mh.msg_control = &control;
    mh.msg_controllen = sizeof(control);

    cmsg = CMSG_FIRSTHDR(&mh);
    cmsg->cmsg_level = SOL_SOCKET;
    cmsg->cmsg_type = SCM_RIGHTS;
    cmsg->cmsg_len = CMSG_LEN(sizeof(int));
    memcpy(CMSG_DATA(cmsg), &buffd, sizeof(int));

    mh.msg_controllen = cmsg->cmsg_len;

    sendmsg(journalfd, &mh, MSG_NOSIGNAL);

cleanup:
    VIR_LOG_CLOSE(buffd);
}


static void virLogCloseJournald(void *data ATTRIBUTE_UNUSED)
{
    VIR_LOG_CLOSE(journalfd);
}


static int virLogAddOutputToJournald(int priority)
{
    if ((journalfd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0)
        return -1;
    if (virSetInherit(journalfd, false) < 0) {
        VIR_LOG_CLOSE(journalfd);
        return -1;
    }
    if (virLogDefineOutput(virLogOutputToJournald, virLogCloseJournald, NULL,
                           priority, VIR_LOG_TO_JOURNALD, NULL, 0) < 0) {
        return -1;
    }
    return 0;
}
E
Eric Blake 已提交
1302
# endif /* USE_JOURNALD */
J
Ján Tomko 已提交
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327

int virLogPriorityFromSyslog(int priority)
{
    switch (priority) {
    case LOG_EMERG:
    case LOG_ALERT:
    case LOG_CRIT:
    case LOG_ERR:
        return VIR_LOG_ERROR;
    case LOG_WARNING:
    case LOG_NOTICE:
        return VIR_LOG_WARN;
    case LOG_INFO:
        return VIR_LOG_INFO;
    case LOG_DEBUG:
        return VIR_LOG_DEBUG;
    }
    return VIR_LOG_ERROR;
}

#else /* HAVE_SYSLOG_H */
int virLogPriorityFromSyslog(int priority ATTRIBUTE_UNUSED)
{
    return VIR_LOG_ERROR;
}
D
Daniel Veillard 已提交
1328 1329 1330 1331 1332 1333
#endif /* HAVE_SYSLOG_H */

#define IS_SPACE(cur)                                                   \
    ((*cur == ' ') || (*cur == '\t') || (*cur == '\n') ||               \
     (*cur == '\r') || (*cur == '\\'))

1334

D
Daniel Veillard 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
/**
 * virLogParseOutputs:
 * @outputs: string defining a (set of) output(s)
 *
 * The format for an output can be:
 *    x:stderr
 *       output goes to stderr
 *    x:syslog:name
 *       use syslog for the output and use the given name as the ident
 *    x:file:file_path
 *       output to a file, with the given filepath
 * In all case the x prefix is the minimal level, acting as a filter
 *    1: DEBUG
 *    2: INFO
 *    3: WARNING
 *    4: ERROR
 *
 * Multiple output can be defined in a single @output, they just need to be
 * separated by spaces.
 *
1355 1356 1357
 * If running in setuid mode, then only the 'stderr' output will
 * be allowed
 *
D
Daniel Veillard 已提交
1358 1359
 * Returns the number of output parsed and installed or -1 in case of error
 */
1360 1361 1362
int
virLogParseOutputs(const char *outputs)
{
D
Daniel Veillard 已提交
1363 1364
    const char *cur = outputs, *str;
    char *name;
1365
    char *abspath;
1366
    virLogPriority prio;
1367 1368
    int ret = -1;
    int count = 0;
1369
    bool isSUID = virIsSUID();
D
Daniel Veillard 已提交
1370 1371

    if (cur == NULL)
1372
        return -1;
D
Daniel Veillard 已提交
1373

1374 1375
    VIR_DEBUG("outputs=%s", outputs);

D
Daniel Veillard 已提交
1376 1377
    virSkipSpaces(&cur);
    while (*cur != 0) {
1378
        prio = virParseNumber(&cur);
1379
        if ((prio < VIR_LOG_DEBUG) || (prio > VIR_LOG_ERROR))
1380
            goto cleanup;
D
Daniel Veillard 已提交
1381
        if (*cur != ':')
1382
            goto cleanup;
D
Daniel Veillard 已提交
1383 1384 1385 1386
        cur++;
        if (STREQLEN(cur, "stderr", 6)) {
            cur += 6;
            if (virLogAddOutputToStderr(prio) == 0)
1387
                count++;
D
Daniel Veillard 已提交
1388
        } else if (STREQLEN(cur, "syslog", 6)) {
1389 1390
            if (isSUID)
                goto cleanup;
D
Daniel Veillard 已提交
1391 1392
            cur += 6;
            if (*cur != ':')
1393
                goto cleanup;
D
Daniel Veillard 已提交
1394 1395 1396 1397 1398
            cur++;
            str = cur;
            while ((*cur != 0) && (!IS_SPACE(cur)))
                cur++;
            if (str == cur)
1399
                goto cleanup;
D
Daniel Veillard 已提交
1400
#if HAVE_SYSLOG_H
1401
            if (VIR_STRNDUP(name, str, cur - str) < 0)
1402
                goto cleanup;
D
Daniel Veillard 已提交
1403
            if (virLogAddOutputToSyslog(prio, name) == 0)
1404
                count++;
D
Daniel Veillard 已提交
1405 1406 1407
            VIR_FREE(name);
#endif /* HAVE_SYSLOG_H */
        } else if (STREQLEN(cur, "file", 4)) {
1408 1409
            if (isSUID)
                goto cleanup;
D
Daniel Veillard 已提交
1410 1411
            cur += 4;
            if (*cur != ':')
1412
                goto cleanup;
D
Daniel Veillard 已提交
1413 1414 1415 1416 1417
            cur++;
            str = cur;
            while ((*cur != 0) && (!IS_SPACE(cur)))
                cur++;
            if (str == cur)
1418
                goto cleanup;
1419
            if (VIR_STRNDUP(name, str, cur - str) < 0)
1420
                goto cleanup;
1421 1422 1423 1424 1425
            if (virFileAbsPath(name, &abspath) < 0) {
                VIR_FREE(name);
                return -1; /* skip warning here because setting was fine */
            }
            if (virLogAddOutputToFile(prio, abspath) == 0)
1426
                count++;
D
Daniel Veillard 已提交
1427
            VIR_FREE(name);
1428
            VIR_FREE(abspath);
D
Daniel P. Berrange 已提交
1429
        } else if (STREQLEN(cur, "journald", 8)) {
1430 1431
            if (isSUID)
                goto cleanup;
D
Daniel P. Berrange 已提交
1432
            cur += 8;
E
Eric Blake 已提交
1433
#if USE_JOURNALD
D
Daniel P. Berrange 已提交
1434 1435
            if (virLogAddOutputToJournald(prio) == 0)
                count++;
E
Eric Blake 已提交
1436
#endif /* USE_JOURNALD */
D
Daniel Veillard 已提交
1437
        } else {
1438
            goto cleanup;
D
Daniel Veillard 已提交
1439 1440 1441
        }
        virSkipSpaces(&cur);
    }
1442 1443 1444
    ret = count;
cleanup:
    if (ret == -1)
1445
        VIR_WARN("Ignoring invalid log output setting.");
1446
    return ret;
D
Daniel Veillard 已提交
1447 1448
}

1449

D
Daniel Veillard 已提交
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
/**
 * virLogParseFilters:
 * @filters: string defining a (set of) filter(s)
 *
 * The format for a filter is:
 *    x:name
 *       where name is a match string
 * the x prefix is the minimal level where the messages should be logged
 *    1: DEBUG
 *    2: INFO
 *    3: WARNING
 *    4: ERROR
 *
 * Multiple filter can be defined in a single @filters, they just need to be
 * separated by spaces.
 *
 * Returns the number of filter parsed and installed or -1 in case of error
 */
1468 1469 1470
int
virLogParseFilters(const char *filters)
{
D
Daniel Veillard 已提交
1471 1472
    const char *cur = filters, *str;
    char *name;
1473
    virLogPriority prio;
1474 1475
    int ret = -1;
    int count = 0;
D
Daniel Veillard 已提交
1476 1477

    if (cur == NULL)
1478
        return -1;
D
Daniel Veillard 已提交
1479 1480 1481

    virSkipSpaces(&cur);
    while (*cur != 0) {
1482
        unsigned int flags = 0;
1483
        prio = virParseNumber(&cur);
1484
        if ((prio < VIR_LOG_DEBUG) || (prio > VIR_LOG_ERROR))
1485
            goto cleanup;
D
Daniel Veillard 已提交
1486
        if (*cur != ':')
1487
            goto cleanup;
D
Daniel Veillard 已提交
1488
        cur++;
1489 1490 1491 1492
        if (*cur == '+') {
            flags |= VIR_LOG_STACK_TRACE;
            cur++;
        }
D
Daniel Veillard 已提交
1493 1494 1495 1496
        str = cur;
        while ((*cur != 0) && (!IS_SPACE(cur)))
            cur++;
        if (str == cur)
1497
            goto cleanup;
1498
        if (VIR_STRNDUP(name, str, cur - str) < 0)
1499
            goto cleanup;
1500
        if (virLogDefineFilter(name, prio, flags) >= 0)
1501
            count++;
D
Daniel Veillard 已提交
1502 1503 1504
        VIR_FREE(name);
        virSkipSpaces(&cur);
    }
1505 1506 1507
    ret = count;
cleanup:
    if (ret == -1)
1508
        VIR_WARN("Ignoring invalid log filter setting.");
1509
    return ret;
D
Daniel Veillard 已提交
1510
}
1511

1512

1513 1514 1515 1516 1517
/**
 * virLogGetDefaultPriority:
 *
 * Returns the current logging priority level.
 */
1518 1519 1520
virLogPriority
virLogGetDefaultPriority(void)
{
1521
    return virLogDefaultPriority;
1522 1523
}

1524

1525 1526 1527 1528 1529 1530 1531
/**
 * virLogGetFilters:
 *
 * Returns a string listing the current filters, in the format originally
 * specified in the config file or environment. Caller must free the
 * result.
 */
1532 1533 1534
char *
virLogGetFilters(void)
{
1535
    size_t i;
1536 1537 1538 1539
    virBuffer filterbuf = VIR_BUFFER_INITIALIZER;

    virLogLock();
    for (i = 0; i < virLogNbFilters; i++) {
1540 1541 1542 1543 1544 1545
        const char *sep = ":";
        if (virLogFilters[i].flags & VIR_LOG_STACK_TRACE)
            sep = ":+";
        virBufferAsprintf(&filterbuf, "%d%s%s ",
                          virLogFilters[i].priority,
                          sep,
1546 1547 1548 1549
                          virLogFilters[i].match);
    }
    virLogUnlock();

1550 1551
    if (virBufferError(&filterbuf)) {
        virBufferFreeAndReset(&filterbuf);
1552
        return NULL;
1553
    }
1554 1555 1556 1557

    return virBufferContentAndReset(&filterbuf);
}

1558

1559 1560 1561 1562 1563 1564 1565
/**
 * virLogGetOutputs:
 *
 * Returns a string listing the current outputs, in the format originally
 * specified in the config file or environment. Caller must free the
 * result.
 */
1566 1567 1568
char *
virLogGetOutputs(void)
{
1569
    size_t i;
1570 1571 1572 1573
    virBuffer outputbuf = VIR_BUFFER_INITIALIZER;

    virLogLock();
    for (i = 0; i < virLogNbOutputs; i++) {
1574
        virLogDestination dest = virLogOutputs[i].dest;
1575
        if (i)
1576
            virBufferAddChar(&outputbuf, ' ');
1577 1578 1579
        switch (dest) {
            case VIR_LOG_TO_SYSLOG:
            case VIR_LOG_TO_FILE:
1580
                virBufferAsprintf(&outputbuf, "%d:%s:%s",
1581 1582 1583 1584 1585
                                  virLogOutputs[i].priority,
                                  virLogOutputString(dest),
                                  virLogOutputs[i].name);
                break;
            default:
1586
                virBufferAsprintf(&outputbuf, "%d:%s",
1587 1588 1589 1590 1591 1592
                                  virLogOutputs[i].priority,
                                  virLogOutputString(dest));
        }
    }
    virLogUnlock();

1593 1594
    if (virBufferError(&outputbuf)) {
        virBufferFreeAndReset(&outputbuf);
1595
        return NULL;
1596
    }
1597 1598 1599 1600

    return virBufferContentAndReset(&outputbuf);
}

1601

1602 1603 1604 1605 1606
/**
 * virLogGetNbFilters:
 *
 * Returns the current number of defined log filters.
 */
1607 1608 1609
int
virLogGetNbFilters(void)
{
1610
    return virLogNbFilters;
1611 1612
}

1613

1614 1615 1616 1617 1618
/**
 * virLogGetNbOutputs:
 *
 * Returns the current number of defined log outputs.
 */
1619 1620 1621
int
virLogGetNbOutputs(void)
{
1622
    return virLogNbOutputs;
1623
}
1624

1625

1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
/**
 * virLogParseDefaultPriority:
 * @priority: string defining the desired logging level
 *
 * Parses and sets the default log priority level. It can take a string or
 * number corresponding to the following levels:
 *    1: DEBUG
 *    2: INFO
 *    3: WARNING
 *    4: ERROR
 *
 * Returns the parsed log level or -1 on error.
 */
1639 1640 1641
int
virLogParseDefaultPriority(const char *priority)
{
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
    int ret = -1;

    if (STREQ(priority, "1") || STREQ(priority, "debug"))
        ret = virLogSetDefaultPriority(VIR_LOG_DEBUG);
    else if (STREQ(priority, "2") || STREQ(priority, "info"))
        ret = virLogSetDefaultPriority(VIR_LOG_INFO);
    else if (STREQ(priority, "3") || STREQ(priority, "warning"))
        ret = virLogSetDefaultPriority(VIR_LOG_WARN);
    else if (STREQ(priority, "4") || STREQ(priority, "error"))
        ret = virLogSetDefaultPriority(VIR_LOG_ERROR);
    else
1653
        VIR_WARN("Ignoring invalid log level setting");
1654 1655 1656 1657

    return ret;
}

1658

1659 1660 1661 1662 1663 1664
/**
 * virLogSetFromEnv:
 *
 * Sets virLogDefaultPriority, virLogFilters and virLogOutputs based on
 * environment variables.
 */
1665 1666 1667
void
virLogSetFromEnv(void)
{
1668
    const char *debugEnv;
1669

1670 1671 1672
    if (virLogInitialize() < 0)
        return;

1673
    debugEnv = virGetEnvAllowSUID("LIBVIRT_DEBUG");
1674 1675
    if (debugEnv && *debugEnv)
        virLogParseDefaultPriority(debugEnv);
1676
    debugEnv = virGetEnvAllowSUID("LIBVIRT_LOG_FILTERS");
1677
    if (debugEnv && *debugEnv)
1678
        virLogParseFilters(debugEnv);
1679
    debugEnv = virGetEnvAllowSUID("LIBVIRT_LOG_OUTPUTS");
1680
    if (debugEnv && *debugEnv)
1681
        virLogParseOutputs(debugEnv);
1682
}
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698


/*
 * Returns a true value if the first line in @str is
 * probably a log message generated by the libvirt
 * logging layer
 */
bool virLogProbablyLogMessage(const char *str)
{
    bool ret = false;
    if (!virLogRegex)
        return false;
    if (regexec(virLogRegex, str, 0, NULL, 0) == 0)
        ret = true;
    return ret;
}