receiver.c 32 KB

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