log.c 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #define SD_JOURNAL_SUPPRESS_LOCATION
  3. #include "../libnetdata.h"
  4. #include <daemon/main.h>
  5. #ifdef __FreeBSD__
  6. #include <sys/endian.h>
  7. #endif
  8. #ifdef __APPLE__
  9. #include <machine/endian.h>
  10. #endif
  11. #ifdef HAVE_BACKTRACE
  12. #include <execinfo.h>
  13. #endif
  14. #ifdef HAVE_SYSTEMD
  15. #include <systemd/sd-journal.h>
  16. #endif
  17. #include <syslog.h>
  18. const char *program_name = "";
  19. uint64_t debug_flags = 0;
  20. #ifdef ENABLE_ACLK
  21. int aclklog_enabled = 0;
  22. #endif
  23. // ----------------------------------------------------------------------------
  24. struct nd_log_source;
  25. static bool nd_log_limit_reached(struct nd_log_source *source);
  26. // ----------------------------------------------------------------------------
  27. // logging method
  28. typedef enum __attribute__((__packed__)) {
  29. NDLM_DISABLED = 0,
  30. NDLM_DEVNULL,
  31. NDLM_DEFAULT,
  32. NDLM_JOURNAL,
  33. NDLM_SYSLOG,
  34. NDLM_STDOUT,
  35. NDLM_STDERR,
  36. NDLM_FILE,
  37. } ND_LOG_METHOD;
  38. static struct {
  39. ND_LOG_METHOD method;
  40. const char *name;
  41. } nd_log_methods[] = {
  42. { .method = NDLM_DISABLED, .name = "none" },
  43. { .method = NDLM_DEVNULL, .name = "/dev/null" },
  44. { .method = NDLM_DEFAULT, .name = "default" },
  45. { .method = NDLM_JOURNAL, .name = "journal" },
  46. { .method = NDLM_SYSLOG, .name = "syslog" },
  47. { .method = NDLM_STDOUT, .name = "stdout" },
  48. { .method = NDLM_STDERR, .name = "stderr" },
  49. { .method = NDLM_FILE, .name = "file" },
  50. };
  51. static ND_LOG_METHOD nd_log_method2id(const char *method) {
  52. if(!method || !*method)
  53. return NDLM_DEFAULT;
  54. size_t entries = sizeof(nd_log_methods) / sizeof(nd_log_methods[0]);
  55. for(size_t i = 0; i < entries ;i++) {
  56. if(strcmp(nd_log_methods[i].name, method) == 0)
  57. return nd_log_methods[i].method;
  58. }
  59. return NDLM_FILE;
  60. }
  61. static const char *nd_log_id2method(ND_LOG_METHOD method) {
  62. size_t entries = sizeof(nd_log_methods) / sizeof(nd_log_methods[0]);
  63. for(size_t i = 0; i < entries ;i++) {
  64. if(method == nd_log_methods[i].method)
  65. return nd_log_methods[i].name;
  66. }
  67. return "unknown";
  68. }
  69. #define IS_VALID_LOG_METHOD_FOR_EXTERNAL_PLUGINS(ndlo) ((ndlo) == NDLM_JOURNAL || (ndlo) == NDLM_SYSLOG || (ndlo) == NDLM_STDERR)
  70. const char *nd_log_method_for_external_plugins(const char *s) {
  71. if(s && *s) {
  72. ND_LOG_METHOD method = nd_log_method2id(s);
  73. if(IS_VALID_LOG_METHOD_FOR_EXTERNAL_PLUGINS(method))
  74. return nd_log_id2method(method);
  75. }
  76. return nd_log_id2method(NDLM_STDERR);
  77. }
  78. // ----------------------------------------------------------------------------
  79. // workaround strerror_r()
  80. #if defined(STRERROR_R_CHAR_P)
  81. // GLIBC version of strerror_r
  82. static const char *strerror_result(const char *a, const char *b) { (void)b; return a; }
  83. #elif defined(HAVE_STRERROR_R)
  84. // POSIX version of strerror_r
  85. static const char *strerror_result(int a, const char *b) { (void)a; return b; }
  86. #elif defined(HAVE_C__GENERIC)
  87. // what a trick!
  88. // http://stackoverflow.com/questions/479207/function-overloading-in-c
  89. static const char *strerror_result_int(int a, const char *b) { (void)a; return b; }
  90. static const char *strerror_result_string(const char *a, const char *b) { (void)b; return a; }
  91. #define strerror_result(a, b) _Generic((a), \
  92. int: strerror_result_int, \
  93. char *: strerror_result_string \
  94. )(a, b)
  95. #else
  96. #error "cannot detect the format of function strerror_r()"
  97. #endif
  98. static const char *errno2str(int errnum, char *buf, size_t size) {
  99. return strerror_result(strerror_r(errnum, buf, size), buf);
  100. }
  101. // ----------------------------------------------------------------------------
  102. // facilities
  103. //
  104. // sys/syslog.h (Linux)
  105. // sys/sys/syslog.h (FreeBSD)
  106. // bsd/sys/syslog.h (darwin-xnu)
  107. static struct {
  108. int facility;
  109. const char *name;
  110. } nd_log_facilities[] = {
  111. { LOG_AUTH, "auth" },
  112. { LOG_AUTHPRIV, "authpriv" },
  113. { LOG_CRON, "cron" },
  114. { LOG_DAEMON, "daemon" },
  115. { LOG_FTP, "ftp" },
  116. { LOG_KERN, "kern" },
  117. { LOG_LPR, "lpr" },
  118. { LOG_MAIL, "mail" },
  119. { LOG_NEWS, "news" },
  120. { LOG_SYSLOG, "syslog" },
  121. { LOG_USER, "user" },
  122. { LOG_UUCP, "uucp" },
  123. { LOG_LOCAL0, "local0" },
  124. { LOG_LOCAL1, "local1" },
  125. { LOG_LOCAL2, "local2" },
  126. { LOG_LOCAL3, "local3" },
  127. { LOG_LOCAL4, "local4" },
  128. { LOG_LOCAL5, "local5" },
  129. { LOG_LOCAL6, "local6" },
  130. { LOG_LOCAL7, "local7" },
  131. #ifdef __FreeBSD__
  132. { LOG_CONSOLE, "console" },
  133. { LOG_NTP, "ntp" },
  134. // FreeBSD does not consider 'security' as deprecated.
  135. { LOG_SECURITY, "security" },
  136. #else
  137. // For all other O/S 'security' is mapped to 'auth'.
  138. { LOG_AUTH, "security" },
  139. #endif
  140. #ifdef __APPLE__
  141. { LOG_INSTALL, "install" },
  142. { LOG_NETINFO, "netinfo" },
  143. { LOG_RAS, "ras" },
  144. { LOG_REMOTEAUTH, "remoteauth" },
  145. { LOG_LAUNCHD, "launchd" },
  146. #endif
  147. };
  148. static int nd_log_facility2id(const char *facility) {
  149. size_t entries = sizeof(nd_log_facilities) / sizeof(nd_log_facilities[0]);
  150. for(size_t i = 0; i < entries ;i++) {
  151. if(strcmp(nd_log_facilities[i].name, facility) == 0)
  152. return nd_log_facilities[i].facility;
  153. }
  154. return LOG_DAEMON;
  155. }
  156. static const char *nd_log_id2facility(int facility) {
  157. size_t entries = sizeof(nd_log_facilities) / sizeof(nd_log_facilities[0]);
  158. for(size_t i = 0; i < entries ;i++) {
  159. if(nd_log_facilities[i].facility == facility)
  160. return nd_log_facilities[i].name;
  161. }
  162. return "daemon";
  163. }
  164. // ----------------------------------------------------------------------------
  165. // priorities
  166. static struct {
  167. ND_LOG_FIELD_PRIORITY priority;
  168. const char *name;
  169. } nd_log_priorities[] = {
  170. { .priority = NDLP_EMERG, .name = "emergency" },
  171. { .priority = NDLP_EMERG, .name = "emerg" },
  172. { .priority = NDLP_ALERT, .name = "alert" },
  173. { .priority = NDLP_CRIT, .name = "critical" },
  174. { .priority = NDLP_CRIT, .name = "crit" },
  175. { .priority = NDLP_ERR, .name = "error" },
  176. { .priority = NDLP_ERR, .name = "err" },
  177. { .priority = NDLP_WARNING, .name = "warning" },
  178. { .priority = NDLP_WARNING, .name = "warn" },
  179. { .priority = NDLP_NOTICE, .name = "notice" },
  180. { .priority = NDLP_INFO, .name = NDLP_INFO_STR },
  181. { .priority = NDLP_DEBUG, .name = "debug" },
  182. };
  183. int nd_log_priority2id(const char *priority) {
  184. size_t entries = sizeof(nd_log_priorities) / sizeof(nd_log_priorities[0]);
  185. for(size_t i = 0; i < entries ;i++) {
  186. if(strcmp(nd_log_priorities[i].name, priority) == 0)
  187. return nd_log_priorities[i].priority;
  188. }
  189. return NDLP_INFO;
  190. }
  191. const char *nd_log_id2priority(ND_LOG_FIELD_PRIORITY priority) {
  192. size_t entries = sizeof(nd_log_priorities) / sizeof(nd_log_priorities[0]);
  193. for(size_t i = 0; i < entries ;i++) {
  194. if(priority == nd_log_priorities[i].priority)
  195. return nd_log_priorities[i].name;
  196. }
  197. return NDLP_INFO_STR;
  198. }
  199. // ----------------------------------------------------------------------------
  200. // log sources
  201. const char *nd_log_sources[] = {
  202. [NDLS_UNSET] = "UNSET",
  203. [NDLS_ACCESS] = "access",
  204. [NDLS_ACLK] = "aclk",
  205. [NDLS_COLLECTORS] = "collector",
  206. [NDLS_DAEMON] = "daemon",
  207. [NDLS_HEALTH] = "health",
  208. [NDLS_DEBUG] = "debug",
  209. };
  210. size_t nd_log_source2id(const char *source, ND_LOG_SOURCES def) {
  211. size_t entries = sizeof(nd_log_sources) / sizeof(nd_log_sources[0]);
  212. for(size_t i = 0; i < entries ;i++) {
  213. if(strcmp(nd_log_sources[i], source) == 0)
  214. return i;
  215. }
  216. return def;
  217. }
  218. static const char *nd_log_id2source(ND_LOG_SOURCES source) {
  219. size_t entries = sizeof(nd_log_sources) / sizeof(nd_log_sources[0]);
  220. if(source < entries)
  221. return nd_log_sources[source];
  222. return nd_log_sources[NDLS_COLLECTORS];
  223. }
  224. // ----------------------------------------------------------------------------
  225. // log output formats
  226. typedef enum __attribute__((__packed__)) {
  227. NDLF_JOURNAL,
  228. NDLF_LOGFMT,
  229. NDLF_JSON,
  230. } ND_LOG_FORMAT;
  231. static struct {
  232. ND_LOG_FORMAT format;
  233. const char *name;
  234. } nd_log_formats[] = {
  235. { .format = NDLF_JOURNAL, .name = "journal" },
  236. { .format = NDLF_LOGFMT, .name = "logfmt" },
  237. { .format = NDLF_JSON, .name = "json" },
  238. };
  239. static ND_LOG_FORMAT nd_log_format2id(const char *format) {
  240. if(!format || !*format)
  241. return NDLF_LOGFMT;
  242. size_t entries = sizeof(nd_log_formats) / sizeof(nd_log_formats[0]);
  243. for(size_t i = 0; i < entries ;i++) {
  244. if(strcmp(nd_log_formats[i].name, format) == 0)
  245. return nd_log_formats[i].format;
  246. }
  247. return NDLF_LOGFMT;
  248. }
  249. static const char *nd_log_id2format(ND_LOG_FORMAT format) {
  250. size_t entries = sizeof(nd_log_formats) / sizeof(nd_log_formats[0]);
  251. for(size_t i = 0; i < entries ;i++) {
  252. if(format == nd_log_formats[i].format)
  253. return nd_log_formats[i].name;
  254. }
  255. return "logfmt";
  256. }
  257. // ----------------------------------------------------------------------------
  258. // format dates
  259. void log_date(char *buffer, size_t len, time_t now) {
  260. if(unlikely(!buffer || !len))
  261. return;
  262. time_t t = now;
  263. struct tm *tmp, tmbuf;
  264. tmp = localtime_r(&t, &tmbuf);
  265. if (unlikely(!tmp)) {
  266. buffer[0] = '\0';
  267. return;
  268. }
  269. if (unlikely(strftime(buffer, len, "%Y-%m-%d %H:%M:%S", tmp) == 0))
  270. buffer[0] = '\0';
  271. buffer[len - 1] = '\0';
  272. }
  273. // ----------------------------------------------------------------------------
  274. struct nd_log_limit {
  275. usec_t started_monotonic_ut;
  276. uint32_t counter;
  277. uint32_t prevented;
  278. uint32_t throttle_period;
  279. uint32_t logs_per_period;
  280. uint32_t logs_per_period_backup;
  281. };
  282. #define ND_LOG_LIMITS_DEFAULT (struct nd_log_limit){ .logs_per_period = ND_LOG_DEFAULT_THROTTLE_LOGS, .logs_per_period_backup = ND_LOG_DEFAULT_THROTTLE_LOGS, .throttle_period = ND_LOG_DEFAULT_THROTTLE_PERIOD, }
  283. #define ND_LOG_LIMITS_UNLIMITED (struct nd_log_limit){ .logs_per_period = 0, .logs_per_period_backup = 0, .throttle_period = 0, }
  284. struct nd_log_source {
  285. SPINLOCK spinlock;
  286. ND_LOG_METHOD method;
  287. ND_LOG_FORMAT format;
  288. const char *filename;
  289. int fd;
  290. FILE *fp;
  291. ND_LOG_FIELD_PRIORITY min_priority;
  292. const char *pending_msg;
  293. struct nd_log_limit limits;
  294. };
  295. static __thread ND_LOG_SOURCES overwrite_thread_source = 0;
  296. void nd_log_set_thread_source(ND_LOG_SOURCES source) {
  297. overwrite_thread_source = source;
  298. }
  299. static struct {
  300. uuid_t invocation_id;
  301. ND_LOG_SOURCES overwrite_process_source;
  302. struct nd_log_source sources[_NDLS_MAX];
  303. struct {
  304. bool initialized;
  305. } journal;
  306. struct {
  307. bool initialized;
  308. int fd;
  309. char filename[FILENAME_MAX + 1];
  310. } journal_direct;
  311. struct {
  312. bool initialized;
  313. int facility;
  314. } syslog;
  315. struct {
  316. SPINLOCK spinlock;
  317. bool initialized;
  318. } std_output;
  319. struct {
  320. SPINLOCK spinlock;
  321. bool initialized;
  322. } std_error;
  323. } nd_log = {
  324. .overwrite_process_source = 0,
  325. .journal = {
  326. .initialized = false,
  327. },
  328. .journal_direct = {
  329. .initialized = false,
  330. .fd = -1,
  331. },
  332. .syslog = {
  333. .initialized = false,
  334. .facility = LOG_DAEMON,
  335. },
  336. .std_output = {
  337. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  338. .initialized = false,
  339. },
  340. .std_error = {
  341. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  342. .initialized = false,
  343. },
  344. .sources = {
  345. [NDLS_UNSET] = {
  346. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  347. .method = NDLM_DISABLED,
  348. .format = NDLF_JOURNAL,
  349. .filename = NULL,
  350. .fd = -1,
  351. .fp = NULL,
  352. .min_priority = NDLP_EMERG,
  353. .limits = ND_LOG_LIMITS_UNLIMITED,
  354. },
  355. [NDLS_ACCESS] = {
  356. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  357. .method = NDLM_DEFAULT,
  358. .format = NDLF_LOGFMT,
  359. .filename = LOG_DIR "/access.log",
  360. .fd = -1,
  361. .fp = NULL,
  362. .min_priority = NDLP_DEBUG,
  363. .limits = ND_LOG_LIMITS_UNLIMITED,
  364. },
  365. [NDLS_ACLK] = {
  366. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  367. .method = NDLM_FILE,
  368. .format = NDLF_LOGFMT,
  369. .filename = LOG_DIR "/aclk.log",
  370. .fd = -1,
  371. .fp = NULL,
  372. .min_priority = NDLP_DEBUG,
  373. .limits = ND_LOG_LIMITS_UNLIMITED,
  374. },
  375. [NDLS_COLLECTORS] = {
  376. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  377. .method = NDLM_DEFAULT,
  378. .format = NDLF_LOGFMT,
  379. .filename = LOG_DIR "/collectors.log",
  380. .fd = STDERR_FILENO,
  381. .fp = NULL,
  382. .min_priority = NDLP_INFO,
  383. .limits = ND_LOG_LIMITS_DEFAULT,
  384. },
  385. [NDLS_DEBUG] = {
  386. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  387. .method = NDLM_DISABLED,
  388. .format = NDLF_LOGFMT,
  389. .filename = LOG_DIR "/debug.log",
  390. .fd = STDOUT_FILENO,
  391. .fp = NULL,
  392. .min_priority = NDLP_DEBUG,
  393. .limits = ND_LOG_LIMITS_UNLIMITED,
  394. },
  395. [NDLS_DAEMON] = {
  396. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  397. .method = NDLM_DEFAULT,
  398. .filename = LOG_DIR "/daemon.log",
  399. .format = NDLF_LOGFMT,
  400. .fd = -1,
  401. .fp = NULL,
  402. .min_priority = NDLP_INFO,
  403. .limits = ND_LOG_LIMITS_DEFAULT,
  404. },
  405. [NDLS_HEALTH] = {
  406. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  407. .method = NDLM_DEFAULT,
  408. .format = NDLF_LOGFMT,
  409. .filename = LOG_DIR "/health.log",
  410. .fd = -1,
  411. .fp = NULL,
  412. .min_priority = NDLP_DEBUG,
  413. .limits = ND_LOG_LIMITS_UNLIMITED,
  414. },
  415. },
  416. };
  417. __attribute__((constructor)) void initialize_invocation_id(void) {
  418. // check for a NETDATA_INVOCATION_ID
  419. if(uuid_parse_flexi(getenv("NETDATA_INVOCATION_ID"), nd_log.invocation_id) != 0) {
  420. // not found, check for systemd set INVOCATION_ID
  421. if(uuid_parse_flexi(getenv("INVOCATION_ID"), nd_log.invocation_id) != 0) {
  422. // not found, generate a new one
  423. uuid_generate_random(nd_log.invocation_id);
  424. }
  425. }
  426. char uuid[UUID_COMPACT_STR_LEN];
  427. uuid_unparse_lower_compact(nd_log.invocation_id, uuid);
  428. setenv("NETDATA_INVOCATION_ID", uuid, 1);
  429. }
  430. int nd_log_health_fd(void) {
  431. if(nd_log.sources[NDLS_HEALTH].method == NDLM_FILE && nd_log.sources[NDLS_HEALTH].fd != -1)
  432. return nd_log.sources[NDLS_HEALTH].fd;
  433. return STDERR_FILENO;
  434. }
  435. void nd_log_set_user_settings(ND_LOG_SOURCES source, const char *setting) {
  436. char buf[FILENAME_MAX + 100];
  437. if(setting && *setting)
  438. strncpyz(buf, setting, sizeof(buf) - 1);
  439. else
  440. buf[0] = '\0';
  441. struct nd_log_source *ls = &nd_log.sources[source];
  442. char *output = strrchr(buf, '@');
  443. if(!output)
  444. // all of it is the output
  445. output = buf;
  446. else {
  447. // we found an '@', the next char is the output
  448. *output = '\0';
  449. output++;
  450. // parse the other params
  451. char *remaining = buf;
  452. while(remaining) {
  453. char *value = strsep_skip_consecutive_separators(&remaining, ",");
  454. if (!value || !*value) continue;
  455. char *name = strsep_skip_consecutive_separators(&value, "=");
  456. if (!name || !*name) continue;
  457. if(strcmp(name, "logfmt") == 0)
  458. ls->format = NDLF_LOGFMT;
  459. else if(strcmp(name, "json") == 0)
  460. ls->format = NDLF_JSON;
  461. else if(strcmp(name, "journal") == 0)
  462. ls->format = NDLF_JOURNAL;
  463. else if(strcmp(name, "level") == 0 && value && *value)
  464. ls->min_priority = nd_log_priority2id(value);
  465. else if(strcmp(name, "protection") == 0 && value && *value) {
  466. if(strcmp(value, "off") == 0 || strcmp(value, "none") == 0) {
  467. ls->limits = ND_LOG_LIMITS_UNLIMITED;
  468. ls->limits.counter = 0;
  469. ls->limits.prevented = 0;
  470. }
  471. else {
  472. ls->limits = ND_LOG_LIMITS_DEFAULT;
  473. char *slash = strchr(value, '/');
  474. if(slash) {
  475. *slash = '\0';
  476. slash++;
  477. ls->limits.logs_per_period = ls->limits.logs_per_period_backup = str2u(value);
  478. ls->limits.throttle_period = str2u(slash);
  479. }
  480. else {
  481. ls->limits.logs_per_period = ls->limits.logs_per_period_backup = str2u(value);
  482. ls->limits.throttle_period = ND_LOG_DEFAULT_THROTTLE_PERIOD;
  483. }
  484. }
  485. }
  486. else
  487. nd_log(NDLS_DAEMON, NDLP_ERR, "Error while parsing configuration of log source '%s'. "
  488. "In config '%s', '%s' is not understood.",
  489. nd_log_id2source(source), setting, name);
  490. }
  491. }
  492. if(!output || !*output || strcmp(output, "none") == 0 || strcmp(output, "off") == 0) {
  493. ls->method = NDLM_DISABLED;
  494. ls->filename = "/dev/null";
  495. }
  496. else if(strcmp(output, "journal") == 0) {
  497. ls->method = NDLM_JOURNAL;
  498. ls->filename = NULL;
  499. }
  500. else if(strcmp(output, "syslog") == 0) {
  501. ls->method = NDLM_SYSLOG;
  502. ls->filename = NULL;
  503. }
  504. else if(strcmp(output, "/dev/null") == 0) {
  505. ls->method = NDLM_DEVNULL;
  506. ls->filename = "/dev/null";
  507. }
  508. else if(strcmp(output, "system") == 0) {
  509. if(ls->fd == STDERR_FILENO) {
  510. ls->method = NDLM_STDERR;
  511. ls->filename = NULL;
  512. ls->fd = STDERR_FILENO;
  513. }
  514. else {
  515. ls->method = NDLM_STDOUT;
  516. ls->filename = NULL;
  517. ls->fd = STDOUT_FILENO;
  518. }
  519. }
  520. else if(strcmp(output, "stderr") == 0) {
  521. ls->method = NDLM_STDERR;
  522. ls->filename = NULL;
  523. ls->fd = STDERR_FILENO;
  524. }
  525. else if(strcmp(output, "stdout") == 0) {
  526. ls->method = NDLM_STDOUT;
  527. ls->filename = NULL;
  528. ls->fd = STDOUT_FILENO;
  529. }
  530. else {
  531. ls->method = NDLM_FILE;
  532. ls->filename = strdupz(output);
  533. }
  534. #if defined(NETDATA_INTERNAL_CHECKS) || defined(NETDATA_DEV_MODE)
  535. ls->min_priority = NDLP_DEBUG;
  536. #endif
  537. if(source == NDLS_COLLECTORS) {
  538. // set the method for the collector processes we will spawn
  539. ND_LOG_METHOD method;
  540. ND_LOG_FORMAT format = ls->format;
  541. ND_LOG_FIELD_PRIORITY priority = ls->min_priority;
  542. if(ls->method == NDLM_SYSLOG || ls->method == NDLM_JOURNAL)
  543. method = ls->method;
  544. else
  545. method = NDLM_STDERR;
  546. setenv("NETDATA_LOG_METHOD", nd_log_id2method(method), 1);
  547. setenv("NETDATA_LOG_FORMAT", nd_log_id2format(format), 1);
  548. setenv("NETDATA_LOG_LEVEL", nd_log_id2priority(priority), 1);
  549. }
  550. }
  551. void nd_log_set_priority_level(const char *setting) {
  552. if(!setting || !*setting)
  553. setting = "info";
  554. ND_LOG_FIELD_PRIORITY priority = nd_log_priority2id(setting);
  555. #if defined(NETDATA_INTERNAL_CHECKS) || defined(NETDATA_DEV_MODE)
  556. priority = NDLP_DEBUG;
  557. #endif
  558. for (size_t i = 0; i < _NDLS_MAX; i++) {
  559. if (i != NDLS_DEBUG)
  560. nd_log.sources[i].min_priority = priority;
  561. }
  562. // the right one
  563. setenv("NETDATA_LOG_LEVEL", nd_log_id2priority(priority), 1);
  564. }
  565. void nd_log_set_facility(const char *facility) {
  566. if(!facility || !*facility)
  567. facility = "daemon";
  568. nd_log.syslog.facility = nd_log_facility2id(facility);
  569. setenv("NETDATA_SYSLOG_FACILITY", nd_log_id2facility(nd_log.syslog.facility), 1);
  570. }
  571. void nd_log_set_flood_protection(size_t logs, time_t period) {
  572. nd_log.sources[NDLS_DAEMON].limits.logs_per_period =
  573. nd_log.sources[NDLS_DAEMON].limits.logs_per_period_backup;
  574. nd_log.sources[NDLS_COLLECTORS].limits.logs_per_period =
  575. nd_log.sources[NDLS_COLLECTORS].limits.logs_per_period_backup = logs;
  576. nd_log.sources[NDLS_DAEMON].limits.throttle_period =
  577. nd_log.sources[NDLS_COLLECTORS].limits.throttle_period = period;
  578. char buf[100];
  579. snprintfz(buf, sizeof(buf), "%" PRIu64, (uint64_t )period);
  580. setenv("NETDATA_ERRORS_THROTTLE_PERIOD", buf, 1);
  581. snprintfz(buf, sizeof(buf), "%" PRIu64, (uint64_t )logs);
  582. setenv("NETDATA_ERRORS_PER_PERIOD", buf, 1);
  583. }
  584. static bool nd_log_journal_systemd_init(void) {
  585. #ifdef HAVE_SYSTEMD
  586. nd_log.journal.initialized = true;
  587. #else
  588. nd_log.journal.initialized = false;
  589. #endif
  590. return nd_log.journal.initialized;
  591. }
  592. static void nd_log_journal_direct_set_env(void) {
  593. if(nd_log.sources[NDLS_COLLECTORS].method == NDLM_JOURNAL)
  594. setenv("NETDATA_SYSTEMD_JOURNAL_PATH", nd_log.journal_direct.filename, 1);
  595. }
  596. static bool nd_log_journal_direct_init(const char *path) {
  597. if(nd_log.journal_direct.initialized) {
  598. nd_log_journal_direct_set_env();
  599. return true;
  600. }
  601. int fd;
  602. char filename[FILENAME_MAX + 1];
  603. if(!is_path_unix_socket(path)) {
  604. journal_construct_path(filename, sizeof(filename), netdata_configured_host_prefix, "netdata");
  605. if (!is_path_unix_socket(filename) || (fd = journal_direct_fd(filename)) == -1) {
  606. journal_construct_path(filename, sizeof(filename), netdata_configured_host_prefix, NULL);
  607. if (!is_path_unix_socket(filename) || (fd = journal_direct_fd(filename)) == -1) {
  608. journal_construct_path(filename, sizeof(filename), NULL, "netdata");
  609. if (!is_path_unix_socket(filename) || (fd = journal_direct_fd(filename)) == -1) {
  610. journal_construct_path(filename, sizeof(filename), NULL, NULL);
  611. if (!is_path_unix_socket(filename) || (fd = journal_direct_fd(filename)) == -1)
  612. return false;
  613. }
  614. }
  615. }
  616. }
  617. else {
  618. snprintfz(filename, sizeof(filename), "%s", path);
  619. fd = journal_direct_fd(filename);
  620. }
  621. if(fd < 0)
  622. return false;
  623. nd_log.journal_direct.fd = fd;
  624. nd_log.journal_direct.initialized = true;
  625. strncpyz(nd_log.journal_direct.filename, filename, sizeof(nd_log.journal_direct.filename) - 1);
  626. nd_log_journal_direct_set_env();
  627. return true;
  628. }
  629. static void nd_log_syslog_init() {
  630. if(nd_log.syslog.initialized)
  631. return;
  632. openlog(program_name, LOG_PID, nd_log.syslog.facility);
  633. nd_log.syslog.initialized = true;
  634. }
  635. void nd_log_initialize_for_external_plugins(const char *name) {
  636. // if we don't run under Netdata, log to stderr,
  637. // otherwise, use the logging method Netdata wants us to use.
  638. setenv("NETDATA_LOG_METHOD", "stderr", 0);
  639. setenv("NETDATA_LOG_FORMAT", "logfmt", 0);
  640. nd_log.overwrite_process_source = NDLS_COLLECTORS;
  641. program_name = name;
  642. for(size_t i = 0; i < _NDLS_MAX ;i++) {
  643. nd_log.sources[i].method = STDERR_FILENO;
  644. nd_log.sources[i].fd = -1;
  645. nd_log.sources[i].fp = NULL;
  646. }
  647. nd_log_set_priority_level(getenv("NETDATA_LOG_LEVEL"));
  648. nd_log_set_facility(getenv("NETDATA_SYSLOG_FACILITY"));
  649. time_t period = 1200;
  650. size_t logs = 200;
  651. const char *s = getenv("NETDATA_ERRORS_THROTTLE_PERIOD");
  652. if(s && *s >= '0' && *s <= '9') {
  653. period = str2l(s);
  654. if(period < 0) period = 0;
  655. }
  656. s = getenv("NETDATA_ERRORS_PER_PERIOD");
  657. if(s && *s >= '0' && *s <= '9')
  658. logs = str2u(s);
  659. nd_log_set_flood_protection(logs, period);
  660. if(!netdata_configured_host_prefix) {
  661. s = getenv("NETDATA_HOST_PREFIX");
  662. if(s && *s)
  663. netdata_configured_host_prefix = (char *)s;
  664. }
  665. ND_LOG_METHOD method = nd_log_method2id(getenv("NETDATA_LOG_METHOD"));
  666. ND_LOG_FORMAT format = nd_log_format2id(getenv("NETDATA_LOG_FORMAT"));
  667. if(!IS_VALID_LOG_METHOD_FOR_EXTERNAL_PLUGINS(method)) {
  668. if(is_stderr_connected_to_journal()) {
  669. nd_log(NDLS_COLLECTORS, NDLP_WARNING, "NETDATA_LOG_METHOD is not set. Using journal.");
  670. method = NDLM_JOURNAL;
  671. }
  672. else {
  673. nd_log(NDLS_COLLECTORS, NDLP_WARNING, "NETDATA_LOG_METHOD is not set. Using stderr.");
  674. method = NDLM_STDERR;
  675. }
  676. }
  677. switch(method) {
  678. case NDLM_JOURNAL:
  679. if(!nd_log_journal_direct_init(getenv("NETDATA_SYSTEMD_JOURNAL_PATH")) ||
  680. !nd_log_journal_direct_init(NULL) || !nd_log_journal_systemd_init()) {
  681. nd_log(NDLS_COLLECTORS, NDLP_WARNING, "Failed to initialize journal. Using stderr.");
  682. method = NDLM_STDERR;
  683. }
  684. break;
  685. case NDLM_SYSLOG:
  686. nd_log_syslog_init();
  687. break;
  688. default:
  689. method = NDLM_STDERR;
  690. break;
  691. }
  692. for(size_t i = 0; i < _NDLS_MAX ;i++) {
  693. nd_log.sources[i].method = method;
  694. nd_log.sources[i].format = format;
  695. nd_log.sources[i].fd = -1;
  696. nd_log.sources[i].fp = NULL;
  697. }
  698. // nd_log(NDLS_COLLECTORS, NDLP_NOTICE, "FINAL_LOG_METHOD: %s", nd_log_id2method(method));
  699. }
  700. static bool nd_log_replace_existing_fd(struct nd_log_source *e, int new_fd) {
  701. if(new_fd == -1 || e->fd == -1 ||
  702. (e->fd == STDOUT_FILENO && nd_log.std_output.initialized) ||
  703. (e->fd == STDERR_FILENO && nd_log.std_error.initialized))
  704. return false;
  705. if(new_fd != e->fd) {
  706. int t = dup2(new_fd, e->fd);
  707. bool ret = true;
  708. if (t == -1) {
  709. netdata_log_error("Cannot dup2() new fd %d to old fd %d for '%s'", new_fd, e->fd, e->filename);
  710. ret = false;
  711. }
  712. else
  713. close(new_fd);
  714. if(e->fd == STDOUT_FILENO)
  715. nd_log.std_output.initialized = true;
  716. else if(e->fd == STDERR_FILENO)
  717. nd_log.std_error.initialized = true;
  718. return ret;
  719. }
  720. return false;
  721. }
  722. static void nd_log_open(struct nd_log_source *e, ND_LOG_SOURCES source) {
  723. if(e->method == NDLM_DEFAULT)
  724. nd_log_set_user_settings(source, e->filename);
  725. if((e->method == NDLM_FILE && !e->filename) ||
  726. (e->method == NDLM_DEVNULL && e->fd == -1))
  727. e->method = NDLM_DISABLED;
  728. if(e->fp)
  729. fflush(e->fp);
  730. switch(e->method) {
  731. case NDLM_SYSLOG:
  732. nd_log_syslog_init();
  733. break;
  734. case NDLM_JOURNAL:
  735. nd_log_journal_direct_init(NULL);
  736. nd_log_journal_systemd_init();
  737. break;
  738. case NDLM_STDOUT:
  739. e->fp = stdout;
  740. e->fd = STDOUT_FILENO;
  741. break;
  742. case NDLM_DISABLED:
  743. break;
  744. case NDLM_DEFAULT:
  745. case NDLM_STDERR:
  746. e->method = NDLM_STDERR;
  747. e->fp = stderr;
  748. e->fd = STDERR_FILENO;
  749. break;
  750. case NDLM_DEVNULL:
  751. case NDLM_FILE: {
  752. int fd = open(e->filename, O_WRONLY | O_APPEND | O_CREAT, 0664);
  753. if(fd == -1) {
  754. if(e->fd != STDOUT_FILENO && e->fd != STDERR_FILENO) {
  755. e->fd = STDERR_FILENO;
  756. e->method = NDLM_STDERR;
  757. netdata_log_error("Cannot open log file '%s'. Falling back to stderr.", e->filename);
  758. }
  759. else
  760. netdata_log_error("Cannot open log file '%s'. Leaving fd %d as-is.", e->filename, e->fd);
  761. }
  762. else {
  763. if (!nd_log_replace_existing_fd(e, fd)) {
  764. if(e->fd == STDOUT_FILENO || e->fd == STDERR_FILENO) {
  765. if(e->fd == STDOUT_FILENO)
  766. e->method = NDLM_STDOUT;
  767. else if(e->fd == STDERR_FILENO)
  768. e->method = NDLM_STDERR;
  769. // we have dup2() fd, so we can close the one we opened
  770. if(fd != STDOUT_FILENO && fd != STDERR_FILENO)
  771. close(fd);
  772. }
  773. else
  774. e->fd = fd;
  775. }
  776. }
  777. // at this point we have e->fd set properly
  778. if(e->fd == STDOUT_FILENO)
  779. e->fp = stdout;
  780. else if(e->fd == STDERR_FILENO)
  781. e->fp = stderr;
  782. if(!e->fp) {
  783. e->fp = fdopen(e->fd, "a");
  784. if (!e->fp) {
  785. netdata_log_error("Cannot fdopen() fd %d ('%s')", e->fd, e->filename);
  786. if(e->fd != STDOUT_FILENO && e->fd != STDERR_FILENO)
  787. close(e->fd);
  788. e->fp = stderr;
  789. e->fd = STDERR_FILENO;
  790. }
  791. }
  792. else {
  793. if (setvbuf(e->fp, NULL, _IOLBF, 0) != 0)
  794. netdata_log_error("Cannot set line buffering on fd %d ('%s')", e->fd, e->filename);
  795. }
  796. }
  797. break;
  798. }
  799. }
  800. static void nd_log_stdin_init(int fd, const char *filename) {
  801. int f = open(filename, O_WRONLY | O_APPEND | O_CREAT, 0664);
  802. if(f == -1)
  803. return;
  804. if(f != fd) {
  805. dup2(f, fd);
  806. close(f);
  807. }
  808. }
  809. void nd_log_initialize(void) {
  810. nd_log_stdin_init(STDIN_FILENO, "/dev/null");
  811. for(size_t i = 0 ; i < _NDLS_MAX ; i++)
  812. nd_log_open(&nd_log.sources[i], i);
  813. }
  814. void nd_log_reopen_log_files(void) {
  815. netdata_log_info("Reopening all log files.");
  816. nd_log.std_output.initialized = false;
  817. nd_log.std_error.initialized = false;
  818. nd_log_initialize();
  819. netdata_log_info("Log files re-opened.");
  820. }
  821. void chown_open_file(int fd, uid_t uid, gid_t gid) {
  822. if(fd == -1) return;
  823. struct stat buf;
  824. if(fstat(fd, &buf) == -1) {
  825. netdata_log_error("Cannot fstat() fd %d", fd);
  826. return;
  827. }
  828. if((buf.st_uid != uid || buf.st_gid != gid) && S_ISREG(buf.st_mode)) {
  829. if(fchown(fd, uid, gid) == -1)
  830. netdata_log_error("Cannot fchown() fd %d.", fd);
  831. }
  832. }
  833. void nd_log_chown_log_files(uid_t uid, gid_t gid) {
  834. for(size_t i = 0 ; i < _NDLS_MAX ; i++) {
  835. if(nd_log.sources[i].fd != -1 && nd_log.sources[i].fd != STDIN_FILENO)
  836. chown_open_file(nd_log.sources[i].fd, uid, gid);
  837. }
  838. }
  839. // ----------------------------------------------------------------------------
  840. // annotators
  841. struct log_field;
  842. static void errno_annotator(BUFFER *wb, const char *key, struct log_field *lf);
  843. static void priority_annotator(BUFFER *wb, const char *key, struct log_field *lf);
  844. static void timestamp_usec_annotator(BUFFER *wb, const char *key, struct log_field *lf);
  845. // ----------------------------------------------------------------------------
  846. typedef void (*annotator_t)(BUFFER *wb, const char *key, struct log_field *lf);
  847. struct log_field {
  848. const char *journal;
  849. const char *logfmt;
  850. annotator_t logfmt_annotator;
  851. struct log_stack_entry entry;
  852. };
  853. #define THREAD_LOG_STACK_MAX 50
  854. static __thread struct log_stack_entry *thread_log_stack_base[THREAD_LOG_STACK_MAX];
  855. static __thread size_t thread_log_stack_next = 0;
  856. static __thread struct log_field thread_log_fields[_NDF_MAX] = {
  857. // THE ORDER DEFINES THE ORDER FIELDS WILL APPEAR IN logfmt
  858. [NDF_STOP] = { // processing will not stop on this - so it is ok to be first
  859. .journal = NULL,
  860. .logfmt = NULL,
  861. .logfmt_annotator = NULL,
  862. },
  863. [NDF_TIMESTAMP_REALTIME_USEC] = {
  864. .journal = NULL,
  865. .logfmt = "time",
  866. .logfmt_annotator = timestamp_usec_annotator,
  867. },
  868. [NDF_SYSLOG_IDENTIFIER] = {
  869. .journal = "SYSLOG_IDENTIFIER", // standard journald field
  870. .logfmt = "comm",
  871. },
  872. [NDF_LOG_SOURCE] = {
  873. .journal = "ND_LOG_SOURCE",
  874. .logfmt = "source",
  875. },
  876. [NDF_PRIORITY] = {
  877. .journal = "PRIORITY", // standard journald field
  878. .logfmt = "level",
  879. .logfmt_annotator = priority_annotator,
  880. },
  881. [NDF_ERRNO] = {
  882. .journal = "ERRNO", // standard journald field
  883. .logfmt = "errno",
  884. .logfmt_annotator = errno_annotator,
  885. },
  886. [NDF_INVOCATION_ID] = {
  887. .journal = "INVOCATION_ID", // standard journald field
  888. .logfmt = NULL,
  889. },
  890. [NDF_LINE] = {
  891. .journal = "CODE_LINE", // standard journald field
  892. .logfmt = NULL,
  893. },
  894. [NDF_FILE] = {
  895. .journal = "CODE_FILE", // standard journald field
  896. .logfmt = NULL,
  897. },
  898. [NDF_FUNC] = {
  899. .journal = "CODE_FUNC", // standard journald field
  900. .logfmt = NULL,
  901. },
  902. [NDF_TID] = {
  903. .journal = "TID", // standard journald field
  904. .logfmt = "tid",
  905. },
  906. [NDF_THREAD_TAG] = {
  907. .journal = "THREAD_TAG",
  908. .logfmt = "thread",
  909. },
  910. [NDF_MESSAGE_ID] = {
  911. .journal = "MESSAGE_ID",
  912. .logfmt = "msg_id",
  913. },
  914. [NDF_MODULE] = {
  915. .journal = "ND_MODULE",
  916. .logfmt = "module",
  917. },
  918. [NDF_NIDL_NODE] = {
  919. .journal = "ND_NIDL_NODE",
  920. .logfmt = "node",
  921. },
  922. [NDF_NIDL_INSTANCE] = {
  923. .journal = "ND_NIDL_INSTANCE",
  924. .logfmt = "instance",
  925. },
  926. [NDF_NIDL_CONTEXT] = {
  927. .journal = "ND_NIDL_CONTEXT",
  928. .logfmt = "context",
  929. },
  930. [NDF_NIDL_DIMENSION] = {
  931. .journal = "ND_NIDL_DIMENSION",
  932. .logfmt = "dimension",
  933. },
  934. [NDF_SRC_TRANSPORT] = {
  935. .journal = "ND_SRC_TRANSPORT",
  936. .logfmt = "src_transport",
  937. },
  938. [NDF_SRC_IP] = {
  939. .journal = "ND_SRC_IP",
  940. .logfmt = "src_ip",
  941. },
  942. [NDF_SRC_PORT] = {
  943. .journal = "ND_SRC_PORT",
  944. .logfmt = "src_port",
  945. },
  946. [NDF_SRC_CAPABILITIES] = {
  947. .journal = "ND_SRC_CAPABILITIES",
  948. .logfmt = "src_capabilities",
  949. },
  950. [NDF_DST_TRANSPORT] = {
  951. .journal = "ND_DST_TRANSPORT",
  952. .logfmt = "dst_transport",
  953. },
  954. [NDF_DST_IP] = {
  955. .journal = "ND_DST_IP",
  956. .logfmt = "dst_ip",
  957. },
  958. [NDF_DST_PORT] = {
  959. .journal = "ND_DST_PORT",
  960. .logfmt = "dst_port",
  961. },
  962. [NDF_DST_CAPABILITIES] = {
  963. .journal = "ND_DST_CAPABILITIES",
  964. .logfmt = "dst_capabilities",
  965. },
  966. [NDF_REQUEST_METHOD] = {
  967. .journal = "ND_REQUEST_METHOD",
  968. .logfmt = "req_method",
  969. },
  970. [NDF_RESPONSE_CODE] = {
  971. .journal = "ND_RESPONSE_CODE",
  972. .logfmt = "code",
  973. },
  974. [NDF_CONNECTION_ID] = {
  975. .journal = "ND_CONNECTION_ID",
  976. .logfmt = "conn",
  977. },
  978. [NDF_TRANSACTION_ID] = {
  979. .journal = "ND_TRANSACTION_ID",
  980. .logfmt = "transaction",
  981. },
  982. [NDF_RESPONSE_SENT_BYTES] = {
  983. .journal = "ND_RESPONSE_SENT_BYTES",
  984. .logfmt = "sent_bytes",
  985. },
  986. [NDF_RESPONSE_SIZE_BYTES] = {
  987. .journal = "ND_RESPONSE_SIZE_BYTES",
  988. .logfmt = "size_bytes",
  989. },
  990. [NDF_RESPONSE_PREPARATION_TIME_USEC] = {
  991. .journal = "ND_RESPONSE_PREP_TIME_USEC",
  992. .logfmt = "prep_ut",
  993. },
  994. [NDF_RESPONSE_SENT_TIME_USEC] = {
  995. .journal = "ND_RESPONSE_SENT_TIME_USEC",
  996. .logfmt = "sent_ut",
  997. },
  998. [NDF_RESPONSE_TOTAL_TIME_USEC] = {
  999. .journal = "ND_RESPONSE_TOTAL_TIME_USEC",
  1000. .logfmt = "total_ut",
  1001. },
  1002. [NDF_ALERT_ID] = {
  1003. .journal = "ND_ALERT_ID",
  1004. .logfmt = "alert_id",
  1005. },
  1006. [NDF_ALERT_UNIQUE_ID] = {
  1007. .journal = "ND_ALERT_UNIQUE_ID",
  1008. .logfmt = "alert_unique_id",
  1009. },
  1010. [NDF_ALERT_TRANSITION_ID] = {
  1011. .journal = "ND_ALERT_TRANSITION_ID",
  1012. .logfmt = "alert_transition_id",
  1013. },
  1014. [NDF_ALERT_EVENT_ID] = {
  1015. .journal = "ND_ALERT_EVENT_ID",
  1016. .logfmt = "alert_event_id",
  1017. },
  1018. [NDF_ALERT_CONFIG_HASH] = {
  1019. .journal = "ND_ALERT_CONFIG",
  1020. .logfmt = "alert_config",
  1021. },
  1022. [NDF_ALERT_NAME] = {
  1023. .journal = "ND_ALERT_NAME",
  1024. .logfmt = "alert",
  1025. },
  1026. [NDF_ALERT_CLASS] = {
  1027. .journal = "ND_ALERT_CLASS",
  1028. .logfmt = "alert_class",
  1029. },
  1030. [NDF_ALERT_COMPONENT] = {
  1031. .journal = "ND_ALERT_COMPONENT",
  1032. .logfmt = "alert_component",
  1033. },
  1034. [NDF_ALERT_TYPE] = {
  1035. .journal = "ND_ALERT_TYPE",
  1036. .logfmt = "alert_type",
  1037. },
  1038. [NDF_ALERT_EXEC] = {
  1039. .journal = "ND_ALERT_EXEC",
  1040. .logfmt = "alert_exec",
  1041. },
  1042. [NDF_ALERT_RECIPIENT] = {
  1043. .journal = "ND_ALERT_RECIPIENT",
  1044. .logfmt = "alert_recipient",
  1045. },
  1046. [NDF_ALERT_VALUE] = {
  1047. .journal = "ND_ALERT_VALUE",
  1048. .logfmt = "alert_value",
  1049. },
  1050. [NDF_ALERT_VALUE_OLD] = {
  1051. .journal = "ND_ALERT_VALUE_OLD",
  1052. .logfmt = "alert_value_old",
  1053. },
  1054. [NDF_ALERT_STATUS] = {
  1055. .journal = "ND_ALERT_STATUS",
  1056. .logfmt = "alert_status",
  1057. },
  1058. [NDF_ALERT_STATUS_OLD] = {
  1059. .journal = "ND_ALERT_STATUS_OLD",
  1060. .logfmt = "alert_value_old",
  1061. },
  1062. [NDF_ALERT_UNITS] = {
  1063. .journal = "ND_ALERT_UNITS",
  1064. .logfmt = "alert_units",
  1065. },
  1066. [NDF_ALERT_SUMMARY] = {
  1067. .journal = "ND_ALERT_SUMMARY",
  1068. .logfmt = "alert_summary",
  1069. },
  1070. [NDF_ALERT_INFO] = {
  1071. .journal = "ND_ALERT_INFO",
  1072. .logfmt = "alert_info",
  1073. },
  1074. [NDF_ALERT_DURATION] = {
  1075. .journal = "ND_ALERT_DURATION",
  1076. .logfmt = "alert_duration",
  1077. },
  1078. [NDF_ALERT_NOTIFICATION_REALTIME_USEC] = {
  1079. .journal = "ND_ALERT_NOTIFICATION_TIMESTAMP_USEC",
  1080. .logfmt = "alert_notification_timestamp",
  1081. .logfmt_annotator = timestamp_usec_annotator,
  1082. },
  1083. // put new items here
  1084. // leave the request URL and the message last
  1085. [NDF_REQUEST] = {
  1086. .journal = "ND_REQUEST",
  1087. .logfmt = "request",
  1088. },
  1089. [NDF_MESSAGE] = {
  1090. .journal = "MESSAGE",
  1091. .logfmt = "msg",
  1092. },
  1093. };
  1094. #define THREAD_FIELDS_MAX (sizeof(thread_log_fields) / sizeof(thread_log_fields[0]))
  1095. ND_LOG_FIELD_ID nd_log_field_id_by_name(const char *field, size_t len) {
  1096. for(size_t i = 0; i < THREAD_FIELDS_MAX ;i++) {
  1097. if(thread_log_fields[i].journal && strlen(thread_log_fields[i].journal) == len && strncmp(field, thread_log_fields[i].journal, len) == 0)
  1098. return i;
  1099. }
  1100. return NDF_STOP;
  1101. }
  1102. void log_stack_pop(void *ptr) {
  1103. if(!ptr) return;
  1104. struct log_stack_entry *lgs = *(struct log_stack_entry (*)[])ptr;
  1105. if(unlikely(!thread_log_stack_next || lgs != thread_log_stack_base[thread_log_stack_next - 1])) {
  1106. fatal("You cannot pop in the middle of the stack, or an item not in the stack");
  1107. return;
  1108. }
  1109. thread_log_stack_next--;
  1110. }
  1111. void log_stack_push(struct log_stack_entry *lgs) {
  1112. if(!lgs || thread_log_stack_next >= THREAD_LOG_STACK_MAX) return;
  1113. thread_log_stack_base[thread_log_stack_next++] = lgs;
  1114. }
  1115. // ----------------------------------------------------------------------------
  1116. // json formatter
  1117. static void nd_logger_json(BUFFER *wb, struct log_field *fields, size_t fields_max) {
  1118. // --- FIELD_PARSER_VERSIONS ---
  1119. //
  1120. // IMPORTANT:
  1121. // THERE ARE 6 VERSIONS OF THIS CODE
  1122. //
  1123. // 1. journal (direct socket API),
  1124. // 2. journal (libsystemd API),
  1125. // 3. logfmt,
  1126. // 4. json,
  1127. // 5. convert to uint64
  1128. // 6. convert to int64
  1129. //
  1130. // UPDATE ALL OF THEM FOR NEW FEATURES OR FIXES
  1131. buffer_json_initialize(wb, "\"", "\"", 0, true, BUFFER_JSON_OPTIONS_MINIFY);
  1132. CLEAN_BUFFER *tmp = NULL;
  1133. for (size_t i = 0; i < fields_max; i++) {
  1134. if (!fields[i].entry.set || !fields[i].logfmt)
  1135. continue;
  1136. const char *key = fields[i].logfmt;
  1137. const char *s = NULL;
  1138. switch(fields[i].entry.type) {
  1139. case NDFT_TXT:
  1140. s = fields[i].entry.txt;
  1141. break;
  1142. case NDFT_STR:
  1143. s = string2str(fields[i].entry.str);
  1144. break;
  1145. case NDFT_BFR:
  1146. s = buffer_tostring(fields[i].entry.bfr);
  1147. break;
  1148. case NDFT_U64:
  1149. buffer_json_member_add_uint64(wb, key, fields[i].entry.u64);
  1150. break;
  1151. case NDFT_I64:
  1152. buffer_json_member_add_int64(wb, key, fields[i].entry.i64);
  1153. break;
  1154. case NDFT_DBL:
  1155. buffer_json_member_add_double(wb, key, fields[i].entry.dbl);
  1156. break;
  1157. case NDFT_UUID:{
  1158. char u[UUID_COMPACT_STR_LEN];
  1159. uuid_unparse_lower_compact(*fields[i].entry.uuid, u);
  1160. buffer_json_member_add_string(wb, key, u);
  1161. }
  1162. break;
  1163. case NDFT_CALLBACK: {
  1164. if(!tmp)
  1165. tmp = buffer_create(1024, NULL);
  1166. else
  1167. buffer_flush(tmp);
  1168. if(fields[i].entry.cb.formatter(tmp, fields[i].entry.cb.formatter_data))
  1169. s = buffer_tostring(tmp);
  1170. else
  1171. s = NULL;
  1172. }
  1173. break;
  1174. default:
  1175. s = "UNHANDLED";
  1176. break;
  1177. }
  1178. if(s && *s)
  1179. buffer_json_member_add_string(wb, key, s);
  1180. }
  1181. buffer_json_finalize(wb);
  1182. }
  1183. // ----------------------------------------------------------------------------
  1184. // logfmt formatter
  1185. static int64_t log_field_to_int64(struct log_field *lf) {
  1186. // --- FIELD_PARSER_VERSIONS ---
  1187. //
  1188. // IMPORTANT:
  1189. // THERE ARE 6 VERSIONS OF THIS CODE
  1190. //
  1191. // 1. journal (direct socket API),
  1192. // 2. journal (libsystemd API),
  1193. // 3. logfmt,
  1194. // 4. json,
  1195. // 5. convert to uint64
  1196. // 6. convert to int64
  1197. //
  1198. // UPDATE ALL OF THEM FOR NEW FEATURES OR FIXES
  1199. CLEAN_BUFFER *tmp = NULL;
  1200. const char *s = NULL;
  1201. switch(lf->entry.type) {
  1202. case NDFT_UUID:
  1203. case NDFT_UNSET:
  1204. return 0;
  1205. case NDFT_TXT:
  1206. s = lf->entry.txt;
  1207. break;
  1208. case NDFT_STR:
  1209. s = string2str(lf->entry.str);
  1210. break;
  1211. case NDFT_BFR:
  1212. s = buffer_tostring(lf->entry.bfr);
  1213. break;
  1214. case NDFT_CALLBACK:
  1215. if(!tmp)
  1216. tmp = buffer_create(0, NULL);
  1217. else
  1218. buffer_flush(tmp);
  1219. if(lf->entry.cb.formatter(tmp, lf->entry.cb.formatter_data))
  1220. s = buffer_tostring(tmp);
  1221. else
  1222. s = NULL;
  1223. break;
  1224. case NDFT_U64:
  1225. return lf->entry.u64;
  1226. case NDFT_I64:
  1227. return lf->entry.i64;
  1228. case NDFT_DBL:
  1229. return lf->entry.dbl;
  1230. }
  1231. if(s && *s)
  1232. return str2ll(s, NULL);
  1233. return 0;
  1234. }
  1235. static uint64_t log_field_to_uint64(struct log_field *lf) {
  1236. // --- FIELD_PARSER_VERSIONS ---
  1237. //
  1238. // IMPORTANT:
  1239. // THERE ARE 6 VERSIONS OF THIS CODE
  1240. //
  1241. // 1. journal (direct socket API),
  1242. // 2. journal (libsystemd API),
  1243. // 3. logfmt,
  1244. // 4. json,
  1245. // 5. convert to uint64
  1246. // 6. convert to int64
  1247. //
  1248. // UPDATE ALL OF THEM FOR NEW FEATURES OR FIXES
  1249. CLEAN_BUFFER *tmp = NULL;
  1250. const char *s = NULL;
  1251. switch(lf->entry.type) {
  1252. case NDFT_UUID:
  1253. case NDFT_UNSET:
  1254. return 0;
  1255. case NDFT_TXT:
  1256. s = lf->entry.txt;
  1257. break;
  1258. case NDFT_STR:
  1259. s = string2str(lf->entry.str);
  1260. break;
  1261. case NDFT_BFR:
  1262. s = buffer_tostring(lf->entry.bfr);
  1263. break;
  1264. case NDFT_CALLBACK:
  1265. if(!tmp)
  1266. tmp = buffer_create(0, NULL);
  1267. else
  1268. buffer_flush(tmp);
  1269. if(lf->entry.cb.formatter(tmp, lf->entry.cb.formatter_data))
  1270. s = buffer_tostring(tmp);
  1271. else
  1272. s = NULL;
  1273. break;
  1274. case NDFT_U64:
  1275. return lf->entry.u64;
  1276. case NDFT_I64:
  1277. return lf->entry.i64;
  1278. case NDFT_DBL:
  1279. return lf->entry.dbl;
  1280. }
  1281. if(s && *s)
  1282. return str2uint64_t(s, NULL);
  1283. return 0;
  1284. }
  1285. static void timestamp_usec_annotator(BUFFER *wb, const char *key, struct log_field *lf) {
  1286. usec_t ut = log_field_to_uint64(lf);
  1287. if(!ut)
  1288. return;
  1289. char datetime[RFC3339_MAX_LENGTH];
  1290. rfc3339_datetime_ut(datetime, sizeof(datetime), ut, 3, false);
  1291. if(buffer_strlen(wb))
  1292. buffer_fast_strcat(wb, " ", 1);
  1293. buffer_strcat(wb, key);
  1294. buffer_fast_strcat(wb, "=", 1);
  1295. buffer_json_strcat(wb, datetime);
  1296. }
  1297. static void errno_annotator(BUFFER *wb, const char *key, struct log_field *lf) {
  1298. int64_t errnum = log_field_to_int64(lf);
  1299. if(errnum == 0)
  1300. return;
  1301. char buf[1024];
  1302. const char *s = errno2str(errnum, buf, sizeof(buf));
  1303. if(buffer_strlen(wb))
  1304. buffer_fast_strcat(wb, " ", 1);
  1305. buffer_strcat(wb, key);
  1306. buffer_fast_strcat(wb, "=\"", 2);
  1307. buffer_print_int64(wb, errnum);
  1308. buffer_fast_strcat(wb, ", ", 2);
  1309. buffer_json_strcat(wb, s);
  1310. buffer_fast_strcat(wb, "\"", 1);
  1311. }
  1312. static void priority_annotator(BUFFER *wb, const char *key, struct log_field *lf) {
  1313. uint64_t pri = log_field_to_uint64(lf);
  1314. if(buffer_strlen(wb))
  1315. buffer_fast_strcat(wb, " ", 1);
  1316. buffer_strcat(wb, key);
  1317. buffer_fast_strcat(wb, "=", 1);
  1318. buffer_strcat(wb, nd_log_id2priority(pri));
  1319. }
  1320. static bool needs_quotes_for_logfmt(const char *s) {
  1321. static bool safe_for_logfmt[256] = {
  1322. [' '] = true, ['!'] = true, ['"'] = false, ['#'] = true, ['$'] = true, ['%'] = true, ['&'] = true,
  1323. ['\''] = true, ['('] = true, [')'] = true, ['*'] = true, ['+'] = true, [','] = true, ['-'] = true,
  1324. ['.'] = true, ['/'] = true, ['0'] = true, ['1'] = true, ['2'] = true, ['3'] = true, ['4'] = true,
  1325. ['5'] = true, ['6'] = true, ['7'] = true, ['8'] = true, ['9'] = true, [':'] = true, [';'] = true,
  1326. ['<'] = true, ['='] = true, ['>'] = true, ['?'] = true, ['@'] = true, ['A'] = true, ['B'] = true,
  1327. ['C'] = true, ['D'] = true, ['E'] = true, ['F'] = true, ['G'] = true, ['H'] = true, ['I'] = true,
  1328. ['J'] = true, ['K'] = true, ['L'] = true, ['M'] = true, ['N'] = true, ['O'] = true, ['P'] = true,
  1329. ['Q'] = true, ['R'] = true, ['S'] = true, ['T'] = true, ['U'] = true, ['V'] = true, ['W'] = true,
  1330. ['X'] = true, ['Y'] = true, ['Z'] = true, ['['] = true, ['\\'] = false, [']'] = true, ['^'] = true,
  1331. ['_'] = true, ['`'] = true, ['a'] = true, ['b'] = true, ['c'] = true, ['d'] = true, ['e'] = true,
  1332. ['f'] = true, ['g'] = true, ['h'] = true, ['i'] = true, ['j'] = true, ['k'] = true, ['l'] = true,
  1333. ['m'] = true, ['n'] = true, ['o'] = true, ['p'] = true, ['q'] = true, ['r'] = true, ['s'] = true,
  1334. ['t'] = true, ['u'] = true, ['v'] = true, ['w'] = true, ['x'] = true, ['y'] = true, ['z'] = true,
  1335. ['{'] = true, ['|'] = true, ['}'] = true, ['~'] = true, [0x7f] = true,
  1336. };
  1337. if(!*s)
  1338. return true;
  1339. while(*s) {
  1340. if(*s == '=' || isspace(*s) || !safe_for_logfmt[(uint8_t)*s])
  1341. return true;
  1342. s++;
  1343. }
  1344. return false;
  1345. }
  1346. static void string_to_logfmt(BUFFER *wb, const char *s) {
  1347. bool spaces = needs_quotes_for_logfmt(s);
  1348. if(spaces)
  1349. buffer_fast_strcat(wb, "\"", 1);
  1350. buffer_json_strcat(wb, s);
  1351. if(spaces)
  1352. buffer_fast_strcat(wb, "\"", 1);
  1353. }
  1354. static void nd_logger_logfmt(BUFFER *wb, struct log_field *fields, size_t fields_max) {
  1355. // --- FIELD_PARSER_VERSIONS ---
  1356. //
  1357. // IMPORTANT:
  1358. // THERE ARE 6 VERSIONS OF THIS CODE
  1359. //
  1360. // 1. journal (direct socket API),
  1361. // 2. journal (libsystemd API),
  1362. // 3. logfmt,
  1363. // 4. json,
  1364. // 5. convert to uint64
  1365. // 6. convert to int64
  1366. //
  1367. // UPDATE ALL OF THEM FOR NEW FEATURES OR FIXES
  1368. CLEAN_BUFFER *tmp = NULL;
  1369. for (size_t i = 0; i < fields_max; i++) {
  1370. if (!fields[i].entry.set || !fields[i].logfmt)
  1371. continue;
  1372. const char *key = fields[i].logfmt;
  1373. if(fields[i].logfmt_annotator)
  1374. fields[i].logfmt_annotator(wb, key, &fields[i]);
  1375. else {
  1376. if(buffer_strlen(wb))
  1377. buffer_fast_strcat(wb, " ", 1);
  1378. switch(fields[i].entry.type) {
  1379. case NDFT_TXT:
  1380. if(*fields[i].entry.txt) {
  1381. buffer_strcat(wb, key);
  1382. buffer_fast_strcat(wb, "=", 1);
  1383. string_to_logfmt(wb, fields[i].entry.txt);
  1384. }
  1385. break;
  1386. case NDFT_STR:
  1387. buffer_strcat(wb, key);
  1388. buffer_fast_strcat(wb, "=", 1);
  1389. string_to_logfmt(wb, string2str(fields[i].entry.str));
  1390. break;
  1391. case NDFT_BFR:
  1392. if(buffer_strlen(fields[i].entry.bfr)) {
  1393. buffer_strcat(wb, key);
  1394. buffer_fast_strcat(wb, "=", 1);
  1395. string_to_logfmt(wb, buffer_tostring(fields[i].entry.bfr));
  1396. }
  1397. break;
  1398. case NDFT_U64:
  1399. buffer_strcat(wb, key);
  1400. buffer_fast_strcat(wb, "=", 1);
  1401. buffer_print_uint64(wb, fields[i].entry.u64);
  1402. break;
  1403. case NDFT_I64:
  1404. buffer_strcat(wb, key);
  1405. buffer_fast_strcat(wb, "=", 1);
  1406. buffer_print_int64(wb, fields[i].entry.i64);
  1407. break;
  1408. case NDFT_DBL:
  1409. buffer_strcat(wb, key);
  1410. buffer_fast_strcat(wb, "=", 1);
  1411. buffer_print_netdata_double(wb, fields[i].entry.dbl);
  1412. break;
  1413. case NDFT_UUID: {
  1414. char u[UUID_COMPACT_STR_LEN];
  1415. uuid_unparse_lower_compact(*fields[i].entry.uuid, u);
  1416. buffer_strcat(wb, key);
  1417. buffer_fast_strcat(wb, "=", 1);
  1418. buffer_fast_strcat(wb, u, sizeof(u) - 1);
  1419. }
  1420. break;
  1421. case NDFT_CALLBACK: {
  1422. if(!tmp)
  1423. tmp = buffer_create(1024, NULL);
  1424. else
  1425. buffer_flush(tmp);
  1426. if(fields[i].entry.cb.formatter(tmp, fields[i].entry.cb.formatter_data)) {
  1427. buffer_strcat(wb, key);
  1428. buffer_fast_strcat(wb, "=", 1);
  1429. string_to_logfmt(wb, buffer_tostring(tmp));
  1430. }
  1431. }
  1432. break;
  1433. default:
  1434. buffer_strcat(wb, "UNHANDLED");
  1435. break;
  1436. }
  1437. }
  1438. }
  1439. }
  1440. // ----------------------------------------------------------------------------
  1441. // journal logger
  1442. bool nd_log_journal_socket_available(void) {
  1443. if(netdata_configured_host_prefix && *netdata_configured_host_prefix) {
  1444. char filename[FILENAME_MAX + 1];
  1445. snprintfz(filename, sizeof(filename), "%s%s",
  1446. netdata_configured_host_prefix, "/run/systemd/journal/socket");
  1447. if(is_path_unix_socket(filename))
  1448. return true;
  1449. }
  1450. return is_path_unix_socket("/run/systemd/journal/socket");
  1451. }
  1452. static bool nd_logger_journal_libsystemd(struct log_field *fields, size_t fields_max) {
  1453. #ifdef HAVE_SYSTEMD
  1454. // --- FIELD_PARSER_VERSIONS ---
  1455. //
  1456. // IMPORTANT:
  1457. // THERE ARE 6 VERSIONS OF THIS CODE
  1458. //
  1459. // 1. journal (direct socket API),
  1460. // 2. journal (libsystemd API),
  1461. // 3. logfmt,
  1462. // 4. json,
  1463. // 5. convert to uint64
  1464. // 6. convert to int64
  1465. //
  1466. // UPDATE ALL OF THEM FOR NEW FEATURES OR FIXES
  1467. struct iovec iov[fields_max];
  1468. int iov_count = 0;
  1469. memset(iov, 0, sizeof(iov));
  1470. CLEAN_BUFFER *tmp = NULL;
  1471. for (size_t i = 0; i < fields_max; i++) {
  1472. if (!fields[i].entry.set || !fields[i].journal)
  1473. continue;
  1474. const char *key = fields[i].journal;
  1475. char *value = NULL;
  1476. switch (fields[i].entry.type) {
  1477. case NDFT_TXT:
  1478. if(*fields[i].entry.txt)
  1479. asprintf(&value, "%s=%s", key, fields[i].entry.txt);
  1480. break;
  1481. case NDFT_STR:
  1482. asprintf(&value, "%s=%s", key, string2str(fields[i].entry.str));
  1483. break;
  1484. case NDFT_BFR:
  1485. if(buffer_strlen(fields[i].entry.bfr))
  1486. asprintf(&value, "%s=%s", key, buffer_tostring(fields[i].entry.bfr));
  1487. break;
  1488. case NDFT_U64:
  1489. asprintf(&value, "%s=%" PRIu64, key, fields[i].entry.u64);
  1490. break;
  1491. case NDFT_I64:
  1492. asprintf(&value, "%s=%" PRId64, key, fields[i].entry.i64);
  1493. break;
  1494. case NDFT_DBL:
  1495. asprintf(&value, "%s=%f", key, fields[i].entry.dbl);
  1496. break;
  1497. case NDFT_UUID: {
  1498. char u[UUID_COMPACT_STR_LEN];
  1499. uuid_unparse_lower_compact(*fields[i].entry.uuid, u);
  1500. asprintf(&value, "%s=%s", key, u);
  1501. }
  1502. break;
  1503. case NDFT_CALLBACK: {
  1504. if(!tmp)
  1505. tmp = buffer_create(1024, NULL);
  1506. else
  1507. buffer_flush(tmp);
  1508. if(fields[i].entry.cb.formatter(tmp, fields[i].entry.cb.formatter_data))
  1509. asprintf(&value, "%s=%s", key, buffer_tostring(tmp));
  1510. }
  1511. break;
  1512. default:
  1513. asprintf(&value, "%s=%s", key, "UNHANDLED");
  1514. break;
  1515. }
  1516. if (value) {
  1517. iov[iov_count].iov_base = value;
  1518. iov[iov_count].iov_len = strlen(value);
  1519. iov_count++;
  1520. }
  1521. }
  1522. int r = sd_journal_sendv(iov, iov_count);
  1523. // Clean up allocated memory
  1524. for (int i = 0; i < iov_count; i++) {
  1525. if (iov[i].iov_base != NULL) {
  1526. free(iov[i].iov_base);
  1527. }
  1528. }
  1529. return r == 0;
  1530. #else
  1531. return false;
  1532. #endif
  1533. }
  1534. static bool nd_logger_journal_direct(struct log_field *fields, size_t fields_max) {
  1535. if(!nd_log.journal_direct.initialized)
  1536. return false;
  1537. // --- FIELD_PARSER_VERSIONS ---
  1538. //
  1539. // IMPORTANT:
  1540. // THERE ARE 6 VERSIONS OF THIS CODE
  1541. //
  1542. // 1. journal (direct socket API),
  1543. // 2. journal (libsystemd API),
  1544. // 3. logfmt,
  1545. // 4. json,
  1546. // 5. convert to uint64
  1547. // 6. convert to int64
  1548. //
  1549. // UPDATE ALL OF THEM FOR NEW FEATURES OR FIXES
  1550. CLEAN_BUFFER *wb = buffer_create(4096, NULL);
  1551. CLEAN_BUFFER *tmp = NULL;
  1552. for (size_t i = 0; i < fields_max; i++) {
  1553. if (!fields[i].entry.set || !fields[i].journal)
  1554. continue;
  1555. const char *key = fields[i].journal;
  1556. const char *s = NULL;
  1557. switch(fields[i].entry.type) {
  1558. case NDFT_TXT:
  1559. s = fields[i].entry.txt;
  1560. break;
  1561. case NDFT_STR:
  1562. s = string2str(fields[i].entry.str);
  1563. break;
  1564. case NDFT_BFR:
  1565. s = buffer_tostring(fields[i].entry.bfr);
  1566. break;
  1567. case NDFT_U64:
  1568. buffer_strcat(wb, key);
  1569. buffer_putc(wb, '=');
  1570. buffer_print_uint64(wb, fields[i].entry.u64);
  1571. buffer_putc(wb, '\n');
  1572. break;
  1573. case NDFT_I64:
  1574. buffer_strcat(wb, key);
  1575. buffer_putc(wb, '=');
  1576. buffer_print_int64(wb, fields[i].entry.i64);
  1577. buffer_putc(wb, '\n');
  1578. break;
  1579. case NDFT_DBL:
  1580. buffer_strcat(wb, key);
  1581. buffer_putc(wb, '=');
  1582. buffer_print_netdata_double(wb, fields[i].entry.dbl);
  1583. buffer_putc(wb, '\n');
  1584. break;
  1585. case NDFT_UUID:{
  1586. char u[UUID_COMPACT_STR_LEN];
  1587. uuid_unparse_lower_compact(*fields[i].entry.uuid, u);
  1588. buffer_strcat(wb, key);
  1589. buffer_putc(wb, '=');
  1590. buffer_fast_strcat(wb, u, sizeof(u) - 1);
  1591. buffer_putc(wb, '\n');
  1592. }
  1593. break;
  1594. case NDFT_CALLBACK: {
  1595. if(!tmp)
  1596. tmp = buffer_create(1024, NULL);
  1597. else
  1598. buffer_flush(tmp);
  1599. if(fields[i].entry.cb.formatter(tmp, fields[i].entry.cb.formatter_data))
  1600. s = buffer_tostring(tmp);
  1601. else
  1602. s = NULL;
  1603. }
  1604. break;
  1605. default:
  1606. s = "UNHANDLED";
  1607. break;
  1608. }
  1609. if(s && *s) {
  1610. buffer_strcat(wb, key);
  1611. if(!strchr(s, '\n')) {
  1612. buffer_putc(wb, '=');
  1613. buffer_strcat(wb, s);
  1614. buffer_putc(wb, '\n');
  1615. }
  1616. else {
  1617. buffer_putc(wb, '\n');
  1618. size_t size = strlen(s);
  1619. uint64_t le_size = htole64(size);
  1620. buffer_memcat(wb, &le_size, sizeof(le_size));
  1621. buffer_memcat(wb, s, size);
  1622. buffer_putc(wb, '\n');
  1623. }
  1624. }
  1625. }
  1626. return journal_direct_send(nd_log.journal_direct.fd, buffer_tostring(wb), buffer_strlen(wb));
  1627. }
  1628. // ----------------------------------------------------------------------------
  1629. // syslog logger - uses logfmt
  1630. static bool nd_logger_syslog(int priority, ND_LOG_FORMAT format, struct log_field *fields, size_t fields_max) {
  1631. CLEAN_BUFFER *wb = buffer_create(1024, NULL);
  1632. nd_logger_logfmt(wb, fields, fields_max);
  1633. syslog(priority, "%s", buffer_tostring(wb));
  1634. return true;
  1635. }
  1636. // ----------------------------------------------------------------------------
  1637. // file logger - uses logfmt
  1638. static bool nd_logger_file(FILE *fp, ND_LOG_FORMAT format, struct log_field *fields, size_t fields_max) {
  1639. BUFFER *wb = buffer_create(1024, NULL);
  1640. if(format == NDLF_JSON)
  1641. nd_logger_json(wb, fields, fields_max);
  1642. else
  1643. nd_logger_logfmt(wb, fields, fields_max);
  1644. int r = fprintf(fp, "%s\n", buffer_tostring(wb));
  1645. fflush(fp);
  1646. buffer_free(wb);
  1647. return r > 0;
  1648. }
  1649. // ----------------------------------------------------------------------------
  1650. // logger router
  1651. static ND_LOG_METHOD nd_logger_select_output(ND_LOG_SOURCES source, FILE **fpp, SPINLOCK **spinlock) {
  1652. *spinlock = NULL;
  1653. ND_LOG_METHOD output = nd_log.sources[source].method;
  1654. switch(output) {
  1655. case NDLM_JOURNAL:
  1656. if(unlikely(!nd_log.journal_direct.initialized && !nd_log.journal.initialized)) {
  1657. output = NDLM_FILE;
  1658. *fpp = stderr;
  1659. *spinlock = &nd_log.std_error.spinlock;
  1660. }
  1661. else {
  1662. *fpp = NULL;
  1663. *spinlock = NULL;
  1664. }
  1665. break;
  1666. case NDLM_SYSLOG:
  1667. if(unlikely(!nd_log.syslog.initialized)) {
  1668. output = NDLM_FILE;
  1669. *spinlock = &nd_log.std_error.spinlock;
  1670. *fpp = stderr;
  1671. }
  1672. else {
  1673. *spinlock = NULL;
  1674. *fpp = NULL;
  1675. }
  1676. break;
  1677. case NDLM_FILE:
  1678. if(!nd_log.sources[source].fp) {
  1679. *fpp = stderr;
  1680. *spinlock = &nd_log.std_error.spinlock;
  1681. }
  1682. else {
  1683. *fpp = nd_log.sources[source].fp;
  1684. *spinlock = &nd_log.sources[source].spinlock;
  1685. }
  1686. break;
  1687. case NDLM_STDOUT:
  1688. output = NDLM_FILE;
  1689. *fpp = stdout;
  1690. *spinlock = &nd_log.std_output.spinlock;
  1691. break;
  1692. default:
  1693. case NDLM_DEFAULT:
  1694. case NDLM_STDERR:
  1695. output = NDLM_FILE;
  1696. *fpp = stderr;
  1697. *spinlock = &nd_log.std_error.spinlock;
  1698. break;
  1699. case NDLM_DISABLED:
  1700. case NDLM_DEVNULL:
  1701. output = NDLM_DISABLED;
  1702. *fpp = NULL;
  1703. *spinlock = NULL;
  1704. break;
  1705. }
  1706. return output;
  1707. }
  1708. // ----------------------------------------------------------------------------
  1709. // high level logger
  1710. static void nd_logger_log_fields(SPINLOCK *spinlock, FILE *fp, bool limit, ND_LOG_FIELD_PRIORITY priority,
  1711. ND_LOG_METHOD output, struct nd_log_source *source,
  1712. struct log_field *fields, size_t fields_max) {
  1713. if(spinlock)
  1714. spinlock_lock(spinlock);
  1715. // check the limits
  1716. if(limit && nd_log_limit_reached(source))
  1717. goto cleanup;
  1718. if(output == NDLM_JOURNAL) {
  1719. if(!nd_logger_journal_direct(fields, fields_max) && !nd_logger_journal_libsystemd(fields, fields_max)) {
  1720. // we can't log to journal, let's log to stderr
  1721. if(spinlock)
  1722. spinlock_unlock(spinlock);
  1723. output = NDLM_FILE;
  1724. spinlock = &nd_log.std_error.spinlock;
  1725. fp = stderr;
  1726. if(spinlock)
  1727. spinlock_lock(spinlock);
  1728. }
  1729. }
  1730. if(output == NDLM_SYSLOG)
  1731. nd_logger_syslog(priority, source->format, fields, fields_max);
  1732. if(output == NDLM_FILE)
  1733. nd_logger_file(fp, source->format, fields, fields_max);
  1734. cleanup:
  1735. if(spinlock)
  1736. spinlock_unlock(spinlock);
  1737. }
  1738. static void nd_logger_unset_all_thread_fields(void) {
  1739. size_t fields_max = THREAD_FIELDS_MAX;
  1740. for(size_t i = 0; i < fields_max ; i++)
  1741. thread_log_fields[i].entry.set = false;
  1742. }
  1743. static void nd_logger_merge_log_stack_to_thread_fields(void) {
  1744. for(size_t c = 0; c < thread_log_stack_next ;c++) {
  1745. struct log_stack_entry *lgs = thread_log_stack_base[c];
  1746. for(size_t i = 0; lgs[i].id != NDF_STOP ; i++) {
  1747. if(lgs[i].id >= _NDF_MAX || !lgs[i].set)
  1748. continue;
  1749. struct log_stack_entry *e = &lgs[i];
  1750. ND_LOG_STACK_FIELD_TYPE type = lgs[i].type;
  1751. // do not add empty / unset fields
  1752. if((type == NDFT_TXT && (!e->txt || !*e->txt)) ||
  1753. (type == NDFT_BFR && (!e->bfr || !buffer_strlen(e->bfr))) ||
  1754. (type == NDFT_STR && !e->str) ||
  1755. (type == NDFT_UUID && !e->uuid) ||
  1756. (type == NDFT_CALLBACK && !e->cb.formatter) ||
  1757. type == NDFT_UNSET)
  1758. continue;
  1759. thread_log_fields[lgs[i].id].entry = *e;
  1760. }
  1761. }
  1762. }
  1763. static void nd_logger(const char *file, const char *function, const unsigned long line,
  1764. ND_LOG_SOURCES source, ND_LOG_FIELD_PRIORITY priority, bool limit, int saved_errno,
  1765. const char *fmt, va_list ap) {
  1766. SPINLOCK *spinlock;
  1767. FILE *fp;
  1768. ND_LOG_METHOD output = nd_logger_select_output(source, &fp, &spinlock);
  1769. if(output != NDLM_FILE && output != NDLM_JOURNAL && output != NDLM_SYSLOG)
  1770. return;
  1771. // mark all fields as unset
  1772. nd_logger_unset_all_thread_fields();
  1773. // flatten the log stack into the fields
  1774. nd_logger_merge_log_stack_to_thread_fields();
  1775. // set the common fields that are automatically set by the logging subsystem
  1776. if(likely(!thread_log_fields[NDF_INVOCATION_ID].entry.set))
  1777. thread_log_fields[NDF_INVOCATION_ID].entry = ND_LOG_FIELD_UUID(NDF_INVOCATION_ID, &nd_log.invocation_id);
  1778. if(likely(!thread_log_fields[NDF_LOG_SOURCE].entry.set))
  1779. thread_log_fields[NDF_LOG_SOURCE].entry = ND_LOG_FIELD_TXT(NDF_LOG_SOURCE, nd_log_id2source(source));
  1780. else {
  1781. ND_LOG_SOURCES src = source;
  1782. if(thread_log_fields[NDF_LOG_SOURCE].entry.type == NDFT_TXT)
  1783. src = nd_log_source2id(thread_log_fields[NDF_LOG_SOURCE].entry.txt, source);
  1784. else if(thread_log_fields[NDF_LOG_SOURCE].entry.type == NDFT_U64)
  1785. src = thread_log_fields[NDF_LOG_SOURCE].entry.u64;
  1786. if(src != source && src >= 0 && src < _NDLS_MAX) {
  1787. source = src;
  1788. output = nd_logger_select_output(source, &fp, &spinlock);
  1789. if(output != NDLM_FILE && output != NDLM_JOURNAL && output != NDLM_SYSLOG)
  1790. return;
  1791. }
  1792. }
  1793. if(likely(!thread_log_fields[NDF_SYSLOG_IDENTIFIER].entry.set))
  1794. thread_log_fields[NDF_SYSLOG_IDENTIFIER].entry = ND_LOG_FIELD_TXT(NDF_SYSLOG_IDENTIFIER, program_name);
  1795. if(likely(!thread_log_fields[NDF_LINE].entry.set)) {
  1796. thread_log_fields[NDF_LINE].entry = ND_LOG_FIELD_U64(NDF_LINE, line);
  1797. thread_log_fields[NDF_FILE].entry = ND_LOG_FIELD_TXT(NDF_FILE, file);
  1798. thread_log_fields[NDF_FUNC].entry = ND_LOG_FIELD_TXT(NDF_FUNC, function);
  1799. }
  1800. if(likely(!thread_log_fields[NDF_PRIORITY].entry.set)) {
  1801. thread_log_fields[NDF_PRIORITY].entry = ND_LOG_FIELD_U64(NDF_PRIORITY, priority);
  1802. }
  1803. if(likely(!thread_log_fields[NDF_TID].entry.set))
  1804. thread_log_fields[NDF_TID].entry = ND_LOG_FIELD_U64(NDF_TID, gettid());
  1805. char os_threadname[NETDATA_THREAD_NAME_MAX + 1];
  1806. if(likely(!thread_log_fields[NDF_THREAD_TAG].entry.set)) {
  1807. const char *thread_tag = netdata_thread_tag();
  1808. if(!netdata_thread_tag_exists()) {
  1809. if (!netdata_thread_tag_exists()) {
  1810. os_thread_get_current_name_np(os_threadname);
  1811. if ('\0' != os_threadname[0])
  1812. /* If it is not an empty string replace "MAIN" thread_tag */
  1813. thread_tag = os_threadname;
  1814. }
  1815. }
  1816. thread_log_fields[NDF_THREAD_TAG].entry = ND_LOG_FIELD_TXT(NDF_THREAD_TAG, thread_tag);
  1817. // TODO: fix the ND_MODULE in logging by setting proper module name in threads
  1818. // if(!thread_log_fields[NDF_MODULE].entry.set)
  1819. // thread_log_fields[NDF_MODULE].entry = ND_LOG_FIELD_CB(NDF_MODULE, thread_tag_to_module, (void *)thread_tag);
  1820. }
  1821. if(likely(!thread_log_fields[NDF_TIMESTAMP_REALTIME_USEC].entry.set))
  1822. thread_log_fields[NDF_TIMESTAMP_REALTIME_USEC].entry = ND_LOG_FIELD_U64(NDF_TIMESTAMP_REALTIME_USEC, now_realtime_usec());
  1823. if(saved_errno != 0 && !thread_log_fields[NDF_ERRNO].entry.set)
  1824. thread_log_fields[NDF_ERRNO].entry = ND_LOG_FIELD_I64(NDF_ERRNO, saved_errno);
  1825. CLEAN_BUFFER *wb = NULL;
  1826. if(fmt && !thread_log_fields[NDF_MESSAGE].entry.set) {
  1827. wb = buffer_create(1024, NULL);
  1828. buffer_vsprintf(wb, fmt, ap);
  1829. thread_log_fields[NDF_MESSAGE].entry = ND_LOG_FIELD_TXT(NDF_MESSAGE, buffer_tostring(wb));
  1830. }
  1831. nd_logger_log_fields(spinlock, fp, limit, priority, output, &nd_log.sources[source],
  1832. thread_log_fields, THREAD_FIELDS_MAX);
  1833. if(nd_log.sources[source].pending_msg) {
  1834. // log a pending message
  1835. nd_logger_unset_all_thread_fields();
  1836. thread_log_fields[NDF_TIMESTAMP_REALTIME_USEC].entry = (struct log_stack_entry){
  1837. .set = true,
  1838. .type = NDFT_U64,
  1839. .u64 = now_realtime_usec(),
  1840. };
  1841. thread_log_fields[NDF_LOG_SOURCE].entry = (struct log_stack_entry){
  1842. .set = true,
  1843. .type = NDFT_TXT,
  1844. .txt = nd_log_id2source(source),
  1845. };
  1846. thread_log_fields[NDF_SYSLOG_IDENTIFIER].entry = (struct log_stack_entry){
  1847. .set = true,
  1848. .type = NDFT_TXT,
  1849. .txt = program_name,
  1850. };
  1851. thread_log_fields[NDF_MESSAGE].entry = (struct log_stack_entry){
  1852. .set = true,
  1853. .type = NDFT_TXT,
  1854. .txt = nd_log.sources[source].pending_msg,
  1855. };
  1856. nd_logger_log_fields(spinlock, fp, false, priority, output,
  1857. &nd_log.sources[source],
  1858. thread_log_fields, THREAD_FIELDS_MAX);
  1859. freez((void *)nd_log.sources[source].pending_msg);
  1860. nd_log.sources[source].pending_msg = NULL;
  1861. }
  1862. errno = 0;
  1863. }
  1864. static ND_LOG_SOURCES nd_log_validate_source(ND_LOG_SOURCES source) {
  1865. if(source >= _NDLS_MAX)
  1866. source = NDLS_DAEMON;
  1867. if(overwrite_thread_source)
  1868. source = overwrite_thread_source;
  1869. if(nd_log.overwrite_process_source)
  1870. source = nd_log.overwrite_process_source;
  1871. return source;
  1872. }
  1873. // ----------------------------------------------------------------------------
  1874. // public API for loggers
  1875. void netdata_logger(ND_LOG_SOURCES source, ND_LOG_FIELD_PRIORITY priority, const char *file, const char *function, unsigned long line, const char *fmt, ... ) {
  1876. int saved_errno = errno;
  1877. source = nd_log_validate_source(source);
  1878. if (source != NDLS_DEBUG && priority > nd_log.sources[source].min_priority)
  1879. return;
  1880. va_list args;
  1881. va_start(args, fmt);
  1882. nd_logger(file, function, line, source, priority,
  1883. source == NDLS_DAEMON || source == NDLS_COLLECTORS,
  1884. saved_errno, fmt, args);
  1885. va_end(args);
  1886. }
  1887. void netdata_logger_with_limit(ERROR_LIMIT *erl, ND_LOG_SOURCES source, ND_LOG_FIELD_PRIORITY priority, const char *file __maybe_unused, const char *function __maybe_unused, const unsigned long line __maybe_unused, const char *fmt, ... ) {
  1888. int saved_errno = errno;
  1889. source = nd_log_validate_source(source);
  1890. if (source != NDLS_DEBUG && priority > nd_log.sources[source].min_priority)
  1891. return;
  1892. if(erl->sleep_ut)
  1893. sleep_usec(erl->sleep_ut);
  1894. spinlock_lock(&erl->spinlock);
  1895. erl->count++;
  1896. time_t now = now_boottime_sec();
  1897. if(now - erl->last_logged < erl->log_every) {
  1898. spinlock_unlock(&erl->spinlock);
  1899. return;
  1900. }
  1901. spinlock_unlock(&erl->spinlock);
  1902. va_list args;
  1903. va_start(args, fmt);
  1904. nd_logger(file, function, line, source, priority,
  1905. source == NDLS_DAEMON || source == NDLS_COLLECTORS,
  1906. saved_errno, fmt, args);
  1907. va_end(args);
  1908. erl->last_logged = now;
  1909. erl->count = 0;
  1910. }
  1911. void netdata_logger_fatal( const char *file, const char *function, const unsigned long line, const char *fmt, ... ) {
  1912. int saved_errno = errno;
  1913. ND_LOG_SOURCES source = NDLS_DAEMON;
  1914. source = nd_log_validate_source(source);
  1915. va_list args;
  1916. va_start(args, fmt);
  1917. nd_logger(file, function, line, source, NDLP_ALERT, true, saved_errno, fmt, args);
  1918. va_end(args);
  1919. char date[LOG_DATE_LENGTH];
  1920. log_date(date, LOG_DATE_LENGTH, now_realtime_sec());
  1921. char action_data[70+1];
  1922. snprintfz(action_data, 70, "%04lu@%-10.10s:%-15.15s/%d", line, file, function, saved_errno);
  1923. char action_result[60+1];
  1924. char os_threadname[NETDATA_THREAD_NAME_MAX + 1];
  1925. const char *thread_tag = netdata_thread_tag();
  1926. if(!netdata_thread_tag_exists()) {
  1927. if (!netdata_thread_tag_exists()) {
  1928. os_thread_get_current_name_np(os_threadname);
  1929. if ('\0' != os_threadname[0])
  1930. /* If it is not an empty string replace "MAIN" thread_tag */
  1931. thread_tag = os_threadname;
  1932. }
  1933. }
  1934. if(!thread_tag)
  1935. thread_tag = "UNKNOWN";
  1936. const char *tag_to_send = thread_tag;
  1937. // anonymize thread names
  1938. if(strncmp(thread_tag, THREAD_TAG_STREAM_RECEIVER, strlen(THREAD_TAG_STREAM_RECEIVER)) == 0)
  1939. tag_to_send = THREAD_TAG_STREAM_RECEIVER;
  1940. if(strncmp(thread_tag, THREAD_TAG_STREAM_SENDER, strlen(THREAD_TAG_STREAM_SENDER)) == 0)
  1941. tag_to_send = THREAD_TAG_STREAM_SENDER;
  1942. snprintfz(action_result, 60, "%s:%s", program_name, tag_to_send);
  1943. send_statistics("FATAL", action_result, action_data);
  1944. #ifdef HAVE_BACKTRACE
  1945. int fd = nd_log.sources[NDLS_DAEMON].fd;
  1946. if(fd == -1)
  1947. fd = STDERR_FILENO;
  1948. int nptrs;
  1949. void *buffer[10000];
  1950. nptrs = backtrace(buffer, sizeof(buffer));
  1951. if(nptrs)
  1952. backtrace_symbols_fd(buffer, nptrs, fd);
  1953. #endif
  1954. #ifdef NETDATA_INTERNAL_CHECKS
  1955. abort();
  1956. #endif
  1957. netdata_cleanup_and_exit(1);
  1958. }
  1959. // ----------------------------------------------------------------------------
  1960. // log limits
  1961. void nd_log_limits_reset(void) {
  1962. usec_t now_ut = now_monotonic_usec();
  1963. spinlock_lock(&nd_log.std_output.spinlock);
  1964. spinlock_lock(&nd_log.std_error.spinlock);
  1965. for(size_t i = 0; i < _NDLS_MAX ;i++) {
  1966. spinlock_lock(&nd_log.sources[i].spinlock);
  1967. nd_log.sources[i].limits.prevented = 0;
  1968. nd_log.sources[i].limits.counter = 0;
  1969. nd_log.sources[i].limits.started_monotonic_ut = now_ut;
  1970. nd_log.sources[i].limits.logs_per_period = nd_log.sources[i].limits.logs_per_period_backup;
  1971. spinlock_unlock(&nd_log.sources[i].spinlock);
  1972. }
  1973. spinlock_unlock(&nd_log.std_output.spinlock);
  1974. spinlock_unlock(&nd_log.std_error.spinlock);
  1975. }
  1976. void nd_log_limits_unlimited(void) {
  1977. nd_log_limits_reset();
  1978. for(size_t i = 0; i < _NDLS_MAX ;i++) {
  1979. nd_log.sources[i].limits.logs_per_period = 0;
  1980. }
  1981. }
  1982. static bool nd_log_limit_reached(struct nd_log_source *source) {
  1983. if(source->limits.throttle_period == 0 || source->limits.logs_per_period == 0)
  1984. return false;
  1985. usec_t now_ut = now_monotonic_usec();
  1986. if(!source->limits.started_monotonic_ut)
  1987. source->limits.started_monotonic_ut = now_ut;
  1988. source->limits.counter++;
  1989. if(now_ut - source->limits.started_monotonic_ut > (usec_t)source->limits.throttle_period) {
  1990. if(source->limits.prevented) {
  1991. BUFFER *wb = buffer_create(1024, NULL);
  1992. buffer_sprintf(wb,
  1993. "LOG FLOOD PROTECTION: resuming logging "
  1994. "(prevented %"PRIu32" logs in the last %"PRIu32" seconds).",
  1995. source->limits.prevented,
  1996. source->limits.throttle_period);
  1997. if(source->pending_msg)
  1998. freez((void *)source->pending_msg);
  1999. source->pending_msg = strdupz(buffer_tostring(wb));
  2000. buffer_free(wb);
  2001. }
  2002. // restart the period accounting
  2003. source->limits.started_monotonic_ut = now_ut;
  2004. source->limits.counter = 1;
  2005. source->limits.prevented = 0;
  2006. // log this error
  2007. return false;
  2008. }
  2009. if(source->limits.counter > source->limits.logs_per_period) {
  2010. if(!source->limits.prevented) {
  2011. BUFFER *wb = buffer_create(1024, NULL);
  2012. buffer_sprintf(wb,
  2013. "LOG FLOOD PROTECTION: too many logs (%"PRIu32" logs in %"PRId64" seconds, threshold is set to %"PRIu32" logs "
  2014. "in %"PRIu32" seconds). Preventing more logs from process '%s' for %"PRId64" seconds.",
  2015. source->limits.counter,
  2016. (int64_t)((now_ut - source->limits.started_monotonic_ut) / USEC_PER_SEC),
  2017. source->limits.logs_per_period,
  2018. source->limits.throttle_period,
  2019. program_name,
  2020. (int64_t)((source->limits.started_monotonic_ut + (source->limits.throttle_period * USEC_PER_SEC) - now_ut)) / USEC_PER_SEC);
  2021. if(source->pending_msg)
  2022. freez((void *)source->pending_msg);
  2023. source->pending_msg = strdupz(buffer_tostring(wb));
  2024. buffer_free(wb);
  2025. }
  2026. source->limits.prevented++;
  2027. // prevent logging this error
  2028. #ifdef NETDATA_INTERNAL_CHECKS
  2029. return false;
  2030. #else
  2031. return true;
  2032. #endif
  2033. }
  2034. return false;
  2035. }