rrdpush.c 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635
  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 BUFFER in RRDHOST
  12. * the sender thread is signalled via a pipe (also 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. #define STREAMING_PROTOCOL_VERSION "1.1"
  26. #define START_STREAMING_PROMPT "Hit me baby, push them over..."
  27. #define START_STREAMING_PROMPT_V2 "Hit me baby, push them over and bring the host labels..."
  28. #define START_STREAMING_PROMPT_VN "Hit me baby, push them over with the version="
  29. typedef enum {
  30. RRDPUSH_MULTIPLE_CONNECTIONS_ALLOW,
  31. RRDPUSH_MULTIPLE_CONNECTIONS_DENY_NEW
  32. } RRDPUSH_MULTIPLE_CONNECTIONS_STRATEGY;
  33. static struct config stream_config = {
  34. .sections = NULL,
  35. .mutex = NETDATA_MUTEX_INITIALIZER,
  36. .index = {
  37. .avl_tree = {
  38. .root = NULL,
  39. .compar = appconfig_section_compare
  40. },
  41. .rwlock = AVL_LOCK_INITIALIZER
  42. }
  43. };
  44. unsigned int default_rrdpush_enabled = 0;
  45. char *default_rrdpush_destination = NULL;
  46. char *default_rrdpush_api_key = NULL;
  47. char *default_rrdpush_send_charts_matching = NULL;
  48. #ifdef ENABLE_HTTPS
  49. int netdata_use_ssl_on_stream = NETDATA_SSL_OPTIONAL;
  50. char *netdata_ssl_ca_path = NULL;
  51. char *netdata_ssl_ca_file = NULL;
  52. #endif
  53. static void load_stream_conf() {
  54. errno = 0;
  55. char *filename = strdupz_path_subpath(netdata_configured_user_config_dir, "stream.conf");
  56. if(!appconfig_load(&stream_config, filename, 0, NULL)) {
  57. info("CONFIG: cannot load user config '%s'. Will try stock config.", filename);
  58. freez(filename);
  59. filename = strdupz_path_subpath(netdata_configured_stock_config_dir, "stream.conf");
  60. if(!appconfig_load(&stream_config, filename, 0, NULL))
  61. info("CONFIG: cannot load stock config '%s'. Running with internal defaults.", filename);
  62. }
  63. freez(filename);
  64. }
  65. int rrdpush_init() {
  66. // --------------------------------------------------------------------
  67. // load stream.conf
  68. load_stream_conf();
  69. default_rrdpush_enabled = (unsigned int)appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM, "enabled", default_rrdpush_enabled);
  70. default_rrdpush_destination = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "destination", "");
  71. default_rrdpush_api_key = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "api key", "");
  72. default_rrdpush_send_charts_matching = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "send charts matching", "*");
  73. rrdhost_free_orphan_time = config_get_number(CONFIG_SECTION_GLOBAL, "cleanup orphan hosts after seconds", rrdhost_free_orphan_time);
  74. if(default_rrdpush_enabled && (!default_rrdpush_destination || !*default_rrdpush_destination || !default_rrdpush_api_key || !*default_rrdpush_api_key)) {
  75. error("STREAM [send]: cannot enable sending thread - information is missing.");
  76. default_rrdpush_enabled = 0;
  77. }
  78. #ifdef ENABLE_HTTPS
  79. if (netdata_use_ssl_on_stream == NETDATA_SSL_OPTIONAL) {
  80. if (default_rrdpush_destination){
  81. char *test = strstr(default_rrdpush_destination,":SSL");
  82. if(test){
  83. *test = 0X00;
  84. netdata_use_ssl_on_stream = NETDATA_SSL_FORCE;
  85. }
  86. }
  87. }
  88. char *invalid_certificate = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "ssl skip certificate verification", "no");
  89. if ( !strcmp(invalid_certificate,"yes")){
  90. if (netdata_validate_server == NETDATA_SSL_VALID_CERTIFICATE){
  91. info("Netdata is configured to accept invalid SSL certificate.");
  92. netdata_validate_server = NETDATA_SSL_INVALID_CERTIFICATE;
  93. }
  94. }
  95. netdata_ssl_ca_path = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "CApath", "/etc/ssl/certs/");
  96. netdata_ssl_ca_file = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "CAfile", "/etc/ssl/certs/certs.pem");
  97. #endif
  98. return default_rrdpush_enabled;
  99. }
  100. #define CONNECTED_TO_SIZE 100
  101. // data collection happens from multiple threads
  102. // each of these threads calls rrdset_done()
  103. // which in turn calls rrdset_done_push()
  104. // which uses this pipe to notify the streaming thread
  105. // that there are more data ready to be sent
  106. #define PIPE_READ 0
  107. #define PIPE_WRITE 1
  108. // to have the remote netdata re-sync the charts
  109. // to its current clock, we send for this many
  110. // iterations a BEGIN line without microseconds
  111. // this is for the first iterations of each chart
  112. unsigned int remote_clock_resync_iterations = 60;
  113. #define rrdpush_buffer_lock(host) netdata_mutex_lock(&((host)->rrdpush_sender_buffer_mutex))
  114. #define rrdpush_buffer_unlock(host) netdata_mutex_unlock(&((host)->rrdpush_sender_buffer_mutex))
  115. static inline int should_send_chart_matching(RRDSET *st) {
  116. if(unlikely(!rrdset_flag_check(st, RRDSET_FLAG_ENABLED))) {
  117. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_SEND);
  118. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  119. }
  120. else if(!rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_SEND|RRDSET_FLAG_UPSTREAM_IGNORE)) {
  121. RRDHOST *host = st->rrdhost;
  122. if(simple_pattern_matches(host->rrdpush_send_charts_matching, st->id) ||
  123. simple_pattern_matches(host->rrdpush_send_charts_matching, st->name)) {
  124. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  125. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_SEND);
  126. }
  127. else {
  128. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_SEND);
  129. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_IGNORE);
  130. }
  131. }
  132. return(rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_SEND));
  133. }
  134. int configured_as_master() {
  135. struct section *section = NULL;
  136. int is_master = 0;
  137. appconfig_wrlock(&stream_config);
  138. for (section = stream_config.sections; section; section = section->next) {
  139. uuid_t uuid;
  140. if (uuid_parse(section->name, uuid) != -1 &&
  141. appconfig_get_boolean(&stream_config, section->name, "enabled", 0)) {
  142. is_master = 1;
  143. break;
  144. }
  145. }
  146. appconfig_unlock(&stream_config);
  147. return is_master;
  148. }
  149. // checks if the current chart definition has been sent
  150. static inline int need_to_send_chart_definition(RRDSET *st) {
  151. rrdset_check_rdlock(st);
  152. if(unlikely(!(rrdset_flag_check(st, RRDSET_FLAG_UPSTREAM_EXPOSED))))
  153. return 1;
  154. RRDDIM *rd;
  155. rrddim_foreach_read(rd, st) {
  156. if(unlikely(!rd->exposed)) {
  157. #ifdef NETDATA_INTERNAL_CHECKS
  158. info("host '%s', chart '%s', dimension '%s' flag 'exposed' triggered chart refresh to upstream", st->rrdhost->hostname, st->id, rd->id);
  159. #endif
  160. return 1;
  161. }
  162. }
  163. return 0;
  164. }
  165. // sends the current chart definition
  166. static inline void rrdpush_send_chart_definition_nolock(RRDSET *st) {
  167. RRDHOST *host = st->rrdhost;
  168. rrdset_flag_set(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  169. // properly set the name for the remote end to parse it
  170. char *name = "";
  171. if(likely(st->name)) {
  172. if(unlikely(strcmp(st->id, st->name))) {
  173. // they differ
  174. name = strchr(st->name, '.');
  175. if(name)
  176. name++;
  177. else
  178. name = "";
  179. }
  180. }
  181. // info("CHART '%s' '%s'", st->id, name);
  182. // send the chart
  183. buffer_sprintf(
  184. host->rrdpush_sender_buffer
  185. , "CHART \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" %ld %d \"%s %s %s %s\" \"%s\" \"%s\"\n"
  186. , st->id
  187. , name
  188. , st->title
  189. , st->units
  190. , st->family
  191. , st->context
  192. , rrdset_type_name(st->chart_type)
  193. , st->priority
  194. , st->update_every
  195. , rrdset_flag_check(st, RRDSET_FLAG_OBSOLETE)?"obsolete":""
  196. , rrdset_flag_check(st, RRDSET_FLAG_DETAIL)?"detail":""
  197. , rrdset_flag_check(st, RRDSET_FLAG_STORE_FIRST)?"store_first":""
  198. , rrdset_flag_check(st, RRDSET_FLAG_HIDDEN)?"hidden":""
  199. , (st->plugin_name)?st->plugin_name:""
  200. , (st->module_name)?st->module_name:""
  201. );
  202. // send the dimensions
  203. RRDDIM *rd;
  204. rrddim_foreach_read(rd, st) {
  205. buffer_sprintf(
  206. host->rrdpush_sender_buffer
  207. , "DIMENSION \"%s\" \"%s\" \"%s\" " COLLECTED_NUMBER_FORMAT " " COLLECTED_NUMBER_FORMAT " \"%s %s %s\"\n"
  208. , rd->id
  209. , rd->name
  210. , rrd_algorithm_name(rd->algorithm)
  211. , rd->multiplier
  212. , rd->divisor
  213. , rrddim_flag_check(rd, RRDDIM_FLAG_OBSOLETE)?"obsolete":""
  214. , rrddim_flag_check(rd, RRDDIM_FLAG_HIDDEN)?"hidden":""
  215. , rrddim_flag_check(rd, RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)?"noreset":""
  216. );
  217. rd->exposed = 1;
  218. }
  219. // send the chart local custom variables
  220. RRDSETVAR *rs;
  221. for(rs = st->variables; rs ;rs = rs->next) {
  222. if(unlikely(rs->type == RRDVAR_TYPE_CALCULATED && rs->options & RRDVAR_OPTION_CUSTOM_CHART_VAR)) {
  223. calculated_number *value = (calculated_number *) rs->value;
  224. buffer_sprintf(
  225. host->rrdpush_sender_buffer
  226. , "VARIABLE CHART %s = " CALCULATED_NUMBER_FORMAT "\n"
  227. , rs->variable
  228. , *value
  229. );
  230. }
  231. }
  232. st->upstream_resync_time = st->last_collected_time.tv_sec + (remote_clock_resync_iterations * st->update_every);
  233. }
  234. // sends the current chart dimensions
  235. static inline void rrdpush_send_chart_metrics_nolock(RRDSET *st) {
  236. RRDHOST *host = st->rrdhost;
  237. buffer_sprintf(host->rrdpush_sender_buffer, "BEGIN \"%s\" %llu\n", st->id, (st->last_collected_time.tv_sec > st->upstream_resync_time)?st->usec_since_last_update:0);
  238. RRDDIM *rd;
  239. rrddim_foreach_read(rd, st) {
  240. if(rd->updated && rd->exposed)
  241. buffer_sprintf(host->rrdpush_sender_buffer
  242. , "SET \"%s\" = " COLLECTED_NUMBER_FORMAT "\n"
  243. , rd->id
  244. , rd->collected_value
  245. );
  246. }
  247. buffer_strcat(host->rrdpush_sender_buffer, "END\n");
  248. }
  249. static void rrdpush_sender_thread_spawn(RRDHOST *host);
  250. void rrdset_push_chart_definition_now(RRDSET *st) {
  251. RRDHOST *host = st->rrdhost;
  252. if(unlikely(!host->rrdpush_send_enabled || !should_send_chart_matching(st)))
  253. return;
  254. rrdset_rdlock(st);
  255. rrdpush_buffer_lock(host);
  256. rrdpush_send_chart_definition_nolock(st);
  257. rrdpush_buffer_unlock(host);
  258. rrdset_unlock(st);
  259. }
  260. void rrdset_done_push(RRDSET *st) {
  261. if(unlikely(!should_send_chart_matching(st)))
  262. return;
  263. RRDHOST *host = st->rrdhost;
  264. rrdpush_buffer_lock(host);
  265. if(unlikely(host->rrdpush_send_enabled && !host->rrdpush_sender_spawn))
  266. rrdpush_sender_thread_spawn(host);
  267. if(unlikely(!host->rrdpush_sender_buffer || !host->rrdpush_sender_connected)) {
  268. if(unlikely(!host->rrdpush_sender_error_shown))
  269. error("STREAM %s [send]: not ready - discarding collected metrics.", host->hostname);
  270. host->rrdpush_sender_error_shown = 1;
  271. rrdpush_buffer_unlock(host);
  272. return;
  273. }
  274. else if(unlikely(host->rrdpush_sender_error_shown)) {
  275. info("STREAM %s [send]: sending metrics...", host->hostname);
  276. host->rrdpush_sender_error_shown = 0;
  277. }
  278. if(need_to_send_chart_definition(st))
  279. rrdpush_send_chart_definition_nolock(st);
  280. rrdpush_send_chart_metrics_nolock(st);
  281. // signal the sender there are more data
  282. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1 && write(host->rrdpush_sender_pipe[PIPE_WRITE], " ", 1) == -1)
  283. error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
  284. rrdpush_buffer_unlock(host);
  285. }
  286. // labels
  287. void rrdpush_send_labels(RRDHOST *host) {
  288. if (!host->labels || !(host->labels_flag & LABEL_FLAG_UPDATE_STREAM) || (host->labels_flag & LABEL_FLAG_STOP_STREAM))
  289. return;
  290. rrdpush_buffer_lock(host);
  291. rrdhost_rdlock(host);
  292. netdata_rwlock_rdlock(&host->labels_rwlock);
  293. struct label *labels = host->labels;
  294. while(labels) {
  295. buffer_sprintf(host->rrdpush_sender_buffer
  296. , "LABEL \"%s\" = %d %s\n"
  297. , labels->key
  298. , (int)labels->label_source
  299. , labels->value);
  300. labels = labels->next;
  301. }
  302. buffer_sprintf(host->rrdpush_sender_buffer
  303. , "OVERWRITE %s\n", "labels");
  304. netdata_rwlock_unlock(&host->labels_rwlock);
  305. rrdhost_unlock(host);
  306. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1 && write(host->rrdpush_sender_pipe[PIPE_WRITE], " ", 1) == -1)
  307. error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
  308. rrdpush_buffer_unlock(host);
  309. host->labels_flag &= ~LABEL_FLAG_UPDATE_STREAM;
  310. }
  311. // ----------------------------------------------------------------------------
  312. // rrdpush sender thread
  313. static inline void rrdpush_sender_add_host_variable_to_buffer_nolock(RRDHOST *host, RRDVAR *rv) {
  314. calculated_number *value = (calculated_number *)rv->value;
  315. buffer_sprintf(
  316. host->rrdpush_sender_buffer
  317. , "VARIABLE HOST %s = " CALCULATED_NUMBER_FORMAT "\n"
  318. , rv->name
  319. , *value
  320. );
  321. debug(D_STREAM, "RRDVAR pushed HOST VARIABLE %s = " CALCULATED_NUMBER_FORMAT, rv->name, *value);
  322. }
  323. void rrdpush_sender_send_this_host_variable_now(RRDHOST *host, RRDVAR *rv) {
  324. if(host->rrdpush_send_enabled && host->rrdpush_sender_spawn && host->rrdpush_sender_connected) {
  325. rrdpush_buffer_lock(host);
  326. rrdpush_sender_add_host_variable_to_buffer_nolock(host, rv);
  327. rrdpush_buffer_unlock(host);
  328. }
  329. }
  330. static int rrdpush_sender_thread_custom_host_variables_callback(void *rrdvar_ptr, void *host_ptr) {
  331. RRDVAR *rv = (RRDVAR *)rrdvar_ptr;
  332. RRDHOST *host = (RRDHOST *)host_ptr;
  333. if(unlikely(rv->options & RRDVAR_OPTION_CUSTOM_HOST_VAR && rv->type == RRDVAR_TYPE_CALCULATED)) {
  334. rrdpush_sender_add_host_variable_to_buffer_nolock(host, rv);
  335. // return 1, so that the traversal will return the number of variables sent
  336. return 1;
  337. }
  338. // returning a negative number will break the traversal
  339. return 0;
  340. }
  341. static void rrdpush_sender_thread_send_custom_host_variables(RRDHOST *host) {
  342. int ret = rrdvar_callback_for_all_host_variables(host, rrdpush_sender_thread_custom_host_variables_callback, host);
  343. (void)ret;
  344. debug(D_STREAM, "RRDVAR sent %d VARIABLES", ret);
  345. }
  346. // resets all the chart, so that their definitions
  347. // will be resent to the central netdata
  348. static void rrdpush_sender_thread_reset_all_charts(RRDHOST *host) {
  349. rrdhost_rdlock(host);
  350. RRDSET *st;
  351. rrdset_foreach_read(st, host) {
  352. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  353. st->upstream_resync_time = 0;
  354. rrdset_rdlock(st);
  355. RRDDIM *rd;
  356. rrddim_foreach_read(rd, st)
  357. rd->exposed = 0;
  358. rrdset_unlock(st);
  359. }
  360. rrdhost_unlock(host);
  361. }
  362. static inline void rrdpush_sender_thread_data_flush(RRDHOST *host) {
  363. rrdpush_buffer_lock(host);
  364. if(buffer_strlen(host->rrdpush_sender_buffer))
  365. error("STREAM %s [send]: discarding %zu bytes of metrics already in the buffer.", host->hostname, buffer_strlen(host->rrdpush_sender_buffer));
  366. buffer_flush(host->rrdpush_sender_buffer);
  367. rrdpush_sender_thread_reset_all_charts(host);
  368. rrdpush_sender_thread_send_custom_host_variables(host);
  369. rrdpush_buffer_unlock(host);
  370. }
  371. void rrdpush_sender_thread_stop(RRDHOST *host) {
  372. rrdpush_buffer_lock(host);
  373. rrdhost_wrlock(host);
  374. netdata_thread_t thr = 0;
  375. if(host->rrdpush_sender_spawn) {
  376. info("STREAM %s [send]: signaling sending thread to stop...", host->hostname);
  377. // signal the thread that we want to join it
  378. host->rrdpush_sender_join = 1;
  379. // copy the thread id, so that we will be waiting for the right one
  380. // even if a new one has been spawn
  381. thr = host->rrdpush_sender_thread;
  382. // signal it to cancel
  383. netdata_thread_cancel(host->rrdpush_sender_thread);
  384. }
  385. rrdhost_unlock(host);
  386. rrdpush_buffer_unlock(host);
  387. if(thr != 0) {
  388. info("STREAM %s [send]: waiting for the sending thread to stop...", host->hostname);
  389. void *result;
  390. netdata_thread_join(thr, &result);
  391. info("STREAM %s [send]: sending thread has exited.", host->hostname);
  392. }
  393. }
  394. static inline void rrdpush_sender_thread_close_socket(RRDHOST *host) {
  395. host->rrdpush_sender_connected = 0;
  396. if(host->rrdpush_sender_socket != -1) {
  397. close(host->rrdpush_sender_socket);
  398. host->rrdpush_sender_socket = -1;
  399. }
  400. }
  401. static inline void rrdpush_set_flags_to_newest_stream(RRDHOST *host) {
  402. host->labels_flag |= LABEL_FLAG_UPDATE_STREAM;
  403. host->labels_flag &= ~LABEL_FLAG_STOP_STREAM;
  404. }
  405. //called from client side
  406. static int rrdpush_sender_thread_connect_to_master(RRDHOST *host, int default_port, int timeout, size_t *reconnects_counter, char *connected_to, size_t connected_to_size) {
  407. struct timeval tv = {
  408. .tv_sec = timeout,
  409. .tv_usec = 0
  410. };
  411. // make sure the socket is closed
  412. rrdpush_sender_thread_close_socket(host);
  413. debug(D_STREAM, "STREAM: Attempting to connect...");
  414. info("STREAM %s [send to %s]: connecting...", host->hostname, host->rrdpush_send_destination);
  415. host->rrdpush_sender_socket = connect_to_one_of(
  416. host->rrdpush_send_destination
  417. , default_port
  418. , &tv
  419. , reconnects_counter
  420. , connected_to
  421. , connected_to_size
  422. );
  423. if(unlikely(host->rrdpush_sender_socket == -1)) {
  424. error("STREAM %s [send to %s]: failed to connect", host->hostname, host->rrdpush_send_destination);
  425. return 0;
  426. }
  427. info("STREAM %s [send to %s]: initializing communication...", host->hostname, connected_to);
  428. #ifdef ENABLE_HTTPS
  429. if( netdata_client_ctx ){
  430. host->ssl.flags = NETDATA_SSL_START;
  431. if (!host->ssl.conn){
  432. host->ssl.conn = SSL_new(netdata_client_ctx);
  433. if(!host->ssl.conn){
  434. error("Failed to allocate SSL structure.");
  435. host->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  436. }
  437. }
  438. else{
  439. SSL_clear(host->ssl.conn);
  440. }
  441. if (host->ssl.conn)
  442. {
  443. if (SSL_set_fd(host->ssl.conn, host->rrdpush_sender_socket) != 1) {
  444. error("Failed to set the socket to the SSL on socket fd %d.", host->rrdpush_sender_socket);
  445. host->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  446. } else{
  447. host->ssl.flags = NETDATA_SSL_HANDSHAKE_COMPLETE;
  448. }
  449. }
  450. }
  451. else {
  452. host->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  453. }
  454. #endif
  455. /* TODO: During the implementation of #7265 switch the set of variables to HOST_* and CONTAINER_* if the
  456. version negotiation resulted in a high enough version.
  457. */
  458. #define HTTP_HEADER_SIZE 8192
  459. char http[HTTP_HEADER_SIZE + 1];
  460. int eol = snprintfz(http, HTTP_HEADER_SIZE,
  461. "STREAM key=%s&hostname=%s&registry_hostname=%s&machine_guid=%s&update_every=%d&os=%s&timezone=%s&tags=%s&ver=%u"
  462. "&NETDATA_SYSTEM_OS_NAME=%s"
  463. "&NETDATA_SYSTEM_OS_ID=%s"
  464. "&NETDATA_SYSTEM_OS_ID_LIKE=%s"
  465. "&NETDATA_SYSTEM_OS_VERSION=%s"
  466. "&NETDATA_SYSTEM_OS_VERSION_ID=%s"
  467. "&NETDATA_SYSTEM_OS_DETECTION=%s"
  468. "&NETDATA_SYSTEM_KERNEL_NAME=%s"
  469. "&NETDATA_SYSTEM_KERNEL_VERSION=%s"
  470. "&NETDATA_SYSTEM_ARCHITECTURE=%s"
  471. "&NETDATA_SYSTEM_VIRTUALIZATION=%s"
  472. "&NETDATA_SYSTEM_VIRT_DETECTION=%s"
  473. "&NETDATA_SYSTEM_CONTAINER=%s"
  474. "&NETDATA_SYSTEM_CONTAINER_DETECTION=%s"
  475. "&NETDATA_CONTAINER_OS_NAME=%s"
  476. "&NETDATA_CONTAINER_OS_ID=%s"
  477. "&NETDATA_CONTAINER_OS_ID_LIKE=%s"
  478. "&NETDATA_CONTAINER_OS_VERSION=%s"
  479. "&NETDATA_CONTAINER_OS_VERSION_ID=%s"
  480. "&NETDATA_CONTAINER_OS_DETECTION=%s"
  481. "&NETDATA_SYSTEM_CPU_LOGICAL_CPU_COUNT=%s"
  482. "&NETDATA_SYSTEM_CPU_FREQ=%s"
  483. "&NETDATA_SYSTEM_TOTAL_RAM=%s"
  484. "&NETDATA_SYSTEM_TOTAL_DISK_SIZE=%s"
  485. "&NETDATA_PROTOCOL_VERSION=%s"
  486. " HTTP/1.1\r\n"
  487. "User-Agent: %s/%s\r\n"
  488. "Accept: */*\r\n\r\n"
  489. , host->rrdpush_send_api_key
  490. , host->hostname
  491. , host->registry_hostname
  492. , host->machine_guid
  493. , default_rrd_update_every
  494. , host->os
  495. , host->timezone
  496. , (host->tags) ? host->tags : ""
  497. , STREAMING_PROTOCOL_CURRENT_VERSION
  498. , (host->system_info->host_os_name) ? host->system_info->host_os_name : ""
  499. , (host->system_info->host_os_id) ? host->system_info->host_os_id : ""
  500. , (host->system_info->host_os_id_like) ? host->system_info->host_os_id_like : ""
  501. , (host->system_info->host_os_version) ? host->system_info->host_os_version : ""
  502. , (host->system_info->host_os_version_id) ? host->system_info->host_os_version_id : ""
  503. , (host->system_info->host_os_detection) ? host->system_info->host_os_detection : ""
  504. , (host->system_info->kernel_name) ? host->system_info->kernel_name : ""
  505. , (host->system_info->kernel_version) ? host->system_info->kernel_version : ""
  506. , (host->system_info->architecture) ? host->system_info->architecture : ""
  507. , (host->system_info->virtualization) ? host->system_info->virtualization : ""
  508. , (host->system_info->virt_detection) ? host->system_info->virt_detection : ""
  509. , (host->system_info->container) ? host->system_info->container : ""
  510. , (host->system_info->container_detection) ? host->system_info->container_detection : ""
  511. , (host->system_info->container_os_name) ? host->system_info->container_os_name : ""
  512. , (host->system_info->container_os_id) ? host->system_info->container_os_id : ""
  513. , (host->system_info->container_os_id_like) ? host->system_info->container_os_id_like : ""
  514. , (host->system_info->container_os_version) ? host->system_info->container_os_version : ""
  515. , (host->system_info->container_os_version_id) ? host->system_info->container_os_version_id : ""
  516. , (host->system_info->container_os_detection) ? host->system_info->container_os_detection : ""
  517. , (host->system_info->host_cores) ? host->system_info->host_cores : ""
  518. , (host->system_info->host_cpu_freq) ? host->system_info->host_cpu_freq : ""
  519. , (host->system_info->host_ram_total) ? host->system_info->host_ram_total : ""
  520. , (host->system_info->host_disk_space) ? host->system_info->host_disk_space : ""
  521. , STREAMING_PROTOCOL_VERSION
  522. , host->program_name
  523. , host->program_version
  524. );
  525. http[eol] = 0x00;
  526. #ifdef ENABLE_HTTPS
  527. if (!host->ssl.flags) {
  528. ERR_clear_error();
  529. SSL_set_connect_state(host->ssl.conn);
  530. int err = SSL_connect(host->ssl.conn);
  531. if (err != 1){
  532. err = SSL_get_error(host->ssl.conn, err);
  533. error("SSL cannot connect with the server: %s ",ERR_error_string((long)SSL_get_error(host->ssl.conn,err),NULL));
  534. if (netdata_use_ssl_on_stream == NETDATA_SSL_FORCE) {
  535. rrdpush_sender_thread_close_socket(host);
  536. return 0;
  537. }else {
  538. host->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  539. }
  540. }
  541. else {
  542. if (netdata_use_ssl_on_stream == NETDATA_SSL_FORCE) {
  543. if (netdata_validate_server == NETDATA_SSL_VALID_CERTIFICATE) {
  544. if ( security_test_certificate(host->ssl.conn)) {
  545. error("Closing the stream connection, because the server SSL certificate is not valid.");
  546. rrdpush_sender_thread_close_socket(host);
  547. return 0;
  548. }
  549. }
  550. }
  551. }
  552. }
  553. if(send_timeout(&host->ssl,host->rrdpush_sender_socket, http, strlen(http), 0, timeout) == -1) {
  554. #else
  555. if(send_timeout(host->rrdpush_sender_socket, http, strlen(http), 0, timeout) == -1) {
  556. #endif
  557. error("STREAM %s [send to %s]: failed to send HTTP header to remote netdata.", host->hostname, connected_to);
  558. rrdpush_sender_thread_close_socket(host);
  559. return 0;
  560. }
  561. info("STREAM %s [send to %s]: waiting response from remote netdata...", host->hostname, connected_to);
  562. ssize_t received;
  563. #ifdef ENABLE_HTTPS
  564. received = recv_timeout(&host->ssl,host->rrdpush_sender_socket, http, HTTP_HEADER_SIZE, 0, timeout);
  565. if(received == -1) {
  566. #else
  567. received = recv_timeout(host->rrdpush_sender_socket, http, HTTP_HEADER_SIZE, 0, timeout);
  568. if(received == -1) {
  569. #endif
  570. error("STREAM %s [send to %s]: remote netdata does not respond.", host->hostname, connected_to);
  571. rrdpush_sender_thread_close_socket(host);
  572. return 0;
  573. }
  574. http[received] = '\0';
  575. int answer = -1;
  576. char *version_start = strchr(http, '=');
  577. uint32_t version;
  578. if(version_start) {
  579. version_start++;
  580. version = (uint32_t)strtol(version_start, NULL, 10);
  581. answer = memcmp(http, START_STREAMING_PROMPT_VN, (size_t)(version_start - http));
  582. if(!answer) {
  583. rrdpush_set_flags_to_newest_stream(host);
  584. host->stream_version = version;
  585. }
  586. } else {
  587. answer = memcmp(http, START_STREAMING_PROMPT_V2, strlen(START_STREAMING_PROMPT_V2));
  588. if(!answer) {
  589. version = 1;
  590. rrdpush_set_flags_to_newest_stream(host);
  591. }
  592. else {
  593. answer = memcmp(http, START_STREAMING_PROMPT, strlen(START_STREAMING_PROMPT));
  594. if(!answer) {
  595. version = 0;
  596. host->labels_flag |= LABEL_FLAG_STOP_STREAM;
  597. host->labels_flag &= ~LABEL_FLAG_UPDATE_STREAM;
  598. }
  599. }
  600. }
  601. if(answer != 0) {
  602. error("STREAM %s [send to %s]: server is not replying properly (is it a netdata?).", host->hostname, connected_to);
  603. rrdpush_sender_thread_close_socket(host);
  604. return 0;
  605. }
  606. info("STREAM %s [send to %s]: established communication with a master using protocol version %u - ready to send metrics..."
  607. , host->hostname
  608. , connected_to
  609. , version);
  610. if(sock_setnonblock(host->rrdpush_sender_socket) < 0)
  611. error("STREAM %s [send to %s]: cannot set non-blocking mode for socket.", host->hostname, connected_to);
  612. if(sock_enlarge_out(host->rrdpush_sender_socket) < 0)
  613. error("STREAM %s [send to %s]: cannot enlarge the socket buffer.", host->hostname, connected_to);
  614. debug(D_STREAM, "STREAM: Connected on fd %d...", host->rrdpush_sender_socket);
  615. return 1;
  616. }
  617. static void rrdpush_sender_thread_cleanup_callback(void *ptr) {
  618. RRDHOST *host = (RRDHOST *)ptr;
  619. rrdpush_buffer_lock(host);
  620. rrdhost_wrlock(host);
  621. info("STREAM %s [send]: sending thread cleans up...", host->hostname);
  622. rrdpush_sender_thread_close_socket(host);
  623. // close the pipe
  624. if(host->rrdpush_sender_pipe[PIPE_READ] != -1) {
  625. close(host->rrdpush_sender_pipe[PIPE_READ]);
  626. host->rrdpush_sender_pipe[PIPE_READ] = -1;
  627. }
  628. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1) {
  629. close(host->rrdpush_sender_pipe[PIPE_WRITE]);
  630. host->rrdpush_sender_pipe[PIPE_WRITE] = -1;
  631. }
  632. buffer_free(host->rrdpush_sender_buffer);
  633. host->rrdpush_sender_buffer = NULL;
  634. if(!host->rrdpush_sender_join) {
  635. info("STREAM %s [send]: sending thread detaches itself.", host->hostname);
  636. netdata_thread_detach(netdata_thread_self());
  637. }
  638. host->rrdpush_sender_spawn = 0;
  639. info("STREAM %s [send]: sending thread now exits.", host->hostname);
  640. rrdhost_unlock(host);
  641. rrdpush_buffer_unlock(host);
  642. }
  643. void *rrdpush_sender_thread(void *ptr) {
  644. RRDHOST *host = (RRDHOST *)ptr;
  645. if(!host->rrdpush_send_enabled || !host->rrdpush_send_destination || !*host->rrdpush_send_destination || !host->rrdpush_send_api_key || !*host->rrdpush_send_api_key) {
  646. error("STREAM %s [send]: thread created (task id %d), but host has streaming disabled.", host->hostname, gettid());
  647. return NULL;
  648. }
  649. #ifdef ENABLE_HTTPS
  650. if (netdata_use_ssl_on_stream & NETDATA_SSL_FORCE ){
  651. security_start_ssl(NETDATA_SSL_CONTEXT_STREAMING);
  652. security_location_for_context(netdata_client_ctx, netdata_ssl_ca_file, netdata_ssl_ca_path);
  653. }
  654. #endif
  655. info("STREAM %s [send]: thread created (task id %d)", host->hostname, gettid());
  656. int timeout = (int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "timeout seconds", 60);
  657. int default_port = (int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "default port", 19999);
  658. size_t max_size = (size_t)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "buffer size bytes", 1024 * 1024);
  659. unsigned int reconnect_delay = (unsigned int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "reconnect delay seconds", 5);
  660. remote_clock_resync_iterations = (unsigned int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "initial clock resync iterations", remote_clock_resync_iterations);
  661. char connected_to[CONNECTED_TO_SIZE + 1] = "";
  662. // initialize rrdpush globals
  663. host->rrdpush_sender_buffer = buffer_create(1);
  664. host->rrdpush_sender_connected = 0;
  665. if(pipe(host->rrdpush_sender_pipe) == -1) fatal("STREAM %s [send]: cannot create required pipe.", host->hostname);
  666. // initialize local variables
  667. size_t begin = 0;
  668. size_t reconnects_counter = 0;
  669. size_t sent_bytes = 0;
  670. size_t sent_bytes_on_this_connection = 0;
  671. size_t send_attempts = 0;
  672. time_t last_sent_t = 0;
  673. struct pollfd fds[2], *ifd, *ofd;
  674. nfds_t fdmax;
  675. ifd = &fds[0];
  676. ofd = &fds[1];
  677. size_t not_connected_loops = 0;
  678. netdata_thread_cleanup_push(rrdpush_sender_thread_cleanup_callback, host);
  679. for(; host->rrdpush_send_enabled && !netdata_exit ;) {
  680. // check for outstanding cancellation requests
  681. netdata_thread_testcancel();
  682. // if we don't have socket open, lets wait a bit
  683. if(unlikely(host->rrdpush_sender_socket == -1)) {
  684. send_attempts = 0;
  685. if(not_connected_loops == 0 && sent_bytes_on_this_connection > 0) {
  686. // fast re-connection on first disconnect
  687. sleep_usec(USEC_PER_MS * 500); // milliseconds
  688. }
  689. else {
  690. // slow re-connection on repeating errors
  691. sleep_usec(USEC_PER_SEC * reconnect_delay); // seconds
  692. }
  693. if(rrdpush_sender_thread_connect_to_master(host, default_port, timeout, &reconnects_counter, connected_to, CONNECTED_TO_SIZE)) {
  694. last_sent_t = now_monotonic_sec();
  695. // reset the buffer, to properly send charts and metrics
  696. rrdpush_sender_thread_data_flush(host);
  697. // send from the beginning
  698. begin = 0;
  699. // make sure the next reconnection will be immediate
  700. not_connected_loops = 0;
  701. // reset the bytes we have sent for this session
  702. sent_bytes_on_this_connection = 0;
  703. // let the data collection threads know we are ready
  704. host->rrdpush_sender_connected = 1;
  705. }
  706. else {
  707. // increase the failed connections counter
  708. not_connected_loops++;
  709. // reset the number of bytes sent
  710. sent_bytes_on_this_connection = 0;
  711. }
  712. // loop through
  713. continue;
  714. }
  715. else if(unlikely(now_monotonic_sec() - last_sent_t > timeout)) {
  716. error("STREAM %s [send to %s]: could not send metrics for %d seconds - closing connection - we have sent %zu bytes on this connection via %zu send attempts.", host->hostname, connected_to, timeout, sent_bytes_on_this_connection, send_attempts);
  717. rrdpush_sender_thread_close_socket(host);
  718. }
  719. ifd->fd = host->rrdpush_sender_pipe[PIPE_READ];
  720. ifd->events = POLLIN;
  721. ifd->revents = 0;
  722. ofd->fd = host->rrdpush_sender_socket;
  723. ofd->revents = 0;
  724. if(ofd->fd != -1 && begin < buffer_strlen(host->rrdpush_sender_buffer)) {
  725. debug(D_STREAM, "STREAM: Requesting data output on streaming socket %d...", ofd->fd);
  726. ofd->events = POLLOUT;
  727. fdmax = 2;
  728. send_attempts++;
  729. }
  730. else {
  731. debug(D_STREAM, "STREAM: Not requesting data output on streaming socket %d (nothing to send now)...", ofd->fd);
  732. ofd->events = 0;
  733. fdmax = 1;
  734. }
  735. debug(D_STREAM, "STREAM: Waiting for poll() events (current buffer length %zu bytes)...", buffer_strlen(host->rrdpush_sender_buffer));
  736. if(unlikely(netdata_exit)) break;
  737. int retval = poll(fds, fdmax, 1000);
  738. if(unlikely(netdata_exit)) break;
  739. if(unlikely(retval == -1)) {
  740. debug(D_STREAM, "STREAM: poll() failed (current buffer length %zu bytes)...", buffer_strlen(host->rrdpush_sender_buffer));
  741. if(errno == EAGAIN || errno == EINTR) {
  742. debug(D_STREAM, "STREAM: poll() failed with EAGAIN or EINTR...");
  743. }
  744. else {
  745. error("STREAM %s [send to %s]: failed to poll(). Closing socket.", host->hostname, connected_to);
  746. rrdpush_sender_thread_close_socket(host);
  747. }
  748. continue;
  749. }
  750. else if(likely(retval)) {
  751. if (ifd->revents & POLLIN || ifd->revents & POLLPRI) {
  752. debug(D_STREAM, "STREAM: Data added to send buffer (current buffer length %zu bytes)...", buffer_strlen(host->rrdpush_sender_buffer));
  753. char buffer[1000 + 1];
  754. if (read(host->rrdpush_sender_pipe[PIPE_READ], buffer, 1000) == -1)
  755. error("STREAM %s [send to %s]: cannot read from internal pipe.", host->hostname, connected_to);
  756. }
  757. if (ofd->revents & POLLOUT) {
  758. rrdpush_send_labels(host);
  759. if (begin < buffer_strlen(host->rrdpush_sender_buffer)) {
  760. debug(D_STREAM, "STREAM: Sending data (current buffer length %zu bytes, begin = %zu)...", buffer_strlen(host->rrdpush_sender_buffer), begin);
  761. // BEGIN RRDPUSH LOCKED SESSION
  762. // during this session, data collectors
  763. // will not be able to append data to our buffer
  764. // but the socket is in non-blocking mode
  765. // so, we will not block at send()
  766. netdata_thread_disable_cancelability();
  767. debug(D_STREAM, "STREAM: Getting exclusive lock on host...");
  768. rrdpush_buffer_lock(host);
  769. debug(D_STREAM, "STREAM: Sending data, starting from %zu, size %zu...", begin, buffer_strlen(host->rrdpush_sender_buffer));
  770. ssize_t ret;
  771. #ifdef ENABLE_HTTPS
  772. SSL *conn = host->ssl.conn ;
  773. if(conn && !host->ssl.flags) {
  774. ret = SSL_write(conn,&host->rrdpush_sender_buffer->buffer[begin], buffer_strlen(host->rrdpush_sender_buffer) - begin);
  775. } else {
  776. ret = send(host->rrdpush_sender_socket, &host->rrdpush_sender_buffer->buffer[begin], buffer_strlen(host->rrdpush_sender_buffer) - begin, MSG_DONTWAIT);
  777. }
  778. #else
  779. ret = send(host->rrdpush_sender_socket, &host->rrdpush_sender_buffer->buffer[begin], buffer_strlen(host->rrdpush_sender_buffer) - begin, MSG_DONTWAIT);
  780. #endif
  781. if (unlikely(ret == -1)) {
  782. if (errno != EAGAIN && errno != EINTR && errno != EWOULDBLOCK) {
  783. debug(D_STREAM, "STREAM: Send failed - closing socket...");
  784. error("STREAM %s [send to %s]: failed to send metrics - closing connection - we have sent %zu bytes on this connection.", host->hostname, connected_to, sent_bytes_on_this_connection);
  785. rrdpush_sender_thread_close_socket(host);
  786. }
  787. else {
  788. debug(D_STREAM, "STREAM: Send failed - will retry...");
  789. }
  790. }
  791. else if (likely(ret > 0)) {
  792. // DEBUG - dump the string to see it
  793. //char c = host->rrdpush_sender_buffer->buffer[begin + ret];
  794. //host->rrdpush_sender_buffer->buffer[begin + ret] = '\0';
  795. //debug(D_STREAM, "STREAM: sent from %zu to %zd:\n%s\n", begin, ret, &host->rrdpush_sender_buffer->buffer[begin]);
  796. //host->rrdpush_sender_buffer->buffer[begin + ret] = c;
  797. sent_bytes_on_this_connection += ret;
  798. sent_bytes += ret;
  799. begin += ret;
  800. if (begin == buffer_strlen(host->rrdpush_sender_buffer)) {
  801. // we send it all
  802. debug(D_STREAM, "STREAM: Sent %zd bytes (the whole buffer)...", ret);
  803. buffer_flush(host->rrdpush_sender_buffer);
  804. begin = 0;
  805. }
  806. else {
  807. debug(D_STREAM, "STREAM: Sent %zd bytes (part of the data buffer)...", ret);
  808. }
  809. last_sent_t = now_monotonic_sec();
  810. }
  811. else {
  812. debug(D_STREAM, "STREAM: send() returned %zd - closing the socket...", ret);
  813. error("STREAM %s [send to %s]: failed to send metrics (send() returned %zd) - closing connection - we have sent %zu bytes on this connection.",
  814. host->hostname, connected_to, ret, sent_bytes_on_this_connection);
  815. rrdpush_sender_thread_close_socket(host);
  816. }
  817. debug(D_STREAM, "STREAM: Releasing exclusive lock on host...");
  818. rrdpush_buffer_unlock(host);
  819. netdata_thread_enable_cancelability();
  820. // END RRDPUSH LOCKED SESSION
  821. }
  822. else {
  823. debug(D_STREAM, "STREAM: we have sent the entire buffer, but we received POLLOUT...");
  824. }
  825. }
  826. if(host->rrdpush_sender_socket != -1) {
  827. char *error = NULL;
  828. if (unlikely(ofd->revents & POLLERR))
  829. error = "socket reports errors (POLLERR)";
  830. else if (unlikely(ofd->revents & POLLHUP))
  831. error = "connection closed by remote end (POLLHUP)";
  832. else if (unlikely(ofd->revents & POLLNVAL))
  833. error = "connection is invalid (POLLNVAL)";
  834. if(unlikely(error)) {
  835. debug(D_STREAM, "STREAM: %s - closing socket...", error);
  836. error("STREAM %s [send to %s]: %s - reopening socket - we have sent %zu bytes on this connection.", host->hostname, connected_to, error, sent_bytes_on_this_connection);
  837. rrdpush_sender_thread_close_socket(host);
  838. }
  839. }
  840. }
  841. else {
  842. debug(D_STREAM, "STREAM: poll() timed out.");
  843. }
  844. // protection from overflow
  845. if(buffer_strlen(host->rrdpush_sender_buffer) > max_size) {
  846. debug(D_STREAM, "STREAM: Buffer is too big (%zu bytes), bigger than the max (%zu) - flushing it...", buffer_strlen(host->rrdpush_sender_buffer), max_size);
  847. errno = 0;
  848. error("STREAM %s [send to %s]: too many data pending - buffer is %zu bytes long, %zu unsent - we have sent %zu bytes in total, %zu on this connection. Closing connection to flush the data.", host->hostname, connected_to, host->rrdpush_sender_buffer->len, host->rrdpush_sender_buffer->len - begin, sent_bytes, sent_bytes_on_this_connection);
  849. rrdpush_sender_thread_close_socket(host);
  850. }
  851. }
  852. netdata_thread_cleanup_pop(1);
  853. return NULL;
  854. }
  855. // ----------------------------------------------------------------------------
  856. // rrdpush receiver thread
  857. static 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) {
  858. 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);
  859. }
  860. static RRDPUSH_MULTIPLE_CONNECTIONS_STRATEGY get_multiple_connections_strategy(struct config *c, const char *section, const char *name, RRDPUSH_MULTIPLE_CONNECTIONS_STRATEGY def) {
  861. char *value;
  862. switch(def) {
  863. default:
  864. case RRDPUSH_MULTIPLE_CONNECTIONS_ALLOW:
  865. value = "allow";
  866. break;
  867. case RRDPUSH_MULTIPLE_CONNECTIONS_DENY_NEW:
  868. value = "deny";
  869. break;
  870. }
  871. value = appconfig_get(c, section, name, value);
  872. RRDPUSH_MULTIPLE_CONNECTIONS_STRATEGY ret = def;
  873. if(strcasecmp(value, "allow") == 0 || strcasecmp(value, "permit") == 0 || strcasecmp(value, "accept") == 0)
  874. ret = RRDPUSH_MULTIPLE_CONNECTIONS_ALLOW;
  875. else if(strcasecmp(value, "deny") == 0 || strcasecmp(value, "reject") == 0 || strcasecmp(value, "block") == 0)
  876. ret = RRDPUSH_MULTIPLE_CONNECTIONS_DENY_NEW;
  877. else
  878. error("Invalid stream config value at section [%s], setting '%s', value '%s'", section, name, value);
  879. return ret;
  880. }
  881. static int rrdpush_receive(int fd
  882. , const char *key
  883. , const char *hostname
  884. , const char *registry_hostname
  885. , const char *machine_guid
  886. , const char *os
  887. , const char *timezone
  888. , const char *tags
  889. , const char *program_name
  890. , const char *program_version
  891. , struct rrdhost_system_info *system_info
  892. , int update_every
  893. , char *client_ip
  894. , char *client_port
  895. , uint32_t stream_version
  896. #ifdef ENABLE_HTTPS
  897. , struct netdata_ssl *ssl
  898. #endif
  899. ) {
  900. RRDHOST *host;
  901. int history = default_rrd_history_entries;
  902. RRD_MEMORY_MODE mode = default_rrd_memory_mode;
  903. int health_enabled = default_health_enabled;
  904. int rrdpush_enabled = default_rrdpush_enabled;
  905. char *rrdpush_destination = default_rrdpush_destination;
  906. char *rrdpush_api_key = default_rrdpush_api_key;
  907. char *rrdpush_send_charts_matching = default_rrdpush_send_charts_matching;
  908. time_t alarms_delay = 60;
  909. RRDPUSH_MULTIPLE_CONNECTIONS_STRATEGY rrdpush_multiple_connections_strategy = RRDPUSH_MULTIPLE_CONNECTIONS_ALLOW;
  910. update_every = (int)appconfig_get_number(&stream_config, machine_guid, "update every", update_every);
  911. if(update_every < 0) update_every = 1;
  912. history = (int)appconfig_get_number(&stream_config, key, "default history", history);
  913. history = (int)appconfig_get_number(&stream_config, machine_guid, "history", history);
  914. if(history < 5) history = 5;
  915. mode = rrd_memory_mode_id(appconfig_get(&stream_config, key, "default memory mode", rrd_memory_mode_name(mode)));
  916. mode = rrd_memory_mode_id(appconfig_get(&stream_config, machine_guid, "memory mode", rrd_memory_mode_name(mode)));
  917. health_enabled = appconfig_get_boolean_ondemand(&stream_config, key, "health enabled by default", health_enabled);
  918. health_enabled = appconfig_get_boolean_ondemand(&stream_config, machine_guid, "health enabled", health_enabled);
  919. alarms_delay = appconfig_get_number(&stream_config, key, "default postpone alarms on connect seconds", alarms_delay);
  920. alarms_delay = appconfig_get_number(&stream_config, machine_guid, "postpone alarms on connect seconds", alarms_delay);
  921. rrdpush_enabled = appconfig_get_boolean(&stream_config, key, "default proxy enabled", rrdpush_enabled);
  922. rrdpush_enabled = appconfig_get_boolean(&stream_config, machine_guid, "proxy enabled", rrdpush_enabled);
  923. rrdpush_destination = appconfig_get(&stream_config, key, "default proxy destination", rrdpush_destination);
  924. rrdpush_destination = appconfig_get(&stream_config, machine_guid, "proxy destination", rrdpush_destination);
  925. rrdpush_api_key = appconfig_get(&stream_config, key, "default proxy api key", rrdpush_api_key);
  926. rrdpush_api_key = appconfig_get(&stream_config, machine_guid, "proxy api key", rrdpush_api_key);
  927. rrdpush_multiple_connections_strategy = get_multiple_connections_strategy(&stream_config, key, "multiple connections", rrdpush_multiple_connections_strategy);
  928. rrdpush_multiple_connections_strategy = get_multiple_connections_strategy(&stream_config, machine_guid, "multiple connections", rrdpush_multiple_connections_strategy);
  929. rrdpush_send_charts_matching = appconfig_get(&stream_config, key, "default proxy send charts matching", rrdpush_send_charts_matching);
  930. rrdpush_send_charts_matching = appconfig_get(&stream_config, machine_guid, "proxy send charts matching", rrdpush_send_charts_matching);
  931. tags = appconfig_set_default(&stream_config, machine_guid, "host tags", (tags)?tags:"");
  932. if(tags && !*tags) tags = NULL;
  933. if (strcmp(machine_guid, localhost->machine_guid) == 0) {
  934. log_stream_connection(client_ip, client_port, key, machine_guid, hostname, "DENIED - ATTEMPT TO RECEIVE METRICS FROM MACHINE_GUID IDENTICAL TO MASTER");
  935. error("STREAM %s [receive from %s:%s]: denied to receive metrics, machine GUID [%s] is my own. Did you copy the master/proxy machine guid to a slave?", hostname, client_ip, client_port, machine_guid);
  936. close(fd);
  937. return 1;
  938. }
  939. else
  940. host = rrdhost_find_or_create(
  941. hostname
  942. , registry_hostname
  943. , machine_guid
  944. , os
  945. , timezone
  946. , tags
  947. , program_name
  948. , program_version
  949. , update_every
  950. , history
  951. , mode
  952. , (unsigned int)(health_enabled != CONFIG_BOOLEAN_NO)
  953. , (unsigned int)(rrdpush_enabled && rrdpush_destination && *rrdpush_destination && rrdpush_api_key && *rrdpush_api_key)
  954. , rrdpush_destination
  955. , rrdpush_api_key
  956. , rrdpush_send_charts_matching
  957. , system_info
  958. );
  959. if(!host) {
  960. close(fd);
  961. log_stream_connection(client_ip, client_port, key, machine_guid, hostname, "FAILED - CANNOT ACQUIRE HOST");
  962. error("STREAM %s [receive from [%s]:%s]: failed to find/create host structure.", hostname, client_ip, client_port);
  963. return 1;
  964. }
  965. #ifdef NETDATA_INTERNAL_CHECKS
  966. info("STREAM %s [receive from [%s]:%s]: client willing to stream metrics for host '%s' with machine_guid '%s': update every = %d, history = %ld, memory mode = %s, health %s, tags '%s'"
  967. , hostname
  968. , client_ip
  969. , client_port
  970. , host->hostname
  971. , host->machine_guid
  972. , host->rrd_update_every
  973. , host->rrd_history_entries
  974. , rrd_memory_mode_name(host->rrd_memory_mode)
  975. , (health_enabled == CONFIG_BOOLEAN_NO)?"disabled":((health_enabled == CONFIG_BOOLEAN_YES)?"enabled":"auto")
  976. , host->tags?host->tags:""
  977. );
  978. #endif // NETDATA_INTERNAL_CHECKS
  979. struct plugind cd = {
  980. .enabled = 1,
  981. .update_every = default_rrd_update_every,
  982. .pid = 0,
  983. .serial_failures = 0,
  984. .successful_collections = 0,
  985. .obsolete = 0,
  986. .started_t = now_realtime_sec(),
  987. .next = NULL,
  988. };
  989. // put the client IP and port into the buffers used by plugins.d
  990. snprintfz(cd.id, CONFIG_MAX_NAME, "%s:%s", client_ip, client_port);
  991. snprintfz(cd.filename, FILENAME_MAX, "%s:%s", client_ip, client_port);
  992. snprintfz(cd.fullfilename, FILENAME_MAX, "%s:%s", client_ip, client_port);
  993. snprintfz(cd.cmd, PLUGINSD_CMD_MAX, "%s:%s", client_ip, client_port);
  994. info("STREAM %s [receive from [%s]:%s]: initializing communication...", host->hostname, client_ip, client_port);
  995. char initial_response[HTTP_HEADER_SIZE];
  996. if (stream_version > 1) {
  997. info("STREAM %s [receive from [%s]:%s]: Netdata is using the stream version %u.", host->hostname, client_ip, client_port, stream_version);
  998. sprintf(initial_response, "%s%u", START_STREAMING_PROMPT_VN, stream_version);
  999. } else if (stream_version == 1) {
  1000. info("STREAM %s [receive from [%s]:%s]: Netdata is using the stream version %u.", host->hostname, client_ip, client_port, stream_version);
  1001. sprintf(initial_response, "%s", START_STREAMING_PROMPT_V2);
  1002. } else {
  1003. info("STREAM %s [receive from [%s]:%s]: Netdata is using first stream protocol.", host->hostname, client_ip, client_port);
  1004. sprintf(initial_response, "%s", START_STREAMING_PROMPT);
  1005. }
  1006. #ifdef ENABLE_HTTPS
  1007. host->stream_ssl.conn = ssl->conn;
  1008. host->stream_ssl.flags = ssl->flags;
  1009. if(send_timeout(ssl, fd, initial_response, strlen(initial_response), 0, 60) != (ssize_t)strlen(initial_response)) {
  1010. #else
  1011. if(send_timeout(fd, initial_response, strlen(initial_response), 0, 60) != strlen(initial_response)) {
  1012. #endif
  1013. log_stream_connection(client_ip, client_port, key, host->machine_guid, host->hostname, "FAILED - CANNOT REPLY");
  1014. error("STREAM %s [receive from [%s]:%s]: cannot send ready command.", host->hostname, client_ip, client_port);
  1015. close(fd);
  1016. return 0;
  1017. }
  1018. // remove the non-blocking flag from the socket
  1019. if(sock_delnonblock(fd) < 0)
  1020. error("STREAM %s [receive from [%s]:%s]: cannot remove the non-blocking flag from socket %d", host->hostname, client_ip, client_port, fd);
  1021. // convert the socket to a FILE *
  1022. FILE *fp = fdopen(fd, "r");
  1023. if(!fp) {
  1024. log_stream_connection(client_ip, client_port, key, host->machine_guid, host->hostname, "FAILED - SOCKET ERROR");
  1025. error("STREAM %s [receive from [%s]:%s]: failed to get a FILE for FD %d.", host->hostname, client_ip, client_port, fd);
  1026. close(fd);
  1027. return 0;
  1028. }
  1029. rrdhost_wrlock(host);
  1030. if(host->connected_senders > 0) {
  1031. switch(rrdpush_multiple_connections_strategy) {
  1032. case RRDPUSH_MULTIPLE_CONNECTIONS_ALLOW:
  1033. info("STREAM %s [receive from [%s]:%s]: multiple streaming connections for the same host detected. If multiple netdata are pushing metrics for the same charts, at the same time, the result is unexpected.", host->hostname, client_ip, client_port);
  1034. break;
  1035. case RRDPUSH_MULTIPLE_CONNECTIONS_DENY_NEW:
  1036. rrdhost_unlock(host);
  1037. log_stream_connection(client_ip, client_port, key, host->machine_guid, host->hostname, "REJECTED - ALREADY CONNECTED");
  1038. info("STREAM %s [receive from [%s]:%s]: multiple streaming connections for the same host detected. Rejecting new connection.", host->hostname, client_ip, client_port);
  1039. fclose(fp);
  1040. return 0;
  1041. }
  1042. }
  1043. rrdhost_flag_clear(host, RRDHOST_FLAG_ORPHAN);
  1044. host->connected_senders++;
  1045. host->senders_disconnected_time = 0;
  1046. host->labels_flag = (stream_version > 0)?LABEL_FLAG_UPDATE_STREAM:LABEL_FLAG_STOP_STREAM;
  1047. if(health_enabled != CONFIG_BOOLEAN_NO) {
  1048. if(alarms_delay > 0) {
  1049. host->health_delay_up_to = now_realtime_sec() + alarms_delay;
  1050. info("Postponing health checks for %ld seconds, on host '%s', because it was just connected."
  1051. , alarms_delay
  1052. , host->hostname
  1053. );
  1054. }
  1055. }
  1056. rrdhost_unlock(host);
  1057. // call the plugins.d processor to receive the metrics
  1058. info("STREAM %s [receive from [%s]:%s]: receiving metrics...", host->hostname, client_ip, client_port);
  1059. log_stream_connection(client_ip, client_port, key, host->machine_guid, host->hostname, "CONNECTED");
  1060. size_t count = pluginsd_process(host, &cd, fp, 1);
  1061. log_stream_connection(client_ip, client_port, key, host->machine_guid, host->hostname, "DISCONNECTED");
  1062. error("STREAM %s [receive from [%s]:%s]: disconnected (completed %zu updates).", host->hostname, client_ip, client_port, count);
  1063. rrdhost_wrlock(host);
  1064. host->senders_disconnected_time = now_realtime_sec();
  1065. host->connected_senders--;
  1066. if(!host->connected_senders) {
  1067. rrdhost_flag_set(host, RRDHOST_FLAG_ORPHAN);
  1068. if(health_enabled == CONFIG_BOOLEAN_AUTO)
  1069. host->health_enabled = 0;
  1070. }
  1071. rrdhost_unlock(host);
  1072. if(host->connected_senders == 0)
  1073. rrdpush_sender_thread_stop(host);
  1074. // cleanup
  1075. fclose(fp);
  1076. return (int)count;
  1077. }
  1078. struct rrdpush_thread {
  1079. int fd;
  1080. char *key;
  1081. char *hostname;
  1082. char *registry_hostname;
  1083. char *machine_guid;
  1084. char *os;
  1085. char *timezone;
  1086. char *tags;
  1087. char *client_ip;
  1088. char *client_port;
  1089. char *program_name;
  1090. char *program_version;
  1091. struct rrdhost_system_info *system_info;
  1092. int update_every;
  1093. uint32_t stream_version;
  1094. #ifdef ENABLE_HTTPS
  1095. struct netdata_ssl ssl;
  1096. #endif
  1097. };
  1098. static void rrdpush_receiver_thread_cleanup(void *ptr) {
  1099. static __thread int executed = 0;
  1100. if(!executed) {
  1101. executed = 1;
  1102. struct rrdpush_thread *rpt = (struct rrdpush_thread *) ptr;
  1103. info("STREAM %s [receive from [%s]:%s]: receive thread ended (task id %d)", rpt->hostname, rpt->client_ip, rpt->client_port, gettid());
  1104. freez(rpt->key);
  1105. freez(rpt->hostname);
  1106. freez(rpt->registry_hostname);
  1107. freez(rpt->machine_guid);
  1108. freez(rpt->os);
  1109. freez(rpt->timezone);
  1110. freez(rpt->tags);
  1111. freez(rpt->client_ip);
  1112. freez(rpt->client_port);
  1113. freez(rpt->program_name);
  1114. freez(rpt->program_version);
  1115. #ifdef ENABLE_HTTPS
  1116. if(rpt->ssl.conn){
  1117. SSL_free(rpt->ssl.conn);
  1118. }
  1119. #endif
  1120. freez(rpt);
  1121. }
  1122. }
  1123. static void *rrdpush_receiver_thread(void *ptr) {
  1124. netdata_thread_cleanup_push(rrdpush_receiver_thread_cleanup, ptr);
  1125. struct rrdpush_thread *rpt = (struct rrdpush_thread *)ptr;
  1126. info("STREAM %s [%s]:%s: receive thread created (task id %d)", rpt->hostname, rpt->client_ip, rpt->client_port, gettid());
  1127. rrdpush_receive(
  1128. rpt->fd
  1129. , rpt->key
  1130. , rpt->hostname
  1131. , rpt->registry_hostname
  1132. , rpt->machine_guid
  1133. , rpt->os
  1134. , rpt->timezone
  1135. , rpt->tags
  1136. , rpt->program_name
  1137. , rpt->program_version
  1138. , rpt->system_info
  1139. , rpt->update_every
  1140. , rpt->client_ip
  1141. , rpt->client_port
  1142. , rpt->stream_version
  1143. #ifdef ENABLE_HTTPS
  1144. , &rpt->ssl
  1145. #endif
  1146. );
  1147. netdata_thread_cleanup_pop(1);
  1148. return NULL;
  1149. }
  1150. static void rrdpush_sender_thread_spawn(RRDHOST *host) {
  1151. rrdhost_wrlock(host);
  1152. if(!host->rrdpush_sender_spawn) {
  1153. char tag[NETDATA_THREAD_TAG_MAX + 1];
  1154. snprintfz(tag, NETDATA_THREAD_TAG_MAX, "STREAM_SENDER[%s]", host->hostname);
  1155. if(netdata_thread_create(&host->rrdpush_sender_thread, tag, NETDATA_THREAD_OPTION_JOINABLE, rrdpush_sender_thread, (void *) host))
  1156. error("STREAM %s [send]: failed to create new thread for client.", host->hostname);
  1157. else
  1158. host->rrdpush_sender_spawn = 1;
  1159. }
  1160. rrdhost_unlock(host);
  1161. }
  1162. int rrdpush_receiver_permission_denied(struct web_client *w) {
  1163. // we always respond with the same message and error code
  1164. // to prevent an attacker from gaining info about the error
  1165. buffer_flush(w->response.data);
  1166. buffer_sprintf(w->response.data, "You are not permitted to access this. Check the logs for more info.");
  1167. return 401;
  1168. }
  1169. int rrdpush_receiver_too_busy_now(struct web_client *w) {
  1170. // we always respond with the same message and error code
  1171. // to prevent an attacker from gaining info about the error
  1172. buffer_flush(w->response.data);
  1173. buffer_sprintf(w->response.data, "The server is too busy now to accept this request. Try later.");
  1174. return 503;
  1175. }
  1176. int rrdpush_receiver_thread_spawn(RRDHOST *host, struct web_client *w, char *url) {
  1177. (void)host;
  1178. info("clients wants to STREAM metrics.");
  1179. char *key = NULL, *hostname = NULL, *registry_hostname = NULL, *machine_guid = NULL, *os = "unknown", *timezone = "unknown", *tags = NULL;
  1180. int update_every = default_rrd_update_every;
  1181. uint32_t stream_version = UINT_MAX;
  1182. char buf[GUID_LEN + 1];
  1183. struct rrdhost_system_info *system_info = callocz(1, sizeof(struct rrdhost_system_info));
  1184. while(url) {
  1185. char *value = mystrsep(&url, "&");
  1186. if(!value || !*value) continue;
  1187. char *name = mystrsep(&value, "=");
  1188. if(!name || !*name) continue;
  1189. if(!value || !*value) continue;
  1190. if(!strcmp(name, "key"))
  1191. key = value;
  1192. else if(!strcmp(name, "hostname"))
  1193. hostname = value;
  1194. else if(!strcmp(name, "registry_hostname"))
  1195. registry_hostname = value;
  1196. else if(!strcmp(name, "machine_guid"))
  1197. machine_guid = value;
  1198. else if(!strcmp(name, "update_every"))
  1199. update_every = (int)strtoul(value, NULL, 0);
  1200. else if(!strcmp(name, "os"))
  1201. os = value;
  1202. else if(!strcmp(name, "timezone"))
  1203. timezone = value;
  1204. else if(!strcmp(name, "tags"))
  1205. tags = value;
  1206. else if(!strcmp(name, "ver"))
  1207. stream_version = MIN((uint32_t) strtoul(value, NULL, 0), STREAMING_PROTOCOL_CURRENT_VERSION);
  1208. else {
  1209. // An old Netdata slave does not have a compatible streaming protocol, map to something sane.
  1210. if (!strcmp(name, "NETDATA_SYSTEM_OS_NAME"))
  1211. name = "NETDATA_HOST_OS_NAME";
  1212. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID"))
  1213. name = "NETDATA_HOST_OS_ID";
  1214. else if (!strcmp(name, "NETDATA_SYSTEM_OS_ID_LIKE"))
  1215. name = "NETDATA_HOST_OS_ID_LIKE";
  1216. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION"))
  1217. name = "NETDATA_HOST_OS_VERSION";
  1218. else if (!strcmp(name, "NETDATA_SYSTEM_OS_VERSION_ID"))
  1219. name = "NETDATA_HOST_OS_VERSION_ID";
  1220. else if (!strcmp(name, "NETDATA_SYSTEM_OS_DETECTION"))
  1221. name = "NETDATA_HOST_OS_DETECTION";
  1222. else if(!strcmp(name, "NETDATA_PROTOCOL_VERSION") && stream_version == UINT_MAX) {
  1223. stream_version = 1;
  1224. }
  1225. if (unlikely(rrdhost_set_system_info_variable(system_info, name, value))) {
  1226. info("STREAM [receive from [%s]:%s]: request has parameter '%s' = '%s', which is not used.",
  1227. w->client_ip, w->client_port, name, value);
  1228. }
  1229. }
  1230. }
  1231. if (stream_version == UINT_MAX)
  1232. stream_version = 0;
  1233. if(!key || !*key) {
  1234. rrdhost_system_info_free(system_info);
  1235. 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");
  1236. error("STREAM [receive from [%s]:%s]: request without an API key. Forbidding access.", w->client_ip, w->client_port);
  1237. return rrdpush_receiver_permission_denied(w);
  1238. }
  1239. if(!hostname || !*hostname) {
  1240. rrdhost_system_info_free(system_info);
  1241. 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");
  1242. error("STREAM [receive from [%s]:%s]: request without a hostname. Forbidding access.", w->client_ip, w->client_port);
  1243. return rrdpush_receiver_permission_denied(w);
  1244. }
  1245. if(!machine_guid || !*machine_guid) {
  1246. rrdhost_system_info_free(system_info);
  1247. 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");
  1248. error("STREAM [receive from [%s]:%s]: request without a machine GUID. Forbidding access.", w->client_ip, w->client_port);
  1249. return rrdpush_receiver_permission_denied(w);
  1250. }
  1251. if(regenerate_guid(key, buf) == -1) {
  1252. rrdhost_system_info_free(system_info);
  1253. 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");
  1254. 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);
  1255. return rrdpush_receiver_permission_denied(w);
  1256. }
  1257. if(regenerate_guid(machine_guid, buf) == -1) {
  1258. rrdhost_system_info_free(system_info);
  1259. 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");
  1260. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not GUID. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  1261. return rrdpush_receiver_permission_denied(w);
  1262. }
  1263. if(!appconfig_get_boolean(&stream_config, key, "enabled", 0)) {
  1264. rrdhost_system_info_free(system_info);
  1265. 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");
  1266. error("STREAM [receive from [%s]:%s]: API key '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, key);
  1267. return rrdpush_receiver_permission_denied(w);
  1268. }
  1269. {
  1270. SIMPLE_PATTERN *key_allow_from = simple_pattern_create(appconfig_get(&stream_config, key, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  1271. if(key_allow_from) {
  1272. if(!simple_pattern_matches(key_allow_from, w->client_ip)) {
  1273. simple_pattern_free(key_allow_from);
  1274. rrdhost_system_info_free(system_info);
  1275. 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");
  1276. error("STREAM [receive from [%s]:%s]: API key '%s' is not permitted from this IP. Forbidding access.", w->client_ip, w->client_port, key);
  1277. return rrdpush_receiver_permission_denied(w);
  1278. }
  1279. simple_pattern_free(key_allow_from);
  1280. }
  1281. }
  1282. if(!appconfig_get_boolean(&stream_config, machine_guid, "enabled", 1)) {
  1283. rrdhost_system_info_free(system_info);
  1284. 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");
  1285. error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, machine_guid);
  1286. return rrdpush_receiver_permission_denied(w);
  1287. }
  1288. {
  1289. SIMPLE_PATTERN *machine_allow_from = simple_pattern_create(appconfig_get(&stream_config, machine_guid, "allow from", "*"), NULL, SIMPLE_PATTERN_EXACT);
  1290. if(machine_allow_from) {
  1291. if(!simple_pattern_matches(machine_allow_from, w->client_ip)) {
  1292. simple_pattern_free(machine_allow_from);
  1293. rrdhost_system_info_free(system_info);
  1294. 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");
  1295. 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);
  1296. return rrdpush_receiver_permission_denied(w);
  1297. }
  1298. simple_pattern_free(machine_allow_from);
  1299. }
  1300. }
  1301. if(unlikely(web_client_streaming_rate_t > 0)) {
  1302. static netdata_mutex_t stream_rate_mutex = NETDATA_MUTEX_INITIALIZER;
  1303. static volatile time_t last_stream_accepted_t = 0;
  1304. netdata_mutex_lock(&stream_rate_mutex);
  1305. time_t now = now_realtime_sec();
  1306. if(unlikely(last_stream_accepted_t == 0))
  1307. last_stream_accepted_t = now;
  1308. if(now - last_stream_accepted_t < web_client_streaming_rate_t) {
  1309. netdata_mutex_unlock(&stream_rate_mutex);
  1310. rrdhost_system_info_free(system_info);
  1311. 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)));
  1312. return rrdpush_receiver_too_busy_now(w);
  1313. }
  1314. last_stream_accepted_t = now;
  1315. netdata_mutex_unlock(&stream_rate_mutex);
  1316. }
  1317. struct rrdpush_thread *rpt = callocz(1, sizeof(struct rrdpush_thread));
  1318. rpt->fd = w->ifd;
  1319. rpt->key = strdupz(key);
  1320. rpt->hostname = strdupz(hostname);
  1321. rpt->registry_hostname = strdupz((registry_hostname && *registry_hostname)?registry_hostname:hostname);
  1322. rpt->machine_guid = strdupz(machine_guid);
  1323. rpt->os = strdupz(os);
  1324. rpt->timezone = strdupz(timezone);
  1325. rpt->tags = (tags)?strdupz(tags):NULL;
  1326. rpt->client_ip = strdupz(w->client_ip);
  1327. rpt->client_port = strdupz(w->client_port);
  1328. rpt->update_every = update_every;
  1329. rpt->system_info = system_info;
  1330. rpt->stream_version = stream_version;
  1331. #ifdef ENABLE_HTTPS
  1332. rpt->ssl.conn = w->ssl.conn;
  1333. rpt->ssl.flags = w->ssl.flags;
  1334. w->ssl.conn = NULL;
  1335. w->ssl.flags = NETDATA_SSL_START;
  1336. #endif
  1337. if(w->user_agent && w->user_agent[0]) {
  1338. char *t = strchr(w->user_agent, '/');
  1339. if(t && *t) {
  1340. *t = '\0';
  1341. t++;
  1342. }
  1343. rpt->program_name = strdupz(w->user_agent);
  1344. if(t && *t) rpt->program_version = strdupz(t);
  1345. }
  1346. netdata_thread_t thread;
  1347. debug(D_SYSTEM, "starting STREAM receive thread.");
  1348. char tag[FILENAME_MAX + 1];
  1349. snprintfz(tag, FILENAME_MAX, "STREAM_RECEIVER[%s,[%s]:%s]", rpt->hostname, w->client_ip, w->client_port);
  1350. if(netdata_thread_create(&thread, tag, NETDATA_THREAD_OPTION_DEFAULT, rrdpush_receiver_thread, (void *)rpt))
  1351. error("Failed to create new STREAM receive thread for client.");
  1352. // prevent the caller from closing the streaming socket
  1353. if(web_server_mode == WEB_SERVER_MODE_STATIC_THREADED) {
  1354. web_client_flag_set(w, WEB_CLIENT_FLAG_DONT_CLOSE_SOCKET);
  1355. }
  1356. else {
  1357. if(w->ifd == w->ofd)
  1358. w->ifd = w->ofd = -1;
  1359. else
  1360. w->ifd = -1;
  1361. }
  1362. buffer_flush(w->response.data);
  1363. return 200;
  1364. }