sender.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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&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->tags) ? host->tags : ""
  207. , STREAMING_PROTOCOL_CURRENT_VERSION
  208. , se.os_name
  209. , se.os_id
  210. , (host->system_info->host_os_id_like) ? host->system_info->host_os_id_like : ""
  211. , se.os_version
  212. , (host->system_info->host_os_version_id) ? host->system_info->host_os_version_id : ""
  213. , (host->system_info->host_os_detection) ? host->system_info->host_os_detection : ""
  214. , (host->system_info->is_k8s_node) ? host->system_info->is_k8s_node : ""
  215. , se.kernel_name
  216. , se.kernel_version
  217. , (host->system_info->architecture) ? host->system_info->architecture : ""
  218. , (host->system_info->virtualization) ? host->system_info->virtualization : ""
  219. , (host->system_info->virt_detection) ? host->system_info->virt_detection : ""
  220. , (host->system_info->container) ? host->system_info->container : ""
  221. , (host->system_info->container_detection) ? host->system_info->container_detection : ""
  222. , (host->system_info->container_os_name) ? host->system_info->container_os_name : ""
  223. , (host->system_info->container_os_id) ? host->system_info->container_os_id : ""
  224. , (host->system_info->container_os_id_like) ? host->system_info->container_os_id_like : ""
  225. , (host->system_info->container_os_version) ? host->system_info->container_os_version : ""
  226. , (host->system_info->container_os_version_id) ? host->system_info->container_os_version_id : ""
  227. , (host->system_info->container_os_detection) ? host->system_info->container_os_detection : ""
  228. , (host->system_info->host_cores) ? host->system_info->host_cores : ""
  229. , (host->system_info->host_cpu_freq) ? host->system_info->host_cpu_freq : ""
  230. , (host->system_info->host_ram_total) ? host->system_info->host_ram_total : ""
  231. , (host->system_info->host_disk_space) ? host->system_info->host_disk_space : ""
  232. , STREAMING_PROTOCOL_VERSION
  233. , host->program_name
  234. , host->program_version
  235. );
  236. http[eol] = 0x00;
  237. rrdpush_clean_encoded(&se);
  238. #ifdef ENABLE_HTTPS
  239. if (!host->ssl.flags) {
  240. ERR_clear_error();
  241. SSL_set_connect_state(host->ssl.conn);
  242. int err = SSL_connect(host->ssl.conn);
  243. if (err != 1){
  244. err = SSL_get_error(host->ssl.conn, err);
  245. error("SSL cannot connect with the server: %s ",ERR_error_string((long)SSL_get_error(host->ssl.conn,err),NULL));
  246. if (netdata_use_ssl_on_stream == NETDATA_SSL_FORCE) {
  247. rrdpush_sender_thread_close_socket(host);
  248. return 0;
  249. }else {
  250. host->ssl.flags = NETDATA_SSL_NO_HANDSHAKE;
  251. }
  252. }
  253. else {
  254. if (netdata_use_ssl_on_stream == NETDATA_SSL_FORCE) {
  255. if (netdata_validate_server == NETDATA_SSL_VALID_CERTIFICATE) {
  256. if ( security_test_certificate(host->ssl.conn)) {
  257. error("Closing the stream connection, because the server SSL certificate is not valid.");
  258. rrdpush_sender_thread_close_socket(host);
  259. return 0;
  260. }
  261. }
  262. }
  263. }
  264. }
  265. if(send_timeout(&host->ssl,host->rrdpush_sender_socket, http, strlen(http), 0, timeout) == -1) {
  266. #else
  267. if(send_timeout(host->rrdpush_sender_socket, http, strlen(http), 0, timeout) == -1) {
  268. #endif
  269. error("STREAM %s [send to %s]: failed to send HTTP header to remote netdata.", host->hostname, s->connected_to);
  270. rrdpush_sender_thread_close_socket(host);
  271. return 0;
  272. }
  273. info("STREAM %s [send to %s]: waiting response from remote netdata...", host->hostname, s->connected_to);
  274. ssize_t received;
  275. #ifdef ENABLE_HTTPS
  276. received = recv_timeout(&host->ssl,host->rrdpush_sender_socket, http, HTTP_HEADER_SIZE, 0, timeout);
  277. if(received == -1) {
  278. #else
  279. received = recv_timeout(host->rrdpush_sender_socket, http, HTTP_HEADER_SIZE, 0, timeout);
  280. if(received == -1) {
  281. #endif
  282. error("STREAM %s [send to %s]: remote netdata does not respond.", host->hostname, s->connected_to);
  283. rrdpush_sender_thread_close_socket(host);
  284. return 0;
  285. }
  286. http[received] = '\0';
  287. debug(D_STREAM, "Response to sender from far end: %s", http);
  288. int answer = -1;
  289. char *version_start = strchr(http, '=');
  290. int32_t version = -1;
  291. if(version_start) {
  292. version_start++;
  293. version = (int32_t)strtol(version_start, NULL, 10);
  294. answer = memcmp(http, START_STREAMING_PROMPT_VN, (size_t)(version_start - http));
  295. if(!answer) {
  296. rrdpush_set_flags_to_newest_stream(host);
  297. }
  298. } else {
  299. answer = memcmp(http, START_STREAMING_PROMPT_V2, strlen(START_STREAMING_PROMPT_V2));
  300. if(!answer) {
  301. version = 1;
  302. rrdpush_set_flags_to_newest_stream(host);
  303. }
  304. else {
  305. answer = memcmp(http, START_STREAMING_PROMPT, strlen(START_STREAMING_PROMPT));
  306. if(!answer) {
  307. version = 0;
  308. host->labels.labels_flag |= LABEL_FLAG_STOP_STREAM;
  309. host->labels.labels_flag &= ~LABEL_FLAG_UPDATE_STREAM;
  310. }
  311. }
  312. }
  313. if(version == -1) {
  314. error("STREAM %s [send to %s]: server is not replying properly (is it a netdata?).", host->hostname, s->connected_to);
  315. rrdpush_sender_thread_close_socket(host);
  316. return 0;
  317. }
  318. s->version = version;
  319. info("STREAM %s [send to %s]: established communication with a parent using protocol version %d - ready to send metrics..."
  320. , host->hostname
  321. , s->connected_to
  322. , version);
  323. if(sock_setnonblock(host->rrdpush_sender_socket) < 0)
  324. error("STREAM %s [send to %s]: cannot set non-blocking mode for socket.", host->hostname, s->connected_to);
  325. if(sock_enlarge_out(host->rrdpush_sender_socket) < 0)
  326. error("STREAM %s [send to %s]: cannot enlarge the socket buffer.", host->hostname, s->connected_to);
  327. debug(D_STREAM, "STREAM: Connected on fd %d...", host->rrdpush_sender_socket);
  328. return 1;
  329. }
  330. static void attempt_to_connect(struct sender_state *state)
  331. {
  332. state->send_attempts = 0;
  333. if(rrdpush_sender_thread_connect_to_parent(state->host, state->default_port, state->timeout, state)) {
  334. state->last_sent_t = now_monotonic_sec();
  335. // reset the buffer, to properly send charts and metrics
  336. rrdpush_sender_thread_data_flush(state->host);
  337. // send from the beginning
  338. state->begin = 0;
  339. // make sure the next reconnection will be immediate
  340. state->not_connected_loops = 0;
  341. // reset the bytes we have sent for this session
  342. state->sent_bytes_on_this_connection = 0;
  343. // let the data collection threads know we are ready
  344. state->host->rrdpush_sender_connected = 1;
  345. }
  346. else {
  347. // increase the failed connections counter
  348. state->not_connected_loops++;
  349. // reset the number of bytes sent
  350. state->sent_bytes_on_this_connection = 0;
  351. // slow re-connection on repeating errors
  352. sleep_usec(USEC_PER_SEC * state->reconnect_delay); // seconds
  353. }
  354. }
  355. // TCP window is open and we have data to transmit.
  356. void attempt_to_send(struct sender_state *s) {
  357. rrdpush_send_labels(s->host);
  358. struct circular_buffer *cb = s->buffer;
  359. netdata_thread_disable_cancelability();
  360. netdata_mutex_lock(&s->mutex);
  361. char *chunk;
  362. size_t outstanding = cbuffer_next_unsafe(s->buffer, &chunk);
  363. debug(D_STREAM, "STREAM: Sending data. Buffer r=%zu w=%zu s=%zu, next chunk=%zu", cb->read, cb->write, cb->size, outstanding);
  364. ssize_t ret;
  365. #ifdef ENABLE_HTTPS
  366. SSL *conn = s->host->ssl.conn ;
  367. if(conn && !s->host->ssl.flags) {
  368. ret = SSL_write(conn, chunk, outstanding);
  369. } else {
  370. ret = send(s->host->rrdpush_sender_socket, chunk, outstanding, MSG_DONTWAIT);
  371. }
  372. #else
  373. ret = send(s->host->rrdpush_sender_socket, chunk, outstanding, MSG_DONTWAIT);
  374. #endif
  375. if (likely(ret > 0)) {
  376. cbuffer_remove_unsafe(s->buffer, ret);
  377. s->sent_bytes_on_this_connection += ret;
  378. s->sent_bytes += ret;
  379. debug(D_STREAM, "STREAM %s [send to %s]: Sent %zd bytes", s->host->hostname, s->connected_to, ret);
  380. s->last_sent_t = now_monotonic_sec();
  381. }
  382. else if (ret == -1 && (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
  383. debug(D_STREAM, "STREAM %s [send to %s]: unavailable after polling POLLOUT", s->host->hostname,
  384. s->connected_to);
  385. else if (ret == -1) {
  386. debug(D_STREAM, "STREAM: Send failed - closing socket...");
  387. 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);
  388. rrdpush_sender_thread_close_socket(s->host);
  389. }
  390. else {
  391. debug(D_STREAM, "STREAM: send() returned 0 -> no error but no transmission");
  392. }
  393. netdata_mutex_unlock(&s->mutex);
  394. netdata_thread_enable_cancelability();
  395. }
  396. void attempt_read(struct sender_state *s) {
  397. int ret;
  398. #ifdef ENABLE_HTTPS
  399. if (s->host->ssl.conn && !s->host->stream_ssl.flags) {
  400. ERR_clear_error();
  401. int desired = sizeof(s->read_buffer) - s->read_len - 1;
  402. ret = SSL_read(s->host->ssl.conn, s->read_buffer, desired);
  403. if (ret > 0 ) {
  404. s->read_len += ret;
  405. return;
  406. }
  407. int sslerrno = SSL_get_error(s->host->ssl.conn, desired);
  408. if (sslerrno == SSL_ERROR_WANT_READ || sslerrno == SSL_ERROR_WANT_WRITE)
  409. return;
  410. u_long err;
  411. char buf[256];
  412. while ((err = ERR_get_error()) != 0) {
  413. ERR_error_string_n(err, buf, sizeof(buf));
  414. error("STREAM %s [send to %s] ssl error: %s", s->host->hostname, s->connected_to, buf);
  415. }
  416. error("Restarting connection");
  417. rrdpush_sender_thread_close_socket(s->host);
  418. return;
  419. }
  420. #endif
  421. ret = recv(s->host->rrdpush_sender_socket, s->read_buffer + s->read_len, sizeof(s->read_buffer) - s->read_len - 1,
  422. MSG_DONTWAIT);
  423. if (ret>0) {
  424. s->read_len += ret;
  425. return;
  426. }
  427. debug(D_STREAM, "Socket was POLLIN, but req %zu bytes gave %d", sizeof(s->read_buffer) - s->read_len - 1, ret);
  428. if (ret<0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR))
  429. return;
  430. if (ret==0)
  431. error("STREAM %s [send to %s]: connection closed by far end. Restarting connection", s->host->hostname, s->connected_to);
  432. else
  433. error("STREAM %s [send to %s]: error during read (%d). Restarting connection", s->host->hostname, s->connected_to,
  434. ret);
  435. rrdpush_sender_thread_close_socket(s->host);
  436. }
  437. // This is just a placeholder until the gap filling state machine is inserted
  438. void execute_commands(struct sender_state *s) {
  439. char *start = s->read_buffer, *end = &s->read_buffer[s->read_len], *newline;
  440. *end = 0;
  441. while( start<end && (newline=strchr(start, '\n')) ) {
  442. *newline = 0;
  443. info("STREAM %s [send to %s] received command over connection: %s", s->host->hostname, s->connected_to, start);
  444. start = newline+1;
  445. }
  446. if (start<end) {
  447. memmove(s->read_buffer, start, end-start);
  448. s->read_len = end-start;
  449. }
  450. }
  451. static void rrdpush_sender_thread_cleanup_callback(void *ptr) {
  452. RRDHOST *host = (RRDHOST *)ptr;
  453. netdata_mutex_lock(&host->sender->mutex);
  454. info("STREAM %s [send]: sending thread cleans up...", host->hostname);
  455. rrdpush_sender_thread_close_socket(host);
  456. // close the pipe
  457. if(host->rrdpush_sender_pipe[PIPE_READ] != -1) {
  458. close(host->rrdpush_sender_pipe[PIPE_READ]);
  459. host->rrdpush_sender_pipe[PIPE_READ] = -1;
  460. }
  461. if(host->rrdpush_sender_pipe[PIPE_WRITE] != -1) {
  462. close(host->rrdpush_sender_pipe[PIPE_WRITE]);
  463. host->rrdpush_sender_pipe[PIPE_WRITE] = -1;
  464. }
  465. if(!host->rrdpush_sender_join) {
  466. info("STREAM %s [send]: sending thread detaches itself.", host->hostname);
  467. netdata_thread_detach(netdata_thread_self());
  468. }
  469. host->rrdpush_sender_spawn = 0;
  470. info("STREAM %s [send]: sending thread now exits.", host->hostname);
  471. netdata_mutex_unlock(&host->sender->mutex);
  472. }
  473. void sender_init(struct sender_state *s, RRDHOST *parent) {
  474. memset(s, 0, sizeof(*s));
  475. s->host = parent;
  476. s->buffer = cbuffer_new(1024, 1024*1024);
  477. s->build = buffer_create(1);
  478. netdata_mutex_init(&s->mutex);
  479. }
  480. void *rrdpush_sender_thread(void *ptr) {
  481. struct sender_state *s = ptr;
  482. s->task_id = gettid();
  483. if(!s->host->rrdpush_send_enabled || !s->host->rrdpush_send_destination ||
  484. !*s->host->rrdpush_send_destination || !s->host->rrdpush_send_api_key ||
  485. !*s->host->rrdpush_send_api_key) {
  486. error("STREAM %s [send]: thread created (task id %d), but host has streaming disabled.",
  487. s->host->hostname, s->task_id);
  488. return NULL;
  489. }
  490. #ifdef ENABLE_HTTPS
  491. if (netdata_use_ssl_on_stream & NETDATA_SSL_FORCE ){
  492. security_start_ssl(NETDATA_SSL_CONTEXT_STREAMING);
  493. security_location_for_context(netdata_client_ctx, netdata_ssl_ca_file, netdata_ssl_ca_path);
  494. }
  495. #endif
  496. info("STREAM %s [send]: thread created (task id %d)", s->host->hostname, s->task_id);
  497. s->timeout = (int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "timeout seconds", 60);
  498. s->default_port = (int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "default port", 19999);
  499. s->buffer->max_size =
  500. (size_t)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "buffer size bytes", 1024 * 1024);
  501. s->reconnect_delay =
  502. (unsigned int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "reconnect delay seconds", 5);
  503. remote_clock_resync_iterations = (unsigned int)appconfig_get_number(
  504. &stream_config, CONFIG_SECTION_STREAM,
  505. "initial clock resync iterations",
  506. remote_clock_resync_iterations); // TODO: REMOVE FOR SLEW / GAPFILLING
  507. // initialize rrdpush globals
  508. s->host->rrdpush_sender_connected = 0;
  509. if(pipe(s->host->rrdpush_sender_pipe) == -1) {
  510. error("STREAM %s [send]: cannot create required pipe. DISABLING STREAMING THREAD", s->host->hostname);
  511. return NULL;
  512. }
  513. enum {
  514. Collector,
  515. Socket
  516. };
  517. struct pollfd fds[2];
  518. fds[Collector].fd = s->host->rrdpush_sender_pipe[PIPE_READ];
  519. fds[Collector].events = POLLIN;
  520. netdata_thread_cleanup_push(rrdpush_sender_thread_cleanup_callback, s->host);
  521. for(; s->host->rrdpush_send_enabled && !netdata_exit ;) {
  522. // check for outstanding cancellation requests
  523. netdata_thread_testcancel();
  524. // The connection attempt blocks (after which we use the socket in nonblocking)
  525. if(unlikely(s->host->rrdpush_sender_socket == -1)) {
  526. s->overflow = 0;
  527. s->read_len = 0;
  528. s->buffer->read = 0;
  529. s->buffer->write = 0;
  530. attempt_to_connect(s);
  531. if (s->version >= VERSION_GAP_FILLING) {
  532. time_t now = now_realtime_sec();
  533. sender_start(s);
  534. buffer_sprintf(s->build, "TIMESTAMP %ld", now);
  535. sender_commit(s);
  536. }
  537. rrdpush_claimed_id(s->host);
  538. continue;
  539. }
  540. // If the TCP window never opened then something is wrong, restart connection
  541. if(unlikely(now_monotonic_sec() - s->last_sent_t > s->timeout)) {
  542. 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);
  543. rrdpush_sender_thread_close_socket(s->host);
  544. continue;
  545. }
  546. // Wait until buffer opens in the socket or a rrdset_done_push wakes us
  547. fds[Collector].revents = 0;
  548. fds[Socket].revents = 0;
  549. fds[Socket].fd = s->host->rrdpush_sender_socket;
  550. netdata_mutex_lock(&s->mutex);
  551. char *chunk;
  552. size_t outstanding = cbuffer_next_unsafe(s->host->sender->buffer, &chunk);
  553. chunk = NULL; // Do not cache pointer outside of region - could be invalidated
  554. netdata_mutex_unlock(&s->mutex);
  555. if(outstanding) {
  556. s->send_attempts++;
  557. fds[Socket].events = POLLIN | POLLOUT;
  558. }
  559. else {
  560. fds[Socket].events = POLLIN;
  561. }
  562. int retval = poll(fds, 2, 1000);
  563. debug(D_STREAM, "STREAM: poll() finished collector=%d socket=%d (current chunk %zu bytes)...",
  564. fds[Collector].revents, fds[Socket].revents, outstanding);
  565. if(unlikely(netdata_exit)) break;
  566. // Spurious wake-ups without error - loop again
  567. if (retval == 0 || ((retval == -1) && (errno == EAGAIN || errno == EINTR)))
  568. {
  569. debug(D_STREAM, "Spurious wakeup");
  570. continue;
  571. }
  572. // Only errors from poll() are internal, but try restarting the connection
  573. if(unlikely(retval == -1)) {
  574. error("STREAM %s [send to %s]: failed to poll(). Closing socket.", s->host->hostname, s->connected_to);
  575. rrdpush_sender_thread_close_socket(s->host);
  576. continue;
  577. }
  578. // If the collector woke us up then empty the pipe to remove the signal
  579. if (fds[Collector].revents & POLLIN || fds[Collector].revents & POLLPRI) {
  580. debug(D_STREAM, "STREAM: Data added to send buffer (current buffer chunk %zu bytes)...", outstanding);
  581. char buffer[1000 + 1];
  582. if (read(s->host->rrdpush_sender_pipe[PIPE_READ], buffer, 1000) == -1)
  583. error("STREAM %s [send to %s]: cannot read from internal pipe.", s->host->hostname, s->connected_to);
  584. }
  585. // Read as much as possible to fill the buffer, split into full lines for execution.
  586. if (fds[Socket].revents & POLLIN)
  587. attempt_read(s);
  588. execute_commands(s);
  589. // If we have data and have seen the TCP window open then try to close it by a transmission.
  590. if (outstanding && fds[Socket].revents & POLLOUT)
  591. attempt_to_send(s);
  592. // TODO-GAPS - why do we only check this on the socket, not the pipe?
  593. if (outstanding) {
  594. char *error = NULL;
  595. if (unlikely(fds[Socket].revents & POLLERR))
  596. error = "socket reports errors (POLLERR)";
  597. else if (unlikely(fds[Socket].revents & POLLHUP))
  598. error = "connection closed by remote end (POLLHUP)";
  599. else if (unlikely(fds[Socket].revents & POLLNVAL))
  600. error = "connection is invalid (POLLNVAL)";
  601. if(unlikely(error)) {
  602. error("STREAM %s [send to %s]: restart stream because %s - %zu bytes transmitted.", s->host->hostname,
  603. s->connected_to, error, s->sent_bytes_on_this_connection);
  604. rrdpush_sender_thread_close_socket(s->host);
  605. }
  606. }
  607. // protection from overflow
  608. if (s->overflow) {
  609. errno = 0;
  610. error("STREAM %s [send to %s]: buffer full (%zu-bytes) after %zu bytes. Restarting connection",
  611. s->host->hostname, s->connected_to, s->buffer->size, s->sent_bytes_on_this_connection);
  612. rrdpush_sender_thread_close_socket(s->host);
  613. }
  614. }
  615. netdata_thread_cleanup_pop(1);
  616. return NULL;
  617. }