systemd-journal-files.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "systemd-internals.h"
  3. #define SYSTEMD_JOURNAL_MAX_SOURCE_LEN 64
  4. #define VAR_LOG_JOURNAL_MAX_DEPTH 10
  5. struct journal_directory journal_directories[MAX_JOURNAL_DIRECTORIES] = { 0 };
  6. DICTIONARY *journal_files_registry = NULL;
  7. DICTIONARY *used_hashes_registry = NULL;
  8. static usec_t systemd_journal_session = 0;
  9. void buffer_json_journal_versions(BUFFER *wb) {
  10. buffer_json_member_add_object(wb, "versions");
  11. {
  12. buffer_json_member_add_uint64(wb, "sources",
  13. systemd_journal_session + dictionary_version(journal_files_registry));
  14. }
  15. buffer_json_object_close(wb);
  16. }
  17. static bool journal_sd_id128_parse(const char *in, sd_id128_t *ret) {
  18. while(isspace(*in))
  19. in++;
  20. char uuid[33];
  21. strncpyz(uuid, in, 32);
  22. uuid[32] = '\0';
  23. if(strlen(uuid) == 32) {
  24. sd_id128_t read;
  25. if(sd_id128_from_string(uuid, &read) == 0) {
  26. *ret = read;
  27. return true;
  28. }
  29. }
  30. return false;
  31. }
  32. static void journal_file_get_header_from_journalctl(const char *filename, struct journal_file *jf) {
  33. // unfortunately, our capabilities are not inheritted by journalctl
  34. // so, it fails to give us the information we need.
  35. bool read_writer = false, read_head = false, read_tail = false;
  36. char cmd[FILENAME_MAX * 2];
  37. snprintfz(cmd, sizeof(cmd), "journalctl --header --file '%s'", filename);
  38. CLEAN_BUFFER *wb = run_command_and_get_output_to_buffer(cmd, 1024);
  39. if(wb) {
  40. const char *s = buffer_tostring(wb);
  41. const char *sequential_id_header = "Sequential Number ID:";
  42. const char *sequential_id_data = strcasestr(s, sequential_id_header);
  43. if(sequential_id_data) {
  44. sequential_id_data += strlen(sequential_id_header);
  45. if(journal_sd_id128_parse(sequential_id_data, &jf->first_writer_id))
  46. read_writer = true;
  47. }
  48. const char *head_sequential_number_header = "Head sequential number:";
  49. const char *head_sequential_number_data = strcasestr(s, head_sequential_number_header);
  50. if(head_sequential_number_data) {
  51. head_sequential_number_data += strlen(head_sequential_number_header);
  52. while(isspace(*head_sequential_number_data))
  53. head_sequential_number_data++;
  54. if(isdigit(*head_sequential_number_data)) {
  55. jf->first_seqnum = strtoul(head_sequential_number_data, NULL, 10);
  56. if(jf->first_seqnum)
  57. read_head = true;
  58. }
  59. }
  60. const char *tail_sequential_number_header = "Tail sequential number:";
  61. const char *tail_sequential_number_data = strcasestr(s, tail_sequential_number_header);
  62. if(tail_sequential_number_data) {
  63. tail_sequential_number_data += strlen(tail_sequential_number_header);
  64. while(isspace(*tail_sequential_number_data))
  65. tail_sequential_number_data++;
  66. if(isdigit(*tail_sequential_number_data)) {
  67. jf->last_seqnum = strtoul(tail_sequential_number_data, NULL, 10);
  68. if(jf->last_seqnum)
  69. read_tail = true;
  70. }
  71. }
  72. if(read_head && read_tail && jf->last_seqnum > jf->first_seqnum)
  73. jf->messages_in_file = jf->last_seqnum - jf->first_seqnum;
  74. }
  75. if(!jf->logged_journalctl_failure && (!read_head || !read_head || !read_tail)) {
  76. nd_log(NDLS_COLLECTORS, NDLP_NOTICE,
  77. "Failed to read %s%s%s from journalctl's output on filename '%s', using the command: %s",
  78. read_writer?"":"writer id,",
  79. read_head?"":"head id,",
  80. read_tail?"":"tail id,",
  81. filename, cmd);
  82. jf->logged_journalctl_failure = true;
  83. }
  84. }
  85. usec_t journal_file_update_annotation_boot_id(sd_journal *j, struct journal_file *jf, const char *boot_id) {
  86. usec_t ut = UINT64_MAX;
  87. int r;
  88. char m[100];
  89. size_t len = snprintfz(m, sizeof(m), "_BOOT_ID=%s", boot_id);
  90. sd_journal_flush_matches(j);
  91. r = sd_journal_add_match(j, m, len);
  92. if(r < 0) {
  93. errno = -r;
  94. internal_error(true,
  95. "JOURNAL: while looking for the first timestamp of boot_id '%s', "
  96. "sd_journal_add_match('%s') on file '%s' returned %d",
  97. boot_id, m, jf->filename, r);
  98. return UINT64_MAX;
  99. }
  100. r = sd_journal_seek_head(j);
  101. if(r < 0) {
  102. errno = -r;
  103. internal_error(true,
  104. "JOURNAL: while looking for the first timestamp of boot_id '%s', "
  105. "sd_journal_seek_head() on file '%s' returned %d",
  106. boot_id, jf->filename, r);
  107. return UINT64_MAX;
  108. }
  109. r = sd_journal_next(j);
  110. if(r < 0) {
  111. errno = -r;
  112. internal_error(true,
  113. "JOURNAL: while looking for the first timestamp of boot_id '%s', "
  114. "sd_journal_next() on file '%s' returned %d",
  115. boot_id, jf->filename, r);
  116. return UINT64_MAX;
  117. }
  118. r = sd_journal_get_realtime_usec(j, &ut);
  119. if(r < 0 || !ut || ut == UINT64_MAX) {
  120. errno = -r;
  121. internal_error(r != -EADDRNOTAVAIL,
  122. "JOURNAL: while looking for the first timestamp of boot_id '%s', "
  123. "sd_journal_get_realtime_usec() on file '%s' returned %d",
  124. boot_id, jf->filename, r);
  125. return UINT64_MAX;
  126. }
  127. if(ut && ut != UINT64_MAX) {
  128. dictionary_set(boot_ids_to_first_ut, boot_id, &ut, sizeof(ut));
  129. return ut;
  130. }
  131. return UINT64_MAX;
  132. }
  133. static void journal_file_get_boot_id_annotations(sd_journal *j __maybe_unused, struct journal_file *jf __maybe_unused) {
  134. #ifdef HAVE_SD_JOURNAL_RESTART_FIELDS
  135. sd_journal_flush_matches(j);
  136. int r = sd_journal_query_unique(j, "_BOOT_ID");
  137. if (r < 0) {
  138. errno = -r;
  139. internal_error(true,
  140. "JOURNAL: while querying for the unique _BOOT_ID values, "
  141. "sd_journal_query_unique() on file '%s' returned %d",
  142. jf->filename, r);
  143. errno = -r;
  144. return;
  145. }
  146. const void *data = NULL;
  147. size_t data_length;
  148. DICTIONARY *dict = dictionary_create(DICT_OPTION_SINGLE_THREADED);
  149. SD_JOURNAL_FOREACH_UNIQUE(j, data, data_length) {
  150. const char *key, *value;
  151. size_t key_length, value_length;
  152. if(!parse_journal_field(data, data_length, &key, &key_length, &value, &value_length))
  153. continue;
  154. if(value_length != 32)
  155. continue;
  156. char buf[33];
  157. memcpy(buf, value, 32);
  158. buf[32] = '\0';
  159. dictionary_set(dict, buf, NULL, 0);
  160. }
  161. void *nothing;
  162. dfe_start_read(dict, nothing){
  163. journal_file_update_annotation_boot_id(j, jf, nothing_dfe.name);
  164. }
  165. dfe_done(nothing);
  166. dictionary_destroy(dict);
  167. #endif
  168. }
  169. void journal_file_update_header(const char *filename, struct journal_file *jf) {
  170. if(jf->last_scan_header_vs_last_modified_ut == jf->file_last_modified_ut)
  171. return;
  172. fstat_cache_enable_on_thread();
  173. const char *files[2] = {
  174. [0] = filename,
  175. [1] = NULL,
  176. };
  177. sd_journal *j = NULL;
  178. if(sd_journal_open_files(&j, files, ND_SD_JOURNAL_OPEN_FLAGS) < 0 || !j) {
  179. netdata_log_error("JOURNAL: cannot open file '%s' to update msg_ut", filename);
  180. fstat_cache_disable_on_thread();
  181. if(!jf->logged_failure) {
  182. netdata_log_error("cannot open journal file '%s', using file timestamps to understand time-frame.", filename);
  183. jf->logged_failure = true;
  184. }
  185. jf->msg_first_ut = 0;
  186. jf->msg_last_ut = jf->file_last_modified_ut;
  187. jf->last_scan_header_vs_last_modified_ut = jf->file_last_modified_ut;
  188. return;
  189. }
  190. usec_t first_ut = 0, last_ut = 0;
  191. uint64_t first_seqnum = 0, last_seqnum = 0;
  192. sd_id128_t first_writer_id = SD_ID128_NULL, last_writer_id = SD_ID128_NULL;
  193. if(sd_journal_seek_head(j) < 0 || sd_journal_next(j) < 0 || sd_journal_get_realtime_usec(j, &first_ut) < 0 || !first_ut) {
  194. internal_error(true, "cannot find the timestamp of the first message in '%s'", filename);
  195. first_ut = 0;
  196. }
  197. #ifdef HAVE_SD_JOURNAL_GET_SEQNUM
  198. else {
  199. if(sd_journal_get_seqnum(j, &first_seqnum, &first_writer_id) < 0 || !first_seqnum) {
  200. internal_error(true, "cannot find the first seqnums of the first message in '%s'", filename);
  201. first_seqnum = 0;
  202. memset(&first_writer_id, 0, sizeof(first_writer_id));
  203. }
  204. }
  205. #endif
  206. if(sd_journal_seek_tail(j) < 0 || sd_journal_previous(j) < 0 || sd_journal_get_realtime_usec(j, &last_ut) < 0 || !last_ut) {
  207. internal_error(true, "cannot find the timestamp of the last message in '%s'", filename);
  208. last_ut = jf->file_last_modified_ut;
  209. }
  210. #ifdef HAVE_SD_JOURNAL_GET_SEQNUM
  211. else {
  212. if(sd_journal_get_seqnum(j, &last_seqnum, &last_writer_id) < 0 || !last_seqnum) {
  213. internal_error(true, "cannot find the last seqnums of the first message in '%s'", filename);
  214. last_seqnum = 0;
  215. memset(&last_writer_id, 0, sizeof(last_writer_id));
  216. }
  217. }
  218. #endif
  219. if(first_ut > last_ut) {
  220. internal_error(true, "timestamps are flipped in file '%s'", filename);
  221. usec_t t = first_ut;
  222. first_ut = last_ut;
  223. last_ut = t;
  224. }
  225. if(!first_seqnum || !first_ut) {
  226. // extract these from the filename - if possible
  227. const char *at = strchr(filename, '@');
  228. if(at) {
  229. const char *dash_seqnum = strchr(at + 1, '-');
  230. if(dash_seqnum) {
  231. const char *dash_first_msg_ut = strchr(dash_seqnum + 1, '-');
  232. if(dash_first_msg_ut) {
  233. const char *dot_journal = strstr(dash_first_msg_ut + 1, ".journal");
  234. if(dot_journal) {
  235. if(dash_seqnum - at - 1 == 32 &&
  236. dash_first_msg_ut - dash_seqnum - 1 == 16 &&
  237. dot_journal - dash_first_msg_ut - 1 == 16) {
  238. sd_id128_t writer;
  239. if(journal_sd_id128_parse(at + 1, &writer)) {
  240. char *endptr = NULL;
  241. uint64_t seqnum = strtoul(dash_seqnum + 1, &endptr, 16);
  242. if(endptr == dash_first_msg_ut) {
  243. uint64_t ts = strtoul(dash_first_msg_ut + 1, &endptr, 16);
  244. if(endptr == dot_journal) {
  245. first_seqnum = seqnum;
  246. first_writer_id = writer;
  247. first_ut = ts;
  248. }
  249. }
  250. }
  251. }
  252. }
  253. }
  254. }
  255. }
  256. }
  257. jf->first_seqnum = first_seqnum;
  258. jf->last_seqnum = last_seqnum;
  259. jf->first_writer_id = first_writer_id;
  260. jf->last_writer_id = last_writer_id;
  261. jf->msg_first_ut = first_ut;
  262. jf->msg_last_ut = last_ut;
  263. if(!jf->msg_last_ut)
  264. jf->msg_last_ut = jf->file_last_modified_ut;
  265. if(last_seqnum > first_seqnum) {
  266. if(!sd_id128_equal(first_writer_id, last_writer_id)) {
  267. jf->messages_in_file = 0;
  268. nd_log(NDLS_COLLECTORS, NDLP_NOTICE,
  269. "The writers of the first and the last message in file '%s' differ."
  270. , filename);
  271. }
  272. else
  273. jf->messages_in_file = last_seqnum - first_seqnum + 1;
  274. }
  275. else
  276. jf->messages_in_file = 0;
  277. // if(!jf->messages_in_file)
  278. // journal_file_get_header_from_journalctl(filename, jf);
  279. journal_file_get_boot_id_annotations(j, jf);
  280. sd_journal_close(j);
  281. fstat_cache_disable_on_thread();
  282. jf->last_scan_header_vs_last_modified_ut = jf->file_last_modified_ut;
  283. nd_log(NDLS_COLLECTORS, NDLP_DEBUG,
  284. "Journal file header updated '%s'",
  285. jf->filename);
  286. }
  287. static STRING *string_strdupz_source(const char *s, const char *e, size_t max_len, const char *prefix) {
  288. char buf[max_len];
  289. size_t len;
  290. char *dst = buf;
  291. if(prefix) {
  292. len = strlen(prefix);
  293. memcpy(buf, prefix, len);
  294. dst = &buf[len];
  295. max_len -= len;
  296. }
  297. len = e - s;
  298. if(len >= max_len)
  299. len = max_len - 1;
  300. memcpy(dst, s, len);
  301. dst[len] = '\0';
  302. buf[max_len - 1] = '\0';
  303. for(size_t i = 0; buf[i] ;i++)
  304. if(!isalnum(buf[i]) && buf[i] != '-' && buf[i] != '.' && buf[i] != ':')
  305. buf[i] = '_';
  306. return string_strdupz(buf);
  307. }
  308. static void files_registry_insert_cb(const DICTIONARY_ITEM *item, void *value, void *data __maybe_unused) {
  309. struct journal_file *jf = value;
  310. jf->filename = dictionary_acquired_item_name(item);
  311. jf->filename_len = strlen(jf->filename);
  312. jf->source_type = SDJF_ALL;
  313. // based on the filename
  314. // decide the source to show to the user
  315. const char *s = strrchr(jf->filename, '/');
  316. if(s) {
  317. if(strstr(jf->filename, "/remote/")) {
  318. jf->source_type |= SDJF_REMOTE_ALL;
  319. if(strncmp(s, "/remote-", 8) == 0) {
  320. s = &s[8]; // skip "/remote-"
  321. char *e = strchr(s, '@');
  322. if(!e)
  323. e = strstr(s, ".journal");
  324. if(e) {
  325. const char *d = s;
  326. for(; d < e && (isdigit(*d) || *d == '.' || *d == ':') ; d++) ;
  327. if(d == e) {
  328. // a valid IP address
  329. char ip[e - s + 1];
  330. memcpy(ip, s, e - s);
  331. ip[e - s] = '\0';
  332. char buf[SYSTEMD_JOURNAL_MAX_SOURCE_LEN];
  333. if(ip_to_hostname(ip, buf, sizeof(buf)))
  334. jf->source = string_strdupz_source(buf, &buf[strlen(buf)], SYSTEMD_JOURNAL_MAX_SOURCE_LEN, "remote-");
  335. else {
  336. internal_error(true, "Cannot find the hostname for IP '%s'", ip);
  337. jf->source = string_strdupz_source(s, e, SYSTEMD_JOURNAL_MAX_SOURCE_LEN, "remote-");
  338. }
  339. }
  340. else
  341. jf->source = string_strdupz_source(s, e, SYSTEMD_JOURNAL_MAX_SOURCE_LEN, "remote-");
  342. }
  343. }
  344. }
  345. else {
  346. jf->source_type |= SDJF_LOCAL_ALL;
  347. const char *t = s - 1;
  348. while(t >= jf->filename && *t != '.' && *t != '/')
  349. t--;
  350. if(t >= jf->filename && *t == '.') {
  351. jf->source_type |= SDJF_LOCAL_NAMESPACE;
  352. jf->source = string_strdupz_source(t + 1, s, SYSTEMD_JOURNAL_MAX_SOURCE_LEN, "namespace-");
  353. }
  354. else if(strncmp(s, "/system", 7) == 0)
  355. jf->source_type |= SDJF_LOCAL_SYSTEM;
  356. else if(strncmp(s, "/user", 5) == 0)
  357. jf->source_type |= SDJF_LOCAL_USER;
  358. else
  359. jf->source_type |= SDJF_LOCAL_OTHER;
  360. }
  361. }
  362. else
  363. jf->source_type |= SDJF_LOCAL_ALL | SDJF_LOCAL_OTHER;
  364. jf->msg_last_ut = jf->file_last_modified_ut;
  365. nd_log(NDLS_COLLECTORS, NDLP_DEBUG,
  366. "Journal file added to the journal files registry: '%s'",
  367. jf->filename);
  368. }
  369. static bool files_registry_conflict_cb(const DICTIONARY_ITEM *item, void *old_value, void *new_value, void *data __maybe_unused) {
  370. struct journal_file *jf = old_value;
  371. struct journal_file *njf = new_value;
  372. if(njf->last_scan_monotonic_ut > jf->last_scan_monotonic_ut)
  373. jf->last_scan_monotonic_ut = njf->last_scan_monotonic_ut;
  374. if(njf->file_last_modified_ut > jf->file_last_modified_ut) {
  375. jf->file_last_modified_ut = njf->file_last_modified_ut;
  376. jf->size = njf->size;
  377. jf->msg_last_ut = jf->file_last_modified_ut;
  378. nd_log(NDLS_COLLECTORS, NDLP_DEBUG,
  379. "Journal file updated to the journal files registry '%s'",
  380. jf->filename);
  381. }
  382. return false;
  383. }
  384. struct journal_file_source {
  385. usec_t first_ut;
  386. usec_t last_ut;
  387. size_t count;
  388. uint64_t size;
  389. };
  390. static void human_readable_size_ib(uint64_t size, char *dst, size_t dst_len) {
  391. if(size > 1024ULL * 1024 * 1024 * 1024)
  392. snprintfz(dst, dst_len, "%0.2f TiB", (double)size / 1024.0 / 1024.0 / 1024.0 / 1024.0);
  393. else if(size > 1024ULL * 1024 * 1024)
  394. snprintfz(dst, dst_len, "%0.2f GiB", (double)size / 1024.0 / 1024.0 / 1024.0);
  395. else if(size > 1024ULL * 1024)
  396. snprintfz(dst, dst_len, "%0.2f MiB", (double)size / 1024.0 / 1024.0);
  397. else if(size > 1024ULL)
  398. snprintfz(dst, dst_len, "%0.2f KiB", (double)size / 1024.0);
  399. else
  400. snprintfz(dst, dst_len, "%"PRIu64" B", size);
  401. }
  402. #define print_duration(dst, dst_len, pos, remaining, duration, one, many, printed) do { \
  403. if((remaining) > (duration)) { \
  404. uint64_t _count = (remaining) / (duration); \
  405. uint64_t _rem = (remaining) - (_count * (duration)); \
  406. (pos) += snprintfz(&(dst)[pos], (dst_len) - (pos), "%s%s%"PRIu64" %s", (printed) ? ", " : "", _rem ? "" : "and ", _count, _count > 1 ? (many) : (one)); \
  407. (remaining) = _rem; \
  408. (printed) = true; \
  409. } \
  410. } while(0)
  411. static void human_readable_duration_s(time_t duration_s, char *dst, size_t dst_len) {
  412. if(duration_s < 0)
  413. duration_s = -duration_s;
  414. size_t pos = 0;
  415. dst[0] = 0 ;
  416. bool printed = false;
  417. print_duration(dst, dst_len, pos, duration_s, 86400 * 365, "year", "years", printed);
  418. print_duration(dst, dst_len, pos, duration_s, 86400 * 30, "month", "months", printed);
  419. print_duration(dst, dst_len, pos, duration_s, 86400 * 1, "day", "days", printed);
  420. print_duration(dst, dst_len, pos, duration_s, 3600 * 1, "hour", "hours", printed);
  421. print_duration(dst, dst_len, pos, duration_s, 60 * 1, "min", "mins", printed);
  422. print_duration(dst, dst_len, pos, duration_s, 1, "sec", "secs", printed);
  423. }
  424. static int journal_file_to_json_array_cb(const DICTIONARY_ITEM *item, void *entry, void *data) {
  425. struct journal_file_source *jfs = entry;
  426. BUFFER *wb = data;
  427. const char *name = dictionary_acquired_item_name(item);
  428. buffer_json_add_array_item_object(wb);
  429. {
  430. char size_for_humans[100];
  431. human_readable_size_ib(jfs->size, size_for_humans, sizeof(size_for_humans));
  432. char duration_for_humans[1024];
  433. human_readable_duration_s((time_t)((jfs->last_ut - jfs->first_ut) / USEC_PER_SEC),
  434. duration_for_humans, sizeof(duration_for_humans));
  435. char info[1024];
  436. snprintfz(info, sizeof(info), "%zu files, with a total size of %s, covering %s",
  437. jfs->count, size_for_humans, duration_for_humans);
  438. buffer_json_member_add_string(wb, "id", name);
  439. buffer_json_member_add_string(wb, "name", name);
  440. buffer_json_member_add_string(wb, "pill", size_for_humans);
  441. buffer_json_member_add_string(wb, "info", info);
  442. }
  443. buffer_json_object_close(wb); // options object
  444. return 1;
  445. }
  446. static bool journal_file_merge_sizes(const DICTIONARY_ITEM *item __maybe_unused, void *old_value, void *new_value , void *data __maybe_unused) {
  447. struct journal_file_source *jfs = old_value, *njfs = new_value;
  448. jfs->count += njfs->count;
  449. jfs->size += njfs->size;
  450. if(njfs->first_ut && njfs->first_ut < jfs->first_ut)
  451. jfs->first_ut = njfs->first_ut;
  452. if(njfs->last_ut && njfs->last_ut > jfs->last_ut)
  453. jfs->last_ut = njfs->last_ut;
  454. return false;
  455. }
  456. void available_journal_file_sources_to_json_array(BUFFER *wb) {
  457. DICTIONARY *dict = dictionary_create(DICT_OPTION_SINGLE_THREADED|DICT_OPTION_NAME_LINK_DONT_CLONE|DICT_OPTION_DONT_OVERWRITE_VALUE);
  458. dictionary_register_conflict_callback(dict, journal_file_merge_sizes, NULL);
  459. struct journal_file_source t = { 0 };
  460. struct journal_file *jf;
  461. dfe_start_read(journal_files_registry, jf) {
  462. t.first_ut = jf->msg_first_ut;
  463. t.last_ut = jf->msg_last_ut;
  464. t.count = 1;
  465. t.size = jf->size;
  466. dictionary_set(dict, SDJF_SOURCE_ALL_NAME, &t, sizeof(t));
  467. if(jf->source_type & SDJF_LOCAL_ALL)
  468. dictionary_set(dict, SDJF_SOURCE_LOCAL_NAME, &t, sizeof(t));
  469. if(jf->source_type & SDJF_LOCAL_SYSTEM)
  470. dictionary_set(dict, SDJF_SOURCE_LOCAL_SYSTEM_NAME, &t, sizeof(t));
  471. if(jf->source_type & SDJF_LOCAL_USER)
  472. dictionary_set(dict, SDJF_SOURCE_LOCAL_USERS_NAME, &t, sizeof(t));
  473. if(jf->source_type & SDJF_LOCAL_OTHER)
  474. dictionary_set(dict, SDJF_SOURCE_LOCAL_OTHER_NAME, &t, sizeof(t));
  475. if(jf->source_type & SDJF_LOCAL_NAMESPACE)
  476. dictionary_set(dict, SDJF_SOURCE_NAMESPACES_NAME, &t, sizeof(t));
  477. if(jf->source_type & SDJF_REMOTE_ALL)
  478. dictionary_set(dict, SDJF_SOURCE_REMOTES_NAME, &t, sizeof(t));
  479. if(jf->source)
  480. dictionary_set(dict, string2str(jf->source), &t, sizeof(t));
  481. }
  482. dfe_done(jf);
  483. dictionary_sorted_walkthrough_read(dict, journal_file_to_json_array_cb, wb);
  484. dictionary_destroy(dict);
  485. }
  486. static void files_registry_delete_cb(const DICTIONARY_ITEM *item, void *value, void *data __maybe_unused) {
  487. struct journal_file *jf = value; (void)jf;
  488. const char *filename = dictionary_acquired_item_name(item); (void)filename;
  489. internal_error(true, "removed journal file '%s'", filename);
  490. string_freez(jf->source);
  491. }
  492. void journal_directory_scan_recursively(DICTIONARY *files, DICTIONARY *dirs, const char *dirname, int depth) {
  493. static const char *ext = ".journal";
  494. static const ssize_t ext_len = sizeof(".journal") - 1;
  495. if (depth > VAR_LOG_JOURNAL_MAX_DEPTH)
  496. return;
  497. DIR *dir;
  498. struct dirent *entry;
  499. char full_path[FILENAME_MAX];
  500. // Open the directory.
  501. if ((dir = opendir(dirname)) == NULL) {
  502. if(errno != ENOENT && errno != ENOTDIR)
  503. netdata_log_error("Cannot opendir() '%s'", dirname);
  504. return;
  505. }
  506. bool existing = false;
  507. bool *found = dictionary_set(dirs, dirname, &existing, sizeof(existing));
  508. if(*found) return;
  509. *found = true;
  510. // Read each entry in the directory.
  511. while ((entry = readdir(dir)) != NULL) {
  512. if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
  513. continue;
  514. ssize_t len = snprintfz(full_path, sizeof(full_path), "%s/%s", dirname, entry->d_name);
  515. if (entry->d_type == DT_DIR) {
  516. journal_directory_scan_recursively(files, dirs, full_path, depth++);
  517. }
  518. else if (entry->d_type == DT_REG && len > ext_len && strcmp(full_path + len - ext_len, ext) == 0) {
  519. if(files)
  520. dictionary_set(files, full_path, NULL, 0);
  521. send_newline_and_flush();
  522. }
  523. else if (entry->d_type == DT_LNK) {
  524. struct stat info;
  525. if (stat(full_path, &info) == -1)
  526. continue;
  527. if (S_ISDIR(info.st_mode)) {
  528. // The symbolic link points to a directory
  529. char resolved_path[FILENAME_MAX + 1];
  530. if (realpath(full_path, resolved_path) != NULL) {
  531. journal_directory_scan_recursively(files, dirs, resolved_path, depth++);
  532. }
  533. }
  534. else if(S_ISREG(info.st_mode) && len > ext_len && strcmp(full_path + len - ext_len, ext) == 0) {
  535. if(files)
  536. dictionary_set(files, full_path, NULL, 0);
  537. send_newline_and_flush();
  538. }
  539. }
  540. }
  541. closedir(dir);
  542. }
  543. static size_t journal_files_scans = 0;
  544. bool journal_files_completed_once(void) {
  545. return journal_files_scans > 0;
  546. }
  547. int filenames_compar(const void *a, const void *b) {
  548. const char *p1 = *(const char **)a;
  549. const char *p2 = *(const char **)b;
  550. const char *at1 = strchr(p1, '@');
  551. const char *at2 = strchr(p2, '@');
  552. if(!at1 && at2)
  553. return -1;
  554. if(at1 && !at2)
  555. return 1;
  556. if(!at1 && !at2)
  557. return strcmp(p1, p2);
  558. const char *dash1 = strrchr(at1, '-');
  559. const char *dash2 = strrchr(at2, '-');
  560. if(!dash1 || !dash2)
  561. return strcmp(p1, p2);
  562. uint64_t ts1 = strtoul(dash1 + 1, NULL, 16);
  563. uint64_t ts2 = strtoul(dash2 + 1, NULL, 16);
  564. if(ts1 > ts2)
  565. return -1;
  566. if(ts1 < ts2)
  567. return 1;
  568. return -strcmp(p1, p2);
  569. }
  570. void journal_files_registry_update(void) {
  571. static SPINLOCK spinlock = NETDATA_SPINLOCK_INITIALIZER;
  572. if(spinlock_trylock(&spinlock)) {
  573. usec_t scan_monotonic_ut = now_monotonic_usec();
  574. DICTIONARY *files = dictionary_create(DICT_OPTION_SINGLE_THREADED | DICT_OPTION_DONT_OVERWRITE_VALUE);
  575. DICTIONARY *dirs = dictionary_create(DICT_OPTION_SINGLE_THREADED|DICT_OPTION_DONT_OVERWRITE_VALUE);
  576. for(unsigned i = 0; i < MAX_JOURNAL_DIRECTORIES; i++) {
  577. if(!journal_directories[i].path) break;
  578. journal_directory_scan_recursively(files, dirs, journal_directories[i].path, 0);
  579. }
  580. const char **array = mallocz(sizeof(const char *) * dictionary_entries(files));
  581. size_t used = 0;
  582. void *x;
  583. dfe_start_read(files, x) {
  584. if(used >= dictionary_entries(files)) continue;
  585. array[used++] = x_dfe.name;
  586. }
  587. dfe_done(x);
  588. qsort(array, used, sizeof(const char *), filenames_compar);
  589. for(size_t i = 0; i < used ;i++) {
  590. const char *full_path = array[i];
  591. struct stat info;
  592. if (stat(full_path, &info) == -1)
  593. continue;
  594. struct journal_file t = {
  595. .file_last_modified_ut = info.st_mtim.tv_sec * USEC_PER_SEC + info.st_mtim.tv_nsec / NSEC_PER_USEC,
  596. .last_scan_monotonic_ut = scan_monotonic_ut,
  597. .size = info.st_size,
  598. .max_journal_vs_realtime_delta_ut = JOURNAL_VS_REALTIME_DELTA_DEFAULT_UT,
  599. };
  600. struct journal_file *jf = dictionary_set(journal_files_registry, full_path, &t, sizeof(t));
  601. journal_file_update_header(jf->filename, jf);
  602. }
  603. freez(array);
  604. dictionary_destroy(files);
  605. dictionary_destroy(dirs);
  606. struct journal_file *jf;
  607. dfe_start_write(journal_files_registry, jf){
  608. if(jf->last_scan_monotonic_ut < scan_monotonic_ut)
  609. dictionary_del(journal_files_registry, jf_dfe.name);
  610. }
  611. dfe_done(jf);
  612. journal_files_scans++;
  613. spinlock_unlock(&spinlock);
  614. internal_error(true,
  615. "Journal library scan completed in %.3f ms",
  616. (double)(now_monotonic_usec() - scan_monotonic_ut) / (double)USEC_PER_MS);
  617. }
  618. }
  619. // ----------------------------------------------------------------------------
  620. int journal_file_dict_items_backward_compar(const void *a, const void *b) {
  621. const DICTIONARY_ITEM **ad = (const DICTIONARY_ITEM **)a, **bd = (const DICTIONARY_ITEM **)b;
  622. struct journal_file *jfa = dictionary_acquired_item_value(*ad);
  623. struct journal_file *jfb = dictionary_acquired_item_value(*bd);
  624. // compare the last message timestamps
  625. if(jfa->msg_last_ut < jfb->msg_last_ut)
  626. return 1;
  627. if(jfa->msg_last_ut > jfb->msg_last_ut)
  628. return -1;
  629. // compare the file last modification timestamps
  630. if(jfa->file_last_modified_ut < jfb->file_last_modified_ut)
  631. return 1;
  632. if(jfa->file_last_modified_ut > jfb->file_last_modified_ut)
  633. return -1;
  634. // compare the first message timestamps
  635. if(jfa->msg_first_ut < jfb->msg_first_ut)
  636. return 1;
  637. if(jfa->msg_first_ut > jfb->msg_first_ut)
  638. return -1;
  639. return 0;
  640. }
  641. int journal_file_dict_items_forward_compar(const void *a, const void *b) {
  642. return -journal_file_dict_items_backward_compar(a, b);
  643. }
  644. static bool boot_id_conflict_cb(const DICTIONARY_ITEM *item, void *old_value, void *new_value, void *data __maybe_unused) {
  645. usec_t *old_usec = old_value;
  646. usec_t *new_usec = new_value;
  647. if(*new_usec < *old_usec) {
  648. *old_usec = *new_usec;
  649. return true;
  650. }
  651. return false;
  652. }
  653. void journal_init_files_and_directories(void) {
  654. unsigned d = 0;
  655. // ------------------------------------------------------------------------
  656. // setup the journal directories
  657. journal_directories[d++].path = strdupz("/run/log/journal");
  658. journal_directories[d++].path = strdupz("/var/log/journal");
  659. if(*netdata_configured_host_prefix) {
  660. char path[PATH_MAX];
  661. snprintfz(path, sizeof(path), "%s/var/log/journal", netdata_configured_host_prefix);
  662. journal_directories[d++].path = strdupz(path);
  663. snprintfz(path, sizeof(path), "%s/run/log/journal", netdata_configured_host_prefix);
  664. journal_directories[d++].path = strdupz(path);
  665. }
  666. // terminate the list
  667. journal_directories[d].path = NULL;
  668. // ------------------------------------------------------------------------
  669. // initialize the used hashes files registry
  670. used_hashes_registry = dictionary_create(DICT_OPTION_DONT_OVERWRITE_VALUE);
  671. systemd_journal_session = (now_realtime_usec() / USEC_PER_SEC) * USEC_PER_SEC;
  672. journal_files_registry = dictionary_create_advanced(
  673. DICT_OPTION_DONT_OVERWRITE_VALUE | DICT_OPTION_FIXED_SIZE,
  674. NULL, sizeof(struct journal_file));
  675. dictionary_register_insert_callback(journal_files_registry, files_registry_insert_cb, NULL);
  676. dictionary_register_delete_callback(journal_files_registry, files_registry_delete_cb, NULL);
  677. dictionary_register_conflict_callback(journal_files_registry, files_registry_conflict_cb, NULL);
  678. boot_ids_to_first_ut = dictionary_create_advanced(
  679. DICT_OPTION_DONT_OVERWRITE_VALUE | DICT_OPTION_FIXED_SIZE,
  680. NULL, sizeof(usec_t));
  681. dictionary_register_conflict_callback(boot_ids_to_first_ut, boot_id_conflict_cb, NULL);
  682. }