rrdpush.c 32 KB

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