logging.c 39.9 KB
Newer Older
1 2 3
/*
 * logging.c: internal logging and debugging
 *
4
 * Copyright (C) 2008, 2010-2012 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>
D
Daniel Veillard 已提交
35
#if HAVE_SYSLOG_H
36
# include <syslog.h>
D
Daniel Veillard 已提交
37
#endif
D
Daniel P. Berrange 已提交
38 39 40 41
#include <sys/socket.h>
#if HAVE_SYS_UN_H
# include <sys/un.h>
#endif
D
Daniel Veillard 已提交
42

43
#include "virterror_internal.h"
44
#include "logging.h"
D
Daniel Veillard 已提交
45 46
#include "memory.h"
#include "util.h"
47
#include "buf.h"
48
#include "threads.h"
E
Eric Blake 已提交
49
#include "virfile.h"
50
#include "virtime.h"
D
Daniel P. Berrange 已提交
51
#include "intprops.h"
52

E
Eric Blake 已提交
53 54 55 56 57 58
/* 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

59 60
#define VIR_FROM_THIS VIR_FROM_NONE

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

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

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

/*
 * Filters are used to refine the rules on what to keep or drop
 * based on a matching pattern (currently a substring)
 */
struct _virLogFilter {
    const char *match;
85
    virLogPriority priority;
86
    unsigned int flags;
D
Daniel Veillard 已提交
87 88 89 90 91 92 93 94 95 96 97 98
};
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 {
99
    bool logVersion;
D
Daniel Veillard 已提交
100 101 102
    void *data;
    virLogOutputFunc f;
    virLogCloseFunc c;
103
    virLogPriority priority;
104 105
    virLogDestination dest;
    const char *name;
D
Daniel Veillard 已提交
106 107 108 109 110 111 112 113 114 115
};
typedef struct _virLogOutput virLogOutput;
typedef virLogOutput *virLogOutputPtr;

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

/*
 * Default priorities
 */
116
static virLogPriority virLogDefaultPriority = VIR_LOG_DEFAULT;
D
Daniel Veillard 已提交
117 118 119

static int virLogResetFilters(void);
static int virLogResetOutputs(void);
120
static void virLogOutputToFd(virLogSource src,
121
                             virLogPriority priority,
122
                             const char *filename,
123
                             int linenr,
124
                             const char *funcname,
125 126
                             const char *timestamp,
                             unsigned int flags,
127 128
                             const char *rawstr,
                             const char *str,
129
                             void *data);
D
Daniel Veillard 已提交
130 131 132 133

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

136 137
void
virLogLock(void)
D
Daniel Veillard 已提交
138
{
139
    virMutexLock(&virLogMutex);
D
Daniel Veillard 已提交
140
}
141 142 143 144


void
virLogUnlock(void)
D
Daniel Veillard 已提交
145
{
146
    virMutexUnlock(&virLogMutex);
D
Daniel Veillard 已提交
147 148
}

149 150 151 152

static const char *
virLogOutputString(virLogDestination ldest)
{
153
    switch (ldest) {
154 155 156 157 158 159
    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 已提交
160 161
    case VIR_LOG_TO_JOURNALD:
        return "journald";
162
    }
163
    return "unknown";
164
}
D
Daniel Veillard 已提交
165

166 167 168 169

static const char *
virLogPriorityString(virLogPriority lvl)
{
D
Daniel Veillard 已提交
170
    switch (lvl) {
171 172 173 174 175 176 177 178
    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 已提交
179
    }
180
    return "unknown";
D
Daniel Veillard 已提交
181 182 183
}


184 185
static int
virLogOnceInit(void)
186
{
187 188
    const char *pbm = NULL;

189 190 191
    if (virMutexInit(&virLogMutex) < 0)
        return -1;

D
Daniel Veillard 已提交
192
    virLogLock();
193
    if (VIR_ALLOC_N(virLogBuffer, virLogSize + 1) < 0) {
194 195 196 197 198 199
        /*
         * 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;
200
        if (VIR_ALLOC_N(virLogBuffer, virLogSize + 1) < 0) {
201 202 203 204 205 206
            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 已提交
207 208 209
    virLogLen = 0;
    virLogStart = 0;
    virLogEnd = 0;
210
    virLogDefaultPriority = VIR_LOG_DEFAULT;
D
Daniel Veillard 已提交
211
    virLogUnlock();
212
    if (pbm)
213
        VIR_WARN("%s", pbm);
214
    return 0;
D
Daniel Veillard 已提交
215 216
}

217 218
VIR_ONCE_GLOBAL_INIT(virLog)

219

220 221 222 223 224 225 226 227 228 229
/**
 * 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
 */
230 231 232
int
virLogSetBufferSize(int size)
{
233 234 235 236 237 238 239 240
    int ret = 0;
    int oldsize;
    char *oldLogBuffer;
    const char *pbm = NULL;

    if (size < 0)
        size = 0;

241 242 243 244
    if (virLogInitialize() < 0)
        return -1;

    if (size * 1024 == virLogSize)
245 246 247 248 249 250 251
        return ret;

    virLogLock();

    oldsize = virLogSize;
    oldLogBuffer = virLogBuffer;

252
    if (INT_MAX / 1024 <= size) {
253 254 255 256 257 258
        pbm = "Requested log size of %d kB too large\n";
        ret = -1;
        goto error;
    }

    virLogSize = size * 1024;
259
    if (VIR_ALLOC_N(virLogBuffer, virLogSize + 1) < 0) {
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
        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;
}

278

D
Daniel Veillard 已提交
279 280 281 282 283 284 285
/**
 * virLogReset:
 *
 * Reset the logging module to its default initial state
 *
 * Returns 0 if successful, and -1 in case or error
 */
286 287 288
int
virLogReset(void)
{
289 290
    if (virLogInitialize() < 0)
        return -1;
D
Daniel Veillard 已提交
291 292 293 294 295 296 297

    virLogLock();
    virLogResetFilters();
    virLogResetOutputs();
    virLogLen = 0;
    virLogStart = 0;
    virLogEnd = 0;
298
    virLogDefaultPriority = VIR_LOG_DEFAULT;
D
Daniel Veillard 已提交
299
    virLogUnlock();
300
    return 0;
D
Daniel Veillard 已提交
301 302
}

303

D
Daniel Veillard 已提交
304 305 306
/*
 * Store a string in the ring buffer
 */
307 308
static void
virLogStr(const char *str)
309
{
D
Daniel Veillard 已提交
310
    int tmp;
311
    int len;
D
Daniel Veillard 已提交
312

313
    if ((str == NULL) || (virLogBuffer == NULL) || (virLogSize <= 0))
D
Daniel Veillard 已提交
314
        return;
315
    len = strlen(str);
E
Eric Blake 已提交
316
    if (len >= virLogSize)
D
Daniel Veillard 已提交
317 318 319 320 321
        return;

    /*
     * copy the data and reset the end, we cycle over the end of the buffer
     */
322 323
    if (virLogEnd + len >= virLogSize) {
        tmp = virLogSize - virLogEnd;
D
Daniel Veillard 已提交
324
        memcpy(&virLogBuffer[virLogEnd], str, tmp);
325
        memcpy(&virLogBuffer[0], &str[tmp], len - tmp);
D
Daniel Veillard 已提交
326 327 328 329 330
        virLogEnd = len - tmp;
    } else {
        memcpy(&virLogBuffer[virLogEnd], str, len);
        virLogEnd += len;
    }
E
Eric Blake 已提交
331
    virLogBuffer[virLogEnd] = 0;
D
Daniel Veillard 已提交
332 333 334 335
    /*
     * Update the log length, and if full move the start index
     */
    virLogLen += len;
336 337 338
    if (virLogLen > virLogSize) {
        tmp = virLogLen - virLogSize;
        virLogLen = virLogSize;
D
Daniel Veillard 已提交
339
        virLogStart += tmp;
340 341
        if (virLogStart >= virLogSize)
            virLogStart -= virLogSize;
D
Daniel Veillard 已提交
342 343 344
    }
}

345 346 347 348

static void
virLogDumpAllFD(const char *msg, int len)
{
349 350
    int i, found = 0;

351 352 353
    if (len <= 0)
        len = strlen(msg);

354 355
    for (i = 0; i < virLogNbOutputs;i++) {
        if (virLogOutputs[i].f == virLogOutputToFd) {
356
            int fd = (intptr_t) virLogOutputs[i].data;
357 358

            if (fd >= 0) {
359
                ignore_value(safewrite(fd, msg, len));
360 361 362 363 364
                found = 1;
            }
        }
    }
    if (!found)
365
        ignore_value(safewrite(STDERR_FILENO, msg, len));
366 367
}

368

369 370 371 372 373 374 375 376
/**
 * 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 已提交
377
 */
378
void
379 380
virLogEmergencyDumpAll(int signum)
{
381
    int len;
C
Christophe Fergeau 已提交
382
    int oldLogStart, oldLogLen;
D
Daniel Veillard 已提交
383

384
    switch (signum) {
D
Daniel Veillard 已提交
385
#ifdef SIGFPE
386
        case SIGFPE:
387
            virLogDumpAllFD("Caught signal Floating-point exception", -1);
388
            break;
D
Daniel Veillard 已提交
389 390
#endif
#ifdef SIGSEGV
391
        case SIGSEGV:
392
            virLogDumpAllFD("Caught Segmentation violation", -1);
393
            break;
D
Daniel Veillard 已提交
394 395
#endif
#ifdef SIGILL
396
        case SIGILL:
397
            virLogDumpAllFD("Caught illegal instruction", -1);
398
            break;
D
Daniel Veillard 已提交
399 400
#endif
#ifdef SIGABRT
401
        case SIGABRT:
402
            virLogDumpAllFD("Caught abort signal", -1);
403
            break;
D
Daniel Veillard 已提交
404 405
#endif
#ifdef SIGBUS
406
        case SIGBUS:
407
            virLogDumpAllFD("Caught bus error", -1);
408
            break;
D
Daniel Veillard 已提交
409 410
#endif
#ifdef SIGUSR2
411
        case SIGUSR2:
412
            virLogDumpAllFD("Caught User-defined signal 2", -1);
413
            break;
D
Daniel Veillard 已提交
414
#endif
415
        default:
416
            virLogDumpAllFD("Caught unexpected signal", -1);
417 418
            break;
    }
419 420
    if ((virLogBuffer == NULL) || (virLogSize <= 0)) {
        virLogDumpAllFD(" internal log buffer deactivated\n", -1);
421
        return;
422
    }
423

424 425
    virLogDumpAllFD(" dumping internal log buffer:\n", -1);
    virLogDumpAllFD("\n\n    ====== start of log =====\n\n", -1);
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447

    /*
     * 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 已提交
448
        } else {
449
            len = virLogSize - oldLogStart;
450
            virLogBuffer[virLogSize] = 0;
451 452 453
            virLogDumpAllFD(&virLogBuffer[oldLogStart], len);
            oldLogLen -= len;
            oldLogStart = 0;
D
Daniel Veillard 已提交
454 455
        }
    }
456
    virLogDumpAllFD("\n\n     ====== end of log =====\n\n", -1);
D
Daniel Veillard 已提交
457
}
458

459

D
Daniel Veillard 已提交
460 461 462 463 464 465 466 467 468 469
/**
 * 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.
 */
470 471 472
int
virLogSetDefaultPriority(virLogPriority priority)
{
473
    if ((priority < VIR_LOG_DEBUG) || (priority > VIR_LOG_ERROR)) {
474
        VIR_WARN("Ignoring invalid log level setting.");
475
        return -1;
476
    }
477 478 479
    if (virLogInitialize() < 0)
        return -1;

D
Daniel Veillard 已提交
480
    virLogDefaultPriority = priority;
481
    return 0;
D
Daniel Veillard 已提交
482 483
}

484

D
Daniel Veillard 已提交
485 486 487 488 489 490 491
/**
 * virLogResetFilters:
 *
 * Removes the set of logging filters defined.
 *
 * Returns the number of filters removed
 */
492 493 494
static int
virLogResetFilters(void)
{
D
Daniel Veillard 已提交
495 496 497 498 499 500
    int i;

    for (i = 0; i < virLogNbFilters;i++)
        VIR_FREE(virLogFilters[i].match);
    VIR_FREE(virLogFilters);
    virLogNbFilters = 0;
501
    return i;
D
Daniel Veillard 已提交
502 503
}

504

D
Daniel Veillard 已提交
505 506 507 508
/**
 * virLogDefineFilter:
 * @match: the pattern to match
 * @priority: the priority to give to messages matching the pattern
509
 * @flags: extra flags, see virLogFilterFlags enum
D
Daniel Veillard 已提交
510 511 512 513 514 515 516 517
 *
 * 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
 */
518 519 520 521
int
virLogDefineFilter(const char *match,
                   virLogPriority priority,
                   unsigned int flags)
522
{
D
Daniel Veillard 已提交
523 524 525
    int i;
    char *mdup = NULL;

526
    virCheckFlags(VIR_LOG_STACK_TRACE, -1);
527

D
Daniel Veillard 已提交
528 529
    if ((match == NULL) || (priority < VIR_LOG_DEBUG) ||
        (priority > VIR_LOG_ERROR))
530
        return -1;
D
Daniel Veillard 已提交
531 532 533 534 535 536 537 538 539 540

    virLogLock();
    for (i = 0;i < virLogNbFilters;i++) {
        if (STREQ(virLogFilters[i].match, match)) {
            virLogFilters[i].priority = priority;
            goto cleanup;
        }
    }

    mdup = strdup(match);
541
    if (mdup == NULL) {
D
Daniel Veillard 已提交
542 543 544 545 546 547 548 549 550 551 552
        i = -1;
        goto cleanup;
    }
    i = virLogNbFilters;
    if (VIR_REALLOC_N(virLogFilters, virLogNbFilters + 1)) {
        i = -1;
        VIR_FREE(mdup);
        goto cleanup;
    }
    virLogFilters[i].match = mdup;
    virLogFilters[i].priority = priority;
553
    virLogFilters[i].flags = flags;
D
Daniel Veillard 已提交
554 555 556
    virLogNbFilters++;
cleanup:
    virLogUnlock();
557
    return i;
D
Daniel Veillard 已提交
558 559
}

560

D
Daniel Veillard 已提交
561 562 563 564 565 566 567 568 569 570
/**
 * 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.
 */
571 572 573 574
static int
virLogFiltersCheck(const char *input,
                   unsigned int *flags)
{
D
Daniel Veillard 已提交
575 576 577 578 579 580 581
    int ret = 0;
    int i;

    virLogLock();
    for (i = 0;i < virLogNbFilters;i++) {
        if (strstr(input, virLogFilters[i].match)) {
            ret = virLogFilters[i].priority;
582
            *flags = virLogFilters[i].flags;
D
Daniel Veillard 已提交
583 584 585 586
            break;
        }
    }
    virLogUnlock();
587
    return ret;
D
Daniel Veillard 已提交
588 589
}

590

D
Daniel Veillard 已提交
591 592 593 594 595 596 597
/**
 * virLogResetOutputs:
 *
 * Removes the set of logging output defined.
 *
 * Returns the number of output removed
 */
598 599 600
static int
virLogResetOutputs(void)
{
D
Daniel Veillard 已提交
601 602 603 604 605
    int i;

    for (i = 0;i < virLogNbOutputs;i++) {
        if (virLogOutputs[i].c != NULL)
            virLogOutputs[i].c(virLogOutputs[i].data);
606
        VIR_FREE(virLogOutputs[i].name);
D
Daniel Veillard 已提交
607 608 609 610
    }
    VIR_FREE(virLogOutputs);
    i = virLogNbOutputs;
    virLogNbOutputs = 0;
611
    return i;
D
Daniel Veillard 已提交
612 613
}

614

D
Daniel Veillard 已提交
615 616 617
/**
 * virLogDefineOutput:
 * @f: the function to call to output a message
618
 * @c: the function to call to close the output (or NULL)
D
Daniel Veillard 已提交
619 620
 * @data: extra data passed as first arg to the function
 * @priority: minimal priority for this filter, use 0 for none
621 622
 * @dest: where to send output of this priority
 * @name: optional name data associated with an output
D
Daniel Veillard 已提交
623 624 625 626 627 628 629
 * @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
 */
630 631 632 633 634 635 636 637
int
virLogDefineOutput(virLogOutputFunc f,
                   virLogCloseFunc c,
                   void *data,
                   virLogPriority priority,
                   virLogDestination dest,
                   const char *name,
                   unsigned int flags)
638
{
D
Daniel Veillard 已提交
639
    int ret = -1;
640
    char *ndup = NULL;
D
Daniel Veillard 已提交
641

642 643
    virCheckFlags(0, -1);

D
Daniel Veillard 已提交
644
    if (f == NULL)
645
        return -1;
D
Daniel Veillard 已提交
646

647 648
    if (dest == VIR_LOG_TO_SYSLOG || dest == VIR_LOG_TO_FILE) {
        if (name == NULL)
649
            return -1;
650 651
        ndup = strdup(name);
        if (ndup == NULL)
652
            return -1;
653 654
    }

D
Daniel Veillard 已提交
655 656
    virLogLock();
    if (VIR_REALLOC_N(virLogOutputs, virLogNbOutputs + 1)) {
657
        VIR_FREE(ndup);
D
Daniel Veillard 已提交
658 659 660
        goto cleanup;
    }
    ret = virLogNbOutputs++;
661
    virLogOutputs[ret].logVersion = true;
D
Daniel Veillard 已提交
662 663 664 665
    virLogOutputs[ret].f = f;
    virLogOutputs[ret].c = c;
    virLogOutputs[ret].data = data;
    virLogOutputs[ret].priority = priority;
666 667
    virLogOutputs[ret].dest = dest;
    virLogOutputs[ret].name = ndup;
D
Daniel Veillard 已提交
668 669
cleanup:
    virLogUnlock();
670
    return ret;
D
Daniel Veillard 已提交
671 672
}

673

674 675
static int
virLogFormatString(char **msg,
676
                   int linenr,
677
                   const char *funcname,
678
                   virLogPriority priority,
679 680 681
                   const char *str)
{
    int ret;
682 683 684 685 686 687 688 689

    /*
     * 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.
     */
690
    if ((funcname != NULL)) {
691
        ret = virAsprintf(msg, "%d: %s : %s:%d : %s\n",
692 693
                          virThreadSelfID(), virLogPriorityString(priority),
                          funcname, linenr, str);
694
    } else {
695 696 697
        ret = virAsprintf(msg, "%d: %s : %s\n",
                          virThreadSelfID(), virLogPriorityString(priority),
                          str);
698 699 700 701
    }
    return ret;
}

702

703
static int
704 705
virLogVersionString(const char **rawmsg,
                    char **msg)
706 707 708 709 710 711 712 713 714 715 716 717 718 719
{
#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

720
    *rawmsg = LOG_VERSION_STRING;
721
    return virLogFormatString(msg, 0, NULL, VIR_LOG_INFO, LOG_VERSION_STRING);
722 723
}

724

D
Daniel Veillard 已提交
725 726
/**
 * virLogMessage:
727
 * @source: where is that message coming from
D
Daniel Veillard 已提交
728
 * @priority: the priority level
729
 * @filename: file where the message was emitted
730
 * @linenr: line where the message was emitted
731
 * @funcname: the function emitting the (debug) message
732
 * @metadata: NULL or metadata array, terminated by an item with NULL key
D
Daniel Veillard 已提交
733 734 735
 * @fmt: the string format
 * @...: the arguments
 *
E
Eric Blake 已提交
736
 * Call the libvirt logger with some information. Based on the configuration
D
Daniel Veillard 已提交
737 738
 * the message may be stored, sent to output or just discarded
 */
739
void
740
virLogMessage(virLogSource source,
741
              virLogPriority priority,
742
              const char *filename,
743
              int linenr,
744
              const char *funcname,
745
              virLogMetadataPtr metadata,
746
              const char *fmt, ...)
747 748 749
{
    va_list ap;
    va_start(ap, fmt);
750
    virLogVMessage(source, priority,
751
                   filename, linenr, funcname,
752
                   metadata, fmt, ap);
753 754 755
    va_end(ap);
}

756

757 758
/**
 * virLogVMessage:
759
 * @source: where is that message coming from
760
 * @priority: the priority level
761
 * @filename: file where the message was emitted
762
 * @linenr: line where the message was emitted
763
 * @funcname: the function emitting the (debug) message
764
 * @metadata: NULL or metadata array, terminated by an item with NULL key
765 766 767 768 769 770
 * @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
 */
771
void
772
virLogVMessage(virLogSource source,
773
               virLogPriority priority,
774
               const char *filename,
775
               int linenr,
776
               const char *funcname,
777
               virLogMetadataPtr metadata ATTRIBUTE_UNUSED,
778 779
               const char *fmt,
               va_list vargs)
780
{
781
    static bool logVersionStderr = true;
D
Daniel Veillard 已提交
782
    char *str = NULL;
783
    char *msg = NULL;
784
    char timestamp[VIR_TIME_STRING_BUFLEN];
785
    int fprio, i, ret;
786
    int saved_errno = errno;
787
    int emit = 1;
788
    unsigned int filterflags = 0;
D
Daniel Veillard 已提交
789

790 791
    if (virLogInitialize() < 0)
        return;
D
Daniel Veillard 已提交
792 793

    if (fmt == NULL)
794
        goto cleanup;
D
Daniel Veillard 已提交
795 796 797 798

    /*
     * check against list of specific logging patterns
     */
799
    fprio = virLogFiltersCheck(filename, &filterflags);
D
Daniel Veillard 已提交
800 801
    if (fprio == 0) {
        if (priority < virLogDefaultPriority)
802
            emit = 0;
803
    } else if (priority < fprio) {
804
        emit = 0;
805
    }
D
Daniel Veillard 已提交
806

807 808 809
    if ((emit == 0) && ((virLogBuffer == NULL) || (virLogSize <= 0)))
        goto cleanup;

D
Daniel Veillard 已提交
810 811 812
    /*
     * serialize the error message, add level and timestamp
     */
813
    if (virVasprintf(&str, fmt, vargs) < 0) {
814
        goto cleanup;
E
Eric Blake 已提交
815
    }
D
Daniel Veillard 已提交
816

817
    ret = virLogFormatString(&msg, linenr, funcname, priority, str);
818 819
    if (ret < 0)
        goto cleanup;
D
Daniel Veillard 已提交
820

821 822
    if (virTimeStringNowRaw(timestamp) < 0)
        timestamp[0] = '\0';
823

D
Daniel Veillard 已提交
824
    /*
825 826
     * 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 已提交
827 828 829 830 831
     * 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.
     */
832 833 834 835
    virLogLock();
    virLogStr(timestamp);
    virLogStr(msg);
    virLogUnlock();
836 837 838
    if (emit == 0)
        goto cleanup;

D
Daniel Veillard 已提交
839
    virLogLock();
840
    for (i = 0; i < virLogNbOutputs; i++) {
841 842
        if (priority >= virLogOutputs[i].priority) {
            if (virLogOutputs[i].logVersion) {
843
                const char *rawver;
844
                char *ver = NULL;
845
                if (virLogVersionString(&rawver, &ver) >= 0)
846
                    virLogOutputs[i].f(VIR_LOG_FROM_FILE, VIR_LOG_INFO,
847
                                       __FILE__, __LINE__, __func__,
848
                                       timestamp, 0, rawver, ver,
849 850 851 852
                                       virLogOutputs[i].data);
                VIR_FREE(ver);
                virLogOutputs[i].logVersion = false;
            }
853
            virLogOutputs[i].f(source, priority,
854
                               filename, linenr, funcname,
855
                               timestamp, filterflags,
856
                               str, msg, virLogOutputs[i].data);
857
        }
D
Daniel Veillard 已提交
858
    }
859
    if ((virLogNbOutputs == 0) && (source != VIR_LOG_FROM_ERROR)) {
860
        if (logVersionStderr) {
861
            const char *rawver;
862
            char *ver = NULL;
863
            if (virLogVersionString(&rawver, &ver) >= 0)
864
                virLogOutputToFd(VIR_LOG_FROM_FILE, VIR_LOG_INFO,
865
                                 __FILE__, __LINE__, __func__,
866
                                 timestamp, 0, rawver, ver,
867
                                 (void *) STDERR_FILENO);
868 869 870
            VIR_FREE(ver);
            logVersionStderr = false;
        }
871
        virLogOutputToFd(source, priority,
872
                         filename, linenr, funcname,
873
                         timestamp, filterflags,
874
                         str, msg, (void *) STDERR_FILENO);
875
    }
D
Daniel Veillard 已提交
876 877
    virLogUnlock();

878
cleanup:
879
    VIR_FREE(str);
880
    VIR_FREE(msg);
881
    errno = saved_errno;
D
Daniel Veillard 已提交
882 883
}

884

885 886
static void
virLogStackTraceToFd(int fd)
887 888 889 890 891
{
    void *array[100];
    int size;
    static bool doneWarning = false;
    const char *msg = "Stack trace not available on this platform\n";
892 893 894 895 896 897 898

#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) {
899 900 901
        ignore_value(safewrite(fd, msg, strlen(msg)));
        doneWarning = true;
    }
902
#undef STRIP_DEPTH
903 904
}

905
static void
906
virLogOutputToFd(virLogSource source ATTRIBUTE_UNUSED,
907
                 virLogPriority priority ATTRIBUTE_UNUSED,
908
                 const char *filename ATTRIBUTE_UNUSED,
909
                 int linenr ATTRIBUTE_UNUSED,
910
                 const char *funcname ATTRIBUTE_UNUSED,
911 912 913 914 915
                 const char *timestamp,
                 unsigned int flags,
                 const char *rawstr ATTRIBUTE_UNUSED,
                 const char *str,
                 void *data)
916
{
917
    int fd = (intptr_t) data;
918
    char *msg;
D
Daniel Veillard 已提交
919 920

    if (fd < 0)
921
        return;
922 923

    if (virAsprintf(&msg, "%s: %s", timestamp, str) < 0)
924
        return;
925

926
    ignore_value(safewrite(fd, msg, strlen(msg)));
927 928
    VIR_FREE(msg);

929 930
    if (flags & VIR_LOG_STACK_TRACE)
        virLogStackTraceToFd(fd);
D
Daniel Veillard 已提交
931 932
}

933 934 935

static void
virLogCloseFd(void *data)
936
{
937
    int fd = (intptr_t) data;
D
Daniel Veillard 已提交
938

939
    VIR_LOG_CLOSE(fd);
D
Daniel Veillard 已提交
940 941
}

942 943 944 945

static int
virLogAddOutputToStderr(virLogPriority priority)
{
946 947
    if (virLogDefineOutput(virLogOutputToFd, NULL, (void *)2L, priority,
                           VIR_LOG_TO_STDERR, NULL, 0) < 0)
948 949
        return -1;
    return 0;
D
Daniel Veillard 已提交
950 951
}

952 953 954 955 956

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

959
    fd = open(file, O_CREAT | O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR);
D
Daniel Veillard 已提交
960
    if (fd < 0)
961
        return -1;
962 963
    if (virLogDefineOutput(virLogOutputToFd, virLogCloseFd,
                           (void *)(intptr_t)fd,
964
                           priority, VIR_LOG_TO_FILE, file, 0) < 0) {
965
        VIR_FORCE_CLOSE(fd);
966
        return -1;
D
Daniel Veillard 已提交
967
    }
968
    return 0;
D
Daniel Veillard 已提交
969 970
}

971

D
Daniel Veillard 已提交
972
#if HAVE_SYSLOG_H
973 974
static int
virLogPrioritySyslog(virLogPriority priority)
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
{
    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;
    }
}

990 991

static void
992
virLogOutputToSyslog(virLogSource source ATTRIBUTE_UNUSED,
993
                     virLogPriority priority,
994
                     const char *filename ATTRIBUTE_UNUSED,
995
                     int linenr ATTRIBUTE_UNUSED,
996
                     const char *funcname ATTRIBUTE_UNUSED,
997 998 999 1000 1001
                     const char *timestamp ATTRIBUTE_UNUSED,
                     unsigned int flags,
                     const char *rawstr ATTRIBUTE_UNUSED,
                     const char *str,
                     void *data ATTRIBUTE_UNUSED)
1002
{
1003
    virCheckFlags(VIR_LOG_STACK_TRACE,);
1004

1005
    syslog(virLogPrioritySyslog(priority), "%s", str);
D
Daniel Veillard 已提交
1006 1007
}

1008 1009
static char *current_ident = NULL;

1010 1011 1012 1013

static void
virLogCloseSyslog(void *data ATTRIBUTE_UNUSED)
{
D
Daniel Veillard 已提交
1014
    closelog();
1015
    VIR_FREE(current_ident);
D
Daniel Veillard 已提交
1016 1017
}

1018 1019 1020 1021 1022

static int
virLogAddOutputToSyslog(virLogPriority priority,
                        const char *ident)
{
1023 1024 1025 1026 1027 1028
    /*
     * ident needs to be kept around on Solaris
     */
    VIR_FREE(current_ident);
    current_ident = strdup(ident);
    if (current_ident == NULL)
1029
        return -1;
1030 1031

    openlog(current_ident, 0, 0);
D
Daniel Veillard 已提交
1032
    if (virLogDefineOutput(virLogOutputToSyslog, virLogCloseSyslog, NULL,
1033
                           priority, VIR_LOG_TO_SYSLOG, ident, 0) < 0) {
D
Daniel Veillard 已提交
1034
        closelog();
1035
        VIR_FREE(current_ident);
1036
        return -1;
D
Daniel Veillard 已提交
1037
    }
1038
    return 0;
D
Daniel Veillard 已提交
1039
}
D
Daniel P. Berrange 已提交
1040 1041


E
Eric Blake 已提交
1042
# if USE_JOURNALD
D
Daniel P. Berrange 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
#  define IOVEC_SET_STRING(iov, str)         \
    do {                                     \
        struct iovec *_i = &(iov);           \
        _i->iov_base = (char*)str;           \
        _i->iov_len = strlen(str);           \
    } while (0)

#  define IOVEC_SET_INT(iov, buf, val)                                  \
    do {                                                                \
        struct iovec *_i = &(iov);                                      \
        _i->iov_base = virFormatIntDecimal(buf, sizeof(buf), val);      \
        _i->iov_len = strlen(buf);                                      \
    } while (0)

static int journalfd = -1;

static void
virLogOutputToJournald(virLogSource source,
                       virLogPriority priority,
                       const char *filename,
                       int linenr,
                       const char *funcname,
                       const char *timestamp ATTRIBUTE_UNUSED,
                       unsigned int flags,
                       const char *rawstr,
                       const char *str ATTRIBUTE_UNUSED,
                       void *data ATTRIBUTE_UNUSED)
{
    virCheckFlags(VIR_LOG_STACK_TRACE,);
    int buffd = -1;
    size_t niov = 0;
    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";
    char priostr[INT_BUFSIZE_BOUND(priority)];
    char linestr[INT_BUFSIZE_BOUND(linenr)];

J
Ján Tomko 已提交
1088
    /* First message takes up to 4 iovecs, and each
D
Daniel P. Berrange 已提交
1089 1090 1091 1092 1093 1094 1095 1096
     * other field needs 3, assuming they don't have
     * newlines in them
     */
#  define IOV_SIZE (4 + (5 * 3))
    struct iovec iov[IOV_SIZE];

    if (strchr(rawstr, '\n')) {
        uint64_t nstr;
J
Ján Tomko 已提交
1097
        /* If 'str' contains a newline, then we must
D
Daniel P. Berrange 已提交
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 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
         * encode the string length, since we can't
         * rely on the newline for the field separator
         */
        IOVEC_SET_STRING(iov[niov++], "MESSAGE\n");
        nstr = htole64(strlen(rawstr));
        iov[niov].iov_base = (char*)&nstr;
        iov[niov].iov_len = sizeof(nstr);
        niov++;
    } else {
        IOVEC_SET_STRING(iov[niov++], "MESSAGE=");
    }
    IOVEC_SET_STRING(iov[niov++], rawstr);
    IOVEC_SET_STRING(iov[niov++], "\n");

    IOVEC_SET_STRING(iov[niov++], "PRIORITY=");
    IOVEC_SET_INT(iov[niov++], priostr, priority);
    IOVEC_SET_STRING(iov[niov++], "\n");

    IOVEC_SET_STRING(iov[niov++], "LIBVIRT_SOURCE=");
    IOVEC_SET_STRING(iov[niov++], virLogSourceTypeToString(source));
    IOVEC_SET_STRING(iov[niov++], "\n");

    IOVEC_SET_STRING(iov[niov++], "CODE_FILE=");
    IOVEC_SET_STRING(iov[niov++], filename);
    IOVEC_SET_STRING(iov[niov++], "\n");

    IOVEC_SET_STRING(iov[niov++], "CODE_LINE=");
    IOVEC_SET_INT(iov[niov++], linestr, linenr);
    IOVEC_SET_STRING(iov[niov++], "\n");

    IOVEC_SET_STRING(iov[niov++], "CODE_FUNC=");
    IOVEC_SET_STRING(iov[niov++], funcname);
    IOVEC_SET_STRING(iov[niov++], "\n");

    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;
    mh.msg_iovlen = niov;

    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;

    if (writev(buffd, iov, niov) < 0)
        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 已提交
1210
# endif /* USE_JOURNALD */
D
Daniel Veillard 已提交
1211 1212 1213 1214 1215 1216
#endif /* HAVE_SYSLOG_H */

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

1217

D
Daniel Veillard 已提交
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
/**
 * 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
 *    0: everything
 *    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.
 *
 * Returns the number of output parsed and installed or -1 in case of error
 */
1241 1242 1243
int
virLogParseOutputs(const char *outputs)
{
D
Daniel Veillard 已提交
1244 1245
    const char *cur = outputs, *str;
    char *name;
1246
    char *abspath;
1247
    virLogPriority prio;
1248 1249
    int ret = -1;
    int count = 0;
D
Daniel Veillard 已提交
1250 1251

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

1254 1255
    VIR_DEBUG("outputs=%s", outputs);

D
Daniel Veillard 已提交
1256 1257 1258
    virSkipSpaces(&cur);
    while (*cur != 0) {
        prio= virParseNumber(&cur);
1259
        if ((prio < VIR_LOG_DEBUG) || (prio > VIR_LOG_ERROR))
1260
            goto cleanup;
D
Daniel Veillard 已提交
1261
        if (*cur != ':')
1262
            goto cleanup;
D
Daniel Veillard 已提交
1263 1264 1265 1266
        cur++;
        if (STREQLEN(cur, "stderr", 6)) {
            cur += 6;
            if (virLogAddOutputToStderr(prio) == 0)
1267
                count++;
D
Daniel Veillard 已提交
1268 1269 1270
        } else if (STREQLEN(cur, "syslog", 6)) {
            cur += 6;
            if (*cur != ':')
1271
                goto cleanup;
D
Daniel Veillard 已提交
1272 1273 1274 1275 1276
            cur++;
            str = cur;
            while ((*cur != 0) && (!IS_SPACE(cur)))
                cur++;
            if (str == cur)
1277
                goto cleanup;
D
Daniel Veillard 已提交
1278 1279 1280
#if HAVE_SYSLOG_H
            name = strndup(str, cur - str);
            if (name == NULL)
1281
                goto cleanup;
D
Daniel Veillard 已提交
1282
            if (virLogAddOutputToSyslog(prio, name) == 0)
1283
                count++;
D
Daniel Veillard 已提交
1284 1285 1286 1287 1288
            VIR_FREE(name);
#endif /* HAVE_SYSLOG_H */
        } else if (STREQLEN(cur, "file", 4)) {
            cur += 4;
            if (*cur != ':')
1289
                goto cleanup;
D
Daniel Veillard 已提交
1290 1291 1292 1293 1294
            cur++;
            str = cur;
            while ((*cur != 0) && (!IS_SPACE(cur)))
                cur++;
            if (str == cur)
1295
                goto cleanup;
D
Daniel Veillard 已提交
1296 1297
            name = strndup(str, cur - str);
            if (name == NULL)
1298
                goto cleanup;
1299 1300 1301 1302 1303
            if (virFileAbsPath(name, &abspath) < 0) {
                VIR_FREE(name);
                return -1; /* skip warning here because setting was fine */
            }
            if (virLogAddOutputToFile(prio, abspath) == 0)
1304
                count++;
D
Daniel Veillard 已提交
1305
            VIR_FREE(name);
1306
            VIR_FREE(abspath);
D
Daniel P. Berrange 已提交
1307 1308
        } else if (STREQLEN(cur, "journald", 8)) {
            cur += 8;
E
Eric Blake 已提交
1309
#if USE_JOURNALD
D
Daniel P. Berrange 已提交
1310 1311
            if (virLogAddOutputToJournald(prio) == 0)
                count++;
E
Eric Blake 已提交
1312
#endif /* USE_JOURNALD */
D
Daniel Veillard 已提交
1313
        } else {
1314
            goto cleanup;
D
Daniel Veillard 已提交
1315 1316 1317
        }
        virSkipSpaces(&cur);
    }
1318 1319 1320
    ret = count;
cleanup:
    if (ret == -1)
1321
        VIR_WARN("Ignoring invalid log output setting.");
1322
    return ret;
D
Daniel Veillard 已提交
1323 1324
}

1325

D
Daniel Veillard 已提交
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
/**
 * 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
 */
1344 1345 1346
int
virLogParseFilters(const char *filters)
{
D
Daniel Veillard 已提交
1347 1348
    const char *cur = filters, *str;
    char *name;
1349
    virLogPriority prio;
1350 1351
    int ret = -1;
    int count = 0;
D
Daniel Veillard 已提交
1352 1353

    if (cur == NULL)
1354
        return -1;
D
Daniel Veillard 已提交
1355 1356 1357

    virSkipSpaces(&cur);
    while (*cur != 0) {
1358
        unsigned int flags = 0;
D
Daniel Veillard 已提交
1359
        prio= virParseNumber(&cur);
1360
        if ((prio < VIR_LOG_DEBUG) || (prio > VIR_LOG_ERROR))
1361
            goto cleanup;
D
Daniel Veillard 已提交
1362
        if (*cur != ':')
1363
            goto cleanup;
D
Daniel Veillard 已提交
1364
        cur++;
1365 1366 1367 1368
        if (*cur == '+') {
            flags |= VIR_LOG_STACK_TRACE;
            cur++;
        }
D
Daniel Veillard 已提交
1369 1370 1371 1372
        str = cur;
        while ((*cur != 0) && (!IS_SPACE(cur)))
            cur++;
        if (str == cur)
1373
            goto cleanup;
D
Daniel Veillard 已提交
1374 1375
        name = strndup(str, cur - str);
        if (name == NULL)
1376
            goto cleanup;
1377
        if (virLogDefineFilter(name, prio, flags) >= 0)
1378
            count++;
D
Daniel Veillard 已提交
1379 1380 1381
        VIR_FREE(name);
        virSkipSpaces(&cur);
    }
1382 1383 1384
    ret = count;
cleanup:
    if (ret == -1)
1385
        VIR_WARN("Ignoring invalid log filter setting.");
1386
    return ret;
D
Daniel Veillard 已提交
1387
}
1388

1389

1390 1391 1392 1393 1394
/**
 * virLogGetDefaultPriority:
 *
 * Returns the current logging priority level.
 */
1395 1396 1397
virLogPriority
virLogGetDefaultPriority(void)
{
1398
    return virLogDefaultPriority;
1399 1400
}

1401

1402 1403 1404 1405 1406 1407 1408
/**
 * virLogGetFilters:
 *
 * Returns a string listing the current filters, in the format originally
 * specified in the config file or environment. Caller must free the
 * result.
 */
1409 1410 1411
char *
virLogGetFilters(void)
{
1412 1413 1414 1415 1416
    int i;
    virBuffer filterbuf = VIR_BUFFER_INITIALIZER;

    virLogLock();
    for (i = 0; i < virLogNbFilters; i++) {
1417 1418 1419 1420 1421 1422
        const char *sep = ":";
        if (virLogFilters[i].flags & VIR_LOG_STACK_TRACE)
            sep = ":+";
        virBufferAsprintf(&filterbuf, "%d%s%s ",
                          virLogFilters[i].priority,
                          sep,
1423 1424 1425 1426
                          virLogFilters[i].match);
    }
    virLogUnlock();

1427 1428
    if (virBufferError(&filterbuf)) {
        virBufferFreeAndReset(&filterbuf);
1429
        return NULL;
1430
    }
1431 1432 1433 1434

    return virBufferContentAndReset(&filterbuf);
}

1435

1436 1437 1438 1439 1440 1441 1442
/**
 * virLogGetOutputs:
 *
 * Returns a string listing the current outputs, in the format originally
 * specified in the config file or environment. Caller must free the
 * result.
 */
1443 1444 1445
char *
virLogGetOutputs(void)
{
1446 1447 1448 1449 1450
    int i;
    virBuffer outputbuf = VIR_BUFFER_INITIALIZER;

    virLogLock();
    for (i = 0; i < virLogNbOutputs; i++) {
1451
        virLogDestination dest = virLogOutputs[i].dest;
1452
        if (i)
1453
            virBufferAsprintf(&outputbuf, " ");
1454 1455 1456
        switch (dest) {
            case VIR_LOG_TO_SYSLOG:
            case VIR_LOG_TO_FILE:
1457
                virBufferAsprintf(&outputbuf, "%d:%s:%s",
1458 1459 1460 1461 1462
                                  virLogOutputs[i].priority,
                                  virLogOutputString(dest),
                                  virLogOutputs[i].name);
                break;
            default:
1463
                virBufferAsprintf(&outputbuf, "%d:%s",
1464 1465 1466 1467 1468 1469
                                  virLogOutputs[i].priority,
                                  virLogOutputString(dest));
        }
    }
    virLogUnlock();

1470 1471
    if (virBufferError(&outputbuf)) {
        virBufferFreeAndReset(&outputbuf);
1472
        return NULL;
1473
    }
1474 1475 1476 1477

    return virBufferContentAndReset(&outputbuf);
}

1478

1479 1480 1481 1482 1483
/**
 * virLogGetNbFilters:
 *
 * Returns the current number of defined log filters.
 */
1484 1485 1486
int
virLogGetNbFilters(void)
{
1487
    return virLogNbFilters;
1488 1489
}

1490

1491 1492 1493 1494 1495
/**
 * virLogGetNbOutputs:
 *
 * Returns the current number of defined log outputs.
 */
1496 1497 1498
int
virLogGetNbOutputs(void)
{
1499
    return virLogNbOutputs;
1500
}
1501

1502

1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
/**
 * 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.
 */
1516 1517 1518
int
virLogParseDefaultPriority(const char *priority)
{
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    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
1530
        VIR_WARN("Ignoring invalid log level setting");
1531 1532 1533 1534

    return ret;
}

1535

1536 1537 1538 1539 1540 1541
/**
 * virLogSetFromEnv:
 *
 * Sets virLogDefaultPriority, virLogFilters and virLogOutputs based on
 * environment variables.
 */
1542 1543 1544
void
virLogSetFromEnv(void)
{
1545 1546 1547 1548 1549 1550 1551
    char *debugEnv;

    debugEnv = getenv("LIBVIRT_DEBUG");
    if (debugEnv && *debugEnv)
        virLogParseDefaultPriority(debugEnv);
    debugEnv = getenv("LIBVIRT_LOG_FILTERS");
    if (debugEnv && *debugEnv)
1552
        virLogParseFilters(debugEnv);
1553 1554
    debugEnv = getenv("LIBVIRT_LOG_OUTPUTS");
    if (debugEnv && *debugEnv)
1555
        virLogParseOutputs(debugEnv);
1556
}