rrdpush.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "rrdpush.h"
  3. #include "parser/parser.h"
  4. /*
  5. * rrdpush
  6. *
  7. * 3 threads are involved for all stream operations
  8. *
  9. * 1. a random data collection thread, calling rrdset_done_push()
  10. * this is called for each chart.
  11. *
  12. * the output of this work is kept in a BUFFER in RRDHOST
  13. * the sender thread is signalled via a pipe (also in RRDHOST)
  14. *
  15. * 2. a sender thread running at the sending netdata
  16. * this is spawned automatically on the first chart to be pushed
  17. *
  18. * It tries to push the metrics to the remote netdata, as fast
  19. * as possible (i.e. immediately after they are collected).
  20. *
  21. * 3. a receiver thread, running at the receiving netdata
  22. * this is spawned automatically when the sender connects to
  23. * the receiver.
  24. *
  25. */
  26. struct config stream_config = {
  27. .first_section = NULL,
  28. .last_section = NULL,
  29. .mutex = NETDATA_MUTEX_INITIALIZER,
  30. .index = {
  31. .avl_tree = {
  32. .root = NULL,
  33. .compar = appconfig_section_compare
  34. },
  35. .rwlock = AVL_LOCK_INITIALIZER
  36. }
  37. };
  38. unsigned int default_rrdpush_enabled = 0;
  39. #ifdef ENABLE_COMPRESSION
  40. unsigned int default_compression_enabled = 1;
  41. #endif
  42. char *default_rrdpush_destination = NULL;
  43. char *default_rrdpush_api_key = NULL;
  44. char *default_rrdpush_send_charts_matching = NULL;
  45. #ifdef ENABLE_HTTPS
  46. int netdata_use_ssl_on_stream = NETDATA_SSL_OPTIONAL;
  47. char *netdata_ssl_ca_path = NULL;
  48. char *netdata_ssl_ca_file = NULL;
  49. #endif
  50. static void load_stream_conf() {
  51. errno = 0;
  52. char *filename = strdupz_path_subpath(netdata_configured_user_config_dir, "stream.conf");
  53. if(!appconfig_load(&stream_config, filename, 0, NULL)) {
  54. info("CONFIG: cannot load user config '%s'. Will try stock config.", filename);
  55. freez(filename);
  56. filename = strdupz_path_subpath(netdata_configured_stock_config_dir, "stream.conf");
  57. if(!appconfig_load(&stream_config, filename, 0, NULL))
  58. info("CONFIG: cannot load stock config '%s'. Running with internal defaults.", filename);
  59. }
  60. freez(filename);
  61. }
  62. int rrdpush_init() {
  63. // --------------------------------------------------------------------
  64. // load stream.conf
  65. load_stream_conf();
  66. default_rrdpush_enabled = (unsigned int)appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM, "enabled", default_rrdpush_enabled);
  67. default_rrdpush_destination = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "destination", "");
  68. default_rrdpush_api_key = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "api key", "");
  69. default_rrdpush_send_charts_matching = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "send charts matching", "*");
  70. rrdhost_free_orphan_time = config_get_number(CONFIG_SECTION_DB, "cleanup orphan hosts after secs", rrdhost_free_orphan_time);
  71. #ifdef ENABLE_COMPRESSION
  72. default_compression_enabled = (unsigned int)appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM,
  73. "enable compression", default_compression_enabled);
  74. #endif
  75. if(default_rrdpush_enabled && (!default_rrdpush_destination || !*default_rrdpush_destination || !default_rrdpush_api_key || !*default_rrdpush_api_key)) {
  76. error("STREAM [send]: cannot enable sending thread - information is missing.");
  77. default_rrdpush_enabled = 0;
  78. }
  79. #ifdef ENABLE_HTTPS
  80. if (netdata_use_ssl_on_stream == NETDATA_SSL_OPTIONAL) {
  81. if (default_rrdpush_destination){
  82. char *test = strstr(default_rrdpush_destination,":SSL");
  83. if(test){
  84. *test = 0X00;
  85. netdata_use_ssl_on_stream = NETDATA_SSL_FORCE;
  86. }
  87. }
  88. }
  89. bool invalid_certificate = appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM, "ssl skip certificate verification", CONFIG_BOOLEAN_NO);
  90. if(invalid_certificate == CONFIG_BOOLEAN_YES){
  91. if(netdata_validate_server == NETDATA_SSL_VALID_CERTIFICATE){
  92. info("Netdata is configured to accept invalid SSL certificate.");
  93. netdata_validate_server = NETDATA_SSL_INVALID_CERTIFICATE;
  94. }
  95. }
  96. netdata_ssl_ca_path = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "CApath", "/etc/ssl/certs/");
  97. netdata_ssl_ca_file = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "CAfile", "/etc/ssl/certs/certs.pem");
  98. #endif
  99. return default_rrdpush_enabled;
  100. }
  101. // data collection happens from multiple threads
  102. // each of these threads calls rrdset_done()
  103. // which in turn calls rrdset_done_push()
  104. // which uses this pipe to notify the streaming thread
  105. // that there are more data ready to be sent
  106. #define PIPE_READ 0
  107. #define PIPE_WRITE 1
  108. // to have the remote netdata re-sync the charts
  109. // to its current clock, we send for this many
  110. // iterations a BEGIN line without microseconds
  111. // this is for the first iterations of each chart
  112. unsigned int remote_clock_resync_iterations = 60;
  113. static inline int should_send_chart_matching(RRDSET *st) {
  114. // Do not stream anomaly rates charts.
  115. if (unlikely(st->state->is_ar_chart))
  116. return false;
  117. if (rrdset_flag_check(st, RRDSET_FLAG_ANOMALY_DETECTION))
  118. return ml_streaming_enabled();
  119. if(!rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_SEND|RRDSET_FLAG_UPSTREAM_IGNORE)) {
  120. RRDHOST *host = st->rrdhost;
  121. if(simple_pattern_matches(host->rrdpush_send_charts_matching, st->id) ||
  122. simple_pattern_matches(host->rrdpush_send_charts_matching, st->name)) {
  123. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  124. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_SEND);
  125. }
  126. else {
  127. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_SEND);
  128. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  129. }
  130. }
  131. return(rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_SEND));
  132. }
  133. int configured_as_parent() {
  134. struct section *section = NULL;
  135. int is_parent = 0;
  136. appconfig_wrlock(&stream_config);
  137. for (section = stream_config.first_section; section; section = section->next) {
  138. uuid_t uuid;
  139. if (uuid_parse(section->name, uuid) != -1 &&
  140. appconfig_get_boolean_by_section(section, "enabled", 0)) {
  141. is_parent = 1;
  142. break;
  143. }
  144. }
  145. appconfig_unlock(&stream_config);
  146. return is_parent;
  147. }
  148. // checks if the current chart definition has been sent
  149. static inline int need_to_send_chart_definition(RRDSET *st) {
  150. rrdset_check_rdlock(st);
  151. if(unlikely(!(rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_EXPOSED))))
  152. return 1;
  153. RRDDIM *rd;
  154. rrddim_foreach_read(rd, st) {
  155. if(unlikely(!rd->exposed)) {
  156. #ifdef NETDATA_INTERNAL_CHECKS
  157. info("host '%s', chart '%s', dimension '%s' flag 'exposed' triggered chart refresh to upstream", st->rrdhost->hostname, st->id, rd->id);
  158. #endif
  159. return 1;
  160. }
  161. }
  162. return 0;
  163. }
  164. // chart labels
  165. static int send_clabels_callback(const char *name, const char *value, RRDLABEL_SRC ls, void *data) {
  166. BUFFER *wb = (BUFFER *)data;
  167. buffer_sprintf(wb, "CLABEL \"%s\" \"%s\" %d\n", name, value, ls);
  168. return 1;
  169. }
  170. void rrdpush_send_clabels(RRDHOST *host, RRDSET *st) {
  171. if (st->state && st->state->chart_labels) {
  172. if(rrdlabels_walkthrough_read(st->state->chart_labels, send_clabels_callback, host->sender->build) > 0)
  173. buffer_sprintf(host->sender->build,"CLABEL_COMMIT\n");
  174. }
  175. }
  176. // Send the current chart definition.
  177. // Assumes that collector thread has already called sender_start for mutex / buffer state.
  178. static inline void rrdpush_send_chart_definition_nolock(RRDSET *st) {
  179. RRDHOST *host = st->rrdhost;
  180. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  181. // properly set the name for the remote end to parse it
  182. char *name = "";
  183. if(likely(st->name)) {
  184. if(unlikely(strcmp(st->id, st->name))) {
  185. // they differ
  186. name = strchr(st->name, '.');
  187. if(name)
  188. name++;
  189. else
  190. name = "";
  191. }
  192. }
  193. // send the chart
  194. buffer_sprintf(
  195. host->sender->build
  196. , "CHART \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" %ld %d \"%s %s %s %s\" \"%s\" \"%s\"\n"
  197. , st->id
  198. , name
  199. , st->title
  200. , st->units
  201. , st->family
  202. , st->context
  203. , rrdset_type_name(st->chart_type)
  204. , st->priority
  205. , st->update_every
  206. , rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE)?"obsolete":""
  207. , rrdset_flag_check(st, RRDSET_FLAG_DETAIL)?"detail":""
  208. , rrdset_flag_check(st, RRDSET_FLAG_STORE_FIRST)?"store_first":""
  209. , rrdset_flag_check(st, RRDSET_FLAG_HIDDEN)?"hidden":""
  210. , (st->plugin_name)?st->plugin_name:""
  211. , (st->module_name)?st->module_name:""
  212. );
  213. // send the chart labels
  214. if (host->sender->version >= STREAM_VERSION_CLABELS)
  215. rrdpush_send_clabels(host, st);
  216. // send the dimensions
  217. RRDDIM *rd;
  218. rrddim_foreach_read(rd, st) {
  219. buffer_sprintf(
  220. host->sender->build
  221. , "DIMENSION \"%s\" \"%s\" \"%s\" " COLLECTED_NUMBER_FORMAT " " COLLECTED_NUMBER_FORMAT " \"%s %s %s\"\n"
  222. , rd->id
  223. , rd->name
  224. , rrd_algorithm_name(rd->algorithm)
  225. , rd->multiplier
  226. , rd->divisor
  227. , rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE)?"obsolete":""
  228. , rrddim_flag_check(rd, RRDDIM_FLAG_HIDDEN)?"hidden":""
  229. , rrddim_flag_check(rd, RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)?"noreset":""
  230. );
  231. rd->exposed = 1;
  232. }
  233. // send the chart local custom variables
  234. RRDSETVAR *rs;
  235. for(rs = st->variables; rs ;rs = rs->next) {
  236. if(unlikely(rs->type == RRDVAR_TYPE_CALCULATED && rs->options & RRDVAR_OPTION_CUSTOM_CHART_VAR)) {
  237. NETDATA_DOUBLE *value = (NETDATA_DOUBLE *) rs->value;
  238. buffer_sprintf(
  239. host->sender->build
  240. , "VARIABLE CHART %s = " NETDATA_DOUBLE_FORMAT "\n"
  241. , rs->variable
  242. , *value
  243. );
  244. }
  245. }
  246. st->upstream_resync_time = st->last_collected_time.tv_sec + (remote_clock_resync_iterations * st->update_every);
  247. }
  248. // sends the current chart dimensions
  249. static inline void rrdpush_send_chart_metrics_nolock(RRDSET *st, struct sender_state *s) {
  250. RRDHOST *host = st->rrdhost;
  251. buffer_sprintf(host->sender->build, "BEGIN \"%s\" %llu", st->id, (st->last_collected_time.tv_sec > st->upstream_resync_time)?st->usec_since_last_update:0);
  252. if (s->version >= VERSION_GAP_FILLING)
  253. buffer_sprintf(host->sender->build, " %"PRId64"\n", (int64_t)st->last_collected_time.tv_sec);
  254. else
  255. buffer_strcat(host->sender->build, "\n");
  256. RRDDIM *rd;
  257. rrddim_foreach_read(rd, st) {
  258. if(rd->updated && rd->exposed)
  259. buffer_sprintf(host->sender->build
  260. , "SET \"%s\" = " COLLECTED_NUMBER_FORMAT "\n"
  261. , rd->id
  262. , rd->collected_value
  263. );
  264. }
  265. buffer_strcat(host->sender->build, "END\n");
  266. }
  267. static void rrdpush_sender_thread_spawn(RRDHOST *host);
  268. // Called from the internal collectors to mark a chart obsolete.
  269. void rrdset_push_chart_definition_now(RRDSET *st) {
  270. RRDHOST *host = st->rrdhost;
  271. if(unlikely(!host->rrdpush_send_enabled || !should_send_chart_matching(st)))
  272. return;
  273. rrdset_rdlock(st);
  274. sender_start(host->sender);
  275. rrdpush_send_chart_definition_nolock(st);
  276. sender_commit(host->sender);
  277. rrdset_unlock(st);
  278. }
  279. void rrdset_done_push(RRDSET *st) {
  280. if(unlikely(!should_send_chart_matching(st)))
  281. return;
  282. RRDHOST *host = st->rrdhost;
  283. if(unlikely(host->rrdpush_send_enabled && !host->rrdpush_sender_spawn))
  284. rrdpush_sender_thread_spawn(host);
  285. // Handle non-connected case
  286. if(unlikely(!__atomic_load_n(&host->rrdpush_sender_connected, __ATOMIC_SEQ_CST))) {
  287. if(unlikely(!host->rrdpush_sender_error_shown))
  288. error("STREAM %s [send]: not ready - discarding collected metrics.", host->hostname);
  289. host->rrdpush_sender_error_shown = 1;
  290. return;
  291. }
  292. else if(unlikely(host->rrdpush_sender_error_shown)) {
  293. info("STREAM %s [send]: sending metrics...", host->hostname);
  294. host->rrdpush_sender_error_shown = 0;
  295. }
  296. sender_start(host->sender);
  297. if(need_to_send_chart_definition(st))
  298. rrdpush_send_chart_definition_nolock(st);
  299. rrdpush_send_chart_metrics_nolock(st, host->sender);
  300. // signal the sender there are more data
  301. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1 && write(host->rrdpush_sender_pipe[PIPE_WRITE], " ", 1) == -1)
  302. error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
  303. sender_commit(host->sender);
  304. }
  305. // labels
  306. static int send_labels_callback(const char *name, const char *value, RRDLABEL_SRC ls, void *data) {
  307. BUFFER *wb = (BUFFER *)data;
  308. buffer_sprintf(wb, "LABEL \"%s\" = %d \"%s\"\n", name, ls, value);
  309. return 1;
  310. }
  311. void rrdpush_send_labels(RRDHOST *host) {
  312. if (!host->host_labels || !rrdhost_flag_check(host, RRDHOST_FLAG_STREAM_LABELS_UPDATE) || (rrdhost_flag_check(host, RRDHOST_FLAG_STREAM_LABELS_STOP)))
  313. return;
  314. sender_start(host->sender);
  315. rrdlabels_walkthrough_read(host->host_labels, send_labels_callback, host->sender->build);
  316. buffer_sprintf(host->sender->build, "OVERWRITE %s\n", "labels");
  317. sender_commit(host->sender);
  318. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1 && write(host->rrdpush_sender_pipe[PIPE_WRITE], " ", 1) == -1)
  319. error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
  320. rrdhost_flag_clear(host, RRDHOST_FLAG_STREAM_LABELS_UPDATE);
  321. }
  322. void rrdpush_claimed_id(RRDHOST *host)
  323. {
  324. if(unlikely(!host->rrdpush_send_enabled || !__atomic_load_n(&host->rrdpush_sender_connected, __ATOMIC_SEQ_CST)))
  325. return;
  326. if(host->sender->version < STREAM_VERSION_CLAIM)
  327. return;
  328. sender_start(host->sender);
  329. rrdhost_aclk_state_lock(host);
  330. buffer_sprintf(host->sender->build, "CLAIMED_ID %s %s\n", host->machine_guid, (host->aclk_state.claimed_id ? host->aclk_state.claimed_id : "NULL") );
  331. rrdhost_aclk_state_unlock(host);
  332. sender_commit(host->sender);
  333. // signal the sender there are more data
  334. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1 && write(host->rrdpush_sender_pipe[PIPE_WRITE], " ", 1) == -1)
  335. error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
  336. }
  337. int connect_to_one_of_destinations(
  338. struct rrdpush_destinations *destinations,
  339. int default_port,
  340. struct timeval *timeout,
  341. size_t *reconnects_counter,
  342. char *connected_to,
  343. size_t connected_to_size,
  344. struct rrdpush_destinations **destination)
  345. {
  346. int sock = -1;
  347. for (struct rrdpush_destinations *d = destinations; d; d = d->next) {
  348. if (d->disabled_no_proper_reply) {
  349. d->disabled_no_proper_reply = 0;
  350. continue;
  351. } else if (d->disabled_because_of_localhost) {
  352. continue;
  353. } else if (d->disabled_already_streaming && (d->disabled_already_streaming + 30 > now_realtime_sec())) {
  354. continue;
  355. } else if (d->disabled_because_of_denied_access) {
  356. d->disabled_because_of_denied_access = 0;
  357. continue;
  358. }
  359. if (reconnects_counter)
  360. *reconnects_counter += 1;
  361. sock = connect_to_this(d->destination, default_port, timeout);
  362. if (sock != -1) {
  363. if (connected_to && connected_to_size) {
  364. strncpy(connected_to, d->destination, connected_to_size);
  365. connected_to[connected_to_size - 1] = '\0';
  366. }
  367. *destination = d;
  368. break;
  369. }
  370. }
  371. return sock;
  372. }
  373. struct rrdpush_destinations *destinations_init(const char *dests) {
  374. const char *s = dests;
  375. struct rrdpush_destinations *destinations = NULL, *prev = NULL;
  376. while(*s) {
  377. const char *e = s;
  378. // skip path, moving both s(tart) and e(nd)
  379. if(*e == '/')
  380. while(!isspace(*e) && *e != ',') s = ++e;
  381. // skip separators, moving both s(tart) and e(nd)
  382. while(isspace(*e) || *e == ',') s = ++e;
  383. // move e(nd) to the first separator
  384. while(*e && !isspace(*e) && *e != ',' && *e != '/') e++;
  385. // is there anything?
  386. if(!*s || s == e) break;
  387. char buf[e - s + 1];
  388. strncpyz(buf, s, e - s);
  389. struct rrdpush_destinations *d = callocz(1, sizeof(struct rrdpush_destinations));
  390. strncpyz(d->destination, buf, sizeof(d->destination)-1);
  391. d->disabled_no_proper_reply = 0;
  392. d->disabled_because_of_localhost = 0;
  393. d->disabled_already_streaming = 0;
  394. d->disabled_because_of_denied_access = 0;
  395. d->next = NULL;
  396. if (!destinations) {
  397. destinations = d;
  398. } else {
  399. prev->next = d;
  400. }
  401. prev = d;
  402. s = e;
  403. }
  404. return destinations;
  405. }
  406. // ----------------------------------------------------------------------------
  407. // rrdpush sender thread
  408. // Either the receiver lost the connection or the host is being destroyed.
  409. // The sender mutex guards thread creation, any spurious data is wiped on reconnection.
  410. void rrdpush_sender_thread_stop(RRDHOST *host) {
  411. if (!host->sender)
  412. return;
  413. netdata_mutex_lock(&host->sender->mutex);
  414. netdata_thread_t thr = 0;
  415. if(host->rrdpush_sender_spawn) {
  416. info("STREAM %s [send]: signaling sending thread to stop...", host->hostname);
  417. // signal the thread that we want to join it
  418. host->rrdpush_sender_join = 1;
  419. // copy the thread id, so that we will be waiting for the right one
  420. // even if a new one has been spawn
  421. thr = host->rrdpush_sender_thread;
  422. // signal it to cancel
  423. netdata_thread_cancel(host->rrdpush_sender_thread);
  424. }
  425. netdata_mutex_unlock(&host->sender->mutex);
  426. if(thr != 0) {
  427. info("STREAM %s [send]: waiting for the sending thread to stop...", host->hostname);
  428. void *result;
  429. netdata_thread_join(thr, &result);
  430. info("STREAM %s [send]: sending thread has exited.", host->hostname);
  431. }
  432. }
  433. // ----------------------------------------------------------------------------
  434. // rrdpush receiver thread
  435. void log_stream_connection(const char *client_ip, const char *client_port, const char *api_key, const char *machine_guid, const char *host, const char *msg) {
  436. log_access("STREAM: %d '[%s]:%s' '%s' host '%s' api key '%s' machine guid '%s'", gettid(), client_ip, client_port, msg, host, api_key, machine_guid);
  437. }
  438. static void rrdpush_sender_thread_spawn(RRDHOST *host) {
  439. netdata_mutex_lock(&host->sender->mutex);
  440. if(!host->rrdpush_sender_spawn) {
  441. char tag[NETDATA_THREAD_TAG_MAX + 1];
  442. snprintfz(tag, NETDATA_THREAD_TAG_MAX, "STREAM_SENDER[%s]", host->hostname);
  443. if(netdata_thread_create(&host->rrdpush_sender_thread, tag, NETDATA_THREAD_OPTION_JOINABLE, rrdpush_sender_thread, (void *) host->sender))
  444. error("STREAM %s [send]: failed to create new thread for client.", host->hostname);
  445. else
  446. host->rrdpush_sender_spawn = 1;
  447. }
  448. netdata_mutex_unlock(&host->sender->mutex);
  449. }
  450. int rrdpush_receiver_permission_denied(struct web_client *w) {
  451. // we always respond with the same message and error code
  452. // to prevent an attacker from gaining info about the error
  453. buffer_flush(w->response.data);
  454. buffer_sprintf(w->response.data, "You are not permitted to access this. Check the logs for more info.");
  455. return 401;
  456. }
  457. int rrdpush_receiver_too_busy_now(struct web_client *w) {
  458. // we always respond with the same message and error code
  459. // to prevent an attacker from gaining info about the error
  460. buffer_flush(w->response.data);
  461. buffer_sprintf(w->response.data, "The server is too busy now to accept this request. Try later.");
  462. return 503;
  463. }
  464. void *rrdpush_receiver_thread(void *ptr);
  465. int rrdpush_receiver_thread_spawn(struct web_client *w, char *url) {
  466. info("clients wants to STREAM metrics.");
  467. char *key = NULL, *hostname = NULL, *registry_hostname = NULL, *machine_guid = NULL, *os = "unknown", *timezone = "unknown", *abbrev_timezone = "UTC", *tags = NULL;
  468. int32_t utc_offset = 0;
  469. int update_every = default_rrd_update_every;
  470. uint32_t stream_version = UINT_MAX;
  471. char buf[GUID_LEN + 1];
  472. struct rrdhost_system_info *system_info = callocz(1, sizeof(struct rrdhost_system_info));
  473. system_info->hops = 1;
  474. while(url) {
  475. char *value = mystrsep(&url, "&");
  476. if(!value || !*value) continue;
  477. char *name = mystrsep(&value, "=");
  478. if(!name || !*name) continue;
  479. if(!value || !*value) continue;
  480. if(!strcmp(name, "key"))
  481. key = value;
  482. else if(!strcmp(name, "hostname"))
  483. hostname = value;
  484. else if(!strcmp(name, "registry_hostname"))
  485. registry_hostname = value;
  486. else if(!strcmp(name, "machine_guid"))
  487. machine_guid = value;
  488. else if(!strcmp(name, "update_every"))
  489. update_every = (int)strtoul(value, NULL, 0);
  490. else if(!strcmp(name, "os"))
  491. os = value;
  492. else if(!strcmp(name, "timezone"))
  493. timezone = value;
  494. else if(!strcmp(name, "abbrev_timezone"))
  495. abbrev_timezone = value;
  496. else if(!strcmp(name, "utc_offset"))
  497. utc_offset = (int32_t)strtol(value, NULL, 0);
  498. else if(!strcmp(name, "hops"))
  499. system_info->hops = (uint16_t) strtoul(value, NULL, 0);
  500. else if(!strcmp(name, "ml_capable"))
  501. system_info->ml_capable = strtoul(value, NULL, 0);
  502. else if(!strcmp(name, "ml_enabled"))
  503. system_info->ml_enabled = strtoul(value, NULL, 0);
  504. else if(!strcmp(name, "mc_version"))
  505. system_info->mc_version = strtoul(value, NULL, 0);
  506. else if(!strcmp(name, "tags"))
  507. tags = value;
  508. else if(!strcmp(name, "ver"))
  509. stream_version = MIN((uint32_t) strtoul(value, NULL, 0), STREAMING_PROTOCOL_CURRENT_VERSION);
  510. else {
  511. // An old Netdata child does not have a compatible streaming protocol, map to something sane.
  512. if (!strcmp(name, "NETDATA_SYSTEM_OS_NAME"))
  513. name = "NETDATA_HOST_OS_NAME";
  514. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID"))
  515. name = "NETDATA_HOST_OS_ID";
  516. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID_LIKE"))
  517. name = "NETDATA_HOST_OS_ID_LIKE";
  518. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION"))
  519. name = "NETDATA_HOST_OS_VERSION";
  520. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION_ID"))
  521. name = "NETDATA_HOST_OS_VERSION_ID";
  522. else if (!strcmp(name, "NETDATA_SYSTEM_OS_DETECTION"))
  523. name = "NETDATA_HOST_OS_DETECTION";
  524. else if(!strcmp(name, "NETDATA_PROTOCOL_VERSION") && stream_version == UINT_MAX) {
  525. stream_version = 1;
  526. }
  527. if (unlikely(rrdhost_set_system_info_variable(system_info, name, value))) {
  528. info("STREAM [receive from [%s]:%s]: request has parameter '%s' = '%s', which is not used.",
  529. w->client_ip, w->client_port, name, value);
  530. }
  531. }
  532. }
  533. if (stream_version == UINT_MAX)
  534. stream_version = 0;
  535. if(!key || !*key) {
  536. rrdhost_system_info_free(system_info);
  537. log_stream_connection(w->client_ip, w->client_port, (key && *key)?key:"-", (machine_guid && *machine_guid)?machine_guid:"-", (hostname && *hostname)?hostname:"-", "ACCESS DENIED - NO KEY");
  538. error("STREAM [receive from [%s]:%s]: request without an API key. Forbidding access.", w->client_ip, w->client_port);
  539. return rrdpush_receiver_permission_denied(w);
  540. }
  541. if(!hostname || !*hostname) {
  542. rrdhost_system_info_free(system_info);
  543. log_stream_connection(w->client_ip, w->client_port, (key && *key)?key:"-", (machine_guid && *machine_guid)?machine_guid:"-", (hostname && *hostname)?hostname:"-", "ACCESS DENIED - NO HOSTNAME");
  544. error("STREAM [receive from [%s]:%s]: request without a hostname. Forbidding access.", w->client_ip, w->client_port);
  545. return rrdpush_receiver_permission_denied(w);
  546. }
  547. if(!machine_guid || !*machine_guid) {
  548. rrdhost_system_info_free(system_info);
  549. log_stream_connection(w->client_ip, w->client_port, (key && *key)?key:"-", (machine_guid && *machine_guid)?machine_guid:"-", (hostname && *hostname)?hostname:"-", "ACCESS DENIED - NO MACHINE GUID");
  550. error("STREAM [receive from [%s]:%s]: request without a machine GUID. Forbidding access.", w->client_ip, w->client_port);
  551. return rrdpush_receiver_permission_denied(w);
  552. }
  553. if(regenerate_guid(key, buf) == -1) {
  554. rrdhost_system_info_free(system_info);
  555. log_stream_connection(w->client_ip, w->client_port, (key && *key)?key:"-", (machine_guid && *machine_guid)?machine_guid:"-", (hostname && *hostname)?hostname:"-", "ACCESS DENIED - INVALID KEY");
  556. error("STREAM [receive from [%s]:%s]: API key '%s' is not valid GUID (use the command uuidgen to generate one). Forbidding access.", w->client_ip, w->client_port, key);
  557. return rrdpush_receiver_permission_denied(w);
  558. }
  559. if(regenerate_guid(machine_guid, buf) == -1) {
  560. rrdhost_system_info_free(system_info);
  561. log_stream_connection(w->client_ip, w->client_port, (key && *key)?key:"-", (machine_guid && *machine_guid)?machine_guid:"-", (hostname && *hostname)?hostname:"-", "ACCESS DENIED - INVALID MACHINE GUID");
  562. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not GUID. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  563. return rrdpush_receiver_permission_denied(w);
  564. }
  565. if(!appconfig_get_boolean(&stream_config, key, "enabled", 0)) {
  566. rrdhost_system_info_free(system_info);
  567. log_stream_connection(w->client_ip, w->client_port, (key && *key)?key:"-", (machine_guid && *machine_guid)?machine_guid:"-", (hostname && *hostname)?hostname:"-", "ACCESS DENIED - KEY NOT ENABLED");
  568. error("STREAM [receive from [%s]:%s]: API key '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, key);
  569. return rrdpush_receiver_permission_denied(w);
  570. }
  571. {
  572. SIMPLE_PATTERN *key_allow_from = simple_pattern_create(appconfig_get(&stream_config, key, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  573. if(key_allow_from) {
  574. if(!simple_pattern_matches(key_allow_from, w->client_ip)) {
  575. simple_pattern_free(key_allow_from);
  576. rrdhost_system_info_free(system_info);
  577. log_stream_connection(w->client_ip, w->client_port, (key && *key)?key:"-", (machine_guid && *machine_guid)?machine_guid:"-", (hostname && *hostname) ? hostname : "-", "ACCESS DENIED - KEY NOT ALLOWED FROM THIS IP");
  578. error("STREAM [receive from [%s]:%s]: API key '%s' is not permitted from this IP. Forbidding access.", w->client_ip, w->client_port, key);
  579. return rrdpush_receiver_permission_denied(w);
  580. }
  581. simple_pattern_free(key_allow_from);
  582. }
  583. }
  584. if(!appconfig_get_boolean(&stream_config, machine_guid, "enabled", 1)) {
  585. rrdhost_system_info_free(system_info);
  586. log_stream_connection(w->client_ip, w->client_port, (key && *key)?key:"-", (machine_guid && *machine_guid)?machine_guid:"-", (hostname && *hostname)?hostname:"-", "ACCESS DENIED - MACHINE GUID NOT ENABLED");
  587. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  588. return rrdpush_receiver_permission_denied(w);
  589. }
  590. {
  591. SIMPLE_PATTERN *machine_allow_from = simple_pattern_create(appconfig_get(&stream_config, machine_guid, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  592. if(machine_allow_from) {
  593. if(!simple_pattern_matches(machine_allow_from, w->client_ip)) {
  594. simple_pattern_free(machine_allow_from);
  595. rrdhost_system_info_free(system_info);
  596. log_stream_connection(w->client_ip, w->client_port, (key && *key)?key:"-", (machine_guid && *machine_guid)?machine_guid:"-", (hostname && *hostname) ? hostname : "-", "ACCESS DENIED - MACHINE GUID NOT ALLOWED FROM THIS IP");
  597. error("STREAM [receive from [%s]:%s]: Machine GUID '%s' is not permitted from this IP. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  598. return rrdpush_receiver_permission_denied(w);
  599. }
  600. simple_pattern_free(machine_allow_from);
  601. }
  602. }
  603. if(unlikely(web_client_streaming_rate_t > 0)) {
  604. static netdata_mutex_t stream_rate_mutex = NETDATA_MUTEX_INITIALIZER;
  605. static volatile time_t last_stream_accepted_t = 0;
  606. netdata_mutex_lock(&stream_rate_mutex);
  607. time_t now = now_realtime_sec();
  608. if(unlikely(last_stream_accepted_t == 0))
  609. last_stream_accepted_t = now;
  610. if(now - last_stream_accepted_t < web_client_streaming_rate_t) {
  611. netdata_mutex_unlock(&stream_rate_mutex);
  612. rrdhost_system_info_free(system_info);
  613. error("STREAM [receive from [%s]:%s]: too busy to accept new streaming request. Will be allowed in %ld secs.", w->client_ip, w->client_port, (long)(web_client_streaming_rate_t - (now - last_stream_accepted_t)));
  614. return rrdpush_receiver_too_busy_now(w);
  615. }
  616. last_stream_accepted_t = now;
  617. netdata_mutex_unlock(&stream_rate_mutex);
  618. }
  619. /*
  620. * Quick path for rejecting multiple connections. The lock taken is fine-grained - it only protects the receiver
  621. * pointer within the host (if a host exists). This protects against multiple concurrent web requests hitting
  622. * separate threads within the web-server and landing here. The lock guards the thread-shutdown sequence that
  623. * detaches the receiver from the host. If the host is being created (first time-access) then we also use the
  624. * lock to prevent race-hazard (two threads try to create the host concurrently, one wins and the other does a
  625. * lookup to the now-attached structure).
  626. */
  627. struct receiver_state *rpt = callocz(1, sizeof(*rpt));
  628. rrd_rdlock();
  629. RRDHOST *host = rrdhost_find_by_guid(machine_guid, 0);
  630. if (unlikely(host && rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED))) /* Ignore archived hosts. */
  631. host = NULL;
  632. if (host) {
  633. rrdhost_wrlock(host);
  634. netdata_mutex_lock(&host->receiver_lock);
  635. rrdhost_flag_clear(host, RRDHOST_FLAG_ORPHAN);
  636. host->senders_disconnected_time = 0;
  637. if (host->receiver != NULL) {
  638. time_t age = now_realtime_sec() - host->receiver->last_msg_t;
  639. if (age > 30) {
  640. host->receiver->shutdown = 1;
  641. shutdown(host->receiver->fd, SHUT_RDWR);
  642. host->receiver = NULL; // Thread holds reference to structure
  643. info(
  644. "STREAM %s [receive from [%s]:%s]: multiple connections for same host detected - "
  645. "existing connection is dead (%"PRId64" sec), accepting new connection.",
  646. host->hostname,
  647. w->client_ip,
  648. w->client_port,
  649. (int64_t)age);
  650. }
  651. else {
  652. netdata_mutex_unlock(&host->receiver_lock);
  653. rrdhost_unlock(host);
  654. rrd_unlock();
  655. log_stream_connection(w->client_ip, w->client_port, key, host->machine_guid, host->hostname,
  656. "REJECTED - ALREADY CONNECTED");
  657. info(
  658. "STREAM %s [receive from [%s]:%s]: multiple connections for same host detected - "
  659. "existing connection is active (within last %"PRId64" sec), rejecting new connection.",
  660. host->hostname,
  661. w->client_ip,
  662. w->client_port,
  663. (int64_t)age);
  664. // Have not set WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET - caller should clean up
  665. buffer_flush(w->response.data);
  666. buffer_strcat(w->response.data, "This GUID is already streaming to this server");
  667. freez(rpt);
  668. return 409;
  669. }
  670. }
  671. host->receiver = rpt;
  672. netdata_mutex_unlock(&host->receiver_lock);
  673. rrdhost_unlock(host);
  674. }
  675. rrd_unlock();
  676. rpt->last_msg_t = now_realtime_sec();
  677. rpt->host = host;
  678. rpt->fd = w->ifd;
  679. rpt->key = strdupz(key);
  680. rpt->hostname = strdupz(hostname);
  681. rpt->registry_hostname = strdupz((registry_hostname && *registry_hostname)?registry_hostname:hostname);
  682. rpt->machine_guid = strdupz(machine_guid);
  683. rpt->os = strdupz(os);
  684. rpt->timezone = strdupz(timezone);
  685. rpt->abbrev_timezone = strdupz(abbrev_timezone);
  686. rpt->utc_offset = utc_offset;
  687. rpt->tags = (tags)?strdupz(tags):NULL;
  688. rpt->client_ip = strdupz(w->client_ip);
  689. rpt->client_port = strdupz(w->client_port);
  690. rpt->update_every = update_every;
  691. rpt->system_info = system_info;
  692. rpt->stream_version = stream_version;
  693. #ifdef ENABLE_HTTPS
  694. rpt->ssl.conn = w->ssl.conn;
  695. rpt->ssl.flags = w->ssl.flags;
  696. w->ssl.conn = NULL;
  697. w->ssl.flags = NETDATA_SSL_START;
  698. #endif
  699. if(w->user_agent && w->user_agent[0]) {
  700. char *t = strchr(w->user_agent, '/');
  701. if(t && *t) {
  702. *t = '\0';
  703. t++;
  704. }
  705. rpt->program_name = strdupz(w->user_agent);
  706. if(t && *t) rpt->program_version = strdupz(t);
  707. }
  708. debug(D_SYSTEM, "starting STREAM receive thread.");
  709. char tag[FILENAME_MAX + 1];
  710. snprintfz(tag, FILENAME_MAX, "STREAM_RECEIVER[%s,[%s]:%s]", rpt->hostname, w->client_ip, w->client_port);
  711. if(netdata_thread_create(&rpt->thread, tag, NETDATA_THREAD_OPTION_DEFAULT, rrdpush_receiver_thread, (void *)rpt))
  712. error("Failed to create new STREAM receive thread for client.");
  713. // prevent the caller from closing the streaming socket
  714. if(web_server_mode == WEB_SERVER_MODE_STATIC_THREADED) {
  715. web_client_flag_set(w, WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET);
  716. }
  717. else {
  718. if(w->ifd == w->ofd)
  719. w->ifd = w->ofd = -1;
  720. else
  721. w->ifd = -1;
  722. }
  723. buffer_flush(w->response.data);
  724. return 200;
  725. }