rrdpush.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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_GLOBAL, "cleanup orphan hosts after seconds", 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. char *invalid_certificate = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "ssl skip certificate verification", "no");
  90. if ( !strcmp(invalid_certificate,"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. if(unlikely(!rrdset_flag_check(st, RRDSET_FLAG_ENABLED))) {
  115. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_SEND);
  116. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  117. }
  118. else if(!rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_SEND|RRDSET_FLAG_UPSTREAM_IGNORE)) {
  119. RRDHOST *host = st->rrdhost;
  120. if(simple_pattern_matches(host->rrdpush_send_charts_matching, st->id) ||
  121. simple_pattern_matches(host->rrdpush_send_charts_matching, st->name)) {
  122. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  123. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_SEND);
  124. }
  125. else {
  126. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_SEND);
  127. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  128. }
  129. }
  130. return(rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_SEND));
  131. }
  132. int configured_as_parent() {
  133. struct section *section = NULL;
  134. int is_parent = 0;
  135. appconfig_wrlock(&stream_config);
  136. for (section = stream_config.first_section; section; section = section->next) {
  137. uuid_t uuid;
  138. if (uuid_parse(section->name, uuid) != -1 &&
  139. appconfig_get_boolean_by_section(section, "enabled", 0)) {
  140. is_parent = 1;
  141. break;
  142. }
  143. }
  144. appconfig_unlock(&stream_config);
  145. return is_parent;
  146. }
  147. // checks if the current chart definition has been sent
  148. static inline int need_to_send_chart_definition(RRDSET *st) {
  149. rrdset_check_rdlock(st);
  150. if(unlikely(!(rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_EXPOSED))))
  151. return 1;
  152. RRDDIM *rd;
  153. rrddim_foreach_read(rd, st) {
  154. if(unlikely(!rd->exposed)) {
  155. #ifdef NETDATA_INTERNAL_CHECKS
  156. info("host '%s', chart '%s', dimension '%s' flag 'exposed' triggered chart refresh to upstream", st->rrdhost->hostname, st->id, rd->id);
  157. #endif
  158. return 1;
  159. }
  160. }
  161. return 0;
  162. }
  163. // chart labels
  164. void rrdpush_send_clabels(RRDHOST *host, RRDSET *st) {
  165. struct label_index *labels_c = &st->state->labels;
  166. if (labels_c) {
  167. netdata_rwlock_rdlock(&host->labels.labels_rwlock);
  168. struct label *lbl = labels_c->head;
  169. while(lbl) {
  170. buffer_sprintf(host->sender->build,
  171. "CLABEL \"%s\" \"%s\" %d\n", lbl->key, lbl->value, (int)lbl->label_source);
  172. lbl = lbl->next;
  173. }
  174. if (labels_c->head)
  175. buffer_sprintf(host->sender->build,"CLABEL_COMMIT\n");
  176. netdata_rwlock_unlock(&host->labels.labels_rwlock);
  177. }
  178. }
  179. // Send the current chart definition.
  180. // Assumes that collector thread has already called sender_start for mutex / buffer state.
  181. static inline void rrdpush_send_chart_definition_nolock(RRDSET *st) {
  182. RRDHOST *host = st->rrdhost;
  183. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  184. // properly set the name for the remote end to parse it
  185. char *name = "";
  186. if(likely(st->name)) {
  187. if(unlikely(strcmp(st->id, st->name))) {
  188. // they differ
  189. name = strchr(st->name, '.');
  190. if(name)
  191. name++;
  192. else
  193. name = "";
  194. }
  195. }
  196. // send the chart
  197. buffer_sprintf(
  198. host->sender->build
  199. , "CHART \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" %ld %d \"%s %s %s %s\" \"%s\" \"%s\"\n"
  200. , st->id
  201. , name
  202. , st->title
  203. , st->units
  204. , st->family
  205. , st->context
  206. , rrdset_type_name(st->chart_type)
  207. , st->priority
  208. , st->update_every
  209. , rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE)?"obsolete":""
  210. , rrdset_flag_check(st, RRDSET_FLAG_DETAIL)?"detail":""
  211. , rrdset_flag_check(st, RRDSET_FLAG_STORE_FIRST)?"store_first":""
  212. , rrdset_flag_check(st, RRDSET_FLAG_HIDDEN)?"hidden":""
  213. , (st->plugin_name)?st->plugin_name:""
  214. , (st->module_name)?st->module_name:""
  215. );
  216. // send the chart labels
  217. if (host->sender->version >= STREAM_VERSION_CLABELS)
  218. rrdpush_send_clabels(host, st);
  219. // send the dimensions
  220. RRDDIM *rd;
  221. rrddim_foreach_read(rd, st) {
  222. buffer_sprintf(
  223. host->sender->build
  224. , "DIMENSION \"%s\" \"%s\" \"%s\" " COLLECTED_NUMBER_FORMAT " " COLLECTED_NUMBER_FORMAT " \"%s %s %s\"\n"
  225. , rd->id
  226. , rd->name
  227. , rrd_algorithm_name(rd->algorithm)
  228. , rd->multiplier
  229. , rd->divisor
  230. , rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE)?"obsolete":""
  231. , rrddim_flag_check(rd, RRDDIM_FLAG_HIDDEN)?"hidden":""
  232. , rrddim_flag_check(rd, RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)?"noreset":""
  233. );
  234. rd->exposed = 1;
  235. }
  236. // send the chart local custom variables
  237. RRDSETVAR *rs;
  238. for(rs = st->variables; rs ;rs = rs->next) {
  239. if(unlikely(rs->type == RRDVAR_TYPE_CALCULATED && rs->options & RRDVAR_OPTION_CUSTOM_CHART_VAR)) {
  240. calculated_number *value = (calculated_number *) rs->value;
  241. buffer_sprintf(
  242. host->sender->build
  243. , "VARIABLE CHART %s = " CALCULATED_NUMBER_FORMAT "\n"
  244. , rs->variable
  245. , *value
  246. );
  247. }
  248. }
  249. st->upstream_resync_time = st->last_collected_time.tv_sec + (remote_clock_resync_iterations * st->update_every);
  250. }
  251. // sends the current chart dimensions
  252. static inline void rrdpush_send_chart_metrics_nolock(RRDSET *st, struct sender_state *s) {
  253. RRDHOST *host = st->rrdhost;
  254. 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);
  255. if (s->version >= VERSION_GAP_FILLING)
  256. buffer_sprintf(host->sender->build, " %"PRId64"\n", (int64_t)st->last_collected_time.tv_sec);
  257. else
  258. buffer_strcat(host->sender->build, "\n");
  259. RRDDIM *rd;
  260. rrddim_foreach_read(rd, st) {
  261. if(rd->updated && rd->exposed)
  262. buffer_sprintf(host->sender->build
  263. , "SET \"%s\" = " COLLECTED_NUMBER_FORMAT "\n"
  264. , rd->id
  265. , rd->collected_value
  266. );
  267. }
  268. buffer_strcat(host->sender->build, "END\n");
  269. }
  270. static void rrdpush_sender_thread_spawn(RRDHOST *host);
  271. // Called from the internal collectors to mark a chart obsolete.
  272. void rrdset_push_chart_definition_now(RRDSET *st) {
  273. RRDHOST *host = st->rrdhost;
  274. if(unlikely(!host->rrdpush_send_enabled || !should_send_chart_matching(st)))
  275. return;
  276. rrdset_rdlock(st);
  277. sender_start(host->sender);
  278. rrdpush_send_chart_definition_nolock(st);
  279. sender_commit(host->sender);
  280. rrdset_unlock(st);
  281. }
  282. void rrdset_done_push(RRDSET *st) {
  283. if(unlikely(!should_send_chart_matching(st)))
  284. return;
  285. RRDHOST *host = st->rrdhost;
  286. if(unlikely(host->rrdpush_send_enabled && !host->rrdpush_sender_spawn))
  287. rrdpush_sender_thread_spawn(host);
  288. // Handle non-connected case
  289. if(unlikely(!host->rrdpush_sender_connected)) {
  290. if(unlikely(!host->rrdpush_sender_error_shown))
  291. error("STREAM %s [send]: not ready - discarding collected metrics.", host->hostname);
  292. host->rrdpush_sender_error_shown = 1;
  293. return;
  294. }
  295. else if(unlikely(host->rrdpush_sender_error_shown)) {
  296. info("STREAM %s [send]: sending metrics...", host->hostname);
  297. host->rrdpush_sender_error_shown = 0;
  298. }
  299. sender_start(host->sender);
  300. if(need_to_send_chart_definition(st))
  301. rrdpush_send_chart_definition_nolock(st);
  302. rrdpush_send_chart_metrics_nolock(st, host->sender);
  303. // signal the sender there are more data
  304. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1 && write(host->rrdpush_sender_pipe[PIPE_WRITE], " ", 1) == -1)
  305. error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
  306. sender_commit(host->sender);
  307. }
  308. // labels
  309. void rrdpush_send_labels(RRDHOST *host) {
  310. if (!host->labels.head || !(host->labels.labels_flag & LABEL_FLAG_UPDATE_STREAM) || (host->labels.labels_flag & LABEL_FLAG_STOP_STREAM))
  311. return;
  312. sender_start(host->sender);
  313. rrdhost_rdlock(host);
  314. netdata_rwlock_rdlock(&host->labels.labels_rwlock);
  315. struct label *label_i = host->labels.head;
  316. while(label_i) {
  317. buffer_sprintf(host->sender->build
  318. , "LABEL \"%s\" = %d %s\n"
  319. , label_i->key
  320. , (int)label_i->label_source
  321. , label_i->value);
  322. label_i = label_i->next;
  323. }
  324. buffer_sprintf(host->sender->build
  325. , "OVERWRITE %s\n", "labels");
  326. netdata_rwlock_unlock(&host->labels.labels_rwlock);
  327. rrdhost_unlock(host);
  328. sender_commit(host->sender);
  329. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1 && write(host->rrdpush_sender_pipe[PIPE_WRITE], " ", 1) == -1)
  330. error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
  331. host->labels.labels_flag &= ~LABEL_FLAG_UPDATE_STREAM;
  332. }
  333. void rrdpush_claimed_id(RRDHOST *host)
  334. {
  335. if(unlikely(!host->rrdpush_send_enabled || !host->rrdpush_sender_connected))
  336. return;
  337. if(host->sender->version < STREAM_VERSION_CLAIM)
  338. return;
  339. sender_start(host->sender);
  340. rrdhost_aclk_state_lock(host);
  341. buffer_sprintf(host->sender->build, "CLAIMED_ID %s %s\n", host->machine_guid, (host->aclk_state.claimed_id ? host->aclk_state.claimed_id : "NULL") );
  342. rrdhost_aclk_state_unlock(host);
  343. sender_commit(host->sender);
  344. // signal the sender there are more data
  345. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1 && write(host->rrdpush_sender_pipe[PIPE_WRITE], " ", 1) == -1)
  346. error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
  347. }
  348. // ----------------------------------------------------------------------------
  349. // rrdpush sender thread
  350. // Either the receiver lost the connection or the host is being destroyed.
  351. // The sender mutex guards thread creation, any spurious data is wiped on reconnection.
  352. void rrdpush_sender_thread_stop(RRDHOST *host) {
  353. netdata_mutex_lock(&host->sender->mutex);
  354. netdata_thread_t thr = 0;
  355. if(host->rrdpush_sender_spawn) {
  356. info("STREAM %s [send]: signaling sending thread to stop...", host->hostname);
  357. // signal the thread that we want to join it
  358. host->rrdpush_sender_join = 1;
  359. // copy the thread id, so that we will be waiting for the right one
  360. // even if a new one has been spawn
  361. thr = host->rrdpush_sender_thread;
  362. // signal it to cancel
  363. netdata_thread_cancel(host->rrdpush_sender_thread);
  364. }
  365. netdata_mutex_unlock(&host->sender->mutex);
  366. if(thr != 0) {
  367. info("STREAM %s [send]: waiting for the sending thread to stop...", host->hostname);
  368. void *result;
  369. netdata_thread_join(thr, &result);
  370. info("STREAM %s [send]: sending thread has exited.", host->hostname);
  371. }
  372. }
  373. // ----------------------------------------------------------------------------
  374. // rrdpush receiver thread
  375. 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) {
  376. 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);
  377. }
  378. static void rrdpush_sender_thread_spawn(RRDHOST *host) {
  379. netdata_mutex_lock(&host->sender->mutex);
  380. if(!host->rrdpush_sender_spawn) {
  381. char tag[NETDATA_THREAD_TAG_MAX + 1];
  382. snprintfz(tag, NETDATA_THREAD_TAG_MAX, "STREAM_SENDER[%s]", host->hostname);
  383. if(netdata_thread_create(&host->rrdpush_sender_thread, tag, NETDATA_THREAD_OPTION_JOINABLE, rrdpush_sender_thread, (void *) host->sender))
  384. error("STREAM %s [send]: failed to create new thread for client.", host->hostname);
  385. else
  386. host->rrdpush_sender_spawn = 1;
  387. }
  388. netdata_mutex_unlock(&host->sender->mutex);
  389. }
  390. int rrdpush_receiver_permission_denied(struct web_client *w) {
  391. // we always respond with the same message and error code
  392. // to prevent an attacker from gaining info about the error
  393. buffer_flush(w->response.data);
  394. buffer_sprintf(w->response.data, "You are not permitted to access this. Check the logs for more info.");
  395. return 401;
  396. }
  397. int rrdpush_receiver_too_busy_now(struct web_client *w) {
  398. // we always respond with the same message and error code
  399. // to prevent an attacker from gaining info about the error
  400. buffer_flush(w->response.data);
  401. buffer_sprintf(w->response.data, "The server is too busy now to accept this request. Try later.");
  402. return 503;
  403. }
  404. void *rrdpush_receiver_thread(void *ptr);
  405. int rrdpush_receiver_thread_spawn(struct web_client *w, char *url) {
  406. info("clients wants to STREAM metrics.");
  407. char *key = NULL, *hostname = NULL, *registry_hostname = NULL, *machine_guid = NULL, *os = "unknown", *timezone = "unknown", *abbrev_timezone = "UTC", *tags = NULL;
  408. int32_t utc_offset = 0;
  409. int update_every = default_rrd_update_every;
  410. uint32_t stream_version = UINT_MAX;
  411. char buf[GUID_LEN + 1];
  412. struct rrdhost_system_info *system_info = callocz(1, sizeof(struct rrdhost_system_info));
  413. system_info->hops = 1;
  414. while(url) {
  415. char *value = mystrsep(&url, "&");
  416. if(!value || !*value) continue;
  417. char *name = mystrsep(&value, "=");
  418. if(!name || !*name) continue;
  419. if(!value || !*value) continue;
  420. if(!strcmp(name, "key"))
  421. key = value;
  422. else if(!strcmp(name, "hostname"))
  423. hostname = value;
  424. else if(!strcmp(name, "registry_hostname"))
  425. registry_hostname = value;
  426. else if(!strcmp(name, "machine_guid"))
  427. machine_guid = value;
  428. else if(!strcmp(name, "update_every"))
  429. update_every = (int)strtoul(value, NULL, 0);
  430. else if(!strcmp(name, "os"))
  431. os = value;
  432. else if(!strcmp(name, "timezone"))
  433. timezone = value;
  434. else if(!strcmp(name, "abbrev_timezone"))
  435. abbrev_timezone = value;
  436. else if(!strcmp(name, "utc_offset"))
  437. utc_offset = (int32_t)strtol(value, NULL, 0);
  438. else if(!strcmp(name, "hops"))
  439. system_info->hops = (uint16_t) strtoul(value, NULL, 0);
  440. else if(!strcmp(name, "ml_capable"))
  441. system_info->ml_capable = strtoul(value, NULL, 0);
  442. else if(!strcmp(name, "ml_enabled"))
  443. system_info->ml_enabled = strtoul(value, NULL, 0);
  444. else if(!strcmp(name, "tags"))
  445. tags = value;
  446. else if(!strcmp(name, "ver"))
  447. stream_version = MIN((uint32_t) strtoul(value, NULL, 0), STREAMING_PROTOCOL_CURRENT_VERSION);
  448. else {
  449. // An old Netdata child does not have a compatible streaming protocol, map to something sane.
  450. if (!strcmp(name, "NETDATA_SYSTEM_OS_NAME"))
  451. name = "NETDATA_HOST_OS_NAME";
  452. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID"))
  453. name = "NETDATA_HOST_OS_ID";
  454. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID_LIKE"))
  455. name = "NETDATA_HOST_OS_ID_LIKE";
  456. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION"))
  457. name = "NETDATA_HOST_OS_VERSION";
  458. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION_ID"))
  459. name = "NETDATA_HOST_OS_VERSION_ID";
  460. else if (!strcmp(name, "NETDATA_SYSTEM_OS_DETECTION"))
  461. name = "NETDATA_HOST_OS_DETECTION";
  462. else if(!strcmp(name, "NETDATA_PROTOCOL_VERSION") && stream_version == UINT_MAX) {
  463. stream_version = 1;
  464. }
  465. if (unlikely(rrdhost_set_system_info_variable(system_info, name, value))) {
  466. info("STREAM [receive from [%s]:%s]: request has parameter '%s' = '%s', which is not used.",
  467. w->client_ip, w->client_port, name, value);
  468. }
  469. }
  470. }
  471. if (stream_version == UINT_MAX)
  472. stream_version = 0;
  473. if(!key || !*key) {
  474. rrdhost_system_info_free(system_info);
  475. 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");
  476. error("STREAM [receive from [%s]:%s]: request without an API key. Forbidding access.", w->client_ip, w->client_port);
  477. return rrdpush_receiver_permission_denied(w);
  478. }
  479. if(!hostname || !*hostname) {
  480. rrdhost_system_info_free(system_info);
  481. 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");
  482. error("STREAM [receive from [%s]:%s]: request without a hostname. Forbidding access.", w->client_ip, w->client_port);
  483. return rrdpush_receiver_permission_denied(w);
  484. }
  485. if(!machine_guid || !*machine_guid) {
  486. rrdhost_system_info_free(system_info);
  487. 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");
  488. error("STREAM [receive from [%s]:%s]: request without a machine GUID. Forbidding access.", w->client_ip, w->client_port);
  489. return rrdpush_receiver_permission_denied(w);
  490. }
  491. if(regenerate_guid(key, buf) == -1) {
  492. rrdhost_system_info_free(system_info);
  493. 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");
  494. 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);
  495. return rrdpush_receiver_permission_denied(w);
  496. }
  497. if(regenerate_guid(machine_guid, buf) == -1) {
  498. rrdhost_system_info_free(system_info);
  499. 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");
  500. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not GUID. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  501. return rrdpush_receiver_permission_denied(w);
  502. }
  503. if(!appconfig_get_boolean(&stream_config, key, "enabled", 0)) {
  504. rrdhost_system_info_free(system_info);
  505. 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");
  506. error("STREAM [receive from [%s]:%s]: API key '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, key);
  507. return rrdpush_receiver_permission_denied(w);
  508. }
  509. {
  510. SIMPLE_PATTERN *key_allow_from = simple_pattern_create(appconfig_get(&stream_config, key, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  511. if(key_allow_from) {
  512. if(!simple_pattern_matches(key_allow_from, w->client_ip)) {
  513. simple_pattern_free(key_allow_from);
  514. rrdhost_system_info_free(system_info);
  515. 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");
  516. error("STREAM [receive from [%s]:%s]: API key '%s' is not permitted from this IP. Forbidding access.", w->client_ip, w->client_port, key);
  517. return rrdpush_receiver_permission_denied(w);
  518. }
  519. simple_pattern_free(key_allow_from);
  520. }
  521. }
  522. if(!appconfig_get_boolean(&stream_config, machine_guid, "enabled", 1)) {
  523. rrdhost_system_info_free(system_info);
  524. 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");
  525. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  526. return rrdpush_receiver_permission_denied(w);
  527. }
  528. {
  529. SIMPLE_PATTERN *machine_allow_from = simple_pattern_create(appconfig_get(&stream_config, machine_guid, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  530. if(machine_allow_from) {
  531. if(!simple_pattern_matches(machine_allow_from, w->client_ip)) {
  532. simple_pattern_free(machine_allow_from);
  533. rrdhost_system_info_free(system_info);
  534. 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");
  535. 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);
  536. return rrdpush_receiver_permission_denied(w);
  537. }
  538. simple_pattern_free(machine_allow_from);
  539. }
  540. }
  541. if(unlikely(web_client_streaming_rate_t > 0)) {
  542. static netdata_mutex_t stream_rate_mutex = NETDATA_MUTEX_INITIALIZER;
  543. static volatile time_t last_stream_accepted_t = 0;
  544. netdata_mutex_lock(&stream_rate_mutex);
  545. time_t now = now_realtime_sec();
  546. if(unlikely(last_stream_accepted_t == 0))
  547. last_stream_accepted_t = now;
  548. if(now - last_stream_accepted_t < web_client_streaming_rate_t) {
  549. netdata_mutex_unlock(&stream_rate_mutex);
  550. rrdhost_system_info_free(system_info);
  551. 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)));
  552. return rrdpush_receiver_too_busy_now(w);
  553. }
  554. last_stream_accepted_t = now;
  555. netdata_mutex_unlock(&stream_rate_mutex);
  556. }
  557. /*
  558. * Quick path for rejecting multiple connections. The lock taken is fine-grained - it only protects the receiver
  559. * pointer within the host (if a host exists). This protects against multiple concurrent web requests hitting
  560. * separate threads within the web-server and landing here. The lock guards the thread-shutdown sequence that
  561. * detaches the receiver from the host. If the host is being created (first time-access) then we also use the
  562. * lock to prevent race-hazard (two threads try to create the host concurrently, one wins and the other does a
  563. * lookup to the now-attached structure).
  564. */
  565. struct receiver_state *rpt = callocz(1, sizeof(*rpt));
  566. rrd_rdlock();
  567. RRDHOST *host = rrdhost_find_by_guid(machine_guid, 0);
  568. if (unlikely(host && rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED))) /* Ignore archived hosts. */
  569. host = NULL;
  570. if (host) {
  571. rrdhost_wrlock(host);
  572. netdata_mutex_lock(&host->receiver_lock);
  573. rrdhost_flag_clear(host, RRDHOST_FLAG_ORPHAN);
  574. host->senders_disconnected_time = 0;
  575. if (host->receiver != NULL) {
  576. time_t age = now_realtime_sec() - host->receiver->last_msg_t;
  577. if (age > 30) {
  578. host->receiver->shutdown = 1;
  579. shutdown(host->receiver->fd, SHUT_RDWR);
  580. host->receiver = NULL; // Thread holds reference to structure
  581. info(
  582. "STREAM %s [receive from [%s]:%s]: multiple connections for same host detected - "
  583. "existing connection is dead (%"PRId64" sec), accepting new connection.",
  584. host->hostname,
  585. w->client_ip,
  586. w->client_port,
  587. (int64_t)age);
  588. }
  589. else {
  590. netdata_mutex_unlock(&host->receiver_lock);
  591. rrdhost_unlock(host);
  592. rrd_unlock();
  593. log_stream_connection(w->client_ip, w->client_port, key, host->machine_guid, host->hostname,
  594. "REJECTED - ALREADY CONNECTED");
  595. info(
  596. "STREAM %s [receive from [%s]:%s]: multiple connections for same host detected - "
  597. "existing connection is active (within last %"PRId64" sec), rejecting new connection.",
  598. host->hostname,
  599. w->client_ip,
  600. w->client_port,
  601. (int64_t)age);
  602. // Have not set WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET - caller should clean up
  603. buffer_flush(w->response.data);
  604. buffer_strcat(w->response.data, "This GUID is already streaming to this server");
  605. freez(rpt);
  606. return 409;
  607. }
  608. }
  609. host->receiver = rpt;
  610. netdata_mutex_unlock(&host->receiver_lock);
  611. rrdhost_unlock(host);
  612. }
  613. rrd_unlock();
  614. rpt->last_msg_t = now_realtime_sec();
  615. rpt->host = host;
  616. rpt->fd = w->ifd;
  617. rpt->key = strdupz(key);
  618. rpt->hostname = strdupz(hostname);
  619. rpt->registry_hostname = strdupz((registry_hostname && *registry_hostname)?registry_hostname:hostname);
  620. rpt->machine_guid = strdupz(machine_guid);
  621. rpt->os = strdupz(os);
  622. rpt->timezone = strdupz(timezone);
  623. rpt->abbrev_timezone = strdupz(abbrev_timezone);
  624. rpt->utc_offset = utc_offset;
  625. rpt->tags = (tags)?strdupz(tags):NULL;
  626. rpt->client_ip = strdupz(w->client_ip);
  627. rpt->client_port = strdupz(w->client_port);
  628. rpt->update_every = update_every;
  629. rpt->system_info = system_info;
  630. rpt->stream_version = stream_version;
  631. #ifdef ENABLE_HTTPS
  632. rpt->ssl.conn = w->ssl.conn;
  633. rpt->ssl.flags = w->ssl.flags;
  634. w->ssl.conn = NULL;
  635. w->ssl.flags = NETDATA_SSL_START;
  636. #endif
  637. if(w->user_agent && w->user_agent[0]) {
  638. char *t = strchr(w->user_agent, '/');
  639. if(t && *t) {
  640. *t = '\0';
  641. t++;
  642. }
  643. rpt->program_name = strdupz(w->user_agent);
  644. if(t && *t) rpt->program_version = strdupz(t);
  645. }
  646. debug(D_SYSTEM, "starting STREAM receive thread.");
  647. char tag[FILENAME_MAX + 1];
  648. snprintfz(tag, FILENAME_MAX, "STREAM_RECEIVER[%s,[%s]:%s]", rpt->hostname, w->client_ip, w->client_port);
  649. if(netdata_thread_create(&rpt->thread, tag, NETDATA_THREAD_OPTION_DEFAULT, rrdpush_receiver_thread, (void *)rpt))
  650. error("Failed to create new STREAM receive thread for client.");
  651. // prevent the caller from closing the streaming socket
  652. if(web_server_mode == WEB_SERVER_MODE_STATIC_THREADED) {
  653. web_client_flag_set(w, WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET);
  654. }
  655. else {
  656. if(w->ifd == w->ofd)
  657. w->ifd = w->ofd = -1;
  658. else
  659. w->ifd = -1;
  660. }
  661. buffer_flush(w->response.data);
  662. return 200;
  663. }