sqlite_aclk.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "sqlite_functions.h"
  3. #include "sqlite_aclk.h"
  4. #include "sqlite_aclk_chart.h"
  5. #include "sqlite_aclk_node.h"
  6. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  7. #include "../../aclk/aclk.h"
  8. #endif
  9. const char *aclk_sync_config[] = {
  10. "CREATE TABLE IF NOT EXISTS dimension_delete (dimension_id blob, dimension_name text, chart_type_id text, "
  11. "dim_id blob, chart_id blob, host_id blob, date_created);",
  12. "CREATE INDEX IF NOT EXISTS ind_h1 ON dimension_delete (host_id);",
  13. "CREATE TRIGGER IF NOT EXISTS tr_dim_del AFTER DELETE ON dimension BEGIN INSERT INTO dimension_delete "
  14. "(dimension_id, dimension_name, chart_type_id, dim_id, chart_id, host_id, date_created)"
  15. " select old.id, old.name, c.type||\".\"||c.id, old.dim_id, old.chart_id, c.host_id, strftime('%s') FROM"
  16. " chart c WHERE c.chart_id = old.chart_id; END;",
  17. "DELETE FROM dimension_delete WHERE host_id NOT IN"
  18. " (SELECT host_id FROM host) OR strftime('%s') - date_created > 604800;",
  19. NULL,
  20. };
  21. uv_mutex_t aclk_async_lock;
  22. struct aclk_database_worker_config *aclk_thread_head = NULL;
  23. int claimed()
  24. {
  25. int rc;
  26. rrdhost_aclk_state_lock(localhost);
  27. rc = (localhost->aclk_state.claimed_id != NULL);
  28. rrdhost_aclk_state_unlock(localhost);
  29. return rc;
  30. }
  31. void aclk_add_worker_thread(struct aclk_database_worker_config *wc)
  32. {
  33. if (unlikely(!wc))
  34. return;
  35. uv_mutex_lock(&aclk_async_lock);
  36. if (unlikely(!wc->host)) {
  37. wc->next = aclk_thread_head;
  38. aclk_thread_head = wc;
  39. }
  40. uv_mutex_unlock(&aclk_async_lock);
  41. return;
  42. }
  43. void aclk_del_worker_thread(struct aclk_database_worker_config *wc)
  44. {
  45. if (unlikely(!wc))
  46. return;
  47. uv_mutex_lock(&aclk_async_lock);
  48. struct aclk_database_worker_config **tmp = &aclk_thread_head;
  49. while (*tmp && (*tmp) != wc)
  50. tmp = &(*tmp)->next;
  51. if (*tmp)
  52. *tmp = wc->next;
  53. uv_mutex_unlock(&aclk_async_lock);
  54. return;
  55. }
  56. int aclk_worker_thread_exists(char *guid)
  57. {
  58. int rc = 0;
  59. uv_mutex_lock(&aclk_async_lock);
  60. struct aclk_database_worker_config *tmp = aclk_thread_head;
  61. while (tmp && !rc) {
  62. rc = strcmp(tmp->uuid_str, guid) == 0;
  63. tmp = tmp->next;
  64. }
  65. uv_mutex_unlock(&aclk_async_lock);
  66. return rc;
  67. }
  68. void aclk_database_init_cmd_queue(struct aclk_database_worker_config *wc)
  69. {
  70. wc->cmd_queue.head = wc->cmd_queue.tail = 0;
  71. wc->queue_size = 0;
  72. fatal_assert(0 == uv_cond_init(&wc->cmd_cond));
  73. fatal_assert(0 == uv_mutex_init(&wc->cmd_mutex));
  74. }
  75. int aclk_database_enq_cmd_noblock(struct aclk_database_worker_config *wc, struct aclk_database_cmd *cmd)
  76. {
  77. unsigned queue_size;
  78. /* wait for free space in queue */
  79. uv_mutex_lock(&wc->cmd_mutex);
  80. if ((queue_size = wc->queue_size) == ACLK_DATABASE_CMD_Q_MAX_SIZE || wc->is_shutting_down) {
  81. uv_mutex_unlock(&wc->cmd_mutex);
  82. return 1;
  83. }
  84. fatal_assert(queue_size < ACLK_DATABASE_CMD_Q_MAX_SIZE);
  85. /* enqueue command */
  86. wc->cmd_queue.cmd_array[wc->cmd_queue.tail] = *cmd;
  87. wc->cmd_queue.tail = wc->cmd_queue.tail != ACLK_DATABASE_CMD_Q_MAX_SIZE - 1 ?
  88. wc->cmd_queue.tail + 1 : 0;
  89. wc->queue_size = queue_size + 1;
  90. uv_mutex_unlock(&wc->cmd_mutex);
  91. return 0;
  92. }
  93. void aclk_database_enq_cmd(struct aclk_database_worker_config *wc, struct aclk_database_cmd *cmd)
  94. {
  95. unsigned queue_size;
  96. /* wait for free space in queue */
  97. uv_mutex_lock(&wc->cmd_mutex);
  98. if (wc->is_shutting_down) {
  99. uv_mutex_unlock(&wc->cmd_mutex);
  100. return;
  101. }
  102. while ((queue_size = wc->queue_size) == ACLK_DATABASE_CMD_Q_MAX_SIZE) {
  103. uv_cond_wait(&wc->cmd_cond, &wc->cmd_mutex);
  104. }
  105. fatal_assert(queue_size < ACLK_DATABASE_CMD_Q_MAX_SIZE);
  106. /* enqueue command */
  107. wc->cmd_queue.cmd_array[wc->cmd_queue.tail] = *cmd;
  108. wc->cmd_queue.tail = wc->cmd_queue.tail != ACLK_DATABASE_CMD_Q_MAX_SIZE - 1 ?
  109. wc->cmd_queue.tail + 1 : 0;
  110. wc->queue_size = queue_size + 1;
  111. uv_mutex_unlock(&wc->cmd_mutex);
  112. /* wake up event loop */
  113. int rc = uv_async_send(&wc->async);
  114. if (unlikely(rc))
  115. debug(D_ACLK_SYNC, "Failed to wake up event loop");
  116. }
  117. struct aclk_database_cmd aclk_database_deq_cmd(struct aclk_database_worker_config* wc)
  118. {
  119. struct aclk_database_cmd ret;
  120. unsigned queue_size;
  121. uv_mutex_lock(&wc->cmd_mutex);
  122. queue_size = wc->queue_size;
  123. if (queue_size == 0 || wc->is_shutting_down) {
  124. memset(&ret, 0, sizeof(ret));
  125. ret.opcode = ACLK_DATABASE_NOOP;
  126. ret.completion = NULL;
  127. if (wc->is_shutting_down)
  128. uv_cond_signal(&wc->cmd_cond);
  129. } else {
  130. /* dequeue command */
  131. ret = wc->cmd_queue.cmd_array[wc->cmd_queue.head];
  132. if (queue_size == 1) {
  133. wc->cmd_queue.head = wc->cmd_queue.tail = 0;
  134. } else {
  135. wc->cmd_queue.head = wc->cmd_queue.head != ACLK_DATABASE_CMD_Q_MAX_SIZE - 1 ?
  136. wc->cmd_queue.head + 1 : 0;
  137. }
  138. wc->queue_size = queue_size - 1;
  139. /* wake up producers */
  140. uv_cond_signal(&wc->cmd_cond);
  141. }
  142. uv_mutex_unlock(&wc->cmd_mutex);
  143. return ret;
  144. }
  145. int aclk_worker_enq_cmd(char *node_id, struct aclk_database_cmd *cmd)
  146. {
  147. if (unlikely(!node_id || !cmd))
  148. return 0;
  149. uv_mutex_lock(&aclk_async_lock);
  150. struct aclk_database_worker_config *wc = aclk_thread_head;
  151. while (wc) {
  152. if (!strcmp(wc->node_id, node_id))
  153. break;
  154. wc = wc->next;
  155. }
  156. uv_mutex_unlock(&aclk_async_lock);
  157. if (wc)
  158. aclk_database_enq_cmd(wc, cmd);
  159. return (wc == NULL);
  160. }
  161. struct aclk_database_worker_config *find_inactive_wc_by_node_id(char *node_id)
  162. {
  163. if (unlikely(!node_id))
  164. return NULL;
  165. uv_mutex_lock(&aclk_async_lock);
  166. struct aclk_database_worker_config *wc = aclk_thread_head;
  167. while (wc) {
  168. if (!strcmp(wc->node_id, node_id))
  169. break;
  170. wc = wc->next;
  171. }
  172. uv_mutex_unlock(&aclk_async_lock);
  173. return (wc);
  174. }
  175. void aclk_sync_exit_all()
  176. {
  177. rrd_rdlock();
  178. RRDHOST *host = localhost;
  179. while(host) {
  180. struct aclk_database_worker_config *wc = host->dbsync_worker;
  181. if (wc) {
  182. wc->is_shutting_down = 1;
  183. (void) aclk_database_deq_cmd(wc);
  184. uv_cond_signal(&wc->cmd_cond);
  185. }
  186. host = host->next;
  187. }
  188. rrd_unlock();
  189. uv_mutex_lock(&aclk_async_lock);
  190. struct aclk_database_worker_config *wc = aclk_thread_head;
  191. while (wc) {
  192. wc->is_shutting_down = 1;
  193. wc = wc->next;
  194. }
  195. uv_mutex_unlock(&aclk_async_lock);
  196. }
  197. int aclk_start_sync_thread(void *data, int argc, char **argv, char **column)
  198. {
  199. char uuid_str[GUID_LEN + 1];
  200. UNUSED(data);
  201. UNUSED(argc);
  202. UNUSED(column);
  203. uuid_unparse_lower(*((uuid_t *) argv[0]), uuid_str);
  204. if (rrdhost_find_by_guid(uuid_str, 0) == localhost)
  205. return 0;
  206. sql_create_aclk_table(NULL, (uuid_t *) argv[0], (uuid_t *) argv[1]);
  207. return 0;
  208. }
  209. void sql_aclk_sync_init(void)
  210. {
  211. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  212. char *err_msg = NULL;
  213. int rc;
  214. if (unlikely(!db_meta)) {
  215. if (default_rrd_memory_mode != RRD_MEMORY_MODE_DBENGINE) {
  216. return;
  217. }
  218. error_report("Database has not been initialized");
  219. return;
  220. }
  221. info("SQLite aclk sync initialization");
  222. for (int i = 0; aclk_sync_config[i]; i++) {
  223. debug(D_ACLK_SYNC, "Executing %s", aclk_sync_config[i]);
  224. rc = sqlite3_exec(db_meta, aclk_sync_config[i], 0, 0, &err_msg);
  225. if (rc != SQLITE_OK) {
  226. error_report("SQLite error aclk sync initialization setup, rc = %d (%s)", rc, err_msg);
  227. error_report("SQLite failed statement %s", aclk_sync_config[i]);
  228. sqlite3_free(err_msg);
  229. return;
  230. }
  231. }
  232. info("SQLite aclk sync initialization completed");
  233. fatal_assert(0 == uv_mutex_init(&aclk_async_lock));
  234. rc = sqlite3_exec(db_meta, "SELECT ni.host_id, ni.node_id FROM host h, node_instance ni WHERE "
  235. "h.host_id = ni.host_id AND ni.node_id IS NOT NULL;", aclk_start_sync_thread, NULL, NULL);
  236. #endif
  237. return;
  238. }
  239. static void async_cb(uv_async_t *handle)
  240. {
  241. uv_stop(handle->loop);
  242. uv_update_time(handle->loop);
  243. debug(D_ACLK_SYNC, "%s called, active=%d.", __func__, uv_is_active((uv_handle_t *)handle));
  244. }
  245. #define TIMER_PERIOD_MS (1000)
  246. static void timer_cb(uv_timer_t* handle)
  247. {
  248. uv_stop(handle->loop);
  249. uv_update_time(handle->loop);
  250. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  251. struct aclk_database_worker_config *wc = handle->data;
  252. struct aclk_database_cmd cmd;
  253. memset(&cmd, 0, sizeof(cmd));
  254. cmd.opcode = ACLK_DATABASE_TIMER;
  255. aclk_database_enq_cmd_noblock(wc, &cmd);
  256. time_t now = now_realtime_sec();
  257. if (wc->cleanup_after && wc->cleanup_after < now) {
  258. cmd.opcode = ACLK_DATABASE_CLEANUP;
  259. if (!aclk_database_enq_cmd_noblock(wc, &cmd))
  260. wc->cleanup_after += ACLK_DATABASE_CLEANUP_INTERVAL;
  261. }
  262. if (aclk_use_new_cloud_arch && aclk_connected) {
  263. if (wc->rotation_after && wc->rotation_after < now) {
  264. cmd.opcode = ACLK_DATABASE_NODE_INFO;
  265. aclk_database_enq_cmd_noblock(wc, &cmd);
  266. cmd.opcode = ACLK_DATABASE_UPD_RETENTION;
  267. if (!aclk_database_enq_cmd_noblock(wc, &cmd))
  268. wc->rotation_after += ACLK_DATABASE_ROTATION_INTERVAL;
  269. }
  270. if (wc->chart_updates && !wc->chart_pending && wc->chart_payload_count) {
  271. cmd.opcode = ACLK_DATABASE_PUSH_CHART;
  272. cmd.count = ACLK_MAX_CHART_BATCH;
  273. cmd.param1 = ACLK_MAX_CHART_BATCH_COUNT;
  274. if (!aclk_database_enq_cmd_noblock(wc, &cmd)) {
  275. if (wc->retry_count)
  276. info("Queued chart/dimension payload command %s, retry count = %u", wc->host_guid, wc->retry_count);
  277. wc->chart_pending = 1;
  278. wc->retry_count = 0;
  279. } else {
  280. wc->retry_count++;
  281. if (wc->retry_count % 100 == 0)
  282. error_report("Failed to queue chart/dimension payload command %s, retry count = %u",
  283. wc->host_guid,
  284. wc->retry_count);
  285. }
  286. }
  287. if (wc->alert_updates) {
  288. cmd.opcode = ACLK_DATABASE_PUSH_ALERT;
  289. cmd.count = ACLK_MAX_ALERT_UPDATES;
  290. aclk_database_enq_cmd_noblock(wc, &cmd);
  291. }
  292. }
  293. #endif
  294. }
  295. #define MAX_CMD_BATCH_SIZE (256)
  296. void aclk_database_worker(void *arg)
  297. {
  298. struct aclk_database_worker_config *wc = arg;
  299. uv_loop_t *loop;
  300. int ret;
  301. enum aclk_database_opcode opcode;
  302. uv_timer_t timer_req;
  303. struct aclk_database_cmd cmd;
  304. unsigned cmd_batch_size;
  305. //aclk_database_init_cmd_queue(wc);
  306. char threadname[NETDATA_THREAD_NAME_MAX+1];
  307. if (wc->host)
  308. snprintfz(threadname, NETDATA_THREAD_NAME_MAX, "AS_%s", wc->host->hostname);
  309. else {
  310. snprintfz(threadname, NETDATA_THREAD_NAME_MAX, "AS_%s", wc->uuid_str);
  311. threadname[11] = '\0';
  312. }
  313. uv_thread_set_name_np(wc->thread, threadname);
  314. loop = wc->loop = mallocz(sizeof(uv_loop_t));
  315. ret = uv_loop_init(loop);
  316. if (ret) {
  317. error("uv_loop_init(): %s", uv_strerror(ret));
  318. goto error_after_loop_init;
  319. }
  320. loop->data = wc;
  321. ret = uv_async_init(wc->loop, &wc->async, async_cb);
  322. if (ret) {
  323. error("uv_async_init(): %s", uv_strerror(ret));
  324. goto error_after_async_init;
  325. }
  326. wc->async.data = wc;
  327. ret = uv_timer_init(loop, &timer_req);
  328. if (ret) {
  329. error("uv_timer_init(): %s", uv_strerror(ret));
  330. goto error_after_timer_init;
  331. }
  332. timer_req.data = wc;
  333. fatal_assert(0 == uv_timer_start(&timer_req, timer_cb, TIMER_PERIOD_MS, TIMER_PERIOD_MS));
  334. // wc->retry_count = 0;
  335. wc->node_info_send = (wc->host && !localhost);
  336. // aclk_add_worker_thread(wc);
  337. info("Starting ACLK sync thread for host %s -- scratch area %lu bytes", wc->host_guid, sizeof(*wc));
  338. memset(&cmd, 0, sizeof(cmd));
  339. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  340. sql_get_last_chart_sequence(wc);
  341. wc->chart_payload_count = sql_get_pending_count(wc);
  342. if (!wc->chart_payload_count)
  343. info("%s: No pending charts and dimensions detected during startup", wc->host_guid);
  344. #endif
  345. wc->startup_time = now_realtime_sec();
  346. wc->cleanup_after = wc->startup_time + ACLK_DATABASE_CLEANUP_FIRST;
  347. wc->rotation_after = wc->startup_time + ACLK_DATABASE_ROTATION_DELAY;
  348. debug(D_ACLK_SYNC,"Node %s reports pending message count = %u", wc->node_id, wc->chart_payload_count);
  349. while (likely(!netdata_exit)) {
  350. uv_run(loop, UV_RUN_DEFAULT);
  351. /* wait for commands */
  352. cmd_batch_size = 0;
  353. do {
  354. if (unlikely(cmd_batch_size >= MAX_CMD_BATCH_SIZE))
  355. break;
  356. cmd = aclk_database_deq_cmd(wc);
  357. if (netdata_exit)
  358. break;
  359. opcode = cmd.opcode;
  360. ++cmd_batch_size;
  361. switch (opcode) {
  362. case ACLK_DATABASE_NOOP:
  363. /* the command queue was empty, do nothing */
  364. break;
  365. // MAINTENANCE
  366. case ACLK_DATABASE_CLEANUP:
  367. debug(D_ACLK_SYNC, "Database cleanup for %s", wc->host_guid);
  368. sql_maint_aclk_sync_database(wc, cmd);
  369. if (wc->host == localhost)
  370. sql_check_aclk_table_list(wc);
  371. break;
  372. case ACLK_DATABASE_DELETE_HOST:
  373. debug(D_ACLK_SYNC,"Cleaning ACLK tables for %s", (char *) cmd.data);
  374. sql_delete_aclk_table_list(wc, cmd);
  375. break;
  376. // CHART / DIMENSION OPERATIONS
  377. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  378. case ACLK_DATABASE_ADD_CHART:
  379. debug(D_ACLK_SYNC, "Adding chart event for %s", wc->host_guid);
  380. aclk_add_chart_event(wc, cmd);
  381. break;
  382. case ACLK_DATABASE_ADD_DIMENSION:
  383. debug(D_ACLK_SYNC, "Adding dimension event for %s", wc->host_guid);
  384. aclk_add_dimension_event(wc, cmd);
  385. break;
  386. case ACLK_DATABASE_PUSH_CHART:
  387. debug(D_ACLK_SYNC, "Pushing chart info to the cloud for node %s", wc->host_guid);
  388. aclk_send_chart_event(wc, cmd);
  389. break;
  390. case ACLK_DATABASE_PUSH_CHART_CONFIG:
  391. debug(D_ACLK_SYNC, "Pushing chart config info to the cloud for node %s", wc->host_guid);
  392. aclk_send_chart_config(wc, cmd);
  393. break;
  394. case ACLK_DATABASE_CHART_ACK:
  395. debug(D_ACLK_SYNC, "ACK chart SEQ for %s to %"PRIu64, wc->uuid_str, (uint64_t) cmd.param1);
  396. aclk_receive_chart_ack(wc, cmd);
  397. break;
  398. case ACLK_DATABASE_RESET_CHART:
  399. debug(D_ACLK_SYNC, "RESET chart SEQ for %s to %"PRIu64, wc->uuid_str, (uint64_t) cmd.param1);
  400. aclk_receive_chart_reset(wc, cmd);
  401. break;
  402. #endif
  403. // ALERTS
  404. case ACLK_DATABASE_PUSH_ALERT_CONFIG:
  405. debug(D_ACLK_SYNC,"Pushing chart config info to the cloud for %s", wc->host_guid);
  406. aclk_push_alert_config_event(wc, cmd);
  407. break;
  408. case ACLK_DATABASE_PUSH_ALERT:
  409. debug(D_ACLK_SYNC, "Pushing alert info to the cloud for %s", wc->host_guid);
  410. aclk_push_alert_event(wc, cmd);
  411. break;
  412. case ACLK_DATABASE_ALARM_HEALTH_LOG:
  413. debug(D_ACLK_SYNC, "Pushing alarm health log to the cloud for %s", wc->host_guid);
  414. aclk_push_alarm_health_log(wc, cmd);
  415. break;
  416. case ACLK_DATABASE_PUSH_ALERT_SNAPSHOT:
  417. debug(D_ACLK_SYNC, "Pushing alert snapshot to the cloud for node %s", wc->host_guid);
  418. aclk_push_alert_snapshot_event(wc, cmd);
  419. break;
  420. case ACLK_DATABASE_QUEUE_REMOVED_ALERTS:
  421. debug(D_ACLK_SYNC, "Queueing removed alerts for node %s", wc->host_guid);
  422. sql_process_queue_removed_alerts_to_aclk(wc, cmd);
  423. break;
  424. // NODE OPERATIONS
  425. case ACLK_DATABASE_NODE_INFO:
  426. debug(D_ACLK_SYNC,"Sending node info for %s", wc->uuid_str);
  427. sql_build_node_info(wc, cmd);
  428. break;
  429. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  430. case ACLK_DATABASE_DIM_DELETION:
  431. debug(D_ACLK_SYNC,"Sending dimension deletion information %s", wc->uuid_str);
  432. aclk_process_dimension_deletion(wc, cmd);
  433. break;
  434. case ACLK_DATABASE_UPD_RETENTION:
  435. debug(D_ACLK_SYNC,"Sending retention info for %s", wc->uuid_str);
  436. aclk_update_retention(wc, cmd);
  437. aclk_process_dimension_deletion(wc, cmd);
  438. break;
  439. // NODE_INSTANCE DETECTION
  440. case ACLK_DATABASE_ORPHAN_HOST:
  441. wc->host = NULL;
  442. wc->is_orphan = 1;
  443. aclk_add_worker_thread(wc);
  444. break;
  445. #endif
  446. case ACLK_DATABASE_TIMER:
  447. if (unlikely(localhost && !wc->host && !wc->is_orphan)) {
  448. if (claimed()) {
  449. wc->host = rrdhost_find_by_guid(wc->host_guid, 0);
  450. if (wc->host) {
  451. info("HOST %s (%s) detected as active", wc->host->hostname, wc->host_guid);
  452. snprintfz(threadname, NETDATA_THREAD_NAME_MAX, "AS_%s", wc->host->hostname);
  453. uv_thread_set_name_np(wc->thread, threadname);
  454. wc->host->dbsync_worker = wc;
  455. aclk_del_worker_thread(wc);
  456. wc->node_info_send = 1;
  457. }
  458. }
  459. }
  460. if (wc->node_info_send && wc->host && localhost && claimed() && aclk_connected) {
  461. cmd.opcode = ACLK_DATABASE_NODE_INFO;
  462. cmd.completion = NULL;
  463. wc->node_info_send = aclk_database_enq_cmd_noblock(wc, &cmd);
  464. }
  465. break;
  466. default:
  467. debug(D_ACLK_SYNC, "%s: default.", __func__);
  468. break;
  469. }
  470. if (cmd.completion)
  471. aclk_complete(cmd.completion);
  472. } while (opcode != ACLK_DATABASE_NOOP);
  473. }
  474. if (!uv_timer_stop(&timer_req))
  475. uv_close((uv_handle_t *)&timer_req, NULL);
  476. /* cleanup operations of the event loop */
  477. //info("Shutting down ACLK sync event loop for %s", wc->host_guid);
  478. /*
  479. * uv_async_send after uv_close does not seem to crash in linux at the moment,
  480. * it is however undocumented behaviour we need to be aware if this becomes
  481. * an issue in the future.
  482. */
  483. uv_close((uv_handle_t *)&wc->async, NULL);
  484. uv_run(loop, UV_RUN_DEFAULT);
  485. info("Shutting down ACLK sync event loop complete for host %s", wc->host_guid);
  486. /* TODO: don't let the API block by waiting to enqueue commands */
  487. uv_cond_destroy(&wc->cmd_cond);
  488. /* uv_mutex_destroy(&wc->cmd_mutex); */
  489. //fatal_assert(0 == uv_loop_close(loop));
  490. int rc;
  491. do {
  492. rc = uv_loop_close(loop);
  493. } while (rc != UV_EBUSY);
  494. freez(loop);
  495. rrd_rdlock();
  496. if (likely(wc->host))
  497. wc->host->dbsync_worker = NULL;
  498. freez(wc);
  499. rrd_unlock();
  500. return;
  501. error_after_timer_init:
  502. uv_close((uv_handle_t *)&wc->async, NULL);
  503. error_after_async_init:
  504. fatal_assert(0 == uv_loop_close(loop));
  505. error_after_loop_init:
  506. freez(loop);
  507. }
  508. // -------------------------------------------------------------
  509. void sql_create_aclk_table(RRDHOST *host, uuid_t *host_uuid, uuid_t *node_id)
  510. {
  511. #ifdef ENABLE_ACLK
  512. char uuid_str[GUID_LEN + 1];
  513. char host_guid[GUID_LEN + 1];
  514. uuid_unparse_lower_fix(host_uuid, uuid_str);
  515. if (aclk_worker_thread_exists(uuid_str))
  516. return;
  517. uuid_unparse_lower(*host_uuid, host_guid);
  518. BUFFER *sql = buffer_create(ACLK_SYNC_QUERY_SIZE);
  519. buffer_sprintf(sql, TABLE_ACLK_CHART, uuid_str);
  520. db_execute(buffer_tostring(sql));
  521. buffer_flush(sql);
  522. buffer_sprintf(sql, TABLE_ACLK_CHART_PAYLOAD, uuid_str);
  523. db_execute(buffer_tostring(sql));
  524. buffer_flush(sql);
  525. buffer_sprintf(sql, TABLE_ACLK_CHART_LATEST, uuid_str);
  526. db_execute(buffer_tostring(sql));
  527. buffer_flush(sql);
  528. buffer_sprintf(sql, INDEX_ACLK_CHART, uuid_str, uuid_str);
  529. db_execute(buffer_tostring(sql));
  530. buffer_flush(sql);
  531. buffer_sprintf(sql, INDEX_ACLK_CHART_LATEST, uuid_str, uuid_str);
  532. db_execute(buffer_tostring(sql));
  533. buffer_flush(sql);
  534. buffer_sprintf(sql, TRIGGER_ACLK_CHART_PAYLOAD, uuid_str, uuid_str, uuid_str);
  535. db_execute(buffer_tostring(sql));
  536. buffer_flush(sql);
  537. buffer_sprintf(sql, TABLE_ACLK_ALERT, uuid_str, uuid_str, uuid_str);
  538. db_execute(buffer_tostring(sql));
  539. buffer_flush(sql);
  540. buffer_sprintf(sql, INDEX_ACLK_ALERT, uuid_str, uuid_str);
  541. db_execute(buffer_tostring(sql));
  542. buffer_free(sql);
  543. if (likely(host) && unlikely(host->dbsync_worker))
  544. return;
  545. struct aclk_database_worker_config *wc = callocz(1, sizeof(struct aclk_database_worker_config));
  546. if (likely(host))
  547. host->dbsync_worker = (void *) wc;
  548. wc->host = host;
  549. strcpy(wc->uuid_str, uuid_str);
  550. strcpy(wc->host_guid, host_guid);
  551. if (node_id && !uuid_is_null(*node_id))
  552. uuid_unparse_lower(*node_id, wc->node_id);
  553. wc->chart_updates = 0;
  554. wc->alert_updates = 0;
  555. wc->retry_count = 0;
  556. aclk_database_init_cmd_queue(wc);
  557. aclk_add_worker_thread(wc);
  558. fatal_assert(0 == uv_thread_create(&(wc->thread), aclk_database_worker, wc));
  559. #else
  560. UNUSED(host);
  561. UNUSED(host_uuid);
  562. UNUSED(node_id);
  563. #endif
  564. return;
  565. }
  566. void sql_maint_aclk_sync_database(struct aclk_database_worker_config *wc, struct aclk_database_cmd cmd)
  567. {
  568. UNUSED(cmd);
  569. debug(D_ACLK, "Checking database for %s", wc->host_guid);
  570. BUFFER *sql = buffer_create(ACLK_SYNC_QUERY_SIZE);
  571. buffer_sprintf(sql,"DELETE FROM aclk_chart_%s WHERE date_submitted IS NOT NULL AND "
  572. "date_updated < strftime('%%s','now','-%d seconds');", wc->uuid_str, ACLK_DELETE_ACK_INTERNAL);
  573. db_execute(buffer_tostring(sql));
  574. buffer_flush(sql);
  575. buffer_sprintf(sql,"DELETE FROM aclk_chart_payload_%s WHERE unique_id NOT IN "
  576. "(SELECT unique_id FROM aclk_chart_%s) AND unique_id NOT IN (SELECT unique_id FROM aclk_chart_latest_%s);",
  577. wc->uuid_str, wc->uuid_str, wc->uuid_str);
  578. db_execute(buffer_tostring(sql));
  579. buffer_flush(sql);
  580. buffer_sprintf(sql,"DELETE FROM aclk_alert_%s WHERE date_submitted IS NOT NULL AND "
  581. "date_cloud_ack < strftime('%%s','now','-%d seconds');", wc->uuid_str, ACLK_DELETE_ACK_ALERTS_INTERNAL);
  582. db_execute(buffer_tostring(sql));
  583. buffer_free(sql);
  584. return;
  585. }
  586. #define SQL_SELECT_HOST_BY_UUID "SELECT host_id FROM host WHERE host_id = @host_id;"
  587. static int is_host_available(uuid_t *host_id)
  588. {
  589. sqlite3_stmt *res = NULL;
  590. int rc;
  591. if (unlikely(!db_meta)) {
  592. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  593. error_report("Database has not been initialized");
  594. return 1;
  595. }
  596. rc = sqlite3_prepare_v2(db_meta, SQL_SELECT_HOST_BY_UUID, -1, &res, 0);
  597. if (unlikely(rc != SQLITE_OK)) {
  598. error_report("Failed to prepare statement to select node instance information for a node");
  599. return 1;
  600. }
  601. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  602. if (unlikely(rc != SQLITE_OK)) {
  603. error_report("Failed to bind host_id parameter to select node instance information");
  604. goto failed;
  605. }
  606. rc = sqlite3_step(res);
  607. failed:
  608. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  609. error_report("Failed to finalize the prepared statement when checking host existence");
  610. return (rc == SQLITE_ROW);
  611. }
  612. // OPCODE: ACLK_DATABASE_DELETE_HOST
  613. void sql_delete_aclk_table_list(struct aclk_database_worker_config *wc, struct aclk_database_cmd cmd)
  614. {
  615. UNUSED(wc);
  616. char uuid_str[GUID_LEN + 1];
  617. char host_str[GUID_LEN + 1];
  618. int rc;
  619. uuid_t host_uuid;
  620. char *host_guid = (char *)cmd.data;
  621. if (unlikely(!host_guid))
  622. return;
  623. rc = uuid_parse(host_guid, host_uuid);
  624. freez(host_guid);
  625. if (rc)
  626. return;
  627. uuid_unparse_lower(host_uuid, host_str);
  628. uuid_unparse_lower_fix(&host_uuid, uuid_str);
  629. debug(D_ACLK_SYNC, "Checking if I should delete aclk tables for node %s", host_str);
  630. if (is_host_available(&host_uuid)) {
  631. debug(D_ACLK_SYNC, "Host %s exists, not deleting aclk sync tables", host_str);
  632. return;
  633. }
  634. debug(D_ACLK_SYNC, "Host %s does NOT exist, can delete aclk sync tables", host_str);
  635. sqlite3_stmt *res = NULL;
  636. BUFFER *sql = buffer_create(ACLK_SYNC_QUERY_SIZE);
  637. buffer_sprintf(sql,"SELECT 'drop '||type||' IF EXISTS '||name||';' FROM sqlite_schema " \
  638. "WHERE name LIKE 'aclk_%%_%s' AND type IN ('table', 'trigger', 'index');", uuid_str);
  639. rc = sqlite3_prepare_v2(db_meta, buffer_tostring(sql), -1, &res, 0);
  640. if (rc != SQLITE_OK) {
  641. error_report("Failed to prepare statement to clean up aclk tables");
  642. goto fail;
  643. }
  644. buffer_flush(sql);
  645. while (sqlite3_step(res) == SQLITE_ROW)
  646. buffer_strcat(sql, (char *) sqlite3_column_text(res, 0));
  647. rc = sqlite3_finalize(res);
  648. if (unlikely(rc != SQLITE_OK))
  649. error_report("Failed to finalize statement to clean up aclk tables, rc = %d", rc);
  650. db_execute(buffer_tostring(sql));
  651. fail:
  652. buffer_free(sql);
  653. return;
  654. }
  655. static int sql_check_aclk_table(void *data, int argc, char **argv, char **column)
  656. {
  657. struct aclk_database_worker_config *wc = data;
  658. UNUSED(argc);
  659. UNUSED(column);
  660. debug(D_ACLK_SYNC,"Scheduling aclk sync table check for node %s", (char *) argv[0]);
  661. struct aclk_database_cmd cmd;
  662. memset(&cmd, 0, sizeof(cmd));
  663. cmd.opcode = ACLK_DATABASE_DELETE_HOST;
  664. cmd.data = strdupz((char *) argv[0]);
  665. aclk_database_enq_cmd_noblock(wc, &cmd);
  666. return 0;
  667. }
  668. #define SQL_SELECT_ACLK_ACTIVE_LIST "SELECT REPLACE(SUBSTR(name,19),'_','-') FROM sqlite_schema " \
  669. "WHERE name LIKE 'aclk_chart_latest_%' AND type IN ('table');"
  670. void sql_check_aclk_table_list(struct aclk_database_worker_config *wc)
  671. {
  672. char *err_msg = NULL;
  673. debug(D_ACLK_SYNC,"Cleaning tables for nodes that do not exist");
  674. int rc = sqlite3_exec(db_meta, SQL_SELECT_ACLK_ACTIVE_LIST, sql_check_aclk_table, (void *) wc, &err_msg);
  675. if (rc != SQLITE_OK) {
  676. error_report("Query failed when trying to check for obsolete ACLK sync tables, %s", err_msg);
  677. sqlite3_free(err_msg);
  678. }
  679. db_execute("DELETE FROM dimension_delete WHERE host_id NOT IN (SELECT host_id FROM host) "
  680. " OR strftime('%s') - date_created > 604800;");
  681. return;
  682. }
  683. void aclk_data_rotated(void)
  684. {
  685. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  686. if (!aclk_use_new_cloud_arch || !aclk_connected)
  687. return;
  688. time_t next_rotation_time = now_realtime_sec()+ACLK_DATABASE_ROTATION_DELAY;
  689. rrd_rdlock();
  690. RRDHOST *this_host = localhost;
  691. while (this_host) {
  692. struct aclk_database_worker_config *wc = this_host->dbsync_worker;
  693. if (wc)
  694. wc->rotation_after = next_rotation_time;
  695. this_host = this_host->next;
  696. }
  697. rrd_unlock();
  698. struct aclk_database_worker_config *tmp = aclk_thread_head;
  699. uv_mutex_lock(&aclk_async_lock);
  700. while (tmp) {
  701. tmp->rotation_after = next_rotation_time;
  702. tmp = tmp->next;
  703. }
  704. uv_mutex_unlock(&aclk_async_lock);
  705. #endif
  706. return;
  707. }