summaryrefslogtreecommitdiffstats
path: root/src/journald/instutil.c
blob: ac9e76809f3f6d4316d10e0dcf6730e2418d3b1f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
 * Copyright (C) 2013 Red Hat, Inc.  All rights reserved.
 *
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Authors: Tomas Bzatek <tbzatek@redhat.com>
 */

#include <errno.h>
#include <syslog.h>
#include <glib.h>

#include "instutil.h"
#include "globals.h"
#include "journal.h"

#include "LMI_JournalLogRecord.h"
#include "LMI_JournalMessageLog.h"


/* Assuming no thread safety */
static sd_journal *ind_journal = NULL;


int create_LMI_JournalLogRecordRef(sd_journal *j,
                                   LMI_JournalLogRecordRef *ref,
                                   const CMPIBroker *_cb)
{
    char *cursor;
    uint64_t usec;
    CMPIDateTime *date;

    LMI_JournalLogRecordRef_Set_CreationClassName(ref, LMI_JournalLogRecord_ClassName);
    LMI_JournalLogRecordRef_Set_LogCreationClassName(ref, LMI_JournalMessageLog_ClassName);
    LMI_JournalLogRecordRef_Set_LogName(ref, JOURNAL_MESSAGE_LOG_NAME);

    /* Get stable cursor string */
    if (sd_journal_get_cursor(j, &cursor) < 0)
        return 0;
    LMI_JournalLogRecordRef_Set_RecordID(ref, cursor);
    free(cursor);

    /* Get timestamp */
    if (sd_journal_get_realtime_usec(j, &usec) < 0)
        return 0;
    date = CMNewDateTimeFromBinary(_cb, usec, 0, NULL);
    LMI_JournalLogRecordRef_Set_MessageTimestamp(ref, date);

    return 1;
}

static int dup_journal_data(
    sd_journal *j,
    const char *key,
    gchar **out)
{
    const char *d;
    size_t l;
    int r;

    *out = NULL;
    r = sd_journal_get_data(j, key, (const void **) &d, &l);
    if (r < 0)
        return r;
    if (l < strlen(key) + 1)
        return -EBADMSG;

    *out = g_strndup(d + strlen(key) + 1, l - strlen(key) - 1);
    if (*out == NULL)
        return -EBADMSG;

    return 0;
}

int create_LMI_JournalLogRecord(sd_journal *j,
                                LMI_JournalLogRecord *rec,
                                const CMPIBroker *_cb)
{
    int r;
    uint64_t usec;
    CMPIDateTime *date;
    gchar *d;
    gchar *syslog_identifier = NULL;
    gchar *comm = NULL;
    gchar *pid = NULL;
    gchar *fake_pid = NULL;
    GString *str;

    /* Construct the message */
    /* Message format is inspired by journalctl short output, containing the identifier (process name),
     * PID and the message. In other words, it's the traditional syslog record format.
     * Keep in sync with systemd:src/shared/logs-show.c:output_short() */
    r = dup_journal_data(j, "MESSAGE", &d);
    if (r < 0)
        return r;
    dup_journal_data(j, "SYSLOG_IDENTIFIER", &syslog_identifier);
    dup_journal_data(j, "_COMM", &comm);
    dup_journal_data(j, "_PID", &pid);
    dup_journal_data(j, "SYSLOG_PID", &fake_pid);
    str = g_string_new(NULL);
    if (syslog_identifier || comm)
        g_string_append(str, syslog_identifier ? syslog_identifier : comm);
    if (pid || fake_pid)
        g_string_append_printf(str, "[%s]", pid ? pid : fake_pid);
    if (str->len > 0)
        g_string_append(str, ": ");
    g_string_append(str, d);
    LMI_JournalLogRecord_Set_DataFormat(rec, str->str);
    g_string_free(str, TRUE);
    g_free(d);
    g_free(syslog_identifier);
    g_free(comm);
    g_free(pid);
    g_free(fake_pid);

    /* Set timestamp */
    r = sd_journal_get_realtime_usec(j, &usec);
    if (r < 0)
        return r;
    date = CMNewDateTimeFromBinary(_cb, usec, 0, NULL);
    LMI_JournalLogRecord_Set_MessageTimestamp(rec, date);

    /* Optional: hostname */
    r = dup_journal_data(j, "_HOSTNAME", &d);
    if (r >= 0 && d != NULL && strlen(d) > 0) {
        LMI_JournalLogRecord_Set_HostName(rec, d);
        g_free(d);
    }

    /* Optional: PerceivedSeverity */
    r = dup_journal_data(j, "PRIORITY", &d);
    if (r >= 0 && d != NULL && strlen(d) > 0) {
        char *conv_err = NULL;
        long int i = strtol(d, &conv_err, 10);
        g_free(d);
        if (conv_err == NULL || *conv_err == '\0')
            switch (i) {
                case LOG_EMERG:
                    /* 7 - Fatal/NonRecoverable should be used to indicate an error occurred,
                     *     but it's too late to take remedial action. */
                    LMI_JournalLogRecord_Set_PerceivedSeverity_Fatal_NonRecoverable(rec);
                    break;
                case LOG_ALERT:
                case LOG_CRIT:
                    /* 6 - Critical should be used to indicate action is needed NOW and the scope
                     *     is broad (perhaps an imminent outage to a critical resource will result). */
                    LMI_JournalLogRecord_Set_PerceivedSeverity_Critical(rec);
                    break;
                case LOG_ERR:
                    /* 4 - Minor should be used to indicate action is needed, but the situation
                     *     is not serious at this time. */
                    LMI_JournalLogRecord_Set_PerceivedSeverity_Minor(rec);
                    break;
                case LOG_WARNING:
                    /* 3 - Degraded/Warning should be used when its appropriate to let the user
                     *     decide if action is needed. */
                    LMI_JournalLogRecord_Set_PerceivedSeverity_Degraded_Warning(rec);
                    break;
                case LOG_NOTICE:
                case LOG_INFO:
                case LOG_DEBUG:
                    /* 2 - Information */
                    LMI_JournalLogRecord_Set_PerceivedSeverity_Information(rec);
                    break;
            }
    }

    return 1;
}


void ind_init()
{
    if (ind_journal == NULL) {
        sd_journal *journal;
        int r;

        r = sd_journal_open(&journal, 0);
        if (r < 0) {
            error("ind_init(): Error opening journal: %s\n", strerror(-r));
            return;
        }

        r = sd_journal_seek_tail(journal);
        if (r < 0) {
            error("ind_init(): Error seeking to the end of the journal: %s\n", strerror(-r));
            sd_journal_close(journal);
            return;
        }

        /* need to position the marker one step before EOF or otherwise the next sd_journal_next() call will overflow to the beginning */
        r = sd_journal_previous(journal);
        if (r < 0) {
            error("ind_init(): Error seeking to the end of the journal: %s\n", strerror(-r));
            sd_journal_close(journal);
            return;
        }
        ind_journal = journal;
    } else
        warn("ind_init(): indications already initialized, possible bug in the code\n");
}

void ind_destroy()
{
    if (ind_journal != NULL) {
        sd_journal_close(ind_journal);
        ind_journal = NULL;
    }
}

bool ind_watcher(void **data)
{
    int r;

    if (ind_journal == NULL) {
        error("ind_watcher(): indications have not been initialized yet or error occurred previously\n");
        return false;
    }

    r = sd_journal_wait(ind_journal, (uint64_t) -1);
    if (r == SD_JOURNAL_INVALIDATE) {
        /* Looking at sd-journal sources, the sd_journal_wait() call will likely return
         * SD_JOURNAL_INVALIDATE on a first run because of creating new inotify watch. */
        r = sd_journal_wait(ind_journal, (uint64_t) -1);
    }
    while (r == SD_JOURNAL_NOP) {
        /* received NOP, ignore the event and wait for the next one */
        r = sd_journal_wait(ind_journal, (uint64_t) -1);
    }
    if (r < 0) {
        warn("ind_watcher(): Error while waiting for new record: %s\n", strerror(-r));
        return false;
    }
    if (r == SD_JOURNAL_INVALIDATE) {
        warn("ind_watcher(): Journal not valid, reopen needed\n");
        ind_destroy();
        ind_init();
        return false;
    }
    *data = ind_journal;

    return true;
}

bool ind_gather(const IMManager *manager, CMPIInstance **old, CMPIInstance **new, void *data)
{
    sd_journal *journal;
    int r;
    LMI_JournalLogRecord log_record;
    CMPIStatus st;

    g_return_val_if_fail(data != NULL, false);
    journal = data;

    r = sd_journal_next(journal);
    if (r < 0) {
        error("ind_gather(): Failed to iterate to next entry: %s\n", strerror(-r));
        return false;
    }
    if (r == 0) {
        /* We've reached the end of the journal */
        return false;
    }

    /* FIXME: hardcoded namespace (so does ind_manager.c) */
    LMI_JournalLogRecord_Init(&log_record, manager->broker, "root/cimv2");
    r = create_LMI_JournalLogRecord(journal, &log_record, manager->broker);
    if (r <= 0) {
        error("ind_gather(): Failed to create instance: %s\n", strerror(-r));
        return false;
    }

    g_assert(new != NULL);
    *new = LMI_JournalLogRecord_ToInstance(&log_record, &st);
    debug(" ind_gather(): new instance created\n");

    return true;
}

bool ind_filter_cb(const CMPISelectExp *filter)
{
    /* TODO: copied from account/indication_common.c, may require generalization */

    /*
     * Support only simple conditions and only on allowed_classes
     * and type of `sourceinstance ISA allowed_class'
     */
    CMPIStatus st;
    CMPISelectCond *sec = CMGetDoc(filter, &st);
    if (!sec) return false;
    CMPICount count = CMGetSubCondCountAndType(sec, NULL, &st);
    if (count != 1) return false;
    CMPISubCond *sub = CMGetSubCondAt(sec, 0, &st);
    if (!sub) return false;
    count = CMGetPredicateCount(sub, &st);
    if (count != 1) return false;
    CMPIPredicate *pred = CMGetPredicateAt(sub, 0, &st);
    if (!pred) return false;
    CMPIType type;
    CMPIPredOp op;
    CMPIString *lhs = NULL;
    CMPIString *rhs = NULL;
    st = CMGetPredicateData(pred, &type, &op, &lhs, &rhs);
    if (st.rc != CMPI_RC_OK || op != CMPI_PredOp_Isa) return false;
    const char *rhs_str = CMGetCharsPtr(rhs, &st);
    if (!rhs_str) return false;
    if (strcasecmp(rhs_str, LMI_JournalLogRecord_ClassName) == 0) return true;
    return false;
}