virlog.c 44.0 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
VIR_ENUM_DECL(virLogDestination);
VIR_ENUM_IMPL(virLogDestination, VIR_LOG_TO_OUTPUT_LAST,
              "stderr", "syslog", "file", "journald");

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

90
static int virLogFiltersSerial = 1;
91 92
static virLogFilterPtr *virLogFilters;
static size_t virLogNbFilters;
D
Daniel Veillard 已提交
93 94 95 96 97 98

/*
 * Outputs are used to emit the messages retained
 * after filtering, multiple output can be used simultaneously
 */
struct _virLogOutput {
99
    bool logInitMessage;
D
Daniel Veillard 已提交
100 101 102
    void *data;
    virLogOutputFunc f;
    virLogCloseFunc c;
103
    virLogPriority priority;
104
    virLogDestination dest;
105
    char *name;
D
Daniel Veillard 已提交
106 107
};

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

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

116 117
static void virLogResetFilters(void);
static void 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 *
virLogPriorityString(virLogPriority lvl)
{
D
Daniel Veillard 已提交
153
    switch (lvl) {
154 155 156 157 158 159 160 161
    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 已提交
162
    }
163
    return "unknown";
D
Daniel Veillard 已提交
164 165 166
}


167 168
static int
virLogOnceInit(void)
169
{
170 171 172
    if (virMutexInit(&virLogMutex) < 0)
        return -1;

D
Daniel Veillard 已提交
173
    virLogLock();
174
    virLogDefaultPriority = VIR_LOG_DEFAULT;
175

176
    if (VIR_ALLOC_QUIET(virLogRegex) >= 0) {
177 178 179 180
        if (regcomp(virLogRegex, VIR_LOG_REGEX, REG_EXTENDED) != 0)
            VIR_FREE(virLogRegex);
    }

D
Daniel Veillard 已提交
181
    virLogUnlock();
182
    return 0;
D
Daniel Veillard 已提交
183 184
}

185 186
VIR_ONCE_GLOBAL_INIT(virLog)

187

D
Daniel Veillard 已提交
188 189 190 191 192 193 194
/**
 * virLogReset:
 *
 * Reset the logging module to its default initial state
 *
 * Returns 0 if successful, and -1 in case or error
 */
195 196 197
int
virLogReset(void)
{
198 199
    if (virLogInitialize() < 0)
        return -1;
D
Daniel Veillard 已提交
200 201 202 203

    virLogLock();
    virLogResetFilters();
    virLogResetOutputs();
204
    virLogDefaultPriority = VIR_LOG_DEFAULT;
D
Daniel Veillard 已提交
205
    virLogUnlock();
206
    return 0;
D
Daniel Veillard 已提交
207 208 209 210 211 212 213 214 215 216 217 218
}

/**
 * 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.
 */
219 220 221
int
virLogSetDefaultPriority(virLogPriority priority)
{
222
    if ((priority < VIR_LOG_DEBUG) || (priority > VIR_LOG_ERROR)) {
223
        VIR_WARN("Ignoring invalid log level setting.");
224
        return -1;
225
    }
226 227 228
    if (virLogInitialize() < 0)
        return -1;

D
Daniel Veillard 已提交
229
    virLogDefaultPriority = priority;
230
    return 0;
D
Daniel Veillard 已提交
231 232
}

233

D
Daniel Veillard 已提交
234 235 236 237 238
/**
 * virLogResetFilters:
 *
 * Removes the set of logging filters defined.
 */
239
static void
240 241
virLogResetFilters(void)
{
242 243
    virLogFilterListFree(virLogFilters, virLogNbFilters);
    virLogFilters = NULL;
D
Daniel Veillard 已提交
244
    virLogNbFilters = 0;
245
    virLogFiltersSerial++;
D
Daniel Veillard 已提交
246 247
}

248

249 250 251 252 253 254 255 256 257 258
void
virLogFilterFree(virLogFilterPtr filter)
{
    if (!filter)
        return;

    VIR_FREE(filter->match);
    VIR_FREE(filter);
}

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280

/**
 * virLogFilterFreeList:
 * @list: list of filters to be freed
 * @count: number of elements in the list
 *
 * Frees a list of filters.
 */
void
virLogFilterListFree(virLogFilterPtr *list, int count)
{
    size_t i;

    if (!list || count < 0)
        return;

    for (i = 0; i < count; i++)
        virLogFilterFree(list[i]);
    VIR_FREE(list);
}


D
Daniel Veillard 已提交
281 282 283 284
/**
 * virLogDefineFilter:
 * @match: the pattern to match
 * @priority: the priority to give to messages matching the pattern
285
 * @flags: extra flags, see virLogFilterFlags enum
D
Daniel Veillard 已提交
286 287 288 289 290 291 292 293
 *
 * 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
 */
294 295 296 297
int
virLogDefineFilter(const char *match,
                   virLogPriority priority,
                   unsigned int flags)
298
{
299 300
    size_t i;
    int ret = -1;
D
Daniel Veillard 已提交
301
    char *mdup = NULL;
302
    virLogFilterPtr filter = NULL;
D
Daniel Veillard 已提交
303

304
    virCheckFlags(VIR_LOG_STACK_TRACE, -1);
305

306 307 308
    if (virLogInitialize() < 0)
        return -1;

D
Daniel Veillard 已提交
309 310
    if ((match == NULL) || (priority < VIR_LOG_DEBUG) ||
        (priority > VIR_LOG_ERROR))
311
        return -1;
D
Daniel Veillard 已提交
312 313

    virLogLock();
314
    for (i = 0; i < virLogNbFilters; i++) {
315 316
        if (STREQ(virLogFilters[i]->match, match)) {
            virLogFilters[i]->priority = priority;
317
            ret = i;
D
Daniel Veillard 已提交
318 319 320 321
            goto cleanup;
        }
    }

322
    if (VIR_STRDUP_QUIET(mdup, match) < 0)
D
Daniel Veillard 已提交
323
        goto cleanup;
324 325

    if (VIR_ALLOC_QUIET(filter) < 0) {
D
Daniel Veillard 已提交
326 327 328
        VIR_FREE(mdup);
        goto cleanup;
    }
329 330 331 332 333 334 335 336

    filter->match = mdup;
    filter->priority = priority;
    filter->flags = flags;

    if (VIR_APPEND_ELEMENT_QUIET(virLogFilters, virLogNbFilters, filter) < 0)
        goto cleanup;

337
    virLogFiltersSerial++;
338
    ret = virLogNbFilters - 1;
339
 cleanup:
D
Daniel Veillard 已提交
340
    virLogUnlock();
341
    if (ret < 0)
342
        virReportOOMError();
343
    return ret;
D
Daniel Veillard 已提交
344 345 346 347 348 349 350
}

/**
 * virLogResetOutputs:
 *
 * Removes the set of logging output defined.
 */
351
static void
352 353
virLogResetOutputs(void)
{
354 355
    virLogOutputListFree(virLogOutputs, virLogNbOutputs);
    virLogOutputs = NULL;
D
Daniel Veillard 已提交
356 357 358
    virLogNbOutputs = 0;
}

359

360 361 362 363 364 365 366 367 368 369 370 371 372
void
virLogOutputFree(virLogOutputPtr output)
{
    if (!output)
        return;

    if (output->c)
        output->c(output->data);
    VIR_FREE(output->name);
    VIR_FREE(output);

}

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

/**
 * virLogOutputsFreeList:
 * @list: list of outputs to be freed
 * @count: number of elements in the list
 *
 * Frees a list of outputs.
 */
void
virLogOutputListFree(virLogOutputPtr *list, int count)
{
    size_t i;

    if (!list || count < 0)
        return;

    for (i = 0; i < count; i++)
        virLogOutputFree(list[i]);
    VIR_FREE(list);
}


D
Daniel Veillard 已提交
395 396 397
/**
 * virLogDefineOutput:
 * @f: the function to call to output a message
398
 * @c: the function to call to close the output (or NULL)
D
Daniel Veillard 已提交
399 400
 * @data: extra data passed as first arg to the function
 * @priority: minimal priority for this filter, use 0 for none
401 402
 * @dest: where to send output of this priority
 * @name: optional name data associated with an output
D
Daniel Veillard 已提交
403 404 405 406 407 408 409
 * @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
 */
410 411 412 413 414 415 416 417
int
virLogDefineOutput(virLogOutputFunc f,
                   virLogCloseFunc c,
                   void *data,
                   virLogPriority priority,
                   virLogDestination dest,
                   const char *name,
                   unsigned int flags)
418
{
419
    char *ndup = NULL;
420
    virLogOutputPtr output = NULL;
D
Daniel Veillard 已提交
421

422 423
    virCheckFlags(0, -1);

424 425 426
    if (virLogInitialize() < 0)
        return -1;

D
Daniel Veillard 已提交
427
    if (f == NULL)
428
        return -1;
D
Daniel Veillard 已提交
429

430
    if (dest == VIR_LOG_TO_SYSLOG || dest == VIR_LOG_TO_FILE) {
431 432
        if (!name) {
            virReportOOMError();
433
            return -1;
434 435
        }
        if (VIR_STRDUP(ndup, name) < 0)
436
            return -1;
437 438
    }

439
    if (VIR_ALLOC_QUIET(output) < 0) {
440
        VIR_FREE(ndup);
441
        return -1;
D
Daniel Veillard 已提交
442
    }
443 444 445 446 447 448 449 450 451 452 453 454 455

    output->logInitMessage = true;
    output->f = f;
    output->c = c;
    output->data = data;
    output->priority = priority;
    output->dest = dest;
    output->name = ndup;

    virLogLock();
    if (VIR_APPEND_ELEMENT_QUIET(virLogOutputs, virLogNbOutputs, output))
        goto cleanup;

456
 cleanup:
D
Daniel Veillard 已提交
457
    virLogUnlock();
458
    return virLogNbOutputs;
D
Daniel Veillard 已提交
459 460
}

461

462 463
static int
virLogFormatString(char **msg,
464
                   int linenr,
465
                   const char *funcname,
466
                   virLogPriority priority,
467 468 469
                   const char *str)
{
    int ret;
470 471 472 473 474 475 476 477

    /*
     * 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.
     */
478
    if ((funcname != NULL)) {
479 480 481
        ret = virAsprintfQuiet(msg, "%llu: %s : %s:%d : %s\n",
                               virThreadSelfID(), virLogPriorityString(priority),
                               funcname, linenr, str);
482
    } else {
483 484 485
        ret = virAsprintfQuiet(msg, "%llu: %s : %s\n",
                               virThreadSelfID(), virLogPriorityString(priority),
                               str);
486 487 488 489
    }
    return ret;
}

490

491
static int
492 493
virLogVersionString(const char **rawmsg,
                    char **msg)
494
{
495 496
    *rawmsg = VIR_LOG_VERSION_STRING;
    return virLogFormatString(msg, 0, NULL, VIR_LOG_INFO, VIR_LOG_VERSION_STRING);
497 498
}

499 500 501 502
/* Similar to virGetHostname() but avoids use of error
 * reporting APIs or logging APIs, to prevent recursion
 */
static int
503
virLogHostnameString(char **rawmsg,
504 505 506 507 508 509 510 511 512 513 514 515
                     char **msg)
{
    char *hostname = virGetHostnameQuiet();
    char *hoststr;

    if (!hostname)
        return -1;

    if (virAsprintfQuiet(&hoststr, "hostname: %s", hostname) < 0) {
        VIR_FREE(hostname);
        return -1;
    }
516
    VIR_FREE(hostname);
517 518 519 520 521 522 523 524 525

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

526

527 528 529 530 531 532 533 534 535 536
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++) {
537 538 539
            if (strstr(source->name, virLogFilters[i]->match)) {
                priority = virLogFilters[i]->priority;
                flags = virLogFilters[i]->flags;
540 541 542 543 544 545 546 547 548 549 550
                break;
            }
        }

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

D
Daniel Veillard 已提交
551 552
/**
 * virLogMessage:
553
 * @source: where is that message coming from
D
Daniel Veillard 已提交
554
 * @priority: the priority level
555
 * @filename: file where the message was emitted
556
 * @linenr: line where the message was emitted
557
 * @funcname: the function emitting the (debug) message
558
 * @metadata: NULL or metadata array, terminated by an item with NULL key
D
Daniel Veillard 已提交
559 560 561
 * @fmt: the string format
 * @...: the arguments
 *
E
Eric Blake 已提交
562
 * Call the libvirt logger with some information. Based on the configuration
D
Daniel Veillard 已提交
563 564
 * the message may be stored, sent to output or just discarded
 */
565
void
566
virLogMessage(virLogSourcePtr source,
567
              virLogPriority priority,
568
              const char *filename,
569
              int linenr,
570
              const char *funcname,
571
              virLogMetadataPtr metadata,
572
              const char *fmt, ...)
573 574 575
{
    va_list ap;
    va_start(ap, fmt);
576
    virLogVMessage(source, priority,
577
                   filename, linenr, funcname,
578
                   metadata, fmt, ap);
579 580 581
    va_end(ap);
}

582

583 584
/**
 * virLogVMessage:
585
 * @source: where is that message coming from
586
 * @priority: the priority level
587
 * @filename: file where the message was emitted
588
 * @linenr: line where the message was emitted
589
 * @funcname: the function emitting the (debug) message
590
 * @metadata: NULL or metadata array, terminated by an item with NULL key
591 592 593 594 595 596
 * @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
 */
597
void
598
virLogVMessage(virLogSourcePtr source,
599
               virLogPriority priority,
600
               const char *filename,
601
               int linenr,
602
               const char *funcname,
M
Miloslav Trmač 已提交
603
               virLogMetadataPtr metadata,
604 605
               const char *fmt,
               va_list vargs)
606
{
607
    static bool logInitMessageStderr = true;
D
Daniel Veillard 已提交
608
    char *str = NULL;
609
    char *msg = NULL;
610
    char timestamp[VIR_TIME_STRING_BUFLEN];
611
    int ret;
612
    size_t i;
613
    int saved_errno = errno;
614
    unsigned int filterflags = 0;
D
Daniel Veillard 已提交
615

616 617
    if (virLogInitialize() < 0)
        return;
D
Daniel Veillard 已提交
618 619

    if (fmt == NULL)
620
        return;
D
Daniel Veillard 已提交
621 622

    /*
623 624 625 626 627 628
     * 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 已提交
629
     */
630 631 632
    if (source->serial < virLogFiltersSerial)
        virLogSourceUpdate(source);
    if (priority < source->priority)
633
        goto cleanup;
634
    filterflags = source->flags;
635

D
Daniel Veillard 已提交
636 637 638
    /*
     * serialize the error message, add level and timestamp
     */
639
    if (virVasprintfQuiet(&str, fmt, vargs) < 0)
640
        goto cleanup;
D
Daniel Veillard 已提交
641

642
    ret = virLogFormatString(&msg, linenr, funcname, priority, str);
643 644
    if (ret < 0)
        goto cleanup;
D
Daniel Veillard 已提交
645

646 647
    if (virTimeStringNowRaw(timestamp) < 0)
        timestamp[0] = '\0';
648

649 650
    virLogLock();

D
Daniel Veillard 已提交
651
    /*
652
     * Push the message to the outputs defined, if none exist then
D
Daniel Veillard 已提交
653 654
     * use stderr.
     */
655
    for (i = 0; i < virLogNbOutputs; i++) {
656 657
        if (priority >= virLogOutputs[i]->priority) {
            if (virLogOutputs[i]->logInitMessage) {
658
                const char *rawinitmsg;
659
                char *hoststr = NULL;
660 661
                char *initmsg = NULL;
                if (virLogVersionString(&rawinitmsg, &initmsg) >= 0)
662
                    virLogOutputs[i]->f(&virLogSelf, VIR_LOG_INFO,
663 664
                                       __FILE__, __LINE__, __func__,
                                       timestamp, NULL, 0, rawinitmsg, initmsg,
665
                                       virLogOutputs[i]->data);
666
                VIR_FREE(initmsg);
667
                if (virLogHostnameString(&hoststr, &initmsg) >= 0)
668
                    virLogOutputs[i]->f(&virLogSelf, VIR_LOG_INFO,
669
                                       __FILE__, __LINE__, __func__,
670
                                       timestamp, NULL, 0, hoststr, initmsg,
671
                                       virLogOutputs[i]->data);
672
                VIR_FREE(hoststr);
673
                VIR_FREE(initmsg);
674
                virLogOutputs[i]->logInitMessage = false;
675
            }
676
            virLogOutputs[i]->f(source, priority,
677
                               filename, linenr, funcname,
M
Miloslav Trmač 已提交
678
                               timestamp, metadata, filterflags,
679
                               str, msg, virLogOutputs[i]->data);
680
        }
D
Daniel Veillard 已提交
681
    }
682
    if (virLogNbOutputs == 0) {
683 684
        if (logInitMessageStderr) {
            const char *rawinitmsg;
685
            char *hoststr = NULL;
686 687 688 689 690 691 692
            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);
693
            if (virLogHostnameString(&hoststr, &initmsg) >= 0)
694
                virLogOutputToFd(&virLogSelf, VIR_LOG_INFO,
695
                                 __FILE__, __LINE__, __func__,
696
                                 timestamp, NULL, 0, hoststr, initmsg,
697
                                 (void *) STDERR_FILENO);
698
            VIR_FREE(hoststr);
699 700
            VIR_FREE(initmsg);
            logInitMessageStderr = false;
701
        }
702
        virLogOutputToFd(source, priority,
703
                         filename, linenr, funcname,
M
Miloslav Trmač 已提交
704
                         timestamp, metadata, filterflags,
705
                         str, msg, (void *) STDERR_FILENO);
706
    }
D
Daniel Veillard 已提交
707 708
    virLogUnlock();

709
 cleanup:
710
    VIR_FREE(str);
711
    VIR_FREE(msg);
712
    errno = saved_errno;
D
Daniel Veillard 已提交
713 714
}

715

716 717
static void
virLogStackTraceToFd(int fd)
718 719 720
{
    void *array[100];
    int size;
721
    static bool doneWarning;
722
    const char *msg = "Stack trace not available on this platform\n";
723 724 725 726 727 728 729

#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) {
730 731 732
        ignore_value(safewrite(fd, msg, strlen(msg)));
        doneWarning = true;
    }
733
#undef STRIP_DEPTH
734 735
}

736
static void
737
virLogOutputToFd(virLogSourcePtr source ATTRIBUTE_UNUSED,
738
                 virLogPriority priority ATTRIBUTE_UNUSED,
739
                 const char *filename ATTRIBUTE_UNUSED,
740
                 int linenr ATTRIBUTE_UNUSED,
741
                 const char *funcname ATTRIBUTE_UNUSED,
742
                 const char *timestamp,
M
Miloslav Trmač 已提交
743
                 virLogMetadataPtr metadata ATTRIBUTE_UNUSED,
744 745 746 747
                 unsigned int flags,
                 const char *rawstr ATTRIBUTE_UNUSED,
                 const char *str,
                 void *data)
748
{
749
    int fd = (intptr_t) data;
750
    char *msg;
D
Daniel Veillard 已提交
751 752

    if (fd < 0)
753
        return;
754

755
    if (virAsprintfQuiet(&msg, "%s: %s", timestamp, str) < 0)
756
        return;
757

758
    ignore_value(safewrite(fd, msg, strlen(msg)));
759 760
    VIR_FREE(msg);

761 762
    if (flags & VIR_LOG_STACK_TRACE)
        virLogStackTraceToFd(fd);
D
Daniel Veillard 已提交
763 764
}

765 766 767

static void
virLogCloseFd(void *data)
768
{
769
    int fd = (intptr_t) data;
D
Daniel Veillard 已提交
770

771
    VIR_LOG_CLOSE(fd);
D
Daniel Veillard 已提交
772 773
}

774 775 776 777

static int
virLogAddOutputToStderr(virLogPriority priority)
{
778 779
    if (virLogDefineOutput(virLogOutputToFd, NULL, (void *)2L, priority,
                           VIR_LOG_TO_STDERR, NULL, 0) < 0)
780 781
        return -1;
    return 0;
D
Daniel Veillard 已提交
782 783
}

784 785 786 787 788

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

791
    fd = open(file, O_CREAT | O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR);
D
Daniel Veillard 已提交
792
    if (fd < 0)
793
        return -1;
794 795
    if (virLogDefineOutput(virLogOutputToFd, virLogCloseFd,
                           (void *)(intptr_t)fd,
796
                           priority, VIR_LOG_TO_FILE, file, 0) < 0) {
797
        VIR_FORCE_CLOSE(fd);
798
        return -1;
D
Daniel Veillard 已提交
799
    }
800
    return 0;
D
Daniel Veillard 已提交
801 802
}

803

804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
#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

820 821
static int
virLogPrioritySyslog(virLogPriority priority)
822 823 824 825 826 827 828 829 830 831 832 833 834 835
{
    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;
    }
}
836
#endif /* HAVE_SYSLOG_H || USE_JOURNALD */
837

838

839
#if HAVE_SYSLOG_H
840
static void
841
virLogOutputToSyslog(virLogSourcePtr source ATTRIBUTE_UNUSED,
842
                     virLogPriority priority,
843
                     const char *filename ATTRIBUTE_UNUSED,
844
                     int linenr ATTRIBUTE_UNUSED,
845
                     const char *funcname ATTRIBUTE_UNUSED,
846
                     const char *timestamp ATTRIBUTE_UNUSED,
M
Miloslav Trmač 已提交
847
                     virLogMetadataPtr metadata ATTRIBUTE_UNUSED,
848 849 850 851
                     unsigned int flags,
                     const char *rawstr ATTRIBUTE_UNUSED,
                     const char *str,
                     void *data ATTRIBUTE_UNUSED)
852
{
853
    virCheckFlags(VIR_LOG_STACK_TRACE,);
854

855
    syslog(virLogPrioritySyslog(priority), "%s", str);
D
Daniel Veillard 已提交
856 857
}

858
static char *current_ident;
859

860 861 862 863

static void
virLogCloseSyslog(void *data ATTRIBUTE_UNUSED)
{
D
Daniel Veillard 已提交
864
    closelog();
865
    VIR_FREE(current_ident);
D
Daniel Veillard 已提交
866 867
}

868 869 870 871 872

static int
virLogAddOutputToSyslog(virLogPriority priority,
                        const char *ident)
{
873 874 875 876
    /*
     * ident needs to be kept around on Solaris
     */
    VIR_FREE(current_ident);
877
    if (VIR_STRDUP(current_ident, ident) < 0)
878
        return -1;
879 880

    openlog(current_ident, 0, 0);
D
Daniel Veillard 已提交
881
    if (virLogDefineOutput(virLogOutputToSyslog, virLogCloseSyslog, NULL,
882
                           priority, VIR_LOG_TO_SYSLOG, ident, 0) < 0) {
D
Daniel Veillard 已提交
883
        closelog();
884
        VIR_FREE(current_ident);
885
        return -1;
D
Daniel Veillard 已提交
886
    }
887
    return 0;
D
Daniel Veillard 已提交
888
}
D
Daniel P. Berrange 已提交
889 890


E
Eric Blake 已提交
891
# if USE_JOURNALD
892 893 894 895 896
#  define IOVEC_SET(iov, data, size)            \
    do {                                        \
        struct iovec *_i = &(iov);              \
        _i->iov_base = (void*)(data);           \
        _i->iov_len = (size);                   \
D
Daniel P. Berrange 已提交
897 898
    } while (0)

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
#  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 已提交
964 965

static void
966
virLogOutputToJournald(virLogSourcePtr source,
D
Daniel P. Berrange 已提交
967 968 969 970 971
                       virLogPriority priority,
                       const char *filename,
                       int linenr,
                       const char *funcname,
                       const char *timestamp ATTRIBUTE_UNUSED,
972
                       virLogMetadataPtr metadata,
D
Daniel P. Berrange 已提交
973 974 975
                       unsigned int flags,
                       const char *rawstr,
                       const char *str ATTRIBUTE_UNUSED,
976
                       void *data)
D
Daniel P. Berrange 已提交
977 978 979
{
    virCheckFlags(VIR_LOG_STACK_TRACE,);
    int buffd = -1;
980
    int journalfd = (intptr_t) data;
D
Daniel P. Berrange 已提交
981 982 983 984 985 986 987 988 989 990 991
    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";
992
    size_t nmetadata = 0;
D
Daniel P. Berrange 已提交
993

994 995 996
#  define NUM_FIELDS_CORE 6
#  define NUM_FIELDS_META 5
#  define NUM_FIELDS (NUM_FIELDS_CORE + NUM_FIELDS_META)
997 998 999
    struct iovec iov[NUM_FIELDS * 5];
    char iov_bufs[NUM_FIELDS][JOURNAL_BUF_SIZE];
    struct journalState state;
D
Daniel P. Berrange 已提交
1000

1001 1002 1003 1004
    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 已提交
1005

E
Eric Blake 已提交
1006
    journalAddString(&state, "MESSAGE", rawstr);
1007 1008
    journalAddInt(&state, "PRIORITY",
                  virLogPrioritySyslog(priority));
1009
    journalAddInt(&state, "SYSLOG_FACILITY", LOG_DAEMON);
1010
    journalAddString(&state, "LIBVIRT_SOURCE", source->name);
1011 1012
    if (filename)
        journalAddString(&state, "CODE_FILE", filename);
1013
    journalAddInt(&state, "CODE_LINE", linenr);
1014 1015
    if (funcname)
        journalAddString(&state, "CODE_FUNC", funcname);
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
    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 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036

    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;
1037
    mh.msg_iovlen = state.iov - iov;
D
Daniel P. Berrange 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060

    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;

1061
    if (writev(buffd, iov, state.iov - iov) < 0)
D
Daniel P. Berrange 已提交
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
        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;

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

1081
 cleanup:
D
Daniel P. Berrange 已提交
1082 1083 1084 1085 1086 1087
    VIR_LOG_CLOSE(buffd);
}


static int virLogAddOutputToJournald(int priority)
{
1088 1089
    int journalfd;

D
Daniel P. Berrange 已提交
1090 1091 1092 1093 1094 1095
    if ((journalfd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0)
        return -1;
    if (virSetInherit(journalfd, false) < 0) {
        VIR_LOG_CLOSE(journalfd);
        return -1;
    }
1096 1097 1098 1099
    if (virLogDefineOutput(virLogOutputToJournald, virLogCloseFd,
                           (void *)(intptr_t) journalfd, priority,
                           VIR_LOG_TO_JOURNALD, NULL, 0) < 0) {
        VIR_LOG_CLOSE(journalfd);
D
Daniel P. Berrange 已提交
1100 1101
        return -1;
    }
1102

D
Daniel P. Berrange 已提交
1103 1104
    return 0;
}
E
Eric Blake 已提交
1105
# endif /* USE_JOURNALD */
J
Ján Tomko 已提交
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130

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 已提交
1131 1132
#endif /* HAVE_SYSLOG_H */

1133

1134
static int
1135
virLogParseAndDefineOutput(const char *src)
1136 1137 1138 1139 1140 1141
{
    int ret = -1;
    char **tokens = NULL;
    char *abspath = NULL;
    size_t count = 0;
    virLogPriority prio;
1142
    int dest;
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
    bool isSUID = virIsSUID();

    if (!src)
        return -1;

    VIR_DEBUG("output=%s", src);

    /* split our format prio:destination:additional_data to tokens and parse
     * them individually
     */
    if (!(tokens = virStringSplitCount(src, ":", 0, &count)))
        return -1;

    if (virStrToLong_uip(tokens[0], NULL, 10, &prio) < 0 ||
        (prio < VIR_LOG_DEBUG) || (prio > VIR_LOG_ERROR))
        goto cleanup;

    if ((dest = virLogDestinationTypeFromString(tokens[1])) < 0)
        goto cleanup;

    if (((dest == VIR_LOG_TO_STDERR ||
          dest == VIR_LOG_TO_JOURNALD) && count != 2) ||
        ((dest == VIR_LOG_TO_FILE ||
          dest == VIR_LOG_TO_SYSLOG) && count != 3))
        goto cleanup;

    /* if running with setuid, only 'stderr' is allowed */
    if (isSUID && dest != VIR_LOG_TO_STDERR)
        goto cleanup;

    switch ((virLogDestination) dest) {
    case VIR_LOG_TO_STDERR:
        ret = virLogAddOutputToStderr(prio);
        break;
    case VIR_LOG_TO_SYSLOG:
#if HAVE_SYSLOG_H
        ret = virLogAddOutputToSyslog(prio, tokens[2]);
#endif
        break;
    case VIR_LOG_TO_FILE:
        if (virFileAbsPath(tokens[2], &abspath) < 0)
            goto cleanup;
        ret = virLogAddOutputToFile(prio, abspath);
        VIR_FREE(abspath);
        break;
    case VIR_LOG_TO_JOURNALD:
#if USE_JOURNALD
        ret = virLogAddOutputToJournald(prio);
#endif
        break;
    case VIR_LOG_TO_OUTPUT_LAST:
        break;
    }

 cleanup:
    if (ret < 0)
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to parse and define log output %s"), src);
    virStringFreeList(tokens);
    return ret;
}


D
Daniel Veillard 已提交
1206
/**
1207
 * virLogParseAndDefineOutputs:
D
Daniel Veillard 已提交
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
 * @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.
 *
1226 1227 1228
 * If running in setuid mode, then only the 'stderr' output will
 * be allowed
 *
1229
 * Returns the number of output parsed or -1 in case of error.
D
Daniel Veillard 已提交
1230
 */
1231
int
1232
virLogParseAndDefineOutputs(const char *src)
1233
{
1234 1235
    int ret = -1;
    int count = 0;
1236 1237
    size_t i;
    char **strings = NULL;
D
Daniel Veillard 已提交
1238

1239
    if (!src)
1240
        return -1;
D
Daniel Veillard 已提交
1241

1242
    VIR_DEBUG("outputs=%s", src);
1243

1244 1245 1246 1247 1248 1249 1250 1251
    if (!(strings = virStringSplit(src, " ", 0)))
        goto cleanup;

    for (i = 0; strings[i]; i++) {
        /* virStringSplit may return empty strings */
        if (STREQ(strings[i], ""))
            continue;

1252
        if (virLogParseAndDefineOutput(strings[i]) < 0)
1253
            goto cleanup;
1254 1255

        count++;
D
Daniel Veillard 已提交
1256
    }
1257

1258
    ret = count;
1259
 cleanup:
1260
    virStringFreeList(strings);
1261
    return ret;
D
Daniel Veillard 已提交
1262 1263
}

1264

1265
static int
1266
virLogParseAndDefineFilter(const char *filter)
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
{
    int ret = -1;
    size_t count = 0;
    virLogPriority prio;
    char **tokens = NULL;
    unsigned int flags = 0;
    char *ref = NULL;

    if (!filter)
        return -1;

    VIR_DEBUG("filter=%s", filter);

    if (!(tokens = virStringSplitCount(filter, ":", 0, &count)))
        return -1;

    if (count != 2)
        goto cleanup;

    if (virStrToLong_uip(tokens[0], NULL, 10, &prio) < 0 ||
        (prio < VIR_LOG_DEBUG) || (prio > VIR_LOG_ERROR))
        goto cleanup;

    ref = tokens[1];
    if (ref[0] == '+') {
        flags |= VIR_LOG_STACK_TRACE;
        ref++;
    }

    if (!*ref)
        goto cleanup;

    if (virLogDefineFilter(ref, prio, flags) < 0)
        goto cleanup;

    ret = 0;
 cleanup:
    if (ret < 0)
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Failed to parse and define log filter %s"), filter);
    virStringFreeList(tokens);
    return ret;
}

D
Daniel Veillard 已提交
1311
/**
1312
 * virLogParseAndDefineFilters:
D
Daniel Veillard 已提交
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
 * @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.
 *
1327
 * Returns the number of filter parsed or -1 in case of error.
D
Daniel Veillard 已提交
1328
 */
1329
int
1330
virLogParseAndDefineFilters(const char *filters)
1331
{
1332 1333
    int ret = -1;
    int count = 0;
1334 1335
    size_t i;
    char **strings = NULL;
D
Daniel Veillard 已提交
1336

1337
    if (!filters)
1338
        return -1;
D
Daniel Veillard 已提交
1339

1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
    VIR_DEBUG("filters=%s", filters);

    if (!(strings = virStringSplit(filters, " ", 0)))
        goto cleanup;

    for (i = 0; strings[i]; i++) {
        /* virStringSplit may return empty strings */
        if (STREQ(strings[i], ""))
            continue;

1350
        if (virLogParseAndDefineFilter(strings[i]) < 0)
1351
            goto cleanup;
1352 1353

        count++;
D
Daniel Veillard 已提交
1354
    }
1355

1356
    ret = count;
1357
 cleanup:
1358
    virStringFreeList(strings);
1359
    return ret;
D
Daniel Veillard 已提交
1360
}
1361

1362

1363 1364 1365 1366 1367
/**
 * virLogGetDefaultPriority:
 *
 * Returns the current logging priority level.
 */
1368 1369 1370
virLogPriority
virLogGetDefaultPriority(void)
{
1371
    return virLogDefaultPriority;
1372 1373
}

1374

1375 1376 1377 1378 1379 1380 1381
/**
 * virLogGetFilters:
 *
 * Returns a string listing the current filters, in the format originally
 * specified in the config file or environment. Caller must free the
 * result.
 */
1382 1383 1384
char *
virLogGetFilters(void)
{
1385
    size_t i;
1386 1387 1388 1389
    virBuffer filterbuf = VIR_BUFFER_INITIALIZER;

    virLogLock();
    for (i = 0; i < virLogNbFilters; i++) {
1390
        const char *sep = ":";
1391
        if (virLogFilters[i]->flags & VIR_LOG_STACK_TRACE)
1392 1393
            sep = ":+";
        virBufferAsprintf(&filterbuf, "%d%s%s ",
1394
                          virLogFilters[i]->priority,
1395
                          sep,
1396
                          virLogFilters[i]->match);
1397 1398 1399
    }
    virLogUnlock();

1400 1401
    if (virBufferError(&filterbuf)) {
        virBufferFreeAndReset(&filterbuf);
1402
        return NULL;
1403
    }
1404 1405 1406 1407

    return virBufferContentAndReset(&filterbuf);
}

1408

1409 1410 1411 1412 1413 1414 1415
/**
 * virLogGetOutputs:
 *
 * Returns a string listing the current outputs, in the format originally
 * specified in the config file or environment. Caller must free the
 * result.
 */
1416 1417 1418
char *
virLogGetOutputs(void)
{
1419
    size_t i;
1420 1421 1422 1423
    virBuffer outputbuf = VIR_BUFFER_INITIALIZER;

    virLogLock();
    for (i = 0; i < virLogNbOutputs; i++) {
1424
        virLogDestination dest = virLogOutputs[i]->dest;
1425
        if (i)
1426
            virBufferAddChar(&outputbuf, ' ');
1427 1428 1429
        switch (dest) {
            case VIR_LOG_TO_SYSLOG:
            case VIR_LOG_TO_FILE:
1430
                virBufferAsprintf(&outputbuf, "%d:%s:%s",
1431
                                  virLogOutputs[i]->priority,
1432
                                  virLogDestinationTypeToString(dest),
1433
                                  virLogOutputs[i]->name);
1434 1435
                break;
            default:
1436
                virBufferAsprintf(&outputbuf, "%d:%s",
1437
                                  virLogOutputs[i]->priority,
1438
                                  virLogDestinationTypeToString(dest));
1439 1440 1441 1442
        }
    }
    virLogUnlock();

1443 1444
    if (virBufferError(&outputbuf)) {
        virBufferFreeAndReset(&outputbuf);
1445
        return NULL;
1446
    }
1447 1448 1449 1450

    return virBufferContentAndReset(&outputbuf);
}

1451

1452 1453 1454 1455 1456
/**
 * virLogGetNbFilters:
 *
 * Returns the current number of defined log filters.
 */
1457 1458 1459
int
virLogGetNbFilters(void)
{
1460
    return virLogNbFilters;
1461 1462
}

1463

1464 1465 1466 1467 1468
/**
 * virLogGetNbOutputs:
 *
 * Returns the current number of defined log outputs.
 */
1469 1470 1471
int
virLogGetNbOutputs(void)
{
1472
    return virLogNbOutputs;
1473
}
1474

1475

1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
/**
 * 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
 *
1487
 * Returns 0 if successful, -1 in case of error.
1488
 */
1489 1490 1491
int
virLogParseDefaultPriority(const char *priority)
{
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
    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
1503
        VIR_WARN("Ignoring invalid log level setting");
1504 1505 1506 1507

    return ret;
}

1508

1509 1510 1511 1512 1513 1514
/**
 * virLogSetFromEnv:
 *
 * Sets virLogDefaultPriority, virLogFilters and virLogOutputs based on
 * environment variables.
 */
1515 1516 1517
void
virLogSetFromEnv(void)
{
1518
    const char *debugEnv;
1519

1520 1521 1522
    if (virLogInitialize() < 0)
        return;

1523
    debugEnv = virGetEnvAllowSUID("LIBVIRT_DEBUG");
1524 1525
    if (debugEnv && *debugEnv)
        virLogParseDefaultPriority(debugEnv);
1526
    debugEnv = virGetEnvAllowSUID("LIBVIRT_LOG_FILTERS");
1527
    if (debugEnv && *debugEnv)
1528
        virLogParseAndDefineFilters(debugEnv);
1529
    debugEnv = virGetEnvAllowSUID("LIBVIRT_LOG_OUTPUTS");
1530
    if (debugEnv && *debugEnv)
1531
        virLogParseAndDefineOutputs(debugEnv);
1532
}
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548


/*
 * 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;
}
E
Erik Skultety 已提交
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603


/**
 * virLogOutputNew:
 * @f: the function to call to output a message
 * @c: the function to call to close the output (or NULL)
 * @data: extra data passed as first arg to functions @f and @c
 * @priority: minimal priority for this filter, use 0 for none
 * @dest: where to send output of this priority (see virLogDestination)
 * @name: additional data associated with syslog and file-based outputs (ident
 *        and filename respectively)
 *
 * Allocates and returns a new log output object. The object has to be later
 * defined, so that the output will be taken into account when emitting a
 * message.
 *
 * Returns reference to a newly created object or NULL in case of failure.
 */
virLogOutputPtr
virLogOutputNew(virLogOutputFunc f,
                virLogCloseFunc c,
                void *data,
                virLogPriority priority,
                virLogDestination dest,
                const char *name)
{
    virLogOutputPtr ret = NULL;
    char *ndup = NULL;

    if (dest == VIR_LOG_TO_SYSLOG || dest == VIR_LOG_TO_FILE) {
        if (!name) {
            virReportError(VIR_ERR_INVALID_ARG, "%s",
                           _("Missing auxiliary data in output definition"));
            return NULL;
        }

        if (VIR_STRDUP(ndup, name) < 0)
            return NULL;
    }

    if (VIR_ALLOC(ret) < 0) {
        VIR_FREE(ndup);
        return NULL;
    }

    ret->logInitMessage = true;
    ret->f = f;
    ret->c = c;
    ret->data = data;
    ret->priority = priority;
    ret->dest = dest;
    ret->name = ndup;

    return ret;
}
E
Erik Skultety 已提交
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651


/**
 * virLogFilterNew:
 * @match: the pattern to match
 * @priority: the priority to give to messages matching the pattern
 * @flags: extra flags, see virLogFilterFlags enum
 *
 * Allocates and returns a new log filter object. The object has to be later
 * defined, so that the pattern will be taken into account when executing the
 * log filters (to select or reject a particular message) on messages.
 *
 * 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 a reference to a newly created filter that needs to be defined using
 * virLogDefineFilters, or NULL in case of an error.
 */
virLogFilterPtr
virLogFilterNew(const char *match,
                virLogPriority priority,
                unsigned int flags)
{
    virLogFilterPtr ret = NULL;
    char *mdup = NULL;

    virCheckFlags(VIR_LOG_STACK_TRACE, NULL);

    if (priority < VIR_LOG_DEBUG || priority > VIR_LOG_ERROR) {
        virReportError(VIR_ERR_INVALID_ARG, _("Invalid log priority %d"),
                       priority);
        return NULL;
    }

    if (VIR_STRDUP_QUIET(mdup, match) < 0)
        return NULL;

    if (VIR_ALLOC_QUIET(ret) < 0) {
        VIR_FREE(mdup);
        return NULL;
    }

    ret->match = mdup;
    ret->priority = priority;
    ret->flags = flags;

    return ret;
}
E
Erik Skultety 已提交
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683


/**
 * virLogFindOutput:
 * @outputs: a list of outputs where to look for the output of type @dest
 * @noutputs: number of elements in @outputs
 * @dest: destination type of an output
 * @opaque: opaque data to the method (only filename at the moment)
 *
 * Looks for an output of destination type @dest in the source list @outputs.
 * If such an output exists, index of the object in the list is returned.
 * In case of the destination being of type FILE also a comparison of the
 * output's filename with @opaque is performed first.
 *
 * Returns the index of the object in the list or -1 if no object matching the
 * specified @dest type and/or @opaque data one was found.
 */
int
virLogFindOutput(virLogOutputPtr *outputs, size_t noutputs,
                 virLogDestination dest, const void *opaque)
{
    size_t i;
    const char *name = opaque;

    for (i = 0; i < noutputs; i++) {
        if (dest == outputs[i]->dest &&
            (STREQ_NULLABLE(outputs[i]->name, name)))
                return i;
    }

    return -1;
}
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708


/**
 * virLogDefineOutputs:
 * @outputs: new set of outputs to be defined
 * @noutputs: number of outputs in @outputs
 *
 * Resets any existing set of outputs and defines a completely new one.
 *
 * Returns number of outputs successfully defined or -1 in case of error;
 */
int
virLogDefineOutputs(virLogOutputPtr *outputs, size_t noutputs)
{
    if (virLogInitialize() < 0)
        return -1;

    virLogLock();
    virLogResetOutputs();
    virLogOutputs = outputs;
    virLogNbOutputs = noutputs;
    virLogUnlock();

    return 0;
}
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735


/**
 * virLogDefineFilters:
 * @filters: new set of filters to be defined
 * @nfilters: number of filters in @filters
 *
 * Resets any existing set of filters and defines a completely new one. The
 * resulting set can also be empty in which case NULL should be passed to
 * @filters.
 *
 * Returns 0 on success or -1 in case of error.
 */
int
virLogDefineFilters(virLogFilterPtr *filters, size_t nfilters)
{
    if (virLogInitialize() < 0)
        return -1;

    virLogLock();
    virLogResetFilters();
    virLogFilters = filters;
    virLogNbFilters = nfilters;
    virLogUnlock();

    return 0;
}