rrdpush.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  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. netdata_mutex_lock(&host->sender->mutex);
  412. netdata_thread_t thr = 0;
  413. if(host->rrdpush_sender_spawn) {
  414. info("STREAM %s [send]: signaling sending thread to stop...", host->hostname);
  415. // signal the thread that we want to join it
  416. host->rrdpush_sender_join = 1;
  417. // copy the thread id, so that we will be waiting for the right one
  418. // even if a new one has been spawn
  419. thr = host->rrdpush_sender_thread;
  420. // signal it to cancel
  421. netdata_thread_cancel(host->rrdpush_sender_thread);
  422. }
  423. netdata_mutex_unlock(&host->sender->mutex);
  424. if(thr != 0) {
  425. info("STREAM %s [send]: waiting for the sending thread to stop...", host->hostname);
  426. void *result;
  427. netdata_thread_join(thr, &result);
  428. info("STREAM %s [send]: sending thread has exited.", host->hostname);
  429. }
  430. }
  431. // ----------------------------------------------------------------------------
  432. // rrdpush receiver thread
  433. 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) {
  434. 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);
  435. }
  436. static void rrdpush_sender_thread_spawn(RRDHOST *host) {
  437. netdata_mutex_lock(&host->sender->mutex);
  438. if(!host->rrdpush_sender_spawn) {
  439. char tag[NETDATA_THREAD_TAG_MAX + 1];
  440. snprintfz(tag, NETDATA_THREAD_TAG_MAX, "STREAM_SENDER[%s]", host->hostname);
  441. if(netdata_thread_create(&host->rrdpush_sender_thread, tag, NETDATA_THREAD_OPTION_JOINABLE, rrdpush_sender_thread, (void *) host->sender))
  442. error("STREAM %s [send]: failed to create new thread for client.", host->hostname);
  443. else
  444. host->rrdpush_sender_spawn = 1;
  445. }
  446. netdata_mutex_unlock(&host->sender->mutex);
  447. }
  448. int rrdpush_receiver_permission_denied(struct web_client *w) {
  449. // we always respond with the same message and error code
  450. // to prevent an attacker from gaining info about the error
  451. buffer_flush(w->response.data);
  452. buffer_sprintf(w->response.data, "You are not permitted to access this. Check the logs for more info.");
  453. return 401;
  454. }
  455. int rrdpush_receiver_too_busy_now(struct web_client *w) {
  456. // we always respond with the same message and error code
  457. // to prevent an attacker from gaining info about the error
  458. buffer_flush(w->response.data);
  459. buffer_sprintf(w->response.data, "The server is too busy now to accept this request. Try later.");
  460. return 503;
  461. }
  462. void *rrdpush_receiver_thread(void *ptr);
  463. int rrdpush_receiver_thread_spawn(struct web_client *w, char *url) {
  464. info("clients wants to STREAM metrics.");
  465. char *key = NULL, *hostname = NULL, *registry_hostname = NULL, *machine_guid = NULL, *os = "unknown", *timezone = "unknown", *abbrev_timezone = "UTC", *tags = NULL;
  466. int32_t utc_offset = 0;
  467. int update_every = default_rrd_update_every;
  468. uint32_t stream_version = UINT_MAX;
  469. char buf[GUID_LEN + 1];
  470. struct rrdhost_system_info *system_info = callocz(1, sizeof(struct rrdhost_system_info));
  471. system_info->hops = 1;
  472. while(url) {
  473. char *value = mystrsep(&url, "&");
  474. if(!value || !*value) continue;
  475. char *name = mystrsep(&value, "=");
  476. if(!name || !*name) continue;
  477. if(!value || !*value) continue;
  478. if(!strcmp(name, "key"))
  479. key = value;
  480. else if(!strcmp(name, "hostname"))
  481. hostname = value;
  482. else if(!strcmp(name, "registry_hostname"))
  483. registry_hostname = value;
  484. else if(!strcmp(name, "machine_guid"))
  485. machine_guid = value;
  486. else if(!strcmp(name, "update_every"))
  487. update_every = (int)strtoul(value, NULL, 0);
  488. else if(!strcmp(name, "os"))
  489. os = value;
  490. else if(!strcmp(name, "timezone"))
  491. timezone = value;
  492. else if(!strcmp(name, "abbrev_timezone"))
  493. abbrev_timezone = value;
  494. else if(!strcmp(name, "utc_offset"))
  495. utc_offset = (int32_t)strtol(value, NULL, 0);
  496. else if(!strcmp(name, "hops"))
  497. system_info->hops = (uint16_t) strtoul(value, NULL, 0);
  498. else if(!strcmp(name, "ml_capable"))
  499. system_info->ml_capable = strtoul(value, NULL, 0);
  500. else if(!strcmp(name, "ml_enabled"))
  501. system_info->ml_enabled = strtoul(value, NULL, 0);
  502. else if(!strcmp(name, "mc_version"))
  503. system_info->mc_version = strtoul(value, NULL, 0);
  504. else if(!strcmp(name, "tags"))
  505. tags = value;
  506. else if(!strcmp(name, "ver"))
  507. stream_version = MIN((uint32_t) strtoul(value, NULL, 0), STREAMING_PROTOCOL_CURRENT_VERSION);
  508. else {
  509. // An old Netdata child does not have a compatible streaming protocol, map to something sane.
  510. if (!strcmp(name, "NETDATA_SYSTEM_OS_NAME"))
  511. name = "NETDATA_HOST_OS_NAME";
  512. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID"))
  513. name = "NETDATA_HOST_OS_ID";
  514. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID_LIKE"))
  515. name = "NETDATA_HOST_OS_ID_LIKE";
  516. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION"))
  517. name = "NETDATA_HOST_OS_VERSION";
  518. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION_ID"))
  519. name = "NETDATA_HOST_OS_VERSION_ID";
  520. else if (!strcmp(name, "NETDATA_SYSTEM_OS_DETECTION"))
  521. name = "NETDATA_HOST_OS_DETECTION";
  522. else if(!strcmp(name, "NETDATA_PROTOCOL_VERSION") && stream_version == UINT_MAX) {
  523. stream_version = 1;
  524. }
  525. if (unlikely(rrdhost_set_system_info_variable(system_info, name, value))) {
  526. info("STREAM [receive from [%s]:%s]: request has parameter '%s' = '%s', which is not used.",
  527. w->client_ip, w->client_port, name, value);
  528. }
  529. }
  530. }
  531. if (stream_version == UINT_MAX)
  532. stream_version = 0;
  533. if(!key || !*key) {
  534. rrdhost_system_info_free(system_info);
  535. 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");
  536. error("STREAM [receive from [%s]:%s]: request without an API key. Forbidding access.", w->client_ip, w->client_port);
  537. return rrdpush_receiver_permission_denied(w);
  538. }
  539. if(!hostname || !*hostname) {
  540. rrdhost_system_info_free(system_info);
  541. 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");
  542. error("STREAM [receive from [%s]:%s]: request without a hostname. Forbidding access.", w->client_ip, w->client_port);
  543. return rrdpush_receiver_permission_denied(w);
  544. }
  545. if(!machine_guid || !*machine_guid) {
  546. rrdhost_system_info_free(system_info);
  547. 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");
  548. error("STREAM [receive from [%s]:%s]: request without a machine GUID. Forbidding access.", w->client_ip, w->client_port);
  549. return rrdpush_receiver_permission_denied(w);
  550. }
  551. if(regenerate_guid(key, buf) == -1) {
  552. rrdhost_system_info_free(system_info);
  553. 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");
  554. 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);
  555. return rrdpush_receiver_permission_denied(w);
  556. }
  557. if(regenerate_guid(machine_guid, buf) == -1) {
  558. rrdhost_system_info_free(system_info);
  559. 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");
  560. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not GUID. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  561. return rrdpush_receiver_permission_denied(w);
  562. }
  563. if(!appconfig_get_boolean(&stream_config, key, "enabled", 0)) {
  564. rrdhost_system_info_free(system_info);
  565. 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");
  566. error("STREAM [receive from [%s]:%s]: API key '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, key);
  567. return rrdpush_receiver_permission_denied(w);
  568. }
  569. {
  570. SIMPLE_PATTERN *key_allow_from = simple_pattern_create(appconfig_get(&stream_config, key, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  571. if(key_allow_from) {
  572. if(!simple_pattern_matches(key_allow_from, w->client_ip)) {
  573. simple_pattern_free(key_allow_from);
  574. rrdhost_system_info_free(system_info);
  575. 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");
  576. error("STREAM [receive from [%s]:%s]: API key '%s' is not permitted from this IP. Forbidding access.", w->client_ip, w->client_port, key);
  577. return rrdpush_receiver_permission_denied(w);
  578. }
  579. simple_pattern_free(key_allow_from);
  580. }
  581. }
  582. if(!appconfig_get_boolean(&stream_config, machine_guid, "enabled", 1)) {
  583. rrdhost_system_info_free(system_info);
  584. 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");
  585. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  586. return rrdpush_receiver_permission_denied(w);
  587. }
  588. {
  589. SIMPLE_PATTERN *machine_allow_from = simple_pattern_create(appconfig_get(&stream_config, machine_guid, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  590. if(machine_allow_from) {
  591. if(!simple_pattern_matches(machine_allow_from, w->client_ip)) {
  592. simple_pattern_free(machine_allow_from);
  593. rrdhost_system_info_free(system_info);
  594. 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");
  595. 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);
  596. return rrdpush_receiver_permission_denied(w);
  597. }
  598. simple_pattern_free(machine_allow_from);
  599. }
  600. }
  601. if(unlikely(web_client_streaming_rate_t > 0)) {
  602. static netdata_mutex_t stream_rate_mutex = NETDATA_MUTEX_INITIALIZER;
  603. static volatile time_t last_stream_accepted_t = 0;
  604. netdata_mutex_lock(&stream_rate_mutex);
  605. time_t now = now_realtime_sec();
  606. if(unlikely(last_stream_accepted_t == 0))
  607. last_stream_accepted_t = now;
  608. if(now - last_stream_accepted_t < web_client_streaming_rate_t) {
  609. netdata_mutex_unlock(&stream_rate_mutex);
  610. rrdhost_system_info_free(system_info);
  611. 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)));
  612. return rrdpush_receiver_too_busy_now(w);
  613. }
  614. last_stream_accepted_t = now;
  615. netdata_mutex_unlock(&stream_rate_mutex);
  616. }
  617. /*
  618. * Quick path for rejecting multiple connections. The lock taken is fine-grained - it only protects the receiver
  619. * pointer within the host (if a host exists). This protects against multiple concurrent web requests hitting
  620. * separate threads within the web-server and landing here. The lock guards the thread-shutdown sequence that
  621. * detaches the receiver from the host. If the host is being created (first time-access) then we also use the
  622. * lock to prevent race-hazard (two threads try to create the host concurrently, one wins and the other does a
  623. * lookup to the now-attached structure).
  624. */
  625. struct receiver_state *rpt = callocz(1, sizeof(*rpt));
  626. rrd_rdlock();
  627. RRDHOST *host = rrdhost_find_by_guid(machine_guid, 0);
  628. if (unlikely(host && rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED))) /* Ignore archived hosts. */
  629. host = NULL;
  630. if (host) {
  631. rrdhost_wrlock(host);
  632. netdata_mutex_lock(&host->receiver_lock);
  633. rrdhost_flag_clear(host, RRDHOST_FLAG_ORPHAN);
  634. host->senders_disconnected_time = 0;
  635. if (host->receiver != NULL) {
  636. time_t age = now_realtime_sec() - host->receiver->last_msg_t;
  637. if (age > 30) {
  638. host->receiver->shutdown = 1;
  639. shutdown(host->receiver->fd, SHUT_RDWR);
  640. host->receiver = NULL; // Thread holds reference to structure
  641. info(
  642. "STREAM %s [receive from [%s]:%s]: multiple connections for same host detected - "
  643. "existing connection is dead (%"PRId64" sec), accepting new connection.",
  644. host->hostname,
  645. w->client_ip,
  646. w->client_port,
  647. (int64_t)age);
  648. }
  649. else {
  650. netdata_mutex_unlock(&host->receiver_lock);
  651. rrdhost_unlock(host);
  652. rrd_unlock();
  653. log_stream_connection(w->client_ip, w->client_port, key, host->machine_guid, host->hostname,
  654. "REJECTED - ALREADY CONNECTED");
  655. info(
  656. "STREAM %s [receive from [%s]:%s]: multiple connections for same host detected - "
  657. "existing connection is active (within last %"PRId64" sec), rejecting new connection.",
  658. host->hostname,
  659. w->client_ip,
  660. w->client_port,
  661. (int64_t)age);
  662. // Have not set WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET - caller should clean up
  663. buffer_flush(w->response.data);
  664. buffer_strcat(w->response.data, "This GUID is already streaming to this server");
  665. freez(rpt);
  666. return 409;
  667. }
  668. }
  669. host->receiver = rpt;
  670. netdata_mutex_unlock(&host->receiver_lock);
  671. rrdhost_unlock(host);
  672. }
  673. rrd_unlock();
  674. rpt->last_msg_t = now_realtime_sec();
  675. rpt->host = host;
  676. rpt->fd = w->ifd;
  677. rpt->key = strdupz(key);
  678. rpt->hostname = strdupz(hostname);
  679. rpt->registry_hostname = strdupz((registry_hostname && *registry_hostname)?registry_hostname:hostname);
  680. rpt->machine_guid = strdupz(machine_guid);
  681. rpt->os = strdupz(os);
  682. rpt->timezone = strdupz(timezone);
  683. rpt->abbrev_timezone = strdupz(abbrev_timezone);
  684. rpt->utc_offset = utc_offset;
  685. rpt->tags = (tags)?strdupz(tags):NULL;
  686. rpt->client_ip = strdupz(w->client_ip);
  687. rpt->client_port = strdupz(w->client_port);
  688. rpt->update_every = update_every;
  689. rpt->system_info = system_info;
  690. rpt->stream_version = stream_version;
  691. #ifdef ENABLE_HTTPS
  692. rpt->ssl.conn = w->ssl.conn;
  693. rpt->ssl.flags = w->ssl.flags;
  694. w->ssl.conn = NULL;
  695. w->ssl.flags = NETDATA_SSL_START;
  696. #endif
  697. if(w->user_agent && w->user_agent[0]) {
  698. char *t = strchr(w->user_agent, '/');
  699. if(t && *t) {
  700. *t = '\0';
  701. t++;
  702. }
  703. rpt->program_name = strdupz(w->user_agent);
  704. if(t && *t) rpt->program_version = strdupz(t);
  705. }
  706. debug(D_SYSTEM, "starting STREAM receive thread.");
  707. char tag[FILENAME_MAX + 1];
  708. snprintfz(tag, FILENAME_MAX, "STREAM_RECEIVER[%s,[%s]:%s]", rpt->hostname, w->client_ip, w->client_port);
  709. if(netdata_thread_create(&rpt->thread, tag, NETDATA_THREAD_OPTION_DEFAULT, rrdpush_receiver_thread, (void *)rpt))
  710. error("Failed to create new STREAM receive thread for client.");
  711. // prevent the caller from closing the streaming socket
  712. if(web_server_mode == WEB_SERVER_MODE_STATIC_THREADED) {
  713. web_client_flag_set(w, WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET);
  714. }
  715. else {
  716. if(w->ifd == w->ofd)
  717. w->ifd = w->ofd = -1;
  718. else
  719. w->ifd = -1;
  720. }
  721. buffer_flush(w->response.data);
  722. return 200;
  723. }