sender.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "rrdpush.h"
  3. #define WORKER_SENDER_JOB_CONNECT 0
  4. #define WORKER_SENDER_JOB_PIPE_READ 1
  5. #define WORKER_SENDER_JOB_SOCKET_RECEIVE 2
  6. #define WORKER_SENDER_JOB_EXECUTE 3
  7. #define WORKER_SENDER_JOB_SOCKET_SEND 4
  8. #define WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE 5
  9. #define WORKER_SENDER_JOB_DISCONNECT_OVERFLOW 6
  10. #define WORKER_SENDER_JOB_DISCONNECT_TIMEOUT 7
  11. #define WORKER_SENDER_JOB_DISCONNECT_POLL_ERROR 8
  12. #define WORKER_SENDER_JOB_DISCONNECT_SOCKER_ERROR 9
  13. #define WORKER_SENDER_JOB_DISCONNECT_SSL_ERROR 10
  14. #define WORKER_SENDER_JOB_DISCONNECT_PARENT_CLOSED 11
  15. #define WORKER_SENDER_JOB_DISCONNECT_RECEIVE_ERROR 12
  16. #define WORKER_SENDER_JOB_DISCONNECT_SEND_ERROR 13
  17. #define WORKER_SENDER_JOB_DISCONNECT_NO_COMPRESSION 14
  18. #define WORKER_SENDER_JOB_BUFFER_RATIO 15
  19. #define WORKER_SENDER_JOB_BYTES_RECEIVED 16
  20. #define WORKER_SENDER_JOB_BYTES_SENT 17
  21. #define WORKER_SENDER_JOB_REPLAY_REQUEST 18
  22. #define WORKER_SENDER_JOB_FUNCTION_REQUEST 19
  23. #define WORKER_SENDER_JOB_REPLAY_DICT_SIZE 20
  24. #if WORKER_UTILIZATION_MAX_JOB_TYPES < 21
  25. #error WORKER_UTILIZATION_MAX_JOB_TYPES has to be at least 21
  26. #endif
  27. extern struct config stream_config;
  28. extern int netdata_use_ssl_on_stream;
  29. extern char *netdata_ssl_ca_path;
  30. extern char *netdata_ssl_ca_file;
  31. static __thread BUFFER *sender_thread_buffer = NULL;
  32. static __thread bool sender_thread_buffer_used = false;
  33. static __thread time_t sender_thread_buffer_last_reset_s = 0;
  34. void sender_thread_buffer_free(void) {
  35. buffer_free(sender_thread_buffer);
  36. sender_thread_buffer = NULL;
  37. sender_thread_buffer_used = false;
  38. }
  39. // Collector thread starting a transmission
  40. BUFFER *sender_start(struct sender_state *s) {
  41. if(unlikely(sender_thread_buffer_used))
  42. fatal("STREAMING: thread buffer is used multiple times concurrently.");
  43. if(unlikely(rrdpush_sender_last_buffer_recreate_get(s) > sender_thread_buffer_last_reset_s)) {
  44. if(unlikely(sender_thread_buffer && sender_thread_buffer->size > THREAD_BUFFER_INITIAL_SIZE)) {
  45. buffer_free(sender_thread_buffer);
  46. sender_thread_buffer = NULL;
  47. }
  48. }
  49. if(unlikely(!sender_thread_buffer)) {
  50. sender_thread_buffer = buffer_create(THREAD_BUFFER_INITIAL_SIZE, &netdata_buffers_statistics.buffers_streaming);
  51. sender_thread_buffer_last_reset_s = rrdpush_sender_last_buffer_recreate_get(s);
  52. }
  53. sender_thread_buffer_used = true;
  54. buffer_flush(sender_thread_buffer);
  55. return sender_thread_buffer;
  56. }
  57. static inline void rrdpush_sender_thread_close_socket(RRDHOST *host);
  58. #ifdef ENABLE_COMPRESSION
  59. /*
  60. * In case of stream compression buffer overflow
  61. * Inform the user through the error log file and
  62. * deactivate compression by downgrading the stream protocol.
  63. */
  64. static inline void deactivate_compression(struct sender_state *s) {
  65. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_NO_COMPRESSION);
  66. error("STREAM_COMPRESSION: Compression returned error, disabling it.");
  67. s->flags &= ~SENDER_FLAG_COMPRESSION;
  68. error("STREAM %s [send to %s]: Restarting connection without compression.", rrdhost_hostname(s->host), s->connected_to);
  69. rrdpush_sender_thread_close_socket(s->host);
  70. }
  71. #endif
  72. #define SENDER_BUFFER_ADAPT_TO_TIMES_MAX_SIZE 3
  73. // Collector thread finishing a transmission
  74. void sender_commit(struct sender_state *s, BUFFER *wb) {
  75. if(unlikely(wb != sender_thread_buffer))
  76. fatal("STREAMING: sender is trying to commit a buffer that is not this thread's buffer.");
  77. if(unlikely(!sender_thread_buffer_used))
  78. fatal("STREAMING: sender is committing a buffer twice.");
  79. sender_thread_buffer_used = false;
  80. char *src = (char *)buffer_tostring(wb);
  81. size_t src_len = buffer_strlen(wb);
  82. if(unlikely(!src || !src_len))
  83. return;
  84. netdata_mutex_lock(&s->mutex);
  85. // FILE *fp = fopen("/tmp/stream.txt", "a");
  86. // fprintf(fp,
  87. // "\n--- SEND BEGIN: %s ----\n"
  88. // "%s"
  89. // "--- SEND END ----------------------------------------\n"
  90. // , rrdhost_hostname(s->host), src);
  91. // fclose(fp);
  92. if(unlikely(s->buffer->max_size < (src_len + 1) * SENDER_BUFFER_ADAPT_TO_TIMES_MAX_SIZE)) {
  93. info("STREAM %s [send to %s]: max buffer size of %zu is too small for a data message of size %zu. Increasing the max buffer size to %d times the max data message size.",
  94. rrdhost_hostname(s->host), s->connected_to, s->buffer->max_size, buffer_strlen(wb) + 1, SENDER_BUFFER_ADAPT_TO_TIMES_MAX_SIZE);
  95. s->buffer->max_size = (src_len + 1) * SENDER_BUFFER_ADAPT_TO_TIMES_MAX_SIZE;
  96. }
  97. #ifdef ENABLE_COMPRESSION
  98. if (stream_has_capability(s, STREAM_CAP_COMPRESSION) && s->compressor) {
  99. while(src_len) {
  100. size_t size_to_compress = src_len;
  101. if(unlikely(size_to_compress > COMPRESSION_MAX_MSG_SIZE)) {
  102. if (stream_has_capability(s, STREAM_CAP_BINARY))
  103. size_to_compress = COMPRESSION_MAX_MSG_SIZE;
  104. else {
  105. if (size_to_compress > COMPRESSION_MAX_MSG_SIZE) {
  106. // we need to find the last newline
  107. // so that the decompressor will have a whole line to work with
  108. const char *t = &src[COMPRESSION_MAX_MSG_SIZE];
  109. while (--t >= src)
  110. if (unlikely(*t == '\n'))
  111. break;
  112. if (t <= src) {
  113. size_to_compress = COMPRESSION_MAX_MSG_SIZE;
  114. } else
  115. size_to_compress = t - src + 1;
  116. }
  117. }
  118. }
  119. char *dst;
  120. size_t dst_len = s->compressor->compress(s->compressor, src, size_to_compress, &dst);
  121. if (!dst_len) {
  122. error("STREAM %s [send to %s]: COMPRESSION failed. Resetting compressor and re-trying",
  123. rrdhost_hostname(s->host), s->connected_to);
  124. s->compressor->reset(s->compressor);
  125. dst_len = s->compressor->compress(s->compressor, src, size_to_compress, &dst);
  126. if(!dst_len) {
  127. error("STREAM %s [send to %s]: COMPRESSION failed again. Deactivating compression",
  128. rrdhost_hostname(s->host), s->connected_to);
  129. deactivate_compression(s);
  130. netdata_mutex_unlock(&s->mutex);
  131. return;
  132. }
  133. }
  134. if(cbuffer_add_unsafe(s->buffer, dst, dst_len))
  135. s->flags |= SENDER_FLAG_OVERFLOW;
  136. src = src + size_to_compress;
  137. src_len -= size_to_compress;
  138. }
  139. }
  140. else if(cbuffer_add_unsafe(s->buffer, src, src_len))
  141. s->flags |= SENDER_FLAG_OVERFLOW;
  142. #else
  143. if(cbuffer_add_unsafe(s->buffer, src, src_len))
  144. s->flags |= SENDER_FLAG_OVERFLOW;
  145. #endif
  146. replication_recalculate_buffer_used_ratio_unsafe(s);
  147. bool signal_sender = false;
  148. if(!rrdpush_sender_pipe_has_pending_data(s)) {
  149. rrdpush_sender_pipe_set_pending_data(s);
  150. signal_sender = true;
  151. }
  152. netdata_mutex_unlock(&s->mutex);
  153. if(signal_sender)
  154. rrdpush_signal_sender_to_wake_up(s);
  155. }
  156. static inline void rrdpush_sender_add_host_variable_to_buffer(BUFFER *wb, const RRDVAR_ACQUIRED *rva) {
  157. buffer_sprintf(
  158. wb
  159. , "VARIABLE HOST %s = " NETDATA_DOUBLE_FORMAT "\n"
  160. , rrdvar_name(rva)
  161. , rrdvar2number(rva)
  162. );
  163. debug(D_STREAM, "RRDVAR pushed HOST VARIABLE %s = " NETDATA_DOUBLE_FORMAT, rrdvar_name(rva), rrdvar2number(rva));
  164. }
  165. void rrdpush_sender_send_this_host_variable_now(RRDHOST *host, const RRDVAR_ACQUIRED *rva) {
  166. if(rrdhost_can_send_definitions_to_parent(host)) {
  167. BUFFER *wb = sender_start(host->sender);
  168. rrdpush_sender_add_host_variable_to_buffer(wb, rva);
  169. sender_commit(host->sender, wb);
  170. sender_thread_buffer_free();
  171. }
  172. }
  173. struct custom_host_variables_callback {
  174. BUFFER *wb;
  175. };
  176. static int rrdpush_sender_thread_custom_host_variables_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rrdvar_ptr __maybe_unused, void *struct_ptr) {
  177. const RRDVAR_ACQUIRED *rv = (const RRDVAR_ACQUIRED *)item;
  178. struct custom_host_variables_callback *tmp = struct_ptr;
  179. BUFFER *wb = tmp->wb;
  180. if(unlikely(rrdvar_flags(rv) & RRDVAR_FLAG_CUSTOM_HOST_VAR && rrdvar_type(rv) == RRDVAR_TYPE_CALCULATED)) {
  181. rrdpush_sender_add_host_variable_to_buffer(wb, rv);
  182. return 1;
  183. }
  184. return 0;
  185. }
  186. static void rrdpush_sender_thread_send_custom_host_variables(RRDHOST *host) {
  187. if(rrdhost_can_send_definitions_to_parent(host)) {
  188. BUFFER *wb = sender_start(host->sender);
  189. struct custom_host_variables_callback tmp = {
  190. .wb = wb
  191. };
  192. int ret = rrdvar_walkthrough_read(host->rrdvars, rrdpush_sender_thread_custom_host_variables_callback, &tmp);
  193. (void)ret;
  194. sender_commit(host->sender, wb);
  195. sender_thread_buffer_free();
  196. debug(D_STREAM, "RRDVAR sent %d VARIABLES", ret);
  197. }
  198. }
  199. // resets all the chart, so that their definitions
  200. // will be resent to the central netdata
  201. static void rrdpush_sender_thread_reset_all_charts(RRDHOST *host) {
  202. RRDSET *st;
  203. rrdset_foreach_read(st, host) {
  204. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED | RRDSET_FLAG_SENDER_REPLICATION_IN_PROGRESS);
  205. rrdset_flag_set(st, RRDSET_FLAG_SENDER_REPLICATION_FINISHED);
  206. st->upstream_resync_time_s = 0;
  207. RRDDIM *rd;
  208. rrddim_foreach_read(rd, st)
  209. rd->exposed = 0;
  210. rrddim_foreach_done(rd);
  211. }
  212. rrdset_foreach_done(st);
  213. rrdhost_sender_replicating_charts_zero(host);
  214. }
  215. static void rrdpush_sender_cbuffer_recreate_timed(struct sender_state *s, time_t now_s, bool have_mutex, bool force) {
  216. static __thread time_t last_reset_time_s = 0;
  217. if(!force && now_s - last_reset_time_s < 300)
  218. return;
  219. if(!have_mutex)
  220. netdata_mutex_lock(&s->mutex);
  221. rrdpush_sender_last_buffer_recreate_set(s, now_s);
  222. last_reset_time_s = now_s;
  223. if(s->buffer && s->buffer->size > CBUFFER_INITIAL_SIZE) {
  224. size_t max = s->buffer->max_size;
  225. cbuffer_free(s->buffer);
  226. s->buffer = cbuffer_new(CBUFFER_INITIAL_SIZE, max, &netdata_buffers_statistics.cbuffers_streaming);
  227. }
  228. sender_thread_buffer_free();
  229. if(!have_mutex)
  230. netdata_mutex_unlock(&s->mutex);
  231. }
  232. static void rrdpush_sender_cbuffer_flush(RRDHOST *host) {
  233. rrdpush_sender_set_flush_time(host->sender);
  234. netdata_mutex_lock(&host->sender->mutex);
  235. // flush the output buffer from any data it may have
  236. cbuffer_flush(host->sender->buffer);
  237. rrdpush_sender_cbuffer_recreate_timed(host->sender, now_monotonic_sec(), true, true);
  238. replication_recalculate_buffer_used_ratio_unsafe(host->sender);
  239. netdata_mutex_unlock(&host->sender->mutex);
  240. }
  241. static void rrdpush_sender_charts_and_replication_reset(RRDHOST *host) {
  242. rrdpush_sender_set_flush_time(host->sender);
  243. // stop all replication commands inflight
  244. replication_sender_delete_pending_requests(host->sender);
  245. // reset the state of all charts
  246. rrdpush_sender_thread_reset_all_charts(host);
  247. rrdpush_sender_replicating_charts_zero(host->sender);
  248. }
  249. static void rrdpush_sender_on_connect(RRDHOST *host) {
  250. rrdpush_sender_cbuffer_flush(host);
  251. rrdpush_sender_charts_and_replication_reset(host);
  252. }
  253. static void rrdpush_sender_after_connect(RRDHOST *host) {
  254. rrdpush_sender_thread_send_custom_host_variables(host);
  255. }
  256. static inline void rrdpush_sender_thread_close_socket(RRDHOST *host) {
  257. if(host->sender->rrdpush_sender_socket != -1) {
  258. close(host->sender->rrdpush_sender_socket);
  259. host->sender->rrdpush_sender_socket = -1;
  260. }
  261. rrdhost_flag_clear(host, RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  262. rrdhost_flag_clear(host, RRDHOST_FLAG_RRDPUSH_SENDER_CONNECTED);
  263. // do not flush the circular buffer here
  264. // this function is called sometimes with the mutex lock, sometimes without the lock
  265. rrdpush_sender_charts_and_replication_reset(host);
  266. }
  267. void rrdpush_encode_variable(stream_encoded_t *se, RRDHOST *host)
  268. {
  269. se->os_name = (host->system_info->host_os_name)?url_encode(host->system_info->host_os_name):"";
  270. se->os_id = (host->system_info->host_os_id)?url_encode(host->system_info->host_os_id):"";
  271. se->os_version = (host->system_info->host_os_version)?url_encode(host->system_info->host_os_version):"";
  272. se->kernel_name = (host->system_info->kernel_name)?url_encode(host->system_info->kernel_name):"";
  273. se->kernel_version = (host->system_info->kernel_version)?url_encode(host->system_info->kernel_version):"";
  274. }
  275. void rrdpush_clean_encoded(stream_encoded_t *se)
  276. {
  277. if (se->os_name)
  278. freez(se->os_name);
  279. if (se->os_id)
  280. freez(se->os_id);
  281. if (se->os_version)
  282. freez(se->os_version);
  283. if (se->kernel_name)
  284. freez(se->kernel_name);
  285. if (se->kernel_version)
  286. freez(se->kernel_version);
  287. }
  288. struct {
  289. const char *response;
  290. size_t length;
  291. int32_t version;
  292. bool dynamic;
  293. const char *error;
  294. int worker_job_id;
  295. time_t postpone_reconnect_seconds;
  296. } stream_responses[] = {
  297. {
  298. .response = START_STREAMING_PROMPT_VN,
  299. .length = sizeof(START_STREAMING_PROMPT_VN) - 1,
  300. .version = STREAM_HANDSHAKE_OK_V3, // and above
  301. .dynamic = true, // dynamic = we will parse the version / capabilities
  302. .error = NULL,
  303. .worker_job_id = 0,
  304. .postpone_reconnect_seconds = 0,
  305. },
  306. {
  307. .response = START_STREAMING_PROMPT_V2,
  308. .length = sizeof(START_STREAMING_PROMPT_V2) - 1,
  309. .version = STREAM_HANDSHAKE_OK_V2,
  310. .dynamic = false,
  311. .error = NULL,
  312. .worker_job_id = 0,
  313. .postpone_reconnect_seconds = 0,
  314. },
  315. {
  316. .response = START_STREAMING_PROMPT_V1,
  317. .length = sizeof(START_STREAMING_PROMPT_V1) - 1,
  318. .version = STREAM_HANDSHAKE_OK_V1,
  319. .dynamic = false,
  320. .error = NULL,
  321. .worker_job_id = 0,
  322. .postpone_reconnect_seconds = 0,
  323. },
  324. {
  325. .response = START_STREAMING_ERROR_SAME_LOCALHOST,
  326. .length = sizeof(START_STREAMING_ERROR_SAME_LOCALHOST) - 1,
  327. .version = STREAM_HANDSHAKE_ERROR_LOCALHOST,
  328. .dynamic = false,
  329. .error = "remote server rejected this stream, the host we are trying to stream is its localhost",
  330. .worker_job_id = WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE,
  331. .postpone_reconnect_seconds = 60 * 60, // the IP may change, try it every hour
  332. },
  333. {
  334. .response = START_STREAMING_ERROR_ALREADY_STREAMING,
  335. .length = sizeof(START_STREAMING_ERROR_ALREADY_STREAMING) - 1,
  336. .version = STREAM_HANDSHAKE_ERROR_ALREADY_CONNECTED,
  337. .dynamic = false,
  338. .error = "remote server rejected this stream, the host we are trying to stream is already streamed to it",
  339. .worker_job_id = WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE,
  340. .postpone_reconnect_seconds = 2 * 60, // 2 minutes
  341. },
  342. {
  343. .response = START_STREAMING_ERROR_NOT_PERMITTED,
  344. .length = sizeof(START_STREAMING_ERROR_NOT_PERMITTED) - 1,
  345. .version = STREAM_HANDSHAKE_ERROR_DENIED,
  346. .dynamic = false,
  347. .error = "remote server denied access, probably we don't have the right API key?",
  348. .worker_job_id = WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE,
  349. .postpone_reconnect_seconds = 1 * 60, // 1 minute
  350. },
  351. // terminator
  352. {
  353. .response = NULL,
  354. .length = 0,
  355. .version = STREAM_HANDSHAKE_ERROR_BAD_HANDSHAKE,
  356. .dynamic = false,
  357. .error = "remote node response is not understood, is it Netdata?",
  358. .worker_job_id = WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE,
  359. .postpone_reconnect_seconds = 1 * 60, // 1 minute
  360. }
  361. };
  362. static inline bool rrdpush_sender_validate_response(RRDHOST *host, struct sender_state *s, char *http, size_t http_length) {
  363. int32_t version = STREAM_HANDSHAKE_ERROR_BAD_HANDSHAKE;
  364. int i;
  365. for(i = 0; stream_responses[i].response ; i++) {
  366. if(stream_responses[i].dynamic &&
  367. http_length > stream_responses[i].length && http_length < (stream_responses[i].length + 30) &&
  368. strncmp(http, stream_responses[i].response, stream_responses[i].length) == 0) {
  369. version = str2i(&http[stream_responses[i].length]);
  370. break;
  371. }
  372. else if(http_length == stream_responses[i].length && strcmp(http, stream_responses[i].response) == 0) {
  373. version = stream_responses[i].version;
  374. break;
  375. }
  376. }
  377. const char *error = stream_responses[i].error;
  378. int worker_job_id = stream_responses[i].worker_job_id;
  379. time_t delay = stream_responses[i].postpone_reconnect_seconds;
  380. if(version >= STREAM_HANDSHAKE_OK_V1) {
  381. host->destination->last_error = NULL;
  382. host->destination->last_handshake = version;
  383. host->destination->postpone_reconnection_until = 0;
  384. s->capabilities = convert_stream_version_to_capabilities(version);
  385. return true;
  386. }
  387. worker_is_busy(worker_job_id);
  388. rrdpush_sender_thread_close_socket(host);
  389. host->destination->last_error = error;
  390. host->destination->last_handshake = version;
  391. host->destination->postpone_reconnection_until = now_realtime_sec() + delay;
  392. char buf[LOG_DATE_LENGTH];
  393. log_date(buf, LOG_DATE_LENGTH, host->destination->postpone_reconnection_until);
  394. error("STREAM %s [send to %s]: %s - will retry in %ld secs, at %s",
  395. rrdhost_hostname(host), s->connected_to, error, delay, buf);
  396. return false;
  397. }
  398. static bool rrdpush_sender_thread_connect_to_parent(RRDHOST *host, int default_port, int timeout, struct sender_state *s) {
  399. struct timeval tv = {
  400. .tv_sec = timeout,
  401. .tv_usec = 0
  402. };
  403. // make sure the socket is closed
  404. rrdpush_sender_thread_close_socket(host);
  405. s->rrdpush_sender_socket = connect_to_one_of_destinations(
  406. host
  407. , default_port
  408. , &tv
  409. , &s->reconnects_counter
  410. , s->connected_to
  411. , sizeof(s->connected_to)-1
  412. , &host->destination
  413. );
  414. if(unlikely(s->rrdpush_sender_socket == -1)) {
  415. // error("STREAM %s [send to %s]: could not connect to parent node at this time.", rrdhost_hostname(host), host->rrdpush_send_destination);
  416. return false;
  417. }
  418. // info("STREAM %s [send to %s]: initializing communication...", rrdhost_hostname(host), s->connected_to);
  419. #ifdef ENABLE_HTTPS
  420. if(netdata_ssl_client_ctx){
  421. host->sender->ssl.flags = NETDATA_SSL_START;
  422. if (!host->sender->ssl.conn){
  423. host->sender->ssl.conn = SSL_new(netdata_ssl_client_ctx);
  424. if(!host->sender->ssl.conn){
  425. error("Failed to allocate SSL structure.");
  426. host->sender->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  427. }
  428. }
  429. else{
  430. SSL_clear(host->sender->ssl.conn);
  431. }
  432. if (host->sender->ssl.conn)
  433. {
  434. if (SSL_set_fd(host->sender->ssl.conn, s->rrdpush_sender_socket) != 1) {
  435. error("Failed to set the socket to the SSL on socket fd %d.", s->rrdpush_sender_socket);
  436. host->sender->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  437. } else{
  438. host->sender->ssl.flags = NETDATA_SSL_HANDSHAKE_COMPLETE;
  439. }
  440. }
  441. }
  442. else {
  443. host->sender->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  444. }
  445. #endif
  446. // reset our capabilities to default
  447. s->capabilities = stream_our_capabilities();
  448. #ifdef ENABLE_COMPRESSION
  449. // If we don't want compression, remove it from our capabilities
  450. if(!(s->flags & SENDER_FLAG_COMPRESSION))
  451. s->capabilities &= ~STREAM_CAP_COMPRESSION;
  452. #endif // ENABLE_COMPRESSION
  453. /* TODO: During the implementation of #7265 switch the set of variables to HOST_* and CONTAINER_* if the
  454. version negotiation resulted in a high enough version.
  455. */
  456. stream_encoded_t se;
  457. rrdpush_encode_variable(&se, host);
  458. host->sender->hops = host->system_info->hops + 1;
  459. char http[HTTP_HEADER_SIZE + 1];
  460. int eol = snprintfz(http, HTTP_HEADER_SIZE,
  461. "STREAM "
  462. "key=%s"
  463. "&hostname=%s"
  464. "&registry_hostname=%s"
  465. "&machine_guid=%s"
  466. "&update_every=%d"
  467. "&os=%s"
  468. "&timezone=%s"
  469. "&abbrev_timezone=%s"
  470. "&utc_offset=%d"
  471. "&hops=%d"
  472. "&ml_capable=%d"
  473. "&ml_enabled=%d"
  474. "&mc_version=%d"
  475. "&tags=%s"
  476. "&ver=%u"
  477. "&NETDATA_INSTANCE_CLOUD_TYPE=%s"
  478. "&NETDATA_INSTANCE_CLOUD_INSTANCE_TYPE=%s"
  479. "&NETDATA_INSTANCE_CLOUD_INSTANCE_REGION=%s"
  480. "&NETDATA_SYSTEM_OS_NAME=%s"
  481. "&NETDATA_SYSTEM_OS_ID=%s"
  482. "&NETDATA_SYSTEM_OS_ID_LIKE=%s"
  483. "&NETDATA_SYSTEM_OS_VERSION=%s"
  484. "&NETDATA_SYSTEM_OS_VERSION_ID=%s"
  485. "&NETDATA_SYSTEM_OS_DETECTION=%s"
  486. "&NETDATA_HOST_IS_K8S_NODE=%s"
  487. "&NETDATA_SYSTEM_KERNEL_NAME=%s"
  488. "&NETDATA_SYSTEM_KERNEL_VERSION=%s"
  489. "&NETDATA_SYSTEM_ARCHITECTURE=%s"
  490. "&NETDATA_SYSTEM_VIRTUALIZATION=%s"
  491. "&NETDATA_SYSTEM_VIRT_DETECTION=%s"
  492. "&NETDATA_SYSTEM_CONTAINER=%s"
  493. "&NETDATA_SYSTEM_CONTAINER_DETECTION=%s"
  494. "&NETDATA_CONTAINER_OS_NAME=%s"
  495. "&NETDATA_CONTAINER_OS_ID=%s"
  496. "&NETDATA_CONTAINER_OS_ID_LIKE=%s"
  497. "&NETDATA_CONTAINER_OS_VERSION=%s"
  498. "&NETDATA_CONTAINER_OS_VERSION_ID=%s"
  499. "&NETDATA_CONTAINER_OS_DETECTION=%s"
  500. "&NETDATA_SYSTEM_CPU_LOGICAL_CPU_COUNT=%s"
  501. "&NETDATA_SYSTEM_CPU_FREQ=%s"
  502. "&NETDATA_SYSTEM_TOTAL_RAM=%s"
  503. "&NETDATA_SYSTEM_TOTAL_DISK_SIZE=%s"
  504. "&NETDATA_PROTOCOL_VERSION=%s"
  505. " HTTP/1.1\r\n"
  506. "User-Agent: %s/%s\r\n"
  507. "Accept: */*\r\n\r\n"
  508. , host->rrdpush_send_api_key
  509. , rrdhost_hostname(host)
  510. , rrdhost_registry_hostname(host)
  511. , host->machine_guid
  512. , default_rrd_update_every
  513. , rrdhost_os(host)
  514. , rrdhost_timezone(host)
  515. , rrdhost_abbrev_timezone(host)
  516. , host->utc_offset
  517. , host->sender->hops
  518. , host->system_info->ml_capable
  519. , host->system_info->ml_enabled
  520. , host->system_info->mc_version
  521. , rrdhost_tags(host)
  522. , s->capabilities
  523. , (host->system_info->cloud_provider_type) ? host->system_info->cloud_provider_type : ""
  524. , (host->system_info->cloud_instance_type) ? host->system_info->cloud_instance_type : ""
  525. , (host->system_info->cloud_instance_region) ? host->system_info->cloud_instance_region : ""
  526. , se.os_name
  527. , se.os_id
  528. , (host->system_info->host_os_id_like) ? host->system_info->host_os_id_like : ""
  529. , se.os_version
  530. , (host->system_info->host_os_version_id) ? host->system_info->host_os_version_id : ""
  531. , (host->system_info->host_os_detection) ? host->system_info->host_os_detection : ""
  532. , (host->system_info->is_k8s_node) ? host->system_info->is_k8s_node : ""
  533. , se.kernel_name
  534. , se.kernel_version
  535. , (host->system_info->architecture) ? host->system_info->architecture : ""
  536. , (host->system_info->virtualization) ? host->system_info->virtualization : ""
  537. , (host->system_info->virt_detection) ? host->system_info->virt_detection : ""
  538. , (host->system_info->container) ? host->system_info->container : ""
  539. , (host->system_info->container_detection) ? host->system_info->container_detection : ""
  540. , (host->system_info->container_os_name) ? host->system_info->container_os_name : ""
  541. , (host->system_info->container_os_id) ? host->system_info->container_os_id : ""
  542. , (host->system_info->container_os_id_like) ? host->system_info->container_os_id_like : ""
  543. , (host->system_info->container_os_version) ? host->system_info->container_os_version : ""
  544. , (host->system_info->container_os_version_id) ? host->system_info->container_os_version_id : ""
  545. , (host->system_info->container_os_detection) ? host->system_info->container_os_detection : ""
  546. , (host->system_info->host_cores) ? host->system_info->host_cores : ""
  547. , (host->system_info->host_cpu_freq) ? host->system_info->host_cpu_freq : ""
  548. , (host->system_info->host_ram_total) ? host->system_info->host_ram_total : ""
  549. , (host->system_info->host_disk_space) ? host->system_info->host_disk_space : ""
  550. , STREAMING_PROTOCOL_VERSION
  551. , rrdhost_program_name(host)
  552. , rrdhost_program_version(host)
  553. );
  554. http[eol] = 0x00;
  555. rrdpush_clean_encoded(&se);
  556. #ifdef ENABLE_HTTPS
  557. if (!host->sender->ssl.flags) {
  558. ERR_clear_error();
  559. SSL_set_connect_state(host->sender->ssl.conn);
  560. int err = SSL_connect(host->sender->ssl.conn);
  561. if (err != 1){
  562. err = SSL_get_error(host->sender->ssl.conn, err);
  563. error("SSL cannot connect with the server: %s ",ERR_error_string((long)SSL_get_error(host->sender->ssl.conn,err),NULL));
  564. if (netdata_use_ssl_on_stream == NETDATA_SSL_FORCE) {
  565. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_SSL_ERROR);
  566. rrdpush_sender_thread_close_socket(host);
  567. host->destination->last_error = "SSL error";
  568. host->destination->last_handshake = STREAM_HANDSHAKE_ERROR_SSL_ERROR;
  569. host->destination->postpone_reconnection_until = now_realtime_sec() + 5 * 60;
  570. return false;
  571. }
  572. else {
  573. host->sender->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  574. }
  575. }
  576. else {
  577. if (netdata_use_ssl_on_stream == NETDATA_SSL_FORCE) {
  578. if (netdata_ssl_validate_server == NETDATA_SSL_VALID_CERTIFICATE) {
  579. if ( security_test_certificate(host->sender->ssl.conn)) {
  580. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_SSL_ERROR);
  581. error("Closing the stream connection, because the server SSL certificate is not valid.");
  582. rrdpush_sender_thread_close_socket(host);
  583. host->destination->last_error = "invalid SSL certificate";
  584. host->destination->last_handshake = STREAM_HANDSHAKE_ERROR_INVALID_CERTIFICATE;
  585. host->destination->postpone_reconnection_until = now_realtime_sec() + 5 * 60;
  586. return false;
  587. }
  588. }
  589. }
  590. }
  591. }
  592. #endif
  593. ssize_t bytes;
  594. bytes = send_timeout(
  595. #ifdef ENABLE_HTTPS
  596. &host->sender->ssl,
  597. #endif
  598. s->rrdpush_sender_socket,
  599. http,
  600. strlen(http),
  601. 0,
  602. timeout);
  603. if(bytes <= 0) { // timeout is 0
  604. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_TIMEOUT);
  605. rrdpush_sender_thread_close_socket(host);
  606. error("STREAM %s [send to %s]: failed to send HTTP header to remote netdata.", rrdhost_hostname(host), s->connected_to);
  607. host->destination->last_error = "timeout while sending request";
  608. host->destination->last_handshake = STREAM_HANDSHAKE_ERROR_SEND_TIMEOUT;
  609. host->destination->postpone_reconnection_until = now_realtime_sec() + 1 * 60;
  610. return false;
  611. }
  612. // info("STREAM %s [send to %s]: waiting response from remote netdata...", rrdhost_hostname(host), s->connected_to);
  613. bytes = recv_timeout(
  614. #ifdef ENABLE_HTTPS
  615. &host->sender->ssl,
  616. #endif
  617. s->rrdpush_sender_socket,
  618. http,
  619. HTTP_HEADER_SIZE,
  620. 0,
  621. timeout);
  622. if(bytes <= 0) { // timeout is 0
  623. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_TIMEOUT);
  624. rrdpush_sender_thread_close_socket(host);
  625. error("STREAM %s [send to %s]: remote netdata does not respond.", rrdhost_hostname(host), s->connected_to);
  626. host->destination->last_error = "timeout while expecting first response";
  627. host->destination->last_handshake = STREAM_HANDSHAKE_ERROR_RECEIVE_TIMEOUT;
  628. host->destination->postpone_reconnection_until = now_realtime_sec() + 30;
  629. return false;
  630. }
  631. http[bytes] = '\0';
  632. debug(D_STREAM, "Response to sender from far end: %s", http);
  633. if(!rrdpush_sender_validate_response(host, s, http, bytes))
  634. return false;
  635. #ifdef ENABLE_COMPRESSION
  636. if(stream_has_capability(s, STREAM_CAP_COMPRESSION)) {
  637. if(!s->compressor)
  638. s->compressor = create_compressor();
  639. else
  640. s->compressor->reset(s->compressor);
  641. }
  642. #endif //ENABLE_COMPRESSION
  643. log_sender_capabilities(s);
  644. if(sock_setnonblock(s->rrdpush_sender_socket) < 0)
  645. error("STREAM %s [send to %s]: cannot set non-blocking mode for socket.", rrdhost_hostname(host), s->connected_to);
  646. if(sock_enlarge_out(s->rrdpush_sender_socket) < 0)
  647. error("STREAM %s [send to %s]: cannot enlarge the socket buffer.", rrdhost_hostname(host), s->connected_to);
  648. debug(D_STREAM, "STREAM: Connected on fd %d...", s->rrdpush_sender_socket);
  649. return true;
  650. }
  651. static bool attempt_to_connect(struct sender_state *state)
  652. {
  653. state->send_attempts = 0;
  654. if(rrdpush_sender_thread_connect_to_parent(state->host, state->default_port, state->timeout, state)) {
  655. // reset the buffer, to properly send charts and metrics
  656. rrdpush_sender_on_connect(state->host);
  657. // send from the beginning
  658. state->begin = 0;
  659. // make sure the next reconnection will be immediate
  660. state->not_connected_loops = 0;
  661. // reset the bytes we have sent for this session
  662. state->sent_bytes_on_this_connection = 0;
  663. // let the data collection threads know we are ready
  664. rrdhost_flag_set(state->host, RRDHOST_FLAG_RRDPUSH_SENDER_CONNECTED);
  665. rrdpush_sender_after_connect(state->host);
  666. return true;
  667. }
  668. // we couldn't connect
  669. // increase the failed connections counter
  670. state->not_connected_loops++;
  671. // reset the number of bytes sent
  672. state->sent_bytes_on_this_connection = 0;
  673. // slow re-connection on repeating errors
  674. usec_t now_ut = now_monotonic_usec();
  675. usec_t end_ut = now_ut + USEC_PER_SEC * state->reconnect_delay;
  676. while(now_ut < end_ut) {
  677. netdata_thread_testcancel();
  678. sleep_usec(500 * USEC_PER_MS); // seconds
  679. now_ut = now_monotonic_usec();
  680. }
  681. return false;
  682. }
  683. // TCP window is open and we have data to transmit.
  684. static ssize_t attempt_to_send(struct sender_state *s) {
  685. ssize_t ret = 0;
  686. #ifdef NETDATA_INTERNAL_CHECKS
  687. struct circular_buffer *cb = s->buffer;
  688. #endif
  689. netdata_mutex_lock(&s->mutex);
  690. char *chunk;
  691. size_t outstanding = cbuffer_next_unsafe(s->buffer, &chunk);
  692. debug(D_STREAM, "STREAM: Sending data. Buffer r=%zu w=%zu s=%zu, next chunk=%zu", cb->read, cb->write, cb->size, outstanding);
  693. #ifdef ENABLE_HTTPS
  694. SSL *conn = s->ssl.conn ;
  695. if(conn && s->ssl.flags == NETDATA_SSL_HANDSHAKE_COMPLETE)
  696. ret = netdata_ssl_write(conn, chunk, outstanding);
  697. else
  698. ret = send(s->rrdpush_sender_socket, chunk, outstanding, MSG_DONTWAIT);
  699. #else
  700. ret = send(s->rrdpush_sender_socket, chunk, outstanding, MSG_DONTWAIT);
  701. #endif
  702. if (likely(ret > 0)) {
  703. cbuffer_remove_unsafe(s->buffer, ret);
  704. s->sent_bytes_on_this_connection += ret;
  705. s->sent_bytes += ret;
  706. debug(D_STREAM, "STREAM %s [send to %s]: Sent %zd bytes", rrdhost_hostname(s->host), s->connected_to, ret);
  707. }
  708. else if (ret == -1 && (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
  709. debug(D_STREAM, "STREAM %s [send to %s]: unavailable after polling POLLOUT", rrdhost_hostname(s->host), s->connected_to);
  710. else if (ret == -1) {
  711. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_SEND_ERROR);
  712. debug(D_STREAM, "STREAM: Send failed - closing socket...");
  713. error("STREAM %s [send to %s]: failed to send metrics - closing connection - we have sent %zu bytes on this connection.", rrdhost_hostname(s->host), s->connected_to, s->sent_bytes_on_this_connection);
  714. rrdpush_sender_thread_close_socket(s->host);
  715. }
  716. else
  717. debug(D_STREAM, "STREAM: send() returned 0 -> no error but no transmission");
  718. replication_recalculate_buffer_used_ratio_unsafe(s);
  719. netdata_mutex_unlock(&s->mutex);
  720. return ret;
  721. }
  722. static ssize_t attempt_read(struct sender_state *s) {
  723. ssize_t ret = 0;
  724. #ifdef ENABLE_HTTPS
  725. if (s->ssl.conn && s->ssl.flags == NETDATA_SSL_HANDSHAKE_COMPLETE) {
  726. size_t desired = sizeof(s->read_buffer) - s->read_len - 1;
  727. ret = netdata_ssl_read(s->ssl.conn, s->read_buffer, desired);
  728. if (ret > 0 ) {
  729. s->read_len += (int)ret;
  730. return ret;
  731. }
  732. if (ret == -1) {
  733. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_SSL_ERROR);
  734. rrdpush_sender_thread_close_socket(s->host);
  735. }
  736. return ret;
  737. }
  738. #endif
  739. ret = recv(s->rrdpush_sender_socket, s->read_buffer + s->read_len, sizeof(s->read_buffer) - s->read_len - 1,MSG_DONTWAIT);
  740. if (ret > 0) {
  741. s->read_len += ret;
  742. return ret;
  743. }
  744. if (ret < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
  745. return ret;
  746. if (ret == 0 || errno == ECONNRESET) {
  747. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_PARENT_CLOSED);
  748. error("STREAM %s [send to %s]: connection closed by far end.", rrdhost_hostname(s->host), s->connected_to);
  749. }
  750. else {
  751. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_RECEIVE_ERROR);
  752. error("STREAM %s [send to %s]: error during receive (%zd) - closing connection.", rrdhost_hostname(s->host), s->connected_to, ret);
  753. }
  754. rrdpush_sender_thread_close_socket(s->host);
  755. return ret;
  756. }
  757. struct inflight_stream_function {
  758. struct sender_state *sender;
  759. STRING *transaction;
  760. usec_t received_ut;
  761. };
  762. void stream_execute_function_callback(BUFFER *func_wb, int code, void *data) {
  763. struct inflight_stream_function *tmp = data;
  764. struct sender_state *s = tmp->sender;
  765. if(rrdhost_can_send_definitions_to_parent(s->host)) {
  766. BUFFER *wb = sender_start(s);
  767. pluginsd_function_result_begin_to_buffer(wb
  768. , string2str(tmp->transaction)
  769. , code
  770. , functions_content_type_to_format(func_wb->content_type)
  771. , func_wb->expires);
  772. buffer_fast_strcat(wb, buffer_tostring(func_wb), buffer_strlen(func_wb));
  773. pluginsd_function_result_end_to_buffer(wb);
  774. sender_commit(s, wb);
  775. sender_thread_buffer_free();
  776. internal_error(true, "STREAM %s [send to %s] FUNCTION transaction %s sending back response (%zu bytes, %llu usec).",
  777. rrdhost_hostname(s->host), s->connected_to,
  778. string2str(tmp->transaction),
  779. buffer_strlen(func_wb),
  780. now_realtime_usec() - tmp->received_ut);
  781. }
  782. string_freez(tmp->transaction);
  783. buffer_free(func_wb);
  784. freez(tmp);
  785. }
  786. // This is just a placeholder until the gap filling state machine is inserted
  787. void execute_commands(struct sender_state *s) {
  788. worker_is_busy(WORKER_SENDER_JOB_EXECUTE);
  789. char *start = s->read_buffer, *end = &s->read_buffer[s->read_len], *newline;
  790. *end = 0;
  791. while( start < end && (newline = strchr(start, '\n')) ) {
  792. *newline = '\0';
  793. log_access("STREAM: %d from '%s' for host '%s': %s",
  794. gettid(), s->connected_to, rrdhost_hostname(s->host), start);
  795. // internal_error(true, "STREAM %s [send to %s] received command over connection: %s", rrdhost_hostname(s->host), s->connected_to, start);
  796. char *words[PLUGINSD_MAX_WORDS] = { NULL };
  797. size_t num_words = pluginsd_split_words(start, words, PLUGINSD_MAX_WORDS);
  798. const char *keyword = get_word(words, num_words, 0);
  799. if(keyword && strcmp(keyword, PLUGINSD_KEYWORD_FUNCTION) == 0) {
  800. worker_is_busy(WORKER_SENDER_JOB_FUNCTION_REQUEST);
  801. char *transaction = get_word(words, num_words, 1);
  802. char *timeout_s = get_word(words, num_words, 2);
  803. char *function = get_word(words, num_words, 3);
  804. if(!transaction || !*transaction || !timeout_s || !*timeout_s || !function || !*function) {
  805. error("STREAM %s [send to %s] %s execution command is incomplete (transaction = '%s', timeout = '%s', function = '%s'). Ignoring it.",
  806. rrdhost_hostname(s->host), s->connected_to,
  807. keyword,
  808. transaction?transaction:"(unset)",
  809. timeout_s?timeout_s:"(unset)",
  810. function?function:"(unset)");
  811. }
  812. else {
  813. int timeout = str2i(timeout_s);
  814. if(timeout <= 0) timeout = PLUGINS_FUNCTIONS_TIMEOUT_DEFAULT;
  815. struct inflight_stream_function *tmp = callocz(1, sizeof(struct inflight_stream_function));
  816. tmp->received_ut = now_realtime_usec();
  817. tmp->sender = s;
  818. tmp->transaction = string_strdupz(transaction);
  819. BUFFER *wb = buffer_create(PLUGINSD_LINE_MAX + 1, &netdata_buffers_statistics.buffers_functions);
  820. int code = rrd_call_function_async(s->host, wb, timeout, function, stream_execute_function_callback, tmp);
  821. if(code != HTTP_RESP_OK) {
  822. rrd_call_function_error(wb, "Failed to route request to collector", code);
  823. stream_execute_function_callback(wb, code, tmp);
  824. }
  825. }
  826. }
  827. else if (keyword && strcmp(keyword, PLUGINSD_KEYWORD_REPLAY_CHART) == 0) {
  828. worker_is_busy(WORKER_SENDER_JOB_REPLAY_REQUEST);
  829. const char *chart_id = get_word(words, num_words, 1);
  830. const char *start_streaming = get_word(words, num_words, 2);
  831. const char *after = get_word(words, num_words, 3);
  832. const char *before = get_word(words, num_words, 4);
  833. if (!chart_id || !start_streaming || !after || !before) {
  834. error("STREAM %s [send to %s] %s command is incomplete"
  835. " (chart=%s, start_streaming=%s, after=%s, before=%s)",
  836. rrdhost_hostname(s->host), s->connected_to,
  837. keyword,
  838. chart_id ? chart_id : "(unset)",
  839. start_streaming ? start_streaming : "(unset)",
  840. after ? after : "(unset)",
  841. before ? before : "(unset)");
  842. }
  843. else {
  844. replication_add_request(s, chart_id,
  845. strtoll(after, NULL, 0),
  846. strtoll(before, NULL, 0),
  847. !strcmp(start_streaming, "true")
  848. );
  849. }
  850. }
  851. else {
  852. error("STREAM %s [send to %s] received unknown command over connection: %s", rrdhost_hostname(s->host), s->connected_to, words[0]?words[0]:"(unset)");
  853. }
  854. worker_is_busy(WORKER_SENDER_JOB_EXECUTE);
  855. start = newline + 1;
  856. }
  857. if (start < end) {
  858. memmove(s->read_buffer, start, end-start);
  859. s->read_len = end - start;
  860. }
  861. else {
  862. s->read_buffer[0] = '\0';
  863. s->read_len = 0;
  864. }
  865. }
  866. struct rrdpush_sender_thread_data {
  867. RRDHOST *host;
  868. char *pipe_buffer;
  869. };
  870. static bool rrdpush_sender_pipe_close(RRDHOST *host, int *pipe_fds, bool reopen) {
  871. static netdata_mutex_t mutex = NETDATA_MUTEX_INITIALIZER;
  872. bool ret = true;
  873. netdata_mutex_lock(&mutex);
  874. int new_pipe_fds[2];
  875. if(reopen) {
  876. if(pipe(new_pipe_fds) != 0) {
  877. error("STREAM %s [send]: cannot create required pipe.", rrdhost_hostname(host));
  878. new_pipe_fds[PIPE_READ] = -1;
  879. new_pipe_fds[PIPE_WRITE] = -1;
  880. ret = false;
  881. }
  882. }
  883. int old_pipe_fds[2];
  884. old_pipe_fds[PIPE_READ] = pipe_fds[PIPE_READ];
  885. old_pipe_fds[PIPE_WRITE] = pipe_fds[PIPE_WRITE];
  886. if(reopen) {
  887. pipe_fds[PIPE_READ] = new_pipe_fds[PIPE_READ];
  888. pipe_fds[PIPE_WRITE] = new_pipe_fds[PIPE_WRITE];
  889. }
  890. else {
  891. pipe_fds[PIPE_READ] = -1;
  892. pipe_fds[PIPE_WRITE] = -1;
  893. }
  894. if(old_pipe_fds[PIPE_READ] > 2)
  895. close(old_pipe_fds[PIPE_READ]);
  896. if(old_pipe_fds[PIPE_WRITE] > 2)
  897. close(old_pipe_fds[PIPE_WRITE]);
  898. netdata_mutex_unlock(&mutex);
  899. return ret;
  900. }
  901. void rrdpush_signal_sender_to_wake_up(struct sender_state *s) {
  902. if(unlikely(s->tid == gettid()))
  903. return;
  904. RRDHOST *host = s->host;
  905. int pipe_fd = s->rrdpush_sender_pipe[PIPE_WRITE];
  906. // signal the sender there are more data
  907. if (pipe_fd != -1 && write(pipe_fd, " ", 1) == -1) {
  908. error("STREAM %s [send]: cannot write to internal pipe.", rrdhost_hostname(host));
  909. rrdpush_sender_pipe_close(host, s->rrdpush_sender_pipe, true);
  910. }
  911. }
  912. static bool rrdhost_set_sender(RRDHOST *host) {
  913. if(unlikely(!host->sender)) return false;
  914. bool ret = false;
  915. netdata_mutex_lock(&host->sender->mutex);
  916. if(!host->sender->tid) {
  917. rrdhost_flag_clear(host, RRDHOST_FLAG_RRDPUSH_SENDER_CONNECTED | RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  918. rrdhost_flag_set(host, RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN);
  919. host->sender->tid = gettid();
  920. ret = true;
  921. }
  922. netdata_mutex_unlock(&host->sender->mutex);
  923. return ret;
  924. }
  925. static void rrdhost_clear_sender___while_having_sender_mutex(RRDHOST *host) {
  926. if(unlikely(!host->sender)) return;
  927. if(host->sender->tid == gettid()) {
  928. host->sender->tid = 0;
  929. host->sender->exit.shutdown = false;
  930. host->sender->exit.reason = NULL;
  931. rrdhost_flag_clear(host, RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN | RRDHOST_FLAG_RRDPUSH_SENDER_CONNECTED | RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  932. }
  933. }
  934. static bool rrdhost_sender_should_exit(struct sender_state *s) {
  935. // check for outstanding cancellation requests
  936. netdata_thread_testcancel();
  937. if(unlikely(!service_running(SERVICE_STREAMING))) {
  938. if(!s->exit.reason)
  939. s->exit.reason = "NETDATA EXIT";
  940. return true;
  941. }
  942. if(unlikely(!rrdhost_has_rrdpush_sender_enabled(s->host))) {
  943. if(!s->exit.reason)
  944. s->exit.reason = "NON STREAMABLE HOST";
  945. return true;
  946. }
  947. if(unlikely(s->exit.shutdown)) {
  948. if(!s->exit.reason)
  949. s->exit.reason = "SENDER SHUTDOWN REQUESTED";
  950. return true;
  951. }
  952. if(unlikely(rrdhost_flag_check(s->host, RRDHOST_FLAG_ORPHAN))) {
  953. if(!s->exit.reason)
  954. s->exit.reason = "RECEIVER LEFT";
  955. return true;
  956. }
  957. return false;
  958. }
  959. static void rrdpush_sender_thread_cleanup_callback(void *ptr) {
  960. struct rrdpush_sender_thread_data *s = ptr;
  961. worker_unregister();
  962. RRDHOST *host = s->host;
  963. netdata_mutex_lock(&host->sender->mutex);
  964. info("STREAM %s [send]: sending thread exits %s",
  965. rrdhost_hostname(host),
  966. host->sender->exit.reason ? host->sender->exit.reason : "");
  967. rrdpush_sender_thread_close_socket(host);
  968. rrdpush_sender_pipe_close(host, host->sender->rrdpush_sender_pipe, false);
  969. rrdhost_clear_sender___while_having_sender_mutex(host);
  970. netdata_mutex_unlock(&host->sender->mutex);
  971. freez(s->pipe_buffer);
  972. freez(s);
  973. }
  974. void *rrdpush_sender_thread(void *ptr) {
  975. worker_register("STREAMSND");
  976. worker_register_job_name(WORKER_SENDER_JOB_CONNECT, "connect");
  977. worker_register_job_name(WORKER_SENDER_JOB_PIPE_READ, "pipe read");
  978. worker_register_job_name(WORKER_SENDER_JOB_SOCKET_RECEIVE, "receive");
  979. worker_register_job_name(WORKER_SENDER_JOB_EXECUTE, "execute");
  980. worker_register_job_name(WORKER_SENDER_JOB_SOCKET_SEND, "send");
  981. // disconnection reasons
  982. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_TIMEOUT, "disconnect timeout");
  983. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_POLL_ERROR, "disconnect poll error");
  984. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_SOCKER_ERROR, "disconnect socket error");
  985. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_OVERFLOW, "disconnect overflow");
  986. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_SSL_ERROR, "disconnect ssl error");
  987. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_PARENT_CLOSED, "disconnect parent closed");
  988. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_RECEIVE_ERROR, "disconnect receive error");
  989. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_SEND_ERROR, "disconnect send error");
  990. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_NO_COMPRESSION, "disconnect no compression");
  991. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE, "disconnect bad handshake");
  992. worker_register_job_name(WORKER_SENDER_JOB_REPLAY_REQUEST, "replay request");
  993. worker_register_job_name(WORKER_SENDER_JOB_FUNCTION_REQUEST, "function");
  994. worker_register_job_custom_metric(WORKER_SENDER_JOB_BUFFER_RATIO, "used buffer ratio", "%", WORKER_METRIC_ABSOLUTE);
  995. worker_register_job_custom_metric(WORKER_SENDER_JOB_BYTES_RECEIVED, "bytes received", "bytes/s", WORKER_METRIC_INCREMENT);
  996. worker_register_job_custom_metric(WORKER_SENDER_JOB_BYTES_SENT, "bytes sent", "bytes/s", WORKER_METRIC_INCREMENT);
  997. worker_register_job_custom_metric(WORKER_SENDER_JOB_REPLAY_DICT_SIZE, "replication dict entries", "entries", WORKER_METRIC_ABSOLUTE);
  998. struct sender_state *s = ptr;
  999. if(!rrdhost_has_rrdpush_sender_enabled(s->host) || !s->host->rrdpush_send_destination ||
  1000. !*s->host->rrdpush_send_destination || !s->host->rrdpush_send_api_key ||
  1001. !*s->host->rrdpush_send_api_key) {
  1002. error("STREAM %s [send]: thread created (task id %d), but host has streaming disabled.",
  1003. rrdhost_hostname(s->host), gettid());
  1004. return NULL;
  1005. }
  1006. if(!rrdhost_set_sender(s->host)) {
  1007. error("STREAM %s [send]: thread created (task id %d), but there is another sender running for this host.",
  1008. rrdhost_hostname(s->host), gettid());
  1009. return NULL;
  1010. }
  1011. #ifdef ENABLE_HTTPS
  1012. if (netdata_use_ssl_on_stream & NETDATA_SSL_FORCE ) {
  1013. static SPINLOCK sp = NETDATA_SPINLOCK_INITIALIZER;
  1014. netdata_spinlock_lock(&sp);
  1015. if(!netdata_ssl_client_ctx) {
  1016. security_start_ssl(NETDATA_SSL_CONTEXT_STREAMING);
  1017. ssl_security_location_for_context(netdata_ssl_client_ctx, netdata_ssl_ca_file, netdata_ssl_ca_path);
  1018. }
  1019. netdata_spinlock_unlock(&sp);
  1020. }
  1021. #endif
  1022. info("STREAM %s [send]: thread created (task id %d)", rrdhost_hostname(s->host), gettid());
  1023. s->timeout = (int)appconfig_get_number(
  1024. &stream_config, CONFIG_SECTION_STREAM, "timeout seconds", 600);
  1025. s->default_port = (int)appconfig_get_number(
  1026. &stream_config, CONFIG_SECTION_STREAM, "default port", 19999);
  1027. s->buffer->max_size = (size_t)appconfig_get_number(
  1028. &stream_config, CONFIG_SECTION_STREAM, "buffer size bytes", 1024 * 1024 * 10);
  1029. s->reconnect_delay = (unsigned int)appconfig_get_number(
  1030. &stream_config, CONFIG_SECTION_STREAM, "reconnect delay seconds", 5);
  1031. remote_clock_resync_iterations = (unsigned int)appconfig_get_number(
  1032. &stream_config, CONFIG_SECTION_STREAM,
  1033. "initial clock resync iterations",
  1034. remote_clock_resync_iterations); // TODO: REMOVE FOR SLEW / GAPFILLING
  1035. // initialize rrdpush globals
  1036. rrdhost_flag_clear(s->host, RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  1037. rrdhost_flag_clear(s->host, RRDHOST_FLAG_RRDPUSH_SENDER_CONNECTED);
  1038. int pipe_buffer_size = 10 * 1024;
  1039. #ifdef F_GETPIPE_SZ
  1040. pipe_buffer_size = fcntl(s->rrdpush_sender_pipe[PIPE_READ], F_GETPIPE_SZ);
  1041. #endif
  1042. if(pipe_buffer_size < 10 * 1024)
  1043. pipe_buffer_size = 10 * 1024;
  1044. if(!rrdpush_sender_pipe_close(s->host, s->rrdpush_sender_pipe, true)) {
  1045. error("STREAM %s [send]: cannot create inter-thread communication pipe. Disabling streaming.",
  1046. rrdhost_hostname(s->host));
  1047. return NULL;
  1048. }
  1049. struct rrdpush_sender_thread_data *thread_data = callocz(1, sizeof(struct rrdpush_sender_thread_data));
  1050. thread_data->pipe_buffer = mallocz(pipe_buffer_size);
  1051. thread_data->host = s->host;
  1052. netdata_thread_cleanup_push(rrdpush_sender_thread_cleanup_callback, thread_data);
  1053. size_t iterations = 0;
  1054. time_t now_s = now_monotonic_sec();
  1055. while(!rrdhost_sender_should_exit(s)) {
  1056. iterations++;
  1057. // The connection attempt blocks (after which we use the socket in nonblocking)
  1058. if(unlikely(s->rrdpush_sender_socket == -1)) {
  1059. worker_is_busy(WORKER_SENDER_JOB_CONNECT);
  1060. now_s = now_monotonic_sec();
  1061. rrdpush_sender_cbuffer_recreate_timed(s, now_s, false, true);
  1062. rrdhost_flag_clear(s->host, RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  1063. s->flags &= ~SENDER_FLAG_OVERFLOW;
  1064. s->read_len = 0;
  1065. s->buffer->read = 0;
  1066. s->buffer->write = 0;
  1067. if(!attempt_to_connect(s))
  1068. continue;
  1069. if(rrdhost_sender_should_exit(s))
  1070. break;
  1071. now_s = s->last_traffic_seen_t = now_monotonic_sec();
  1072. rrdpush_claimed_id(s->host);
  1073. rrdpush_send_host_labels(s->host);
  1074. rrdhost_flag_set(s->host, RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  1075. info("STREAM %s [send to %s]: enabling metrics streaming...", rrdhost_hostname(s->host), s->connected_to);
  1076. continue;
  1077. }
  1078. if(iterations % 1000 == 0)
  1079. now_s = now_monotonic_sec();
  1080. // If the TCP window never opened then something is wrong, restart connection
  1081. if(unlikely(now_s - s->last_traffic_seen_t > s->timeout &&
  1082. !rrdpush_sender_pending_replication_requests(s) &&
  1083. !rrdpush_sender_replicating_charts(s)
  1084. )) {
  1085. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_TIMEOUT);
  1086. 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.", rrdhost_hostname(s->host), s->connected_to, s->timeout, s->sent_bytes_on_this_connection, s->send_attempts);
  1087. rrdpush_sender_thread_close_socket(s->host);
  1088. continue;
  1089. }
  1090. netdata_mutex_lock(&s->mutex);
  1091. size_t outstanding = cbuffer_next_unsafe(s->buffer, NULL);
  1092. size_t available = cbuffer_available_size_unsafe(s->buffer);
  1093. if (unlikely(!outstanding)) {
  1094. rrdpush_sender_pipe_clear_pending_data(s);
  1095. rrdpush_sender_cbuffer_recreate_timed(s, now_s, true, false);
  1096. }
  1097. netdata_mutex_unlock(&s->mutex);
  1098. worker_set_metric(WORKER_SENDER_JOB_BUFFER_RATIO, (NETDATA_DOUBLE)(s->buffer->max_size - available) * 100.0 / (NETDATA_DOUBLE)s->buffer->max_size);
  1099. if(outstanding)
  1100. s->send_attempts++;
  1101. if(unlikely(s->rrdpush_sender_pipe[PIPE_READ] == -1)) {
  1102. if(!rrdpush_sender_pipe_close(s->host, s->rrdpush_sender_pipe, true)) {
  1103. error("STREAM %s [send]: cannot create inter-thread communication pipe. Disabling streaming.",
  1104. rrdhost_hostname(s->host));
  1105. rrdpush_sender_thread_close_socket(s->host);
  1106. break;
  1107. }
  1108. }
  1109. worker_is_idle();
  1110. // Wait until buffer opens in the socket or a rrdset_done_push wakes us
  1111. enum {
  1112. Collector = 0,
  1113. Socket = 1,
  1114. };
  1115. struct pollfd fds[2] = {
  1116. [Collector] = {
  1117. .fd = s->rrdpush_sender_pipe[PIPE_READ],
  1118. .events = POLLIN,
  1119. .revents = 0,
  1120. },
  1121. [Socket] = {
  1122. .fd = s->rrdpush_sender_socket,
  1123. .events = POLLIN | (outstanding ? POLLOUT : 0 ),
  1124. .revents = 0,
  1125. }
  1126. };
  1127. int poll_rc = poll(fds, 2, 1000);
  1128. debug(D_STREAM, "STREAM: poll() finished collector=%d socket=%d (current chunk %zu bytes)...",
  1129. fds[Collector].revents, fds[Socket].revents, outstanding);
  1130. if(unlikely(rrdhost_sender_should_exit(s)))
  1131. break;
  1132. internal_error(fds[Collector].fd != s->rrdpush_sender_pipe[PIPE_READ],
  1133. "STREAM %s [send to %s]: pipe changed after poll().", rrdhost_hostname(s->host), s->connected_to);
  1134. internal_error(fds[Socket].fd != s->rrdpush_sender_socket,
  1135. "STREAM %s [send to %s]: socket changed after poll().", rrdhost_hostname(s->host), s->connected_to);
  1136. // Spurious wake-ups without error - loop again
  1137. if (poll_rc == 0 || ((poll_rc == -1) && (errno == EAGAIN || errno == EINTR))) {
  1138. netdata_thread_testcancel();
  1139. debug(D_STREAM, "Spurious wakeup");
  1140. now_s = now_monotonic_sec();
  1141. continue;
  1142. }
  1143. // Only errors from poll() are internal, but try restarting the connection
  1144. if(unlikely(poll_rc == -1)) {
  1145. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_POLL_ERROR);
  1146. error("STREAM %s [send to %s]: failed to poll(). Closing socket.", rrdhost_hostname(s->host), s->connected_to);
  1147. rrdpush_sender_pipe_close(s->host, s->rrdpush_sender_pipe, true);
  1148. rrdpush_sender_thread_close_socket(s->host);
  1149. continue;
  1150. }
  1151. // If we have data and have seen the TCP window open then try to close it by a transmission.
  1152. if(likely(outstanding && (fds[Socket].revents & POLLOUT))) {
  1153. worker_is_busy(WORKER_SENDER_JOB_SOCKET_SEND);
  1154. ssize_t bytes = attempt_to_send(s);
  1155. if(bytes > 0) {
  1156. s->last_traffic_seen_t = now_monotonic_sec();
  1157. worker_set_metric(WORKER_SENDER_JOB_BYTES_SENT, (NETDATA_DOUBLE)bytes);
  1158. }
  1159. }
  1160. // If the collector woke us up then empty the pipe to remove the signal
  1161. if (fds[Collector].revents & (POLLIN|POLLPRI)) {
  1162. worker_is_busy(WORKER_SENDER_JOB_PIPE_READ);
  1163. debug(D_STREAM, "STREAM: Data added to send buffer (current buffer chunk %zu bytes)...", outstanding);
  1164. if (read(fds[Collector].fd, thread_data->pipe_buffer, pipe_buffer_size) == -1)
  1165. error("STREAM %s [send to %s]: cannot read from internal pipe.", rrdhost_hostname(s->host), s->connected_to);
  1166. }
  1167. // Read as much as possible to fill the buffer, split into full lines for execution.
  1168. if (fds[Socket].revents & POLLIN) {
  1169. worker_is_busy(WORKER_SENDER_JOB_SOCKET_RECEIVE);
  1170. ssize_t bytes = attempt_read(s);
  1171. if(bytes > 0) {
  1172. s->last_traffic_seen_t = now_monotonic_sec();
  1173. worker_set_metric(WORKER_SENDER_JOB_BYTES_RECEIVED, (NETDATA_DOUBLE)bytes);
  1174. }
  1175. }
  1176. if(unlikely(s->read_len))
  1177. execute_commands(s);
  1178. if(unlikely(fds[Collector].revents & (POLLERR|POLLHUP|POLLNVAL))) {
  1179. char *error = NULL;
  1180. if (unlikely(fds[Collector].revents & POLLERR))
  1181. error = "pipe reports errors (POLLERR)";
  1182. else if (unlikely(fds[Collector].revents & POLLHUP))
  1183. error = "pipe closed (POLLHUP)";
  1184. else if (unlikely(fds[Collector].revents & POLLNVAL))
  1185. error = "pipe is invalid (POLLNVAL)";
  1186. if(error) {
  1187. rrdpush_sender_pipe_close(s->host, s->rrdpush_sender_pipe, true);
  1188. error("STREAM %s [send to %s]: restarting internal pipe: %s.",
  1189. rrdhost_hostname(s->host), s->connected_to, error);
  1190. }
  1191. }
  1192. if(unlikely(fds[Socket].revents & (POLLERR|POLLHUP|POLLNVAL))) {
  1193. char *error = NULL;
  1194. if (unlikely(fds[Socket].revents & POLLERR))
  1195. error = "socket reports errors (POLLERR)";
  1196. else if (unlikely(fds[Socket].revents & POLLHUP))
  1197. error = "connection closed by remote end (POLLHUP)";
  1198. else if (unlikely(fds[Socket].revents & POLLNVAL))
  1199. error = "connection is invalid (POLLNVAL)";
  1200. if(unlikely(error)) {
  1201. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_SOCKER_ERROR);
  1202. error("STREAM %s [send to %s]: restarting connection: %s - %zu bytes transmitted.",
  1203. rrdhost_hostname(s->host), s->connected_to, error, s->sent_bytes_on_this_connection);
  1204. rrdpush_sender_thread_close_socket(s->host);
  1205. }
  1206. }
  1207. // protection from overflow
  1208. if(unlikely(s->flags & SENDER_FLAG_OVERFLOW)) {
  1209. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_OVERFLOW);
  1210. errno = 0;
  1211. error("STREAM %s [send to %s]: buffer full (allocated %zu bytes) after sending %zu bytes. Restarting connection",
  1212. rrdhost_hostname(s->host), s->connected_to, s->buffer->size, s->sent_bytes_on_this_connection);
  1213. rrdpush_sender_thread_close_socket(s->host);
  1214. }
  1215. worker_set_metric(WORKER_SENDER_JOB_REPLAY_DICT_SIZE, (NETDATA_DOUBLE) dictionary_entries(s->replication.requests));
  1216. }
  1217. netdata_thread_cleanup_pop(1);
  1218. return NULL;
  1219. }