rrdpush.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "rrdpush.h"
  3. /*
  4. * rrdpush
  5. *
  6. * 3 threads are involved for all stream operations
  7. *
  8. * 1. a random data collection thread, calling rrdset_done_push()
  9. * this is called for each chart.
  10. *
  11. * the output of this work is kept in a thread BUFFER
  12. * the sender thread is signalled via a pipe (in RRDHOST)
  13. *
  14. * 2. a sender thread running at the sending netdata
  15. * this is spawned automatically on the first chart to be pushed
  16. *
  17. * It tries to push the metrics to the remote netdata, as fast
  18. * as possible (i.e. immediately after they are collected).
  19. *
  20. * 3. a receiver thread, running at the receiving netdata
  21. * this is spawned automatically when the sender connects to
  22. * the receiver.
  23. *
  24. */
  25. struct config stream_config = {
  26. .first_section = NULL,
  27. .last_section = NULL,
  28. .mutex = NETDATA_MUTEX_INITIALIZER,
  29. .index = {
  30. .avl_tree = {
  31. .root = NULL,
  32. .compar = appconfig_section_compare
  33. },
  34. .rwlock = AVL_LOCK_INITIALIZER
  35. }
  36. };
  37. unsigned int default_rrdpush_enabled = 0;
  38. #ifdef ENABLE_COMPRESSION
  39. unsigned int default_compression_enabled = 1;
  40. #endif
  41. char *default_rrdpush_destination = NULL;
  42. char *default_rrdpush_api_key = NULL;
  43. char *default_rrdpush_send_charts_matching = NULL;
  44. bool default_rrdpush_enable_replication = true;
  45. time_t default_rrdpush_seconds_to_replicate = 86400;
  46. time_t default_rrdpush_replication_step = 600;
  47. #ifdef ENABLE_HTTPS
  48. char *netdata_ssl_ca_path = NULL;
  49. char *netdata_ssl_ca_file = NULL;
  50. #endif
  51. static void load_stream_conf() {
  52. errno = 0;
  53. char *filename = strdupz_path_subpath(netdata_configured_user_config_dir, "stream.conf");
  54. if(!appconfig_load(&stream_config, filename, 0, NULL)) {
  55. info("CONFIG: cannot load user config '%s'. Will try stock config.", filename);
  56. freez(filename);
  57. filename = strdupz_path_subpath(netdata_configured_stock_config_dir, "stream.conf");
  58. if(!appconfig_load(&stream_config, filename, 0, NULL))
  59. info("CONFIG: cannot load stock config '%s'. Running with internal defaults.", filename);
  60. }
  61. freez(filename);
  62. }
  63. STREAM_CAPABILITIES stream_our_capabilities() {
  64. return STREAM_CAP_V1 |
  65. STREAM_CAP_V2 |
  66. STREAM_CAP_VN |
  67. STREAM_CAP_VCAPS |
  68. STREAM_CAP_HLABELS |
  69. STREAM_CAP_CLAIM |
  70. STREAM_CAP_CLABELS |
  71. STREAM_CAP_FUNCTIONS |
  72. STREAM_CAP_REPLICATION |
  73. STREAM_CAP_BINARY |
  74. STREAM_CAP_INTERPOLATED |
  75. STREAM_HAS_COMPRESSION |
  76. (ieee754_doubles ? STREAM_CAP_IEEE754 : 0) |
  77. 0;
  78. }
  79. bool rrdpush_receiver_needs_dbengine() {
  80. struct section *co;
  81. for(co = stream_config.first_section; co; co = co->next) {
  82. if(strcmp(co->name, "stream") == 0)
  83. continue; // the first section is not relevant
  84. char *s;
  85. s = appconfig_get_by_section(co, "enabled", NULL);
  86. if(!s || !appconfig_test_boolean_value(s))
  87. continue;
  88. s = appconfig_get_by_section(co, "default memory mode", NULL);
  89. if(s && strcmp(s, "dbengine") == 0)
  90. return true;
  91. s = appconfig_get_by_section(co, "memory mode", NULL);
  92. if(s && strcmp(s, "dbengine") == 0)
  93. return true;
  94. }
  95. return false;
  96. }
  97. int rrdpush_init() {
  98. // --------------------------------------------------------------------
  99. // load stream.conf
  100. load_stream_conf();
  101. default_rrdpush_enabled = (unsigned int)appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM, "enabled", default_rrdpush_enabled);
  102. default_rrdpush_destination = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "destination", "");
  103. default_rrdpush_api_key = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "api key", "");
  104. default_rrdpush_send_charts_matching = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "send charts matching", "*");
  105. default_rrdpush_enable_replication = config_get_boolean(CONFIG_SECTION_DB, "enable replication", default_rrdpush_enable_replication);
  106. default_rrdpush_seconds_to_replicate = config_get_number(CONFIG_SECTION_DB, "seconds to replicate", default_rrdpush_seconds_to_replicate);
  107. default_rrdpush_replication_step = config_get_number(CONFIG_SECTION_DB, "seconds per replication step", default_rrdpush_replication_step);
  108. rrdhost_free_orphan_time_s = config_get_number(CONFIG_SECTION_DB, "cleanup orphan hosts after secs", rrdhost_free_orphan_time_s);
  109. #ifdef ENABLE_COMPRESSION
  110. default_compression_enabled = (unsigned int)appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM,
  111. "enable compression", default_compression_enabled);
  112. #endif
  113. if(default_rrdpush_enabled && (!default_rrdpush_destination || !*default_rrdpush_destination || !default_rrdpush_api_key || !*default_rrdpush_api_key)) {
  114. error("STREAM [send]: cannot enable sending thread - information is missing.");
  115. default_rrdpush_enabled = 0;
  116. }
  117. #ifdef ENABLE_HTTPS
  118. netdata_ssl_validate_certificate_sender = !appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM, "ssl skip certificate verification", !netdata_ssl_validate_certificate);
  119. if(!netdata_ssl_validate_certificate_sender)
  120. info("SSL: streaming senders will skip SSL certificates verification.");
  121. netdata_ssl_ca_path = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "CApath", NULL);
  122. netdata_ssl_ca_file = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "CAfile", NULL);
  123. #endif
  124. return default_rrdpush_enabled;
  125. }
  126. // data collection happens from multiple threads
  127. // each of these threads calls rrdset_done()
  128. // which in turn calls rrdset_done_push()
  129. // which uses this pipe to notify the streaming thread
  130. // that there are more data ready to be sent
  131. #define PIPE_READ 0
  132. #define PIPE_WRITE 1
  133. // to have the remote netdata re-sync the charts
  134. // to its current clock, we send for this many
  135. // iterations a BEGIN line without microseconds
  136. // this is for the first iterations of each chart
  137. unsigned int remote_clock_resync_iterations = 60;
  138. static inline bool should_send_chart_matching(RRDSET *st, RRDSET_FLAGS flags) {
  139. if(!(flags & RRDSET_FLAG_RECEIVER_REPLICATION_FINISHED))
  140. return false;
  141. if(unlikely(!(flags & (RRDSET_FLAG_UPSTREAM_SEND | RRDSET_FLAG_UPSTREAM_IGNORE)))) {
  142. RRDHOST *host = st->rrdhost;
  143. if (flags & RRDSET_FLAG_ANOMALY_DETECTION) {
  144. if(ml_streaming_enabled())
  145. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_SEND);
  146. else
  147. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  148. }
  149. else if(simple_pattern_matches_string(host->rrdpush_send_charts_matching, st->id) ||
  150. simple_pattern_matches_string(host->rrdpush_send_charts_matching, st->name))
  151. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_SEND);
  152. else
  153. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  154. // get the flags again, to know how to respond
  155. flags = rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_SEND|RRDSET_FLAG_UPSTREAM_IGNORE);
  156. }
  157. return flags & RRDSET_FLAG_UPSTREAM_SEND;
  158. }
  159. int configured_as_parent() {
  160. struct section *section = NULL;
  161. int is_parent = 0;
  162. appconfig_wrlock(&stream_config);
  163. for (section = stream_config.first_section; section; section = section->next) {
  164. uuid_t uuid;
  165. if (uuid_parse(section->name, uuid) != -1 &&
  166. appconfig_get_boolean_by_section(section, "enabled", 0)) {
  167. is_parent = 1;
  168. break;
  169. }
  170. }
  171. appconfig_unlock(&stream_config);
  172. return is_parent;
  173. }
  174. // chart labels
  175. static int send_clabels_callback(const char *name, const char *value, RRDLABEL_SRC ls, void *data) {
  176. BUFFER *wb = (BUFFER *)data;
  177. buffer_sprintf(wb, "CLABEL \"%s\" \"%s\" %d\n", name, value, ls);
  178. return 1;
  179. }
  180. static void rrdpush_send_clabels(BUFFER *wb, RRDSET *st) {
  181. if (st->rrdlabels) {
  182. if(rrdlabels_walkthrough_read(st->rrdlabels, send_clabels_callback, wb) > 0)
  183. buffer_sprintf(wb, "CLABEL_COMMIT\n");
  184. }
  185. }
  186. // Send the current chart definition.
  187. // Assumes that collector thread has already called sender_start for mutex / buffer state.
  188. static inline bool rrdpush_send_chart_definition(BUFFER *wb, RRDSET *st) {
  189. bool replication_progress = false;
  190. RRDHOST *host = st->rrdhost;
  191. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  192. // properly set the name for the remote end to parse it
  193. char *name = "";
  194. if(likely(st->name)) {
  195. if(unlikely(st->id != st->name)) {
  196. // they differ
  197. name = strchr(rrdset_name(st), '.');
  198. if(name)
  199. name++;
  200. else
  201. name = "";
  202. }
  203. }
  204. // send the chart
  205. buffer_sprintf(
  206. wb
  207. , "CHART \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" %ld %d \"%s %s %s %s\" \"%s\" \"%s\"\n"
  208. , rrdset_id(st)
  209. , name
  210. , rrdset_title(st)
  211. , rrdset_units(st)
  212. , rrdset_family(st)
  213. , rrdset_context(st)
  214. , rrdset_type_name(st->chart_type)
  215. , st->priority
  216. , st->update_every
  217. , rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE)?"obsolete":""
  218. , rrdset_flag_check(st, RRDSET_FLAG_DETAIL)?"detail":""
  219. , rrdset_flag_check(st, RRDSET_FLAG_STORE_FIRST)?"store_first":""
  220. , rrdset_flag_check(st, RRDSET_FLAG_HIDDEN)?"hidden":""
  221. , rrdset_plugin_name(st)
  222. , rrdset_module_name(st)
  223. );
  224. // send the chart labels
  225. if (stream_has_capability(host->sender, STREAM_CAP_CLABELS))
  226. rrdpush_send_clabels(wb, st);
  227. // send the dimensions
  228. RRDDIM *rd;
  229. rrddim_foreach_read(rd, st) {
  230. buffer_sprintf(
  231. wb
  232. , "DIMENSION \"%s\" \"%s\" \"%s\" " COLLECTED_NUMBER_FORMAT " " COLLECTED_NUMBER_FORMAT " \"%s %s %s\"\n"
  233. , rrddim_id(rd)
  234. , rrddim_name(rd)
  235. , rrd_algorithm_name(rd->algorithm)
  236. , rd->multiplier
  237. , rd->divisor
  238. , rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE)?"obsolete":""
  239. , rrddim_option_check(rd, RRDDIM_OPTION_HIDDEN)?"hidden":""
  240. , rrddim_option_check(rd, RRDDIM_OPTION_DONT_DETECT_RESETS_OR_OVERFLOWS)?"noreset":""
  241. );
  242. rd->exposed = 1;
  243. }
  244. rrddim_foreach_done(rd);
  245. // send the chart functions
  246. if(stream_has_capability(host->sender, STREAM_CAP_FUNCTIONS))
  247. rrd_functions_expose_rrdpush(st, wb);
  248. // send the chart local custom variables
  249. rrdsetvar_print_to_streaming_custom_chart_variables(st, wb);
  250. if (stream_has_capability(host->sender, STREAM_CAP_REPLICATION)) {
  251. time_t db_first_time_t, db_last_time_t;
  252. time_t now = now_realtime_sec();
  253. rrdset_get_retention_of_tier_for_collected_chart(st, &db_first_time_t, &db_last_time_t, now, 0);
  254. buffer_sprintf(wb, PLUGINSD_KEYWORD_CHART_DEFINITION_END " %llu %llu %llu\n",
  255. (unsigned long long)db_first_time_t,
  256. (unsigned long long)db_last_time_t,
  257. (unsigned long long)now);
  258. if(!rrdset_flag_check(st, RRDSET_FLAG_SENDER_REPLICATION_IN_PROGRESS)) {
  259. rrdset_flag_set(st, RRDSET_FLAG_SENDER_REPLICATION_IN_PROGRESS);
  260. rrdset_flag_clear(st, RRDSET_FLAG_SENDER_REPLICATION_FINISHED);
  261. rrdhost_sender_replicating_charts_plus_one(st->rrdhost);
  262. }
  263. replication_progress = true;
  264. #ifdef NETDATA_LOG_REPLICATION_REQUESTS
  265. internal_error(true, "REPLAY: 'host:%s/chart:%s' replication starts",
  266. rrdhost_hostname(st->rrdhost), rrdset_id(st));
  267. #endif
  268. }
  269. st->upstream_resync_time_s = st->last_collected_time.tv_sec + (remote_clock_resync_iterations * st->update_every);
  270. return replication_progress;
  271. }
  272. // sends the current chart dimensions
  273. static void rrdpush_send_chart_metrics(BUFFER *wb, RRDSET *st, struct sender_state *s __maybe_unused, RRDSET_FLAGS flags) {
  274. buffer_fast_strcat(wb, "BEGIN \"", 7);
  275. buffer_fast_strcat(wb, rrdset_id(st), string_strlen(st->id));
  276. buffer_fast_strcat(wb, "\" ", 2);
  277. if(st->last_collected_time.tv_sec > st->upstream_resync_time_s)
  278. buffer_print_uint64(wb, st->usec_since_last_update);
  279. else
  280. buffer_fast_strcat(wb, "0", 1);
  281. buffer_fast_strcat(wb, "\n", 1);
  282. RRDDIM *rd;
  283. rrddim_foreach_read(rd, st) {
  284. if(unlikely(!rd->updated))
  285. continue;
  286. if(likely(rd->exposed)) {
  287. buffer_fast_strcat(wb, "SET \"", 5);
  288. buffer_fast_strcat(wb, rrddim_id(rd), string_strlen(rd->id));
  289. buffer_fast_strcat(wb, "\" = ", 4);
  290. buffer_print_int64(wb, rd->collected_value);
  291. buffer_fast_strcat(wb, "\n", 1);
  292. }
  293. else {
  294. internal_error(true, "STREAM: 'host:%s/chart:%s/dim:%s' flag 'exposed' is updated but not exposed",
  295. rrdhost_hostname(st->rrdhost), rrdset_id(st), rrddim_id(rd));
  296. // we will include it in the next iteration
  297. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  298. }
  299. }
  300. rrddim_foreach_done(rd);
  301. if(unlikely(flags & RRDSET_FLAG_UPSTREAM_SEND_VARIABLES))
  302. rrdsetvar_print_to_streaming_custom_chart_variables(st, wb);
  303. buffer_fast_strcat(wb, "END\n", 4);
  304. }
  305. static void rrdpush_sender_thread_spawn(RRDHOST *host);
  306. // Called from the internal collectors to mark a chart obsolete.
  307. bool rrdset_push_chart_definition_now(RRDSET *st) {
  308. RRDHOST *host = st->rrdhost;
  309. if(unlikely(!rrdhost_can_send_definitions_to_parent(host)
  310. || !should_send_chart_matching(st, __atomic_load_n(&st->flags, __ATOMIC_SEQ_CST))))
  311. return false;
  312. BUFFER *wb = sender_start(host->sender);
  313. rrdpush_send_chart_definition(wb, st);
  314. sender_commit(host->sender, wb, STREAM_TRAFFIC_TYPE_METADATA);
  315. sender_thread_buffer_free();
  316. return true;
  317. }
  318. void rrdset_push_metrics_v1(RRDSET_STREAM_BUFFER *rsb, RRDSET *st) {
  319. RRDHOST *host = st->rrdhost;
  320. rrdpush_send_chart_metrics(rsb->wb, st, host->sender, rsb->rrdset_flags);
  321. }
  322. void rrddim_push_metrics_v2(RRDSET_STREAM_BUFFER *rsb, RRDDIM *rd, usec_t point_end_time_ut, NETDATA_DOUBLE n, SN_FLAGS flags) {
  323. if(!rsb->wb || !rsb->v2 || !netdata_double_isnumber(n) || !does_storage_number_exist(flags))
  324. return;
  325. NUMBER_ENCODING integer_encoding = stream_has_capability(rsb, STREAM_CAP_IEEE754) ? NUMBER_ENCODING_BASE64 : NUMBER_ENCODING_HEX;
  326. NUMBER_ENCODING doubles_encoding = stream_has_capability(rsb, STREAM_CAP_IEEE754) ? NUMBER_ENCODING_BASE64 : NUMBER_ENCODING_DECIMAL;
  327. BUFFER *wb = rsb->wb;
  328. time_t point_end_time_s = (time_t)(point_end_time_ut / USEC_PER_SEC);
  329. if(unlikely(rsb->last_point_end_time_s != point_end_time_s)) {
  330. if(unlikely(rsb->begin_v2_added))
  331. buffer_fast_strcat(wb, PLUGINSD_KEYWORD_END_V2 "\n", sizeof(PLUGINSD_KEYWORD_END_V2) - 1 + 1);
  332. buffer_fast_strcat(wb, PLUGINSD_KEYWORD_BEGIN_V2 " '", sizeof(PLUGINSD_KEYWORD_BEGIN_V2) - 1 + 2);
  333. buffer_fast_strcat(wb, rrdset_id(rd->rrdset), string_strlen(rd->rrdset->id));
  334. buffer_fast_strcat(wb, "' ", 2);
  335. buffer_print_uint64_encoded(wb, integer_encoding, rd->rrdset->update_every);
  336. buffer_fast_strcat(wb, " ", 1);
  337. buffer_print_uint64_encoded(wb, integer_encoding, point_end_time_s);
  338. buffer_fast_strcat(wb, " ", 1);
  339. if(point_end_time_s == rsb->wall_clock_time)
  340. buffer_fast_strcat(wb, "#", 1);
  341. else
  342. buffer_print_uint64_encoded(wb, integer_encoding, rsb->wall_clock_time);
  343. buffer_fast_strcat(wb, "\n", 1);
  344. rsb->last_point_end_time_s = point_end_time_s;
  345. rsb->begin_v2_added = true;
  346. }
  347. buffer_fast_strcat(wb, PLUGINSD_KEYWORD_SET_V2 " '", sizeof(PLUGINSD_KEYWORD_SET_V2) - 1 + 2);
  348. buffer_fast_strcat(wb, rrddim_id(rd), string_strlen(rd->id));
  349. buffer_fast_strcat(wb, "' ", 2);
  350. buffer_print_int64_encoded(wb, integer_encoding, rd->last_collected_value);
  351. buffer_fast_strcat(wb, " ", 1);
  352. if((NETDATA_DOUBLE)rd->last_collected_value == n)
  353. buffer_fast_strcat(wb, "#", 1);
  354. else
  355. buffer_print_netdata_double_encoded(wb, doubles_encoding, n);
  356. buffer_fast_strcat(wb, " ", 1);
  357. buffer_print_sn_flags(wb, flags, true);
  358. buffer_fast_strcat(wb, "\n", 1);
  359. }
  360. void rrdset_push_metrics_finished(RRDSET_STREAM_BUFFER *rsb, RRDSET *st) {
  361. if(!rsb->wb)
  362. return;
  363. if(rsb->v2 && rsb->begin_v2_added) {
  364. if(unlikely(rsb->rrdset_flags & RRDSET_FLAG_UPSTREAM_SEND_VARIABLES))
  365. rrdsetvar_print_to_streaming_custom_chart_variables(st, rsb->wb);
  366. buffer_fast_strcat(rsb->wb, PLUGINSD_KEYWORD_END_V2 "\n", sizeof(PLUGINSD_KEYWORD_END_V2) - 1 + 1);
  367. }
  368. sender_commit(st->rrdhost->sender, rsb->wb, STREAM_TRAFFIC_TYPE_DATA);
  369. *rsb = (RRDSET_STREAM_BUFFER){ .wb = NULL, };
  370. }
  371. RRDSET_STREAM_BUFFER rrdset_push_metric_initialize(RRDSET *st, time_t wall_clock_time) {
  372. RRDHOST *host = st->rrdhost;
  373. // fetch the flags we need to check with one atomic operation
  374. RRDHOST_FLAGS host_flags = __atomic_load_n(&host->flags, __ATOMIC_SEQ_CST);
  375. // check if we are not connected
  376. if(unlikely(!(host_flags & RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS))) {
  377. if(unlikely(!(host_flags & (RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN | RRDHOST_FLAG_RRDPUSH_RECEIVER_DISCONNECTED))))
  378. rrdpush_sender_thread_spawn(host);
  379. if(unlikely(!(host_flags & RRDHOST_FLAG_RRDPUSH_SENDER_LOGGED_STATUS))) {
  380. rrdhost_flag_set(host, RRDHOST_FLAG_RRDPUSH_SENDER_LOGGED_STATUS);
  381. error("STREAM %s [send]: not ready - collected metrics are not sent to parent.", rrdhost_hostname(host));
  382. }
  383. return (RRDSET_STREAM_BUFFER) { .wb = NULL, };
  384. }
  385. else if(unlikely(host_flags & RRDHOST_FLAG_RRDPUSH_SENDER_LOGGED_STATUS)) {
  386. info("STREAM %s [send]: sending metrics to parent...", rrdhost_hostname(host));
  387. rrdhost_flag_clear(host, RRDHOST_FLAG_RRDPUSH_SENDER_LOGGED_STATUS);
  388. }
  389. RRDSET_FLAGS rrdset_flags = __atomic_load_n(&st->flags, __ATOMIC_SEQ_CST);
  390. bool exposed_upstream = (rrdset_flags & RRDSET_FLAG_UPSTREAM_EXPOSED);
  391. bool replication_in_progress = !(rrdset_flags & RRDSET_FLAG_SENDER_REPLICATION_FINISHED);
  392. if(unlikely((exposed_upstream && replication_in_progress) ||
  393. !should_send_chart_matching(st, rrdset_flags)))
  394. return (RRDSET_STREAM_BUFFER) { .wb = NULL, };
  395. if(unlikely(!exposed_upstream)) {
  396. BUFFER *wb = sender_start(host->sender);
  397. replication_in_progress = rrdpush_send_chart_definition(wb, st);
  398. sender_commit(host->sender, wb, STREAM_TRAFFIC_TYPE_METADATA);
  399. }
  400. if(replication_in_progress)
  401. return (RRDSET_STREAM_BUFFER) { .wb = NULL, };
  402. return (RRDSET_STREAM_BUFFER) {
  403. .capabilities = host->sender->capabilities,
  404. .v2 = stream_has_capability(host->sender, STREAM_CAP_INTERPOLATED),
  405. .rrdset_flags = rrdset_flags,
  406. .wb = sender_start(host->sender),
  407. .wall_clock_time = wall_clock_time,
  408. };
  409. }
  410. // labels
  411. static int send_labels_callback(const char *name, const char *value, RRDLABEL_SRC ls, void *data) {
  412. BUFFER *wb = (BUFFER *)data;
  413. buffer_sprintf(wb, "LABEL \"%s\" = %d \"%s\"\n", name, ls, value);
  414. return 1;
  415. }
  416. void rrdpush_send_host_labels(RRDHOST *host) {
  417. if(unlikely(!rrdhost_can_send_definitions_to_parent(host)
  418. || !stream_has_capability(host->sender, STREAM_CAP_HLABELS)))
  419. return;
  420. BUFFER *wb = sender_start(host->sender);
  421. rrdlabels_walkthrough_read(host->rrdlabels, send_labels_callback, wb);
  422. buffer_sprintf(wb, "OVERWRITE %s\n", "labels");
  423. sender_commit(host->sender, wb, STREAM_TRAFFIC_TYPE_METADATA);
  424. sender_thread_buffer_free();
  425. }
  426. void rrdpush_claimed_id(RRDHOST *host)
  427. {
  428. if(!stream_has_capability(host->sender, STREAM_CAP_CLAIM))
  429. return;
  430. if(unlikely(!rrdhost_can_send_definitions_to_parent(host)))
  431. return;
  432. BUFFER *wb = sender_start(host->sender);
  433. rrdhost_aclk_state_lock(host);
  434. buffer_sprintf(wb, "CLAIMED_ID %s %s\n", host->machine_guid, (host->aclk_state.claimed_id ? host->aclk_state.claimed_id : "NULL") );
  435. rrdhost_aclk_state_unlock(host);
  436. sender_commit(host->sender, wb, STREAM_TRAFFIC_TYPE_METADATA);
  437. sender_thread_buffer_free();
  438. }
  439. int connect_to_one_of_destinations(
  440. RRDHOST *host,
  441. int default_port,
  442. struct timeval *timeout,
  443. size_t *reconnects_counter,
  444. char *connected_to,
  445. size_t connected_to_size,
  446. struct rrdpush_destinations **destination)
  447. {
  448. int sock = -1;
  449. for (struct rrdpush_destinations *d = host->destinations; d; d = d->next) {
  450. time_t now = now_realtime_sec();
  451. if(d->postpone_reconnection_until > now)
  452. continue;
  453. info(
  454. "STREAM %s: connecting to '%s' (default port: %d)...",
  455. rrdhost_hostname(host),
  456. string2str(d->destination),
  457. default_port);
  458. if (reconnects_counter)
  459. *reconnects_counter += 1;
  460. d->last_attempt = now;
  461. sock = connect_to_this(string2str(d->destination), default_port, timeout);
  462. if (sock != -1) {
  463. if (connected_to && connected_to_size)
  464. strncpyz(connected_to, string2str(d->destination), connected_to_size);
  465. *destination = d;
  466. // move the current item to the end of the list
  467. // without this, this destination will break the loop again and again
  468. // not advancing the destinations to find one that may work
  469. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(host->destinations, d, prev, next);
  470. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(host->destinations, d, prev, next);
  471. break;
  472. }
  473. }
  474. return sock;
  475. }
  476. struct destinations_init_tmp {
  477. RRDHOST *host;
  478. struct rrdpush_destinations *list;
  479. int count;
  480. };
  481. bool destinations_init_add_one(char *entry, void *data) {
  482. struct destinations_init_tmp *t = data;
  483. struct rrdpush_destinations *d = callocz(1, sizeof(struct rrdpush_destinations));
  484. char *colon_ssl = strstr(entry, ":SSL");
  485. if(colon_ssl) {
  486. *colon_ssl = '\0';
  487. d->ssl = true;
  488. }
  489. else
  490. d->ssl = false;
  491. d->destination = string_strdupz(entry);
  492. __atomic_add_fetch(&netdata_buffers_statistics.rrdhost_senders, sizeof(struct rrdpush_destinations), __ATOMIC_RELAXED);
  493. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(t->list, d, prev, next);
  494. t->count++;
  495. info("STREAM: added streaming destination No %d: '%s' to host '%s'", t->count, string2str(d->destination), rrdhost_hostname(t->host));
  496. return false; // we return false, so that we will get all defined destinations
  497. }
  498. void rrdpush_destinations_init(RRDHOST *host) {
  499. if(!host->rrdpush_send_destination) return;
  500. rrdpush_destinations_free(host);
  501. struct destinations_init_tmp t = {
  502. .host = host,
  503. .list = NULL,
  504. .count = 0,
  505. };
  506. foreach_entry_in_connection_string(host->rrdpush_send_destination, destinations_init_add_one, &t);
  507. host->destinations = t.list;
  508. }
  509. void rrdpush_destinations_free(RRDHOST *host) {
  510. while (host->destinations) {
  511. struct rrdpush_destinations *tmp = host->destinations;
  512. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(host->destinations, tmp, prev, next);
  513. string_freez(tmp->destination);
  514. freez(tmp);
  515. __atomic_sub_fetch(&netdata_buffers_statistics.rrdhost_senders, sizeof(struct rrdpush_destinations), __ATOMIC_RELAXED);
  516. }
  517. host->destinations = NULL;
  518. }
  519. // ----------------------------------------------------------------------------
  520. // rrdpush sender thread
  521. // Either the receiver lost the connection or the host is being destroyed.
  522. // The sender mutex guards thread creation, any spurious data is wiped on reconnection.
  523. void rrdpush_sender_thread_stop(RRDHOST *host, const char *reason, bool wait) {
  524. if (!host->sender)
  525. return;
  526. netdata_mutex_lock(&host->sender->mutex);
  527. if(rrdhost_flag_check(host, RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN)) {
  528. host->sender->exit.shutdown = true;
  529. host->sender->exit.reason = reason;
  530. // signal it to cancel
  531. netdata_thread_cancel(host->rrdpush_sender_thread);
  532. }
  533. netdata_mutex_unlock(&host->sender->mutex);
  534. if(wait) {
  535. netdata_mutex_lock(&host->sender->mutex);
  536. while(host->sender->tid) {
  537. netdata_mutex_unlock(&host->sender->mutex);
  538. sleep_usec(10 * USEC_PER_MS);
  539. netdata_mutex_lock(&host->sender->mutex);
  540. }
  541. netdata_mutex_unlock(&host->sender->mutex);
  542. }
  543. }
  544. // ----------------------------------------------------------------------------
  545. // rrdpush receiver thread
  546. 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) {
  547. 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);
  548. }
  549. static void rrdpush_sender_thread_spawn(RRDHOST *host) {
  550. netdata_mutex_lock(&host->sender->mutex);
  551. if(!rrdhost_flag_check(host, RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN)) {
  552. char tag[NETDATA_THREAD_TAG_MAX + 1];
  553. snprintfz(tag, NETDATA_THREAD_TAG_MAX, THREAD_TAG_STREAM_SENDER "[%s]", rrdhost_hostname(host));
  554. if(netdata_thread_create(&host->rrdpush_sender_thread, tag, NETDATA_THREAD_OPTION_DEFAULT, rrdpush_sender_thread, (void *) host->sender))
  555. error("STREAM %s [send]: failed to create new thread for client.", rrdhost_hostname(host));
  556. else
  557. rrdhost_flag_set(host, RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN);
  558. }
  559. netdata_mutex_unlock(&host->sender->mutex);
  560. }
  561. int rrdpush_receiver_permission_denied(struct web_client *w) {
  562. // we always respond with the same message and error code
  563. // to prevent an attacker from gaining info about the error
  564. buffer_flush(w->response.data);
  565. buffer_strcat(w->response.data, START_STREAMING_ERROR_NOT_PERMITTED);
  566. return HTTP_RESP_UNAUTHORIZED;
  567. }
  568. int rrdpush_receiver_too_busy_now(struct web_client *w) {
  569. // we always respond with the same message and error code
  570. // to prevent an attacker from gaining info about the error
  571. buffer_flush(w->response.data);
  572. buffer_strcat(w->response.data, START_STREAMING_ERROR_BUSY_TRY_LATER);
  573. return HTTP_RESP_SERVICE_UNAVAILABLE;
  574. }
  575. static void rrdpush_receiver_takeover_web_connection(struct web_client *w, struct receiver_state *rpt) {
  576. rpt->fd = w->ifd;
  577. #ifdef ENABLE_HTTPS
  578. rpt->ssl.conn = w->ssl.conn;
  579. rpt->ssl.state = w->ssl.state;
  580. w->ssl = NETDATA_SSL_UNSET_CONNECTION;
  581. #endif
  582. WEB_CLIENT_IS_DEAD(w);
  583. if(web_server_mode == WEB_SERVER_MODE_STATIC_THREADED) {
  584. web_client_flag_set(w, WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET);
  585. }
  586. else {
  587. if(w->ifd == w->ofd)
  588. w->ifd = w->ofd = -1;
  589. else
  590. w->ifd = -1;
  591. }
  592. buffer_flush(w->response.data);
  593. }
  594. void *rrdpush_receiver_thread(void *ptr);
  595. int rrdpush_receiver_thread_spawn(struct web_client *w, char *decoded_query_string) {
  596. if(!service_running(ABILITY_STREAMING_CONNECTIONS))
  597. return rrdpush_receiver_too_busy_now(w);
  598. struct receiver_state *rpt = callocz(1, sizeof(*rpt));
  599. rpt->last_msg_t = now_realtime_sec();
  600. rpt->capabilities = STREAM_CAP_INVALID;
  601. rpt->hops = 1;
  602. __atomic_add_fetch(&netdata_buffers_statistics.rrdhost_receivers, sizeof(*rpt), __ATOMIC_RELAXED);
  603. __atomic_add_fetch(&netdata_buffers_statistics.rrdhost_allocations_size, sizeof(struct rrdhost_system_info), __ATOMIC_RELAXED);
  604. rpt->system_info = callocz(1, sizeof(struct rrdhost_system_info));
  605. rpt->system_info->hops = rpt->hops;
  606. rpt->fd = -1;
  607. rpt->client_ip = strdupz(w->client_ip);
  608. rpt->client_port = strdupz(w->client_port);
  609. #ifdef ENABLE_HTTPS
  610. rpt->ssl = NETDATA_SSL_UNSET_CONNECTION;
  611. #endif
  612. rpt->config.update_every = default_rrd_update_every;
  613. // parse the parameters and fill rpt and rpt->system_info
  614. while(decoded_query_string) {
  615. char *value = strsep_skip_consecutive_separators(&decoded_query_string, "&");
  616. if(!value || !*value) continue;
  617. char *name = strsep_skip_consecutive_separators(&value, "=");
  618. if(!name || !*name) continue;
  619. if(!value || !*value) continue;
  620. if(!strcmp(name, "key") && !rpt->key)
  621. rpt->key = strdupz(value);
  622. else if(!strcmp(name, "hostname") && !rpt->hostname)
  623. rpt->hostname = strdupz(value);
  624. else if(!strcmp(name, "registry_hostname") && !rpt->registry_hostname)
  625. rpt->registry_hostname = strdupz(value);
  626. else if(!strcmp(name, "machine_guid") && !rpt->machine_guid)
  627. rpt->machine_guid = strdupz(value);
  628. else if(!strcmp(name, "update_every"))
  629. rpt->config.update_every = (int)strtoul(value, NULL, 0);
  630. else if(!strcmp(name, "os") && !rpt->os)
  631. rpt->os = strdupz(value);
  632. else if(!strcmp(name, "timezone") && !rpt->timezone)
  633. rpt->timezone = strdupz(value);
  634. else if(!strcmp(name, "abbrev_timezone") && !rpt->abbrev_timezone)
  635. rpt->abbrev_timezone = strdupz(value);
  636. else if(!strcmp(name, "utc_offset"))
  637. rpt->utc_offset = (int32_t)strtol(value, NULL, 0);
  638. else if(!strcmp(name, "hops"))
  639. rpt->hops = rpt->system_info->hops = (uint16_t) strtoul(value, NULL, 0);
  640. else if(!strcmp(name, "ml_capable"))
  641. rpt->system_info->ml_capable = strtoul(value, NULL, 0);
  642. else if(!strcmp(name, "ml_enabled"))
  643. rpt->system_info->ml_enabled = strtoul(value, NULL, 0);
  644. else if(!strcmp(name, "mc_version"))
  645. rpt->system_info->mc_version = strtoul(value, NULL, 0);
  646. else if(!strcmp(name, "tags") && !rpt->tags)
  647. rpt->tags = strdupz(value);
  648. else if(!strcmp(name, "ver") && (rpt->capabilities & STREAM_CAP_INVALID))
  649. rpt->capabilities = convert_stream_version_to_capabilities(strtoul(value, NULL, 0));
  650. else {
  651. // An old Netdata child does not have a compatible streaming protocol, map to something sane.
  652. if (!strcmp(name, "NETDATA_SYSTEM_OS_NAME"))
  653. name = "NETDATA_HOST_OS_NAME";
  654. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID"))
  655. name = "NETDATA_HOST_OS_ID";
  656. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID_LIKE"))
  657. name = "NETDATA_HOST_OS_ID_LIKE";
  658. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION"))
  659. name = "NETDATA_HOST_OS_VERSION";
  660. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION_ID"))
  661. name = "NETDATA_HOST_OS_VERSION_ID";
  662. else if (!strcmp(name, "NETDATA_SYSTEM_OS_DETECTION"))
  663. name = "NETDATA_HOST_OS_DETECTION";
  664. else if(!strcmp(name, "NETDATA_PROTOCOL_VERSION") && (rpt->capabilities & STREAM_CAP_INVALID))
  665. rpt->capabilities = convert_stream_version_to_capabilities(1);
  666. if (unlikely(rrdhost_set_system_info_variable(rpt->system_info, name, value))) {
  667. info("STREAM '%s' [receive from [%s]:%s]: "
  668. "request has parameter '%s' = '%s', which is not used."
  669. , (rpt->hostname && *rpt->hostname) ? rpt->hostname : "-"
  670. , rpt->client_ip, rpt->client_port
  671. , name, value);
  672. }
  673. }
  674. }
  675. if (rpt->capabilities & STREAM_CAP_INVALID)
  676. // no version is supplied, assume version 0;
  677. rpt->capabilities = convert_stream_version_to_capabilities(0);
  678. // find the program name and version
  679. if(w->user_agent && w->user_agent[0]) {
  680. char *t = strchr(w->user_agent, '/');
  681. if(t && *t) {
  682. *t = '\0';
  683. t++;
  684. }
  685. rpt->program_name = strdupz(w->user_agent);
  686. if(t && *t) rpt->program_version = strdupz(t);
  687. }
  688. // check if we should accept this connection
  689. if(!rpt->key || !*rpt->key) {
  690. rrdpush_receive_log_status(
  691. rpt,
  692. "request without an API key",
  693. "NO API KEY PERMISSION DENIED");
  694. receiver_state_free(rpt);
  695. return rrdpush_receiver_permission_denied(w);
  696. }
  697. if(!rpt->hostname || !*rpt->hostname) {
  698. rrdpush_receive_log_status(
  699. rpt,
  700. "request without a hostname",
  701. "NO HOSTNAME PERMISSION DENIED");
  702. receiver_state_free(rpt);
  703. return rrdpush_receiver_permission_denied(w);
  704. }
  705. if(!rpt->registry_hostname)
  706. rpt->registry_hostname = strdupz(rpt->hostname);
  707. if(!rpt->machine_guid || !*rpt->machine_guid) {
  708. rrdpush_receive_log_status(
  709. rpt,
  710. "request without a machine GUID",
  711. "NO MACHINE GUID PERMISSION DENIED");
  712. receiver_state_free(rpt);
  713. return rrdpush_receiver_permission_denied(w);
  714. }
  715. {
  716. char buf[GUID_LEN + 1];
  717. if (regenerate_guid(rpt->key, buf) == -1) {
  718. rrdpush_receive_log_status(
  719. rpt,
  720. "API key is not a valid UUID (use the command uuidgen to generate one)",
  721. "INVALID API KEY PERMISSION DENIED");
  722. receiver_state_free(rpt);
  723. return rrdpush_receiver_permission_denied(w);
  724. }
  725. if (regenerate_guid(rpt->machine_guid, buf) == -1) {
  726. rrdpush_receive_log_status(
  727. rpt,
  728. "machine GUID is not a valid UUID",
  729. "INVALID MACHINE GUID PERMISSION DENIED");
  730. receiver_state_free(rpt);
  731. return rrdpush_receiver_permission_denied(w);
  732. }
  733. }
  734. const char *api_key_type = appconfig_get(&stream_config, rpt->key, "type", "api");
  735. if(!api_key_type || !*api_key_type) api_key_type = "unknown";
  736. if(strcmp(api_key_type, "api") != 0) {
  737. rrdpush_receive_log_status(
  738. rpt,
  739. "API key is a machine GUID",
  740. "INVALID API KEY PERMISSION DENIED");
  741. receiver_state_free(rpt);
  742. return rrdpush_receiver_permission_denied(w);
  743. }
  744. if(!appconfig_get_boolean(&stream_config, rpt->key, "enabled", 0)) {
  745. rrdpush_receive_log_status(
  746. rpt,
  747. "API key is not enabled",
  748. "API KEY DISABLED PERMISSION DENIED");
  749. receiver_state_free(rpt);
  750. return rrdpush_receiver_permission_denied(w);
  751. }
  752. {
  753. SIMPLE_PATTERN *key_allow_from = simple_pattern_create(
  754. appconfig_get(&stream_config, rpt->key, "allow from", "*"),
  755. NULL, SIMPLE_PATTERN_EXACT, true);
  756. if(key_allow_from) {
  757. if(!simple_pattern_matches(key_allow_from, w->client_ip)) {
  758. simple_pattern_free(key_allow_from);
  759. rrdpush_receive_log_status(
  760. rpt,
  761. "API key is not allowed from this IP",
  762. "NOT ALLOWED IP PERMISSION DENIED");
  763. receiver_state_free(rpt);
  764. return rrdpush_receiver_permission_denied(w);
  765. }
  766. simple_pattern_free(key_allow_from);
  767. }
  768. }
  769. {
  770. const char *machine_guid_type = appconfig_get(&stream_config, rpt->machine_guid, "type", "machine");
  771. if (!machine_guid_type || !*machine_guid_type) machine_guid_type = "unknown";
  772. if (strcmp(machine_guid_type, "machine") != 0) {
  773. rrdpush_receive_log_status(
  774. rpt,
  775. "machine GUID is an API key",
  776. "INVALID MACHINE GUID PERMISSION DENIED");
  777. receiver_state_free(rpt);
  778. return rrdpush_receiver_permission_denied(w);
  779. }
  780. }
  781. if(!appconfig_get_boolean(&stream_config, rpt->machine_guid, "enabled", 1)) {
  782. rrdpush_receive_log_status(
  783. rpt,
  784. "machine GUID is not enabled",
  785. "MACHINE GUID DISABLED PERMISSION DENIED");
  786. receiver_state_free(rpt);
  787. return rrdpush_receiver_permission_denied(w);
  788. }
  789. {
  790. SIMPLE_PATTERN *machine_allow_from = simple_pattern_create(
  791. appconfig_get(&stream_config, rpt->machine_guid, "allow from", "*"),
  792. NULL, SIMPLE_PATTERN_EXACT, true);
  793. if(machine_allow_from) {
  794. if(!simple_pattern_matches(machine_allow_from, w->client_ip)) {
  795. simple_pattern_free(machine_allow_from);
  796. rrdpush_receive_log_status(
  797. rpt,
  798. "machine GUID is not allowed from this IP",
  799. "NOT ALLOWED IP PERMISSION DENIED");
  800. receiver_state_free(rpt);
  801. return rrdpush_receiver_permission_denied(w);
  802. }
  803. simple_pattern_free(machine_allow_from);
  804. }
  805. }
  806. if (strcmp(rpt->machine_guid, localhost->machine_guid) == 0) {
  807. rrdpush_receiver_takeover_web_connection(w, rpt);
  808. rrdpush_receive_log_status(
  809. rpt,
  810. "machine GUID is my own",
  811. "LOCALHOST PERMISSION DENIED");
  812. char initial_response[HTTP_HEADER_SIZE + 1];
  813. snprintfz(initial_response, HTTP_HEADER_SIZE, "%s", START_STREAMING_ERROR_SAME_LOCALHOST);
  814. if(send_timeout(
  815. #ifdef ENABLE_HTTPS
  816. &rpt->ssl,
  817. #endif
  818. rpt->fd, initial_response, strlen(initial_response), 0, 60) != (ssize_t)strlen(initial_response)) {
  819. error("STREAM '%s' [receive from [%s]:%s]: "
  820. "failed to reply."
  821. , rpt->hostname
  822. , rpt->client_ip, rpt->client_port
  823. );
  824. }
  825. receiver_state_free(rpt);
  826. return HTTP_RESP_OK;
  827. }
  828. if(unlikely(web_client_streaming_rate_t > 0)) {
  829. static SPINLOCK spinlock = NETDATA_SPINLOCK_INITIALIZER;
  830. static time_t last_stream_accepted_t = 0;
  831. time_t now = now_realtime_sec();
  832. netdata_spinlock_lock(&spinlock);
  833. if(unlikely(last_stream_accepted_t == 0))
  834. last_stream_accepted_t = now;
  835. if(now - last_stream_accepted_t < web_client_streaming_rate_t) {
  836. netdata_spinlock_unlock(&spinlock);
  837. char msg[100 + 1];
  838. snprintfz(msg, 100,
  839. "rate limit, will accept new connection in %ld secs",
  840. (long)(web_client_streaming_rate_t - (now - last_stream_accepted_t)));
  841. rrdpush_receive_log_status(
  842. rpt,
  843. msg,
  844. "RATE LIMIT TRY LATER");
  845. receiver_state_free(rpt);
  846. return rrdpush_receiver_too_busy_now(w);
  847. }
  848. last_stream_accepted_t = now;
  849. netdata_spinlock_unlock(&spinlock);
  850. }
  851. /*
  852. * Quick path for rejecting multiple connections. The lock taken is fine-grained - it only protects the receiver
  853. * pointer within the host (if a host exists). This protects against multiple concurrent web requests hitting
  854. * separate threads within the web-server and landing here. The lock guards the thread-shutdown sequence that
  855. * detaches the receiver from the host. If the host is being created (first time-access) then we also use the
  856. * lock to prevent race-hazard (two threads try to create the host concurrently, one wins and the other does a
  857. * lookup to the now-attached structure).
  858. */
  859. {
  860. time_t age = 0;
  861. bool receiver_stale = false;
  862. bool receiver_working = false;
  863. rrd_rdlock();
  864. RRDHOST *host = rrdhost_find_by_guid(rpt->machine_guid);
  865. if (unlikely(host && rrdhost_flag_check(host, RRDHOST_FLAG_ARCHIVED))) /* Ignore archived hosts. */
  866. host = NULL;
  867. if (host) {
  868. netdata_mutex_lock(&host->receiver_lock);
  869. if (host->receiver) {
  870. age = now_realtime_sec() - host->receiver->last_msg_t;
  871. if (age < 30)
  872. receiver_working = true;
  873. else
  874. receiver_stale = true;
  875. }
  876. netdata_mutex_unlock(&host->receiver_lock);
  877. }
  878. rrd_unlock();
  879. if (receiver_stale && stop_streaming_receiver(host, "STALE RECEIVER")) {
  880. // we stopped the receiver
  881. // we can proceed with this connection
  882. receiver_stale = false;
  883. info("STREAM '%s' [receive from [%s]:%s]: "
  884. "stopped previous stale receiver to accept this one."
  885. , rpt->hostname
  886. , rpt->client_ip, rpt->client_port
  887. );
  888. }
  889. if (receiver_working || receiver_stale) {
  890. // another receiver is already connected
  891. // try again later
  892. char msg[200 + 1];
  893. snprintfz(msg, 200,
  894. "multiple connections for same host, "
  895. "old connection was used %ld secs ago%s",
  896. age, receiver_stale ? " (signaled old receiver to stop)" : " (new connection not accepted)");
  897. rrdpush_receive_log_status(
  898. rpt,
  899. msg,
  900. "ALREADY CONNECTED");
  901. // Have not set WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET - caller should clean up
  902. buffer_flush(w->response.data);
  903. buffer_strcat(w->response.data, START_STREAMING_ERROR_ALREADY_STREAMING);
  904. receiver_state_free(rpt);
  905. return HTTP_RESP_CONFLICT;
  906. }
  907. }
  908. debug(D_SYSTEM, "starting STREAM receive thread.");
  909. rrdpush_receiver_takeover_web_connection(w, rpt);
  910. char tag[NETDATA_THREAD_TAG_MAX + 1];
  911. snprintfz(tag, NETDATA_THREAD_TAG_MAX, THREAD_TAG_STREAM_RECEIVER "[%s]", rpt->hostname);
  912. tag[NETDATA_THREAD_TAG_MAX] = '\0';
  913. if(netdata_thread_create(&rpt->thread, tag, NETDATA_THREAD_OPTION_DEFAULT, rrdpush_receiver_thread, (void *)rpt)) {
  914. rrdpush_receive_log_status(
  915. rpt,
  916. "can't create receiver thread",
  917. "INTERNAL SERVER ERROR");
  918. buffer_flush(w->response.data);
  919. buffer_strcat(w->response.data, "Can't handle this request");
  920. receiver_state_free(rpt);
  921. return HTTP_RESP_INTERNAL_SERVER_ERROR;
  922. }
  923. // prevent the caller from closing the streaming socket
  924. return HTTP_RESP_OK;
  925. }
  926. void rrdpush_reset_destinations_postpone_time(RRDHOST *host) {
  927. struct rrdpush_destinations *d;
  928. for (d = host->destinations; d; d = d->next)
  929. d->postpone_reconnection_until = 0;
  930. }
  931. static struct {
  932. STREAM_HANDSHAKE err;
  933. const char *str;
  934. } handshake_errors[] = {
  935. { STREAM_HANDSHAKE_OK_V5, "OK_V5" },
  936. { STREAM_HANDSHAKE_OK_V4, "OK_V4" },
  937. { STREAM_HANDSHAKE_OK_V3, "OK_V3" },
  938. { STREAM_HANDSHAKE_OK_V2, "OK_V2" },
  939. { STREAM_HANDSHAKE_OK_V1, "OK_V1" },
  940. { STREAM_HANDSHAKE_ERROR_BAD_HANDSHAKE, "BAD HANDSHAKE" },
  941. { STREAM_HANDSHAKE_ERROR_LOCALHOST, "LOCALHOST" },
  942. { STREAM_HANDSHAKE_ERROR_ALREADY_CONNECTED, "ALREADY CONNECTED" },
  943. { STREAM_HANDSHAKE_ERROR_DENIED, "DENIED" },
  944. { STREAM_HANDSHAKE_ERROR_SEND_TIMEOUT, "SEND TIMEOUT" },
  945. { STREAM_HANDSHAKE_ERROR_RECEIVE_TIMEOUT, "RECEIVE TIMEOUT" },
  946. { STREAM_HANDSHAKE_ERROR_INVALID_CERTIFICATE, "INVALID CERTIFICATE" },
  947. { STREAM_HANDSHAKE_ERROR_SSL_ERROR, "SSL ERROR" },
  948. { STREAM_HANDSHAKE_ERROR_CANT_CONNECT, "CANT CONNECT" },
  949. { STREAM_HANDSHAKE_BUSY_TRY_LATER, "BUSY TRY LATER" },
  950. { STREAM_HANDSHAKE_INTERNAL_ERROR, "INTERNAL ERROR" },
  951. { STREAM_HANDSHAKE_INITIALIZATION, "INITIALIZING" },
  952. { 0, NULL },
  953. };
  954. const char *stream_handshake_error_to_string(STREAM_HANDSHAKE handshake_error) {
  955. for(size_t i = 0; handshake_errors[i].str ; i++) {
  956. if(handshake_error == handshake_errors[i].err)
  957. return handshake_errors[i].str;
  958. }
  959. return "";
  960. }
  961. static struct {
  962. STREAM_CAPABILITIES cap;
  963. const char *str;
  964. } capability_names[] = {
  965. { STREAM_CAP_V1, "V1" },
  966. { STREAM_CAP_V2, "V2" },
  967. { STREAM_CAP_VN, "VN" },
  968. { STREAM_CAP_VCAPS, "VCAPS" },
  969. { STREAM_CAP_HLABELS, "HLABELS" },
  970. { STREAM_CAP_CLAIM, "CLAIM" },
  971. { STREAM_CAP_CLABELS, "CLABELS" },
  972. { STREAM_CAP_COMPRESSION, "COMPRESSION" },
  973. { STREAM_CAP_FUNCTIONS, "FUNCTIONS" },
  974. { STREAM_CAP_REPLICATION, "REPLICATION" },
  975. { STREAM_CAP_BINARY, "BINARY" },
  976. { STREAM_CAP_INTERPOLATED, "INTERPOLATED" },
  977. { STREAM_CAP_IEEE754, "IEEE754" },
  978. { 0 , NULL },
  979. };
  980. static void stream_capabilities_to_string(BUFFER *wb, STREAM_CAPABILITIES caps) {
  981. for(size_t i = 0; capability_names[i].str ; i++) {
  982. if(caps & capability_names[i].cap) {
  983. buffer_strcat(wb, capability_names[i].str);
  984. buffer_strcat(wb, " ");
  985. }
  986. }
  987. }
  988. void stream_capabilities_to_json_array(BUFFER *wb, STREAM_CAPABILITIES caps, const char *key) {
  989. buffer_json_member_add_array(wb, key);
  990. for(size_t i = 0; capability_names[i].str ; i++) {
  991. if(caps & capability_names[i].cap)
  992. buffer_json_add_array_item_string(wb, capability_names[i].str);
  993. }
  994. buffer_json_array_close(wb);
  995. }
  996. void log_receiver_capabilities(struct receiver_state *rpt) {
  997. BUFFER *wb = buffer_create(100, NULL);
  998. stream_capabilities_to_string(wb, rpt->capabilities);
  999. info("STREAM %s [receive from [%s]:%s]: established link with negotiated capabilities: %s",
  1000. rrdhost_hostname(rpt->host), rpt->client_ip, rpt->client_port, buffer_tostring(wb));
  1001. buffer_free(wb);
  1002. }
  1003. void log_sender_capabilities(struct sender_state *s) {
  1004. BUFFER *wb = buffer_create(100, NULL);
  1005. stream_capabilities_to_string(wb, s->capabilities);
  1006. info("STREAM %s [send to %s]: established link with negotiated capabilities: %s",
  1007. rrdhost_hostname(s->host), s->connected_to, buffer_tostring(wb));
  1008. buffer_free(wb);
  1009. }
  1010. STREAM_CAPABILITIES convert_stream_version_to_capabilities(int32_t version) {
  1011. STREAM_CAPABILITIES caps = 0;
  1012. if(version <= 1) caps = STREAM_CAP_V1;
  1013. else if(version < STREAM_OLD_VERSION_CLAIM) caps = STREAM_CAP_V2 | STREAM_CAP_HLABELS;
  1014. else if(version <= STREAM_OLD_VERSION_CLAIM) caps = STREAM_CAP_VN | STREAM_CAP_HLABELS | STREAM_CAP_CLAIM;
  1015. else if(version <= STREAM_OLD_VERSION_CLABELS) caps = STREAM_CAP_VN | STREAM_CAP_HLABELS | STREAM_CAP_CLAIM | STREAM_CAP_CLABELS;
  1016. else if(version <= STREAM_OLD_VERSION_COMPRESSION) caps = STREAM_CAP_VN | STREAM_CAP_HLABELS | STREAM_CAP_CLAIM | STREAM_CAP_CLABELS | STREAM_HAS_COMPRESSION;
  1017. else caps = version;
  1018. if(caps & STREAM_CAP_VCAPS)
  1019. caps &= ~(STREAM_CAP_V1|STREAM_CAP_V2|STREAM_CAP_VN);
  1020. if(caps & STREAM_CAP_VN)
  1021. caps &= ~(STREAM_CAP_V1|STREAM_CAP_V2);
  1022. if(caps & STREAM_CAP_V2)
  1023. caps &= ~(STREAM_CAP_V1);
  1024. return caps & stream_our_capabilities();
  1025. }
  1026. int32_t stream_capabilities_to_vn(uint32_t caps) {
  1027. if(caps & STREAM_CAP_COMPRESSION) return STREAM_OLD_VERSION_COMPRESSION;
  1028. if(caps & STREAM_CAP_CLABELS) return STREAM_OLD_VERSION_CLABELS;
  1029. return STREAM_OLD_VERSION_CLAIM; // if(caps & STREAM_CAP_CLAIM)
  1030. }