aclk.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. #include "aclk.h"
  2. #include "aclk_stats.h"
  3. #include "mqtt_wss_client.h"
  4. #include "aclk_otp.h"
  5. #include "aclk_tx_msgs.h"
  6. #include "aclk_query.h"
  7. #include "aclk_query_queue.h"
  8. #include "aclk_util.h"
  9. #include "aclk_rx_msgs.h"
  10. #include "aclk_collector_list.h"
  11. #ifdef ACLK_LOG_CONVERSATION_DIR
  12. #include <sys/types.h>
  13. #include <sys/stat.h>
  14. #include <fcntl.h>
  15. #endif
  16. #define ACLK_STABLE_TIMEOUT 3 // Minimum delay to mark AGENT as stable
  17. //TODO remove most (as in 99.999999999%) of this crap
  18. int aclk_connected = 0;
  19. int aclk_disable_runtime = 0;
  20. int aclk_disable_single_updates = 0;
  21. int aclk_kill_link = 0;
  22. int aclk_pubacks_per_conn = 0; // How many PubAcks we got since MQTT conn est.
  23. usec_t aclk_session_us = 0; // Used by the mqtt layer
  24. time_t aclk_session_sec = 0; // Used by the mqtt layer
  25. mqtt_wss_client mqttwss_client;
  26. netdata_mutex_t aclk_shared_state_mutex = NETDATA_MUTEX_INITIALIZER;
  27. #define ACLK_SHARED_STATE_LOCK netdata_mutex_lock(&aclk_shared_state_mutex)
  28. #define ACLK_SHARED_STATE_UNLOCK netdata_mutex_unlock(&aclk_shared_state_mutex)
  29. struct aclk_shared_state aclk_shared_state = {
  30. .agent_state = AGENT_INITIALIZING,
  31. .last_popcorn_interrupt = 0,
  32. .version_neg = 0,
  33. .version_neg_wait_till = 0,
  34. .mqtt_shutdown_msg_id = -1,
  35. .mqtt_shutdown_msg_rcvd = 0
  36. };
  37. void aclk_single_update_disable()
  38. {
  39. aclk_disable_single_updates = 1;
  40. }
  41. void aclk_single_update_enable()
  42. {
  43. aclk_disable_single_updates = 0;
  44. }
  45. //ENDTODO
  46. static RSA *aclk_private_key = NULL;
  47. static int load_private_key()
  48. {
  49. if (aclk_private_key != NULL)
  50. RSA_free(aclk_private_key);
  51. aclk_private_key = NULL;
  52. char filename[FILENAME_MAX + 1];
  53. snprintfz(filename, FILENAME_MAX, "%s/cloud.d/private.pem", netdata_configured_varlib_dir);
  54. long bytes_read;
  55. char *private_key = read_by_filename(filename, &bytes_read);
  56. if (!private_key) {
  57. error("Claimed agent cannot establish ACLK - unable to load private key '%s' failed.", filename);
  58. return 1;
  59. }
  60. debug(D_ACLK, "Claimed agent loaded private key len=%ld bytes", bytes_read);
  61. BIO *key_bio = BIO_new_mem_buf(private_key, -1);
  62. if (key_bio==NULL) {
  63. error("Claimed agent cannot establish ACLK - failed to create BIO for key");
  64. goto biofailed;
  65. }
  66. aclk_private_key = PEM_read_bio_RSAPrivateKey(key_bio, NULL, NULL, NULL);
  67. BIO_free(key_bio);
  68. if (aclk_private_key!=NULL)
  69. {
  70. freez(private_key);
  71. return 0;
  72. }
  73. char err[512];
  74. ERR_error_string_n(ERR_get_error(), err, sizeof(err));
  75. error("Claimed agent cannot establish ACLK - cannot create private key: %s", err);
  76. biofailed:
  77. freez(private_key);
  78. return 1;
  79. }
  80. static int wait_till_cloud_enabled()
  81. {
  82. info("Waiting for Cloud to be enabled");
  83. while (!netdata_cloud_setting) {
  84. sleep_usec(USEC_PER_SEC * 1);
  85. if (netdata_exit)
  86. return 1;
  87. }
  88. return 0;
  89. }
  90. /**
  91. * Will block until agent is claimed. Returns only if agent claimed
  92. * or if agent needs to shutdown.
  93. *
  94. * @return `0` if agent has been claimed,
  95. * `1` if interrupted due to agent shutting down
  96. */
  97. static int wait_till_agent_claimed(void)
  98. {
  99. //TODO prevent malloc and freez
  100. char *agent_id = is_agent_claimed();
  101. while (likely(!agent_id)) {
  102. sleep_usec(USEC_PER_SEC * 1);
  103. if (netdata_exit)
  104. return 1;
  105. agent_id = is_agent_claimed();
  106. }
  107. freez(agent_id);
  108. return 0;
  109. }
  110. /**
  111. * Checks everything is ready for connection
  112. * agent claimed, cloud url set and private key available
  113. *
  114. * @param aclk_hostname points to location where string pointer to hostname will be set
  115. * @param ackl_port port to int where port will be saved
  116. *
  117. * @return If non 0 returned irrecoverable error happened and ACLK should be terminated
  118. */
  119. static int wait_till_agent_claim_ready()
  120. {
  121. int port;
  122. char *hostname = NULL;
  123. while (!netdata_exit) {
  124. if (wait_till_agent_claimed())
  125. return 1;
  126. // The NULL return means the value was never initialised, but this value has been initialized in post_conf_load.
  127. // We trap the impossible NULL here to keep the linter happy without using a fatal() in the code.
  128. char *cloud_base_url = appconfig_get(&cloud_config, CONFIG_SECTION_GLOBAL, "cloud base url", NULL);
  129. if (cloud_base_url == NULL) {
  130. error("Do not move the cloud base url out of post_conf_load!!");
  131. return 1;
  132. }
  133. // We just check configuration is valid here
  134. // TODO make it without malloc/free
  135. if (aclk_decode_base_url(cloud_base_url, &hostname, &port)) {
  136. error("Agent is claimed but the configuration is invalid, please fix");
  137. freez(hostname);
  138. hostname = NULL;
  139. sleep(5);
  140. continue;
  141. }
  142. freez(hostname);
  143. hostname = NULL;
  144. if (!load_private_key()) {
  145. sleep(5);
  146. break;
  147. }
  148. }
  149. return 0;
  150. }
  151. void aclk_mqtt_wss_log_cb(mqtt_wss_log_type_t log_type, const char* str)
  152. {
  153. switch(log_type) {
  154. case MQTT_WSS_LOG_ERROR:
  155. case MQTT_WSS_LOG_FATAL:
  156. case MQTT_WSS_LOG_WARN:
  157. error("%s", str);
  158. return;
  159. case MQTT_WSS_LOG_INFO:
  160. info("%s", str);
  161. return;
  162. case MQTT_WSS_LOG_DEBUG:
  163. debug(D_ACLK, "%s", str);
  164. return;
  165. default:
  166. error("Unknown log type from mqtt_wss");
  167. }
  168. }
  169. //TODO prevent big buffer on stack
  170. #define RX_MSGLEN_MAX 4096
  171. static void msg_callback(const char *topic, const void *msg, size_t msglen, int qos)
  172. {
  173. char cmsg[RX_MSGLEN_MAX];
  174. size_t len = (msglen < RX_MSGLEN_MAX - 1) ? msglen : (RX_MSGLEN_MAX - 1);
  175. if (msglen > RX_MSGLEN_MAX - 1)
  176. error("Incoming ACLK message was bigger than MAX of %d and got truncated.", RX_MSGLEN_MAX);
  177. memcpy(cmsg,
  178. msg,
  179. len);
  180. cmsg[len] = 0;
  181. #ifdef ACLK_LOG_CONVERSATION_DIR
  182. #define FN_MAX_LEN 512
  183. char filename[FN_MAX_LEN];
  184. int logfd;
  185. snprintf(filename, FN_MAX_LEN, ACLK_LOG_CONVERSATION_DIR "/%010d-rx.json", ACLK_GET_CONV_LOG_NEXT());
  186. logfd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR );
  187. if(logfd < 0)
  188. error("Error opening ACLK Conversation logfile \"%s\" for RX message.", filename);
  189. write(logfd, msg, msglen);
  190. close(logfd);
  191. #endif
  192. debug(D_ACLK, "Got Message From Broker Topic \"%s\" QOS %d MSG: \"%s\"", topic, qos, cmsg);
  193. if (strcmp(aclk_get_topic(ACLK_TOPICID_COMMAND), topic))
  194. error("Received message on unexpected topic %s", topic);
  195. if (aclk_shared_state.mqtt_shutdown_msg_id > 0) {
  196. error("Link is shutting down. Ignoring message.");
  197. return;
  198. }
  199. aclk_handle_cloud_message(cmsg);
  200. }
  201. static void puback_callback(uint16_t packet_id)
  202. {
  203. if (++aclk_pubacks_per_conn == ACLK_PUBACKS_CONN_STABLE)
  204. aclk_reconnect_delay(0);
  205. #ifdef NETDATA_INTERNAL_CHECKS
  206. aclk_stats_msg_puback(packet_id);
  207. #endif
  208. if (aclk_shared_state.mqtt_shutdown_msg_id == (int)packet_id) {
  209. error("Got PUBACK for shutdown message. Can exit gracefully.");
  210. aclk_shared_state.mqtt_shutdown_msg_rcvd = 1;
  211. }
  212. }
  213. static int read_query_thread_count()
  214. {
  215. int threads = MIN(processors/2, 6);
  216. threads = MAX(threads, 2);
  217. threads = config_get_number(CONFIG_SECTION_CLOUD, "query thread count", threads);
  218. if(threads < 1) {
  219. error("You need at least one query thread. Overriding configured setting of \"%d\"", threads);
  220. threads = 1;
  221. config_set_number(CONFIG_SECTION_CLOUD, "query thread count", threads);
  222. }
  223. return threads;
  224. }
  225. /* Keeps connection alive and handles all network comms.
  226. * Returns on error or when netdata is shutting down.
  227. * @param client instance of mqtt_wss_client
  228. * @returns 0 - Netdata Exits
  229. * >0 - Error happened. Reconnect and start over.
  230. */
  231. static int handle_connection(mqtt_wss_client client)
  232. {
  233. time_t last_periodic_query_wakeup = now_monotonic_sec();
  234. while (!netdata_exit) {
  235. // timeout 1000 to check at least once a second
  236. // for netdata_exit
  237. if (mqtt_wss_service(client, 1000) < 0){
  238. error("Connection Error or Dropped");
  239. return 1;
  240. }
  241. // mqtt_wss_service will return faster than in one second
  242. // if there is enough work to do
  243. time_t now = now_monotonic_sec();
  244. if (last_periodic_query_wakeup < now) {
  245. // wake up at least one Query Thread at least
  246. // once per second
  247. last_periodic_query_wakeup = now;
  248. QUERY_THREAD_WAKEUP;
  249. }
  250. }
  251. return 0;
  252. }
  253. inline static int aclk_popcorn_check_bump()
  254. {
  255. ACLK_SHARED_STATE_LOCK;
  256. if (unlikely(aclk_shared_state.agent_state == AGENT_INITIALIZING)) {
  257. aclk_shared_state.last_popcorn_interrupt = now_realtime_sec();
  258. ACLK_SHARED_STATE_UNLOCK;
  259. return 1;
  260. }
  261. ACLK_SHARED_STATE_UNLOCK;
  262. return 0;
  263. }
  264. static inline void queue_connect_payloads(void)
  265. {
  266. aclk_query_t query = aclk_query_new(METADATA_INFO);
  267. query->data.metadata_info.host = localhost;
  268. query->data.metadata_info.initial_on_connect = 1;
  269. aclk_queue_query(query);
  270. query = aclk_query_new(METADATA_ALARMS);
  271. query->data.metadata_alarms.initial_on_connect = 1;
  272. aclk_queue_query(query);
  273. }
  274. static inline void mqtt_connected_actions(mqtt_wss_client client)
  275. {
  276. // TODO global vars?
  277. usec_t now = now_realtime_usec();
  278. aclk_session_sec = now / USEC_PER_SEC;
  279. aclk_session_us = now % USEC_PER_SEC;
  280. mqtt_wss_subscribe(client, aclk_get_topic(ACLK_TOPICID_COMMAND), 1);
  281. aclk_stats_upd_online(1);
  282. aclk_connected = 1;
  283. aclk_pubacks_per_conn = 0;
  284. aclk_hello_msg(client);
  285. ACLK_SHARED_STATE_LOCK;
  286. if (aclk_shared_state.agent_state != AGENT_INITIALIZING) {
  287. error("Sending `connect` payload immediatelly as popcorning was finished already.");
  288. queue_connect_payloads();
  289. }
  290. ACLK_SHARED_STATE_UNLOCK;
  291. }
  292. /* Waits until agent is ready or needs to exit
  293. * @param client instance of mqtt_wss_client
  294. * @param query_threads pointer to aclk_query_threads
  295. * structure where to store data about started query threads
  296. * @return 0 - Popcorning Finished - Agent STABLE,
  297. * !0 - netdata_exit
  298. */
  299. static int wait_popcorning_finishes(mqtt_wss_client client, struct aclk_query_threads *query_threads)
  300. {
  301. time_t elapsed;
  302. int need_wait;
  303. while (!netdata_exit) {
  304. ACLK_SHARED_STATE_LOCK;
  305. if (likely(aclk_shared_state.agent_state != AGENT_INITIALIZING)) {
  306. ACLK_SHARED_STATE_UNLOCK;
  307. return 0;
  308. }
  309. elapsed = now_realtime_sec() - aclk_shared_state.last_popcorn_interrupt;
  310. if (elapsed >= ACLK_STABLE_TIMEOUT) {
  311. aclk_shared_state.agent_state = AGENT_STABLE;
  312. ACLK_SHARED_STATE_UNLOCK;
  313. error("ACLK localhost popocorn finished");
  314. if (unlikely(!query_threads->thread_list))
  315. aclk_query_threads_start(query_threads, client);
  316. queue_connect_payloads();
  317. return 0;
  318. }
  319. ACLK_SHARED_STATE_UNLOCK;
  320. need_wait = ACLK_STABLE_TIMEOUT - elapsed;
  321. error("ACLK localhost popocorn wait %d seconds longer", need_wait);
  322. sleep(need_wait);
  323. }
  324. return 1;
  325. }
  326. void aclk_graceful_disconnect(mqtt_wss_client client)
  327. {
  328. error("Preparing to Gracefully Shutdown the ACLK");
  329. aclk_queue_lock();
  330. aclk_queue_flush();
  331. aclk_shared_state.mqtt_shutdown_msg_id = aclk_send_app_layer_disconnect(client, "graceful");
  332. time_t t = now_monotonic_sec();
  333. while (!mqtt_wss_service(client, 100)) {
  334. if (now_monotonic_sec() - t >= 2) {
  335. error("Wasn't able to gracefully shutdown ACLK in time!");
  336. break;
  337. }
  338. if (aclk_shared_state.mqtt_shutdown_msg_rcvd) {
  339. error("MQTT App Layer `disconnect` message sent successfully");
  340. break;
  341. }
  342. }
  343. aclk_stats_upd_online(0);
  344. aclk_connected = 0;
  345. error("Attempting to Gracefully Shutdown MQTT/WSS connection");
  346. mqtt_wss_disconnect(client, 1000);
  347. }
  348. /* Block till aclk_reconnect_delay is satisifed or netdata_exit is signalled
  349. * @return 0 - Go ahead and connect (delay expired)
  350. * 1 - netdata_exit
  351. */
  352. #define NETDATA_EXIT_POLL_MS (MSEC_PER_SEC/4)
  353. static int aclk_block_till_recon_allowed() {
  354. // Handle reconnect exponential backoff
  355. // fnc aclk_reconnect_delay comes from ACLK Legacy @amoss
  356. // but has been modifed slightly (more randomness)
  357. unsigned long recon_delay = aclk_reconnect_delay(1);
  358. info("Wait before attempting to reconnect in %.3f seconds\n", recon_delay / (float)MSEC_PER_SEC);
  359. // we want to wake up from time to time to check netdata_exit
  360. while (recon_delay)
  361. {
  362. if (netdata_exit)
  363. return 1;
  364. if (recon_delay > NETDATA_EXIT_POLL_MS) {
  365. sleep_usec(NETDATA_EXIT_POLL_MS * USEC_PER_MS);
  366. recon_delay -= NETDATA_EXIT_POLL_MS;
  367. continue;
  368. }
  369. sleep_usec(recon_delay * USEC_PER_MS);
  370. recon_delay = 0;
  371. }
  372. return 0;
  373. }
  374. #define HTTP_PROXY_PREFIX "http://"
  375. static void set_proxy(struct mqtt_wss_proxy *out)
  376. {
  377. ACLK_PROXY_TYPE pt;
  378. const char *ptr = aclk_get_proxy(&pt);
  379. char *tmp;
  380. char *host;
  381. if (pt != PROXY_TYPE_HTTP)
  382. return;
  383. out->port = 0;
  384. if (!strncmp(ptr, HTTP_PROXY_PREFIX, strlen(HTTP_PROXY_PREFIX)))
  385. ptr += strlen(HTTP_PROXY_PREFIX);
  386. if ((tmp = strchr(ptr, '@')))
  387. ptr = tmp;
  388. if ((tmp = strchr(ptr, '/'))) {
  389. host = mallocz((tmp - ptr) + 1);
  390. memcpy(host, ptr, (tmp - ptr));
  391. host[tmp - ptr] = 0;
  392. } else
  393. host = strdupz(ptr);
  394. if ((tmp = strchr(host, ':'))) {
  395. *tmp = 0;
  396. tmp++;
  397. out->port = atoi(tmp);
  398. }
  399. if (out->port <= 0 || out->port > 65535)
  400. out->port = 8080;
  401. out->host = host;
  402. out->type = MQTT_WSS_PROXY_HTTP;
  403. }
  404. /* Attempts to make a connection to MQTT broker over WSS
  405. * @param client instance of mqtt_wss_client
  406. * @return 0 - Successfull Connection,
  407. * <0 - Irrecoverable Error -> Kill ACLK,
  408. * >0 - netdata_exit
  409. */
  410. #define CLOUD_BASE_URL_READ_RETRY 30
  411. #ifdef ACLK_SSL_ALLOW_SELF_SIGNED
  412. #define ACLK_SSL_FLAGS MQTT_WSS_SSL_ALLOW_SELF_SIGNED
  413. #else
  414. #define ACLK_SSL_FLAGS MQTT_WSS_SSL_CERT_CHECK_FULL
  415. #endif
  416. static int aclk_attempt_to_connect(mqtt_wss_client client)
  417. {
  418. char *aclk_hostname = NULL;
  419. int aclk_port;
  420. #ifndef ACLK_DISABLE_CHALLENGE
  421. char *mqtt_otp_user = NULL;
  422. char *mqtt_otp_pass = NULL;
  423. #endif
  424. json_object *lwt;
  425. while (!netdata_exit) {
  426. char *cloud_base_url = appconfig_get(&cloud_config, CONFIG_SECTION_GLOBAL, "cloud base url", NULL);
  427. if (cloud_base_url == NULL) {
  428. error("Do not move the cloud base url out of post_conf_load!!");
  429. return -1;
  430. }
  431. if (aclk_block_till_recon_allowed())
  432. return 1;
  433. info("Attempting connection now");
  434. if (aclk_decode_base_url(cloud_base_url, &aclk_hostname, &aclk_port)) {
  435. error("ACLK base URL configuration key could not be parsed. Will retry in %d seconds.", CLOUD_BASE_URL_READ_RETRY);
  436. sleep(CLOUD_BASE_URL_READ_RETRY);
  437. continue;
  438. }
  439. struct mqtt_wss_proxy proxy_conf;
  440. proxy_conf.type = MQTT_WSS_DIRECT;
  441. set_proxy(&proxy_conf);
  442. struct mqtt_connect_params mqtt_conn_params = {
  443. .clientid = "anon",
  444. .username = "anon",
  445. .password = "anon",
  446. .will_topic = aclk_get_topic(ACLK_TOPICID_METADATA),
  447. .will_msg = NULL,
  448. .will_flags = MQTT_WSS_PUB_QOS2,
  449. .keep_alive = 60
  450. };
  451. #ifndef ACLK_DISABLE_CHALLENGE
  452. aclk_get_mqtt_otp(aclk_private_key, aclk_hostname, aclk_port, &mqtt_otp_user, &mqtt_otp_pass);
  453. mqtt_conn_params.clientid = mqtt_otp_user;
  454. mqtt_conn_params.username = mqtt_otp_user;
  455. mqtt_conn_params.password = mqtt_otp_pass;
  456. #endif
  457. lwt = aclk_generate_disconnect(NULL);
  458. mqtt_conn_params.will_msg = json_object_to_json_string_ext(lwt, JSON_C_TO_STRING_PLAIN);
  459. mqtt_conn_params.will_msg_len = strlen(mqtt_conn_params.will_msg);
  460. if (!mqtt_wss_connect(client, aclk_hostname, aclk_port, &mqtt_conn_params, ACLK_SSL_FLAGS, &proxy_conf)) {
  461. json_object_put(lwt);
  462. freez(aclk_hostname);
  463. aclk_hostname = NULL;
  464. info("MQTTWSS connection succeeded");
  465. mqtt_connected_actions(client);
  466. return 0;
  467. }
  468. freez(aclk_hostname);
  469. aclk_hostname = NULL;
  470. json_object_put(lwt);
  471. error("Connect failed\n");
  472. }
  473. return 1;
  474. }
  475. /**
  476. * Main agent cloud link thread
  477. *
  478. * This thread will simply call the main event loop that handles
  479. * pending requests - both inbound and outbound
  480. *
  481. * @param ptr is a pointer to the netdata_static_thread structure.
  482. *
  483. * @return It always returns NULL
  484. */
  485. void *aclk_main(void *ptr)
  486. {
  487. struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr;
  488. struct aclk_stats_thread *stats_thread = NULL;
  489. struct aclk_query_threads query_threads;
  490. query_threads.thread_list = NULL;
  491. ACLK_PROXY_TYPE proxy_type;
  492. aclk_get_proxy(&proxy_type);
  493. if (proxy_type == PROXY_TYPE_SOCKS5) {
  494. error("SOCKS5 proxy is not supported by ACLK-NG yet.");
  495. static_thread->enabled = NETDATA_MAIN_THREAD_EXITED;
  496. return NULL;
  497. }
  498. // This thread is unusual in that it cannot be cancelled by cancel_main_threads()
  499. // as it must notify the far end that it shutdown gracefully and avoid the LWT.
  500. netdata_thread_disable_cancelability();
  501. #if defined( DISABLE_CLOUD ) || !defined( ENABLE_ACLK )
  502. info("Killing ACLK thread -> cloud functionality has been disabled");
  503. static_thread->enabled = NETDATA_MAIN_THREAD_EXITED;
  504. return NULL;
  505. #endif
  506. aclk_popcorn_check_bump(); // start localhost popcorn timer
  507. query_threads.count = read_query_thread_count();
  508. if (wait_till_cloud_enabled())
  509. goto exit;
  510. if (wait_till_agent_claim_ready())
  511. goto exit;
  512. if (!(mqttwss_client = mqtt_wss_new("mqtt_wss", aclk_mqtt_wss_log_cb, msg_callback, puback_callback))) {
  513. error("Couldn't initialize MQTT_WSS network library");
  514. goto exit;
  515. }
  516. aclk_stats_enabled = config_get_boolean(CONFIG_SECTION_CLOUD, "statistics", CONFIG_BOOLEAN_YES);
  517. if (aclk_stats_enabled) {
  518. stats_thread = callocz(1, sizeof(struct aclk_stats_thread));
  519. stats_thread->thread = mallocz(sizeof(netdata_thread_t));
  520. stats_thread->query_thread_count = query_threads.count;
  521. netdata_thread_create(
  522. stats_thread->thread, ACLK_STATS_THREAD_NAME, NETDATA_THREAD_OPTION_JOINABLE, aclk_stats_main_thread,
  523. stats_thread);
  524. }
  525. // Keep reconnecting and talking until our time has come
  526. // and the Grim Reaper (netdata_exit) calls
  527. do {
  528. if (aclk_attempt_to_connect(mqttwss_client))
  529. goto exit_full;
  530. // warning this assumes the popcorning is relative short (3s)
  531. // if that changes call mqtt_wss_service from within
  532. // to keep OpenSSL, WSS and MQTT connection alive
  533. if (wait_popcorning_finishes(mqttwss_client, &query_threads))
  534. goto exit_full;
  535. if (!handle_connection(mqttwss_client)) {
  536. aclk_stats_upd_online(0);
  537. aclk_connected = 0;
  538. }
  539. } while (!netdata_exit);
  540. aclk_graceful_disconnect(mqttwss_client);
  541. exit_full:
  542. // Tear Down
  543. QUERY_THREAD_WAKEUP_ALL;
  544. aclk_query_threads_cleanup(&query_threads);
  545. if (aclk_stats_enabled) {
  546. netdata_thread_join(*stats_thread->thread, NULL);
  547. aclk_stats_thread_cleanup();
  548. freez(stats_thread->thread);
  549. freez(stats_thread);
  550. }
  551. free_topic_cache();
  552. mqtt_wss_destroy(mqttwss_client);
  553. exit:
  554. static_thread->enabled = NETDATA_MAIN_THREAD_EXITED;
  555. return NULL;
  556. }
  557. // TODO this is taken over as workaround from old ACLK
  558. // fix this in both old and new ACLK
  559. extern void health_alarm_entry2json_nolock(BUFFER *wb, ALARM_ENTRY *ae, RRDHOST *host);
  560. void aclk_alarm_reload(void)
  561. {
  562. ACLK_SHARED_STATE_LOCK;
  563. if (unlikely(aclk_shared_state.agent_state == AGENT_INITIALIZING)) {
  564. ACLK_SHARED_STATE_UNLOCK;
  565. return;
  566. }
  567. ACLK_SHARED_STATE_UNLOCK;
  568. aclk_queue_query(aclk_query_new(METADATA_ALARMS));
  569. }
  570. int aclk_update_alarm(RRDHOST *host, ALARM_ENTRY *ae)
  571. {
  572. BUFFER *local_buffer;
  573. json_object *msg;
  574. if (host != localhost)
  575. return 0;
  576. ACLK_SHARED_STATE_LOCK;
  577. if (unlikely(aclk_shared_state.agent_state == AGENT_INITIALIZING)) {
  578. ACLK_SHARED_STATE_UNLOCK;
  579. return 0;
  580. }
  581. ACLK_SHARED_STATE_UNLOCK;
  582. local_buffer = buffer_create(NETDATA_WEB_RESPONSE_HEADER_SIZE);
  583. netdata_rwlock_rdlock(&host->health_log.alarm_log_rwlock);
  584. health_alarm_entry2json_nolock(local_buffer, ae, host);
  585. netdata_rwlock_unlock(&host->health_log.alarm_log_rwlock);
  586. msg = json_tokener_parse(local_buffer->buffer);
  587. struct aclk_query *query = aclk_query_new(ALARM_STATE_UPDATE);
  588. query->data.alarm_update = msg;
  589. aclk_queue_query(query);
  590. buffer_free(local_buffer);
  591. return 0;
  592. }
  593. int aclk_update_chart(RRDHOST *host, char *chart_name, int create)
  594. {
  595. struct aclk_query *query;
  596. if (aclk_popcorn_check_bump())
  597. return 0;
  598. query = aclk_query_new(create ? CHART_NEW : CHART_DEL);
  599. if(create) {
  600. query->data.chart_add_del.host = host;
  601. query->data.chart_add_del.chart_name = strdupz(chart_name);
  602. } else {
  603. query->data.metadata_info.host = host;
  604. query->data.metadata_info.initial_on_connect = 0;
  605. }
  606. aclk_queue_query(query);
  607. return 0;
  608. }
  609. /*
  610. * Add a new collector to the list
  611. * If it exists, update the chart count
  612. */
  613. void aclk_add_collector(RRDHOST *host, const char *plugin_name, const char *module_name)
  614. {
  615. struct aclk_query *query;
  616. struct _collector *tmp_collector;
  617. if (unlikely(!netdata_ready)) {
  618. return;
  619. }
  620. COLLECTOR_LOCK;
  621. tmp_collector = _add_collector(host->machine_guid, plugin_name, module_name);
  622. if (unlikely(tmp_collector->count != 1)) {
  623. COLLECTOR_UNLOCK;
  624. return;
  625. }
  626. COLLECTOR_UNLOCK;
  627. if (aclk_popcorn_check_bump())
  628. return;
  629. if (host != localhost)
  630. return;
  631. query = aclk_query_new(METADATA_INFO);
  632. query->data.metadata_info.host = localhost; //TODO
  633. query->data.metadata_info.initial_on_connect = 0;
  634. aclk_queue_query(query);
  635. query = aclk_query_new(METADATA_ALARMS);
  636. query->data.metadata_alarms.initial_on_connect = 0;
  637. aclk_queue_query(query);
  638. }
  639. /*
  640. * Delete a collector from the list
  641. * If the chart count reaches zero the collector will be removed
  642. * from the list by calling del_collector.
  643. *
  644. * This function will release the memory used and schedule
  645. * a cloud update
  646. */
  647. void aclk_del_collector(RRDHOST *host, const char *plugin_name, const char *module_name)
  648. {
  649. struct aclk_query *query;
  650. struct _collector *tmp_collector;
  651. if (unlikely(!netdata_ready)) {
  652. return;
  653. }
  654. COLLECTOR_LOCK;
  655. tmp_collector = _del_collector(host->machine_guid, plugin_name, module_name);
  656. if (unlikely(!tmp_collector || tmp_collector->count)) {
  657. COLLECTOR_UNLOCK;
  658. return;
  659. }
  660. debug(
  661. D_ACLK, "DEL COLLECTOR [%s:%s] -- charts %u", plugin_name ? plugin_name : "*", module_name ? module_name : "*",
  662. tmp_collector->count);
  663. COLLECTOR_UNLOCK;
  664. _free_collector(tmp_collector);
  665. if (aclk_popcorn_check_bump())
  666. return;
  667. if (host != localhost)
  668. return;
  669. query = aclk_query_new(METADATA_INFO);
  670. query->data.metadata_info.host = localhost; //TODO
  671. query->data.metadata_info.initial_on_connect = 0;
  672. aclk_queue_query(query);
  673. query = aclk_query_new(METADATA_ALARMS);
  674. query->data.metadata_alarms.initial_on_connect = 0;
  675. aclk_queue_query(query);
  676. }
  677. struct label *add_aclk_host_labels(struct label *label) {
  678. #ifdef ENABLE_ACLK
  679. ACLK_PROXY_TYPE aclk_proxy;
  680. char *proxy_str;
  681. aclk_get_proxy(&aclk_proxy);
  682. switch(aclk_proxy) {
  683. case PROXY_TYPE_SOCKS5:
  684. proxy_str = "SOCKS5";
  685. break;
  686. case PROXY_TYPE_HTTP:
  687. proxy_str = "HTTP";
  688. break;
  689. default:
  690. proxy_str = "none";
  691. break;
  692. }
  693. label = add_label_to_list(label, "_aclk_impl", "Next Generation", LABEL_SOURCE_AUTO);
  694. return add_label_to_list(label, "_aclk_proxy", proxy_str, LABEL_SOURCE_AUTO);
  695. #else
  696. return label;
  697. #endif
  698. }