sender.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "rrdpush.h"
  3. extern struct config stream_config;
  4. extern int netdata_use_ssl_on_stream;
  5. extern char *netdata_ssl_ca_path;
  6. extern char *netdata_ssl_ca_file;
  7. // Collector thread starting a transmission
  8. void sender_start(struct sender_state *s) {
  9. netdata_mutex_lock(&s->mutex);
  10. buffer_flush(s->build);
  11. }
  12. static inline void rrdpush_sender_thread_close_socket(RRDHOST *host);
  13. #ifdef ENABLE_COMPRESSION
  14. /*
  15. * In case of stream compression buffer oveflow
  16. * Inform the user through the error log file and
  17. * deactivate compression by downgrading the stream protocol.
  18. */
  19. static inline void deactivate_compression(struct sender_state *s)
  20. {
  21. error("STREAM_COMPRESSION: Deactivating compression to avoid stream corruption");
  22. default_compression_enabled = 0;
  23. s->rrdpush_compression = 0;
  24. s->version = STREAM_VERSION_CLABELS;
  25. error("STREAM_COMPRESSION %s [send to %s]: Restarting connection without compression", s->host->hostname, s->connected_to);
  26. rrdpush_sender_thread_close_socket(s->host);
  27. }
  28. #endif
  29. // Collector thread finishing a transmission
  30. void sender_commit(struct sender_state *s) {
  31. char *src = (char *)buffer_tostring(s->host->sender->build);
  32. size_t src_len = s->host->sender->build->len;
  33. #ifdef ENABLE_COMPRESSION
  34. if (src && src_len) {
  35. if (s->compressor && s->rrdpush_compression) {
  36. src_len = s->compressor->compress(s->compressor, src, src_len, &src);
  37. if (!src_len) {
  38. deactivate_compression(s);
  39. buffer_flush(s->build);
  40. netdata_mutex_unlock(&s->mutex);
  41. return;
  42. }
  43. }
  44. if(cbuffer_add_unsafe(s->host->sender->buffer, src, src_len))
  45. s->overflow = 1;
  46. }
  47. #else
  48. if(cbuffer_add_unsafe(s->host->sender->buffer, src, src_len))
  49. s->overflow = 1;
  50. #endif
  51. buffer_flush(s->build);
  52. netdata_mutex_unlock(&s->mutex);
  53. }
  54. static inline void rrdpush_sender_thread_close_socket(RRDHOST *host) {
  55. host->rrdpush_sender_connected = 0;
  56. if(host->rrdpush_sender_socket != -1) {
  57. close(host->rrdpush_sender_socket);
  58. host->rrdpush_sender_socket = -1;
  59. }
  60. }
  61. static inline void rrdpush_sender_add_host_variable_to_buffer_nolock(RRDHOST *host, RRDVAR *rv) {
  62. calculated_number *value = (calculated_number *)rv->value;
  63. buffer_sprintf(
  64. host->sender->build
  65. , "VARIABLE HOST %s = " CALCULATED_NUMBER_FORMAT "\n"
  66. , rv->name
  67. , *value
  68. );
  69. debug(D_STREAM, "RRDVAR pushed HOST VARIABLE %s = " CALCULATED_NUMBER_FORMAT, rv->name, *value);
  70. }
  71. void rrdpush_sender_send_this_host_variable_now(RRDHOST *host, RRDVAR *rv) {
  72. if(host->rrdpush_send_enabled && host->rrdpush_sender_spawn && host->rrdpush_sender_connected) {
  73. sender_start(host->sender);
  74. rrdpush_sender_add_host_variable_to_buffer_nolock(host, rv);
  75. sender_commit(host->sender);
  76. }
  77. }
  78. static int rrdpush_sender_thread_custom_host_variables_callback(void *rrdvar_ptr, void *host_ptr) {
  79. RRDVAR *rv = (RRDVAR *)rrdvar_ptr;
  80. RRDHOST *host = (RRDHOST *)host_ptr;
  81. if(unlikely(rv->options & RRDVAR_OPTION_CUSTOM_HOST_VAR && rv->type == RRDVAR_TYPE_CALCULATED)) {
  82. rrdpush_sender_add_host_variable_to_buffer_nolock(host, rv);
  83. // return 1, so that the traversal will return the number of variables sent
  84. return 1;
  85. }
  86. // returning a negative number will break the traversal
  87. return 0;
  88. }
  89. static void rrdpush_sender_thread_send_custom_host_variables(RRDHOST *host) {
  90. sender_start(host->sender);
  91. int ret = rrdvar_callback_for_all_host_variables(host, rrdpush_sender_thread_custom_host_variables_callback, host);
  92. (void)ret;
  93. sender_commit(host->sender);
  94. debug(D_STREAM, "RRDVAR sent %d VARIABLES", ret);
  95. }
  96. // resets all the chart, so that their definitions
  97. // will be resent to the central netdata
  98. static void rrdpush_sender_thread_reset_all_charts(RRDHOST *host) {
  99. rrdhost_rdlock(host);
  100. RRDSET *st;
  101. rrdset_foreach_read(st, host) {
  102. rrdset_flag_clear(st, RRDSET_FLAG_UPSTREAM_EXPOSED);
  103. st->upstream_resync_time = 0;
  104. rrdset_rdlock(st);
  105. RRDDIM *rd;
  106. rrddim_foreach_read(rd, st)
  107. rd->exposed = 0;
  108. rrdset_unlock(st);
  109. }
  110. rrdhost_unlock(host);
  111. }
  112. static inline void rrdpush_sender_thread_data_flush(RRDHOST *host) {
  113. netdata_mutex_lock(&host->sender->mutex);
  114. size_t len = cbuffer_next_unsafe(host->sender->buffer, NULL);
  115. if (len)
  116. error("STREAM %s [send]: discarding %zu bytes of metrics already in the buffer.", host->hostname, len);
  117. cbuffer_remove_unsafe(host->sender->buffer, len);
  118. netdata_mutex_unlock(&host->sender->mutex);
  119. rrdpush_sender_thread_reset_all_charts(host);
  120. rrdpush_sender_thread_send_custom_host_variables(host);
  121. }
  122. static inline void rrdpush_set_flags_to_newest_stream(RRDHOST *host) {
  123. host->labels.labels_flag |= LABEL_FLAG_UPDATE_STREAM;
  124. host->labels.labels_flag &= ~LABEL_FLAG_STOP_STREAM;
  125. }
  126. void rrdpush_encode_variable(stream_encoded_t *se, RRDHOST *host)
  127. {
  128. se->os_name = (host->system_info->host_os_name)?url_encode(host->system_info->host_os_name):"";
  129. se->os_id = (host->system_info->host_os_id)?url_encode(host->system_info->host_os_id):"";
  130. se->os_version = (host->system_info->host_os_version)?url_encode(host->system_info->host_os_version):"";
  131. se->kernel_name = (host->system_info->kernel_name)?url_encode(host->system_info->kernel_name):"";
  132. se->kernel_version = (host->system_info->kernel_version)?url_encode(host->system_info->kernel_version):"";
  133. }
  134. void rrdpush_clean_encoded(stream_encoded_t *se)
  135. {
  136. if (se->os_name)
  137. freez(se->os_name);
  138. if (se->os_id)
  139. freez(se->os_id);
  140. if (se->os_version)
  141. freez(se->os_version);
  142. if (se->kernel_name)
  143. freez(se->kernel_name);
  144. if (se->kernel_version)
  145. freez(se->kernel_version);
  146. }
  147. static inline long int parse_stream_version(RRDHOST *host, char *http)
  148. {
  149. long int stream_version = -1;
  150. int answer = -1;
  151. char *stream_version_start = strchr(http, '=');
  152. if (stream_version_start) {
  153. stream_version_start++;
  154. stream_version = strtol(stream_version_start, NULL, 10);
  155. answer = memcmp(http, START_STREAMING_PROMPT_VN, (size_t)(stream_version_start - http));
  156. if (!answer) {
  157. rrdpush_set_flags_to_newest_stream(host);
  158. }
  159. } else {
  160. answer = memcmp(http, START_STREAMING_PROMPT_V2, strlen(START_STREAMING_PROMPT_V2));
  161. if (!answer) {
  162. stream_version = 1;
  163. rrdpush_set_flags_to_newest_stream(host);
  164. } else {
  165. answer = memcmp(http, START_STREAMING_PROMPT, strlen(START_STREAMING_PROMPT));
  166. if (!answer) {
  167. stream_version = 0;
  168. host->labels.labels_flag |= LABEL_FLAG_STOP_STREAM;
  169. host->labels.labels_flag &= ~LABEL_FLAG_UPDATE_STREAM;
  170. }
  171. }
  172. }
  173. return stream_version;
  174. }
  175. static int rrdpush_sender_thread_connect_to_parent(RRDHOST *host, int default_port, int timeout,
  176. struct sender_state *s) {
  177. struct timeval tv = {
  178. .tv_sec = timeout,
  179. .tv_usec = 0
  180. };
  181. // make sure the socket is closed
  182. rrdpush_sender_thread_close_socket(host);
  183. debug(D_STREAM, "STREAM: Attempting to connect...");
  184. info("STREAM %s [send to %s]: connecting...", host->hostname, host->rrdpush_send_destination);
  185. host->rrdpush_sender_socket = connect_to_one_of(
  186. host->rrdpush_send_destination
  187. , default_port
  188. , &tv
  189. , &s->reconnects_counter
  190. , s->connected_to
  191. , sizeof(s->connected_to)-1
  192. );
  193. if(unlikely(host->rrdpush_sender_socket == -1)) {
  194. error("STREAM %s [send to %s]: failed to connect", host->hostname, host->rrdpush_send_destination);
  195. return 0;
  196. }
  197. info("STREAM %s [send to %s]: initializing communication...", host->hostname, s->connected_to);
  198. #ifdef ENABLE_HTTPS
  199. if( netdata_client_ctx ){
  200. host->ssl.flags = NETDATA_SSL_START;
  201. if (!host->ssl.conn){
  202. host->ssl.conn = SSL_new(netdata_client_ctx);
  203. if(!host->ssl.conn){
  204. error("Failed to allocate SSL structure.");
  205. host->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  206. }
  207. }
  208. else{
  209. SSL_clear(host->ssl.conn);
  210. }
  211. if (host->ssl.conn)
  212. {
  213. if (SSL_set_fd(host->ssl.conn, host->rrdpush_sender_socket) != 1) {
  214. error("Failed to set the socket to the SSL on socket fd %d.", host->rrdpush_sender_socket);
  215. host->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  216. } else{
  217. host->ssl.flags = NETDATA_SSL_HANDSHAKE_COMPLETE;
  218. }
  219. }
  220. }
  221. else {
  222. host->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  223. }
  224. #endif
  225. #ifdef ENABLE_COMPRESSION
  226. // Negotiate stream VERSION_CLABELS if stream compression is not supported
  227. s->rrdpush_compression = (default_compression_enabled && (s->version >= STREAM_VERSION_COMPRESSION));
  228. if(!s->rrdpush_compression)
  229. s->version = STREAM_VERSION_CLABELS;
  230. #endif //ENABLE_COMPRESSION
  231. /* TODO: During the implementation of #7265 switch the set of variables to HOST_* and CONTAINER_* if the
  232. version negotiation resulted in a high enough version.
  233. */
  234. stream_encoded_t se;
  235. rrdpush_encode_variable(&se, host);
  236. char http[HTTP_HEADER_SIZE + 1];
  237. int eol = snprintfz(http, HTTP_HEADER_SIZE,
  238. "STREAM "
  239. "key=%s"
  240. "&hostname=%s"
  241. "&registry_hostname=%s"
  242. "&machine_guid=%s"
  243. "&update_every=%d"
  244. "&os=%s"
  245. "&timezone=%s"
  246. "&abbrev_timezone=%s"
  247. "&utc_offset=%d"
  248. "&hops=%d"
  249. "&ml_capable=%d"
  250. "&ml_enabled=%d"
  251. "&tags=%s"
  252. "&ver=%d"
  253. "&NETDATA_INSTANCE_CLOUD_TYPE=%s"
  254. "&NETDATA_INSTANCE_CLOUD_INSTANCE_TYPE=%s"
  255. "&NETDATA_INSTANCE_CLOUD_INSTANCE_REGION=%s"
  256. "&NETDATA_SYSTEM_OS_NAME=%s"
  257. "&NETDATA_SYSTEM_OS_ID=%s"
  258. "&NETDATA_SYSTEM_OS_ID_LIKE=%s"
  259. "&NETDATA_SYSTEM_OS_VERSION=%s"
  260. "&NETDATA_SYSTEM_OS_VERSION_ID=%s"
  261. "&NETDATA_SYSTEM_OS_DETECTION=%s"
  262. "&NETDATA_HOST_IS_K8S_NODE=%s"
  263. "&NETDATA_SYSTEM_KERNEL_NAME=%s"
  264. "&NETDATA_SYSTEM_KERNEL_VERSION=%s"
  265. "&NETDATA_SYSTEM_ARCHITECTURE=%s"
  266. "&NETDATA_SYSTEM_VIRTUALIZATION=%s"
  267. "&NETDATA_SYSTEM_VIRT_DETECTION=%s"
  268. "&NETDATA_SYSTEM_CONTAINER=%s"
  269. "&NETDATA_SYSTEM_CONTAINER_DETECTION=%s"
  270. "&NETDATA_CONTAINER_OS_NAME=%s"
  271. "&NETDATA_CONTAINER_OS_ID=%s"
  272. "&NETDATA_CONTAINER_OS_ID_LIKE=%s"
  273. "&NETDATA_CONTAINER_OS_VERSION=%s"
  274. "&NETDATA_CONTAINER_OS_VERSION_ID=%s"
  275. "&NETDATA_CONTAINER_OS_DETECTION=%s"
  276. "&NETDATA_SYSTEM_CPU_LOGICAL_CPU_COUNT=%s"
  277. "&NETDATA_SYSTEM_CPU_FREQ=%s"
  278. "&NETDATA_SYSTEM_TOTAL_RAM=%s"
  279. "&NETDATA_SYSTEM_TOTAL_DISK_SIZE=%s"
  280. "&NETDATA_PROTOCOL_VERSION=%s"
  281. " HTTP/1.1\r\n"
  282. "User-Agent: %s/%s\r\n"
  283. "Accept: */*\r\n\r\n"
  284. , host->rrdpush_send_api_key
  285. , host->hostname
  286. , host->registry_hostname
  287. , host->machine_guid
  288. , default_rrd_update_every
  289. , host->os
  290. , host->timezone
  291. , host->abbrev_timezone
  292. , host->utc_offset
  293. , host->system_info->hops + 1
  294. , host->system_info->ml_capable
  295. , host->system_info->ml_enabled
  296. , (host->tags) ? host->tags : ""
  297. , s->version
  298. , (host->system_info->cloud_provider_type) ? host->system_info->cloud_provider_type : ""
  299. , (host->system_info->cloud_instance_type) ? host->system_info->cloud_instance_type : ""
  300. , (host->system_info->cloud_instance_region) ? host->system_info->cloud_instance_region : ""
  301. , se.os_name
  302. , se.os_id
  303. , (host->system_info->host_os_id_like) ? host->system_info->host_os_id_like : ""
  304. , se.os_version
  305. , (host->system_info->host_os_version_id) ? host->system_info->host_os_version_id : ""
  306. , (host->system_info->host_os_detection) ? host->system_info->host_os_detection : ""
  307. , (host->system_info->is_k8s_node) ? host->system_info->is_k8s_node : ""
  308. , se.kernel_name
  309. , se.kernel_version
  310. , (host->system_info->architecture) ? host->system_info->architecture : ""
  311. , (host->system_info->virtualization) ? host->system_info->virtualization : ""
  312. , (host->system_info->virt_detection) ? host->system_info->virt_detection : ""
  313. , (host->system_info->container) ? host->system_info->container : ""
  314. , (host->system_info->container_detection) ? host->system_info->container_detection : ""
  315. , (host->system_info->container_os_name) ? host->system_info->container_os_name : ""
  316. , (host->system_info->container_os_id) ? host->system_info->container_os_id : ""
  317. , (host->system_info->container_os_id_like) ? host->system_info->container_os_id_like : ""
  318. , (host->system_info->container_os_version) ? host->system_info->container_os_version : ""
  319. , (host->system_info->container_os_version_id) ? host->system_info->container_os_version_id : ""
  320. , (host->system_info->container_os_detection) ? host->system_info->container_os_detection : ""
  321. , (host->system_info->host_cores) ? host->system_info->host_cores : ""
  322. , (host->system_info->host_cpu_freq) ? host->system_info->host_cpu_freq : ""
  323. , (host->system_info->host_ram_total) ? host->system_info->host_ram_total : ""
  324. , (host->system_info->host_disk_space) ? host->system_info->host_disk_space : ""
  325. , STREAMING_PROTOCOL_VERSION
  326. , host->program_name
  327. , host->program_version
  328. );
  329. http[eol] = 0x00;
  330. rrdpush_clean_encoded(&se);
  331. #ifdef ENABLE_HTTPS
  332. if (!host->ssl.flags) {
  333. ERR_clear_error();
  334. SSL_set_connect_state(host->ssl.conn);
  335. int err = SSL_connect(host->ssl.conn);
  336. if (err != 1){
  337. err = SSL_get_error(host->ssl.conn, err);
  338. error("SSL cannot connect with the server: %s ",ERR_error_string((long)SSL_get_error(host->ssl.conn,err),NULL));
  339. if (netdata_use_ssl_on_stream == NETDATA_SSL_FORCE) {
  340. rrdpush_sender_thread_close_socket(host);
  341. return 0;
  342. }else {
  343. host->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  344. }
  345. }
  346. else {
  347. if (netdata_use_ssl_on_stream == NETDATA_SSL_FORCE) {
  348. if (netdata_validate_server == NETDATA_SSL_VALID_CERTIFICATE) {
  349. if ( security_test_certificate(host->ssl.conn)) {
  350. error("Closing the stream connection, because the server SSL certificate is not valid.");
  351. rrdpush_sender_thread_close_socket(host);
  352. return 0;
  353. }
  354. }
  355. }
  356. }
  357. }
  358. if(send_timeout(&host->ssl,host->rrdpush_sender_socket, http, strlen(http), 0, timeout) == -1) {
  359. #else
  360. if(send_timeout(host->rrdpush_sender_socket, http, strlen(http), 0, timeout) == -1) {
  361. #endif
  362. error("STREAM %s [send to %s]: failed to send HTTP header to remote netdata.", host->hostname, s->connected_to);
  363. rrdpush_sender_thread_close_socket(host);
  364. return 0;
  365. }
  366. info("STREAM %s [send to %s]: waiting response from remote netdata...", host->hostname, s->connected_to);
  367. ssize_t received;
  368. #ifdef ENABLE_HTTPS
  369. received = recv_timeout(&host->ssl,host->rrdpush_sender_socket, http, HTTP_HEADER_SIZE, 0, timeout);
  370. if(received == -1) {
  371. #else
  372. received = recv_timeout(host->rrdpush_sender_socket, http, HTTP_HEADER_SIZE, 0, timeout);
  373. if(received == -1) {
  374. #endif
  375. error("STREAM %s [send to %s]: remote netdata does not respond.", host->hostname, s->connected_to);
  376. rrdpush_sender_thread_close_socket(host);
  377. return 0;
  378. }
  379. http[received] = '\0';
  380. debug(D_STREAM, "Response to sender from far end: %s", http);
  381. int32_t version = (int32_t)parse_stream_version(host, http);
  382. if(version == -1) {
  383. error("STREAM %s [send to %s]: server is not replying properly (is it a netdata?).", host->hostname, s->connected_to);
  384. rrdpush_sender_thread_close_socket(host);
  385. return 0;
  386. }
  387. s->version = version;
  388. #ifdef ENABLE_COMPRESSION
  389. s->rrdpush_compression = (s->rrdpush_compression && (s->version >= STREAM_VERSION_COMPRESSION));
  390. if(s->rrdpush_compression)
  391. {
  392. // parent supports compression
  393. if(s->compressor)
  394. s->compressor->reset(s->compressor);
  395. }
  396. else {
  397. //parent does not support compression or has compression disabled
  398. debug(D_STREAM, "Stream is uncompressed! One of the agents (%s <-> %s) does not support compression OR compression is disabled.", s->connected_to, s->host->hostname);
  399. infoerr("Stream is uncompressed! One of the agents (%s <-> %s) does not support compression OR compression is disabled.", s->connected_to, s->host->hostname);
  400. s->version = STREAM_VERSION_CLABELS;
  401. }
  402. #endif //ENABLE_COMPRESSION
  403. info("STREAM %s [send to %s]: established communication with a parent using protocol version %d - ready to send metrics..."
  404. , host->hostname
  405. , s->connected_to
  406. , s->version);
  407. if(sock_setnonblock(host->rrdpush_sender_socket) < 0)
  408. error("STREAM %s [send to %s]: cannot set non-blocking mode for socket.", host->hostname, s->connected_to);
  409. if(sock_enlarge_out(host->rrdpush_sender_socket) < 0)
  410. error("STREAM %s [send to %s]: cannot enlarge the socket buffer.", host->hostname, s->connected_to);
  411. debug(D_STREAM, "STREAM: Connected on fd %d...", host->rrdpush_sender_socket);
  412. return 1;
  413. }
  414. static void attempt_to_connect(struct sender_state *state)
  415. {
  416. state->send_attempts = 0;
  417. if(rrdpush_sender_thread_connect_to_parent(state->host, state->default_port, state->timeout, state)) {
  418. state->last_sent_t = now_monotonic_sec();
  419. // reset the buffer, to properly send charts and metrics
  420. rrdpush_sender_thread_data_flush(state->host);
  421. // send from the beginning
  422. state->begin = 0;
  423. // make sure the next reconnection will be immediate
  424. state->not_connected_loops = 0;
  425. // reset the bytes we have sent for this session
  426. state->sent_bytes_on_this_connection = 0;
  427. // let the data collection threads know we are ready
  428. state->host->rrdpush_sender_connected = 1;
  429. }
  430. else {
  431. // increase the failed connections counter
  432. state->not_connected_loops++;
  433. // reset the number of bytes sent
  434. state->sent_bytes_on_this_connection = 0;
  435. // slow re-connection on repeating errors
  436. sleep_usec(USEC_PER_SEC * state->reconnect_delay); // seconds
  437. }
  438. }
  439. // TCP window is open and we have data to transmit.
  440. void attempt_to_send(struct sender_state *s) {
  441. rrdpush_send_labels(s->host);
  442. #ifdef NETDATA_INTERNAL_CHECKS
  443. struct circular_buffer *cb = s->buffer;
  444. #endif
  445. netdata_thread_disable_cancelability();
  446. netdata_mutex_lock(&s->mutex);
  447. char *chunk;
  448. size_t outstanding = cbuffer_next_unsafe(s->buffer, &chunk);
  449. debug(D_STREAM, "STREAM: Sending data. Buffer r=%zu w=%zu s=%zu, next chunk=%zu", cb->read, cb->write, cb->size, outstanding);
  450. ssize_t ret;
  451. #ifdef ENABLE_HTTPS
  452. SSL *conn = s->host->ssl.conn ;
  453. if(conn && !s->host->ssl.flags) {
  454. ret = SSL_write(conn, chunk, outstanding);
  455. } else {
  456. ret = send(s->host->rrdpush_sender_socket, chunk, outstanding, MSG_DONTWAIT);
  457. }
  458. #else
  459. ret = send(s->host->rrdpush_sender_socket, chunk, outstanding, MSG_DONTWAIT);
  460. #endif
  461. if (likely(ret > 0)) {
  462. cbuffer_remove_unsafe(s->buffer, ret);
  463. s->sent_bytes_on_this_connection += ret;
  464. s->sent_bytes += ret;
  465. debug(D_STREAM, "STREAM %s [send to %s]: Sent %zd bytes", s->host->hostname, s->connected_to, ret);
  466. s->last_sent_t = now_monotonic_sec();
  467. }
  468. else if (ret == -1 && (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
  469. debug(D_STREAM, "STREAM %s [send to %s]: unavailable after polling POLLOUT", s->host->hostname,
  470. s->connected_to);
  471. else if (ret == -1) {
  472. debug(D_STREAM, "STREAM: Send failed - closing socket...");
  473. error("STREAM %s [send to %s]: failed to send metrics - closing connection - we have sent %zu bytes on this connection.", s->host->hostname, s->connected_to, s->sent_bytes_on_this_connection);
  474. rrdpush_sender_thread_close_socket(s->host);
  475. }
  476. else {
  477. debug(D_STREAM, "STREAM: send() returned 0 -> no error but no transmission");
  478. }
  479. netdata_mutex_unlock(&s->mutex);
  480. netdata_thread_enable_cancelability();
  481. }
  482. void attempt_read(struct sender_state *s) {
  483. int ret;
  484. #ifdef ENABLE_HTTPS
  485. if (s->host->ssl.conn && !s->host->stream_ssl.flags) {
  486. ERR_clear_error();
  487. int desired = sizeof(s->read_buffer) - s->read_len - 1;
  488. ret = SSL_read(s->host->ssl.conn, s->read_buffer, desired);
  489. if (ret > 0 ) {
  490. s->read_len += ret;
  491. return;
  492. }
  493. int sslerrno = SSL_get_error(s->host->ssl.conn, desired);
  494. if (sslerrno == SSL_ERROR_WANT_READ || sslerrno == SSL_ERROR_WANT_WRITE)
  495. return;
  496. u_long err;
  497. char buf[256];
  498. while ((err = ERR_get_error()) != 0) {
  499. ERR_error_string_n(err, buf, sizeof(buf));
  500. error("STREAM %s [send to %s] ssl error: %s", s->host->hostname, s->connected_to, buf);
  501. }
  502. error("Restarting connection");
  503. rrdpush_sender_thread_close_socket(s->host);
  504. return;
  505. }
  506. #endif
  507. ret = recv(s->host->rrdpush_sender_socket, s->read_buffer + s->read_len, sizeof(s->read_buffer) - s->read_len - 1,
  508. MSG_DONTWAIT);
  509. if (ret>0) {
  510. s->read_len += ret;
  511. return;
  512. }
  513. debug(D_STREAM, "Socket was POLLIN, but req %zu bytes gave %d", sizeof(s->read_buffer) - s->read_len - 1, ret);
  514. if (ret<0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
  515. return;
  516. if (ret==0)
  517. error("STREAM %s [send to %s]: connection closed by far end. Restarting connection", s->host->hostname, s->connected_to);
  518. else
  519. error("STREAM %s [send to %s]: error during read (%d). Restarting connection", s->host->hostname, s->connected_to,
  520. ret);
  521. rrdpush_sender_thread_close_socket(s->host);
  522. }
  523. // This is just a placeholder until the gap filling state machine is inserted
  524. void execute_commands(struct sender_state *s) {
  525. char *start = s->read_buffer, *end = &s->read_buffer[s->read_len], *newline;
  526. *end = 0;
  527. while( start<end && (newline=strchr(start, '\n')) ) {
  528. *newline = 0;
  529. info("STREAM %s [send to %s] received command over connection: %s", s->host->hostname, s->connected_to, start);
  530. start = newline+1;
  531. }
  532. if (start<end) {
  533. memmove(s->read_buffer, start, end-start);
  534. s->read_len = end-start;
  535. }
  536. }
  537. static void rrdpush_sender_thread_cleanup_callback(void *ptr) {
  538. RRDHOST *host = (RRDHOST *)ptr;
  539. netdata_mutex_lock(&host->sender->mutex);
  540. info("STREAM %s [send]: sending thread cleans up...", host->hostname);
  541. rrdpush_sender_thread_close_socket(host);
  542. // close the pipe
  543. if(host->rrdpush_sender_pipe[PIPE_READ] != -1) {
  544. close(host->rrdpush_sender_pipe[PIPE_READ]);
  545. host->rrdpush_sender_pipe[PIPE_READ] = -1;
  546. }
  547. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1) {
  548. close(host->rrdpush_sender_pipe[PIPE_WRITE]);
  549. host->rrdpush_sender_pipe[PIPE_WRITE] = -1;
  550. }
  551. if(!host->rrdpush_sender_join) {
  552. info("STREAM %s [send]: sending thread detaches itself.", host->hostname);
  553. netdata_thread_detach(netdata_thread_self());
  554. }
  555. host->rrdpush_sender_spawn = 0;
  556. info("STREAM %s [send]: sending thread now exits.", host->hostname);
  557. netdata_mutex_unlock(&host->sender->mutex);
  558. }
  559. void sender_init(struct sender_state *s, RRDHOST *parent) {
  560. memset(s, 0, sizeof(*s));
  561. s->host = parent;
  562. s->buffer = cbuffer_new(1024, 1024*1024);
  563. s->build = buffer_create(1);
  564. #ifdef ENABLE_COMPRESSION
  565. s->rrdpush_compression = default_compression_enabled;
  566. if (default_compression_enabled)
  567. s->compressor = create_compressor();
  568. #endif
  569. netdata_mutex_init(&s->mutex);
  570. }
  571. void *rrdpush_sender_thread(void *ptr) {
  572. struct sender_state *s = ptr;
  573. s->task_id = gettid();
  574. if(!s->host->rrdpush_send_enabled || !s->host->rrdpush_send_destination ||
  575. !*s->host->rrdpush_send_destination || !s->host->rrdpush_send_api_key ||
  576. !*s->host->rrdpush_send_api_key) {
  577. error("STREAM %s [send]: thread created (task id %d), but host has streaming disabled.",
  578. s->host->hostname, s->task_id);
  579. return NULL;
  580. }
  581. #ifdef ENABLE_HTTPS
  582. if (netdata_use_ssl_on_stream & NETDATA_SSL_FORCE ){
  583. security_start_ssl(NETDATA_SSL_CONTEXT_STREAMING);
  584. security_location_for_context(netdata_client_ctx, netdata_ssl_ca_file, netdata_ssl_ca_path);
  585. }
  586. #endif
  587. info("STREAM %s [send]: thread created (task id %d)", s->host->hostname, s->task_id);
  588. s->timeout = (int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "timeout seconds", 60);
  589. s->default_port = (int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "default port", 19999);
  590. s->buffer->max_size =
  591. (size_t)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "buffer size bytes", 1024 * 1024);
  592. s->reconnect_delay =
  593. (unsigned int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "reconnect delay seconds", 5);
  594. remote_clock_resync_iterations = (unsigned int)appconfig_get_number(
  595. &stream_config, CONFIG_SECTION_STREAM,
  596. "initial clock resync iterations",
  597. remote_clock_resync_iterations); // TODO: REMOVE FOR SLEW / GAPFILLING
  598. // initialize rrdpush globals
  599. s->host->rrdpush_sender_connected = 0;
  600. if(pipe(s->host->rrdpush_sender_pipe) == -1) {
  601. error("STREAM %s [send]: cannot create required pipe. DISABLING STREAMING THREAD", s->host->hostname);
  602. return NULL;
  603. }
  604. s->version = STREAMING_PROTOCOL_CURRENT_VERSION;
  605. enum {
  606. Collector,
  607. Socket
  608. };
  609. struct pollfd fds[2];
  610. fds[Collector].fd = s->host->rrdpush_sender_pipe[PIPE_READ];
  611. fds[Collector].events = POLLIN;
  612. netdata_thread_cleanup_push(rrdpush_sender_thread_cleanup_callback, s->host);
  613. for(; s->host->rrdpush_send_enabled && !netdata_exit ;) {
  614. // check for outstanding cancellation requests
  615. netdata_thread_testcancel();
  616. // The connection attempt blocks (after which we use the socket in nonblocking)
  617. if(unlikely(s->host->rrdpush_sender_socket == -1)) {
  618. s->overflow = 0;
  619. s->read_len = 0;
  620. s->buffer->read = 0;
  621. s->buffer->write = 0;
  622. attempt_to_connect(s);
  623. if (s->version >= VERSION_GAP_FILLING) {
  624. time_t now = now_realtime_sec();
  625. sender_start(s);
  626. buffer_sprintf(s->build, "TIMESTAMP %"PRId64"", (int64_t)now);
  627. sender_commit(s);
  628. }
  629. rrdpush_claimed_id(s->host);
  630. continue;
  631. }
  632. // If the TCP window never opened then something is wrong, restart connection
  633. if(unlikely(now_monotonic_sec() - s->last_sent_t > s->timeout)) {
  634. 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.", s->host->hostname, s->connected_to, s->timeout, s->sent_bytes_on_this_connection, s->send_attempts);
  635. rrdpush_sender_thread_close_socket(s->host);
  636. continue;
  637. }
  638. // Wait until buffer opens in the socket or a rrdset_done_push wakes us
  639. fds[Collector].revents = 0;
  640. fds[Socket].revents = 0;
  641. fds[Socket].fd = s->host->rrdpush_sender_socket;
  642. netdata_mutex_lock(&s->mutex);
  643. char *chunk;
  644. size_t outstanding = cbuffer_next_unsafe(s->host->sender->buffer, &chunk);
  645. chunk = NULL; // Do not cache pointer outside of region - could be invalidated
  646. netdata_mutex_unlock(&s->mutex);
  647. if(outstanding) {
  648. s->send_attempts++;
  649. fds[Socket].events = POLLIN | POLLOUT;
  650. }
  651. else {
  652. fds[Socket].events = POLLIN;
  653. }
  654. int retval = poll(fds, 2, 1000);
  655. debug(D_STREAM, "STREAM: poll() finished collector=%d socket=%d (current chunk %zu bytes)...",
  656. fds[Collector].revents, fds[Socket].revents, outstanding);
  657. if(unlikely(netdata_exit)) break;
  658. // Spurious wake-ups without error - loop again
  659. if (retval == 0 || ((retval == -1) && (errno == EAGAIN || errno == EINTR)))
  660. {
  661. debug(D_STREAM, "Spurious wakeup");
  662. continue;
  663. }
  664. // Only errors from poll() are internal, but try restarting the connection
  665. if(unlikely(retval == -1)) {
  666. error("STREAM %s [send to %s]: failed to poll(). Closing socket.", s->host->hostname, s->connected_to);
  667. rrdpush_sender_thread_close_socket(s->host);
  668. continue;
  669. }
  670. // If the collector woke us up then empty the pipe to remove the signal
  671. if (fds[Collector].revents & POLLIN || fds[Collector].revents & POLLPRI) {
  672. debug(D_STREAM, "STREAM: Data added to send buffer (current buffer chunk %zu bytes)...", outstanding);
  673. char buffer[1000 + 1];
  674. if (read(s->host->rrdpush_sender_pipe[PIPE_READ], buffer, 1000) == -1)
  675. error("STREAM %s [send to %s]: cannot read from internal pipe.", s->host->hostname, s->connected_to);
  676. }
  677. // Read as much as possible to fill the buffer, split into full lines for execution.
  678. if (fds[Socket].revents & POLLIN)
  679. attempt_read(s);
  680. execute_commands(s);
  681. // If we have data and have seen the TCP window open then try to close it by a transmission.
  682. if (outstanding && fds[Socket].revents & POLLOUT)
  683. attempt_to_send(s);
  684. // TODO-GAPS - why do we only check this on the socket, not the pipe?
  685. if (outstanding) {
  686. char *error = NULL;
  687. if (unlikely(fds[Socket].revents & POLLERR))
  688. error = "socket reports errors (POLLERR)";
  689. else if (unlikely(fds[Socket].revents & POLLHUP))
  690. error = "connection closed by remote end (POLLHUP)";
  691. else if (unlikely(fds[Socket].revents & POLLNVAL))
  692. error = "connection is invalid (POLLNVAL)";
  693. if(unlikely(error)) {
  694. error("STREAM %s [send to %s]: restart stream because %s - %zu bytes transmitted.", s->host->hostname,
  695. s->connected_to, error, s->sent_bytes_on_this_connection);
  696. rrdpush_sender_thread_close_socket(s->host);
  697. }
  698. }
  699. // protection from overflow
  700. if (s->overflow) {
  701. errno = 0;
  702. error("STREAM %s [send to %s]: buffer full (%zu-bytes) after %zu bytes. Restarting connection",
  703. s->host->hostname, s->connected_to, s->buffer->size, s->sent_bytes_on_this_connection);
  704. rrdpush_sender_thread_close_socket(s->host);
  705. }
  706. }
  707. netdata_thread_cleanup_pop(1);
  708. return NULL;
  709. }