sender.c 28 KB

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