sender.c 57 KB

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