summaryrefslogtreecommitdiffstats
path: root/src/libnetdata/spawn_server/log-forwarder.c
blob: 5c4db55ea0f9c3602871be537bd3dd8f5da1c386 (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
322
// SPDX-License-Identifier: GPL-3.0-or-later

#include "../libnetdata.h"
#include "log-forwarder.h"

typedef struct LOG_FORWARDER_ENTRY {
    int fd;
    char *cmd;
    pid_t pid;
    BUFFER *wb;
    size_t pfds_idx;
    bool delete;

    struct LOG_FORWARDER_ENTRY *prev;
    struct LOG_FORWARDER_ENTRY *next;
} LOG_FORWARDER_ENTRY;

typedef struct LOG_FORWARDER {
    LOG_FORWARDER_ENTRY *entries;
    ND_THREAD *thread;
    SPINLOCK spinlock;
    int pipe_fds[2]; // Pipe for notifications
    bool running;
} LOG_FORWARDER;

static void *log_forwarder_thread_func(void *arg);

// --------------------------------------------------------------------------------------------------------------------
// helper functions

static inline LOG_FORWARDER_ENTRY *log_forwarder_find_entry_unsafe(LOG_FORWARDER *lf, int fd) {
    for (LOG_FORWARDER_ENTRY *entry = lf->entries; entry; entry = entry->next) {
        if (entry->fd == fd)
            return entry;
    }

    return NULL;
}

static inline void log_forwarder_del_entry_unsafe(LOG_FORWARDER *lf, LOG_FORWARDER_ENTRY *entry) {
    DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(lf->entries, entry, prev, next);
    buffer_free(entry->wb);
    freez(entry->cmd);
    close(entry->fd);
    freez(entry);
}

static inline void log_forwarder_wake_up_worker(LOG_FORWARDER *lf) {
    char ch = 0;
    ssize_t bytes_written = write(lf->pipe_fds[PIPE_WRITE], &ch, 1);
    if (bytes_written != 1)
        nd_log(NDLS_COLLECTORS, NDLP_ERR, "Failed to write to notification pipe");
}

// --------------------------------------------------------------------------------------------------------------------
// starting / stopping

LOG_FORWARDER *log_forwarder_start(void) {
    LOG_FORWARDER *lf = callocz(1, sizeof(LOG_FORWARDER));

    spinlock_init(&lf->spinlock);
    if (pipe(lf->pipe_fds) != 0) {
        freez(lf);
        return NULL;
    }

    // make sure read() will not block on this pipe
    sock_setnonblock(lf->pipe_fds[PIPE_READ]);

    lf->running = true;
    lf->thread = nd_thread_create("log-fw", NETDATA_THREAD_OPTION_JOINABLE, log_forwarder_thread_func, lf);

    return lf;
}

static inline void mark_all_entries_for_deletion_unsafe(LOG_FORWARDER *lf) {
    for(LOG_FORWARDER_ENTRY *entry = lf->entries; entry ;entry = entry->next)
        entry->delete = true;
}

void log_forwarder_stop(LOG_FORWARDER *lf) {
    if(!lf || !lf->running) return;

    // Signal the thread to stop
    spinlock_lock(&lf->spinlock);
    lf->running = false;

    // mark them all for deletion
    mark_all_entries_for_deletion_unsafe(lf);

    // Send a byte to the pipe to wake up the thread
    char ch = 0;
    write(lf->pipe_fds[PIPE_WRITE], &ch, 1);
    spinlock_unlock(&lf->spinlock);

    // Wait for the thread to finish
    close(lf->pipe_fds[PIPE_WRITE]); // force it to quit
    nd_thread_join(lf->thread);
    close(lf->pipe_fds[PIPE_READ]);

    freez(lf);
}

// --------------------------------------------------------------------------------------------------------------------
// managing entries

void log_forwarder_add_fd(LOG_FORWARDER *lf, int fd) {
    if(!lf || !lf->running || fd < 0) return;

    LOG_FORWARDER_ENTRY *entry = callocz(1, sizeof(LOG_FORWARDER_ENTRY));
    entry->fd = fd;
    entry->cmd = NULL;
    entry->pid = 0;
    entry->pfds_idx = 0;
    entry->delete = false;
    entry->wb = buffer_create(0, NULL);

    spinlock_lock(&lf->spinlock);

    // Append to the entries list
    DOUBLE_LINKED_LIST_PREPEND_ITEM_UNSAFE(lf->entries, entry, prev, next);

    // Send a byte to the pipe to wake up the thread
    log_forwarder_wake_up_worker(lf);

    spinlock_unlock(&lf->spinlock);
}

bool log_forwarder_del_and_close_fd(LOG_FORWARDER *lf, int fd) {
    if(!lf || !lf->running || fd < 0) return false;

    bool ret = false;

    spinlock_lock(&lf->spinlock);

    LOG_FORWARDER_ENTRY *entry = log_forwarder_find_entry_unsafe(lf, fd);
    if(entry) {
        entry->delete = true;

        // Send a byte to the pipe to wake up the thread
        log_forwarder_wake_up_worker(lf);

        ret = true;
    }

    spinlock_unlock(&lf->spinlock);

    return ret;
}

void log_forwarder_annotate_fd_name(LOG_FORWARDER *lf, int fd, const char *cmd) {
    if(!lf || !lf->running || fd < 0 || !cmd || !*cmd) return;

    spinlock_lock(&lf->spinlock);

    LOG_FORWARDER_ENTRY *entry = log_forwarder_find_entry_unsafe(lf, fd);
    if (entry) {
        freez(entry->cmd);
        entry->cmd = strdupz(cmd);
    }

    spinlock_unlock(&lf->spinlock);
}

void log_forwarder_annotate_fd_pid(LOG_FORWARDER *lf, int fd, pid_t pid) {
    if(!lf || !lf->running || fd < 0) return;

    spinlock_lock(&lf->spinlock);

    LOG_FORWARDER_ENTRY *entry = log_forwarder_find_entry_unsafe(lf, fd);
    if (entry)
        entry->pid = pid;

    spinlock_unlock(&lf->spinlock);
}

// --------------------------------------------------------------------------------------------------------------------
// log forwarder thread

static inline void log_forwarder_log(LOG_FORWARDER *lf __maybe_unused, LOG_FORWARDER_ENTRY *entry, const char *msg) {
    const char *s = msg;
    while(*s && isspace((uint8_t)*s)) s++;
    if(*s == '\0') return; // do not log empty lines

    ND_LOG_STACK lgs[] = {
            ND_LOG_FIELD_TXT(NDF_SYSLOG_IDENTIFIER, entry->cmd ? entry->cmd : "unknown"),
            ND_LOG_FIELD_I64(NDF_TID, entry->pid),
            ND_LOG_FIELD_END(),
    };
    ND_LOG_STACK_PUSH(lgs);

    nd_log(NDLS_COLLECTORS, NDLP_WARNING, "STDERR: %s", msg);
}

// returns the number of entries active
static inline size_t log_forwarder_remove_deleted_unsafe(LOG_FORWARDER *lf) {
    size_t entries = 0;

    LOG_FORWARDER_ENTRY *entry = lf->entries;
    while(entry) {
        LOG_FORWARDER_ENTRY *next = entry->next;

        if(entry->delete) {
            if (buffer_strlen(entry->wb))
                // there is something not logged in it - log it
                log_forwarder_log(lf, entry, buffer_tostring(entry->wb));

            log_forwarder_del_entry_unsafe(lf, entry);
        }
        else
            entries++;

        entry = next;
    }

    return entries;
}

static void *log_forwarder_thread_func(void *arg) {
    LOG_FORWARDER *lf = (LOG_FORWARDER *)arg;

    while (1) {
        spinlock_lock(&lf->spinlock);
        if (!lf->running) {
            mark_all_entries_for_deletion_unsafe(lf);
            log_forwarder_remove_deleted_unsafe(lf);
            spinlock_unlock(&lf->spinlock);
            break;
        }

        // Count the number of fds
        size_t nfds = 1 + log_forwarder_remove_deleted_unsafe(lf);

        struct pollfd pfds[nfds];

        // First, the notification pipe
        pfds[0].fd = lf->pipe_fds[PIPE_READ];
        pfds[0].events = POLLIN;

        int idx = 1;
        for(LOG_FORWARDER_ENTRY *entry = lf->entries; entry ; entry = entry->next, idx++) {
            pfds[idx].fd = entry->fd;
            pfds[idx].events = POLLIN;
            entry->pfds_idx = idx;
        }

        spinlock_unlock(&lf->spinlock);

        int timeout = 200; // 200ms
        int ret = poll(pfds, nfds, timeout);

        if (ret > 0) {
            // Check the notification pipe
            if (pfds[0].revents & POLLIN) {
                // Read and discard the data
                char buf[256];
                ssize_t bytes_read = read(lf->pipe_fds[PIPE_READ], buf, sizeof(buf));
                // Ignore the data; proceed regardless of the result
                if (bytes_read == -1) {
                    if (errno != EAGAIN && errno != EWOULDBLOCK) {
                        // Handle read error if necessary
                        nd_log(NDLS_COLLECTORS, NDLP_ERR, "Failed to read from notification pipe");
                        return NULL;
                    }
                }
            }

            // Now check the other fds
            spinlock_lock(&lf->spinlock);

            size_t to_remove = 0;

            // read or mark them for deletion
            for(LOG_FORWARDER_ENTRY *entry = lf->entries; entry ; entry = entry->next) {
                if (entry->pfds_idx < 1 || entry->pfds_idx >= nfds || !(pfds[entry->pfds_idx].revents & POLLIN))
                    continue;

                BUFFER *wb = entry->wb;
                buffer_need_bytes(wb, 1024);

                ssize_t bytes_read = read(entry->fd, &wb->buffer[wb->len], wb->size - wb->len - 1);
                if(bytes_read > 0)
                    wb->len += bytes_read;
                else if(bytes_read == 0 || (bytes_read == -1 && errno != EINTR && errno != EAGAIN)) {
                    // EOF or error
                    entry->delete = true;
                    to_remove++;
                }

                // log as many lines are they have been received
                char *start = (char *)buffer_tostring(wb);
                char *newline = strchr(start, '\n');
                while(newline) {
                    *newline = '\0';
                    log_forwarder_log(lf, entry, start);

                    start = ++newline;
                    newline = strchr(newline, '\n');
                }

                if(start != wb->buffer) {
                    wb->len = strlen(start);
                    if (wb->len)
                        memmove(wb->buffer, start, wb->len);
                }

                entry->pfds_idx = 0;
            }

            spinlock_unlock(&lf->spinlock);
        }
        else if (ret == 0) {
            // Timeout, nothing to do
            continue;

        }
        else
            nd_log(NDLS_COLLECTORS, NDLP_ERR, "Log forwarder: poll() error");
    }

    return NULL;
}