rrdpush.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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.head || !(host->labels.labels_flag & LABEL_FLAG_UPDATE_STREAM) || (host->labels.labels_flag & LABEL_FLAG_STOP_STREAM))
  285. return;
  286. sender_start(host->sender);
  287. rrdhost_rdlock(host);
  288. netdata_rwlock_rdlock(&host->labels.labels_rwlock);
  289. struct label *label_i = host->labels.head;
  290. while(label_i) {
  291. buffer_sprintf(host->sender->build
  292. , "LABEL \"%s\" = %d %s\n"
  293. , label_i->key
  294. , (int)label_i->label_source
  295. , label_i->value);
  296. label_i = label_i->next;
  297. }
  298. buffer_sprintf(host->sender->build
  299. , "OVERWRITE %s\n", "labels");
  300. netdata_rwlock_unlock(&host->labels.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.labels_flag &= ~LABEL_FLAG_UPDATE_STREAM;
  306. }
  307. void rrdpush_claimed_id(RRDHOST *host)
  308. {
  309. if(unlikely(!host->rrdpush_send_enabled || !host->rrdpush_sender_connected))
  310. return;
  311. if(host->sender->version < STREAM_VERSION_CLAIM)
  312. return;
  313. sender_start(host->sender);
  314. rrdhost_aclk_state_lock(host);
  315. buffer_sprintf(host->sender->build, "CLAIMED_ID %s %s\n", host->machine_guid, (host->aclk_state.claimed_id ? host->aclk_state.claimed_id : "NULL") );
  316. rrdhost_aclk_state_unlock(host);
  317. sender_commit(host->sender);
  318. // signal the sender there are more data
  319. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1 && write(host->rrdpush_sender_pipe[PIPE_WRITE], " ", 1) == -1)
  320. error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
  321. }
  322. // ----------------------------------------------------------------------------
  323. // rrdpush sender thread
  324. // Either the receiver lost the connection or the host is being destroyed.
  325. // The sender mutex guards thread creation, any spurious data is wiped on reconnection.
  326. void rrdpush_sender_thread_stop(RRDHOST *host) {
  327. netdata_mutex_lock(&host->sender->mutex);
  328. netdata_thread_t thr = 0;
  329. if(host->rrdpush_sender_spawn) {
  330. info("STREAM %s [send]: signaling sending thread to stop...", host->hostname);
  331. // signal the thread that we want to join it
  332. host->rrdpush_sender_join = 1;
  333. // copy the thread id, so that we will be waiting for the right one
  334. // even if a new one has been spawn
  335. thr = host->rrdpush_sender_thread;
  336. // signal it to cancel
  337. netdata_thread_cancel(host->rrdpush_sender_thread);
  338. }
  339. netdata_mutex_unlock(&host->sender->mutex);
  340. if(thr != 0) {
  341. info("STREAM %s [send]: waiting for the sending thread to stop...", host->hostname);
  342. void *result;
  343. netdata_thread_join(thr, &result);
  344. info("STREAM %s [send]: sending thread has exited.", host->hostname);
  345. }
  346. }
  347. // ----------------------------------------------------------------------------
  348. // rrdpush receiver thread
  349. 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) {
  350. 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);
  351. }
  352. static void rrdpush_sender_thread_spawn(RRDHOST *host) {
  353. netdata_mutex_lock(&host->sender->mutex);
  354. if(!host->rrdpush_sender_spawn) {
  355. char tag[NETDATA_THREAD_TAG_MAX + 1];
  356. snprintfz(tag, NETDATA_THREAD_TAG_MAX, "STREAM_SENDER[%s]", host->hostname);
  357. if(netdata_thread_create(&host->rrdpush_sender_thread, tag, NETDATA_THREAD_OPTION_JOINABLE, rrdpush_sender_thread, (void *) host->sender))
  358. error("STREAM %s [send]: failed to create new thread for client.", host->hostname);
  359. else
  360. host->rrdpush_sender_spawn = 1;
  361. }
  362. netdata_mutex_unlock(&host->sender->mutex);
  363. }
  364. int rrdpush_receiver_permission_denied(struct web_client *w) {
  365. // we always respond with the same message and error code
  366. // to prevent an attacker from gaining info about the error
  367. buffer_flush(w->response.data);
  368. buffer_sprintf(w->response.data, "You are not permitted to access this. Check the logs for more info.");
  369. return 401;
  370. }
  371. int rrdpush_receiver_too_busy_now(struct web_client *w) {
  372. // we always respond with the same message and error code
  373. // to prevent an attacker from gaining info about the error
  374. buffer_flush(w->response.data);
  375. buffer_sprintf(w->response.data, "The server is too busy now to accept this request. Try later.");
  376. return 503;
  377. }
  378. void *rrdpush_receiver_thread(void *ptr);
  379. int rrdpush_receiver_thread_spawn(struct web_client *w, char *url) {
  380. info("clients wants to STREAM metrics.");
  381. char *key = NULL, *hostname = NULL, *registry_hostname = NULL, *machine_guid = NULL, *os = "unknown", *timezone = "unknown", *tags = NULL;
  382. int update_every = default_rrd_update_every;
  383. uint32_t stream_version = UINT_MAX;
  384. char buf[GUID_LEN + 1];
  385. struct rrdhost_system_info *system_info = callocz(1, sizeof(struct rrdhost_system_info));
  386. while(url) {
  387. char *value = mystrsep(&url, "&");
  388. if(!value || !*value) continue;
  389. char *name = mystrsep(&value, "=");
  390. if(!name || !*name) continue;
  391. if(!value || !*value) continue;
  392. if(!strcmp(name, "key"))
  393. key = value;
  394. else if(!strcmp(name, "hostname"))
  395. hostname = value;
  396. else if(!strcmp(name, "registry_hostname"))
  397. registry_hostname = value;
  398. else if(!strcmp(name, "machine_guid"))
  399. machine_guid = value;
  400. else if(!strcmp(name, "update_every"))
  401. update_every = (int)strtoul(value, NULL, 0);
  402. else if(!strcmp(name, "os"))
  403. os = value;
  404. else if(!strcmp(name, "timezone"))
  405. timezone = value;
  406. else if(!strcmp(name, "tags"))
  407. tags = value;
  408. else if(!strcmp(name, "ver"))
  409. stream_version = MIN((uint32_t) strtoul(value, NULL, 0), STREAMING_PROTOCOL_CURRENT_VERSION);
  410. else {
  411. // An old Netdata child does not have a compatible streaming protocol, map to something sane.
  412. if (!strcmp(name, "NETDATA_SYSTEM_OS_NAME"))
  413. name = "NETDATA_HOST_OS_NAME";
  414. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID"))
  415. name = "NETDATA_HOST_OS_ID";
  416. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID_LIKE"))
  417. name = "NETDATA_HOST_OS_ID_LIKE";
  418. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION"))
  419. name = "NETDATA_HOST_OS_VERSION";
  420. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION_ID"))
  421. name = "NETDATA_HOST_OS_VERSION_ID";
  422. else if (!strcmp(name, "NETDATA_SYSTEM_OS_DETECTION"))
  423. name = "NETDATA_HOST_OS_DETECTION";
  424. else if(!strcmp(name, "NETDATA_PROTOCOL_VERSION") && stream_version == UINT_MAX) {
  425. stream_version = 1;
  426. }
  427. if (unlikely(rrdhost_set_system_info_variable(system_info, name, value))) {
  428. info("STREAM [receive from [%s]:%s]: request has parameter '%s' = '%s', which is not used.",
  429. w->client_ip, w->client_port, name, value);
  430. }
  431. }
  432. }
  433. if (stream_version == UINT_MAX)
  434. stream_version = 0;
  435. if(!key || !*key) {
  436. rrdhost_system_info_free(system_info);
  437. 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");
  438. error("STREAM [receive from [%s]:%s]: request without an API key. Forbidding access.", w->client_ip, w->client_port);
  439. return rrdpush_receiver_permission_denied(w);
  440. }
  441. if(!hostname || !*hostname) {
  442. rrdhost_system_info_free(system_info);
  443. 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");
  444. error("STREAM [receive from [%s]:%s]: request without a hostname. Forbidding access.", w->client_ip, w->client_port);
  445. return rrdpush_receiver_permission_denied(w);
  446. }
  447. if(!machine_guid || !*machine_guid) {
  448. rrdhost_system_info_free(system_info);
  449. 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");
  450. error("STREAM [receive from [%s]:%s]: request without a machine GUID. Forbidding access.", w->client_ip, w->client_port);
  451. return rrdpush_receiver_permission_denied(w);
  452. }
  453. if(regenerate_guid(key, buf) == -1) {
  454. rrdhost_system_info_free(system_info);
  455. 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");
  456. 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);
  457. return rrdpush_receiver_permission_denied(w);
  458. }
  459. if(regenerate_guid(machine_guid, buf) == -1) {
  460. rrdhost_system_info_free(system_info);
  461. 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");
  462. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not GUID. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  463. return rrdpush_receiver_permission_denied(w);
  464. }
  465. if(!appconfig_get_boolean(&stream_config, key, "enabled", 0)) {
  466. rrdhost_system_info_free(system_info);
  467. 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");
  468. error("STREAM [receive from [%s]:%s]: API key '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, key);
  469. return rrdpush_receiver_permission_denied(w);
  470. }
  471. {
  472. SIMPLE_PATTERN *key_allow_from = simple_pattern_create(appconfig_get(&stream_config, key, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  473. if(key_allow_from) {
  474. if(!simple_pattern_matches(key_allow_from, w->client_ip)) {
  475. simple_pattern_free(key_allow_from);
  476. rrdhost_system_info_free(system_info);
  477. 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");
  478. error("STREAM [receive from [%s]:%s]: API key '%s' is not permitted from this IP. Forbidding access.", w->client_ip, w->client_port, key);
  479. return rrdpush_receiver_permission_denied(w);
  480. }
  481. simple_pattern_free(key_allow_from);
  482. }
  483. }
  484. if(!appconfig_get_boolean(&stream_config, machine_guid, "enabled", 1)) {
  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 - MACHINE GUID NOT ENABLED");
  487. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  488. return rrdpush_receiver_permission_denied(w);
  489. }
  490. {
  491. SIMPLE_PATTERN *machine_allow_from = simple_pattern_create(appconfig_get(&stream_config, machine_guid, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  492. if(machine_allow_from) {
  493. if(!simple_pattern_matches(machine_allow_from, w->client_ip)) {
  494. simple_pattern_free(machine_allow_from);
  495. rrdhost_system_info_free(system_info);
  496. 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");
  497. 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);
  498. return rrdpush_receiver_permission_denied(w);
  499. }
  500. simple_pattern_free(machine_allow_from);
  501. }
  502. }
  503. if(unlikely(web_client_streaming_rate_t > 0)) {
  504. static netdata_mutex_t stream_rate_mutex = NETDATA_MUTEX_INITIALIZER;
  505. static volatile time_t last_stream_accepted_t = 0;
  506. netdata_mutex_lock(&stream_rate_mutex);
  507. time_t now = now_realtime_sec();
  508. if(unlikely(last_stream_accepted_t == 0))
  509. last_stream_accepted_t = now;
  510. if(now - last_stream_accepted_t < web_client_streaming_rate_t) {
  511. netdata_mutex_unlock(&stream_rate_mutex);
  512. rrdhost_system_info_free(system_info);
  513. 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)));
  514. return rrdpush_receiver_too_busy_now(w);
  515. }
  516. last_stream_accepted_t = now;
  517. netdata_mutex_unlock(&stream_rate_mutex);
  518. }
  519. /*
  520. * Quick path for rejecting multiple connections. The lock taken is fine-grained - it only protects the receiver
  521. * pointer within the host (if a host exists). This protects against multiple concurrent web requests hitting
  522. * separate threads within the web-server and landing here. The lock guards the thread-shutdown sequence that
  523. * detaches the receiver from the host. If the host is being created (first time-access) then we also use the
  524. * lock to prevent race-hazard (two threads try to create the host concurrently, one wins and the other does a
  525. * lookup to the now-attached structure).
  526. */
  527. struct receiver_state *rpt = callocz(1, sizeof(*rpt));
  528. rrd_rdlock();
  529. RRDHOST *host = rrdhost_find_by_guid(machine_guid, 0);
  530. if (unlikely(host && rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED))) /* Ignore archived hosts. */
  531. host = NULL;
  532. if (host) {
  533. rrdhost_wrlock(host);
  534. netdata_mutex_lock(&host->receiver_lock);
  535. rrdhost_flag_clear(host, RRDHOST_FLAG_ORPHAN);
  536. host->senders_disconnected_time = 0;
  537. if (host->receiver != NULL) {
  538. time_t age = now_realtime_sec() - host->receiver->last_msg_t;
  539. if (age > 30) {
  540. host->receiver->shutdown = 1;
  541. shutdown(host->receiver->fd, SHUT_RDWR);
  542. host->receiver = NULL; // Thread holds reference to structure
  543. 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);
  544. }
  545. else {
  546. netdata_mutex_unlock(&host->receiver_lock);
  547. rrdhost_unlock(host);
  548. rrd_unlock();
  549. log_stream_connection(w->client_ip, w->client_port, key, host->machine_guid, host->hostname,
  550. "REJECTED - ALREADY CONNECTED");
  551. 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);
  552. // Have not set WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET - caller should clean up
  553. buffer_flush(w->response.data);
  554. buffer_strcat(w->response.data, "This GUID is already streaming to this server");
  555. freez(rpt);
  556. return 409;
  557. }
  558. }
  559. host->receiver = rpt;
  560. netdata_mutex_unlock(&host->receiver_lock);
  561. rrdhost_unlock(host);
  562. }
  563. rrd_unlock();
  564. rpt->last_msg_t = now_realtime_sec();
  565. rpt->host = host;
  566. rpt->fd = w->ifd;
  567. rpt->key = strdupz(key);
  568. rpt->hostname = strdupz(hostname);
  569. rpt->registry_hostname = strdupz((registry_hostname && *registry_hostname)?registry_hostname:hostname);
  570. rpt->machine_guid = strdupz(machine_guid);
  571. rpt->os = strdupz(os);
  572. rpt->timezone = strdupz(timezone);
  573. rpt->tags = (tags)?strdupz(tags):NULL;
  574. rpt->client_ip = strdupz(w->client_ip);
  575. rpt->client_port = strdupz(w->client_port);
  576. rpt->update_every = update_every;
  577. rpt->system_info = system_info;
  578. rpt->stream_version = stream_version;
  579. #ifdef ENABLE_HTTPS
  580. rpt->ssl.conn = w->ssl.conn;
  581. rpt->ssl.flags = w->ssl.flags;
  582. w->ssl.conn = NULL;
  583. w->ssl.flags = NETDATA_SSL_START;
  584. #endif
  585. if(w->user_agent && w->user_agent[0]) {
  586. char *t = strchr(w->user_agent, '/');
  587. if(t && *t) {
  588. *t = '\0';
  589. t++;
  590. }
  591. rpt->program_name = strdupz(w->user_agent);
  592. if(t && *t) rpt->program_version = strdupz(t);
  593. }
  594. debug(D_SYSTEM, "starting STREAM receive thread.");
  595. char tag[FILENAME_MAX + 1];
  596. snprintfz(tag, FILENAME_MAX, "STREAM_RECEIVER[%s,[%s]:%s]", rpt->hostname, w->client_ip, w->client_port);
  597. if(netdata_thread_create(&rpt->thread, tag, NETDATA_THREAD_OPTION_DEFAULT, rrdpush_receiver_thread, (void *)rpt))
  598. error("Failed to create new STREAM receive thread for client.");
  599. // prevent the caller from closing the streaming socket
  600. if(web_server_mode == WEB_SERVER_MODE_STATIC_THREADED) {
  601. web_client_flag_set(w, WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET);
  602. }
  603. else {
  604. if(w->ifd == w->ofd)
  605. w->ifd = w->ofd = -1;
  606. else
  607. w->ifd = -1;
  608. }
  609. buffer_flush(w->response.data);
  610. return 200;
  611. }