aclk.c 46 KB

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