receiver.c 35 KB

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