sender.c 57 KB

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