master
c 834 lines 28.3 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 #include "systemd-cat-native.h"
4
5 #ifdef __FreeBSD__
6 #include <sys/endian.h>
7 #endif
8
9 #ifdef __APPLE__
10 #include <machine/endian.h>
11 #endif
12
13 bool verbose = false;
14
15 static inline void log_message_to_stderr(BUFFER *msg, const char *scope) {
16 CLEAN_BUFFER *tmp = buffer_create(0, NULL);
17
18 for(size_t i = 0; i < msg->len ;i++) {
19 if(isprint(msg->buffer[i]))
20 buffer_putc(tmp, msg->buffer[i]);
21 else {
22 buffer_putc(tmp, '[');
23 buffer_print_uint64_hex(tmp, msg->buffer[i]);
24 buffer_putc(tmp, ']');
25 }
26 }
27
28 fprintf(stderr, "SENDING %s: %s\n", scope, buffer_tostring(tmp));
29 }
30
31 static inline buffered_reader_ret_t get_next_line(struct buffered_reader *reader, BUFFER *line, int timeout_ms) {
32 while(true) {
33 if(unlikely(!buffered_reader_next_line(reader, line))) {
34 buffered_reader_ret_t ret = buffered_reader_read_timeout(reader, STDIN_FILENO, timeout_ms, verbose);
35 if(unlikely(ret != BUFFERED_READER_READ_OK))
36 return ret;
37
38 continue;
39 }
40 else {
41 // make sure the buffer is NULL terminated
42 line->buffer[line->len] = '\0';
43
44 // remove the trailing newlines
45 while(line->len && line->buffer[line->len - 1] == '\n')
46 line->buffer[--line->len] = '\0';
47
48 return BUFFERED_READER_READ_OK;
49 }
50 }
51 }
52
53 static inline size_t copy_replacing_newlines(char *dst, size_t dst_len, const char *src, size_t src_len, const char *newline) {
54 if (!dst || !src) return 0;
55
56 const char *current_src = src;
57 const char *src_end = src + src_len; // Pointer to the end of src
58 char *current_dst = dst;
59 size_t remaining_dst_len = dst_len;
60 size_t newline_len = newline && *newline ? strlen(newline) : 0;
61
62 size_t bytes_copied = 0; // To track the number of bytes copied
63
64 while (remaining_dst_len > 1 && current_src < src_end) {
65 if (newline_len > 0) {
66 const char *found = strstr(current_src, newline);
67 if (found && found < src_end) {
68 size_t copy_len = found - current_src;
69 if (copy_len >= remaining_dst_len) copy_len = remaining_dst_len - 1;
70
71 memcpy(current_dst, current_src, copy_len);
72 current_dst += copy_len;
73 *current_dst++ = '\n';
74 remaining_dst_len -= (copy_len + 1);
75 bytes_copied += copy_len + 1; // +1 for the newline character
76 current_src = found + newline_len;
77 continue;
78 }
79 }
80
81 // Copy the remaining part of src to dst
82 size_t copy_len = src_end - current_src;
83 if (copy_len >= remaining_dst_len) copy_len = remaining_dst_len - 1;
84
85 memcpy(current_dst, current_src, copy_len);
86 current_dst += copy_len;
87 remaining_dst_len -= copy_len;
88 bytes_copied += copy_len;
89 break;
90 }
91
92 // Ensure the string is null-terminated
93 *current_dst = '\0';
94
95 return bytes_copied;
96 }
97
98 static inline void buffer_memcat_replacing_newlines(BUFFER *wb, const char *src, size_t src_len, const char *newline) {
99 if(!src) return;
100
101 const char *equal;
102 if(!newline || !*newline || !strstr(src, newline) || !(equal = strchr(src, '='))) {
103 buffer_memcat(wb, src, src_len);
104 buffer_putc(wb, '\n');
105 return;
106 }
107
108 size_t key_len = equal - src;
109 buffer_memcat(wb, src, key_len);
110 buffer_putc(wb, '\n');
111
112 size_t length_offset = wb->len;
113 uint64_t le_size = 0;
114 buffer_memcat(wb, &le_size, sizeof(le_size));
115
116 const char *value = ++equal;
117 size_t value_len = src_len - key_len - 1;
118 buffer_need_bytes(wb, value_len + 1);
119 size_t size = copy_replacing_newlines(&wb->buffer[wb->len], value_len + 1, value, value_len, newline);
120 wb->len += size;
121 buffer_putc(wb, '\n');
122
123 le_size = htole64(size);
124 memcpy(&wb->buffer[length_offset], &le_size, sizeof(le_size));
125 }
126
127 // ----------------------------------------------------------------------------
128 // log to a systemd-journal-remote
129
130 #ifdef HAVE_LIBCURL
131 #include <curl/curl.h>
132
133 #ifndef HOST_NAME_MAX
134 #define HOST_NAME_MAX 256
135 #endif
136
137 char global_hostname[HOST_NAME_MAX] = "";
138 char global_boot_id[UUID_COMPACT_STR_LEN] = "";
139 char global_machine_id[UUID_COMPACT_STR_LEN] = "";
140 char global_stream_id[UUID_COMPACT_STR_LEN] = "";
141 char global_namespace[1024] = "";
142 char global_systemd_invocation_id[1024] = "";
143 #define BOOT_ID_PATH "/proc/sys/kernel/random/boot_id"
144 #define MACHINE_ID_PATH "/etc/machine-id"
145
146 #define DEFAULT_PRIVATE_KEY "/etc/ssl/private/journal-upload.pem"
147 #define DEFAULT_PUBLIC_KEY "/etc/ssl/certs/journal-upload.pem"
148 #define DEFAULT_CA_CERT "/etc/ssl/ca/trusted.pem"
149
150 struct upload_data {
151 char *data;
152 size_t length;
153 };
154
155 static size_t systemd_journal_remote_read_callback(void *ptr, size_t size, size_t nmemb, void *userp) {
156 struct upload_data *upload = (struct upload_data *)userp;
157 size_t buffer_size = size * nmemb;
158
159 if (upload->length) {
160 size_t copy_size = upload->length < buffer_size ? upload->length : buffer_size;
161 memcpy(ptr, upload->data, copy_size);
162 upload->data += copy_size;
163 upload->length -= copy_size;
164 return copy_size;
165 }
166
167 return 0;
168 }
169
170 CURL* initialize_connection_to_systemd_journal_remote(const char* url, const char* private_key, const char* public_key, const char* ca_cert, struct curl_slist **headers) {
171 CURL *curl = curl_easy_init();
172 if (!curl) {
173 fprintf(stderr, "Failed to initialize curl\n");
174 return NULL;
175 }
176
177 *headers = curl_slist_append(*headers, "Content-Type: application/vnd.fdo.journal");
178 *headers = curl_slist_append(*headers, "Transfer-Encoding: chunked");
179 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, *headers);
180 curl_easy_setopt(curl, CURLOPT_URL, url);
181 curl_easy_setopt(curl, CURLOPT_POST, 1L);
182 curl_easy_setopt(curl, CURLOPT_READFUNCTION, systemd_journal_remote_read_callback);
183
184 if (strncmp(url, "https://", 8) == 0) {
185 if (private_key) curl_easy_setopt(curl, CURLOPT_SSLKEY, private_key);
186 if (public_key) curl_easy_setopt(curl, CURLOPT_SSLCERT, public_key);
187
188 if (strcmp(ca_cert, "all") != 0) {
189 curl_easy_setopt(curl, CURLOPT_CAINFO, ca_cert);
190 } else {
191 curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
192 }
193 }
194 // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); // Remove for less verbose output
195
196 return curl;
197 }
198
199 static void journal_remote_complete_event(BUFFER *msg, usec_t *monotonic_ut) {
200 usec_t ut = now_monotonic_usec();
201
202 if(monotonic_ut)
203 *monotonic_ut = ut;
204
205 buffer_sprintf(msg,
206 ""
207 "__REALTIME_TIMESTAMP=%"PRIu64"\n"
208 "__MONOTONIC_TIMESTAMP=%"PRIu64"\n"
209 "_MACHINE_ID=%s\n"
210 "_BOOT_ID=%s\n"
211 "_HOSTNAME=%s\n"
212 "_TRANSPORT=stdout\n"
213 "_LINE_BREAK=nul\n"
214 "_STREAM_ID=%s\n"
215 "_RUNTIME_SCOPE=system\n"
216 "%s%s\n"
217 , now_realtime_usec()
218 , ut
219 , global_machine_id
220 , global_boot_id
221 , global_hostname
222 , global_stream_id
223 , global_namespace
224 , global_systemd_invocation_id
225 );
226 }
227
228 static CURLcode journal_remote_send_buffer(CURL* curl, BUFFER *msg) {
229
230 if(verbose)
231 log_message_to_stderr(msg, "REMOTE");
232
233 if (!curl || !buffer_strlen(msg))
234 return CURLE_FAILED_INIT;
235
236 struct upload_data upload = {
237 .data = (char *) buffer_tostring(msg),
238 .length = buffer_strlen(msg),
239 };
240
241 curl_easy_setopt(curl, CURLOPT_READDATA, &upload);
242 curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)upload.length);
243
244 return curl_easy_perform(curl);
245 }
246
247 typedef enum {
248 LOG_TO_JOURNAL_REMOTE_BAD_PARAMS = -1,
249 LOG_TO_JOURNAL_REMOTE_CANNOT_INITIALIZE = -2,
250 LOG_TO_JOURNAL_REMOTE_CANNOT_SEND = -3,
251 LOG_TO_JOURNAL_REMOTE_CANNOT_READ = -4,
252 } log_to_journal_remote_ret_t;
253
254 static log_to_journal_remote_ret_t log_input_to_journal_remote(const char *url, const char *key, const char *cert, const char *trust, const char *newline, int timeout_ms) {
255 if(!url || !*url) {
256 fprintf(stderr, "No URL is given.\n");
257 return LOG_TO_JOURNAL_REMOTE_BAD_PARAMS;
258 }
259
260 if(timeout_ms < 10)
261 timeout_ms = 10;
262
263 global_boot_id[0] = '\0';
264 char buffer[1024];
265 if(read_txt_file(BOOT_ID_PATH, buffer, sizeof(buffer)) == 0) {
266 nd_uuid_t uuid;
267 if(uuid_parse_flexi(buffer, uuid) == 0)
268 uuid_unparse_lower_compact(uuid, global_boot_id);
269 else
270 fprintf(stderr, "WARNING: cannot parse the UUID found in '%s'.\n", BOOT_ID_PATH);
271 }
272
273 if(global_boot_id[0] == '\0') {
274 fprintf(stderr, "WARNING: cannot read '%s'. Will generate a random _BOOT_ID.\n", BOOT_ID_PATH);
275 nd_uuid_t uuid;
276 uuid_generate_random(uuid);
277 uuid_unparse_lower_compact(uuid, global_boot_id);
278 }
279
280 if(read_txt_file(MACHINE_ID_PATH, buffer, sizeof(buffer)) == 0) {
281 nd_uuid_t uuid;
282 if(uuid_parse_flexi(buffer, uuid) == 0)
283 uuid_unparse_lower_compact(uuid, global_machine_id);
284 else
285 fprintf(stderr, "WARNING: cannot parse the UUID found in '%s'.\n", MACHINE_ID_PATH);
286 }
287
288 if(global_machine_id[0] == '\0') {
289 fprintf(stderr, "WARNING: cannot read '%s'. Will generate a random _MACHINE_ID.\n", MACHINE_ID_PATH);
290 nd_uuid_t uuid;
291 uuid_generate_random(uuid);
292 uuid_unparse_lower_compact(uuid, global_machine_id);
293 }
294
295 if(global_stream_id[0] == '\0') {
296 nd_uuid_t uuid;
297 uuid_generate_random(uuid);
298 uuid_unparse_lower_compact(uuid, global_stream_id);
299 }
300
301 if(global_hostname[0] == '\0') {
302 if(gethostname(global_hostname, sizeof(global_hostname)) != 0) {
303 fprintf(stderr, "WARNING: cannot get system's hostname. Will use internal default.\n");
304 snprintfz(global_hostname, sizeof(global_hostname), "systemd-cat-native-unknown-hostname");
305 }
306 }
307
308 if(global_systemd_invocation_id[0] == '\0' && getenv("INVOCATION_ID"))
309 snprintfz(global_systemd_invocation_id, sizeof(global_systemd_invocation_id), "_SYSTEMD_INVOCATION_ID=%s\n", getenv("INVOCATION_ID"));
310
311 if(!key)
312 key = DEFAULT_PRIVATE_KEY;
313
314 if(!cert)
315 cert = DEFAULT_PUBLIC_KEY;
316
317 if(!trust)
318 trust = DEFAULT_CA_CERT;
319
320 char full_url[4096];
321 snprintfz(full_url, sizeof(full_url), "%s/upload", url);
322
323 CURL *curl;
324 CURLcode res = CURLE_OK;
325 struct curl_slist *headers = NULL;
326
327 curl_global_init(CURL_GLOBAL_ALL);
328 curl = initialize_connection_to_systemd_journal_remote(full_url, key, cert, trust, &headers);
329
330 if(!curl)
331 return LOG_TO_JOURNAL_REMOTE_CANNOT_INITIALIZE;
332
333 struct buffered_reader reader;
334 buffered_reader_init(&reader);
335 CLEAN_BUFFER *line = buffer_create(sizeof(reader.read_buffer), NULL);
336 CLEAN_BUFFER *msg = buffer_create(sizeof(reader.read_buffer), NULL);
337
338 size_t msg_full_events = 0;
339 size_t msg_partial_fields = 0;
340 usec_t msg_started_ut = 0;
341 size_t failures = 0;
342 size_t messages_logged = 0;
343
344 log_to_journal_remote_ret_t ret = 0;
345
346 while(true) {
347 buffered_reader_ret_t rc = get_next_line(&reader, line, timeout_ms);
348 if(rc == BUFFERED_READER_READ_POLL_TIMEOUT) {
349 if(msg_full_events && !msg_partial_fields) {
350 res = journal_remote_send_buffer(curl, msg);
351 if(res != CURLE_OK) {
352 fprintf(stderr, "journal_remote_send_buffer() failed: %s\n", curl_easy_strerror(res));
353 failures++;
354 ret = LOG_TO_JOURNAL_REMOTE_CANNOT_SEND;
355 goto cleanup;
356 }
357 else
358 messages_logged++;
359
360 msg_full_events = 0;
361 buffer_flush(msg);
362 }
363 }
364 else if(rc == BUFFERED_READER_READ_OK) {
365 if(!line->len) {
366 // an empty line - we are done for this message
367 if(msg_partial_fields) {
368 msg_partial_fields = 0;
369
370 usec_t ut;
371 journal_remote_complete_event(msg, &ut);
372 if(!msg_full_events)
373 msg_started_ut = ut;
374
375 msg_full_events++;
376
377 if(ut - msg_started_ut >= USEC_PER_SEC / 2) {
378 res = journal_remote_send_buffer(curl, msg);
379 if(res != CURLE_OK) {
380 fprintf(stderr, "journal_remote_send_buffer() failed: %s\n", curl_easy_strerror(res));
381 failures++;
382 ret = LOG_TO_JOURNAL_REMOTE_CANNOT_SEND;
383 goto cleanup;
384 }
385 else
386 messages_logged++;
387
388 msg_full_events = 0;
389 buffer_flush(msg);
390 }
391 }
392 }
393 else {
394 buffer_memcat_replacing_newlines(msg, line->buffer, line->len, newline);
395 msg_partial_fields++;
396 }
397
398 buffer_flush(line);
399 }
400 else {
401 fprintf(stderr, "cannot read input data, failed with code %d\n", rc);
402 ret = LOG_TO_JOURNAL_REMOTE_CANNOT_READ;
403 break;
404 }
405 }
406
407 if (msg_full_events || msg_partial_fields) {
408 if(msg_partial_fields) {
409 msg_partial_fields = 0;
410 msg_full_events++;
411 journal_remote_complete_event(msg, NULL);
412 }
413
414 if(msg_full_events) {
415 res = journal_remote_send_buffer(curl, msg);
416 if(res != CURLE_OK) {
417 fprintf(stderr, "journal_remote_send_buffer() failed: %s\n", curl_easy_strerror(res));
418 failures++;
419 }
420 else
421 messages_logged++;
422
423 msg_full_events = 0;
424 buffer_flush(msg);
425 }
426 }
427
428 cleanup:
429 curl_easy_cleanup(curl);
430 curl_slist_free_all(headers);
431 curl_global_cleanup();
432
433 return ret;
434 }
435
436 #endif
437
438 static int help(void) {
439 fprintf(stderr,
440 "\n"
441 "Netdata systemd-cat-native " NETDATA_VERSION "\n"
442 "\n"
443 "This program reads from its standard input, lines in the format:\n"
444 "\n"
445 "KEY1=VALUE1\\n\n"
446 "KEY2=VALUE2\\n\n"
447 "KEYN=VALUEN\\n\n"
448 "\\n\n"
449 "\n"
450 "and sends them to systemd-journal.\n"
451 "\n"
452 " - Binary journal fields are not accepted at its input\n"
453 " - Binary journal fields can be generated after newline processing\n"
454 " - Messages have to be separated by an empty line\n"
455 " - Keys starting with underscore are not accepted (by journald)\n"
456 " - Other rules imposed by systemd-journald are imposed (by journald)\n"
457 "\n"
458 "Usage:\n"
459 "\n"
460 " %s\n"
461 " [--verbose|-v]\n"
462 " [--newline=STRING]\n"
463 " [--log-as-netdata|-N]\n"
464 " [--namespace=NAMESPACE] [--socket=PATH]\n"
465 #ifdef HAVE_LIBCURL
466 " [--url=URL [--key=FILENAME] [--cert=FILENAME] [--trust=FILENAME|all]]\n"
467 #endif
468 "\n"
469 "The program has the following modes of logging:\n"
470 "\n"
471 " * Log to a local systemd-journald or stderr\n"
472 "\n"
473 " This is the default mode. If systemd-journald is available, logs will be\n"
474 " sent to systemd, otherwise logs will be printed on stderr, using logfmt\n"
475 " formatting. Options --socket and --namespace are available to configure\n"
476 " the journal destination:\n"
477 "\n"
478 " --socket=PATH\n"
479 " The path of a systemd-journald UNIX socket.\n"
480 " The program will use the default systemd-journald socket when this\n"
481 " option is not used.\n"
482 "\n"
483 " --namespace=NAMESPACE\n"
484 " The name of a configured and running systemd-journald namespace.\n"
485 " The program will produce the socket path based on its internal\n"
486 " defaults, to send the messages to the systemd journal namespace.\n"
487 "\n"
488 " * Log as Netdata, enabled with --log-as-netdata or -N\n"
489 "\n"
490 " In this mode the program uses environment variables set by Netdata for\n"
491 " the log destination. Only log fields defined by Netdata are accepted.\n"
492 " If the environment variables expected by Netdata are not found, it\n"
493 " falls back to stderr logging in logfmt format.\n"
494 #ifdef HAVE_LIBCURL
495 "\n"
496 " * Log to a systemd-journal-remote TCP socket, enabled with --url=URL\n"
497 "\n"
498 " In this mode, the program will directly sent logs to a remote systemd\n"
499 " journal (systemd-journal-remote expected at the destination)\n"
500 " This mode is available even when the local system does not support\n"
501 " systemd, or even it is not Linux, allowing a remote Linux systemd\n"
502 " journald to become the logs database of the local system.\n"
503 "\n"
504 " Unfortunately systemd-journal-remote does not accept compressed\n"
505 " data over the network, so the stream will be uncompressed.\n"
506 "\n"
507 " --url=URL\n"
508 " The destination systemd-journal-remote address and port, similarly\n"
509 " to what /etc/systemd/journal-upload.conf accepts.\n"
510 " Usually it is in the form: https://ip.address:19532\n"
511 " Both http and https URLs are accepted. When using https, the\n"
512 " following additional options are accepted:\n"
513 "\n"
514 " --key=FILENAME\n"
515 " The filename of the private key of the server.\n"
516 " The default is: " DEFAULT_PRIVATE_KEY "\n"
517 "\n"
518 " --cert=FILENAME\n"
519 " The filename of the public key of the server.\n"
520 " The default is: " DEFAULT_PUBLIC_KEY "\n"
521 "\n"
522 " --trust=FILENAME | all\n"
523 " The filename of the trusted CA public key.\n"
524 " The default is: " DEFAULT_CA_CERT "\n"
525 " The keyword 'all' can be used to trust all CAs.\n"
526 "\n"
527 " --namespace=NAMESPACE\n"
528 " Set the namespace of the messages sent.\n"
529 "\n"
530 " --keep-trying\n"
531 " Keep trying to send the message, if the remote journal is not there.\n"
532 #endif
533 "\n"
534 " NEWLINES PROCESSING\n"
535 " systemd-journal logs entries may have newlines in them. However the\n"
536 " Journal Export Format uses binary formatted data to achieve this,\n"
537 " making it hard for text processing.\n"
538 "\n"
539 " To overcome this limitation, this program allows single-line text\n"
540 " formatted values at its input, to be binary formatted multi-line Journal\n"
541 " Export Format at its output.\n"
542 "\n"
543 " To achieve that it allows replacing a given string to a newline.\n"
544 " The parameter --newline=STRING allows setting the string to be replaced\n"
545 " with newlines.\n"
546 "\n"
547 " With the default setting of --newline='\\n', the program will replace\n"
548 " all occurrences of \\n with the newline character, within each\n"
549 " VALUE of the KEY=VALUE lines. Once this this done, the program will\n"
550 " switch the field to the binary Journal Export Format before sending the\n"
551 " log event to systemd-journal.\n"
552 "\n",
553 program_name);
554
555 return 1;
556 }
557
558 // ----------------------------------------------------------------------------
559 // log as Netdata
560
561 static void lgs_reset(struct log_stack_entry *lgs) {
562 for(size_t i = 1; i < _NDF_MAX ;i++) {
563 if(lgs[i].type == NDFT_TXT && lgs[i].set && lgs[i].txt)
564 freez((void *)lgs[i].txt);
565
566 lgs[i] = ND_LOG_FIELD_TXT(i, NULL);
567 }
568
569 lgs[0] = ND_LOG_FIELD_TXT(NDF_MESSAGE, NULL);
570 lgs[_NDF_MAX] = ND_LOG_FIELD_END();
571 }
572
573 static const char *strdupz_replacing_newlines(const char *src, const char *newline) {
574 if(!src) src = "";
575
576 size_t src_len = strlen(src);
577 char *buffer = mallocz(src_len + 1);
578 copy_replacing_newlines(buffer, src_len + 1, src, src_len, newline);
579 return buffer;
580 }
581
582 static int log_input_as_netdata(const char *newline, int timeout_ms) {
583 struct buffered_reader reader;
584 buffered_reader_init(&reader);
585 CLEAN_BUFFER *line = buffer_create(sizeof(reader.read_buffer), NULL);
586
587 ND_LOG_STACK lgs[_NDF_MAX + 1] = { 0 };
588 ND_LOG_STACK_PUSH(lgs);
589 lgs_reset(lgs);
590
591 ND_LOG_SOURCES source = NDLS_HEALTH;
592 ND_LOG_FIELD_PRIORITY priority = NDLP_INFO;
593 size_t fields_added = 0;
594 size_t messages_logged = 0;
595
596 while(get_next_line(&reader, line, timeout_ms) == BUFFERED_READER_READ_OK) {
597 if(!line->len) {
598 // an empty line - we are done for this message
599
600 nd_log(source, priority,
601 "added %zu fields", // if the user supplied a MESSAGE, this will be ignored
602 fields_added);
603
604 lgs_reset(lgs);
605 fields_added = 0;
606 messages_logged++;
607 }
608 else {
609 char *equal = strchr(line->buffer, '=');
610 if(equal) {
611 const char *field = line->buffer;
612 size_t field_len = equal - line->buffer;
613 ND_LOG_FIELD_ID id = nd_log_field_id_by_journal_name(field, field_len);
614 if(id != NDF_STOP) {
615 const char *value = ++equal;
616
617 if(lgs[id].txt)
618 freez((void *) lgs[id].txt);
619
620 lgs[id].txt = strdupz_replacing_newlines(value, newline);
621 lgs[id].set = true;
622
623 fields_added++;
624
625 if(id == NDF_PRIORITY)
626 priority = nd_log_priority2id(value);
627 }
628 else {
629 struct log_stack_entry backup = lgs[NDF_MESSAGE];
630 lgs[NDF_MESSAGE] = ND_LOG_FIELD_TXT(NDF_MESSAGE, NULL);
631
632 nd_log(source, NDLP_ERR,
633 "Field '%.*s' is not a Netdata field. Ignoring it.",
634 (int)field_len, field);
635
636 lgs[NDF_MESSAGE] = backup;
637 }
638 }
639 else {
640 struct log_stack_entry backup = lgs[NDF_MESSAGE];
641 lgs[NDF_MESSAGE] = ND_LOG_FIELD_TXT(NDF_MESSAGE, NULL);
642
643 nd_log(source, NDLP_ERR,
644 "Line does not contain an = sign; ignoring it: %s",
645 line->buffer);
646
647 lgs[NDF_MESSAGE] = backup;
648 }
649 }
650
651 buffer_flush(line);
652 }
653
654 if(fields_added) {
655 nd_log(source, priority, "added %zu fields", fields_added);
656 messages_logged++;
657 }
658
659 return messages_logged ? 0 : 1;
660 }
661
662 // ----------------------------------------------------------------------------
663 // log to a local systemd-journald
664
665 static bool journal_local_send_buffer(int fd, BUFFER *msg) {
666 if(verbose)
667 log_message_to_stderr(msg, "LOCAL");
668
669 bool ret = journal_direct_send(fd, msg->buffer, msg->len);
670 if (!ret)
671 fprintf(stderr, "Cannot send message to systemd journal.\n");
672
673 return ret;
674 }
675
676 static int log_input_to_journal(const char *socket, const char *namespace, const char *newline, int timeout_ms) {
677 char path[FILENAME_MAX + 1];
678 int fd = -1;
679
680 if(socket)
681 snprintfz(path, sizeof(path), "%s", socket);
682 else
683 journal_construct_path(path, sizeof(path), NULL, namespace);
684
685 fd = journal_direct_fd(path);
686 if (fd == -1) {
687 fprintf(stderr, "Cannot open '%s' as a UNIX socket (errno = %d)\n",
688 path, errno);
689 return 1;
690 }
691
692 struct buffered_reader reader;
693 buffered_reader_init(&reader);
694 CLEAN_BUFFER *line = buffer_create(sizeof(reader.read_buffer), NULL);
695 CLEAN_BUFFER *msg = buffer_create(sizeof(reader.read_buffer), NULL);
696
697 size_t messages_logged = 0;
698 size_t failed_messages = 0;
699
700 while(get_next_line(&reader, line, timeout_ms) == BUFFERED_READER_READ_OK) {
701 if (!line->len) {
702 // an empty line - we are done for this message
703 if (msg->len) {
704 if(journal_local_send_buffer(fd, msg))
705 messages_logged++;
706 else {
707 failed_messages++;
708 goto cleanup;
709 }
710 }
711
712 buffer_flush(msg);
713 }
714 else
715 buffer_memcat_replacing_newlines(msg, line->buffer, line->len, newline);
716
717 buffer_flush(line);
718 }
719
720 if (msg && msg->len) {
721 if(journal_local_send_buffer(fd, msg))
722 messages_logged++;
723 else
724 failed_messages++;
725 }
726
727 cleanup:
728 if(verbose) {
729 if(failed_messages)
730 fprintf(stderr, "%zu messages failed to be logged\n", failed_messages);
731 if(!messages_logged)
732 fprintf(stderr, "No messages were logged!\n");
733 }
734
735 return !failed_messages && messages_logged ? 0 : 1;
736 }
737
738 int main(int argc, char *argv[]) {
739 nd_log_initialize_for_external_plugins(argv[0]);
740
741 int timeout_ms = 0; // wait forever
742 bool log_as_netdata = false;
743 const char *newline = "\\n";
744 const char *namespace = NULL;
745 const char *socket = getenv("NETDATA_SYSTEMD_JOURNAL_PATH");
746 #ifdef HAVE_LIBCURL
747 const char *url = NULL;
748 const char *key = NULL;
749 const char *cert = NULL;
750 const char *trust = NULL;
751 bool keep_trying = false;
752 #endif
753
754 for(int i = 1; i < argc ;i++) {
755 const char *k = argv[i];
756
757 if(strcmp(k, "--help") == 0 || strcmp(k, "-h") == 0)
758 return help();
759
760 else if(strcmp(k, "--verbose") == 0 || strcmp(k, "-v") == 0)
761 verbose = true;
762
763 else if(strcmp(k, "--log-as-netdata") == 0 || strcmp(k, "-N") == 0)
764 log_as_netdata = true;
765
766 else if(strncmp(k, "--namespace=", 12) == 0)
767 namespace = &k[12];
768
769 else if(strncmp(k, "--socket=", 9) == 0)
770 socket = &k[9];
771
772 else if(strncmp(k, "--newline=", 10) == 0)
773 newline = &k[10];
774
775 #ifdef HAVE_LIBCURL
776 else if (strncmp(k, "--url=", 6) == 0)
777 url = &k[6];
778
779 else if (strncmp(k, "--key=", 6) == 0)
780 key = &k[6];
781
782 else if (strncmp(k, "--cert=", 7) == 0)
783 cert = &k[7];
784
785 else if (strncmp(k, "--trust=", 8) == 0)
786 trust = &k[8];
787
788 else if (strcmp(k, "--keep-trying") == 0)
789 keep_trying = true;
790 #endif
791 else {
792 fprintf(stderr, "Unknown parameter '%s'\n", k);
793 return 1;
794 }
795 }
796
797 #ifdef HAVE_LIBCURL
798 if(log_as_netdata && url) {
799 fprintf(stderr, "Cannot log to a systemd-journal-remote URL as Netdata. "
800 "Please either give --url or --log-as-netdata, not both.\n");
801 return 1;
802 }
803
804 if(socket && url) {
805 fprintf(stderr, "Cannot log to a systemd-journal-remote URL using a UNIX socket. "
806 "Please either give --url or --socket, not both.\n");
807 return 1;
808 }
809
810 #endif
811
812 if(log_as_netdata && namespace) {
813 fprintf(stderr, "Cannot log as netdata using a namespace. "
814 "Please either give --log-as-netdata or --namespace, not both.\n");
815 return 1;
816 }
817
818 if(log_as_netdata)
819 return log_input_as_netdata(newline, timeout_ms);
820
821 #ifdef HAVE_LIBCURL
822 if(url) {
823 if(url && namespace && *namespace)
824 snprintfz(global_namespace, sizeof(global_namespace), "_NAMESPACE=%s\n", namespace);
825
826 log_to_journal_remote_ret_t rc;
827 do {
828 rc = log_input_to_journal_remote(url, key, cert, trust, newline, timeout_ms);
829 } while(keep_trying && rc == LOG_TO_JOURNAL_REMOTE_CANNOT_SEND);
830 }
831 #endif
832
833 return log_input_to_journal(socket, namespace, newline, timeout_ms);
834 }