receiver.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "rrdpush.h"
  3. extern struct config stream_config;
  4. void receiver_state_free(struct receiver_state *rpt) {
  5. freez(rpt->key);
  6. freez(rpt->hostname);
  7. freez(rpt->registry_hostname);
  8. freez(rpt->machine_guid);
  9. freez(rpt->os);
  10. freez(rpt->timezone);
  11. freez(rpt->abbrev_timezone);
  12. freez(rpt->tags);
  13. freez(rpt->client_ip);
  14. freez(rpt->client_port);
  15. freez(rpt->program_name);
  16. freez(rpt->program_version);
  17. #ifdef ENABLE_HTTPS
  18. netdata_ssl_close(&rpt->ssl);
  19. #endif
  20. if(rpt->fd != -1) {
  21. internal_error(true, "closing socket...");
  22. close(rpt->fd);
  23. }
  24. #ifdef ENABLE_RRDPUSH_COMPRESSION
  25. rrdpush_decompressor_destroy(&rpt->decompressor);
  26. #endif
  27. if(rpt->system_info)
  28. rrdhost_system_info_free(rpt->system_info);
  29. __atomic_sub_fetch(&netdata_buffers_statistics.rrdhost_receivers, sizeof(*rpt), __ATOMIC_RELAXED);
  30. freez(rpt);
  31. }
  32. #include "collectors/plugins.d/pluginsd_parser.h"
  33. // IMPORTANT: to add workers, you have to edit WORKER_PARSER_FIRST_JOB accordingly
  34. #define WORKER_RECEIVER_JOB_BYTES_READ (WORKER_PARSER_FIRST_JOB - 1)
  35. #define WORKER_RECEIVER_JOB_BYTES_UNCOMPRESSED (WORKER_PARSER_FIRST_JOB - 2)
  36. // this has to be the same at parser.h
  37. #define WORKER_RECEIVER_JOB_REPLICATION_COMPLETION (WORKER_PARSER_FIRST_JOB - 3)
  38. #if WORKER_PARSER_FIRST_JOB < 1
  39. #error The define WORKER_PARSER_FIRST_JOB needs to be at least 1
  40. #endif
  41. static inline int read_stream(struct receiver_state *r, char* buffer, size_t size) {
  42. if(unlikely(!size)) {
  43. internal_error(true, "%s() asked to read zero bytes", __FUNCTION__);
  44. return 0;
  45. }
  46. int tries = 100;
  47. ssize_t bytes_read;
  48. do {
  49. errno = 0;
  50. #ifdef ENABLE_HTTPS
  51. if (SSL_connection(&r->ssl))
  52. bytes_read = netdata_ssl_read(&r->ssl, buffer, size);
  53. else
  54. bytes_read = read(r->fd, buffer, size);
  55. #else
  56. bytes_read = read(r->fd, buffer, size);
  57. #endif
  58. } while(bytes_read < 0 && errno == EINTR && tries--);
  59. if((bytes_read == 0 || bytes_read == -1) && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINPROGRESS)) {
  60. netdata_log_error("STREAM: %s(): timeout while waiting for data on socket!", __FUNCTION__);
  61. bytes_read = -3;
  62. }
  63. else if (bytes_read == 0) {
  64. netdata_log_error("STREAM: %s(): EOF while reading data from socket!", __FUNCTION__);
  65. bytes_read = -1;
  66. }
  67. else if (bytes_read < 0) {
  68. netdata_log_error("STREAM: %s() failed to read from socket!", __FUNCTION__);
  69. bytes_read = -2;
  70. }
  71. return (int)bytes_read;
  72. }
  73. static inline bool receiver_read_uncompressed(struct receiver_state *r) {
  74. #ifdef NETDATA_INTERNAL_CHECKS
  75. if(r->reader.read_buffer[r->reader.read_len] != '\0')
  76. fatal("%s(): read_buffer does not start with zero", __FUNCTION__ );
  77. #endif
  78. int bytes_read = read_stream(r, r->reader.read_buffer + r->reader.read_len, sizeof(r->reader.read_buffer) - r->reader.read_len - 1);
  79. if(unlikely(bytes_read <= 0))
  80. return false;
  81. worker_set_metric(WORKER_RECEIVER_JOB_BYTES_READ, (NETDATA_DOUBLE)bytes_read);
  82. worker_set_metric(WORKER_RECEIVER_JOB_BYTES_UNCOMPRESSED, (NETDATA_DOUBLE)bytes_read);
  83. r->reader.read_len += bytes_read;
  84. r->reader.read_buffer[r->reader.read_len] = '\0';
  85. return true;
  86. }
  87. #ifdef ENABLE_RRDPUSH_COMPRESSION
  88. static inline bool receiver_read_compressed(struct receiver_state *r) {
  89. internal_fatal(r->reader.read_buffer[r->reader.read_len] != '\0',
  90. "%s: read_buffer does not start with zero #2", __FUNCTION__ );
  91. // first use any available uncompressed data
  92. if (likely(rrdpush_decompressed_bytes_in_buffer(&r->decompressor))) {
  93. size_t available = sizeof(r->reader.read_buffer) - r->reader.read_len - 1;
  94. if (likely(available)) {
  95. size_t len = rrdpush_decompressor_get(&r->decompressor, r->reader.read_buffer + r->reader.read_len, available);
  96. if (unlikely(!len)) {
  97. internal_error(true, "decompressor returned zero length #1");
  98. return false;
  99. }
  100. r->reader.read_len += (int)len;
  101. r->reader.read_buffer[r->reader.read_len] = '\0';
  102. }
  103. else
  104. internal_fatal(true, "The line to read is too big! Already have %zd bytes in read_buffer.", r->reader.read_len);
  105. return true;
  106. }
  107. // no decompressed data available
  108. // read the compression signature of the next block
  109. if(unlikely(r->reader.read_len + r->decompressor.signature_size > sizeof(r->reader.read_buffer) - 1)) {
  110. internal_error(true, "The last incomplete line does not leave enough room for the next compression header! "
  111. "Already have %zd bytes in read_buffer.", r->reader.read_len);
  112. return false;
  113. }
  114. // read the compression signature from the stream
  115. // we have to do a loop here, because read_stream() may return less than the data we need
  116. int bytes_read = 0;
  117. do {
  118. int ret = read_stream(r, r->reader.read_buffer + r->reader.read_len + bytes_read, r->decompressor.signature_size - bytes_read);
  119. if (unlikely(ret <= 0))
  120. return false;
  121. bytes_read += ret;
  122. } while(unlikely(bytes_read < (int)r->decompressor.signature_size));
  123. worker_set_metric(WORKER_RECEIVER_JOB_BYTES_READ, (NETDATA_DOUBLE)bytes_read);
  124. if(unlikely(bytes_read != (int)r->decompressor.signature_size))
  125. fatal("read %d bytes, but expected compression signature of size %zu", bytes_read, r->decompressor.signature_size);
  126. size_t compressed_message_size = rrdpush_decompressor_start(&r->decompressor, r->reader.read_buffer + r->reader.read_len, bytes_read);
  127. if (unlikely(!compressed_message_size)) {
  128. internal_error(true, "multiplexed uncompressed data in compressed stream!");
  129. r->reader.read_len += bytes_read;
  130. r->reader.read_buffer[r->reader.read_len] = '\0';
  131. return true;
  132. }
  133. if(unlikely(compressed_message_size > COMPRESSION_MAX_MSG_SIZE)) {
  134. netdata_log_error("received a compressed message of %zu bytes, which is bigger than the max compressed message size supported of %zu. Ignoring message.",
  135. compressed_message_size, (size_t)COMPRESSION_MAX_MSG_SIZE);
  136. return false;
  137. }
  138. // delete compression header from our read buffer
  139. r->reader.read_buffer[r->reader.read_len] = '\0';
  140. // Read the entire compressed block of compressed data
  141. char compressed[compressed_message_size];
  142. size_t compressed_bytes_read = 0;
  143. do {
  144. size_t start = compressed_bytes_read;
  145. size_t remaining = compressed_message_size - start;
  146. int last_read_bytes = read_stream(r, &compressed[start], remaining);
  147. if (unlikely(last_read_bytes <= 0)) {
  148. internal_error(true, "read_stream() failed #2, with code %d", last_read_bytes);
  149. return false;
  150. }
  151. compressed_bytes_read += last_read_bytes;
  152. } while(unlikely(compressed_message_size > compressed_bytes_read));
  153. worker_set_metric(WORKER_RECEIVER_JOB_BYTES_READ, (NETDATA_DOUBLE)compressed_bytes_read);
  154. // decompress the compressed block
  155. size_t bytes_to_parse = rrdpush_decompress(&r->decompressor, compressed, compressed_bytes_read);
  156. if (unlikely(!bytes_to_parse)) {
  157. internal_error(true, "no bytes to parse.");
  158. return false;
  159. }
  160. worker_set_metric(WORKER_RECEIVER_JOB_BYTES_UNCOMPRESSED, (NETDATA_DOUBLE)bytes_to_parse);
  161. // fill read buffer with decompressed data
  162. size_t len = (int) rrdpush_decompressor_get(&r->decompressor, r->reader.read_buffer + r->reader.read_len, sizeof(r->reader.read_buffer) - r->reader.read_len - 1);
  163. if (unlikely(!len)) {
  164. internal_error(true, "decompressor returned zero length #2");
  165. return false;
  166. }
  167. r->reader.read_len += (int)len;
  168. r->reader.read_buffer[r->reader.read_len] = '\0';
  169. return true;
  170. }
  171. #else // !ENABLE_RRDPUSH_COMPRESSION
  172. static inline bool receiver_read_compressed(struct receiver_state *r) {
  173. return receiver_read_uncompressed(r);
  174. }
  175. #endif // ENABLE_RRDPUSH_COMPRESSION
  176. /* Produce a full line if one exists, statefully return where we start next time.
  177. * When we hit the end of the buffer with a partial line move it to the beginning for the next fill.
  178. */
  179. inline bool buffered_reader_next_line(struct buffered_reader *reader, BUFFER *dst) {
  180. buffer_need_bytes(dst, reader->read_len - reader->pos + 2);
  181. size_t start = reader->pos;
  182. char *ss = &reader->read_buffer[start];
  183. char *se = &reader->read_buffer[reader->read_len];
  184. char *ds = &dst->buffer[dst->len];
  185. char *de = &ds[dst->size - dst->len - 2];
  186. if(ss >= se) {
  187. *ds = '\0';
  188. reader->pos = 0;
  189. reader->read_len = 0;
  190. reader->read_buffer[reader->read_len] = '\0';
  191. return false;
  192. }
  193. // copy all bytes to buffer
  194. while(ss < se && ds < de && *ss != '\n') {
  195. *ds++ = *ss++;
  196. dst->len++;
  197. }
  198. // if we have a newline, return the buffer
  199. if(ss < se && ds < de && *ss == '\n') {
  200. // newline found in the r->read_buffer
  201. *ds++ = *ss++; // copy the newline too
  202. dst->len++;
  203. *ds = '\0';
  204. reader->pos = ss - reader->read_buffer;
  205. return true;
  206. }
  207. reader->pos = 0;
  208. reader->read_len = 0;
  209. reader->read_buffer[reader->read_len] = '\0';
  210. return false;
  211. }
  212. bool plugin_is_enabled(struct plugind *cd);
  213. static void receiver_set_exit_reason(struct receiver_state *rpt, STREAM_HANDSHAKE reason, bool force) {
  214. if(force || !rpt->exit.reason)
  215. rpt->exit.reason = reason;
  216. }
  217. static inline bool receiver_should_stop(struct receiver_state *rpt) {
  218. static __thread size_t counter = 0;
  219. if(unlikely(rpt->exit.shutdown)) {
  220. receiver_set_exit_reason(rpt, STREAM_HANDSHAKE_DISCONNECT_SHUTDOWN, false);
  221. return true;
  222. }
  223. if(unlikely(!service_running(SERVICE_STREAMING))) {
  224. receiver_set_exit_reason(rpt, STREAM_HANDSHAKE_DISCONNECT_NETDATA_EXIT, false);
  225. return true;
  226. }
  227. if(unlikely((counter++ % 1000) == 0)) {
  228. // check every 1000 lines read
  229. netdata_thread_testcancel();
  230. rpt->last_msg_t = now_monotonic_sec();
  231. }
  232. return false;
  233. }
  234. static size_t streaming_parser(struct receiver_state *rpt, struct plugind *cd, int fd, void *ssl) {
  235. size_t result = 0;
  236. PARSER *parser = NULL;
  237. {
  238. PARSER_USER_OBJECT user = {
  239. .enabled = plugin_is_enabled(cd),
  240. .host = rpt->host,
  241. .opaque = rpt,
  242. .cd = cd,
  243. .trust_durations = 1,
  244. .capabilities = rpt->capabilities,
  245. };
  246. parser = parser_init(&user, NULL, NULL, fd, PARSER_INPUT_SPLIT, ssl);
  247. }
  248. pluginsd_keywords_init(parser, PARSER_INIT_STREAMING);
  249. rrd_collector_started();
  250. // this keeps the parser with its current value
  251. // so, parser needs to be allocated before pushing it
  252. netdata_thread_cleanup_push(pluginsd_process_thread_cleanup, parser);
  253. bool compressed_connection = false;
  254. #ifdef ENABLE_RRDPUSH_COMPRESSION
  255. if(stream_has_capability(rpt, STREAM_CAP_COMPRESSION)) {
  256. compressed_connection = true;
  257. rrdpush_decompressor_reset(&rpt->decompressor);
  258. }
  259. else
  260. rrdpush_decompressor_destroy(&rpt->decompressor);
  261. #endif
  262. buffered_reader_init(&rpt->reader);
  263. BUFFER *buffer = buffer_create(sizeof(rpt->reader.read_buffer), NULL);
  264. while(!receiver_should_stop(rpt)) {
  265. if(!buffered_reader_next_line(&rpt->reader, buffer)) {
  266. bool have_new_data = compressed_connection ? receiver_read_compressed(rpt) : receiver_read_uncompressed(rpt);
  267. if(unlikely(!have_new_data)) {
  268. receiver_set_exit_reason(rpt, STREAM_HANDSHAKE_DISCONNECT_SOCKET_READ_ERROR, false);
  269. break;
  270. }
  271. continue;
  272. }
  273. if (unlikely(parser_action(parser, buffer->buffer))) {
  274. receiver_set_exit_reason(rpt, STREAM_HANDSHAKE_DISCONNECT_PARSER_FAILED, false);
  275. break;
  276. }
  277. buffer->len = 0;
  278. buffer->buffer[0] = '\0';
  279. }
  280. buffer_free(buffer);
  281. result = parser->user.data_collections_count;
  282. // free parser with the pop function
  283. netdata_thread_cleanup_pop(1);
  284. return result;
  285. }
  286. static void rrdpush_receiver_replication_reset(RRDHOST *host) {
  287. RRDSET *st;
  288. rrdset_foreach_read(st, host) {
  289. rrdset_flag_clear(st, RRDSET_FLAG_RECEIVER_REPLICATION_IN_PROGRESS);
  290. rrdset_flag_set(st, RRDSET_FLAG_RECEIVER_REPLICATION_FINISHED);
  291. }
  292. rrdset_foreach_done(st);
  293. rrdhost_receiver_replicating_charts_zero(host);
  294. }
  295. static bool rrdhost_set_receiver(RRDHOST *host, struct receiver_state *rpt) {
  296. bool signal_rrdcontext = false;
  297. bool set_this = false;
  298. netdata_mutex_lock(&host->receiver_lock);
  299. if (!host->receiver) {
  300. rrdhost_flag_clear(host, RRDHOST_FLAG_ORPHAN);
  301. host->rrdpush_receiver_connection_counter++;
  302. __atomic_add_fetch(&localhost->connected_children_count, 1, __ATOMIC_RELAXED);
  303. host->receiver = rpt;
  304. rpt->host = host;
  305. host->child_connect_time = now_realtime_sec();
  306. host->child_disconnected_time = 0;
  307. host->child_last_chart_command = 0;
  308. host->trigger_chart_obsoletion_check = 1;
  309. if (rpt->config.health_enabled != CONFIG_BOOLEAN_NO) {
  310. if (rpt->config.alarms_delay > 0) {
  311. host->health.health_delay_up_to = now_realtime_sec() + rpt->config.alarms_delay;
  312. netdata_log_health(
  313. "[%s]: Postponing health checks for %" PRId64 " seconds, because it was just connected.",
  314. rrdhost_hostname(host),
  315. (int64_t) rpt->config.alarms_delay);
  316. }
  317. }
  318. host->health_log.health_log_history = rpt->config.alarms_history;
  319. // this is a test
  320. // if(rpt->hops <= host->sender->hops)
  321. // rrdpush_sender_thread_stop(host, "HOPS MISMATCH", false);
  322. signal_rrdcontext = true;
  323. rrdpush_receiver_replication_reset(host);
  324. rrdhost_flag_clear(rpt->host, RRDHOST_FLAG_RRDPUSH_RECEIVER_DISCONNECTED);
  325. aclk_queue_node_info(rpt->host, true);
  326. rrdpush_reset_destinations_postpone_time(host);
  327. set_this = true;
  328. }
  329. netdata_mutex_unlock(&host->receiver_lock);
  330. if(signal_rrdcontext)
  331. rrdcontext_host_child_connected(host);
  332. return set_this;
  333. }
  334. static void rrdhost_clear_receiver(struct receiver_state *rpt) {
  335. bool signal_rrdcontext = false;
  336. RRDHOST *host = rpt->host;
  337. if(host) {
  338. netdata_mutex_lock(&host->receiver_lock);
  339. // Make sure that we detach this thread and don't kill a freshly arriving receiver
  340. if(host->receiver == rpt) {
  341. __atomic_sub_fetch(&localhost->connected_children_count, 1, __ATOMIC_RELAXED);
  342. rrdhost_flag_set(rpt->host, RRDHOST_FLAG_RRDPUSH_RECEIVER_DISCONNECTED);
  343. host->trigger_chart_obsoletion_check = 0;
  344. host->child_connect_time = 0;
  345. host->child_disconnected_time = now_realtime_sec();
  346. if (rpt->config.health_enabled == CONFIG_BOOLEAN_AUTO)
  347. host->health.health_enabled = 0;
  348. rrdpush_sender_thread_stop(host, STREAM_HANDSHAKE_DISCONNECT_RECEIVER_LEFT, false);
  349. signal_rrdcontext = true;
  350. rrdpush_receiver_replication_reset(host);
  351. rrdhost_flag_set(host, RRDHOST_FLAG_ORPHAN);
  352. host->receiver = NULL;
  353. host->rrdpush_last_receiver_exit_reason = rpt->exit.reason;
  354. }
  355. netdata_mutex_unlock(&host->receiver_lock);
  356. if(signal_rrdcontext)
  357. rrdcontext_host_child_disconnected(host);
  358. rrdpush_reset_destinations_postpone_time(host);
  359. }
  360. }
  361. bool stop_streaming_receiver(RRDHOST *host, STREAM_HANDSHAKE reason) {
  362. bool ret = false;
  363. netdata_mutex_lock(&host->receiver_lock);
  364. if(host->receiver) {
  365. if(!host->receiver->exit.shutdown) {
  366. host->receiver->exit.shutdown = true;
  367. receiver_set_exit_reason(host->receiver, reason, true);
  368. shutdown(host->receiver->fd, SHUT_RDWR);
  369. }
  370. netdata_thread_cancel(host->receiver->thread);
  371. }
  372. int count = 2000;
  373. while (host->receiver && count-- > 0) {
  374. netdata_mutex_unlock(&host->receiver_lock);
  375. // let the lock for the receiver thread to exit
  376. sleep_usec(1 * USEC_PER_MS);
  377. netdata_mutex_lock(&host->receiver_lock);
  378. }
  379. if(host->receiver)
  380. netdata_log_error("STREAM '%s' [receive from [%s]:%s]: "
  381. "thread %d takes too long to stop, giving up..."
  382. , rrdhost_hostname(host)
  383. , host->receiver->client_ip, host->receiver->client_port
  384. , host->receiver->tid);
  385. else
  386. ret = true;
  387. netdata_mutex_unlock(&host->receiver_lock);
  388. return ret;
  389. }
  390. static void rrdpush_send_error_on_taken_over_connection(struct receiver_state *rpt, const char *msg) {
  391. (void) send_timeout(
  392. #ifdef ENABLE_HTTPS
  393. &rpt->ssl,
  394. #endif
  395. rpt->fd,
  396. (char *)msg,
  397. strlen(msg),
  398. 0,
  399. 5);
  400. }
  401. void rrdpush_receive_log_status(struct receiver_state *rpt, const char *msg, const char *status) {
  402. log_stream_connection(rpt->client_ip, rpt->client_port,
  403. (rpt->key && *rpt->key)? rpt->key : "-",
  404. (rpt->machine_guid && *rpt->machine_guid) ? rpt->machine_guid : "-",
  405. (rpt->hostname && *rpt->hostname) ? rpt->hostname : "-",
  406. status);
  407. netdata_log_info("STREAM '%s' [receive from [%s]:%s]: "
  408. "%s. "
  409. "STATUS: %s%s%s%s"
  410. , rpt->hostname
  411. , rpt->client_ip, rpt->client_port
  412. , msg
  413. , status
  414. , rpt->exit.reason != STREAM_HANDSHAKE_NEVER?" (":""
  415. , stream_handshake_error_to_string(rpt->exit.reason)
  416. , rpt->exit.reason != STREAM_HANDSHAKE_NEVER?")":""
  417. );
  418. }
  419. static void rrdpush_receive(struct receiver_state *rpt)
  420. {
  421. rpt->config.mode = default_rrd_memory_mode;
  422. rpt->config.history = default_rrd_history_entries;
  423. rpt->config.health_enabled = (int)default_health_enabled;
  424. rpt->config.alarms_delay = 60;
  425. rpt->config.alarms_history = HEALTH_LOG_DEFAULT_HISTORY;
  426. rpt->config.rrdpush_enabled = (int)default_rrdpush_enabled;
  427. rpt->config.rrdpush_destination = default_rrdpush_destination;
  428. rpt->config.rrdpush_api_key = default_rrdpush_api_key;
  429. rpt->config.rrdpush_send_charts_matching = default_rrdpush_send_charts_matching;
  430. rpt->config.rrdpush_enable_replication = default_rrdpush_enable_replication;
  431. rpt->config.rrdpush_seconds_to_replicate = default_rrdpush_seconds_to_replicate;
  432. rpt->config.rrdpush_replication_step = default_rrdpush_replication_step;
  433. rpt->config.update_every = (int)appconfig_get_number(&stream_config, rpt->machine_guid, "update every", rpt->config.update_every);
  434. if(rpt->config.update_every < 0) rpt->config.update_every = 1;
  435. rpt->config.history = (int)appconfig_get_number(&stream_config, rpt->key, "default history", rpt->config.history);
  436. rpt->config.history = (int)appconfig_get_number(&stream_config, rpt->machine_guid, "history", rpt->config.history);
  437. if(rpt->config.history < 5) rpt->config.history = 5;
  438. rpt->config.mode = rrd_memory_mode_id(appconfig_get(&stream_config, rpt->key, "default memory mode", rrd_memory_mode_name(rpt->config.mode)));
  439. rpt->config.mode = rrd_memory_mode_id(appconfig_get(&stream_config, rpt->machine_guid, "memory mode", rrd_memory_mode_name(rpt->config.mode)));
  440. if (unlikely(rpt->config.mode == RRD_MEMORY_MODE_DBENGINE && !dbengine_enabled)) {
  441. netdata_log_error("STREAM '%s' [receive from %s:%s]: "
  442. "dbengine is not enabled, falling back to default."
  443. , rpt->hostname
  444. , rpt->client_ip, rpt->client_port
  445. );
  446. rpt->config.mode = default_rrd_memory_mode;
  447. }
  448. rpt->config.health_enabled = appconfig_get_boolean_ondemand(&stream_config, rpt->key, "health enabled by default", rpt->config.health_enabled);
  449. rpt->config.health_enabled = appconfig_get_boolean_ondemand(&stream_config, rpt->machine_guid, "health enabled", rpt->config.health_enabled);
  450. rpt->config.alarms_delay = appconfig_get_number(&stream_config, rpt->key, "default postpone alarms on connect seconds", rpt->config.alarms_delay);
  451. rpt->config.alarms_delay = appconfig_get_number(&stream_config, rpt->machine_guid, "postpone alarms on connect seconds", rpt->config.alarms_delay);
  452. rpt->config.alarms_history = appconfig_get_number(&stream_config, rpt->key, "default health log history", rpt->config.alarms_history);
  453. rpt->config.alarms_history = appconfig_get_number(&stream_config, rpt->machine_guid, "health log history", rpt->config.alarms_history);
  454. rpt->config.rrdpush_enabled = appconfig_get_boolean(&stream_config, rpt->key, "default proxy enabled", rpt->config.rrdpush_enabled);
  455. rpt->config.rrdpush_enabled = appconfig_get_boolean(&stream_config, rpt->machine_guid, "proxy enabled", rpt->config.rrdpush_enabled);
  456. rpt->config.rrdpush_destination = appconfig_get(&stream_config, rpt->key, "default proxy destination", rpt->config.rrdpush_destination);
  457. rpt->config.rrdpush_destination = appconfig_get(&stream_config, rpt->machine_guid, "proxy destination", rpt->config.rrdpush_destination);
  458. rpt->config.rrdpush_api_key = appconfig_get(&stream_config, rpt->key, "default proxy api key", rpt->config.rrdpush_api_key);
  459. rpt->config.rrdpush_api_key = appconfig_get(&stream_config, rpt->machine_guid, "proxy api key", rpt->config.rrdpush_api_key);
  460. rpt->config.rrdpush_send_charts_matching = appconfig_get(&stream_config, rpt->key, "default proxy send charts matching", rpt->config.rrdpush_send_charts_matching);
  461. rpt->config.rrdpush_send_charts_matching = appconfig_get(&stream_config, rpt->machine_guid, "proxy send charts matching", rpt->config.rrdpush_send_charts_matching);
  462. rpt->config.rrdpush_enable_replication = appconfig_get_boolean(&stream_config, rpt->key, "enable replication", rpt->config.rrdpush_enable_replication);
  463. rpt->config.rrdpush_enable_replication = appconfig_get_boolean(&stream_config, rpt->machine_guid, "enable replication", rpt->config.rrdpush_enable_replication);
  464. rpt->config.rrdpush_seconds_to_replicate = appconfig_get_number(&stream_config, rpt->key, "seconds to replicate", rpt->config.rrdpush_seconds_to_replicate);
  465. rpt->config.rrdpush_seconds_to_replicate = appconfig_get_number(&stream_config, rpt->machine_guid, "seconds to replicate", rpt->config.rrdpush_seconds_to_replicate);
  466. rpt->config.rrdpush_replication_step = appconfig_get_number(&stream_config, rpt->key, "seconds per replication step", rpt->config.rrdpush_replication_step);
  467. rpt->config.rrdpush_replication_step = appconfig_get_number(&stream_config, rpt->machine_guid, "seconds per replication step", rpt->config.rrdpush_replication_step);
  468. #ifdef ENABLE_RRDPUSH_COMPRESSION
  469. rpt->config.rrdpush_compression = default_rrdpush_compression_enabled;
  470. rpt->config.rrdpush_compression = appconfig_get_boolean(&stream_config, rpt->key, "enable compression", rpt->config.rrdpush_compression);
  471. rpt->config.rrdpush_compression = appconfig_get_boolean(&stream_config, rpt->machine_guid, "enable compression", rpt->config.rrdpush_compression);
  472. #endif // ENABLE_RRDPUSH_COMPRESSION
  473. (void)appconfig_set_default(&stream_config, rpt->machine_guid, "host tags", (rpt->tags)?rpt->tags:"");
  474. // find the host for this receiver
  475. {
  476. // this will also update the host with our system_info
  477. RRDHOST *host = rrdhost_find_or_create(
  478. rpt->hostname
  479. , rpt->registry_hostname
  480. , rpt->machine_guid
  481. , rpt->os
  482. , rpt->timezone
  483. , rpt->abbrev_timezone
  484. , rpt->utc_offset
  485. , rpt->tags
  486. , rpt->program_name
  487. , rpt->program_version
  488. , rpt->config.update_every
  489. , rpt->config.history
  490. , rpt->config.mode
  491. , (unsigned int)(rpt->config.health_enabled != CONFIG_BOOLEAN_NO)
  492. , (unsigned int)(rpt->config.rrdpush_enabled && rpt->config.rrdpush_destination && *rpt->config.rrdpush_destination && rpt->config.rrdpush_api_key && *rpt->config.rrdpush_api_key)
  493. , rpt->config.rrdpush_destination
  494. , rpt->config.rrdpush_api_key
  495. , rpt->config.rrdpush_send_charts_matching
  496. , rpt->config.rrdpush_enable_replication
  497. , rpt->config.rrdpush_seconds_to_replicate
  498. , rpt->config.rrdpush_replication_step
  499. , rpt->system_info
  500. , 0
  501. );
  502. if(!host) {
  503. rrdpush_receive_log_status(rpt, "failed to find/create host structure", "INTERNAL ERROR DROPPING CONNECTION");
  504. rrdpush_send_error_on_taken_over_connection(rpt, START_STREAMING_ERROR_INTERNAL_ERROR);
  505. goto cleanup;
  506. }
  507. if (unlikely(rrdhost_flag_check(host, RRDHOST_FLAG_PENDING_CONTEXT_LOAD))) {
  508. rrdpush_receive_log_status(rpt, "host is initializing", "INITIALIZATION IN PROGRESS RETRY LATER");
  509. rrdpush_send_error_on_taken_over_connection(rpt, START_STREAMING_ERROR_INITIALIZATION);
  510. goto cleanup;
  511. }
  512. // system_info has been consumed by the host structure
  513. rpt->system_info = NULL;
  514. if(!rrdhost_set_receiver(host, rpt)) {
  515. rrdpush_receive_log_status(rpt, "host is already served by another receiver", "DUPLICATE RECEIVER DROPPING CONNECTION");
  516. rrdpush_send_error_on_taken_over_connection(rpt, START_STREAMING_ERROR_ALREADY_STREAMING);
  517. goto cleanup;
  518. }
  519. }
  520. #ifdef NETDATA_INTERNAL_CHECKS
  521. netdata_log_info("STREAM '%s' [receive from [%s]:%s]: "
  522. "client willing to stream metrics for host '%s' with machine_guid '%s': "
  523. "update every = %d, history = %d, memory mode = %s, health %s,%s tags '%s'"
  524. , rpt->hostname
  525. , rpt->client_ip
  526. , rpt->client_port
  527. , rrdhost_hostname(rpt->host)
  528. , rpt->host->machine_guid
  529. , rpt->host->rrd_update_every
  530. , rpt->host->rrd_history_entries
  531. , rrd_memory_mode_name(rpt->host->rrd_memory_mode)
  532. , (rpt->config.health_enabled == CONFIG_BOOLEAN_NO)?"disabled":((rpt->config.health_enabled == CONFIG_BOOLEAN_YES)?"enabled":"auto")
  533. #ifdef ENABLE_HTTPS
  534. , (rpt->ssl.conn != NULL) ? " SSL," : ""
  535. #else
  536. , ""
  537. #endif
  538. , rrdhost_tags(rpt->host)
  539. );
  540. #endif // NETDATA_INTERNAL_CHECKS
  541. struct plugind cd = {
  542. .update_every = default_rrd_update_every,
  543. .unsafe = {
  544. .spinlock = NETDATA_SPINLOCK_INITIALIZER,
  545. .running = true,
  546. .enabled = true,
  547. },
  548. .started_t = now_realtime_sec(),
  549. };
  550. // put the client IP and port into the buffers used by plugins.d
  551. snprintfz(cd.id, CONFIG_MAX_NAME, "%s:%s", rpt->client_ip, rpt->client_port);
  552. snprintfz(cd.filename, FILENAME_MAX, "%s:%s", rpt->client_ip, rpt->client_port);
  553. snprintfz(cd.fullfilename, FILENAME_MAX, "%s:%s", rpt->client_ip, rpt->client_port);
  554. snprintfz(cd.cmd, PLUGINSD_CMD_MAX, "%s:%s", rpt->client_ip, rpt->client_port);
  555. #ifdef ENABLE_RRDPUSH_COMPRESSION
  556. if (stream_has_capability(rpt, STREAM_CAP_COMPRESSION)) {
  557. if (!rpt->config.rrdpush_compression)
  558. rpt->capabilities &= ~STREAM_CAP_COMPRESSION;
  559. }
  560. #endif // ENABLE_RRDPUSH_COMPRESSION
  561. {
  562. // netdata_log_info("STREAM %s [receive from [%s]:%s]: initializing communication...", rrdhost_hostname(rpt->host), rpt->client_ip, rpt->client_port);
  563. char initial_response[HTTP_HEADER_SIZE];
  564. if (stream_has_capability(rpt, STREAM_CAP_VCAPS)) {
  565. log_receiver_capabilities(rpt);
  566. sprintf(initial_response, "%s%u", START_STREAMING_PROMPT_VN, rpt->capabilities);
  567. }
  568. else if (stream_has_capability(rpt, STREAM_CAP_VN)) {
  569. log_receiver_capabilities(rpt);
  570. sprintf(initial_response, "%s%d", START_STREAMING_PROMPT_VN, stream_capabilities_to_vn(rpt->capabilities));
  571. }
  572. else if (stream_has_capability(rpt, STREAM_CAP_V2)) {
  573. log_receiver_capabilities(rpt);
  574. sprintf(initial_response, "%s", START_STREAMING_PROMPT_V2);
  575. }
  576. else { // stream_has_capability(rpt, STREAM_CAP_V1)
  577. log_receiver_capabilities(rpt);
  578. sprintf(initial_response, "%s", START_STREAMING_PROMPT_V1);
  579. }
  580. netdata_log_debug(D_STREAM, "Initial response to %s: %s", rpt->client_ip, initial_response);
  581. ssize_t bytes_sent = send_timeout(
  582. #ifdef ENABLE_HTTPS
  583. &rpt->ssl,
  584. #endif
  585. rpt->fd, initial_response, strlen(initial_response), 0, 60);
  586. if(bytes_sent != (ssize_t)strlen(initial_response)) {
  587. internal_error(true, "Cannot send response, got %zd bytes, expecting %zu bytes", bytes_sent, strlen(initial_response));
  588. rrdpush_receive_log_status(rpt, "cannot reply back", "CANT REPLY DROPPING CONNECTION");
  589. goto cleanup;
  590. }
  591. }
  592. {
  593. // remove the non-blocking flag from the socket
  594. if(sock_delnonblock(rpt->fd) < 0)
  595. netdata_log_error("STREAM '%s' [receive from [%s]:%s]: "
  596. "cannot remove the non-blocking flag from socket %d"
  597. , rrdhost_hostname(rpt->host)
  598. , rpt->client_ip, rpt->client_port
  599. , rpt->fd);
  600. struct timeval timeout;
  601. timeout.tv_sec = 600;
  602. timeout.tv_usec = 0;
  603. if (unlikely(setsockopt(rpt->fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout) != 0))
  604. netdata_log_error("STREAM '%s' [receive from [%s]:%s]: "
  605. "cannot set timeout for socket %d"
  606. , rrdhost_hostname(rpt->host)
  607. , rpt->client_ip, rpt->client_port
  608. , rpt->fd);
  609. }
  610. rrdpush_receive_log_status(rpt, "ready to receive data", "CONNECTED");
  611. #ifdef ENABLE_ACLK
  612. // in case we have cloud connection we inform cloud
  613. // new child connected
  614. if (netdata_cloud_enabled)
  615. aclk_host_state_update(rpt->host, 1);
  616. #endif
  617. rrdhost_set_is_parent_label();
  618. // let it reconnect to parent immediately
  619. rrdpush_reset_destinations_postpone_time(rpt->host);
  620. size_t count = streaming_parser(rpt, &cd, rpt->fd,
  621. #ifdef ENABLE_HTTPS
  622. (rpt->ssl.conn) ? &rpt->ssl : NULL
  623. #else
  624. NULL
  625. #endif
  626. );
  627. receiver_set_exit_reason(rpt, STREAM_HANDSHAKE_DISCONNECT_PARSER_EXIT, false);
  628. {
  629. char msg[100 + 1];
  630. snprintfz(msg, 100, "disconnected (completed %zu updates)", count);
  631. rrdpush_receive_log_status(rpt, msg, "DISCONNECTED");
  632. }
  633. #ifdef ENABLE_ACLK
  634. // in case we have cloud connection we inform cloud
  635. // a child disconnected
  636. if (netdata_cloud_enabled)
  637. aclk_host_state_update(rpt->host, 0);
  638. #endif
  639. cleanup:
  640. ;
  641. }
  642. static void rrdpush_receiver_thread_cleanup(void *ptr) {
  643. struct receiver_state *rpt = (struct receiver_state *) ptr;
  644. worker_unregister();
  645. rrdhost_clear_receiver(rpt);
  646. netdata_log_info("STREAM '%s' [receive from [%s]:%s]: "
  647. "receive thread ended (task id %d)"
  648. , rpt->hostname ? rpt->hostname : "-"
  649. , rpt->client_ip ? rpt->client_ip : "-", rpt->client_port ? rpt->client_port : "-"
  650. , gettid());
  651. receiver_state_free(rpt);
  652. rrdhost_set_is_parent_label();
  653. }
  654. void *rrdpush_receiver_thread(void *ptr) {
  655. netdata_thread_cleanup_push(rrdpush_receiver_thread_cleanup, ptr);
  656. worker_register("STREAMRCV");
  657. worker_register_job_custom_metric(WORKER_RECEIVER_JOB_BYTES_READ, "received bytes", "bytes/s", WORKER_METRIC_INCREMENT);
  658. worker_register_job_custom_metric(WORKER_RECEIVER_JOB_BYTES_UNCOMPRESSED, "uncompressed bytes", "bytes/s", WORKER_METRIC_INCREMENT);
  659. worker_register_job_custom_metric(WORKER_RECEIVER_JOB_REPLICATION_COMPLETION, "replication completion", "%", WORKER_METRIC_ABSOLUTE);
  660. struct receiver_state *rpt = (struct receiver_state *)ptr;
  661. rpt->tid = gettid();
  662. netdata_log_info("STREAM %s [%s]:%s: receive thread created (task id %d)", rpt->hostname, rpt->client_ip, rpt->client_port, rpt->tid);
  663. rrdpush_receive(rpt);
  664. netdata_thread_cleanup_pop(1);
  665. return NULL;
  666. }