sender.c 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "rrdpush.h"
  3. #include "common.h"
  4. #include "aclk/https_client.h"
  5. #define WORKER_SENDER_JOB_CONNECT 0
  6. #define WORKER_SENDER_JOB_PIPE_READ 1
  7. #define WORKER_SENDER_JOB_SOCKET_RECEIVE 2
  8. #define WORKER_SENDER_JOB_EXECUTE 3
  9. #define WORKER_SENDER_JOB_SOCKET_SEND 4
  10. #define WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE 5
  11. #define WORKER_SENDER_JOB_DISCONNECT_OVERFLOW 6
  12. #define WORKER_SENDER_JOB_DISCONNECT_TIMEOUT 7
  13. #define WORKER_SENDER_JOB_DISCONNECT_POLL_ERROR 8
  14. #define WORKER_SENDER_JOB_DISCONNECT_SOCKET_ERROR 9
  15. #define WORKER_SENDER_JOB_DISCONNECT_SSL_ERROR 10
  16. #define WORKER_SENDER_JOB_DISCONNECT_PARENT_CLOSED 11
  17. #define WORKER_SENDER_JOB_DISCONNECT_RECEIVE_ERROR 12
  18. #define WORKER_SENDER_JOB_DISCONNECT_SEND_ERROR 13
  19. #define WORKER_SENDER_JOB_DISCONNECT_NO_COMPRESSION 14
  20. #define WORKER_SENDER_JOB_BUFFER_RATIO 15
  21. #define WORKER_SENDER_JOB_BYTES_RECEIVED 16
  22. #define WORKER_SENDER_JOB_BYTES_SENT 17
  23. #define WORKER_SENDER_JOB_BYTES_COMPRESSED 18
  24. #define WORKER_SENDER_JOB_BYTES_UNCOMPRESSED 19
  25. #define WORKER_SENDER_JOB_BYTES_COMPRESSION_RATIO 20
  26. #define WORKER_SENDER_JOB_REPLAY_REQUEST 21
  27. #define WORKER_SENDER_JOB_FUNCTION_REQUEST 22
  28. #define WORKER_SENDER_JOB_REPLAY_DICT_SIZE 23
  29. #define WORKER_SENDER_JOB_DISCONNECT_CANT_UPGRADE_CONNECTION 24
  30. #if WORKER_UTILIZATION_MAX_JOB_TYPES < 25
  31. #error WORKER_UTILIZATION_MAX_JOB_TYPES has to be at least 25
  32. #endif
  33. extern struct config stream_config;
  34. extern char *netdata_ssl_ca_path;
  35. extern char *netdata_ssl_ca_file;
  36. static __thread BUFFER *sender_thread_buffer = NULL;
  37. static __thread bool sender_thread_buffer_used = false;
  38. static __thread time_t sender_thread_buffer_last_reset_s = 0;
  39. void sender_thread_buffer_free(void) {
  40. buffer_free(sender_thread_buffer);
  41. sender_thread_buffer = NULL;
  42. sender_thread_buffer_used = false;
  43. }
  44. // Collector thread starting a transmission
  45. BUFFER *sender_start(struct sender_state *s) {
  46. if(unlikely(sender_thread_buffer_used))
  47. fatal("STREAMING: thread buffer is used multiple times concurrently.");
  48. if(unlikely(rrdpush_sender_last_buffer_recreate_get(s) > sender_thread_buffer_last_reset_s)) {
  49. if(unlikely(sender_thread_buffer && sender_thread_buffer->size > THREAD_BUFFER_INITIAL_SIZE)) {
  50. buffer_free(sender_thread_buffer);
  51. sender_thread_buffer = NULL;
  52. }
  53. }
  54. if(unlikely(!sender_thread_buffer)) {
  55. sender_thread_buffer = buffer_create(THREAD_BUFFER_INITIAL_SIZE, &netdata_buffers_statistics.buffers_streaming);
  56. sender_thread_buffer_last_reset_s = rrdpush_sender_last_buffer_recreate_get(s);
  57. }
  58. sender_thread_buffer_used = true;
  59. buffer_flush(sender_thread_buffer);
  60. return sender_thread_buffer;
  61. }
  62. static inline void rrdpush_sender_thread_close_socket(RRDHOST *host);
  63. #define SENDER_BUFFER_ADAPT_TO_TIMES_MAX_SIZE 3
  64. // Collector thread finishing a transmission
  65. void sender_commit(struct sender_state *s, BUFFER *wb, STREAM_TRAFFIC_TYPE type) {
  66. if(unlikely(wb != sender_thread_buffer))
  67. fatal("STREAMING: sender is trying to commit a buffer that is not this thread's buffer.");
  68. if(unlikely(!sender_thread_buffer_used))
  69. fatal("STREAMING: sender is committing a buffer twice.");
  70. sender_thread_buffer_used = false;
  71. char *src = (char *)buffer_tostring(wb);
  72. size_t src_len = buffer_strlen(wb);
  73. if(unlikely(!src || !src_len))
  74. return;
  75. sender_lock(s);
  76. #ifdef NETDATA_LOG_STREAM_SENDER
  77. if(type == STREAM_TRAFFIC_TYPE_METADATA) {
  78. if(!s->stream_log_fp) {
  79. char filename[FILENAME_MAX + 1];
  80. snprintfz(filename, FILENAME_MAX, "/tmp/stream-sender-%s.txt", s->host ? rrdhost_hostname(s->host) : "unknown");
  81. s->stream_log_fp = fopen(filename, "w");
  82. }
  83. fprintf(s->stream_log_fp, "\n--- SEND MESSAGE START: %s ----\n"
  84. "%s"
  85. "--- SEND MESSAGE END ----------------------------------------\n"
  86. , rrdhost_hostname(s->host), src
  87. );
  88. }
  89. #endif
  90. if(unlikely(s->buffer->max_size < (src_len + 1) * SENDER_BUFFER_ADAPT_TO_TIMES_MAX_SIZE)) {
  91. netdata_log_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.",
  92. rrdhost_hostname(s->host), s->connected_to, s->buffer->max_size, buffer_strlen(wb) + 1, SENDER_BUFFER_ADAPT_TO_TIMES_MAX_SIZE);
  93. s->buffer->max_size = (src_len + 1) * SENDER_BUFFER_ADAPT_TO_TIMES_MAX_SIZE;
  94. }
  95. if (s->compressor.initialized) {
  96. while(src_len) {
  97. size_t size_to_compress = src_len;
  98. if(unlikely(size_to_compress > COMPRESSION_MAX_MSG_SIZE)) {
  99. if (stream_has_capability(s, STREAM_CAP_BINARY))
  100. size_to_compress = COMPRESSION_MAX_MSG_SIZE;
  101. else {
  102. if (size_to_compress > COMPRESSION_MAX_MSG_SIZE) {
  103. // we need to find the last newline
  104. // so that the decompressor will have a whole line to work with
  105. const char *t = &src[COMPRESSION_MAX_MSG_SIZE];
  106. while (--t >= src)
  107. if (unlikely(*t == '\n'))
  108. break;
  109. if (t <= src) {
  110. size_to_compress = COMPRESSION_MAX_MSG_SIZE;
  111. } else
  112. size_to_compress = t - src + 1;
  113. }
  114. }
  115. }
  116. const char *dst;
  117. size_t dst_len = rrdpush_compress(&s->compressor, src, size_to_compress, &dst);
  118. if (!dst_len) {
  119. netdata_log_error("STREAM %s [send to %s]: COMPRESSION failed. Resetting compressor and re-trying",
  120. rrdhost_hostname(s->host), s->connected_to);
  121. rrdpush_compression_initialize(s);
  122. dst_len = rrdpush_compress(&s->compressor, src, size_to_compress, &dst);
  123. if(!dst_len) {
  124. netdata_log_error("STREAM %s [send to %s]: COMPRESSION failed again. Deactivating compression",
  125. rrdhost_hostname(s->host), s->connected_to);
  126. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_NO_COMPRESSION);
  127. rrdpush_compression_deactivate(s);
  128. rrdpush_sender_thread_close_socket(s->host);
  129. sender_unlock(s);
  130. return;
  131. }
  132. }
  133. rrdpush_signature_t signature = rrdpush_compress_encode_signature(dst_len);
  134. #ifdef NETDATA_INTERNAL_CHECKS
  135. // check if reversing the signature provides the same length
  136. size_t decoded_dst_len = rrdpush_decompress_decode_signature((const char *)&signature, sizeof(signature));
  137. if(decoded_dst_len != dst_len)
  138. fatal("RRDPUSH COMPRESSION: invalid signature, original payload %zu bytes, "
  139. "compressed payload length %zu bytes, but signature says payload is %zu bytes",
  140. size_to_compress, dst_len, decoded_dst_len);
  141. #endif
  142. if(cbuffer_add_unsafe(s->buffer, (const char *)&signature, sizeof(signature)))
  143. s->flags |= SENDER_FLAG_OVERFLOW;
  144. else {
  145. if(cbuffer_add_unsafe(s->buffer, dst, dst_len))
  146. s->flags |= SENDER_FLAG_OVERFLOW;
  147. else
  148. s->sent_bytes_on_this_connection_per_type[type] += dst_len + sizeof(signature);
  149. }
  150. src = src + size_to_compress;
  151. src_len -= size_to_compress;
  152. }
  153. }
  154. else if(cbuffer_add_unsafe(s->buffer, src, src_len))
  155. s->flags |= SENDER_FLAG_OVERFLOW;
  156. else
  157. s->sent_bytes_on_this_connection_per_type[type] += src_len;
  158. replication_recalculate_buffer_used_ratio_unsafe(s);
  159. bool signal_sender = false;
  160. if(!rrdpush_sender_pipe_has_pending_data(s)) {
  161. rrdpush_sender_pipe_set_pending_data(s);
  162. signal_sender = true;
  163. }
  164. sender_unlock(s);
  165. if(signal_sender && (!stream_has_capability(s, STREAM_CAP_INTERPOLATED) || type != STREAM_TRAFFIC_TYPE_DATA))
  166. rrdpush_signal_sender_to_wake_up(s);
  167. }
  168. static inline void rrdpush_sender_add_host_variable_to_buffer(BUFFER *wb, const RRDVAR_ACQUIRED *rva) {
  169. buffer_sprintf(
  170. wb
  171. , "VARIABLE HOST %s = " NETDATA_DOUBLE_FORMAT "\n"
  172. , rrdvar_name(rva)
  173. , rrdvar2number(rva)
  174. );
  175. netdata_log_debug(D_STREAM, "RRDVAR pushed HOST VARIABLE %s = " NETDATA_DOUBLE_FORMAT, rrdvar_name(rva), rrdvar2number(rva));
  176. }
  177. void rrdpush_sender_send_this_host_variable_now(RRDHOST *host, const RRDVAR_ACQUIRED *rva) {
  178. if(rrdhost_can_send_definitions_to_parent(host)) {
  179. BUFFER *wb = sender_start(host->sender);
  180. rrdpush_sender_add_host_variable_to_buffer(wb, rva);
  181. sender_commit(host->sender, wb, STREAM_TRAFFIC_TYPE_METADATA);
  182. sender_thread_buffer_free();
  183. }
  184. }
  185. struct custom_host_variables_callback {
  186. BUFFER *wb;
  187. };
  188. static int rrdpush_sender_thread_custom_host_variables_callback(const DICTIONARY_ITEM *item __maybe_unused, void *rrdvar_ptr __maybe_unused, void *struct_ptr) {
  189. const RRDVAR_ACQUIRED *rv = (const RRDVAR_ACQUIRED *)item;
  190. struct custom_host_variables_callback *tmp = struct_ptr;
  191. BUFFER *wb = tmp->wb;
  192. if(unlikely(rrdvar_flags(rv) & RRDVAR_FLAG_CUSTOM_HOST_VAR && rrdvar_type(rv) == RRDVAR_TYPE_CALCULATED)) {
  193. rrdpush_sender_add_host_variable_to_buffer(wb, rv);
  194. return 1;
  195. }
  196. return 0;
  197. }
  198. static void rrdpush_sender_thread_send_custom_host_variables(RRDHOST *host) {
  199. if(rrdhost_can_send_definitions_to_parent(host)) {
  200. BUFFER *wb = sender_start(host->sender);
  201. struct custom_host_variables_callback tmp = {
  202. .wb = wb
  203. };
  204. int ret = rrdvar_walkthrough_read(host->rrdvars, rrdpush_sender_thread_custom_host_variables_callback, &tmp);
  205. (void)ret;
  206. sender_commit(host->sender, wb, STREAM_TRAFFIC_TYPE_METADATA);
  207. sender_thread_buffer_free();
  208. netdata_log_debug(D_STREAM, "RRDVAR sent %d VARIABLES", ret);
  209. }
  210. }
  211. // resets all the chart, so that their definitions
  212. // will be resent to the central netdata
  213. static void rrdpush_sender_thread_reset_all_charts(RRDHOST *host) {
  214. RRDSET *st;
  215. rrdset_foreach_read(st, host) {
  216. rrdset_flag_clear(st, RRDSET_FLAG_SENDER_REPLICATION_IN_PROGRESS);
  217. rrdset_flag_set(st, RRDSET_FLAG_SENDER_REPLICATION_FINISHED);
  218. st->rrdpush.sender.resync_time_s = 0;
  219. RRDDIM *rd;
  220. rrddim_foreach_read(rd, st)
  221. rrddim_metadata_exposed_upstream_clear(rd);
  222. rrddim_foreach_done(rd);
  223. rrdset_metadata_updated(st);
  224. }
  225. rrdset_foreach_done(st);
  226. rrdhost_sender_replicating_charts_zero(host);
  227. }
  228. static void rrdpush_sender_cbuffer_recreate_timed(struct sender_state *s, time_t now_s, bool have_mutex, bool force) {
  229. static __thread time_t last_reset_time_s = 0;
  230. if(!force && now_s - last_reset_time_s < 300)
  231. return;
  232. if(!have_mutex)
  233. sender_lock(s);
  234. rrdpush_sender_last_buffer_recreate_set(s, now_s);
  235. last_reset_time_s = now_s;
  236. if(s->buffer && s->buffer->size > CBUFFER_INITIAL_SIZE) {
  237. size_t max = s->buffer->max_size;
  238. cbuffer_free(s->buffer);
  239. s->buffer = cbuffer_new(CBUFFER_INITIAL_SIZE, max, &netdata_buffers_statistics.cbuffers_streaming);
  240. }
  241. sender_thread_buffer_free();
  242. if(!have_mutex)
  243. sender_unlock(s);
  244. }
  245. static void rrdpush_sender_cbuffer_flush(RRDHOST *host) {
  246. rrdpush_sender_set_flush_time(host->sender);
  247. sender_lock(host->sender);
  248. // flush the output buffer from any data it may have
  249. cbuffer_flush(host->sender->buffer);
  250. rrdpush_sender_cbuffer_recreate_timed(host->sender, now_monotonic_sec(), true, true);
  251. replication_recalculate_buffer_used_ratio_unsafe(host->sender);
  252. sender_unlock(host->sender);
  253. }
  254. static void rrdpush_sender_charts_and_replication_reset(RRDHOST *host) {
  255. rrdpush_sender_set_flush_time(host->sender);
  256. // stop all replication commands inflight
  257. replication_sender_delete_pending_requests(host->sender);
  258. // reset the state of all charts
  259. rrdpush_sender_thread_reset_all_charts(host);
  260. rrdpush_sender_replicating_charts_zero(host->sender);
  261. }
  262. static void rrdpush_sender_on_connect(RRDHOST *host) {
  263. rrdpush_sender_cbuffer_flush(host);
  264. rrdpush_sender_charts_and_replication_reset(host);
  265. }
  266. static void rrdpush_sender_after_connect(RRDHOST *host) {
  267. rrdpush_sender_thread_send_custom_host_variables(host);
  268. }
  269. static inline void rrdpush_sender_thread_close_socket(RRDHOST *host) {
  270. #ifdef ENABLE_HTTPS
  271. netdata_ssl_close(&host->sender->ssl);
  272. #endif
  273. if(host->sender->rrdpush_sender_socket != -1) {
  274. close(host->sender->rrdpush_sender_socket);
  275. host->sender->rrdpush_sender_socket = -1;
  276. }
  277. rrdhost_flag_clear(host, RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  278. rrdhost_flag_clear(host, RRDHOST_FLAG_RRDPUSH_SENDER_CONNECTED);
  279. // do not flush the circular buffer here
  280. // this function is called sometimes with the mutex lock, sometimes without the lock
  281. rrdpush_sender_charts_and_replication_reset(host);
  282. }
  283. void rrdpush_encode_variable(stream_encoded_t *se, RRDHOST *host) {
  284. se->os_name = (host->system_info->host_os_name)?url_encode(host->system_info->host_os_name):strdupz("");
  285. se->os_id = (host->system_info->host_os_id)?url_encode(host->system_info->host_os_id):strdupz("");
  286. se->os_version = (host->system_info->host_os_version)?url_encode(host->system_info->host_os_version):strdupz("");
  287. se->kernel_name = (host->system_info->kernel_name)?url_encode(host->system_info->kernel_name):strdupz("");
  288. se->kernel_version = (host->system_info->kernel_version)?url_encode(host->system_info->kernel_version):strdupz("");
  289. }
  290. void rrdpush_clean_encoded(stream_encoded_t *se) {
  291. if (se->os_name) {
  292. freez(se->os_name);
  293. se->os_name = NULL;
  294. }
  295. if (se->os_id) {
  296. freez(se->os_id);
  297. se->os_id = NULL;
  298. }
  299. if (se->os_version) {
  300. freez(se->os_version);
  301. se->os_version = NULL;
  302. }
  303. if (se->kernel_name) {
  304. freez(se->kernel_name);
  305. se->kernel_name = NULL;
  306. }
  307. if (se->kernel_version) {
  308. freez(se->kernel_version);
  309. se->kernel_version = NULL;
  310. }
  311. }
  312. struct {
  313. const char *response;
  314. const char *status;
  315. size_t length;
  316. int32_t version;
  317. bool dynamic;
  318. const char *error;
  319. int worker_job_id;
  320. int postpone_reconnect_seconds;
  321. ND_LOG_FIELD_PRIORITY priority;
  322. } stream_responses[] = {
  323. {
  324. .response = START_STREAMING_PROMPT_VN,
  325. .length = sizeof(START_STREAMING_PROMPT_VN) - 1,
  326. .status = RRDPUSH_STATUS_CONNECTED,
  327. .version = STREAM_HANDSHAKE_OK_V3, // and above
  328. .dynamic = true, // dynamic = we will parse the version / capabilities
  329. .error = NULL,
  330. .worker_job_id = 0,
  331. .postpone_reconnect_seconds = 0,
  332. .priority = NDLP_INFO,
  333. },
  334. {
  335. .response = START_STREAMING_PROMPT_V2,
  336. .length = sizeof(START_STREAMING_PROMPT_V2) - 1,
  337. .status = RRDPUSH_STATUS_CONNECTED,
  338. .version = STREAM_HANDSHAKE_OK_V2,
  339. .dynamic = false,
  340. .error = NULL,
  341. .worker_job_id = 0,
  342. .postpone_reconnect_seconds = 0,
  343. .priority = NDLP_INFO,
  344. },
  345. {
  346. .response = START_STREAMING_PROMPT_V1,
  347. .length = sizeof(START_STREAMING_PROMPT_V1) - 1,
  348. .status = RRDPUSH_STATUS_CONNECTED,
  349. .version = STREAM_HANDSHAKE_OK_V1,
  350. .dynamic = false,
  351. .error = NULL,
  352. .worker_job_id = 0,
  353. .postpone_reconnect_seconds = 0,
  354. .priority = NDLP_INFO,
  355. },
  356. {
  357. .response = START_STREAMING_ERROR_SAME_LOCALHOST,
  358. .length = sizeof(START_STREAMING_ERROR_SAME_LOCALHOST) - 1,
  359. .status = RRDPUSH_STATUS_LOCALHOST,
  360. .version = STREAM_HANDSHAKE_ERROR_LOCALHOST,
  361. .dynamic = false,
  362. .error = "remote server rejected this stream, the host we are trying to stream is its localhost",
  363. .worker_job_id = WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE,
  364. .postpone_reconnect_seconds = 60 * 60, // the IP may change, try it every hour
  365. .priority = NDLP_DEBUG,
  366. },
  367. {
  368. .response = START_STREAMING_ERROR_ALREADY_STREAMING,
  369. .length = sizeof(START_STREAMING_ERROR_ALREADY_STREAMING) - 1,
  370. .status = RRDPUSH_STATUS_ALREADY_CONNECTED,
  371. .version = STREAM_HANDSHAKE_ERROR_ALREADY_CONNECTED,
  372. .dynamic = false,
  373. .error = "remote server rejected this stream, the host we are trying to stream is already streamed to it",
  374. .worker_job_id = WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE,
  375. .postpone_reconnect_seconds = 2 * 60, // 2 minutes
  376. .priority = NDLP_DEBUG,
  377. },
  378. {
  379. .response = START_STREAMING_ERROR_NOT_PERMITTED,
  380. .length = sizeof(START_STREAMING_ERROR_NOT_PERMITTED) - 1,
  381. .status = RRDPUSH_STATUS_PERMISSION_DENIED,
  382. .version = STREAM_HANDSHAKE_ERROR_DENIED,
  383. .dynamic = false,
  384. .error = "remote server denied access, probably we don't have the right API key?",
  385. .worker_job_id = WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE,
  386. .postpone_reconnect_seconds = 1 * 60, // 1 minute
  387. .priority = NDLP_ERR,
  388. },
  389. {
  390. .response = START_STREAMING_ERROR_BUSY_TRY_LATER,
  391. .length = sizeof(START_STREAMING_ERROR_BUSY_TRY_LATER) - 1,
  392. .status = RRDPUSH_STATUS_RATE_LIMIT,
  393. .version = STREAM_HANDSHAKE_BUSY_TRY_LATER,
  394. .dynamic = false,
  395. .error = "remote server is currently busy, we should try later",
  396. .worker_job_id = WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE,
  397. .postpone_reconnect_seconds = 2 * 60, // 2 minutes
  398. .priority = NDLP_NOTICE,
  399. },
  400. {
  401. .response = START_STREAMING_ERROR_INTERNAL_ERROR,
  402. .length = sizeof(START_STREAMING_ERROR_INTERNAL_ERROR) - 1,
  403. .status = RRDPUSH_STATUS_INTERNAL_SERVER_ERROR,
  404. .version = STREAM_HANDSHAKE_INTERNAL_ERROR,
  405. .dynamic = false,
  406. .error = "remote server is encountered an internal error, we should try later",
  407. .worker_job_id = WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE,
  408. .postpone_reconnect_seconds = 5 * 60, // 5 minutes
  409. .priority = NDLP_CRIT,
  410. },
  411. {
  412. .response = START_STREAMING_ERROR_INITIALIZATION,
  413. .length = sizeof(START_STREAMING_ERROR_INITIALIZATION) - 1,
  414. .status = RRDPUSH_STATUS_INITIALIZATION_IN_PROGRESS,
  415. .version = STREAM_HANDSHAKE_INITIALIZATION,
  416. .dynamic = false,
  417. .error = "remote server is initializing, we should try later",
  418. .worker_job_id = WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE,
  419. .postpone_reconnect_seconds = 2 * 60, // 2 minute
  420. .priority = NDLP_NOTICE,
  421. },
  422. // terminator
  423. {
  424. .response = NULL,
  425. .length = 0,
  426. .status = RRDPUSH_STATUS_BAD_HANDSHAKE,
  427. .version = STREAM_HANDSHAKE_ERROR_BAD_HANDSHAKE,
  428. .dynamic = false,
  429. .error = "remote node response is not understood, is it Netdata?",
  430. .worker_job_id = WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE,
  431. .postpone_reconnect_seconds = 1 * 60, // 1 minute
  432. .priority = NDLP_ERR,
  433. }
  434. };
  435. static inline bool rrdpush_sender_validate_response(RRDHOST *host, struct sender_state *s, char *http, size_t http_length) {
  436. int32_t version = STREAM_HANDSHAKE_ERROR_BAD_HANDSHAKE;
  437. int i;
  438. for(i = 0; stream_responses[i].response ; i++) {
  439. if(stream_responses[i].dynamic &&
  440. http_length > stream_responses[i].length && http_length < (stream_responses[i].length + 30) &&
  441. strncmp(http, stream_responses[i].response, stream_responses[i].length) == 0) {
  442. version = str2i(&http[stream_responses[i].length]);
  443. break;
  444. }
  445. else if(http_length == stream_responses[i].length && strcmp(http, stream_responses[i].response) == 0) {
  446. version = stream_responses[i].version;
  447. break;
  448. }
  449. }
  450. if(version >= STREAM_HANDSHAKE_OK_V1) {
  451. host->destination->reason = version;
  452. host->destination->postpone_reconnection_until = now_realtime_sec() + s->reconnect_delay;
  453. s->capabilities = convert_stream_version_to_capabilities(version, host, true);
  454. return true;
  455. }
  456. ND_LOG_FIELD_PRIORITY priority = stream_responses[i].priority;
  457. const char *error = stream_responses[i].error;
  458. const char *status = stream_responses[i].status;
  459. int worker_job_id = stream_responses[i].worker_job_id;
  460. int delay = stream_responses[i].postpone_reconnect_seconds;
  461. worker_is_busy(worker_job_id);
  462. rrdpush_sender_thread_close_socket(host);
  463. host->destination->reason = version;
  464. host->destination->postpone_reconnection_until = now_realtime_sec() + delay;
  465. ND_LOG_STACK lgs[] = {
  466. ND_LOG_FIELD_TXT(NDF_RESPONSE_CODE, status),
  467. ND_LOG_FIELD_END(),
  468. };
  469. ND_LOG_STACK_PUSH(lgs);
  470. char buf[RFC3339_MAX_LENGTH];
  471. rfc3339_datetime_ut(buf, sizeof(buf), host->destination->postpone_reconnection_until * USEC_PER_SEC, 0, false);
  472. nd_log(NDLS_DAEMON, priority,
  473. "STREAM %s [send to %s]: %s - will retry in %d secs, at %s",
  474. rrdhost_hostname(host), s->connected_to, error, delay, buf);
  475. return false;
  476. }
  477. unsigned char alpn_proto_list[] = {
  478. 18, 'n', 'e', 't', 'd', 'a', 't', 'a', '_', 's', 't', 'r', 'e', 'a', 'm', '/', '2', '.', '0',
  479. 8, 'h', 't', 't', 'p', '/', '1', '.', '1'
  480. };
  481. #define CONN_UPGRADE_VAL "upgrade"
  482. static bool rrdpush_sender_connect_ssl(struct sender_state *s __maybe_unused) {
  483. #ifdef ENABLE_HTTPS
  484. RRDHOST *host = s->host;
  485. bool ssl_required = host->destination && host->destination->ssl;
  486. netdata_ssl_close(&host->sender->ssl);
  487. if(!ssl_required)
  488. return true;
  489. if (netdata_ssl_open_ext(&host->sender->ssl, netdata_ssl_streaming_sender_ctx, s->rrdpush_sender_socket, alpn_proto_list, sizeof(alpn_proto_list))) {
  490. if(!netdata_ssl_connect(&host->sender->ssl)) {
  491. // couldn't connect
  492. ND_LOG_STACK lgs[] = {
  493. ND_LOG_FIELD_TXT(NDF_RESPONSE_CODE, RRDPUSH_STATUS_SSL_ERROR),
  494. ND_LOG_FIELD_END(),
  495. };
  496. ND_LOG_STACK_PUSH(lgs);
  497. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_SSL_ERROR);
  498. rrdpush_sender_thread_close_socket(host);
  499. host->destination->reason = STREAM_HANDSHAKE_ERROR_SSL_ERROR;
  500. host->destination->postpone_reconnection_until = now_realtime_sec() + 5 * 60;
  501. return false;
  502. }
  503. if (netdata_ssl_validate_certificate_sender &&
  504. security_test_certificate(host->sender->ssl.conn)) {
  505. // certificate is not valid
  506. ND_LOG_STACK lgs[] = {
  507. ND_LOG_FIELD_TXT(NDF_RESPONSE_CODE, RRDPUSH_STATUS_INVALID_SSL_CERTIFICATE),
  508. ND_LOG_FIELD_END(),
  509. };
  510. ND_LOG_STACK_PUSH(lgs);
  511. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_SSL_ERROR);
  512. netdata_log_error("SSL: closing the stream connection, because the server SSL certificate is not valid.");
  513. rrdpush_sender_thread_close_socket(host);
  514. host->destination->reason = STREAM_HANDSHAKE_ERROR_INVALID_CERTIFICATE;
  515. host->destination->postpone_reconnection_until = now_realtime_sec() + 5 * 60;
  516. return false;
  517. }
  518. return true;
  519. }
  520. ND_LOG_STACK lgs[] = {
  521. ND_LOG_FIELD_TXT(NDF_RESPONSE_CODE, RRDPUSH_STATUS_CANT_ESTABLISH_SSL_CONNECTION),
  522. ND_LOG_FIELD_END(),
  523. };
  524. ND_LOG_STACK_PUSH(lgs);
  525. netdata_log_error("SSL: failed to establish connection.");
  526. return false;
  527. #else
  528. // SSL is not enabled
  529. return true;
  530. #endif
  531. }
  532. static int rrdpush_http_upgrade_prelude(RRDHOST *host, struct sender_state *s) {
  533. char http[HTTP_HEADER_SIZE + 1];
  534. snprintfz(http, HTTP_HEADER_SIZE,
  535. "GET " NETDATA_STREAM_URL HTTP_1_1 HTTP_ENDL
  536. "Upgrade: " NETDATA_STREAM_PROTO_NAME HTTP_ENDL
  537. "Connection: Upgrade"
  538. HTTP_HDR_END);
  539. ssize_t bytes = send_timeout(
  540. #ifdef ENABLE_HTTPS
  541. &host->sender->ssl,
  542. #endif
  543. s->rrdpush_sender_socket,
  544. http,
  545. strlen(http),
  546. 0,
  547. 1000);
  548. bytes = recv_timeout(
  549. #ifdef ENABLE_HTTPS
  550. &host->sender->ssl,
  551. #endif
  552. s->rrdpush_sender_socket,
  553. http,
  554. HTTP_HEADER_SIZE,
  555. 0,
  556. 1000);
  557. if (bytes <= 0) {
  558. error_report("Error reading from remote");
  559. return 1;
  560. }
  561. rbuf_t buf = rbuf_create(bytes);
  562. rbuf_push(buf, http, bytes);
  563. http_parse_ctx ctx;
  564. http_parse_ctx_create(&ctx);
  565. ctx.flags |= HTTP_PARSE_FLAG_DONT_WAIT_FOR_CONTENT;
  566. int rc;
  567. // while((rc = parse_http_response(buf, &ctx)) == HTTP_PARSE_NEED_MORE_DATA);
  568. rc = parse_http_response(buf, &ctx);
  569. if (rc != HTTP_PARSE_SUCCESS) {
  570. error_report("Failed to parse HTTP response sent. (%d)", rc);
  571. goto err_cleanup;
  572. }
  573. if (ctx.http_code == HTTP_RESP_MOVED_PERM) {
  574. const char *hdr = get_http_header_by_name(&ctx, "location");
  575. if (hdr)
  576. error_report("HTTP response is %d Moved Permanently (location: \"%s\") instead of expected %d Switching Protocols.", ctx.http_code, hdr, HTTP_RESP_SWITCH_PROTO);
  577. else
  578. error_report("HTTP response is %d instead of expected %d Switching Protocols.", ctx.http_code, HTTP_RESP_SWITCH_PROTO);
  579. goto err_cleanup;
  580. }
  581. if (ctx.http_code == HTTP_RESP_NOT_FOUND) {
  582. error_report("HTTP response is %d instead of expected %d Switching Protocols. Parent version too old.", ctx.http_code, HTTP_RESP_SWITCH_PROTO);
  583. // TODO set some flag here that will signify parent is older version
  584. // and to try connection without rrdpush_http_upgrade_prelude next time
  585. goto err_cleanup;
  586. }
  587. if (ctx.http_code != HTTP_RESP_SWITCH_PROTO) {
  588. error_report("HTTP response is %d instead of expected %d Switching Protocols", ctx.http_code, HTTP_RESP_SWITCH_PROTO);
  589. goto err_cleanup;
  590. }
  591. const char *hdr = get_http_header_by_name(&ctx, "connection");
  592. if (!hdr) {
  593. error_report("Missing \"connection\" header in reply");
  594. goto err_cleanup;
  595. }
  596. if (strncmp(hdr, CONN_UPGRADE_VAL, strlen(CONN_UPGRADE_VAL))) {
  597. error_report("Expected \"connection: " CONN_UPGRADE_VAL "\"");
  598. goto err_cleanup;
  599. }
  600. hdr = get_http_header_by_name(&ctx, "upgrade");
  601. if (!hdr) {
  602. error_report("Missing \"upgrade\" header in reply");
  603. goto err_cleanup;
  604. }
  605. if (strncmp(hdr, NETDATA_STREAM_PROTO_NAME, strlen(NETDATA_STREAM_PROTO_NAME))) {
  606. error_report("Expected \"upgrade: " NETDATA_STREAM_PROTO_NAME "\"");
  607. goto err_cleanup;
  608. }
  609. netdata_log_debug(D_STREAM, "Stream sender upgrade to \"" NETDATA_STREAM_PROTO_NAME "\" successful");
  610. rbuf_free(buf);
  611. http_parse_ctx_destroy(&ctx);
  612. return 0;
  613. err_cleanup:
  614. rbuf_free(buf);
  615. http_parse_ctx_destroy(&ctx);
  616. return 1;
  617. }
  618. static bool rrdpush_sender_thread_connect_to_parent(RRDHOST *host, int default_port, int timeout, struct sender_state *s) {
  619. struct timeval tv = {
  620. .tv_sec = timeout,
  621. .tv_usec = 0
  622. };
  623. // make sure the socket is closed
  624. rrdpush_sender_thread_close_socket(host);
  625. s->rrdpush_sender_socket = connect_to_one_of_destinations(
  626. host
  627. , default_port
  628. , &tv
  629. , &s->reconnects_counter
  630. , s->connected_to
  631. , sizeof(s->connected_to)-1
  632. , &host->destination
  633. );
  634. if(unlikely(s->rrdpush_sender_socket == -1)) {
  635. // netdata_log_error("STREAM %s [send to %s]: could not connect to parent node at this time.", rrdhost_hostname(host), host->rrdpush_send_destination);
  636. return false;
  637. }
  638. // netdata_log_info("STREAM %s [send to %s]: initializing communication...", rrdhost_hostname(host), s->connected_to);
  639. // reset our capabilities to default
  640. s->capabilities = stream_our_capabilities(host, true);
  641. /* TODO: During the implementation of #7265 switch the set of variables to HOST_* and CONTAINER_* if the
  642. version negotiation resulted in a high enough version.
  643. */
  644. stream_encoded_t se;
  645. rrdpush_encode_variable(&se, host);
  646. host->sender->hops = host->system_info->hops + 1;
  647. char http[HTTP_HEADER_SIZE + 1];
  648. int eol = snprintfz(http, HTTP_HEADER_SIZE,
  649. "STREAM "
  650. "key=%s"
  651. "&hostname=%s"
  652. "&registry_hostname=%s"
  653. "&machine_guid=%s"
  654. "&update_every=%d"
  655. "&os=%s"
  656. "&timezone=%s"
  657. "&abbrev_timezone=%s"
  658. "&utc_offset=%d"
  659. "&hops=%d"
  660. "&ml_capable=%d"
  661. "&ml_enabled=%d"
  662. "&mc_version=%d"
  663. "&tags=%s"
  664. "&ver=%u"
  665. "&NETDATA_INSTANCE_CLOUD_TYPE=%s"
  666. "&NETDATA_INSTANCE_CLOUD_INSTANCE_TYPE=%s"
  667. "&NETDATA_INSTANCE_CLOUD_INSTANCE_REGION=%s"
  668. "&NETDATA_SYSTEM_OS_NAME=%s"
  669. "&NETDATA_SYSTEM_OS_ID=%s"
  670. "&NETDATA_SYSTEM_OS_ID_LIKE=%s"
  671. "&NETDATA_SYSTEM_OS_VERSION=%s"
  672. "&NETDATA_SYSTEM_OS_VERSION_ID=%s"
  673. "&NETDATA_SYSTEM_OS_DETECTION=%s"
  674. "&NETDATA_HOST_IS_K8S_NODE=%s"
  675. "&NETDATA_SYSTEM_KERNEL_NAME=%s"
  676. "&NETDATA_SYSTEM_KERNEL_VERSION=%s"
  677. "&NETDATA_SYSTEM_ARCHITECTURE=%s"
  678. "&NETDATA_SYSTEM_VIRTUALIZATION=%s"
  679. "&NETDATA_SYSTEM_VIRT_DETECTION=%s"
  680. "&NETDATA_SYSTEM_CONTAINER=%s"
  681. "&NETDATA_SYSTEM_CONTAINER_DETECTION=%s"
  682. "&NETDATA_CONTAINER_OS_NAME=%s"
  683. "&NETDATA_CONTAINER_OS_ID=%s"
  684. "&NETDATA_CONTAINER_OS_ID_LIKE=%s"
  685. "&NETDATA_CONTAINER_OS_VERSION=%s"
  686. "&NETDATA_CONTAINER_OS_VERSION_ID=%s"
  687. "&NETDATA_CONTAINER_OS_DETECTION=%s"
  688. "&NETDATA_SYSTEM_CPU_LOGICAL_CPU_COUNT=%s"
  689. "&NETDATA_SYSTEM_CPU_FREQ=%s"
  690. "&NETDATA_SYSTEM_TOTAL_RAM=%s"
  691. "&NETDATA_SYSTEM_TOTAL_DISK_SIZE=%s"
  692. "&NETDATA_PROTOCOL_VERSION=%s"
  693. HTTP_1_1 HTTP_ENDL
  694. "User-Agent: %s/%s\r\n"
  695. "Accept: */*\r\n\r\n"
  696. , host->rrdpush_send_api_key
  697. , rrdhost_hostname(host)
  698. , rrdhost_registry_hostname(host)
  699. , host->machine_guid
  700. , default_rrd_update_every
  701. , rrdhost_os(host)
  702. , rrdhost_timezone(host)
  703. , rrdhost_abbrev_timezone(host)
  704. , host->utc_offset
  705. , host->sender->hops
  706. , host->system_info->ml_capable
  707. , host->system_info->ml_enabled
  708. , host->system_info->mc_version
  709. , rrdhost_tags(host)
  710. , s->capabilities
  711. , (host->system_info->cloud_provider_type) ? host->system_info->cloud_provider_type : ""
  712. , (host->system_info->cloud_instance_type) ? host->system_info->cloud_instance_type : ""
  713. , (host->system_info->cloud_instance_region) ? host->system_info->cloud_instance_region : ""
  714. , se.os_name
  715. , se.os_id
  716. , (host->system_info->host_os_id_like) ? host->system_info->host_os_id_like : ""
  717. , se.os_version
  718. , (host->system_info->host_os_version_id) ? host->system_info->host_os_version_id : ""
  719. , (host->system_info->host_os_detection) ? host->system_info->host_os_detection : ""
  720. , (host->system_info->is_k8s_node) ? host->system_info->is_k8s_node : ""
  721. , se.kernel_name
  722. , se.kernel_version
  723. , (host->system_info->architecture) ? host->system_info->architecture : ""
  724. , (host->system_info->virtualization) ? host->system_info->virtualization : ""
  725. , (host->system_info->virt_detection) ? host->system_info->virt_detection : ""
  726. , (host->system_info->container) ? host->system_info->container : ""
  727. , (host->system_info->container_detection) ? host->system_info->container_detection : ""
  728. , (host->system_info->container_os_name) ? host->system_info->container_os_name : ""
  729. , (host->system_info->container_os_id) ? host->system_info->container_os_id : ""
  730. , (host->system_info->container_os_id_like) ? host->system_info->container_os_id_like : ""
  731. , (host->system_info->container_os_version) ? host->system_info->container_os_version : ""
  732. , (host->system_info->container_os_version_id) ? host->system_info->container_os_version_id : ""
  733. , (host->system_info->container_os_detection) ? host->system_info->container_os_detection : ""
  734. , (host->system_info->host_cores) ? host->system_info->host_cores : ""
  735. , (host->system_info->host_cpu_freq) ? host->system_info->host_cpu_freq : ""
  736. , (host->system_info->host_ram_total) ? host->system_info->host_ram_total : ""
  737. , (host->system_info->host_disk_space) ? host->system_info->host_disk_space : ""
  738. , STREAMING_PROTOCOL_VERSION
  739. , rrdhost_program_name(host)
  740. , rrdhost_program_version(host)
  741. );
  742. http[eol] = 0x00;
  743. rrdpush_clean_encoded(&se);
  744. if(!rrdpush_sender_connect_ssl(s))
  745. return false;
  746. if (s->parent_using_h2o && rrdpush_http_upgrade_prelude(host, s)) {
  747. ND_LOG_STACK lgs[] = {
  748. ND_LOG_FIELD_TXT(NDF_RESPONSE_CODE, RRDPUSH_STATUS_CANT_UPGRADE_CONNECTION),
  749. ND_LOG_FIELD_END(),
  750. };
  751. ND_LOG_STACK_PUSH(lgs);
  752. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_CANT_UPGRADE_CONNECTION);
  753. rrdpush_sender_thread_close_socket(host);
  754. host->destination->reason = STREAM_HANDSHAKE_ERROR_HTTP_UPGRADE;
  755. host->destination->postpone_reconnection_until = now_realtime_sec() + 1 * 60;
  756. return false;
  757. }
  758. ssize_t bytes, len = (ssize_t)strlen(http);
  759. bytes = send_timeout(
  760. #ifdef ENABLE_HTTPS
  761. &host->sender->ssl,
  762. #endif
  763. s->rrdpush_sender_socket,
  764. http,
  765. len,
  766. 0,
  767. timeout);
  768. if(bytes <= 0) { // timeout is 0
  769. ND_LOG_STACK lgs[] = {
  770. ND_LOG_FIELD_TXT(NDF_RESPONSE_CODE, RRDPUSH_STATUS_TIMEOUT),
  771. ND_LOG_FIELD_END(),
  772. };
  773. ND_LOG_STACK_PUSH(lgs);
  774. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_TIMEOUT);
  775. rrdpush_sender_thread_close_socket(host);
  776. nd_log(NDLS_DAEMON, NDLP_ERR,
  777. "STREAM %s [send to %s]: failed to send HTTP header to remote netdata.",
  778. rrdhost_hostname(host), s->connected_to);
  779. host->destination->reason = STREAM_HANDSHAKE_ERROR_SEND_TIMEOUT;
  780. host->destination->postpone_reconnection_until = now_realtime_sec() + 1 * 60;
  781. return false;
  782. }
  783. bytes = recv_timeout(
  784. #ifdef ENABLE_HTTPS
  785. &host->sender->ssl,
  786. #endif
  787. s->rrdpush_sender_socket,
  788. http,
  789. HTTP_HEADER_SIZE,
  790. 0,
  791. timeout);
  792. if(bytes <= 0) { // timeout is 0
  793. ND_LOG_STACK lgs[] = {
  794. ND_LOG_FIELD_TXT(NDF_RESPONSE_CODE, RRDPUSH_STATUS_TIMEOUT),
  795. ND_LOG_FIELD_END(),
  796. };
  797. ND_LOG_STACK_PUSH(lgs);
  798. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_TIMEOUT);
  799. rrdpush_sender_thread_close_socket(host);
  800. nd_log(NDLS_DAEMON, NDLP_ERR,
  801. "STREAM %s [send to %s]: remote netdata does not respond.",
  802. rrdhost_hostname(host), s->connected_to);
  803. host->destination->reason = STREAM_HANDSHAKE_ERROR_RECEIVE_TIMEOUT;
  804. host->destination->postpone_reconnection_until = now_realtime_sec() + 30;
  805. return false;
  806. }
  807. if(sock_setnonblock(s->rrdpush_sender_socket) < 0)
  808. nd_log(NDLS_DAEMON, NDLP_WARNING,
  809. "STREAM %s [send to %s]: cannot set non-blocking mode for socket.",
  810. rrdhost_hostname(host), s->connected_to);
  811. if(sock_enlarge_out(s->rrdpush_sender_socket) < 0)
  812. nd_log(NDLS_DAEMON, NDLP_WARNING,
  813. "STREAM %s [send to %s]: cannot enlarge the socket buffer.",
  814. rrdhost_hostname(host), s->connected_to);
  815. http[bytes] = '\0';
  816. if(!rrdpush_sender_validate_response(host, s, http, bytes))
  817. return false;
  818. rrdpush_compression_initialize(s);
  819. log_sender_capabilities(s);
  820. ND_LOG_STACK lgs[] = {
  821. ND_LOG_FIELD_TXT(NDF_RESPONSE_CODE, RRDPUSH_STATUS_CONNECTED),
  822. ND_LOG_FIELD_END(),
  823. };
  824. ND_LOG_STACK_PUSH(lgs);
  825. nd_log(NDLS_DAEMON, NDLP_DEBUG,
  826. "STREAM %s: connected to %s...",
  827. rrdhost_hostname(host), s->connected_to);
  828. return true;
  829. }
  830. static bool attempt_to_connect(struct sender_state *state) {
  831. ND_LOG_STACK lgs[] = {
  832. ND_LOG_FIELD_UUID(NDF_MESSAGE_ID, &streaming_to_parent_msgid),
  833. ND_LOG_FIELD_END(),
  834. };
  835. ND_LOG_STACK_PUSH(lgs);
  836. state->send_attempts = 0;
  837. // reset the bytes we have sent for this session
  838. state->sent_bytes_on_this_connection = 0;
  839. memset(state->sent_bytes_on_this_connection_per_type, 0, sizeof(state->sent_bytes_on_this_connection_per_type));
  840. if(rrdpush_sender_thread_connect_to_parent(state->host, state->default_port, state->timeout, state)) {
  841. // reset the buffer, to properly send charts and metrics
  842. rrdpush_sender_on_connect(state->host);
  843. // send from the beginning
  844. state->begin = 0;
  845. // make sure the next reconnection will be immediate
  846. state->not_connected_loops = 0;
  847. // let the data collection threads know we are ready
  848. rrdhost_flag_set(state->host, RRDHOST_FLAG_RRDPUSH_SENDER_CONNECTED);
  849. rrdpush_sender_after_connect(state->host);
  850. return true;
  851. }
  852. // we couldn't connect
  853. // increase the failed connections counter
  854. state->not_connected_loops++;
  855. // slow re-connection on repeating errors
  856. usec_t now_ut = now_monotonic_usec();
  857. usec_t end_ut = now_ut + USEC_PER_SEC * state->reconnect_delay;
  858. while(now_ut < end_ut) {
  859. netdata_thread_testcancel();
  860. sleep_usec(500 * USEC_PER_MS); // seconds
  861. now_ut = now_monotonic_usec();
  862. }
  863. return false;
  864. }
  865. // TCP window is open, and we have data to transmit.
  866. static ssize_t attempt_to_send(struct sender_state *s) {
  867. ssize_t ret;
  868. #ifdef NETDATA_INTERNAL_CHECKS
  869. struct circular_buffer *cb = s->buffer;
  870. #endif
  871. sender_lock(s);
  872. char *chunk;
  873. size_t outstanding = cbuffer_next_unsafe(s->buffer, &chunk);
  874. netdata_log_debug(D_STREAM, "STREAM: Sending data. Buffer r=%zu w=%zu s=%zu, next chunk=%zu", cb->read, cb->write, cb->size, outstanding);
  875. #ifdef ENABLE_HTTPS
  876. if(SSL_connection(&s->ssl))
  877. ret = netdata_ssl_write(&s->ssl, chunk, outstanding);
  878. else
  879. ret = send(s->rrdpush_sender_socket, chunk, outstanding, MSG_DONTWAIT);
  880. #else
  881. ret = send(s->rrdpush_sender_socket, chunk, outstanding, MSG_DONTWAIT);
  882. #endif
  883. if (likely(ret > 0)) {
  884. cbuffer_remove_unsafe(s->buffer, ret);
  885. s->sent_bytes_on_this_connection += ret;
  886. s->sent_bytes += ret;
  887. netdata_log_debug(D_STREAM, "STREAM %s [send to %s]: Sent %zd bytes", rrdhost_hostname(s->host), s->connected_to, ret);
  888. }
  889. else if (ret == -1 && (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
  890. netdata_log_debug(D_STREAM, "STREAM %s [send to %s]: unavailable after polling POLLOUT", rrdhost_hostname(s->host), s->connected_to);
  891. else if (ret == -1) {
  892. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_SEND_ERROR);
  893. netdata_log_debug(D_STREAM, "STREAM: Send failed - closing socket...");
  894. netdata_log_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);
  895. rrdpush_sender_thread_close_socket(s->host);
  896. }
  897. else
  898. netdata_log_debug(D_STREAM, "STREAM: send() returned 0 -> no error but no transmission");
  899. replication_recalculate_buffer_used_ratio_unsafe(s);
  900. sender_unlock(s);
  901. return ret;
  902. }
  903. static ssize_t attempt_read(struct sender_state *s) {
  904. ssize_t ret;
  905. #ifdef ENABLE_HTTPS
  906. if (SSL_connection(&s->ssl))
  907. ret = netdata_ssl_read(&s->ssl, s->read_buffer + s->read_len, sizeof(s->read_buffer) - s->read_len - 1);
  908. else
  909. ret = recv(s->rrdpush_sender_socket, s->read_buffer + s->read_len, sizeof(s->read_buffer) - s->read_len - 1,MSG_DONTWAIT);
  910. #else
  911. ret = recv(s->rrdpush_sender_socket, s->read_buffer + s->read_len, sizeof(s->read_buffer) - s->read_len - 1,MSG_DONTWAIT);
  912. #endif
  913. if (ret > 0) {
  914. s->read_len += ret;
  915. return ret;
  916. }
  917. if (ret < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
  918. return ret;
  919. #ifdef ENABLE_HTTPS
  920. if (SSL_connection(&s->ssl))
  921. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_SSL_ERROR);
  922. else
  923. #endif
  924. if (ret == 0 || errno == ECONNRESET) {
  925. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_PARENT_CLOSED);
  926. netdata_log_error("STREAM %s [send to %s]: connection closed by far end.", rrdhost_hostname(s->host), s->connected_to);
  927. }
  928. else {
  929. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_RECEIVE_ERROR);
  930. netdata_log_error("STREAM %s [send to %s]: error during receive (%zd) - closing connection.", rrdhost_hostname(s->host), s->connected_to, ret);
  931. }
  932. rrdpush_sender_thread_close_socket(s->host);
  933. return ret;
  934. }
  935. struct inflight_stream_function {
  936. struct sender_state *sender;
  937. STRING *transaction;
  938. usec_t received_ut;
  939. };
  940. void stream_execute_function_callback(BUFFER *func_wb, int code, void *data) {
  941. struct inflight_stream_function *tmp = data;
  942. struct sender_state *s = tmp->sender;
  943. if(rrdhost_can_send_definitions_to_parent(s->host)) {
  944. BUFFER *wb = sender_start(s);
  945. pluginsd_function_result_begin_to_buffer(wb
  946. , string2str(tmp->transaction)
  947. , code
  948. , functions_content_type_to_format(func_wb->content_type)
  949. , func_wb->expires);
  950. buffer_fast_strcat(wb, buffer_tostring(func_wb), buffer_strlen(func_wb));
  951. pluginsd_function_result_end_to_buffer(wb);
  952. sender_commit(s, wb, STREAM_TRAFFIC_TYPE_FUNCTIONS);
  953. sender_thread_buffer_free();
  954. internal_error(true, "STREAM %s [send to %s] FUNCTION transaction %s sending back response (%zu bytes, %"PRIu64" usec).",
  955. rrdhost_hostname(s->host), s->connected_to,
  956. string2str(tmp->transaction),
  957. buffer_strlen(func_wb),
  958. now_realtime_usec() - tmp->received_ut);
  959. }
  960. string_freez(tmp->transaction);
  961. buffer_free(func_wb);
  962. freez(tmp);
  963. }
  964. // This is just a placeholder until the gap filling state machine is inserted
  965. void execute_commands(struct sender_state *s) {
  966. worker_is_busy(WORKER_SENDER_JOB_EXECUTE);
  967. ND_LOG_STACK lgs[] = {
  968. ND_LOG_FIELD_CB(NDF_REQUEST, line_splitter_reconstruct_line, &s->line),
  969. ND_LOG_FIELD_END(),
  970. };
  971. ND_LOG_STACK_PUSH(lgs);
  972. char *start = s->read_buffer, *end = &s->read_buffer[s->read_len], *newline;
  973. *end = 0;
  974. while( start < end && (newline = strchr(start, '\n')) ) {
  975. *newline = '\0';
  976. if (s->receiving_function_payload && unlikely(strcmp(start, PLUGINSD_KEYWORD_FUNCTION_PAYLOAD_END) != 0)) {
  977. if (buffer_strlen(s->function_payload.payload) != 0)
  978. buffer_strcat(s->function_payload.payload, "\n");
  979. buffer_strcat(s->function_payload.payload, start);
  980. start = newline + 1;
  981. continue;
  982. }
  983. s->line.count++;
  984. s->line.num_words = quoted_strings_splitter_pluginsd(start, s->line.words, PLUGINSD_MAX_WORDS);
  985. const char *command = get_word(s->line.words, s->line.num_words, 0);
  986. if(command && (strcmp(command, PLUGINSD_KEYWORD_FUNCTION) == 0 || strcmp(command, PLUGINSD_KEYWORD_FUNCTION_PAYLOAD_END) == 0)) {
  987. worker_is_busy(WORKER_SENDER_JOB_FUNCTION_REQUEST);
  988. nd_log(NDLS_ACCESS, NDLP_INFO, NULL);
  989. char *transaction = s->receiving_function_payload ? s->function_payload.txid : get_word(s->line.words, s->line.num_words, 1);
  990. char *timeout_s = s->receiving_function_payload ? s->function_payload.timeout : get_word(s->line.words, s->line.num_words, 2);
  991. char *function = s->receiving_function_payload ? s->function_payload.fn_name : get_word(s->line.words, s->line.num_words, 3);
  992. if(!transaction || !*transaction || !timeout_s || !*timeout_s || !function || !*function) {
  993. netdata_log_error("STREAM %s [send to %s] %s execution command is incomplete (transaction = '%s', timeout = '%s', function = '%s'). Ignoring it.",
  994. rrdhost_hostname(s->host), s->connected_to,
  995. command,
  996. transaction?transaction:"(unset)",
  997. timeout_s?timeout_s:"(unset)",
  998. function?function:"(unset)");
  999. }
  1000. else {
  1001. int timeout = str2i(timeout_s);
  1002. if(timeout <= 0) timeout = PLUGINS_FUNCTIONS_TIMEOUT_DEFAULT;
  1003. struct inflight_stream_function *tmp = callocz(1, sizeof(struct inflight_stream_function));
  1004. tmp->received_ut = now_realtime_usec();
  1005. tmp->sender = s;
  1006. tmp->transaction = string_strdupz(transaction);
  1007. BUFFER *wb = buffer_create(PLUGINSD_LINE_MAX + 1, &netdata_buffers_statistics.buffers_functions);
  1008. char *payload = s->receiving_function_payload ? (char *)buffer_tostring(s->function_payload.payload) : NULL;
  1009. int code = rrd_function_run(s->host, wb, timeout, function, false, transaction,
  1010. stream_execute_function_callback, tmp, NULL, NULL, payload);
  1011. if(code != HTTP_RESP_OK) {
  1012. if (!buffer_strlen(wb))
  1013. rrd_call_function_error(wb, "Failed to route request to collector", code);
  1014. stream_execute_function_callback(wb, code, tmp);
  1015. }
  1016. }
  1017. if (s->receiving_function_payload) {
  1018. s->receiving_function_payload = false;
  1019. buffer_free(s->function_payload.payload);
  1020. freez(s->function_payload.txid);
  1021. freez(s->function_payload.timeout);
  1022. freez(s->function_payload.fn_name);
  1023. memset(&s->function_payload, 0, sizeof(struct function_payload_state));
  1024. }
  1025. }
  1026. else if (command && strcmp(command, PLUGINSD_KEYWORD_FUNCTION_PAYLOAD) == 0) {
  1027. nd_log(NDLS_ACCESS, NDLP_INFO, NULL);
  1028. if (s->receiving_function_payload) {
  1029. netdata_log_error("STREAM %s [send to %s] received %s command while already receiving function payload",
  1030. rrdhost_hostname(s->host), s->connected_to, command);
  1031. s->receiving_function_payload = false;
  1032. buffer_free(s->function_payload.payload);
  1033. s->function_payload.payload = NULL;
  1034. // TODO send error response
  1035. }
  1036. char *transaction = get_word(s->line.words, s->line.num_words, 1);
  1037. char *timeout_s = get_word(s->line.words, s->line.num_words, 2);
  1038. char *function = get_word(s->line.words, s->line.num_words, 3);
  1039. if(!transaction || !*transaction || !timeout_s || !*timeout_s || !function || !*function) {
  1040. netdata_log_error("STREAM %s [send to %s] %s execution command is incomplete (transaction = '%s', timeout = '%s', function = '%s'). Ignoring it.",
  1041. rrdhost_hostname(s->host), s->connected_to,
  1042. command,
  1043. transaction?transaction:"(unset)",
  1044. timeout_s?timeout_s:"(unset)",
  1045. function?function:"(unset)");
  1046. }
  1047. s->receiving_function_payload = true;
  1048. s->function_payload.payload = buffer_create(4096, &netdata_buffers_statistics.buffers_functions);
  1049. s->function_payload.txid = strdupz(get_word(s->line.words, s->line.num_words, 1));
  1050. s->function_payload.timeout = strdupz(get_word(s->line.words, s->line.num_words, 2));
  1051. s->function_payload.fn_name = strdupz(get_word(s->line.words, s->line.num_words, 3));
  1052. }
  1053. else if(command && strcmp(command, PLUGINSD_KEYWORD_FUNCTION_CANCEL) == 0) {
  1054. worker_is_busy(WORKER_SENDER_JOB_FUNCTION_REQUEST);
  1055. nd_log(NDLS_ACCESS, NDLP_DEBUG, NULL);
  1056. char *transaction = get_word(s->line.words, s->line.num_words, 1);
  1057. if(transaction && *transaction)
  1058. rrd_function_cancel(transaction);
  1059. }
  1060. else if (command && strcmp(command, PLUGINSD_KEYWORD_REPLAY_CHART) == 0) {
  1061. worker_is_busy(WORKER_SENDER_JOB_REPLAY_REQUEST);
  1062. nd_log(NDLS_ACCESS, NDLP_DEBUG, NULL);
  1063. const char *chart_id = get_word(s->line.words, s->line.num_words, 1);
  1064. const char *start_streaming = get_word(s->line.words, s->line.num_words, 2);
  1065. const char *after = get_word(s->line.words, s->line.num_words, 3);
  1066. const char *before = get_word(s->line.words, s->line.num_words, 4);
  1067. if (!chart_id || !start_streaming || !after || !before) {
  1068. netdata_log_error("STREAM %s [send to %s] %s command is incomplete"
  1069. " (chart=%s, start_streaming=%s, after=%s, before=%s)",
  1070. rrdhost_hostname(s->host), s->connected_to,
  1071. command,
  1072. chart_id ? chart_id : "(unset)",
  1073. start_streaming ? start_streaming : "(unset)",
  1074. after ? after : "(unset)",
  1075. before ? before : "(unset)");
  1076. }
  1077. else {
  1078. replication_add_request(s, chart_id,
  1079. strtoll(after, NULL, 0),
  1080. strtoll(before, NULL, 0),
  1081. !strcmp(start_streaming, "true")
  1082. );
  1083. }
  1084. }
  1085. else {
  1086. netdata_log_error("STREAM %s [send to %s] received unknown command over connection: %s", rrdhost_hostname(s->host), s->connected_to, s->line.words[0]?s->line.words[0]:"(unset)");
  1087. }
  1088. line_splitter_reset(&s->line);
  1089. worker_is_busy(WORKER_SENDER_JOB_EXECUTE);
  1090. start = newline + 1;
  1091. }
  1092. if (start < end) {
  1093. memmove(s->read_buffer, start, end-start);
  1094. s->read_len = end - start;
  1095. }
  1096. else {
  1097. s->read_buffer[0] = '\0';
  1098. s->read_len = 0;
  1099. }
  1100. }
  1101. struct rrdpush_sender_thread_data {
  1102. RRDHOST *host;
  1103. char *pipe_buffer;
  1104. };
  1105. static bool rrdpush_sender_pipe_close(RRDHOST *host, int *pipe_fds, bool reopen) {
  1106. static netdata_mutex_t mutex = NETDATA_MUTEX_INITIALIZER;
  1107. bool ret = true;
  1108. netdata_mutex_lock(&mutex);
  1109. int new_pipe_fds[2];
  1110. if(reopen) {
  1111. if(pipe(new_pipe_fds) != 0) {
  1112. netdata_log_error("STREAM %s [send]: cannot create required pipe.", rrdhost_hostname(host));
  1113. new_pipe_fds[PIPE_READ] = -1;
  1114. new_pipe_fds[PIPE_WRITE] = -1;
  1115. ret = false;
  1116. }
  1117. }
  1118. int old_pipe_fds[2];
  1119. old_pipe_fds[PIPE_READ] = pipe_fds[PIPE_READ];
  1120. old_pipe_fds[PIPE_WRITE] = pipe_fds[PIPE_WRITE];
  1121. if(reopen) {
  1122. pipe_fds[PIPE_READ] = new_pipe_fds[PIPE_READ];
  1123. pipe_fds[PIPE_WRITE] = new_pipe_fds[PIPE_WRITE];
  1124. }
  1125. else {
  1126. pipe_fds[PIPE_READ] = -1;
  1127. pipe_fds[PIPE_WRITE] = -1;
  1128. }
  1129. if(old_pipe_fds[PIPE_READ] > 2)
  1130. close(old_pipe_fds[PIPE_READ]);
  1131. if(old_pipe_fds[PIPE_WRITE] > 2)
  1132. close(old_pipe_fds[PIPE_WRITE]);
  1133. netdata_mutex_unlock(&mutex);
  1134. return ret;
  1135. }
  1136. void rrdpush_signal_sender_to_wake_up(struct sender_state *s) {
  1137. if(unlikely(s->tid == gettid()))
  1138. return;
  1139. RRDHOST *host = s->host;
  1140. int pipe_fd = s->rrdpush_sender_pipe[PIPE_WRITE];
  1141. // signal the sender there are more data
  1142. if (pipe_fd != -1 && write(pipe_fd, " ", 1) == -1) {
  1143. netdata_log_error("STREAM %s [send]: cannot write to internal pipe.", rrdhost_hostname(host));
  1144. rrdpush_sender_pipe_close(host, s->rrdpush_sender_pipe, true);
  1145. }
  1146. }
  1147. static bool rrdhost_set_sender(RRDHOST *host) {
  1148. if(unlikely(!host->sender)) return false;
  1149. bool ret = false;
  1150. sender_lock(host->sender);
  1151. if(!host->sender->tid) {
  1152. rrdhost_flag_clear(host, RRDHOST_FLAG_RRDPUSH_SENDER_CONNECTED | RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  1153. rrdhost_flag_set(host, RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN);
  1154. host->rrdpush_sender_connection_counter++;
  1155. host->sender->tid = gettid();
  1156. host->sender->last_state_since_t = now_realtime_sec();
  1157. host->sender->exit.reason = STREAM_HANDSHAKE_NEVER;
  1158. ret = true;
  1159. }
  1160. sender_unlock(host->sender);
  1161. rrdpush_reset_destinations_postpone_time(host);
  1162. return ret;
  1163. }
  1164. static void rrdhost_clear_sender___while_having_sender_mutex(RRDHOST *host) {
  1165. if(unlikely(!host->sender)) return;
  1166. if(host->sender->tid == gettid()) {
  1167. host->sender->tid = 0;
  1168. host->sender->exit.shutdown = false;
  1169. rrdhost_flag_clear(host, RRDHOST_FLAG_RRDPUSH_SENDER_SPAWN | RRDHOST_FLAG_RRDPUSH_SENDER_CONNECTED | RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  1170. host->sender->last_state_since_t = now_realtime_sec();
  1171. if(host->destination) {
  1172. host->destination->since = host->sender->last_state_since_t;
  1173. host->destination->reason = host->sender->exit.reason;
  1174. }
  1175. }
  1176. rrdpush_reset_destinations_postpone_time(host);
  1177. }
  1178. static bool rrdhost_sender_should_exit(struct sender_state *s) {
  1179. // check for outstanding cancellation requests
  1180. netdata_thread_testcancel();
  1181. if(unlikely(!service_running(SERVICE_STREAMING))) {
  1182. if(!s->exit.reason)
  1183. s->exit.reason = STREAM_HANDSHAKE_DISCONNECT_NETDATA_EXIT;
  1184. return true;
  1185. }
  1186. if(unlikely(!rrdhost_has_rrdpush_sender_enabled(s->host))) {
  1187. if(!s->exit.reason)
  1188. s->exit.reason = STREAM_HANDSHAKE_NON_STREAMABLE_HOST;
  1189. return true;
  1190. }
  1191. if(unlikely(s->exit.shutdown)) {
  1192. if(!s->exit.reason)
  1193. s->exit.reason = STREAM_HANDSHAKE_DISCONNECT_SHUTDOWN;
  1194. return true;
  1195. }
  1196. if(unlikely(rrdhost_flag_check(s->host, RRDHOST_FLAG_ORPHAN))) {
  1197. if(!s->exit.reason)
  1198. s->exit.reason = STREAM_HANDSHAKE_DISCONNECT_ORPHAN_HOST;
  1199. return true;
  1200. }
  1201. return false;
  1202. }
  1203. static void rrdpush_sender_thread_cleanup_callback(void *ptr) {
  1204. struct rrdpush_sender_thread_data *s = ptr;
  1205. worker_unregister();
  1206. RRDHOST *host = s->host;
  1207. sender_lock(host->sender);
  1208. netdata_log_info("STREAM %s [send]: sending thread exits %s",
  1209. rrdhost_hostname(host),
  1210. host->sender->exit.reason != STREAM_HANDSHAKE_NEVER ? stream_handshake_error_to_string(host->sender->exit.reason) : "");
  1211. rrdpush_sender_thread_close_socket(host);
  1212. rrdpush_sender_pipe_close(host, host->sender->rrdpush_sender_pipe, false);
  1213. rrdhost_clear_sender___while_having_sender_mutex(host);
  1214. #ifdef NETDATA_LOG_STREAM_SENDER
  1215. if(host->sender->stream_log_fp) {
  1216. fclose(host->sender->stream_log_fp);
  1217. host->sender->stream_log_fp = NULL;
  1218. }
  1219. #endif
  1220. sender_unlock(host->sender);
  1221. freez(s->pipe_buffer);
  1222. freez(s);
  1223. }
  1224. void rrdpush_initialize_ssl_ctx(RRDHOST *host __maybe_unused) {
  1225. #ifdef ENABLE_HTTPS
  1226. static SPINLOCK sp = NETDATA_SPINLOCK_INITIALIZER;
  1227. spinlock_lock(&sp);
  1228. if(netdata_ssl_streaming_sender_ctx || !host) {
  1229. spinlock_unlock(&sp);
  1230. return;
  1231. }
  1232. for(struct rrdpush_destinations *d = host->destinations; d ; d = d->next) {
  1233. if (d->ssl) {
  1234. // we need to initialize SSL
  1235. netdata_ssl_initialize_ctx(NETDATA_SSL_STREAMING_SENDER_CTX);
  1236. ssl_security_location_for_context(netdata_ssl_streaming_sender_ctx, netdata_ssl_ca_file, netdata_ssl_ca_path);
  1237. // stop the loop
  1238. break;
  1239. }
  1240. }
  1241. spinlock_unlock(&sp);
  1242. #endif
  1243. }
  1244. static bool stream_sender_log_capabilities(BUFFER *wb, void *ptr) {
  1245. struct sender_state *state = ptr;
  1246. if(!state)
  1247. return false;
  1248. stream_capabilities_to_string(wb, state->capabilities);
  1249. return true;
  1250. }
  1251. static bool stream_sender_log_transport(BUFFER *wb, void *ptr) {
  1252. struct sender_state *state = ptr;
  1253. if(!state)
  1254. return false;
  1255. #ifdef ENABLE_HTTPS
  1256. buffer_strcat(wb, SSL_connection(&state->ssl) ? "https" : "http");
  1257. #else
  1258. buffer_strcat(wb, "http");
  1259. #endif
  1260. return true;
  1261. }
  1262. static bool stream_sender_log_dst_ip(BUFFER *wb, void *ptr) {
  1263. struct sender_state *state = ptr;
  1264. if(!state || state->rrdpush_sender_socket == -1)
  1265. return false;
  1266. SOCKET_PEERS peers = socket_peers(state->rrdpush_sender_socket);
  1267. buffer_strcat(wb, peers.peer.ip);
  1268. return true;
  1269. }
  1270. static bool stream_sender_log_dst_port(BUFFER *wb, void *ptr) {
  1271. struct sender_state *state = ptr;
  1272. if(!state || state->rrdpush_sender_socket == -1)
  1273. return false;
  1274. SOCKET_PEERS peers = socket_peers(state->rrdpush_sender_socket);
  1275. buffer_print_uint64(wb, peers.peer.port);
  1276. return true;
  1277. }
  1278. void *rrdpush_sender_thread(void *ptr) {
  1279. struct sender_state *s = ptr;
  1280. ND_LOG_STACK lgs[] = {
  1281. ND_LOG_FIELD_STR(NDF_NIDL_NODE, s->host->hostname),
  1282. ND_LOG_FIELD_CB(NDF_DST_IP, stream_sender_log_dst_ip, s),
  1283. ND_LOG_FIELD_CB(NDF_DST_PORT, stream_sender_log_dst_port, s),
  1284. ND_LOG_FIELD_CB(NDF_DST_TRANSPORT, stream_sender_log_transport, s),
  1285. ND_LOG_FIELD_CB(NDF_SRC_CAPABILITIES, stream_sender_log_capabilities, s),
  1286. ND_LOG_FIELD_END(),
  1287. };
  1288. ND_LOG_STACK_PUSH(lgs);
  1289. worker_register("STREAMSND");
  1290. worker_register_job_name(WORKER_SENDER_JOB_CONNECT, "connect");
  1291. worker_register_job_name(WORKER_SENDER_JOB_PIPE_READ, "pipe read");
  1292. worker_register_job_name(WORKER_SENDER_JOB_SOCKET_RECEIVE, "receive");
  1293. worker_register_job_name(WORKER_SENDER_JOB_EXECUTE, "execute");
  1294. worker_register_job_name(WORKER_SENDER_JOB_SOCKET_SEND, "send");
  1295. // disconnection reasons
  1296. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_TIMEOUT, "disconnect timeout");
  1297. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_POLL_ERROR, "disconnect poll error");
  1298. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_SOCKET_ERROR, "disconnect socket error");
  1299. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_OVERFLOW, "disconnect overflow");
  1300. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_SSL_ERROR, "disconnect ssl error");
  1301. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_PARENT_CLOSED, "disconnect parent closed");
  1302. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_RECEIVE_ERROR, "disconnect receive error");
  1303. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_SEND_ERROR, "disconnect send error");
  1304. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_NO_COMPRESSION, "disconnect no compression");
  1305. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_BAD_HANDSHAKE, "disconnect bad handshake");
  1306. worker_register_job_name(WORKER_SENDER_JOB_DISCONNECT_CANT_UPGRADE_CONNECTION, "disconnect cant upgrade");
  1307. worker_register_job_name(WORKER_SENDER_JOB_REPLAY_REQUEST, "replay request");
  1308. worker_register_job_name(WORKER_SENDER_JOB_FUNCTION_REQUEST, "function");
  1309. worker_register_job_custom_metric(WORKER_SENDER_JOB_BUFFER_RATIO, "used buffer ratio", "%", WORKER_METRIC_ABSOLUTE);
  1310. worker_register_job_custom_metric(WORKER_SENDER_JOB_BYTES_RECEIVED, "bytes received", "bytes/s", WORKER_METRIC_INCREMENT);
  1311. worker_register_job_custom_metric(WORKER_SENDER_JOB_BYTES_SENT, "bytes sent", "bytes/s", WORKER_METRIC_INCREMENT);
  1312. worker_register_job_custom_metric(WORKER_SENDER_JOB_BYTES_COMPRESSED, "bytes compressed", "bytes/s", WORKER_METRIC_INCREMENTAL_TOTAL);
  1313. worker_register_job_custom_metric(WORKER_SENDER_JOB_BYTES_UNCOMPRESSED, "bytes uncompressed", "bytes/s", WORKER_METRIC_INCREMENTAL_TOTAL);
  1314. worker_register_job_custom_metric(WORKER_SENDER_JOB_BYTES_COMPRESSION_RATIO, "cumulative compression savings ratio", "%", WORKER_METRIC_ABSOLUTE);
  1315. worker_register_job_custom_metric(WORKER_SENDER_JOB_REPLAY_DICT_SIZE, "replication dict entries", "entries", WORKER_METRIC_ABSOLUTE);
  1316. if(!rrdhost_has_rrdpush_sender_enabled(s->host) || !s->host->rrdpush_send_destination ||
  1317. !*s->host->rrdpush_send_destination || !s->host->rrdpush_send_api_key ||
  1318. !*s->host->rrdpush_send_api_key) {
  1319. netdata_log_error("STREAM %s [send]: thread created (task id %d), but host has streaming disabled.",
  1320. rrdhost_hostname(s->host), gettid());
  1321. return NULL;
  1322. }
  1323. if(!rrdhost_set_sender(s->host)) {
  1324. netdata_log_error("STREAM %s [send]: thread created (task id %d), but there is another sender running for this host.",
  1325. rrdhost_hostname(s->host), gettid());
  1326. return NULL;
  1327. }
  1328. rrdpush_initialize_ssl_ctx(s->host);
  1329. netdata_log_info("STREAM %s [send]: thread created (task id %d)", rrdhost_hostname(s->host), gettid());
  1330. s->timeout = (int)appconfig_get_number(
  1331. &stream_config, CONFIG_SECTION_STREAM, "timeout seconds", 600);
  1332. s->default_port = (int)appconfig_get_number(
  1333. &stream_config, CONFIG_SECTION_STREAM, "default port", 19999);
  1334. s->buffer->max_size = (size_t)appconfig_get_number(
  1335. &stream_config, CONFIG_SECTION_STREAM, "buffer size bytes", 1024 * 1024 * 10);
  1336. s->reconnect_delay = (unsigned int)appconfig_get_number(
  1337. &stream_config, CONFIG_SECTION_STREAM, "reconnect delay seconds", 5);
  1338. remote_clock_resync_iterations = (unsigned int)appconfig_get_number(
  1339. &stream_config, CONFIG_SECTION_STREAM,
  1340. "initial clock resync iterations",
  1341. remote_clock_resync_iterations); // TODO: REMOVE FOR SLEW / GAPFILLING
  1342. s->parent_using_h2o = appconfig_get_boolean(
  1343. &stream_config, CONFIG_SECTION_STREAM, "parent using h2o", false);
  1344. // initialize rrdpush globals
  1345. rrdhost_flag_clear(s->host, RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  1346. rrdhost_flag_clear(s->host, RRDHOST_FLAG_RRDPUSH_SENDER_CONNECTED);
  1347. int pipe_buffer_size = 10 * 1024;
  1348. #ifdef F_GETPIPE_SZ
  1349. pipe_buffer_size = fcntl(s->rrdpush_sender_pipe[PIPE_READ], F_GETPIPE_SZ);
  1350. #endif
  1351. if(pipe_buffer_size < 10 * 1024)
  1352. pipe_buffer_size = 10 * 1024;
  1353. if(!rrdpush_sender_pipe_close(s->host, s->rrdpush_sender_pipe, true)) {
  1354. netdata_log_error("STREAM %s [send]: cannot create inter-thread communication pipe. Disabling streaming.",
  1355. rrdhost_hostname(s->host));
  1356. return NULL;
  1357. }
  1358. struct rrdpush_sender_thread_data *thread_data = callocz(1, sizeof(struct rrdpush_sender_thread_data));
  1359. thread_data->pipe_buffer = mallocz(pipe_buffer_size);
  1360. thread_data->host = s->host;
  1361. netdata_thread_cleanup_push(rrdpush_sender_thread_cleanup_callback, thread_data);
  1362. size_t iterations = 0;
  1363. time_t now_s = now_monotonic_sec();
  1364. while(!rrdhost_sender_should_exit(s)) {
  1365. iterations++;
  1366. // The connection attempt blocks (after which we use the socket in nonblocking)
  1367. if(unlikely(s->rrdpush_sender_socket == -1)) {
  1368. worker_is_busy(WORKER_SENDER_JOB_CONNECT);
  1369. now_s = now_monotonic_sec();
  1370. rrdpush_sender_cbuffer_recreate_timed(s, now_s, false, true);
  1371. rrdhost_flag_clear(s->host, RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  1372. s->flags &= ~SENDER_FLAG_OVERFLOW;
  1373. s->read_len = 0;
  1374. s->buffer->read = 0;
  1375. s->buffer->write = 0;
  1376. if(!attempt_to_connect(s))
  1377. continue;
  1378. if(rrdhost_sender_should_exit(s))
  1379. break;
  1380. now_s = s->last_traffic_seen_t = now_monotonic_sec();
  1381. rrdpush_send_claimed_id(s->host);
  1382. rrdpush_send_host_labels(s->host);
  1383. rrdpush_send_global_functions(s->host);
  1384. rrdpush_send_dyncfg(s->host);
  1385. s->replication.oldest_request_after_t = 0;
  1386. rrdhost_flag_set(s->host, RRDHOST_FLAG_RRDPUSH_SENDER_READY_4_METRICS);
  1387. nd_log(NDLS_DAEMON, NDLP_DEBUG,
  1388. "STREAM %s [send to %s]: enabling metrics streaming...",
  1389. rrdhost_hostname(s->host), s->connected_to);
  1390. continue;
  1391. }
  1392. if(iterations % 1000 == 0)
  1393. now_s = now_monotonic_sec();
  1394. // If the TCP window never opened then something is wrong, restart connection
  1395. if(unlikely(now_s - s->last_traffic_seen_t > s->timeout &&
  1396. !rrdpush_sender_pending_replication_requests(s) &&
  1397. !rrdpush_sender_replicating_charts(s)
  1398. )) {
  1399. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_TIMEOUT);
  1400. netdata_log_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);
  1401. rrdpush_sender_thread_close_socket(s->host);
  1402. continue;
  1403. }
  1404. sender_lock(s);
  1405. size_t outstanding = cbuffer_next_unsafe(s->buffer, NULL);
  1406. size_t available = cbuffer_available_size_unsafe(s->buffer);
  1407. if (unlikely(!outstanding)) {
  1408. rrdpush_sender_pipe_clear_pending_data(s);
  1409. rrdpush_sender_cbuffer_recreate_timed(s, now_s, true, false);
  1410. }
  1411. if(s->compressor.initialized) {
  1412. size_t bytes_uncompressed = s->compressor.sender_locked.total_uncompressed;
  1413. size_t bytes_compressed = s->compressor.sender_locked.total_compressed + s->compressor.sender_locked.total_compressions * sizeof(rrdpush_signature_t);
  1414. NETDATA_DOUBLE ratio = 100.0 - ((NETDATA_DOUBLE)bytes_compressed * 100.0 / (NETDATA_DOUBLE)bytes_uncompressed);
  1415. worker_set_metric(WORKER_SENDER_JOB_BYTES_UNCOMPRESSED, (NETDATA_DOUBLE)bytes_uncompressed);
  1416. worker_set_metric(WORKER_SENDER_JOB_BYTES_COMPRESSED, (NETDATA_DOUBLE)bytes_compressed);
  1417. worker_set_metric(WORKER_SENDER_JOB_BYTES_COMPRESSION_RATIO, ratio);
  1418. }
  1419. sender_unlock(s);
  1420. worker_set_metric(WORKER_SENDER_JOB_BUFFER_RATIO, (NETDATA_DOUBLE)(s->buffer->max_size - available) * 100.0 / (NETDATA_DOUBLE)s->buffer->max_size);
  1421. if(outstanding)
  1422. s->send_attempts++;
  1423. if(unlikely(s->rrdpush_sender_pipe[PIPE_READ] == -1)) {
  1424. if(!rrdpush_sender_pipe_close(s->host, s->rrdpush_sender_pipe, true)) {
  1425. netdata_log_error("STREAM %s [send]: cannot create inter-thread communication pipe. Disabling streaming.",
  1426. rrdhost_hostname(s->host));
  1427. rrdpush_sender_thread_close_socket(s->host);
  1428. break;
  1429. }
  1430. }
  1431. worker_is_idle();
  1432. // Wait until buffer opens in the socket or a rrdset_done_push wakes us
  1433. enum {
  1434. Collector = 0,
  1435. Socket = 1,
  1436. };
  1437. struct pollfd fds[2] = {
  1438. [Collector] = {
  1439. .fd = s->rrdpush_sender_pipe[PIPE_READ],
  1440. .events = POLLIN,
  1441. .revents = 0,
  1442. },
  1443. [Socket] = {
  1444. .fd = s->rrdpush_sender_socket,
  1445. .events = POLLIN | (outstanding ? POLLOUT : 0 ),
  1446. .revents = 0,
  1447. }
  1448. };
  1449. int poll_rc = poll(fds, 2, 50); // timeout in milliseconds
  1450. netdata_log_debug(D_STREAM, "STREAM: poll() finished collector=%d socket=%d (current chunk %zu bytes)...",
  1451. fds[Collector].revents, fds[Socket].revents, outstanding);
  1452. if(unlikely(rrdhost_sender_should_exit(s)))
  1453. break;
  1454. internal_error(fds[Collector].fd != s->rrdpush_sender_pipe[PIPE_READ],
  1455. "STREAM %s [send to %s]: pipe changed after poll().", rrdhost_hostname(s->host), s->connected_to);
  1456. internal_error(fds[Socket].fd != s->rrdpush_sender_socket,
  1457. "STREAM %s [send to %s]: socket changed after poll().", rrdhost_hostname(s->host), s->connected_to);
  1458. // Spurious wake-ups without error - loop again
  1459. if (poll_rc == 0 || ((poll_rc == -1) && (errno == EAGAIN || errno == EINTR))) {
  1460. netdata_thread_testcancel();
  1461. netdata_log_debug(D_STREAM, "Spurious wakeup");
  1462. now_s = now_monotonic_sec();
  1463. continue;
  1464. }
  1465. // Only errors from poll() are internal, but try restarting the connection
  1466. if(unlikely(poll_rc == -1)) {
  1467. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_POLL_ERROR);
  1468. netdata_log_error("STREAM %s [send to %s]: failed to poll(). Closing socket.", rrdhost_hostname(s->host), s->connected_to);
  1469. rrdpush_sender_pipe_close(s->host, s->rrdpush_sender_pipe, true);
  1470. rrdpush_sender_thread_close_socket(s->host);
  1471. continue;
  1472. }
  1473. // If we have data and have seen the TCP window open then try to close it by a transmission.
  1474. if(likely(outstanding && (fds[Socket].revents & POLLOUT))) {
  1475. worker_is_busy(WORKER_SENDER_JOB_SOCKET_SEND);
  1476. ssize_t bytes = attempt_to_send(s);
  1477. if(bytes > 0) {
  1478. s->last_traffic_seen_t = now_monotonic_sec();
  1479. worker_set_metric(WORKER_SENDER_JOB_BYTES_SENT, (NETDATA_DOUBLE)bytes);
  1480. }
  1481. }
  1482. // If the collector woke us up then empty the pipe to remove the signal
  1483. if (fds[Collector].revents & (POLLIN|POLLPRI)) {
  1484. worker_is_busy(WORKER_SENDER_JOB_PIPE_READ);
  1485. netdata_log_debug(D_STREAM, "STREAM: Data added to send buffer (current buffer chunk %zu bytes)...", outstanding);
  1486. if (read(fds[Collector].fd, thread_data->pipe_buffer, pipe_buffer_size) == -1)
  1487. netdata_log_error("STREAM %s [send to %s]: cannot read from internal pipe.", rrdhost_hostname(s->host), s->connected_to);
  1488. }
  1489. // Read as much as possible to fill the buffer, split into full lines for execution.
  1490. if (fds[Socket].revents & POLLIN) {
  1491. worker_is_busy(WORKER_SENDER_JOB_SOCKET_RECEIVE);
  1492. ssize_t bytes = attempt_read(s);
  1493. if(bytes > 0) {
  1494. s->last_traffic_seen_t = now_monotonic_sec();
  1495. worker_set_metric(WORKER_SENDER_JOB_BYTES_RECEIVED, (NETDATA_DOUBLE)bytes);
  1496. }
  1497. }
  1498. if(unlikely(s->read_len))
  1499. execute_commands(s);
  1500. if(unlikely(fds[Collector].revents & (POLLERR|POLLHUP|POLLNVAL))) {
  1501. char *error = NULL;
  1502. if (unlikely(fds[Collector].revents & POLLERR))
  1503. error = "pipe reports errors (POLLERR)";
  1504. else if (unlikely(fds[Collector].revents & POLLHUP))
  1505. error = "pipe closed (POLLHUP)";
  1506. else if (unlikely(fds[Collector].revents & POLLNVAL))
  1507. error = "pipe is invalid (POLLNVAL)";
  1508. if(error) {
  1509. rrdpush_sender_pipe_close(s->host, s->rrdpush_sender_pipe, true);
  1510. netdata_log_error("STREAM %s [send to %s]: restarting internal pipe: %s.",
  1511. rrdhost_hostname(s->host), s->connected_to, error);
  1512. }
  1513. }
  1514. if(unlikely(fds[Socket].revents & (POLLERR|POLLHUP|POLLNVAL))) {
  1515. char *error = NULL;
  1516. if (unlikely(fds[Socket].revents & POLLERR))
  1517. error = "socket reports errors (POLLERR)";
  1518. else if (unlikely(fds[Socket].revents & POLLHUP))
  1519. error = "connection closed by remote end (POLLHUP)";
  1520. else if (unlikely(fds[Socket].revents & POLLNVAL))
  1521. error = "connection is invalid (POLLNVAL)";
  1522. if(unlikely(error)) {
  1523. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_SOCKET_ERROR);
  1524. netdata_log_error("STREAM %s [send to %s]: restarting connection: %s - %zu bytes transmitted.",
  1525. rrdhost_hostname(s->host), s->connected_to, error, s->sent_bytes_on_this_connection);
  1526. rrdpush_sender_thread_close_socket(s->host);
  1527. }
  1528. }
  1529. // protection from overflow
  1530. if(unlikely(s->flags & SENDER_FLAG_OVERFLOW)) {
  1531. worker_is_busy(WORKER_SENDER_JOB_DISCONNECT_OVERFLOW);
  1532. errno = 0;
  1533. netdata_log_error("STREAM %s [send to %s]: buffer full (allocated %zu bytes) after sending %zu bytes. Restarting connection",
  1534. rrdhost_hostname(s->host), s->connected_to, s->buffer->size, s->sent_bytes_on_this_connection);
  1535. rrdpush_sender_thread_close_socket(s->host);
  1536. }
  1537. worker_set_metric(WORKER_SENDER_JOB_REPLAY_DICT_SIZE, (NETDATA_DOUBLE) dictionary_entries(s->replication.requests));
  1538. }
  1539. netdata_thread_cleanup_pop(1);
  1540. return NULL;
  1541. }