virlog.c 37.0 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 <execinfo.h>
34
#include <regex.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 "virerror.h"
44
#include "virlog.h"
45
#include "viralloc.h"
46
#include "virutil.h"
47
#include "virbuffer.h"
48
#include "virthread.h"
E
Eric Blake 已提交
49
#include "virfile.h"
50
#include "virtime.h"
D
Daniel P. Berrange 已提交
51
#include "intprops.h"
52
#include "virstring.h"
53

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

60 61
#define VIR_FROM_THIS VIR_FROM_NONE

62 63
VIR_LOG_INIT("util.log");

64 65 66
static regex_t *virLogRegex = NULL;


67 68
#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}"
69
#define VIR_LOG_PID_REGEX "[0-9]+"
70
#define VIR_LOG_LEVEL_REGEX "(debug|info|warning|error)"
71 72 73 74

#define VIR_LOG_REGEX \
    VIR_LOG_DATE_REGEX " " VIR_LOG_TIME_REGEX ": " \
    VIR_LOG_PID_REGEX ": " VIR_LOG_LEVEL_REGEX " : "
D
Daniel Veillard 已提交
75 76 77 78 79 80

/*
 * Filters are used to refine the rules on what to keep or drop
 * based on a matching pattern (currently a substring)
 */
struct _virLogFilter {
81
    char *match;
82
    virLogPriority priority;
83
    unsigned int flags;
D
Daniel Veillard 已提交
84 85 86 87
};
typedef struct _virLogFilter virLogFilter;
typedef virLogFilter *virLogFilterPtr;

88
static int virLogFiltersSerial = 1;
D
Daniel Veillard 已提交
89 90 91 92 93 94 95 96
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 {
97
    bool logVersion;
D
Daniel Veillard 已提交
98 99 100
    void *data;
    virLogOutputFunc f;
    virLogCloseFunc c;
101
    virLogPriority priority;
102
    virLogDestination dest;
103
    char *name;
D
Daniel Veillard 已提交
104 105 106 107 108 109 110 111 112 113
};
typedef struct _virLogOutput virLogOutput;
typedef virLogOutput *virLogOutputPtr;

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

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

static int virLogResetFilters(void);
static int virLogResetOutputs(void);
118
static void virLogOutputToFd(virLogSourcePtr src,
119
                             virLogPriority priority,
120
                             const char *filename,
121
                             int linenr,
122
                             const char *funcname,
123
                             const char *timestamp,
M
Miloslav Trmač 已提交
124
                             virLogMetadataPtr metadata,
125
                             unsigned int flags,
126 127
                             const char *rawstr,
                             const char *str,
128
                             void *data);
D
Daniel Veillard 已提交
129

130

D
Daniel Veillard 已提交
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 189
    if (virMutexInit(&virLogMutex) < 0)
        return -1;

D
Daniel Veillard 已提交
190
    virLogLock();
191
    virLogDefaultPriority = VIR_LOG_DEFAULT;
192

193
    if (VIR_ALLOC_QUIET(virLogRegex) >= 0) {
194 195 196 197
        if (regcomp(virLogRegex, VIR_LOG_REGEX, REG_EXTENDED) != 0)
            VIR_FREE(virLogRegex);
    }

D
Daniel Veillard 已提交
198
    virLogUnlock();
199
    return 0;
D
Daniel Veillard 已提交
200 201
}

202 203
VIR_ONCE_GLOBAL_INIT(virLog)

204

D
Daniel Veillard 已提交
205 206 207 208 209 210 211
/**
 * virLogReset:
 *
 * Reset the logging module to its default initial state
 *
 * Returns 0 if successful, and -1 in case or error
 */
212 213 214
int
virLogReset(void)
{
215 216
    if (virLogInitialize() < 0)
        return -1;
D
Daniel Veillard 已提交
217 218 219 220

    virLogLock();
    virLogResetFilters();
    virLogResetOutputs();
221
    virLogDefaultPriority = VIR_LOG_DEFAULT;
D
Daniel Veillard 已提交
222
    virLogUnlock();
223
    return 0;
D
Daniel Veillard 已提交
224 225 226 227 228 229 230 231 232 233 234 235
}

/**
 * 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.
 */
236 237 238
int
virLogSetDefaultPriority(virLogPriority priority)
{
239
    if ((priority < VIR_LOG_DEBUG) || (priority > VIR_LOG_ERROR)) {
240
        VIR_WARN("Ignoring invalid log level setting.");
241
        return -1;
242
    }
243 244 245
    if (virLogInitialize() < 0)
        return -1;

D
Daniel Veillard 已提交
246
    virLogDefaultPriority = priority;
247
    return 0;
D
Daniel Veillard 已提交
248 249
}

250

D
Daniel Veillard 已提交
251 252 253 254 255 256 257
/**
 * virLogResetFilters:
 *
 * Removes the set of logging filters defined.
 *
 * Returns the number of filters removed
 */
258 259 260
static int
virLogResetFilters(void)
{
261
    size_t i;
D
Daniel Veillard 已提交
262

263
    for (i = 0; i < virLogNbFilters; i++)
D
Daniel Veillard 已提交
264 265 266
        VIR_FREE(virLogFilters[i].match);
    VIR_FREE(virLogFilters);
    virLogNbFilters = 0;
267
    virLogFiltersSerial++;
268
    return i;
D
Daniel Veillard 已提交
269 270
}

271

D
Daniel Veillard 已提交
272 273 274 275
/**
 * virLogDefineFilter:
 * @match: the pattern to match
 * @priority: the priority to give to messages matching the pattern
276
 * @flags: extra flags, see virLogFilterFlags enum
D
Daniel Veillard 已提交
277 278 279 280 281 282 283 284
 *
 * 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
 */
285 286 287 288
int
virLogDefineFilter(const char *match,
                   virLogPriority priority,
                   unsigned int flags)
289
{
290 291
    size_t i;
    int ret = -1;
D
Daniel Veillard 已提交
292 293
    char *mdup = NULL;

294
    virCheckFlags(VIR_LOG_STACK_TRACE, -1);
295

296 297 298
    if (virLogInitialize() < 0)
        return -1;

D
Daniel Veillard 已提交
299 300
    if ((match == NULL) || (priority < VIR_LOG_DEBUG) ||
        (priority > VIR_LOG_ERROR))
301
        return -1;
D
Daniel Veillard 已提交
302 303

    virLogLock();
304
    for (i = 0; i < virLogNbFilters; i++) {
D
Daniel Veillard 已提交
305 306
        if (STREQ(virLogFilters[i].match, match)) {
            virLogFilters[i].priority = priority;
307
            ret = i;
D
Daniel Veillard 已提交
308 309 310 311
            goto cleanup;
        }
    }

312
    if (VIR_STRDUP_QUIET(mdup, match) < 0)
D
Daniel Veillard 已提交
313
        goto cleanup;
314
    if (VIR_REALLOC_N_QUIET(virLogFilters, virLogNbFilters + 1)) {
D
Daniel Veillard 已提交
315 316 317
        VIR_FREE(mdup);
        goto cleanup;
    }
318
    ret = virLogNbFilters;
D
Daniel Veillard 已提交
319 320
    virLogFilters[i].match = mdup;
    virLogFilters[i].priority = priority;
321
    virLogFilters[i].flags = flags;
D
Daniel Veillard 已提交
322
    virLogNbFilters++;
323
    virLogFiltersSerial++;
D
Daniel Veillard 已提交
324 325
cleanup:
    virLogUnlock();
326
    if (ret < 0)
327
        virReportOOMError();
328
    return ret;
D
Daniel Veillard 已提交
329 330 331 332 333 334 335 336 337
}

/**
 * virLogResetOutputs:
 *
 * Removes the set of logging output defined.
 *
 * Returns the number of output removed
 */
338 339 340
static int
virLogResetOutputs(void)
{
341
    size_t i;
D
Daniel Veillard 已提交
342

343
    for (i = 0; i < virLogNbOutputs; i++) {
D
Daniel Veillard 已提交
344 345
        if (virLogOutputs[i].c != NULL)
            virLogOutputs[i].c(virLogOutputs[i].data);
346
        VIR_FREE(virLogOutputs[i].name);
D
Daniel Veillard 已提交
347 348 349 350
    }
    VIR_FREE(virLogOutputs);
    i = virLogNbOutputs;
    virLogNbOutputs = 0;
351
    return i;
D
Daniel Veillard 已提交
352 353
}

354

D
Daniel Veillard 已提交
355 356 357
/**
 * virLogDefineOutput:
 * @f: the function to call to output a message
358
 * @c: the function to call to close the output (or NULL)
D
Daniel Veillard 已提交
359 360
 * @data: extra data passed as first arg to the function
 * @priority: minimal priority for this filter, use 0 for none
361 362
 * @dest: where to send output of this priority
 * @name: optional name data associated with an output
D
Daniel Veillard 已提交
363 364 365 366 367 368 369
 * @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
 */
370 371 372 373 374 375 376 377
int
virLogDefineOutput(virLogOutputFunc f,
                   virLogCloseFunc c,
                   void *data,
                   virLogPriority priority,
                   virLogDestination dest,
                   const char *name,
                   unsigned int flags)
378
{
D
Daniel Veillard 已提交
379
    int ret = -1;
380
    char *ndup = NULL;
D
Daniel Veillard 已提交
381

382 383
    virCheckFlags(0, -1);

384 385 386
    if (virLogInitialize() < 0)
        return -1;

D
Daniel Veillard 已提交
387
    if (f == NULL)
388
        return -1;
D
Daniel Veillard 已提交
389

390
    if (dest == VIR_LOG_TO_SYSLOG || dest == VIR_LOG_TO_FILE) {
391 392
        if (!name) {
            virReportOOMError();
393
            return -1;
394 395
        }
        if (VIR_STRDUP(ndup, name) < 0)
396
            return -1;
397 398
    }

D
Daniel Veillard 已提交
399
    virLogLock();
400
    if (VIR_REALLOC_N_QUIET(virLogOutputs, virLogNbOutputs + 1)) {
401
        VIR_FREE(ndup);
D
Daniel Veillard 已提交
402 403 404
        goto cleanup;
    }
    ret = virLogNbOutputs++;
405
    virLogOutputs[ret].logVersion = true;
D
Daniel Veillard 已提交
406 407 408 409
    virLogOutputs[ret].f = f;
    virLogOutputs[ret].c = c;
    virLogOutputs[ret].data = data;
    virLogOutputs[ret].priority = priority;
410 411
    virLogOutputs[ret].dest = dest;
    virLogOutputs[ret].name = ndup;
D
Daniel Veillard 已提交
412 413
cleanup:
    virLogUnlock();
414
    return ret;
D
Daniel Veillard 已提交
415 416
}

417

418 419
static int
virLogFormatString(char **msg,
420
                   int linenr,
421
                   const char *funcname,
422
                   virLogPriority priority,
423 424 425
                   const char *str)
{
    int ret;
426 427 428 429 430 431 432 433

    /*
     * 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.
     */
434
    if ((funcname != NULL)) {
435 436 437
        ret = virAsprintfQuiet(msg, "%llu: %s : %s:%d : %s\n",
                               virThreadSelfID(), virLogPriorityString(priority),
                               funcname, linenr, str);
438
    } else {
439 440 441
        ret = virAsprintfQuiet(msg, "%llu: %s : %s\n",
                               virThreadSelfID(), virLogPriorityString(priority),
                               str);
442 443 444 445
    }
    return ret;
}

446

447
static int
448 449
virLogVersionString(const char **rawmsg,
                    char **msg)
450 451 452 453 454 455 456 457 458 459 460 461 462 463
{
#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

464
    *rawmsg = LOG_VERSION_STRING;
465
    return virLogFormatString(msg, 0, NULL, VIR_LOG_INFO, LOG_VERSION_STRING);
466 467
}

468

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
static void
virLogSourceUpdate(virLogSourcePtr source)
{
    virLogLock();
    if (source->serial < virLogFiltersSerial) {
        unsigned int priority = virLogDefaultPriority;
        unsigned int flags = 0;
        size_t i;

        for (i = 0; i < virLogNbFilters; i++) {
            if (strstr(source->name, virLogFilters[i].match)) {
                priority = virLogFilters[i].priority;
                flags = virLogFilters[i].flags;
                break;
            }
        }

        source->priority = priority;
        source->flags = flags;
        source->serial = virLogFiltersSerial;
    }
    virLogUnlock();
}

D
Daniel Veillard 已提交
493 494
/**
 * virLogMessage:
495
 * @source: where is that message coming from
D
Daniel Veillard 已提交
496
 * @priority: the priority level
497
 * @filename: file where the message was emitted
498
 * @linenr: line where the message was emitted
499
 * @funcname: the function emitting the (debug) message
500
 * @metadata: NULL or metadata array, terminated by an item with NULL key
D
Daniel Veillard 已提交
501 502 503
 * @fmt: the string format
 * @...: the arguments
 *
E
Eric Blake 已提交
504
 * Call the libvirt logger with some information. Based on the configuration
D
Daniel Veillard 已提交
505 506
 * the message may be stored, sent to output or just discarded
 */
507
void
508
virLogMessage(virLogSourcePtr source,
509
              virLogPriority priority,
510
              const char *filename,
511
              int linenr,
512
              const char *funcname,
513
              virLogMetadataPtr metadata,
514
              const char *fmt, ...)
515 516 517
{
    va_list ap;
    va_start(ap, fmt);
518
    virLogVMessage(source, priority,
519
                   filename, linenr, funcname,
520
                   metadata, fmt, ap);
521 522 523
    va_end(ap);
}

524

525 526
/**
 * virLogVMessage:
527
 * @source: where is that message coming from
528
 * @priority: the priority level
529
 * @filename: file where the message was emitted
530
 * @linenr: line where the message was emitted
531
 * @funcname: the function emitting the (debug) message
532
 * @metadata: NULL or metadata array, terminated by an item with NULL key
533 534 535 536 537 538
 * @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
 */
539
void
540
virLogVMessage(virLogSourcePtr source,
541
               virLogPriority priority,
542
               const char *filename,
543
               int linenr,
544
               const char *funcname,
M
Miloslav Trmač 已提交
545
               virLogMetadataPtr metadata,
546 547
               const char *fmt,
               va_list vargs)
548
{
549
    static bool logVersionStderr = true;
D
Daniel Veillard 已提交
550
    char *str = NULL;
551
    char *msg = NULL;
552
    char timestamp[VIR_TIME_STRING_BUFLEN];
553
    int ret;
554
    size_t i;
555
    int saved_errno = errno;
556
    unsigned int filterflags = 0;
D
Daniel Veillard 已提交
557

558 559
    if (virLogInitialize() < 0)
        return;
D
Daniel Veillard 已提交
560 561

    if (fmt == NULL)
562
        return;
D
Daniel Veillard 已提交
563 564

    /*
565 566 567 568 569 570
     * 3 intentionally non-thread safe variable reads.
     * Since writes to the variable are serialized on
     * virLogLock, worst case result is a log message
     * is accidentally dropped or emitted, if another
     * thread is updating log filter list concurrently
     * with a log message emission.
D
Daniel Veillard 已提交
571
     */
572 573 574
    if (source->serial < virLogFiltersSerial)
        virLogSourceUpdate(source);
    if (priority < source->priority)
575
        goto cleanup;
576
    filterflags = source->flags;
577

D
Daniel Veillard 已提交
578 579 580
    /*
     * serialize the error message, add level and timestamp
     */
581
    if (virVasprintfQuiet(&str, fmt, vargs) < 0) {
582
        goto cleanup;
E
Eric Blake 已提交
583
    }
D
Daniel Veillard 已提交
584

585
    ret = virLogFormatString(&msg, linenr, funcname, priority, str);
586 587
    if (ret < 0)
        goto cleanup;
D
Daniel Veillard 已提交
588

589 590
    if (virTimeStringNowRaw(timestamp) < 0)
        timestamp[0] = '\0';
591

592 593
    virLogLock();

D
Daniel Veillard 已提交
594
    /*
595
     * Push the message to the outputs defined, if none exist then
D
Daniel Veillard 已提交
596 597
     * use stderr.
     */
598
    for (i = 0; i < virLogNbOutputs; i++) {
599 600
        if (priority >= virLogOutputs[i].priority) {
            if (virLogOutputs[i].logVersion) {
601
                const char *rawver;
602
                char *ver = NULL;
603
                if (virLogVersionString(&rawver, &ver) >= 0)
604
                    virLogOutputs[i].f(&virLogSelf, VIR_LOG_INFO,
605
                                       __FILE__, __LINE__, __func__,
M
Miloslav Trmač 已提交
606
                                       timestamp, NULL, 0, rawver, ver,
607 608 609 610
                                       virLogOutputs[i].data);
                VIR_FREE(ver);
                virLogOutputs[i].logVersion = false;
            }
611
            virLogOutputs[i].f(source, priority,
612
                               filename, linenr, funcname,
M
Miloslav Trmač 已提交
613
                               timestamp, metadata, filterflags,
614
                               str, msg, virLogOutputs[i].data);
615
        }
D
Daniel Veillard 已提交
616
    }
617
    if (virLogNbOutputs == 0) {
618
        if (logVersionStderr) {
619
            const char *rawver;
620
            char *ver = NULL;
621
            if (virLogVersionString(&rawver, &ver) >= 0)
622
                virLogOutputToFd(&virLogSelf, VIR_LOG_INFO,
623
                                 __FILE__, __LINE__, __func__,
M
Miloslav Trmač 已提交
624
                                 timestamp, NULL, 0, rawver, ver,
625
                                 (void *) STDERR_FILENO);
626 627 628
            VIR_FREE(ver);
            logVersionStderr = false;
        }
629
        virLogOutputToFd(source, priority,
630
                         filename, linenr, funcname,
M
Miloslav Trmač 已提交
631
                         timestamp, metadata, filterflags,
632
                         str, msg, (void *) STDERR_FILENO);
633
    }
D
Daniel Veillard 已提交
634 635
    virLogUnlock();

636
cleanup:
637
    VIR_FREE(str);
638
    VIR_FREE(msg);
639
    errno = saved_errno;
D
Daniel Veillard 已提交
640 641
}

642

643 644
static void
virLogStackTraceToFd(int fd)
645 646 647 648 649
{
    void *array[100];
    int size;
    static bool doneWarning = false;
    const char *msg = "Stack trace not available on this platform\n";
650 651 652 653 654 655 656

#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) {
657 658 659
        ignore_value(safewrite(fd, msg, strlen(msg)));
        doneWarning = true;
    }
660
#undef STRIP_DEPTH
661 662
}

663
static void
664
virLogOutputToFd(virLogSourcePtr source ATTRIBUTE_UNUSED,
665
                 virLogPriority priority ATTRIBUTE_UNUSED,
666
                 const char *filename ATTRIBUTE_UNUSED,
667
                 int linenr ATTRIBUTE_UNUSED,
668
                 const char *funcname ATTRIBUTE_UNUSED,
669
                 const char *timestamp,
M
Miloslav Trmač 已提交
670
                 virLogMetadataPtr metadata ATTRIBUTE_UNUSED,
671 672 673 674
                 unsigned int flags,
                 const char *rawstr ATTRIBUTE_UNUSED,
                 const char *str,
                 void *data)
675
{
676
    int fd = (intptr_t) data;
677
    char *msg;
D
Daniel Veillard 已提交
678 679

    if (fd < 0)
680
        return;
681

682
    if (virAsprintfQuiet(&msg, "%s: %s", timestamp, str) < 0)
683
        return;
684

685
    ignore_value(safewrite(fd, msg, strlen(msg)));
686 687
    VIR_FREE(msg);

688 689
    if (flags & VIR_LOG_STACK_TRACE)
        virLogStackTraceToFd(fd);
D
Daniel Veillard 已提交
690 691
}

692 693 694

static void
virLogCloseFd(void *data)
695
{
696
    int fd = (intptr_t) data;
D
Daniel Veillard 已提交
697

698
    VIR_LOG_CLOSE(fd);
D
Daniel Veillard 已提交
699 700
}

701 702 703 704

static int
virLogAddOutputToStderr(virLogPriority priority)
{
705 706
    if (virLogDefineOutput(virLogOutputToFd, NULL, (void *)2L, priority,
                           VIR_LOG_TO_STDERR, NULL, 0) < 0)
707 708
        return -1;
    return 0;
D
Daniel Veillard 已提交
709 710
}

711 712 713 714 715

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

718
    fd = open(file, O_CREAT | O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR);
D
Daniel Veillard 已提交
719
    if (fd < 0)
720
        return -1;
721 722
    if (virLogDefineOutput(virLogOutputToFd, virLogCloseFd,
                           (void *)(intptr_t)fd,
723
                           priority, VIR_LOG_TO_FILE, file, 0) < 0) {
724
        VIR_FORCE_CLOSE(fd);
725
        return -1;
D
Daniel Veillard 已提交
726
    }
727
    return 0;
D
Daniel Veillard 已提交
728 729
}

730

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
#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

747 748
static int
virLogPrioritySyslog(virLogPriority priority)
749 750 751 752 753 754 755 756 757 758 759 760 761 762
{
    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;
    }
}
763
#endif /* HAVE_SYSLOG_H || USE_JOURNALD */
764

765

766
#if HAVE_SYSLOG_H
767
static void
768
virLogOutputToSyslog(virLogSourcePtr source ATTRIBUTE_UNUSED,
769
                     virLogPriority priority,
770
                     const char *filename ATTRIBUTE_UNUSED,
771
                     int linenr ATTRIBUTE_UNUSED,
772
                     const char *funcname ATTRIBUTE_UNUSED,
773
                     const char *timestamp ATTRIBUTE_UNUSED,
M
Miloslav Trmač 已提交
774
                     virLogMetadataPtr metadata ATTRIBUTE_UNUSED,
775 776 777 778
                     unsigned int flags,
                     const char *rawstr ATTRIBUTE_UNUSED,
                     const char *str,
                     void *data ATTRIBUTE_UNUSED)
779
{
780
    virCheckFlags(VIR_LOG_STACK_TRACE,);
781

782
    syslog(virLogPrioritySyslog(priority), "%s", str);
D
Daniel Veillard 已提交
783 784
}

785 786
static char *current_ident = NULL;

787 788 789 790

static void
virLogCloseSyslog(void *data ATTRIBUTE_UNUSED)
{
D
Daniel Veillard 已提交
791
    closelog();
792
    VIR_FREE(current_ident);
D
Daniel Veillard 已提交
793 794
}

795 796 797 798 799

static int
virLogAddOutputToSyslog(virLogPriority priority,
                        const char *ident)
{
800 801 802 803
    /*
     * ident needs to be kept around on Solaris
     */
    VIR_FREE(current_ident);
804
    if (VIR_STRDUP(current_ident, ident) < 0)
805
        return -1;
806 807

    openlog(current_ident, 0, 0);
D
Daniel Veillard 已提交
808
    if (virLogDefineOutput(virLogOutputToSyslog, virLogCloseSyslog, NULL,
809
                           priority, VIR_LOG_TO_SYSLOG, ident, 0) < 0) {
D
Daniel Veillard 已提交
810
        closelog();
811
        VIR_FREE(current_ident);
812
        return -1;
D
Daniel Veillard 已提交
813
    }
814
    return 0;
D
Daniel Veillard 已提交
815
}
D
Daniel P. Berrange 已提交
816 817


E
Eric Blake 已提交
818
# if USE_JOURNALD
819 820 821 822 823
#  define IOVEC_SET(iov, data, size)            \
    do {                                        \
        struct iovec *_i = &(iov);              \
        _i->iov_base = (void*)(data);           \
        _i->iov_len = (size);                   \
D
Daniel P. Berrange 已提交
824 825
    } while (0)

826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
#  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 已提交
891 892 893 894

static int journalfd = -1;

static void
895
virLogOutputToJournald(virLogSourcePtr source,
D
Daniel P. Berrange 已提交
896 897 898 899 900
                       virLogPriority priority,
                       const char *filename,
                       int linenr,
                       const char *funcname,
                       const char *timestamp ATTRIBUTE_UNUSED,
901
                       virLogMetadataPtr metadata,
D
Daniel P. Berrange 已提交
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
                       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";
920
    size_t nmetadata = 0;
D
Daniel P. Berrange 已提交
921

922 923 924
#  define NUM_FIELDS_CORE 6
#  define NUM_FIELDS_META 5
#  define NUM_FIELDS (NUM_FIELDS_CORE + NUM_FIELDS_META)
925 926 927
    struct iovec iov[NUM_FIELDS * 5];
    char iov_bufs[NUM_FIELDS][JOURNAL_BUF_SIZE];
    struct journalState state;
D
Daniel P. Berrange 已提交
928

929 930 931 932
    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 已提交
933

E
Eric Blake 已提交
934
    journalAddString(&state, "MESSAGE", rawstr);
935 936
    journalAddInt(&state, "PRIORITY",
                  virLogPrioritySyslog(priority));
937
    journalAddString(&state, "LIBVIRT_SOURCE", source->name);
938 939
    if (filename)
        journalAddString(&state, "CODE_FILE", filename);
940
    journalAddInt(&state, "CODE_LINE", linenr);
941 942
    if (funcname)
        journalAddString(&state, "CODE_FUNC", funcname);
943 944 945 946 947 948 949 950 951 952 953
    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 已提交
954 955 956 957 958 959 960 961 962 963

    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;
964
    mh.msg_iovlen = state.iov - iov;
D
Daniel P. Berrange 已提交
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987

    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;

988
    if (writev(buffd, iov, state.iov - iov) < 0)
D
Daniel P. Berrange 已提交
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
        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 已提交
1033
# endif /* USE_JOURNALD */
J
Ján Tomko 已提交
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058

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 已提交
1059 1060 1061 1062 1063 1064
#endif /* HAVE_SYSLOG_H */

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

1065

D
Daniel Veillard 已提交
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
/**
 * 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.
 *
1086 1087 1088
 * If running in setuid mode, then only the 'stderr' output will
 * be allowed
 *
D
Daniel Veillard 已提交
1089 1090
 * Returns the number of output parsed and installed or -1 in case of error
 */
1091 1092 1093
int
virLogParseOutputs(const char *outputs)
{
D
Daniel Veillard 已提交
1094 1095
    const char *cur = outputs, *str;
    char *name;
1096
    char *abspath;
1097
    virLogPriority prio;
1098 1099
    int ret = -1;
    int count = 0;
1100
    bool isSUID = virIsSUID();
D
Daniel Veillard 已提交
1101 1102

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

1105 1106
    VIR_DEBUG("outputs=%s", outputs);

D
Daniel Veillard 已提交
1107 1108
    virSkipSpaces(&cur);
    while (*cur != 0) {
1109
        prio = virParseNumber(&cur);
1110
        if ((prio < VIR_LOG_DEBUG) || (prio > VIR_LOG_ERROR))
1111
            goto cleanup;
D
Daniel Veillard 已提交
1112
        if (*cur != ':')
1113
            goto cleanup;
D
Daniel Veillard 已提交
1114 1115 1116 1117
        cur++;
        if (STREQLEN(cur, "stderr", 6)) {
            cur += 6;
            if (virLogAddOutputToStderr(prio) == 0)
1118
                count++;
D
Daniel Veillard 已提交
1119
        } else if (STREQLEN(cur, "syslog", 6)) {
1120 1121
            if (isSUID)
                goto cleanup;
D
Daniel Veillard 已提交
1122 1123
            cur += 6;
            if (*cur != ':')
1124
                goto cleanup;
D
Daniel Veillard 已提交
1125 1126 1127 1128 1129
            cur++;
            str = cur;
            while ((*cur != 0) && (!IS_SPACE(cur)))
                cur++;
            if (str == cur)
1130
                goto cleanup;
D
Daniel Veillard 已提交
1131
#if HAVE_SYSLOG_H
1132
            if (VIR_STRNDUP(name, str, cur - str) < 0)
1133
                goto cleanup;
D
Daniel Veillard 已提交
1134
            if (virLogAddOutputToSyslog(prio, name) == 0)
1135
                count++;
D
Daniel Veillard 已提交
1136 1137 1138
            VIR_FREE(name);
#endif /* HAVE_SYSLOG_H */
        } else if (STREQLEN(cur, "file", 4)) {
1139 1140
            if (isSUID)
                goto cleanup;
D
Daniel Veillard 已提交
1141 1142
            cur += 4;
            if (*cur != ':')
1143
                goto cleanup;
D
Daniel Veillard 已提交
1144 1145 1146 1147 1148
            cur++;
            str = cur;
            while ((*cur != 0) && (!IS_SPACE(cur)))
                cur++;
            if (str == cur)
1149
                goto cleanup;
1150
            if (VIR_STRNDUP(name, str, cur - str) < 0)
1151
                goto cleanup;
1152 1153 1154 1155 1156
            if (virFileAbsPath(name, &abspath) < 0) {
                VIR_FREE(name);
                return -1; /* skip warning here because setting was fine */
            }
            if (virLogAddOutputToFile(prio, abspath) == 0)
1157
                count++;
D
Daniel Veillard 已提交
1158
            VIR_FREE(name);
1159
            VIR_FREE(abspath);
D
Daniel P. Berrange 已提交
1160
        } else if (STREQLEN(cur, "journald", 8)) {
1161 1162
            if (isSUID)
                goto cleanup;
D
Daniel P. Berrange 已提交
1163
            cur += 8;
E
Eric Blake 已提交
1164
#if USE_JOURNALD
D
Daniel P. Berrange 已提交
1165 1166
            if (virLogAddOutputToJournald(prio) == 0)
                count++;
E
Eric Blake 已提交
1167
#endif /* USE_JOURNALD */
D
Daniel Veillard 已提交
1168
        } else {
1169
            goto cleanup;
D
Daniel Veillard 已提交
1170 1171 1172
        }
        virSkipSpaces(&cur);
    }
1173 1174 1175
    ret = count;
cleanup:
    if (ret == -1)
1176
        VIR_WARN("Ignoring invalid log output setting.");
1177
    return ret;
D
Daniel Veillard 已提交
1178 1179
}

1180

D
Daniel Veillard 已提交
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
/**
 * 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
 */
1199 1200 1201
int
virLogParseFilters(const char *filters)
{
D
Daniel Veillard 已提交
1202 1203
    const char *cur = filters, *str;
    char *name;
1204
    virLogPriority prio;
1205 1206
    int ret = -1;
    int count = 0;
D
Daniel Veillard 已提交
1207 1208

    if (cur == NULL)
1209
        return -1;
D
Daniel Veillard 已提交
1210 1211 1212

    virSkipSpaces(&cur);
    while (*cur != 0) {
1213
        unsigned int flags = 0;
1214
        prio = virParseNumber(&cur);
1215
        if ((prio < VIR_LOG_DEBUG) || (prio > VIR_LOG_ERROR))
1216
            goto cleanup;
D
Daniel Veillard 已提交
1217
        if (*cur != ':')
1218
            goto cleanup;
D
Daniel Veillard 已提交
1219
        cur++;
1220 1221 1222 1223
        if (*cur == '+') {
            flags |= VIR_LOG_STACK_TRACE;
            cur++;
        }
D
Daniel Veillard 已提交
1224 1225 1226 1227
        str = cur;
        while ((*cur != 0) && (!IS_SPACE(cur)))
            cur++;
        if (str == cur)
1228
            goto cleanup;
1229
        if (VIR_STRNDUP(name, str, cur - str) < 0)
1230
            goto cleanup;
1231
        if (virLogDefineFilter(name, prio, flags) >= 0)
1232
            count++;
D
Daniel Veillard 已提交
1233 1234 1235
        VIR_FREE(name);
        virSkipSpaces(&cur);
    }
1236 1237 1238
    ret = count;
cleanup:
    if (ret == -1)
1239
        VIR_WARN("Ignoring invalid log filter setting.");
1240
    return ret;
D
Daniel Veillard 已提交
1241
}
1242

1243

1244 1245 1246 1247 1248
/**
 * virLogGetDefaultPriority:
 *
 * Returns the current logging priority level.
 */
1249 1250 1251
virLogPriority
virLogGetDefaultPriority(void)
{
1252
    return virLogDefaultPriority;
1253 1254
}

1255

1256 1257 1258 1259 1260 1261 1262
/**
 * virLogGetFilters:
 *
 * Returns a string listing the current filters, in the format originally
 * specified in the config file or environment. Caller must free the
 * result.
 */
1263 1264 1265
char *
virLogGetFilters(void)
{
1266
    size_t i;
1267 1268 1269 1270
    virBuffer filterbuf = VIR_BUFFER_INITIALIZER;

    virLogLock();
    for (i = 0; i < virLogNbFilters; i++) {
1271 1272 1273 1274 1275 1276
        const char *sep = ":";
        if (virLogFilters[i].flags & VIR_LOG_STACK_TRACE)
            sep = ":+";
        virBufferAsprintf(&filterbuf, "%d%s%s ",
                          virLogFilters[i].priority,
                          sep,
1277 1278 1279 1280
                          virLogFilters[i].match);
    }
    virLogUnlock();

1281 1282
    if (virBufferError(&filterbuf)) {
        virBufferFreeAndReset(&filterbuf);
1283
        return NULL;
1284
    }
1285 1286 1287 1288

    return virBufferContentAndReset(&filterbuf);
}

1289

1290 1291 1292 1293 1294 1295 1296
/**
 * virLogGetOutputs:
 *
 * Returns a string listing the current outputs, in the format originally
 * specified in the config file or environment. Caller must free the
 * result.
 */
1297 1298 1299
char *
virLogGetOutputs(void)
{
1300
    size_t i;
1301 1302 1303 1304
    virBuffer outputbuf = VIR_BUFFER_INITIALIZER;

    virLogLock();
    for (i = 0; i < virLogNbOutputs; i++) {
1305
        virLogDestination dest = virLogOutputs[i].dest;
1306
        if (i)
1307
            virBufferAddChar(&outputbuf, ' ');
1308 1309 1310
        switch (dest) {
            case VIR_LOG_TO_SYSLOG:
            case VIR_LOG_TO_FILE:
1311
                virBufferAsprintf(&outputbuf, "%d:%s:%s",
1312 1313 1314 1315 1316
                                  virLogOutputs[i].priority,
                                  virLogOutputString(dest),
                                  virLogOutputs[i].name);
                break;
            default:
1317
                virBufferAsprintf(&outputbuf, "%d:%s",
1318 1319 1320 1321 1322 1323
                                  virLogOutputs[i].priority,
                                  virLogOutputString(dest));
        }
    }
    virLogUnlock();

1324 1325
    if (virBufferError(&outputbuf)) {
        virBufferFreeAndReset(&outputbuf);
1326
        return NULL;
1327
    }
1328 1329 1330 1331

    return virBufferContentAndReset(&outputbuf);
}

1332

1333 1334 1335 1336 1337
/**
 * virLogGetNbFilters:
 *
 * Returns the current number of defined log filters.
 */
1338 1339 1340
int
virLogGetNbFilters(void)
{
1341
    return virLogNbFilters;
1342 1343
}

1344

1345 1346 1347 1348 1349
/**
 * virLogGetNbOutputs:
 *
 * Returns the current number of defined log outputs.
 */
1350 1351 1352
int
virLogGetNbOutputs(void)
{
1353
    return virLogNbOutputs;
1354
}
1355

1356

1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
/**
 * 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
 *
1368
 * Returns 0 if successful, -1 in case of error.
1369
 */
1370 1371 1372
int
virLogParseDefaultPriority(const char *priority)
{
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
    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
1384
        VIR_WARN("Ignoring invalid log level setting");
1385 1386 1387 1388

    return ret;
}

1389

1390 1391 1392 1393 1394 1395
/**
 * virLogSetFromEnv:
 *
 * Sets virLogDefaultPriority, virLogFilters and virLogOutputs based on
 * environment variables.
 */
1396 1397 1398
void
virLogSetFromEnv(void)
{
1399
    const char *debugEnv;
1400

1401 1402 1403
    if (virLogInitialize() < 0)
        return;

1404
    debugEnv = virGetEnvAllowSUID("LIBVIRT_DEBUG");
1405 1406
    if (debugEnv && *debugEnv)
        virLogParseDefaultPriority(debugEnv);
1407
    debugEnv = virGetEnvAllowSUID("LIBVIRT_LOG_FILTERS");
1408
    if (debugEnv && *debugEnv)
1409
        virLogParseFilters(debugEnv);
1410
    debugEnv = virGetEnvAllowSUID("LIBVIRT_LOG_OUTPUTS");
1411
    if (debugEnv && *debugEnv)
1412
        virLogParseOutputs(debugEnv);
1413
}
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429


/*
 * 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;
}