rrdpush.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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. char *default_rrdpush_destination = NULL;
  40. char *default_rrdpush_api_key = NULL;
  41. char *default_rrdpush_send_charts_matching = NULL;
  42. #ifdef ENABLE_HTTPS
  43. int netdata_use_ssl_on_stream = NETDATA_SSL_OPTIONAL;
  44. char *netdata_ssl_ca_path = NULL;
  45. char *netdata_ssl_ca_file = NULL;
  46. #endif
  47. static void load_stream_conf() {
  48. errno = 0;
  49. char *filename = strdupz_path_subpath(netdata_configured_user_config_dir, "stream.conf");
  50. if(!appconfig_load(&stream_config, filename, 0, NULL)) {
  51. info("CONFIG: cannot load user config '%s'. Will try stock config.", filename);
  52. freez(filename);
  53. filename = strdupz_path_subpath(netdata_configured_stock_config_dir, "stream.conf");
  54. if(!appconfig_load(&stream_config, filename, 0, NULL))
  55. info("CONFIG: cannot load stock config '%s'. Running with internal defaults.", filename);
  56. }
  57. freez(filename);
  58. }
  59. int rrdpush_init() {
  60. // --------------------------------------------------------------------
  61. // load stream.conf
  62. load_stream_conf();
  63. default_rrdpush_enabled = (unsigned int)appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM, "enabled", default_rrdpush_enabled);
  64. default_rrdpush_destination = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "destination", "");
  65. default_rrdpush_api_key = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "api key", "");
  66. default_rrdpush_send_charts_matching = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "send charts matching", "*");
  67. rrdhost_free_orphan_time = config_get_number(CONFIG_SECTION_GLOBAL, "cleanup orphan hosts after seconds", rrdhost_free_orphan_time);
  68. if(default_rrdpush_enabled && (!default_rrdpush_destination || !*default_rrdpush_destination || !default_rrdpush_api_key || !*default_rrdpush_api_key)) {
  69. error("STREAM [send]: cannot enable sending thread - information is missing.");
  70. default_rrdpush_enabled = 0;
  71. }
  72. #ifdef ENABLE_HTTPS
  73. if (netdata_use_ssl_on_stream == NETDATA_SSL_OPTIONAL) {
  74. if (default_rrdpush_destination){
  75. char *test = strstr(default_rrdpush_destination,":SSL");
  76. if(test){
  77. *test = 0X00;
  78. netdata_use_ssl_on_stream = NETDATA_SSL_FORCE;
  79. }
  80. }
  81. }
  82. char *invalid_certificate = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "ssl skip certificate verification", "no");
  83. if ( !strcmp(invalid_certificate,"yes")){
  84. if (netdata_validate_server == NETDATA_SSL_VALID_CERTIFICATE){
  85. info("Netdata is configured to accept invalid SSL certificate.");
  86. netdata_validate_server = NETDATA_SSL_INVALID_CERTIFICATE;
  87. }
  88. }
  89. netdata_ssl_ca_path = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "CApath", "/etc/ssl/certs/");
  90. netdata_ssl_ca_file = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "CAfile", "/etc/ssl/certs/certs.pem");
  91. #endif
  92. return default_rrdpush_enabled;
  93. }
  94. // data collection happens from multiple threads
  95. // each of these threads calls rrdset_done()
  96. // which in turn calls rrdset_done_push()
  97. // which uses this pipe to notify the streaming thread
  98. // that there are more data ready to be sent
  99. #define PIPE_READ 0
  100. #define PIPE_WRITE 1
  101. // to have the remote netdata re-sync the charts
  102. // to its current clock, we send for this many
  103. // iterations a BEGIN line without microseconds
  104. // this is for the first iterations of each chart
  105. unsigned int remote_clock_resync_iterations = 60;
  106. static inline int should_send_chart_matching(RRDSET *st) {
  107. if(unlikely(!rrdset_flag_check(st, RRDSET_FLAG_ENABLED))) {
  108. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_SEND);
  109. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  110. }
  111. else if(!rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_SEND|RRDSET_FLAG_UPSTREAM_IGNORE)) {
  112. RRDHOST *host = st->rrdhost;
  113. if(simple_pattern_matches(host->rrdpush_send_charts_matching, st->id) ||
  114. simple_pattern_matches(host->rrdpush_send_charts_matching, st->name)) {
  115. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  116. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_SEND);
  117. }
  118. else {
  119. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_SEND);
  120. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  121. }
  122. }
  123. return(rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_SEND));
  124. }
  125. int configured_as_parent() {
  126. struct section *section = NULL;
  127. int is_parent = 0;
  128. appconfig_wrlock(&stream_config);
  129. for (section = stream_config.first_section; section; section = section->next) {
  130. uuid_t uuid;
  131. if (uuid_parse(section->name, uuid) != -1 &&
  132. appconfig_get_boolean_by_section(section, "enabled", 0)) {
  133. is_parent = 1;
  134. break;
  135. }
  136. }
  137. appconfig_unlock(&stream_config);
  138. return is_parent;
  139. }
  140. // checks if the current chart definition has been sent
  141. static inline int need_to_send_chart_definition(RRDSET *st) {
  142. rrdset_check_rdlock(st);
  143. if(unlikely(!(rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_EXPOSED))))
  144. return 1;
  145. RRDDIM *rd;
  146. rrddim_foreach_read(rd, st) {
  147. if(unlikely(!rd->exposed)) {
  148. #ifdef NETDATA_INTERNAL_CHECKS
  149. info("host '%s', chart '%s', dimension '%s' flag 'exposed' triggered chart refresh to upstream", st->rrdhost->hostname, st->id, rd->id);
  150. #endif
  151. return 1;
  152. }
  153. }
  154. return 0;
  155. }
  156. // Send the current chart definition.
  157. // Assumes that collector thread has already called sender_start for mutex / buffer state.
  158. static inline void rrdpush_send_chart_definition_nolock(RRDSET *st) {
  159. RRDHOST *host = st->rrdhost;
  160. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  161. // properly set the name for the remote end to parse it
  162. char *name = "";
  163. if(likely(st->name)) {
  164. if(unlikely(strcmp(st->id, st->name))) {
  165. // they differ
  166. name = strchr(st->name, '.');
  167. if(name)
  168. name++;
  169. else
  170. name = "";
  171. }
  172. }
  173. // send the chart
  174. buffer_sprintf(
  175. host->sender->build
  176. , "CHART \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" %ld %d \"%s %s %s %s\" \"%s\" \"%s\"\n"
  177. , st->id
  178. , name
  179. , st->title
  180. , st->units
  181. , st->family
  182. , st->context
  183. , rrdset_type_name(st->chart_type)
  184. , st->priority
  185. , st->update_every
  186. , rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE)?"obsolete":""
  187. , rrdset_flag_check(st, RRDSET_FLAG_DETAIL)?"detail":""
  188. , rrdset_flag_check(st, RRDSET_FLAG_STORE_FIRST)?"store_first":""
  189. , rrdset_flag_check(st, RRDSET_FLAG_HIDDEN)?"hidden":""
  190. , (st->plugin_name)?st->plugin_name:""
  191. , (st->module_name)?st->module_name:""
  192. );
  193. // send the dimensions
  194. RRDDIM *rd;
  195. rrddim_foreach_read(rd, st) {
  196. buffer_sprintf(
  197. host->sender->build
  198. , "DIMENSION \"%s\" \"%s\" \"%s\" " COLLECTED_NUMBER_FORMAT " " COLLECTED_NUMBER_FORMAT " \"%s %s %s\"\n"
  199. , rd->id
  200. , rd->name
  201. , rrd_algorithm_name(rd->algorithm)
  202. , rd->multiplier
  203. , rd->divisor
  204. , rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE)?"obsolete":""
  205. , rrddim_flag_check(rd, RRDDIM_FLAG_HIDDEN)?"hidden":""
  206. , rrddim_flag_check(rd, RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)?"noreset":""
  207. );
  208. rd->exposed = 1;
  209. }
  210. // send the chart local custom variables
  211. RRDSETVAR *rs;
  212. for(rs = st->variables; rs ;rs = rs->next) {
  213. if(unlikely(rs->type == RRDVAR_TYPE_CALCULATED && rs->options & RRDVAR_OPTION_CUSTOM_CHART_VAR)) {
  214. calculated_number *value = (calculated_number *) rs->value;
  215. buffer_sprintf(
  216. host->sender->build
  217. , "VARIABLE CHART %s = " CALCULATED_NUMBER_FORMAT "\n"
  218. , rs->variable
  219. , *value
  220. );
  221. }
  222. }
  223. st->upstream_resync_time = st->last_collected_time.tv_sec + (remote_clock_resync_iterations * st->update_every);
  224. }
  225. // sends the current chart dimensions
  226. static inline void rrdpush_send_chart_metrics_nolock(RRDSET *st, struct sender_state *s) {
  227. RRDHOST *host = st->rrdhost;
  228. 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);
  229. if (s->version >= VERSION_GAP_FILLING)
  230. buffer_sprintf(host->sender->build, " %ld\n", st->last_collected_time.tv_sec);
  231. else
  232. buffer_strcat(host->sender->build, "\n");
  233. RRDDIM *rd;
  234. rrddim_foreach_read(rd, st) {
  235. if(rd->updated && rd->exposed)
  236. buffer_sprintf(host->sender->build
  237. , "SET \"%s\" = " COLLECTED_NUMBER_FORMAT "\n"
  238. , rd->id
  239. , rd->collected_value
  240. );
  241. }
  242. buffer_strcat(host->sender->build, "END\n");
  243. }
  244. static void rrdpush_sender_thread_spawn(RRDHOST *host);
  245. // Called from the internal collectors to mark a chart obsolete.
  246. void rrdset_push_chart_definition_now(RRDSET *st) {
  247. RRDHOST *host = st->rrdhost;
  248. if(unlikely(!host->rrdpush_send_enabled || !should_send_chart_matching(st)))
  249. return;
  250. rrdset_rdlock(st);
  251. sender_start(host->sender);
  252. rrdpush_send_chart_definition_nolock(st);
  253. sender_commit(host->sender);
  254. rrdset_unlock(st);
  255. }
  256. void rrdset_done_push(RRDSET *st) {
  257. if(unlikely(!should_send_chart_matching(st)))
  258. return;
  259. RRDHOST *host = st->rrdhost;
  260. if(unlikely(host->rrdpush_send_enabled && !host->rrdpush_sender_spawn))
  261. rrdpush_sender_thread_spawn(host);
  262. // Handle non-connected case
  263. if(unlikely(!host->rrdpush_sender_connected)) {
  264. if(unlikely(!host->rrdpush_sender_error_shown))
  265. error("STREAM %s [send]: not ready - discarding collected metrics.", host->hostname);
  266. host->rrdpush_sender_error_shown = 1;
  267. return;
  268. }
  269. else if(unlikely(host->rrdpush_sender_error_shown)) {
  270. info("STREAM %s [send]: sending metrics...", host->hostname);
  271. host->rrdpush_sender_error_shown = 0;
  272. }
  273. sender_start(host->sender);
  274. if(need_to_send_chart_definition(st))
  275. rrdpush_send_chart_definition_nolock(st);
  276. rrdpush_send_chart_metrics_nolock(st, host->sender);
  277. // signal the sender there are more data
  278. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1 && write(host->rrdpush_sender_pipe[PIPE_WRITE], " ", 1) == -1)
  279. error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
  280. sender_commit(host->sender);
  281. }
  282. // labels
  283. void rrdpush_send_labels(RRDHOST *host) {
  284. if (!host->labels || !(host->labels_flag & LABEL_FLAG_UPDATE_STREAM) || (host->labels_flag & LABEL_FLAG_STOP_STREAM))
  285. return;
  286. sender_start(host->sender);
  287. rrdhost_rdlock(host);
  288. netdata_rwlock_rdlock(&host->labels_rwlock);
  289. struct label *labels = host->labels;
  290. while(labels) {
  291. buffer_sprintf(host->sender->build
  292. , "LABEL \"%s\" = %d %s\n"
  293. , labels->key
  294. , (int)labels->label_source
  295. , labels->value);
  296. labels = labels->next;
  297. }
  298. buffer_sprintf(host->sender->build
  299. , "OVERWRITE %s\n", "labels");
  300. netdata_rwlock_unlock(&host->labels_rwlock);
  301. rrdhost_unlock(host);
  302. sender_commit(host->sender);
  303. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1 && write(host->rrdpush_sender_pipe[PIPE_WRITE], " ", 1) == -1)
  304. error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
  305. host->labels_flag &= ~LABEL_FLAG_UPDATE_STREAM;
  306. }
  307. // ----------------------------------------------------------------------------
  308. // rrdpush sender thread
  309. // Either the receiver lost the connection or the host is being destroyed.
  310. // The sender mutex guards thread creation, any spurious data is wiped on reconnection.
  311. void rrdpush_sender_thread_stop(RRDHOST *host) {
  312. netdata_mutex_lock(&host->sender->mutex);
  313. netdata_thread_t thr = 0;
  314. if(host->rrdpush_sender_spawn) {
  315. info("STREAM %s [send]: signaling sending thread to stop...", host->hostname);
  316. // signal the thread that we want to join it
  317. host->rrdpush_sender_join = 1;
  318. // copy the thread id, so that we will be waiting for the right one
  319. // even if a new one has been spawn
  320. thr = host->rrdpush_sender_thread;
  321. // signal it to cancel
  322. netdata_thread_cancel(host->rrdpush_sender_thread);
  323. }
  324. netdata_mutex_unlock(&host->sender->mutex);
  325. if(thr != 0) {
  326. info("STREAM %s [send]: waiting for the sending thread to stop...", host->hostname);
  327. void *result;
  328. netdata_thread_join(thr, &result);
  329. info("STREAM %s [send]: sending thread has exited.", host->hostname);
  330. }
  331. }
  332. // ----------------------------------------------------------------------------
  333. // rrdpush receiver thread
  334. 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) {
  335. 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);
  336. }
  337. static void rrdpush_sender_thread_spawn(RRDHOST *host) {
  338. netdata_mutex_lock(&host->sender->mutex);
  339. if(!host->rrdpush_sender_spawn) {
  340. char tag[NETDATA_THREAD_TAG_MAX + 1];
  341. snprintfz(tag, NETDATA_THREAD_TAG_MAX, "STREAM_SENDER[%s]", host->hostname);
  342. if(netdata_thread_create(&host->rrdpush_sender_thread, tag, NETDATA_THREAD_OPTION_JOINABLE, rrdpush_sender_thread, (void *) host->sender))
  343. error("STREAM %s [send]: failed to create new thread for client.", host->hostname);
  344. else
  345. host->rrdpush_sender_spawn = 1;
  346. }
  347. netdata_mutex_unlock(&host->sender->mutex);
  348. }
  349. int rrdpush_receiver_permission_denied(struct web_client *w) {
  350. // we always respond with the same message and error code
  351. // to prevent an attacker from gaining info about the error
  352. buffer_flush(w->response.data);
  353. buffer_sprintf(w->response.data, "You are not permitted to access this. Check the logs for more info.");
  354. return 401;
  355. }
  356. int rrdpush_receiver_too_busy_now(struct web_client *w) {
  357. // we always respond with the same message and error code
  358. // to prevent an attacker from gaining info about the error
  359. buffer_flush(w->response.data);
  360. buffer_sprintf(w->response.data, "The server is too busy now to accept this request. Try later.");
  361. return 503;
  362. }
  363. void *rrdpush_receiver_thread(void *ptr);
  364. int rrdpush_receiver_thread_spawn(struct web_client *w, char *url) {
  365. info("clients wants to STREAM metrics.");
  366. char *key = NULL, *hostname = NULL, *registry_hostname = NULL, *machine_guid = NULL, *os = "unknown", *timezone = "unknown", *tags = NULL;
  367. int update_every = default_rrd_update_every;
  368. uint32_t stream_version = UINT_MAX;
  369. char buf[GUID_LEN + 1];
  370. struct rrdhost_system_info *system_info = callocz(1, sizeof(struct rrdhost_system_info));
  371. while(url) {
  372. char *value = mystrsep(&url, "&");
  373. if(!value || !*value) continue;
  374. char *name = mystrsep(&value, "=");
  375. if(!name || !*name) continue;
  376. if(!value || !*value) continue;
  377. if(!strcmp(name, "key"))
  378. key = value;
  379. else if(!strcmp(name, "hostname"))
  380. hostname = value;
  381. else if(!strcmp(name, "registry_hostname"))
  382. registry_hostname = value;
  383. else if(!strcmp(name, "machine_guid"))
  384. machine_guid = value;
  385. else if(!strcmp(name, "update_every"))
  386. update_every = (int)strtoul(value, NULL, 0);
  387. else if(!strcmp(name, "os"))
  388. os = value;
  389. else if(!strcmp(name, "timezone"))
  390. timezone = value;
  391. else if(!strcmp(name, "tags"))
  392. tags = value;
  393. else if(!strcmp(name, "ver"))
  394. stream_version = MIN((uint32_t) strtoul(value, NULL, 0), STREAMING_PROTOCOL_CURRENT_VERSION);
  395. else {
  396. // An old Netdata child does not have a compatible streaming protocol, map to something sane.
  397. if (!strcmp(name, "NETDATA_SYSTEM_OS_NAME"))
  398. name = "NETDATA_HOST_OS_NAME";
  399. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID"))
  400. name = "NETDATA_HOST_OS_ID";
  401. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID_LIKE"))
  402. name = "NETDATA_HOST_OS_ID_LIKE";
  403. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION"))
  404. name = "NETDATA_HOST_OS_VERSION";
  405. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION_ID"))
  406. name = "NETDATA_HOST_OS_VERSION_ID";
  407. else if (!strcmp(name, "NETDATA_SYSTEM_OS_DETECTION"))
  408. name = "NETDATA_HOST_OS_DETECTION";
  409. else if(!strcmp(name, "NETDATA_PROTOCOL_VERSION") && stream_version == UINT_MAX) {
  410. stream_version = 1;
  411. }
  412. if (unlikely(rrdhost_set_system_info_variable(system_info, name, value))) {
  413. info("STREAM [receive from [%s]:%s]: request has parameter '%s' = '%s', which is not used.",
  414. w->client_ip, w->client_port, name, value);
  415. }
  416. }
  417. }
  418. if (stream_version == UINT_MAX)
  419. stream_version = 0;
  420. if(!key || !*key) {
  421. rrdhost_system_info_free(system_info);
  422. 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");
  423. error("STREAM [receive from [%s]:%s]: request without an API key. Forbidding access.", w->client_ip, w->client_port);
  424. return rrdpush_receiver_permission_denied(w);
  425. }
  426. if(!hostname || !*hostname) {
  427. rrdhost_system_info_free(system_info);
  428. 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");
  429. error("STREAM [receive from [%s]:%s]: request without a hostname. Forbidding access.", w->client_ip, w->client_port);
  430. return rrdpush_receiver_permission_denied(w);
  431. }
  432. if(!machine_guid || !*machine_guid) {
  433. rrdhost_system_info_free(system_info);
  434. 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");
  435. error("STREAM [receive from [%s]:%s]: request without a machine GUID. Forbidding access.", w->client_ip, w->client_port);
  436. return rrdpush_receiver_permission_denied(w);
  437. }
  438. if(regenerate_guid(key, buf) == -1) {
  439. rrdhost_system_info_free(system_info);
  440. 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");
  441. 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);
  442. return rrdpush_receiver_permission_denied(w);
  443. }
  444. if(regenerate_guid(machine_guid, buf) == -1) {
  445. rrdhost_system_info_free(system_info);
  446. 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");
  447. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not GUID. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  448. return rrdpush_receiver_permission_denied(w);
  449. }
  450. if(!appconfig_get_boolean(&stream_config, key, "enabled", 0)) {
  451. rrdhost_system_info_free(system_info);
  452. 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");
  453. error("STREAM [receive from [%s]:%s]: API key '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, key);
  454. return rrdpush_receiver_permission_denied(w);
  455. }
  456. {
  457. SIMPLE_PATTERN *key_allow_from = simple_pattern_create(appconfig_get(&stream_config, key, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  458. if(key_allow_from) {
  459. if(!simple_pattern_matches(key_allow_from, w->client_ip)) {
  460. simple_pattern_free(key_allow_from);
  461. rrdhost_system_info_free(system_info);
  462. 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");
  463. error("STREAM [receive from [%s]:%s]: API key '%s' is not permitted from this IP. Forbidding access.", w->client_ip, w->client_port, key);
  464. return rrdpush_receiver_permission_denied(w);
  465. }
  466. simple_pattern_free(key_allow_from);
  467. }
  468. }
  469. if(!appconfig_get_boolean(&stream_config, machine_guid, "enabled", 1)) {
  470. rrdhost_system_info_free(system_info);
  471. 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");
  472. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  473. return rrdpush_receiver_permission_denied(w);
  474. }
  475. {
  476. SIMPLE_PATTERN *machine_allow_from = simple_pattern_create(appconfig_get(&stream_config, machine_guid, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  477. if(machine_allow_from) {
  478. if(!simple_pattern_matches(machine_allow_from, w->client_ip)) {
  479. simple_pattern_free(machine_allow_from);
  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 - MACHINE GUID NOT ALLOWED FROM THIS IP");
  482. 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);
  483. return rrdpush_receiver_permission_denied(w);
  484. }
  485. simple_pattern_free(machine_allow_from);
  486. }
  487. }
  488. if(unlikely(web_client_streaming_rate_t > 0)) {
  489. static netdata_mutex_t stream_rate_mutex = NETDATA_MUTEX_INITIALIZER;
  490. static volatile time_t last_stream_accepted_t = 0;
  491. netdata_mutex_lock(&stream_rate_mutex);
  492. time_t now = now_realtime_sec();
  493. if(unlikely(last_stream_accepted_t == 0))
  494. last_stream_accepted_t = now;
  495. if(now - last_stream_accepted_t < web_client_streaming_rate_t) {
  496. netdata_mutex_unlock(&stream_rate_mutex);
  497. rrdhost_system_info_free(system_info);
  498. 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)));
  499. return rrdpush_receiver_too_busy_now(w);
  500. }
  501. last_stream_accepted_t = now;
  502. netdata_mutex_unlock(&stream_rate_mutex);
  503. }
  504. /*
  505. * Quick path for rejecting multiple connections. The lock taken is fine-grained - it only protects the receiver
  506. * pointer within the host (if a host exists). This protects against multiple concurrent web requests hitting
  507. * separate threads within the web-server and landing here. The lock guards the thread-shutdown sequence that
  508. * detaches the receiver from the host. If the host is being created (first time-access) then we also use the
  509. * lock to prevent race-hazard (two threads try to create the host concurrently, one wins and the other does a
  510. * lookup to the now-attached structure).
  511. */
  512. struct receiver_state *rpt = callocz(1, sizeof(*rpt));
  513. RRDHOST *host = rrdhost_find_by_guid(machine_guid, 0);
  514. if (host) {
  515. netdata_mutex_lock(&host->receiver_lock);
  516. if (host->receiver != NULL) {
  517. time_t age = now_realtime_sec() - host->receiver->last_msg_t;
  518. if (age > 30) {
  519. host->receiver->shutdown = 1;
  520. shutdown(host->receiver->fd, SHUT_RDWR);
  521. host->receiver = NULL; // Thread holds reference to structure
  522. info("STREAM %s [receive from [%s]:%s]: multiple connections for same host detected - existing connection is dead (%ld sec), accepting new connection.", host->hostname, w->client_ip, w->client_port, age);
  523. }
  524. else {
  525. netdata_mutex_unlock(&host->receiver_lock);
  526. log_stream_connection(w->client_ip, w->client_port, key, host->machine_guid, host->hostname,
  527. "REJECTED - ALREADY CONNECTED");
  528. info("STREAM %s [receive from [%s]:%s]: multiple connections for same host detected - existing connection is active (within last %ld sec), rejecting new connection.", host->hostname, w->client_ip, w->client_port, age);
  529. // Have not set WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET - caller should clean up
  530. buffer_flush(w->response.data);
  531. buffer_strcat(w->response.data, "This GUID is already streaming to this server");
  532. freez(rpt);
  533. return 409;
  534. }
  535. }
  536. host->receiver = rpt;
  537. netdata_mutex_unlock(&host->receiver_lock);
  538. }
  539. rpt->last_msg_t = now_realtime_sec();
  540. rpt->host = host;
  541. rpt->fd = w->ifd;
  542. rpt->key = strdupz(key);
  543. rpt->hostname = strdupz(hostname);
  544. rpt->registry_hostname = strdupz((registry_hostname && *registry_hostname)?registry_hostname:hostname);
  545. rpt->machine_guid = strdupz(machine_guid);
  546. rpt->os = strdupz(os);
  547. rpt->timezone = strdupz(timezone);
  548. rpt->tags = (tags)?strdupz(tags):NULL;
  549. rpt->client_ip = strdupz(w->client_ip);
  550. rpt->client_port = strdupz(w->client_port);
  551. rpt->update_every = update_every;
  552. rpt->system_info = system_info;
  553. rpt->stream_version = stream_version;
  554. #ifdef ENABLE_HTTPS
  555. rpt->ssl.conn = w->ssl.conn;
  556. rpt->ssl.flags = w->ssl.flags;
  557. w->ssl.conn = NULL;
  558. w->ssl.flags = NETDATA_SSL_START;
  559. #endif
  560. if(w->user_agent && w->user_agent[0]) {
  561. char *t = strchr(w->user_agent, '/');
  562. if(t && *t) {
  563. *t = '\0';
  564. t++;
  565. }
  566. rpt->program_name = strdupz(w->user_agent);
  567. if(t && *t) rpt->program_version = strdupz(t);
  568. }
  569. debug(D_SYSTEM, "starting STREAM receive thread.");
  570. char tag[FILENAME_MAX + 1];
  571. snprintfz(tag, FILENAME_MAX, "STREAM_RECEIVER[%s,[%s]:%s]", rpt->hostname, w->client_ip, w->client_port);
  572. if(netdata_thread_create(&rpt->thread, tag, NETDATA_THREAD_OPTION_DEFAULT, rrdpush_receiver_thread, (void *)rpt))
  573. error("Failed to create new STREAM receive thread for client.");
  574. // prevent the caller from closing the streaming socket
  575. if(web_server_mode == WEB_SERVER_MODE_STATIC_THREADED) {
  576. web_client_flag_set(w, WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET);
  577. }
  578. else {
  579. if(w->ifd == w->ofd)
  580. w->ifd = w->ofd = -1;
  581. else
  582. w->ifd = -1;
  583. }
  584. buffer_flush(w->response.data);
  585. return 200;
  586. }