sqlite_aclk.c 32 KB

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