virlog.c 38.2 KB
Newer Older
1
/*
2
 * virlog.c: internal logging and debugging
3
 *
4
 * Copyright (C) 2008, 2010-2014 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
static regex_t *virLogRegex;
65 66


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;
89 90
static virLogFilterPtr virLogFilters;
static int virLogNbFilters;
D
Daniel Veillard 已提交
91 92 93 94 95 96

/*
 * Outputs are used to emit the messages retained
 * after filtering, multiple output can be used simultaneously
 */
struct _virLogOutput {
97
    bool logInitMessage;
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
};
typedef struct _virLogOutput virLogOutput;
typedef virLogOutput *virLogOutputPtr;

108 109
static virLogOutputPtr virLogOutputs;
static int virLogNbOutputs;
D
Daniel Veillard 已提交
110 111 112 113

/*
 * 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++;
324
 cleanup:
D
Daniel Veillard 已提交
325
    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].logInitMessage = 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;
412
 cleanup:
D
Daniel Veillard 已提交
413
    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
    *rawmsg = VIR_LOG_VERSION_STRING;
    return virLogFormatString(msg, 0, NULL, VIR_LOG_INFO, VIR_LOG_VERSION_STRING);
453 454
}

455 456 457 458
/* Similar to virGetHostname() but avoids use of error
 * reporting APIs or logging APIs, to prevent recursion
 */
static int
459
virLogHostnameString(char **rawmsg,
460 461 462 463 464 465 466 467 468 469 470 471
                     char **msg)
{
    char *hostname = virGetHostnameQuiet();
    char *hoststr;

    if (!hostname)
        return -1;

    if (virAsprintfQuiet(&hoststr, "hostname: %s", hostname) < 0) {
        VIR_FREE(hostname);
        return -1;
    }
472
    VIR_FREE(hostname);
473 474 475 476 477 478 479 480 481

    if (virLogFormatString(msg, 0, NULL, VIR_LOG_INFO, hoststr) < 0) {
        VIR_FREE(hoststr);
        return -1;
    }
    *rawmsg = hoststr;
    return 0;
}

482

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
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 已提交
507 508
/**
 * virLogMessage:
509
 * @source: where is that message coming from
D
Daniel Veillard 已提交
510
 * @priority: the priority level
511
 * @filename: file where the message was emitted
512
 * @linenr: line where the message was emitted
513
 * @funcname: the function emitting the (debug) message
514
 * @metadata: NULL or metadata array, terminated by an item with NULL key
D
Daniel Veillard 已提交
515 516 517
 * @fmt: the string format
 * @...: the arguments
 *
E
Eric Blake 已提交
518
 * Call the libvirt logger with some information. Based on the configuration
D
Daniel Veillard 已提交
519 520
 * the message may be stored, sent to output or just discarded
 */
521
void
522
virLogMessage(virLogSourcePtr source,
523
              virLogPriority priority,
524
              const char *filename,
525
              int linenr,
526
              const char *funcname,
527
              virLogMetadataPtr metadata,
528
              const char *fmt, ...)
529 530 531
{
    va_list ap;
    va_start(ap, fmt);
532
    virLogVMessage(source, priority,
533
                   filename, linenr, funcname,
534
                   metadata, fmt, ap);
535 536 537
    va_end(ap);
}

538

539 540
/**
 * virLogVMessage:
541
 * @source: where is that message coming from
542
 * @priority: the priority level
543
 * @filename: file where the message was emitted
544
 * @linenr: line where the message was emitted
545
 * @funcname: the function emitting the (debug) message
546
 * @metadata: NULL or metadata array, terminated by an item with NULL key
547 548 549 550 551 552
 * @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
 */
553
void
554
virLogVMessage(virLogSourcePtr source,
555
               virLogPriority priority,
556
               const char *filename,
557
               int linenr,
558
               const char *funcname,
M
Miloslav Trmač 已提交
559
               virLogMetadataPtr metadata,
560 561
               const char *fmt,
               va_list vargs)
562
{
563
    static bool logInitMessageStderr = true;
D
Daniel Veillard 已提交
564
    char *str = NULL;
565
    char *msg = NULL;
566
    char timestamp[VIR_TIME_STRING_BUFLEN];
567
    int ret;
568
    size_t i;
569
    int saved_errno = errno;
570
    unsigned int filterflags = 0;
D
Daniel Veillard 已提交
571

572 573
    if (virLogInitialize() < 0)
        return;
D
Daniel Veillard 已提交
574 575

    if (fmt == NULL)
576
        return;
D
Daniel Veillard 已提交
577 578

    /*
579 580 581 582 583 584
     * 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 已提交
585
     */
586 587 588
    if (source->serial < virLogFiltersSerial)
        virLogSourceUpdate(source);
    if (priority < source->priority)
589
        goto cleanup;
590
    filterflags = source->flags;
591

D
Daniel Veillard 已提交
592 593 594
    /*
     * serialize the error message, add level and timestamp
     */
595
    if (virVasprintfQuiet(&str, fmt, vargs) < 0)
596
        goto cleanup;
D
Daniel Veillard 已提交
597

598
    ret = virLogFormatString(&msg, linenr, funcname, priority, str);
599 600
    if (ret < 0)
        goto cleanup;
D
Daniel Veillard 已提交
601

602 603
    if (virTimeStringNowRaw(timestamp) < 0)
        timestamp[0] = '\0';
604

605 606
    virLogLock();

D
Daniel Veillard 已提交
607
    /*
608
     * Push the message to the outputs defined, if none exist then
D
Daniel Veillard 已提交
609 610
     * use stderr.
     */
611
    for (i = 0; i < virLogNbOutputs; i++) {
612
        if (priority >= virLogOutputs[i].priority) {
613 614
            if (virLogOutputs[i].logInitMessage) {
                const char *rawinitmsg;
615
                char *hoststr = NULL;
616 617 618 619 620 621 622
                char *initmsg = NULL;
                if (virLogVersionString(&rawinitmsg, &initmsg) >= 0)
                    virLogOutputs[i].f(&virLogSelf, VIR_LOG_INFO,
                                       __FILE__, __LINE__, __func__,
                                       timestamp, NULL, 0, rawinitmsg, initmsg,
                                       virLogOutputs[i].data);
                VIR_FREE(initmsg);
623
                if (virLogHostnameString(&hoststr, &initmsg) >= 0)
624
                    virLogOutputs[i].f(&virLogSelf, VIR_LOG_INFO,
625
                                       __FILE__, __LINE__, __func__,
626
                                       timestamp, NULL, 0, hoststr, initmsg,
627
                                       virLogOutputs[i].data);
628
                VIR_FREE(hoststr);
629 630
                VIR_FREE(initmsg);
                virLogOutputs[i].logInitMessage = false;
631
            }
632
            virLogOutputs[i].f(source, priority,
633
                               filename, linenr, funcname,
M
Miloslav Trmač 已提交
634
                               timestamp, metadata, filterflags,
635
                               str, msg, virLogOutputs[i].data);
636
        }
D
Daniel Veillard 已提交
637
    }
638
    if (virLogNbOutputs == 0) {
639 640
        if (logInitMessageStderr) {
            const char *rawinitmsg;
641
            char *hoststr = NULL;
642 643 644 645 646 647 648
            char *initmsg = NULL;
            if (virLogVersionString(&rawinitmsg, &initmsg) >= 0)
                virLogOutputToFd(&virLogSelf, VIR_LOG_INFO,
                                 __FILE__, __LINE__, __func__,
                                 timestamp, NULL, 0, rawinitmsg, initmsg,
                                 (void *) STDERR_FILENO);
            VIR_FREE(initmsg);
649
            if (virLogHostnameString(&hoststr, &initmsg) >= 0)
650
                virLogOutputToFd(&virLogSelf, VIR_LOG_INFO,
651
                                 __FILE__, __LINE__, __func__,
652
                                 timestamp, NULL, 0, hoststr, initmsg,
653
                                 (void *) STDERR_FILENO);
654
            VIR_FREE(hoststr);
655 656
            VIR_FREE(initmsg);
            logInitMessageStderr = false;
657
        }
658
        virLogOutputToFd(source, priority,
659
                         filename, linenr, funcname,
M
Miloslav Trmač 已提交
660
                         timestamp, metadata, filterflags,
661
                         str, msg, (void *) STDERR_FILENO);
662
    }
D
Daniel Veillard 已提交
663 664
    virLogUnlock();

665
 cleanup:
666
    VIR_FREE(str);
667
    VIR_FREE(msg);
668
    errno = saved_errno;
D
Daniel Veillard 已提交
669 670
}

671

672 673
static void
virLogStackTraceToFd(int fd)
674 675 676
{
    void *array[100];
    int size;
677
    static bool doneWarning;
678
    const char *msg = "Stack trace not available on this platform\n";
679 680 681 682 683 684 685

#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) {
686 687 688
        ignore_value(safewrite(fd, msg, strlen(msg)));
        doneWarning = true;
    }
689
#undef STRIP_DEPTH
690 691
}

692
static void
693
virLogOutputToFd(virLogSourcePtr source ATTRIBUTE_UNUSED,
694
                 virLogPriority priority ATTRIBUTE_UNUSED,
695
                 const char *filename ATTRIBUTE_UNUSED,
696
                 int linenr ATTRIBUTE_UNUSED,
697
                 const char *funcname ATTRIBUTE_UNUSED,
698
                 const char *timestamp,
M
Miloslav Trmač 已提交
699
                 virLogMetadataPtr metadata ATTRIBUTE_UNUSED,
700 701 702 703
                 unsigned int flags,
                 const char *rawstr ATTRIBUTE_UNUSED,
                 const char *str,
                 void *data)
704
{
705
    int fd = (intptr_t) data;
706
    char *msg;
D
Daniel Veillard 已提交
707 708

    if (fd < 0)
709
        return;
710

711
    if (virAsprintfQuiet(&msg, "%s: %s", timestamp, str) < 0)
712
        return;
713

714
    ignore_value(safewrite(fd, msg, strlen(msg)));
715 716
    VIR_FREE(msg);

717 718
    if (flags & VIR_LOG_STACK_TRACE)
        virLogStackTraceToFd(fd);
D
Daniel Veillard 已提交
719 720
}

721 722 723

static void
virLogCloseFd(void *data)
724
{
725
    int fd = (intptr_t) data;
D
Daniel Veillard 已提交
726

727
    VIR_LOG_CLOSE(fd);
D
Daniel Veillard 已提交
728 729
}

730 731 732 733

static int
virLogAddOutputToStderr(virLogPriority priority)
{
734 735
    if (virLogDefineOutput(virLogOutputToFd, NULL, (void *)2L, priority,
                           VIR_LOG_TO_STDERR, NULL, 0) < 0)
736 737
        return -1;
    return 0;
D
Daniel Veillard 已提交
738 739
}

740 741 742 743 744

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

747
    fd = open(file, O_CREAT | O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR);
D
Daniel Veillard 已提交
748
    if (fd < 0)
749
        return -1;
750 751
    if (virLogDefineOutput(virLogOutputToFd, virLogCloseFd,
                           (void *)(intptr_t)fd,
752
                           priority, VIR_LOG_TO_FILE, file, 0) < 0) {
753
        VIR_FORCE_CLOSE(fd);
754
        return -1;
D
Daniel Veillard 已提交
755
    }
756
    return 0;
D
Daniel Veillard 已提交
757 758
}

759

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
#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

776 777
static int
virLogPrioritySyslog(virLogPriority priority)
778 779 780 781 782 783 784 785 786 787 788 789 790 791
{
    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;
    }
}
792
#endif /* HAVE_SYSLOG_H || USE_JOURNALD */
793

794

795
#if HAVE_SYSLOG_H
796
static void
797
virLogOutputToSyslog(virLogSourcePtr source ATTRIBUTE_UNUSED,
798
                     virLogPriority priority,
799
                     const char *filename ATTRIBUTE_UNUSED,
800
                     int linenr ATTRIBUTE_UNUSED,
801
                     const char *funcname ATTRIBUTE_UNUSED,
802
                     const char *timestamp ATTRIBUTE_UNUSED,
M
Miloslav Trmač 已提交
803
                     virLogMetadataPtr metadata ATTRIBUTE_UNUSED,
804 805 806 807
                     unsigned int flags,
                     const char *rawstr ATTRIBUTE_UNUSED,
                     const char *str,
                     void *data ATTRIBUTE_UNUSED)
808
{
809
    virCheckFlags(VIR_LOG_STACK_TRACE,);
810

811
    syslog(virLogPrioritySyslog(priority), "%s", str);
D
Daniel Veillard 已提交
812 813
}

814
static char *current_ident;
815

816 817 818 819

static void
virLogCloseSyslog(void *data ATTRIBUTE_UNUSED)
{
D
Daniel Veillard 已提交
820
    closelog();
821
    VIR_FREE(current_ident);
D
Daniel Veillard 已提交
822 823
}

824 825 826 827 828

static int
virLogAddOutputToSyslog(virLogPriority priority,
                        const char *ident)
{
829 830 831 832
    /*
     * ident needs to be kept around on Solaris
     */
    VIR_FREE(current_ident);
833
    if (VIR_STRDUP(current_ident, ident) < 0)
834
        return -1;
835 836

    openlog(current_ident, 0, 0);
D
Daniel Veillard 已提交
837
    if (virLogDefineOutput(virLogOutputToSyslog, virLogCloseSyslog, NULL,
838
                           priority, VIR_LOG_TO_SYSLOG, ident, 0) < 0) {
D
Daniel Veillard 已提交
839
        closelog();
840
        VIR_FREE(current_ident);
841
        return -1;
D
Daniel Veillard 已提交
842
    }
843
    return 0;
D
Daniel Veillard 已提交
844
}
D
Daniel P. Berrange 已提交
845 846


E
Eric Blake 已提交
847
# if USE_JOURNALD
848 849 850 851 852
#  define IOVEC_SET(iov, data, size)            \
    do {                                        \
        struct iovec *_i = &(iov);              \
        _i->iov_base = (void*)(data);           \
        _i->iov_len = (size);                   \
D
Daniel P. Berrange 已提交
853 854
    } while (0)

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 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
#  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 已提交
920 921 922 923

static int journalfd = -1;

static void
924
virLogOutputToJournald(virLogSourcePtr source,
D
Daniel P. Berrange 已提交
925 926 927 928 929
                       virLogPriority priority,
                       const char *filename,
                       int linenr,
                       const char *funcname,
                       const char *timestamp ATTRIBUTE_UNUSED,
930
                       virLogMetadataPtr metadata,
D
Daniel P. Berrange 已提交
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
                       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";
949
    size_t nmetadata = 0;
D
Daniel P. Berrange 已提交
950

951 952 953
#  define NUM_FIELDS_CORE 6
#  define NUM_FIELDS_META 5
#  define NUM_FIELDS (NUM_FIELDS_CORE + NUM_FIELDS_META)
954 955 956
    struct iovec iov[NUM_FIELDS * 5];
    char iov_bufs[NUM_FIELDS][JOURNAL_BUF_SIZE];
    struct journalState state;
D
Daniel P. Berrange 已提交
957

958 959 960 961
    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 已提交
962

E
Eric Blake 已提交
963
    journalAddString(&state, "MESSAGE", rawstr);
964 965
    journalAddInt(&state, "PRIORITY",
                  virLogPrioritySyslog(priority));
966
    journalAddInt(&state, "SYSLOG_FACILITY", LOG_DAEMON);
967
    journalAddString(&state, "LIBVIRT_SOURCE", source->name);
968 969
    if (filename)
        journalAddString(&state, "CODE_FILE", filename);
970
    journalAddInt(&state, "CODE_LINE", linenr);
971 972
    if (funcname)
        journalAddString(&state, "CODE_FUNC", funcname);
973 974 975 976 977 978 979 980 981 982 983
    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 已提交
984 985 986 987 988 989 990 991 992 993

    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;
994
    mh.msg_iovlen = state.iov - iov;
D
Daniel P. Berrange 已提交
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

    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;

1018
    if (writev(buffd, iov, state.iov - iov) < 0)
D
Daniel P. Berrange 已提交
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
        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;

1036
    ignore_value(sendmsg(journalfd, &mh, MSG_NOSIGNAL));
D
Daniel P. Berrange 已提交
1037

1038
 cleanup:
D
Daniel P. Berrange 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
    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 已提交
1063
# endif /* USE_JOURNALD */
J
Ján Tomko 已提交
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088

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 已提交
1089 1090 1091 1092 1093 1094
#endif /* HAVE_SYSLOG_H */

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

1095

D
Daniel Veillard 已提交
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
/**
 * 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.
 *
1116 1117 1118
 * If running in setuid mode, then only the 'stderr' output will
 * be allowed
 *
D
Daniel Veillard 已提交
1119 1120
 * Returns the number of output parsed and installed or -1 in case of error
 */
1121 1122 1123
int
virLogParseOutputs(const char *outputs)
{
D
Daniel Veillard 已提交
1124 1125
    const char *cur = outputs, *str;
    char *name;
1126
    char *abspath;
1127
    virLogPriority prio;
1128 1129
    int ret = -1;
    int count = 0;
1130
    bool isSUID = virIsSUID();
D
Daniel Veillard 已提交
1131 1132

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

1135 1136
    VIR_DEBUG("outputs=%s", outputs);

D
Daniel Veillard 已提交
1137 1138
    virSkipSpaces(&cur);
    while (*cur != 0) {
1139
        prio = virParseNumber(&cur);
1140
        if ((prio < VIR_LOG_DEBUG) || (prio > VIR_LOG_ERROR))
1141
            goto cleanup;
D
Daniel Veillard 已提交
1142
        if (*cur != ':')
1143
            goto cleanup;
D
Daniel Veillard 已提交
1144 1145 1146 1147
        cur++;
        if (STREQLEN(cur, "stderr", 6)) {
            cur += 6;
            if (virLogAddOutputToStderr(prio) == 0)
1148
                count++;
D
Daniel Veillard 已提交
1149
        } else if (STREQLEN(cur, "syslog", 6)) {
1150 1151
            if (isSUID)
                goto cleanup;
D
Daniel Veillard 已提交
1152 1153
            cur += 6;
            if (*cur != ':')
1154
                goto cleanup;
D
Daniel Veillard 已提交
1155 1156 1157 1158 1159
            cur++;
            str = cur;
            while ((*cur != 0) && (!IS_SPACE(cur)))
                cur++;
            if (str == cur)
1160
                goto cleanup;
D
Daniel Veillard 已提交
1161
#if HAVE_SYSLOG_H
1162
            if (VIR_STRNDUP(name, str, cur - str) < 0)
1163
                goto cleanup;
D
Daniel Veillard 已提交
1164
            if (virLogAddOutputToSyslog(prio, name) == 0)
1165
                count++;
D
Daniel Veillard 已提交
1166 1167 1168
            VIR_FREE(name);
#endif /* HAVE_SYSLOG_H */
        } else if (STREQLEN(cur, "file", 4)) {
1169 1170
            if (isSUID)
                goto cleanup;
D
Daniel Veillard 已提交
1171 1172
            cur += 4;
            if (*cur != ':')
1173
                goto cleanup;
D
Daniel Veillard 已提交
1174 1175 1176 1177 1178
            cur++;
            str = cur;
            while ((*cur != 0) && (!IS_SPACE(cur)))
                cur++;
            if (str == cur)
1179
                goto cleanup;
1180
            if (VIR_STRNDUP(name, str, cur - str) < 0)
1181
                goto cleanup;
1182 1183 1184 1185 1186
            if (virFileAbsPath(name, &abspath) < 0) {
                VIR_FREE(name);
                return -1; /* skip warning here because setting was fine */
            }
            if (virLogAddOutputToFile(prio, abspath) == 0)
1187
                count++;
D
Daniel Veillard 已提交
1188
            VIR_FREE(name);
1189
            VIR_FREE(abspath);
D
Daniel P. Berrange 已提交
1190
        } else if (STREQLEN(cur, "journald", 8)) {
1191 1192
            if (isSUID)
                goto cleanup;
D
Daniel P. Berrange 已提交
1193
            cur += 8;
E
Eric Blake 已提交
1194
#if USE_JOURNALD
D
Daniel P. Berrange 已提交
1195 1196
            if (virLogAddOutputToJournald(prio) == 0)
                count++;
E
Eric Blake 已提交
1197
#endif /* USE_JOURNALD */
D
Daniel Veillard 已提交
1198
        } else {
1199
            goto cleanup;
D
Daniel Veillard 已提交
1200 1201 1202
        }
        virSkipSpaces(&cur);
    }
1203
    ret = count;
1204
 cleanup:
1205
    if (ret == -1)
1206
        VIR_WARN("Ignoring invalid log output setting.");
1207
    return ret;
D
Daniel Veillard 已提交
1208 1209
}

1210

D
Daniel Veillard 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
/**
 * 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
 */
1229 1230 1231
int
virLogParseFilters(const char *filters)
{
D
Daniel Veillard 已提交
1232 1233
    const char *cur = filters, *str;
    char *name;
1234
    virLogPriority prio;
1235 1236
    int ret = -1;
    int count = 0;
D
Daniel Veillard 已提交
1237 1238

    if (cur == NULL)
1239
        return -1;
D
Daniel Veillard 已提交
1240 1241 1242

    virSkipSpaces(&cur);
    while (*cur != 0) {
1243
        unsigned int flags = 0;
1244
        prio = virParseNumber(&cur);
1245
        if ((prio < VIR_LOG_DEBUG) || (prio > VIR_LOG_ERROR))
1246
            goto cleanup;
D
Daniel Veillard 已提交
1247
        if (*cur != ':')
1248
            goto cleanup;
D
Daniel Veillard 已提交
1249
        cur++;
1250 1251 1252 1253
        if (*cur == '+') {
            flags |= VIR_LOG_STACK_TRACE;
            cur++;
        }
D
Daniel Veillard 已提交
1254 1255 1256 1257
        str = cur;
        while ((*cur != 0) && (!IS_SPACE(cur)))
            cur++;
        if (str == cur)
1258
            goto cleanup;
1259
        if (VIR_STRNDUP(name, str, cur - str) < 0)
1260
            goto cleanup;
1261
        if (virLogDefineFilter(name, prio, flags) >= 0)
1262
            count++;
D
Daniel Veillard 已提交
1263 1264 1265
        VIR_FREE(name);
        virSkipSpaces(&cur);
    }
1266
    ret = count;
1267
 cleanup:
1268
    if (ret == -1)
1269
        VIR_WARN("Ignoring invalid log filter setting.");
1270
    return ret;
D
Daniel Veillard 已提交
1271
}
1272

1273

1274 1275 1276 1277 1278
/**
 * virLogGetDefaultPriority:
 *
 * Returns the current logging priority level.
 */
1279 1280 1281
virLogPriority
virLogGetDefaultPriority(void)
{
1282
    return virLogDefaultPriority;
1283 1284
}

1285

1286 1287 1288 1289 1290 1291 1292
/**
 * virLogGetFilters:
 *
 * Returns a string listing the current filters, in the format originally
 * specified in the config file or environment. Caller must free the
 * result.
 */
1293 1294 1295
char *
virLogGetFilters(void)
{
1296
    size_t i;
1297 1298 1299 1300
    virBuffer filterbuf = VIR_BUFFER_INITIALIZER;

    virLogLock();
    for (i = 0; i < virLogNbFilters; i++) {
1301 1302 1303 1304 1305 1306
        const char *sep = ":";
        if (virLogFilters[i].flags & VIR_LOG_STACK_TRACE)
            sep = ":+";
        virBufferAsprintf(&filterbuf, "%d%s%s ",
                          virLogFilters[i].priority,
                          sep,
1307 1308 1309 1310
                          virLogFilters[i].match);
    }
    virLogUnlock();

1311 1312
    if (virBufferError(&filterbuf)) {
        virBufferFreeAndReset(&filterbuf);
1313
        return NULL;
1314
    }
1315 1316 1317 1318

    return virBufferContentAndReset(&filterbuf);
}

1319

1320 1321 1322 1323 1324 1325 1326
/**
 * virLogGetOutputs:
 *
 * Returns a string listing the current outputs, in the format originally
 * specified in the config file or environment. Caller must free the
 * result.
 */
1327 1328 1329
char *
virLogGetOutputs(void)
{
1330
    size_t i;
1331 1332 1333 1334
    virBuffer outputbuf = VIR_BUFFER_INITIALIZER;

    virLogLock();
    for (i = 0; i < virLogNbOutputs; i++) {
1335
        virLogDestination dest = virLogOutputs[i].dest;
1336
        if (i)
1337
            virBufferAddChar(&outputbuf, ' ');
1338 1339 1340
        switch (dest) {
            case VIR_LOG_TO_SYSLOG:
            case VIR_LOG_TO_FILE:
1341
                virBufferAsprintf(&outputbuf, "%d:%s:%s",
1342 1343 1344 1345 1346
                                  virLogOutputs[i].priority,
                                  virLogOutputString(dest),
                                  virLogOutputs[i].name);
                break;
            default:
1347
                virBufferAsprintf(&outputbuf, "%d:%s",
1348 1349 1350 1351 1352 1353
                                  virLogOutputs[i].priority,
                                  virLogOutputString(dest));
        }
    }
    virLogUnlock();

1354 1355
    if (virBufferError(&outputbuf)) {
        virBufferFreeAndReset(&outputbuf);
1356
        return NULL;
1357
    }
1358 1359 1360 1361

    return virBufferContentAndReset(&outputbuf);
}

1362

1363 1364 1365 1366 1367
/**
 * virLogGetNbFilters:
 *
 * Returns the current number of defined log filters.
 */
1368 1369 1370
int
virLogGetNbFilters(void)
{
1371
    return virLogNbFilters;
1372 1373
}

1374

1375 1376 1377 1378 1379
/**
 * virLogGetNbOutputs:
 *
 * Returns the current number of defined log outputs.
 */
1380 1381 1382
int
virLogGetNbOutputs(void)
{
1383
    return virLogNbOutputs;
1384
}
1385

1386

1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
/**
 * 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
 *
1398
 * Returns 0 if successful, -1 in case of error.
1399
 */
1400 1401 1402
int
virLogParseDefaultPriority(const char *priority)
{
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
    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
1414
        VIR_WARN("Ignoring invalid log level setting");
1415 1416 1417 1418

    return ret;
}

1419

1420 1421 1422 1423 1424 1425
/**
 * virLogSetFromEnv:
 *
 * Sets virLogDefaultPriority, virLogFilters and virLogOutputs based on
 * environment variables.
 */
1426 1427 1428
void
virLogSetFromEnv(void)
{
1429
    const char *debugEnv;
1430

1431 1432 1433
    if (virLogInitialize() < 0)
        return;

1434
    debugEnv = virGetEnvAllowSUID("LIBVIRT_DEBUG");
1435 1436
    if (debugEnv && *debugEnv)
        virLogParseDefaultPriority(debugEnv);
1437
    debugEnv = virGetEnvAllowSUID("LIBVIRT_LOG_FILTERS");
1438
    if (debugEnv && *debugEnv)
1439
        virLogParseFilters(debugEnv);
1440
    debugEnv = virGetEnvAllowSUID("LIBVIRT_LOG_OUTPUTS");
1441
    if (debugEnv && *debugEnv)
1442
        virLogParseOutputs(debugEnv);
1443
}
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459


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