aclk.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "aclk.h"
  3. #include "aclk_stats.h"
  4. #include "mqtt_wss_client.h"
  5. #include "aclk_otp.h"
  6. #include "aclk_tx_msgs.h"
  7. #include "aclk_query.h"
  8. #include "aclk_query_queue.h"
  9. #include "aclk_util.h"
  10. #include "aclk_rx_msgs.h"
  11. #include "https_client.h"
  12. #include "schema-wrappers/schema_wrappers.h"
  13. #include "aclk_proxy.h"
  14. #ifdef ACLK_LOG_CONVERSATION_DIR
  15. #include <sys/types.h>
  16. #include <sys/stat.h>
  17. #include <fcntl.h>
  18. #endif
  19. #define ACLK_STABLE_TIMEOUT 3 // Minimum delay to mark AGENT as stable
  20. int aclk_pubacks_per_conn = 0; // How many PubAcks we got since MQTT conn est.
  21. int aclk_rcvd_cloud_msgs = 0;
  22. int aclk_connection_counter = 0;
  23. int disconnect_req = 0;
  24. time_t last_conn_time_mqtt = 0;
  25. time_t last_conn_time_appl = 0;
  26. time_t last_disconnect_time = 0;
  27. time_t next_connection_attempt = 0;
  28. float last_backoff_value = 0;
  29. int aclk_alert_reloaded = 0; //1 on health log exchange, and again on health_reload
  30. time_t aclk_block_until = 0;
  31. mqtt_wss_client mqttwss_client;
  32. netdata_mutex_t aclk_shared_state_mutex = NETDATA_MUTEX_INITIALIZER;
  33. #define ACLK_SHARED_STATE_LOCK netdata_mutex_lock(&aclk_shared_state_mutex)
  34. #define ACLK_SHARED_STATE_UNLOCK netdata_mutex_unlock(&aclk_shared_state_mutex)
  35. struct aclk_shared_state aclk_shared_state = {
  36. .mqtt_shutdown_msg_id = -1,
  37. .mqtt_shutdown_msg_rcvd = 0
  38. };
  39. #if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_300
  40. OSSL_DECODER_CTX *aclk_dctx = NULL;
  41. EVP_PKEY *aclk_private_key = NULL;
  42. #else
  43. static RSA *aclk_private_key = NULL;
  44. #endif
  45. static int load_private_key()
  46. {
  47. if (aclk_private_key != NULL) {
  48. #if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_300
  49. EVP_PKEY_free(aclk_private_key);
  50. if (aclk_dctx)
  51. OSSL_DECODER_CTX_free(aclk_dctx);
  52. aclk_dctx = NULL;
  53. #else
  54. RSA_free(aclk_private_key);
  55. #endif
  56. }
  57. aclk_private_key = NULL;
  58. char filename[FILENAME_MAX + 1];
  59. snprintfz(filename, FILENAME_MAX, "%s/cloud.d/private.pem", netdata_configured_varlib_dir);
  60. long bytes_read;
  61. char *private_key = read_by_filename(filename, &bytes_read);
  62. if (!private_key) {
  63. error("Claimed agent cannot establish ACLK - unable to load private key '%s' failed.", filename);
  64. return 1;
  65. }
  66. debug(D_ACLK, "Claimed agent loaded private key len=%ld bytes", bytes_read);
  67. BIO *key_bio = BIO_new_mem_buf(private_key, -1);
  68. if (key_bio==NULL) {
  69. error("Claimed agent cannot establish ACLK - failed to create BIO for key");
  70. goto biofailed;
  71. }
  72. #if OPENSSL_VERSION_NUMBER >= OPENSSL_VERSION_300
  73. aclk_dctx = OSSL_DECODER_CTX_new_for_pkey(&aclk_private_key, "PEM", NULL,
  74. "RSA",
  75. OSSL_KEYMGMT_SELECT_PRIVATE_KEY,
  76. NULL, NULL);
  77. if (!aclk_dctx) {
  78. error("Loading private key (from claiming) failed - no OpenSSL Decoders found");
  79. goto biofailed;
  80. }
  81. // this is necesseary to avoid RSA key with wrong size
  82. if (!OSSL_DECODER_from_bio(aclk_dctx, key_bio)) {
  83. error("Decoding private key (from claiming) failed - invalid format.");
  84. goto biofailed;
  85. }
  86. #else
  87. aclk_private_key = PEM_read_bio_RSAPrivateKey(key_bio, NULL, NULL, NULL);
  88. #endif
  89. BIO_free(key_bio);
  90. if (aclk_private_key!=NULL)
  91. {
  92. freez(private_key);
  93. return 0;
  94. }
  95. char err[512];
  96. ERR_error_string_n(ERR_get_error(), err, sizeof(err));
  97. error("Claimed agent cannot establish ACLK - cannot create private key: %s", err);
  98. biofailed:
  99. freez(private_key);
  100. return 1;
  101. }
  102. static int wait_till_cloud_enabled()
  103. {
  104. info("Waiting for Cloud to be enabled");
  105. while (!netdata_cloud_setting) {
  106. sleep_usec(USEC_PER_SEC * 1);
  107. if (netdata_exit)
  108. return 1;
  109. }
  110. return 0;
  111. }
  112. /**
  113. * Will block until agent is claimed. Returns only if agent claimed
  114. * or if agent needs to shutdown.
  115. *
  116. * @return `0` if agent has been claimed,
  117. * `1` if interrupted due to agent shutting down
  118. */
  119. static int wait_till_agent_claimed(void)
  120. {
  121. //TODO prevent malloc and freez
  122. char *agent_id = get_agent_claimid();
  123. while (likely(!agent_id)) {
  124. sleep_usec(USEC_PER_SEC * 1);
  125. if (netdata_exit)
  126. return 1;
  127. agent_id = get_agent_claimid();
  128. }
  129. freez(agent_id);
  130. return 0;
  131. }
  132. /**
  133. * Checks everything is ready for connection
  134. * agent claimed, cloud url set and private key available
  135. *
  136. * @param aclk_hostname points to location where string pointer to hostname will be set
  137. * @param aclk_port port to int where port will be saved
  138. *
  139. * @return If non 0 returned irrecoverable error happened (or netdata_exit) and ACLK should be terminated
  140. */
  141. static int wait_till_agent_claim_ready()
  142. {
  143. url_t url;
  144. while (!netdata_exit) {
  145. if (wait_till_agent_claimed())
  146. return 1;
  147. // The NULL return means the value was never initialised, but this value has been initialized in post_conf_load.
  148. // We trap the impossible NULL here to keep the linter happy without using a fatal() in the code.
  149. char *cloud_base_url = appconfig_get(&cloud_config, CONFIG_SECTION_GLOBAL, "cloud base url", NULL);
  150. if (cloud_base_url == NULL) {
  151. error("Do not move the cloud base url out of post_conf_load!!");
  152. return 1;
  153. }
  154. // We just check configuration is valid here
  155. // TODO make it without malloc/free
  156. memset(&url, 0, sizeof(url_t));
  157. if (url_parse(cloud_base_url, &url)) {
  158. error("Agent is claimed but the URL in configuration key \"cloud base url\" is invalid, please fix");
  159. url_t_destroy(&url);
  160. sleep(5);
  161. continue;
  162. }
  163. url_t_destroy(&url);
  164. if (!load_private_key())
  165. return 0;
  166. sleep(5);
  167. }
  168. return 1;
  169. }
  170. void aclk_mqtt_wss_log_cb(mqtt_wss_log_type_t log_type, const char* str)
  171. {
  172. switch(log_type) {
  173. case MQTT_WSS_LOG_ERROR:
  174. case MQTT_WSS_LOG_FATAL:
  175. case MQTT_WSS_LOG_WARN:
  176. error_report("%s", str);
  177. return;
  178. case MQTT_WSS_LOG_INFO:
  179. info("%s", str);
  180. return;
  181. case MQTT_WSS_LOG_DEBUG:
  182. debug(D_ACLK, "%s", str);
  183. return;
  184. default:
  185. error("Unknown log type from mqtt_wss");
  186. }
  187. }
  188. //TODO prevent big buffer on stack
  189. #define RX_MSGLEN_MAX 4096
  190. static void msg_callback(const char *topic, const void *msg, size_t msglen, int qos)
  191. {
  192. UNUSED(qos);
  193. aclk_rcvd_cloud_msgs++;
  194. if (msglen > RX_MSGLEN_MAX)
  195. error("Incoming ACLK message was bigger than MAX of %d and got truncated.", RX_MSGLEN_MAX);
  196. debug(D_ACLK, "Got Message From Broker Topic \"%s\" QOS %d", topic, qos);
  197. if (aclk_shared_state.mqtt_shutdown_msg_id > 0) {
  198. error("Link is shutting down. Ignoring incoming message.");
  199. return;
  200. }
  201. const char *msgtype = strrchr(topic, '/');
  202. if (unlikely(!msgtype)) {
  203. error_report("Cannot get message type from topic. Ignoring message from topic \"%s\"", topic);
  204. return;
  205. }
  206. msgtype++;
  207. if (unlikely(!*msgtype)) {
  208. error_report("Message type empty. Ignoring message from topic \"%s\"", topic);
  209. return;
  210. }
  211. #ifdef ACLK_LOG_CONVERSATION_DIR
  212. #define FN_MAX_LEN 512
  213. char filename[FN_MAX_LEN];
  214. int logfd;
  215. snprintf(filename, FN_MAX_LEN, ACLK_LOG_CONVERSATION_DIR "/%010d-rx-%s.bin", ACLK_GET_CONV_LOG_NEXT(), msgtype);
  216. logfd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR );
  217. if(logfd < 0)
  218. error("Error opening ACLK Conversation logfile \"%s\" for RX message.", filename);
  219. write(logfd, msg, msglen);
  220. close(logfd);
  221. #endif
  222. aclk_handle_new_cloud_msg(msgtype, msg, msglen, topic);
  223. }
  224. static void puback_callback(uint16_t packet_id)
  225. {
  226. if (++aclk_pubacks_per_conn == ACLK_PUBACKS_CONN_STABLE) {
  227. last_conn_time_appl = now_realtime_sec();
  228. aclk_tbeb_reset();
  229. }
  230. #ifdef NETDATA_INTERNAL_CHECKS
  231. aclk_stats_msg_puback(packet_id);
  232. #endif
  233. if (aclk_shared_state.mqtt_shutdown_msg_id == (int)packet_id) {
  234. info("Shutdown message has been acknowledged by the cloud. Exiting gracefully");
  235. aclk_shared_state.mqtt_shutdown_msg_rcvd = 1;
  236. }
  237. }
  238. static int read_query_thread_count()
  239. {
  240. int threads = MIN(processors/2, 6);
  241. threads = MAX(threads, 2);
  242. threads = config_get_number(CONFIG_SECTION_CLOUD, "query thread count", threads);
  243. if(threads < 1) {
  244. error("You need at least one query thread. Overriding configured setting of \"%d\"", threads);
  245. threads = 1;
  246. config_set_number(CONFIG_SECTION_CLOUD, "query thread count", threads);
  247. }
  248. return threads;
  249. }
  250. void aclk_graceful_disconnect(mqtt_wss_client client);
  251. /* Keeps connection alive and handles all network communications.
  252. * Returns on error or when netdata is shutting down.
  253. * @param client instance of mqtt_wss_client
  254. * @returns 0 - Netdata Exits
  255. * >0 - Error happened. Reconnect and start over.
  256. */
  257. static int handle_connection(mqtt_wss_client client)
  258. {
  259. time_t last_periodic_query_wakeup = now_monotonic_sec();
  260. while (!netdata_exit) {
  261. // timeout 1000 to check at least once a second
  262. // for netdata_exit
  263. if (mqtt_wss_service(client, 1000) < 0){
  264. error_report("Connection Error or Dropped");
  265. return 1;
  266. }
  267. if (disconnect_req || aclk_kill_link) {
  268. info("Going to restart connection due to disconnect_req=%s (cloud req), aclk_kill_link=%s (reclaim)",
  269. disconnect_req ? "true" : "false",
  270. aclk_kill_link ? "true" : "false");
  271. disconnect_req = 0;
  272. aclk_kill_link = 0;
  273. aclk_graceful_disconnect(client);
  274. aclk_queue_unlock();
  275. aclk_shared_state.mqtt_shutdown_msg_id = -1;
  276. aclk_shared_state.mqtt_shutdown_msg_rcvd = 0;
  277. return 1;
  278. }
  279. // mqtt_wss_service will return faster than in one second
  280. // if there is enough work to do
  281. time_t now = now_monotonic_sec();
  282. if (last_periodic_query_wakeup < now) {
  283. // wake up at least one Query Thread at least
  284. // once per second
  285. last_periodic_query_wakeup = now;
  286. QUERY_THREAD_WAKEUP;
  287. }
  288. }
  289. return 0;
  290. }
  291. static inline void mqtt_connected_actions(mqtt_wss_client client)
  292. {
  293. char *topic = (char*)aclk_get_topic(ACLK_TOPICID_COMMAND);
  294. if (!topic)
  295. error("Unable to fetch topic for COMMAND (to subscribe)");
  296. else
  297. mqtt_wss_subscribe(client, topic, 1);
  298. topic = (char*)aclk_get_topic(ACLK_TOPICID_CMD_NG_V1);
  299. if (!topic)
  300. error("Unable to fetch topic for protobuf COMMAND (to subscribe)");
  301. else
  302. mqtt_wss_subscribe(client, topic, 1);
  303. aclk_stats_upd_online(1);
  304. aclk_connected = 1;
  305. aclk_pubacks_per_conn = 0;
  306. aclk_rcvd_cloud_msgs = 0;
  307. aclk_connection_counter++;
  308. aclk_send_agent_connection_update(client, 1);
  309. }
  310. void aclk_graceful_disconnect(mqtt_wss_client client)
  311. {
  312. info("Preparing to gracefully shutdown ACLK connection");
  313. aclk_queue_lock();
  314. aclk_queue_flush();
  315. aclk_shared_state.mqtt_shutdown_msg_id = aclk_send_agent_connection_update(client, 0);
  316. time_t t = now_monotonic_sec();
  317. while (!mqtt_wss_service(client, 100)) {
  318. if (now_monotonic_sec() - t >= 2) {
  319. error("Wasn't able to gracefully shutdown ACLK in time!");
  320. break;
  321. }
  322. if (aclk_shared_state.mqtt_shutdown_msg_rcvd) {
  323. info("MQTT App Layer `disconnect` message sent successfully");
  324. break;
  325. }
  326. }
  327. info("ACLK link is down");
  328. log_access("ACLK DISCONNECTED");
  329. aclk_stats_upd_online(0);
  330. last_disconnect_time = now_realtime_sec();
  331. aclk_connected = 0;
  332. info("Attempting to gracefully shutdown the MQTT/WSS connection");
  333. mqtt_wss_disconnect(client, 1000);
  334. }
  335. static unsigned long aclk_reconnect_delay() {
  336. unsigned long recon_delay;
  337. time_t now;
  338. if (aclk_disable_runtime) {
  339. aclk_tbeb_reset();
  340. return 60 * MSEC_PER_SEC;
  341. }
  342. now = now_monotonic_sec();
  343. if (aclk_block_until) {
  344. if (now < aclk_block_until) {
  345. recon_delay = aclk_block_until - now;
  346. recon_delay *= MSEC_PER_SEC;
  347. aclk_block_until = 0;
  348. aclk_tbeb_reset();
  349. return recon_delay;
  350. }
  351. aclk_block_until = 0;
  352. }
  353. if (!aclk_env || !aclk_env->backoff.base)
  354. return aclk_tbeb_delay(0, 2, 0, 1024);
  355. return aclk_tbeb_delay(0, aclk_env->backoff.base, aclk_env->backoff.min_s, aclk_env->backoff.max_s);
  356. }
  357. /* Block till aclk_reconnect_delay is satisfied or netdata_exit is signalled
  358. * @return 0 - Go ahead and connect (delay expired)
  359. * 1 - netdata_exit
  360. */
  361. #define NETDATA_EXIT_POLL_MS (MSEC_PER_SEC/4)
  362. static int aclk_block_till_recon_allowed() {
  363. unsigned long recon_delay = aclk_reconnect_delay();
  364. next_connection_attempt = now_realtime_sec() + (recon_delay / MSEC_PER_SEC);
  365. last_backoff_value = (float)recon_delay / MSEC_PER_SEC;
  366. info("Wait before attempting to reconnect in %.3f seconds\n", recon_delay / (float)MSEC_PER_SEC);
  367. // we want to wake up from time to time to check netdata_exit
  368. while (recon_delay)
  369. {
  370. if (netdata_exit)
  371. return 1;
  372. if (recon_delay > NETDATA_EXIT_POLL_MS) {
  373. sleep_usec(NETDATA_EXIT_POLL_MS * USEC_PER_MS);
  374. recon_delay -= NETDATA_EXIT_POLL_MS;
  375. continue;
  376. }
  377. sleep_usec(recon_delay * USEC_PER_MS);
  378. recon_delay = 0;
  379. }
  380. return netdata_exit;
  381. }
  382. #ifndef ACLK_DISABLE_CHALLENGE
  383. /* Cloud returns transport list ordered with highest
  384. * priority first. This function selects highest prio
  385. * transport that we can actually use (support)
  386. */
  387. static int aclk_get_transport_idx(aclk_env_t *env) {
  388. for (size_t i = 0; i < env->transport_count; i++) {
  389. // currently we support only MQTT 3
  390. // therefore select first transport that matches
  391. if (env->transports[i]->type == ACLK_TRP_MQTT_3_1_1) {
  392. return i;
  393. }
  394. }
  395. return -1;
  396. }
  397. #endif
  398. /* Attempts to make a connection to MQTT broker over WSS
  399. * @param client instance of mqtt_wss_client
  400. * @return 0 - Successful Connection,
  401. * <0 - Irrecoverable Error -> Kill ACLK,
  402. * >0 - netdata_exit
  403. */
  404. #define CLOUD_BASE_URL_READ_RETRY 30
  405. #ifdef ACLK_SSL_ALLOW_SELF_SIGNED
  406. #define ACLK_SSL_FLAGS MQTT_WSS_SSL_ALLOW_SELF_SIGNED
  407. #else
  408. #define ACLK_SSL_FLAGS MQTT_WSS_SSL_CERT_CHECK_FULL
  409. #endif
  410. static int aclk_attempt_to_connect(mqtt_wss_client client)
  411. {
  412. int ret;
  413. url_t base_url;
  414. #ifndef ACLK_DISABLE_CHALLENGE
  415. url_t auth_url;
  416. url_t mqtt_url;
  417. #endif
  418. while (!netdata_exit) {
  419. char *cloud_base_url = appconfig_get(&cloud_config, CONFIG_SECTION_GLOBAL, "cloud base url", NULL);
  420. if (cloud_base_url == NULL) {
  421. error("Do not move the cloud base url out of post_conf_load!!");
  422. return -1;
  423. }
  424. if (aclk_block_till_recon_allowed())
  425. return 1;
  426. info("Attempting connection now");
  427. memset(&base_url, 0, sizeof(url_t));
  428. if (url_parse(cloud_base_url, &base_url)) {
  429. error("ACLK base URL configuration key could not be parsed. Will retry in %d seconds.", CLOUD_BASE_URL_READ_RETRY);
  430. sleep(CLOUD_BASE_URL_READ_RETRY);
  431. url_t_destroy(&base_url);
  432. continue;
  433. }
  434. struct mqtt_wss_proxy proxy_conf = { .host = NULL, .port = 0, .type = MQTT_WSS_DIRECT };
  435. aclk_set_proxy((char**)&proxy_conf.host, &proxy_conf.port, &proxy_conf.type);
  436. struct mqtt_connect_params mqtt_conn_params = {
  437. .clientid = "anon",
  438. .username = "anon",
  439. .password = "anon",
  440. .will_topic = "lwt",
  441. .will_msg = NULL,
  442. .will_flags = MQTT_WSS_PUB_QOS2,
  443. .keep_alive = 60,
  444. .drop_on_publish_fail = 1
  445. };
  446. #ifndef ACLK_DISABLE_CHALLENGE
  447. if (aclk_env) {
  448. aclk_env_t_destroy(aclk_env);
  449. freez(aclk_env);
  450. }
  451. aclk_env = callocz(1, sizeof(aclk_env_t));
  452. ret = aclk_get_env(aclk_env, base_url.host, base_url.port);
  453. url_t_destroy(&base_url);
  454. if (ret) {
  455. error("Failed to Get ACLK environment");
  456. // delay handled by aclk_block_till_recon_allowed
  457. continue;
  458. }
  459. if (netdata_exit)
  460. return 1;
  461. if (aclk_env->encoding != ACLK_ENC_PROTO) {
  462. error_report("This agent can only use the new cloud protocol but cloud requested old one.");
  463. continue;
  464. }
  465. if (!aclk_env_has_capa("proto")) {
  466. error ("Can't use encoding=proto without at least \"proto\" capability.");
  467. continue;
  468. }
  469. info("New ACLK protobuf protocol negotiated successfully (/env response).");
  470. memset(&auth_url, 0, sizeof(url_t));
  471. if (url_parse(aclk_env->auth_endpoint, &auth_url)) {
  472. error("Parsing URL returned by env endpoint for authentication failed. \"%s\"", aclk_env->auth_endpoint);
  473. url_t_destroy(&auth_url);
  474. continue;
  475. }
  476. ret = aclk_get_mqtt_otp(aclk_private_key, (char **)&mqtt_conn_params.clientid, (char **)&mqtt_conn_params.username, (char **)&mqtt_conn_params.password, &auth_url);
  477. url_t_destroy(&auth_url);
  478. if (ret) {
  479. error("Error passing Challenge/Response to get OTP");
  480. continue;
  481. }
  482. // aclk_get_topic moved here as during OTP we
  483. // generate the topic cache
  484. mqtt_conn_params.will_topic = aclk_get_topic(ACLK_TOPICID_AGENT_CONN);
  485. if (!mqtt_conn_params.will_topic) {
  486. error("Couldn't get LWT topic. Will not send LWT.");
  487. continue;
  488. }
  489. // Do the MQTT connection
  490. ret = aclk_get_transport_idx(aclk_env);
  491. if (ret < 0) {
  492. error("Cloud /env endpoint didn't return any transport usable by this Agent.");
  493. continue;
  494. }
  495. memset(&mqtt_url, 0, sizeof(url_t));
  496. if (url_parse(aclk_env->transports[ret]->endpoint, &mqtt_url)){
  497. error("Failed to parse target URL for /env trp idx %d \"%s\"", ret, aclk_env->transports[ret]->endpoint);
  498. url_t_destroy(&mqtt_url);
  499. continue;
  500. }
  501. #endif
  502. aclk_session_newarch = now_realtime_usec();
  503. aclk_session_sec = aclk_session_newarch / USEC_PER_SEC;
  504. aclk_session_us = aclk_session_newarch % USEC_PER_SEC;
  505. mqtt_conn_params.will_msg = aclk_generate_lwt(&mqtt_conn_params.will_msg_len);
  506. #ifdef ACLK_DISABLE_CHALLENGE
  507. ret = mqtt_wss_connect(client, base_url.host, base_url.port, &mqtt_conn_params, ACLK_SSL_FLAGS, &proxy_conf);
  508. url_t_destroy(&base_url);
  509. #else
  510. ret = mqtt_wss_connect(client, mqtt_url.host, mqtt_url.port, &mqtt_conn_params, ACLK_SSL_FLAGS, &proxy_conf);
  511. url_t_destroy(&mqtt_url);
  512. freez((char*)mqtt_conn_params.clientid);
  513. freez((char*)mqtt_conn_params.password);
  514. freez((char*)mqtt_conn_params.username);
  515. #endif
  516. freez((char *)mqtt_conn_params.will_msg);
  517. if (!ret) {
  518. last_conn_time_mqtt = now_realtime_sec();
  519. info("ACLK connection successfully established");
  520. log_access("ACLK CONNECTED");
  521. mqtt_connected_actions(client);
  522. return 0;
  523. }
  524. error_report("Connect failed");
  525. }
  526. return 1;
  527. }
  528. /**
  529. * Main agent cloud link thread
  530. *
  531. * This thread will simply call the main event loop that handles
  532. * pending requests - both inbound and outbound
  533. *
  534. * @param ptr is a pointer to the netdata_static_thread structure.
  535. *
  536. * @return It always returns NULL
  537. */
  538. void *aclk_main(void *ptr)
  539. {
  540. struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr;
  541. struct aclk_stats_thread *stats_thread = NULL;
  542. struct aclk_query_threads query_threads;
  543. query_threads.thread_list = NULL;
  544. ACLK_PROXY_TYPE proxy_type;
  545. aclk_get_proxy(&proxy_type);
  546. if (proxy_type == PROXY_TYPE_SOCKS5) {
  547. error("SOCKS5 proxy is not supported by ACLK-NG yet.");
  548. static_thread->enabled = NETDATA_MAIN_THREAD_EXITED;
  549. return NULL;
  550. }
  551. unsigned int proto_hdl_cnt = aclk_init_rx_msg_handlers();
  552. // This thread is unusual in that it cannot be cancelled by cancel_main_threads()
  553. // as it must notify the far end that it shutdown gracefully and avoid the LWT.
  554. netdata_thread_disable_cancelability();
  555. #if defined( DISABLE_CLOUD ) || !defined( ENABLE_ACLK )
  556. info("Killing ACLK thread -> cloud functionality has been disabled");
  557. static_thread->enabled = NETDATA_MAIN_THREAD_EXITED;
  558. return NULL;
  559. #endif
  560. query_threads.count = read_query_thread_count();
  561. if (wait_till_cloud_enabled())
  562. goto exit;
  563. if (wait_till_agent_claim_ready())
  564. goto exit;
  565. use_mqtt_5 = config_get_boolean(CONFIG_SECTION_CLOUD, "mqtt5", CONFIG_BOOLEAN_YES);
  566. if (!(mqttwss_client = mqtt_wss_new("mqtt_wss", aclk_mqtt_wss_log_cb, msg_callback, puback_callback, use_mqtt_5))) {
  567. error("Couldn't initialize MQTT_WSS network library");
  568. goto exit;
  569. }
  570. // Enable MQTT buffer growth if necessary
  571. // e.g. old cloud architecture clients with huge nodes
  572. // that send JSON payloads of 10 MB as single messages
  573. mqtt_wss_set_max_buf_size(mqttwss_client, 25*1024*1024);
  574. aclk_stats_enabled = config_get_boolean(CONFIG_SECTION_CLOUD, "statistics", CONFIG_BOOLEAN_YES);
  575. if (aclk_stats_enabled) {
  576. stats_thread = callocz(1, sizeof(struct aclk_stats_thread));
  577. stats_thread->thread = mallocz(sizeof(netdata_thread_t));
  578. stats_thread->query_thread_count = query_threads.count;
  579. stats_thread->client = mqttwss_client;
  580. aclk_stats_thread_prepare(query_threads.count, proto_hdl_cnt);
  581. netdata_thread_create(
  582. stats_thread->thread, ACLK_STATS_THREAD_NAME, NETDATA_THREAD_OPTION_JOINABLE, aclk_stats_main_thread,
  583. stats_thread);
  584. }
  585. // Keep reconnecting and talking until our time has come
  586. // and the Grim Reaper (netdata_exit) calls
  587. do {
  588. if (aclk_attempt_to_connect(mqttwss_client))
  589. goto exit_full;
  590. if (unlikely(!query_threads.thread_list))
  591. aclk_query_threads_start(&query_threads, mqttwss_client);
  592. if (handle_connection(mqttwss_client)) {
  593. aclk_stats_upd_online(0);
  594. last_disconnect_time = now_realtime_sec();
  595. aclk_connected = 0;
  596. log_access("ACLK DISCONNECTED");
  597. }
  598. } while (!netdata_exit);
  599. aclk_graceful_disconnect(mqttwss_client);
  600. exit_full:
  601. // Tear Down
  602. QUERY_THREAD_WAKEUP_ALL;
  603. aclk_query_threads_cleanup(&query_threads);
  604. if (aclk_stats_enabled) {
  605. netdata_thread_join(*stats_thread->thread, NULL);
  606. aclk_stats_thread_cleanup();
  607. freez(stats_thread->thread);
  608. freez(stats_thread);
  609. }
  610. free_topic_cache();
  611. mqtt_wss_destroy(mqttwss_client);
  612. exit:
  613. if (aclk_env) {
  614. aclk_env_t_destroy(aclk_env);
  615. freez(aclk_env);
  616. }
  617. static_thread->enabled = NETDATA_MAIN_THREAD_EXITED;
  618. return NULL;
  619. }
  620. void aclk_host_state_update(RRDHOST *host, int cmd)
  621. {
  622. uuid_t node_id;
  623. int ret;
  624. if (!aclk_connected)
  625. return;
  626. ret = get_node_id(&host->host_uuid, &node_id);
  627. if (ret > 0) {
  628. // this means we were not able to check if node_id already present
  629. error("Unable to check for node_id. Ignoring the host state update.");
  630. return;
  631. }
  632. if (ret < 0) {
  633. // node_id not found
  634. aclk_query_t create_query;
  635. create_query = aclk_query_new(REGISTER_NODE);
  636. rrdhost_aclk_state_lock(localhost);
  637. node_instance_creation_t node_instance_creation = {
  638. .claim_id = localhost->aclk_state.claimed_id,
  639. .hops = host->system_info->hops,
  640. .hostname = host->hostname,
  641. .machine_guid = host->machine_guid
  642. };
  643. create_query->data.bin_payload.payload = generate_node_instance_creation(&create_query->data.bin_payload.size, &node_instance_creation);
  644. rrdhost_aclk_state_unlock(localhost);
  645. create_query->data.bin_payload.topic = ACLK_TOPICID_CREATE_NODE;
  646. create_query->data.bin_payload.msg_name = "CreateNodeInstance";
  647. info("Registering host=%s, hops=%u",host->machine_guid, host->system_info->hops);
  648. aclk_queue_query(create_query);
  649. return;
  650. }
  651. aclk_query_t query = aclk_query_new(NODE_STATE_UPDATE);
  652. node_instance_connection_t node_state_update = {
  653. .hops = host->system_info->hops,
  654. .live = cmd,
  655. .queryable = 1,
  656. .session_id = aclk_session_newarch
  657. };
  658. node_state_update.node_id = mallocz(UUID_STR_LEN);
  659. uuid_unparse_lower(node_id, (char*)node_state_update.node_id);
  660. struct capability caps[] = {
  661. { .name = "proto", .version = 1, .enabled = 1 },
  662. { .name = "ml", .version = ml_capable(localhost), .enabled = ml_enabled(host) },
  663. { .name = "mc", .version = enable_metric_correlations ? metric_correlations_version : 0, .enabled = enable_metric_correlations },
  664. { .name = "ctx", .version = 1, .enabled = 1 },
  665. { .name = NULL, .version = 0, .enabled = 0 }
  666. };
  667. node_state_update.capabilities = caps;
  668. rrdhost_aclk_state_lock(localhost);
  669. node_state_update.claim_id = localhost->aclk_state.claimed_id;
  670. query->data.bin_payload.payload = generate_node_instance_connection(&query->data.bin_payload.size, &node_state_update);
  671. rrdhost_aclk_state_unlock(localhost);
  672. info("Queuing status update for node=%s, live=%d, hops=%u",(char*)node_state_update.node_id, cmd,
  673. host->system_info->hops);
  674. freez((void*)node_state_update.node_id);
  675. query->data.bin_payload.msg_name = "UpdateNodeInstanceConnection";
  676. query->data.bin_payload.topic = ACLK_TOPICID_NODE_CONN;
  677. aclk_queue_query(query);
  678. }
  679. void aclk_send_node_instances()
  680. {
  681. struct node_instance_list *list_head = get_node_list();
  682. struct node_instance_list *list = list_head;
  683. if (unlikely(!list)) {
  684. error_report("Failure to get_node_list from DB!");
  685. return;
  686. }
  687. while (!uuid_is_null(list->host_id)) {
  688. if (!uuid_is_null(list->node_id)) {
  689. aclk_query_t query = aclk_query_new(NODE_STATE_UPDATE);
  690. node_instance_connection_t node_state_update = {
  691. .live = list->live,
  692. .hops = list->hops,
  693. .queryable = 1,
  694. .session_id = aclk_session_newarch
  695. };
  696. node_state_update.node_id = mallocz(UUID_STR_LEN);
  697. uuid_unparse_lower(list->node_id, (char*)node_state_update.node_id);
  698. char host_id[UUID_STR_LEN];
  699. uuid_unparse_lower(list->host_id, host_id);
  700. RRDHOST *host = rrdhost_find_by_guid(host_id, 0);
  701. struct capability caps[] = {
  702. { .name = "proto", .version = 1, .enabled = 1 },
  703. { .name = "ml", .version = ml_capable(localhost), .enabled = host ? ml_enabled(host) : 0 },
  704. { .name = "mc", .version = enable_metric_correlations ? metric_correlations_version : 0, .enabled = enable_metric_correlations },
  705. { .name = "ctx", .version = 1, .enabled = 1 },
  706. { .name = NULL, .version = 0, .enabled = 0 }
  707. };
  708. node_state_update.capabilities = caps;
  709. rrdhost_aclk_state_lock(localhost);
  710. node_state_update.claim_id = localhost->aclk_state.claimed_id;
  711. query->data.bin_payload.payload = generate_node_instance_connection(&query->data.bin_payload.size, &node_state_update);
  712. rrdhost_aclk_state_unlock(localhost);
  713. info("Queuing status update for node=%s, live=%d, hops=%d",(char*)node_state_update.node_id,
  714. list->live,
  715. list->hops);
  716. freez((void*)node_state_update.node_id);
  717. query->data.bin_payload.msg_name = "UpdateNodeInstanceConnection";
  718. query->data.bin_payload.topic = ACLK_TOPICID_NODE_CONN;
  719. aclk_queue_query(query);
  720. } else {
  721. aclk_query_t create_query;
  722. create_query = aclk_query_new(REGISTER_NODE);
  723. node_instance_creation_t node_instance_creation = {
  724. .hops = list->hops,
  725. .hostname = list->hostname,
  726. };
  727. node_instance_creation.machine_guid = mallocz(UUID_STR_LEN);
  728. uuid_unparse_lower(list->host_id, (char*)node_instance_creation.machine_guid);
  729. create_query->data.bin_payload.topic = ACLK_TOPICID_CREATE_NODE;
  730. create_query->data.bin_payload.msg_name = "CreateNodeInstance";
  731. rrdhost_aclk_state_lock(localhost);
  732. node_instance_creation.claim_id = localhost->aclk_state.claimed_id,
  733. create_query->data.bin_payload.payload = generate_node_instance_creation(&create_query->data.bin_payload.size, &node_instance_creation);
  734. rrdhost_aclk_state_unlock(localhost);
  735. info("Queuing registration for host=%s, hops=%d",(char*)node_instance_creation.machine_guid,
  736. list->hops);
  737. freez(node_instance_creation.machine_guid);
  738. aclk_queue_query(create_query);
  739. }
  740. freez(list->hostname);
  741. list++;
  742. }
  743. freez(list_head);
  744. }
  745. void aclk_send_bin_msg(char *msg, size_t msg_len, enum aclk_topics subtopic, const char *msgname)
  746. {
  747. aclk_send_bin_message_subtopic_pid(mqttwss_client, msg, msg_len, subtopic, msgname);
  748. }
  749. static void fill_alert_status_for_host(BUFFER *wb, RRDHOST *host)
  750. {
  751. struct proto_alert_status status;
  752. memset(&status, 0, sizeof(status));
  753. if (get_proto_alert_status(host, &status)) {
  754. buffer_strcat(wb, "\nFailed to get alert streaming status for this host");
  755. return;
  756. }
  757. buffer_sprintf(wb,
  758. "\n\t\tUpdates: %d"
  759. "\n\t\tBatch ID: %"PRIu64
  760. "\n\t\tLast Acked Seq ID: %"PRIu64
  761. "\n\t\tPending Min Seq ID: %"PRIu64
  762. "\n\t\tPending Max Seq ID: %"PRIu64
  763. "\n\t\tLast Submitted Seq ID: %"PRIu64,
  764. status.alert_updates,
  765. status.alerts_batch_id,
  766. status.last_acked_sequence_id,
  767. status.pending_min_sequence_id,
  768. status.pending_max_sequence_id,
  769. status.last_submitted_sequence_id
  770. );
  771. }
  772. static void fill_chart_status_for_host(BUFFER *wb, RRDHOST *host)
  773. {
  774. struct aclk_chart_sync_stats *stats = aclk_get_chart_sync_stats(host);
  775. if (!stats) {
  776. buffer_strcat(wb, "\n\t\tFailed to get alert streaming status for this host");
  777. return;
  778. }
  779. buffer_sprintf(wb,
  780. "\n\t\tUpdates: %d"
  781. "\n\t\tBatch ID: %"PRIu64
  782. "\n\t\tMin Seq ID: %"PRIu64
  783. "\n\t\tMax Seq ID: %"PRIu64
  784. "\n\t\tPending Min Seq ID: %"PRIu64
  785. "\n\t\tPending Max Seq ID: %"PRIu64
  786. "\n\t\tSent Min Seq ID: %"PRIu64
  787. "\n\t\tSent Max Seq ID: %"PRIu64
  788. "\n\t\tAcked Min Seq ID: %"PRIu64
  789. "\n\t\tAcked Max Seq ID: %"PRIu64,
  790. stats->updates,
  791. stats->batch_id,
  792. stats->min_seqid,
  793. stats->max_seqid,
  794. stats->min_seqid_pend,
  795. stats->max_seqid_pend,
  796. stats->min_seqid_sent,
  797. stats->max_seqid_sent,
  798. stats->min_seqid_ack,
  799. stats->max_seqid_ack
  800. );
  801. freez(stats);
  802. }
  803. char *ng_aclk_state(void)
  804. {
  805. BUFFER *wb = buffer_create(1024);
  806. struct tm *tmptr, tmbuf;
  807. char *ret;
  808. buffer_strcat(wb,
  809. "ACLK Available: Yes\n"
  810. "ACLK Version: 2\n"
  811. "Protocols Supported: Protobuf\n"
  812. );
  813. buffer_sprintf(wb, "Protocol Used: Protobuf\nMQTT Version: %d\nClaimed: ", use_mqtt_5 ? 5 : 3);
  814. char *agent_id = get_agent_claimid();
  815. if (agent_id == NULL)
  816. buffer_strcat(wb, "No\n");
  817. else {
  818. char *cloud_base_url = appconfig_get(&cloud_config, CONFIG_SECTION_GLOBAL, "cloud base url", NULL);
  819. buffer_sprintf(wb, "Yes\nClaimed Id: %s\nCloud URL: %s\n", agent_id, cloud_base_url ? cloud_base_url : "null");
  820. freez(agent_id);
  821. }
  822. buffer_sprintf(wb, "Online: %s\nReconnect count: %d\nBanned By Cloud: %s\n", aclk_connected ? "Yes" : "No", aclk_connection_counter > 0 ? (aclk_connection_counter - 1) : 0, aclk_disable_runtime ? "Yes" : "No");
  823. if (last_conn_time_mqtt && (tmptr = localtime_r(&last_conn_time_mqtt, &tmbuf)) ) {
  824. char timebuf[26];
  825. strftime(timebuf, 26, "%Y-%m-%d %H:%M:%S", tmptr);
  826. buffer_sprintf(wb, "Last Connection Time: %s\n", timebuf);
  827. }
  828. if (last_conn_time_appl && (tmptr = localtime_r(&last_conn_time_appl, &tmbuf)) ) {
  829. char timebuf[26];
  830. strftime(timebuf, 26, "%Y-%m-%d %H:%M:%S", tmptr);
  831. buffer_sprintf(wb, "Last Connection Time + %d PUBACKs received: %s\n", ACLK_PUBACKS_CONN_STABLE, timebuf);
  832. }
  833. if (last_disconnect_time && (tmptr = localtime_r(&last_disconnect_time, &tmbuf)) ) {
  834. char timebuf[26];
  835. strftime(timebuf, 26, "%Y-%m-%d %H:%M:%S", tmptr);
  836. buffer_sprintf(wb, "Last Disconnect Time: %s\n", timebuf);
  837. }
  838. if (!aclk_connected && next_connection_attempt && (tmptr = localtime_r(&next_connection_attempt, &tmbuf)) ) {
  839. char timebuf[26];
  840. strftime(timebuf, 26, "%Y-%m-%d %H:%M:%S", tmptr);
  841. buffer_sprintf(wb, "Next Connection Attempt At: %s\nLast Backoff: %.3f", timebuf, last_backoff_value);
  842. }
  843. if (aclk_connected) {
  844. buffer_sprintf(wb, "Received Cloud MQTT Messages: %d\nMQTT Messages Confirmed by Remote Broker (PUBACKs): %d", aclk_rcvd_cloud_msgs, aclk_pubacks_per_conn);
  845. RRDHOST *host;
  846. rrd_rdlock();
  847. rrdhost_foreach_read(host) {
  848. buffer_sprintf(wb, "\n\n> Node Instance for mGUID: \"%s\" hostname \"%s\"\n", host->machine_guid, host->hostname);
  849. buffer_strcat(wb, "\tClaimed ID: ");
  850. rrdhost_aclk_state_lock(host);
  851. if (host->aclk_state.claimed_id)
  852. buffer_strcat(wb, host->aclk_state.claimed_id);
  853. else
  854. buffer_strcat(wb, "null");
  855. rrdhost_aclk_state_unlock(host);
  856. if (host->node_id == NULL || uuid_is_null(*host->node_id)) {
  857. buffer_strcat(wb, "\n\tNode ID: null\n");
  858. } else {
  859. char node_id[GUID_LEN + 1];
  860. uuid_unparse_lower(*host->node_id, node_id);
  861. buffer_sprintf(wb, "\n\tNode ID: %s\n", node_id);
  862. }
  863. buffer_sprintf(wb, "\tStreaming Hops: %d\n\tRelationship: %s", host->system_info->hops, host == localhost ? "self" : "child");
  864. if (host != localhost)
  865. buffer_sprintf(wb, "\n\tStreaming Connection Live: %s", host->receiver ? "true" : "false");
  866. buffer_strcat(wb, "\n\tAlert Streaming Status:");
  867. fill_alert_status_for_host(wb, host);
  868. buffer_strcat(wb, "\n\tChart Streaming Status:");
  869. fill_chart_status_for_host(wb, host);
  870. }
  871. rrd_unlock();
  872. }
  873. ret = strdupz(buffer_tostring(wb));
  874. buffer_free(wb);
  875. return ret;
  876. }
  877. static void fill_alert_status_for_host_json(json_object *obj, RRDHOST *host)
  878. {
  879. struct proto_alert_status status;
  880. memset(&status, 0, sizeof(status));
  881. if (get_proto_alert_status(host, &status))
  882. return;
  883. json_object *tmp = json_object_new_int(status.alert_updates);
  884. json_object_object_add(obj, "updates", tmp);
  885. tmp = json_object_new_int(status.alerts_batch_id);
  886. json_object_object_add(obj, "batch-id", tmp);
  887. tmp = json_object_new_int(status.last_acked_sequence_id);
  888. json_object_object_add(obj, "last-acked-seq-id", tmp);
  889. tmp = json_object_new_int(status.pending_min_sequence_id);
  890. json_object_object_add(obj, "pending-min-seq-id", tmp);
  891. tmp = json_object_new_int(status.pending_max_sequence_id);
  892. json_object_object_add(obj, "pending-max-seq-id", tmp);
  893. tmp = json_object_new_int(status.last_submitted_sequence_id);
  894. json_object_object_add(obj, "last-submitted-seq-id", tmp);
  895. }
  896. static void fill_chart_status_for_host_json(json_object *obj, RRDHOST *host)
  897. {
  898. struct aclk_chart_sync_stats *stats = aclk_get_chart_sync_stats(host);
  899. if (!stats)
  900. return;
  901. json_object *tmp = json_object_new_int(stats->updates);
  902. json_object_object_add(obj, "updates", tmp);
  903. tmp = json_object_new_int(stats->batch_id);
  904. json_object_object_add(obj, "batch-id", tmp);
  905. tmp = json_object_new_int(stats->min_seqid);
  906. json_object_object_add(obj, "min-seq-id", tmp);
  907. tmp = json_object_new_int(stats->max_seqid);
  908. json_object_object_add(obj, "max-seq-id", tmp);
  909. tmp = json_object_new_int(stats->min_seqid_pend);
  910. json_object_object_add(obj, "pending-min-seq-id", tmp);
  911. tmp = json_object_new_int(stats->max_seqid_pend);
  912. json_object_object_add(obj, "pending-max-seq-id", tmp);
  913. tmp = json_object_new_int(stats->min_seqid_sent);
  914. json_object_object_add(obj, "sent-min-seq-id", tmp);
  915. tmp = json_object_new_int(stats->max_seqid_sent);
  916. json_object_object_add(obj, "sent-max-seq-id", tmp);
  917. tmp = json_object_new_int(stats->min_seqid_ack);
  918. json_object_object_add(obj, "acked-min-seq-id", tmp);
  919. tmp = json_object_new_int(stats->max_seqid_ack);
  920. json_object_object_add(obj, "acked-max-seq-id", tmp);
  921. freez(stats);
  922. }
  923. static json_object *timestamp_to_json(const time_t *t)
  924. {
  925. struct tm *tmptr, tmbuf;
  926. if (*t && (tmptr = gmtime_r(t, &tmbuf)) ) {
  927. char timebuf[26];
  928. strftime(timebuf, 26, "%Y-%m-%d %H:%M:%S", tmptr);
  929. return json_object_new_string(timebuf);
  930. }
  931. return NULL;
  932. }
  933. char *ng_aclk_state_json(void)
  934. {
  935. json_object *tmp, *grp, *msg = json_object_new_object();
  936. tmp = json_object_new_boolean(1);
  937. json_object_object_add(msg, "aclk-available", tmp);
  938. tmp = json_object_new_int(2);
  939. json_object_object_add(msg, "aclk-version", tmp);
  940. grp = json_object_new_array();
  941. tmp = json_object_new_string("Protobuf");
  942. json_object_array_add(grp, tmp);
  943. json_object_object_add(msg, "protocols-supported", grp);
  944. char *agent_id = get_agent_claimid();
  945. tmp = json_object_new_boolean(agent_id != NULL);
  946. json_object_object_add(msg, "agent-claimed", tmp);
  947. if (agent_id) {
  948. tmp = json_object_new_string(agent_id);
  949. freez(agent_id);
  950. } else
  951. tmp = NULL;
  952. json_object_object_add(msg, "claimed-id", tmp);
  953. char *cloud_base_url = appconfig_get(&cloud_config, CONFIG_SECTION_GLOBAL, "cloud base url", NULL);
  954. tmp = cloud_base_url ? json_object_new_string(cloud_base_url) : NULL;
  955. json_object_object_add(msg, "cloud-url", tmp);
  956. tmp = json_object_new_boolean(aclk_connected);
  957. json_object_object_add(msg, "online", tmp);
  958. tmp = json_object_new_string("Protobuf");
  959. json_object_object_add(msg, "used-cloud-protocol", tmp);
  960. tmp = json_object_new_int(use_mqtt_5 ? 5 : 3);
  961. json_object_object_add(msg, "mqtt-version", tmp);
  962. tmp = json_object_new_int(aclk_rcvd_cloud_msgs);
  963. json_object_object_add(msg, "received-app-layer-msgs", tmp);
  964. tmp = json_object_new_int(aclk_pubacks_per_conn);
  965. json_object_object_add(msg, "received-mqtt-pubacks", tmp);
  966. tmp = json_object_new_int(aclk_connection_counter > 0 ? (aclk_connection_counter - 1) : 0);
  967. json_object_object_add(msg, "reconnect-count", tmp);
  968. json_object_object_add(msg, "last-connect-time-utc", timestamp_to_json(&last_conn_time_mqtt));
  969. json_object_object_add(msg, "last-connect-time-puback-utc", timestamp_to_json(&last_conn_time_appl));
  970. json_object_object_add(msg, "last-disconnect-time-utc", timestamp_to_json(&last_disconnect_time));
  971. json_object_object_add(msg, "next-connection-attempt-utc", !aclk_connected ? timestamp_to_json(&next_connection_attempt) : NULL);
  972. tmp = NULL;
  973. if (!aclk_connected && last_backoff_value)
  974. tmp = json_object_new_double(last_backoff_value);
  975. json_object_object_add(msg, "last-backoff-value", tmp);
  976. tmp = json_object_new_boolean(aclk_disable_runtime);
  977. json_object_object_add(msg, "banned-by-cloud", tmp);
  978. grp = json_object_new_array();
  979. RRDHOST *host;
  980. rrd_rdlock();
  981. rrdhost_foreach_read(host) {
  982. json_object *nodeinstance = json_object_new_object();
  983. tmp = json_object_new_string(host->hostname);
  984. json_object_object_add(nodeinstance, "hostname", tmp);
  985. tmp = json_object_new_string(host->machine_guid);
  986. json_object_object_add(nodeinstance, "mguid", tmp);
  987. rrdhost_aclk_state_lock(host);
  988. if (host->aclk_state.claimed_id) {
  989. tmp = json_object_new_string(host->aclk_state.claimed_id);
  990. json_object_object_add(nodeinstance, "claimed_id", tmp);
  991. } else
  992. json_object_object_add(nodeinstance, "claimed_id", NULL);
  993. rrdhost_aclk_state_unlock(host);
  994. if (host->node_id == NULL || uuid_is_null(*host->node_id)) {
  995. json_object_object_add(nodeinstance, "node-id", NULL);
  996. } else {
  997. char node_id[GUID_LEN + 1];
  998. uuid_unparse_lower(*host->node_id, node_id);
  999. tmp = json_object_new_string(node_id);
  1000. json_object_object_add(nodeinstance, "node-id", tmp);
  1001. }
  1002. tmp = json_object_new_int(host->system_info->hops);
  1003. json_object_object_add(nodeinstance, "streaming-hops", tmp);
  1004. tmp = json_object_new_string(host == localhost ? "self" : "child");
  1005. json_object_object_add(nodeinstance, "relationship", tmp);
  1006. tmp = json_object_new_boolean((host->receiver || host == localhost));
  1007. json_object_object_add(nodeinstance, "streaming-online", tmp);
  1008. tmp = json_object_new_object();
  1009. fill_alert_status_for_host_json(tmp, host);
  1010. json_object_object_add(nodeinstance, "alert-sync-status", tmp);
  1011. tmp = json_object_new_object();
  1012. fill_chart_status_for_host_json(tmp, host);
  1013. json_object_object_add(nodeinstance, "chart-sync-status", tmp);
  1014. json_object_array_add(grp, nodeinstance);
  1015. }
  1016. rrd_unlock();
  1017. json_object_object_add(msg, "node-instances", grp);
  1018. char *str = strdupz(json_object_to_json_string_ext(msg, JSON_C_TO_STRING_PLAIN));
  1019. json_object_put(msg);
  1020. return str;
  1021. }