sqlite_aclk.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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. 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, strftime('%s') 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 strftime('%s') - 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_NEW_CLOUD_PROTOCOL
  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_NEW_CLOUD_PROTOCOL
  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_NEW_CLOUD_PROTOCOL
  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_use_new_cloud_arch && 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_NEW_CLOUD_PROTOCOL
  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. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  347. worker_register_job_name(ACLK_DATABASE_ADD_CHART, "chart add");
  348. worker_register_job_name(ACLK_DATABASE_ADD_DIMENSION, "dimension add");
  349. worker_register_job_name(ACLK_DATABASE_PUSH_CHART, "chart push");
  350. worker_register_job_name(ACLK_DATABASE_PUSH_CHART_CONFIG, "chart conf push");
  351. worker_register_job_name(ACLK_DATABASE_RESET_CHART, "chart reset");
  352. worker_register_job_name(ACLK_DATABASE_CHART_ACK, "chart ack");
  353. worker_register_job_name(ACLK_DATABASE_UPD_RETENTION, "retention check");
  354. worker_register_job_name(ACLK_DATABASE_DIM_DELETION, "dimension delete");
  355. worker_register_job_name(ACLK_DATABASE_ORPHAN_HOST, "node orphan");
  356. #endif
  357. worker_register_job_name(ACLK_DATABASE_ALARM_HEALTH_LOG, "alert log");
  358. worker_register_job_name(ACLK_DATABASE_CLEANUP, "cleanup");
  359. worker_register_job_name(ACLK_DATABASE_DELETE_HOST, "node delete");
  360. worker_register_job_name(ACLK_DATABASE_NODE_INFO, "node info");
  361. worker_register_job_name(ACLK_DATABASE_PUSH_ALERT, "alert push");
  362. worker_register_job_name(ACLK_DATABASE_PUSH_ALERT_CONFIG, "alert conf push");
  363. worker_register_job_name(ACLK_DATABASE_PUSH_ALERT_SNAPSHOT, "alert snapshot");
  364. worker_register_job_name(ACLK_DATABASE_QUEUE_REMOVED_ALERTS, "alerts check");
  365. worker_register_job_name(ACLK_DATABASE_TIMER, "timer");
  366. struct aclk_database_worker_config *wc = arg;
  367. uv_loop_t *loop;
  368. int ret;
  369. enum aclk_database_opcode opcode;
  370. uv_timer_t timer_req;
  371. struct aclk_database_cmd cmd;
  372. unsigned cmd_batch_size;
  373. //aclk_database_init_cmd_queue(wc);
  374. char threadname[NETDATA_THREAD_NAME_MAX+1];
  375. if (wc->host)
  376. snprintfz(threadname, NETDATA_THREAD_NAME_MAX, "AS_%s", wc->host->hostname);
  377. else {
  378. snprintfz(threadname, NETDATA_THREAD_NAME_MAX, "AS_%s", wc->uuid_str);
  379. threadname[11] = '\0';
  380. }
  381. uv_thread_set_name_np(wc->thread, threadname);
  382. loop = wc->loop = mallocz(sizeof(uv_loop_t));
  383. ret = uv_loop_init(loop);
  384. if (ret) {
  385. error("uv_loop_init(): %s", uv_strerror(ret));
  386. goto error_after_loop_init;
  387. }
  388. loop->data = wc;
  389. ret = uv_async_init(wc->loop, &wc->async, async_cb);
  390. if (ret) {
  391. error("uv_async_init(): %s", uv_strerror(ret));
  392. goto error_after_async_init;
  393. }
  394. wc->async.data = wc;
  395. ret = uv_timer_init(loop, &timer_req);
  396. if (ret) {
  397. error("uv_timer_init(): %s", uv_strerror(ret));
  398. goto error_after_timer_init;
  399. }
  400. timer_req.data = wc;
  401. fatal_assert(0 == uv_timer_start(&timer_req, timer_cb, TIMER_PERIOD_MS, TIMER_PERIOD_MS));
  402. // wc->retry_count = 0;
  403. wc->node_info_send = (wc->host && !localhost);
  404. // aclk_add_worker_thread(wc);
  405. info("Starting ACLK sync thread for host %s -- scratch area %lu bytes", wc->host_guid, sizeof(*wc));
  406. memset(&cmd, 0, sizeof(cmd));
  407. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  408. uv_work_t retention_work;
  409. sql_get_last_chart_sequence(wc);
  410. wc->chart_payload_count = sql_get_pending_count(wc);
  411. if (!wc->chart_payload_count)
  412. info("%s: No pending charts and dimensions detected during startup", wc->host_guid);
  413. #endif
  414. wc->startup_time = now_realtime_sec();
  415. wc->cleanup_after = wc->startup_time + ACLK_DATABASE_CLEANUP_FIRST;
  416. wc->rotation_after = wc->startup_time + ACLK_DATABASE_ROTATION_DELAY;
  417. debug(D_ACLK_SYNC,"Node %s reports pending message count = %u", wc->node_id, wc->chart_payload_count);
  418. while (likely(!netdata_exit)) {
  419. worker_is_idle();
  420. uv_run(loop, UV_RUN_DEFAULT);
  421. /* wait for commands */
  422. cmd_batch_size = 0;
  423. do {
  424. if (unlikely(cmd_batch_size >= MAX_CMD_BATCH_SIZE))
  425. break;
  426. cmd = aclk_database_deq_cmd(wc);
  427. if (netdata_exit)
  428. break;
  429. opcode = cmd.opcode;
  430. ++cmd_batch_size;
  431. if(likely(opcode != ACLK_DATABASE_NOOP))
  432. worker_is_busy(opcode);
  433. switch (opcode) {
  434. case ACLK_DATABASE_NOOP:
  435. /* the command queue was empty, do nothing */
  436. break;
  437. // MAINTENANCE
  438. case ACLK_DATABASE_CLEANUP:
  439. debug(D_ACLK_SYNC, "Database cleanup for %s", wc->host_guid);
  440. sql_maint_aclk_sync_database(wc, cmd);
  441. if (wc->host == localhost)
  442. sql_check_aclk_table_list(wc);
  443. break;
  444. case ACLK_DATABASE_DELETE_HOST:
  445. debug(D_ACLK_SYNC,"Cleaning ACLK tables for %s", (char *) cmd.data);
  446. sql_delete_aclk_table_list(wc, cmd);
  447. break;
  448. // CHART / DIMENSION OPERATIONS
  449. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  450. case ACLK_DATABASE_ADD_CHART:
  451. debug(D_ACLK_SYNC, "Adding chart event for %s", wc->host_guid);
  452. aclk_add_chart_event(wc, cmd);
  453. break;
  454. case ACLK_DATABASE_ADD_DIMENSION:
  455. debug(D_ACLK_SYNC, "Adding dimension event for %s", wc->host_guid);
  456. aclk_add_dimension_event(wc, cmd);
  457. break;
  458. case ACLK_DATABASE_PUSH_CHART:
  459. debug(D_ACLK_SYNC, "Pushing chart info to the cloud for node %s", wc->host_guid);
  460. aclk_send_chart_event(wc, cmd);
  461. break;
  462. case ACLK_DATABASE_PUSH_CHART_CONFIG:
  463. debug(D_ACLK_SYNC, "Pushing chart config info to the cloud for node %s", wc->host_guid);
  464. aclk_send_chart_config(wc, cmd);
  465. break;
  466. case ACLK_DATABASE_CHART_ACK:
  467. debug(D_ACLK_SYNC, "ACK chart SEQ for %s to %"PRIu64, wc->uuid_str, (uint64_t) cmd.param1);
  468. aclk_receive_chart_ack(wc, cmd);
  469. break;
  470. case ACLK_DATABASE_RESET_CHART:
  471. debug(D_ACLK_SYNC, "RESET chart SEQ for %s to %"PRIu64, wc->uuid_str, (uint64_t) cmd.param1);
  472. aclk_receive_chart_reset(wc, cmd);
  473. break;
  474. #endif
  475. // ALERTS
  476. case ACLK_DATABASE_PUSH_ALERT_CONFIG:
  477. debug(D_ACLK_SYNC,"Pushing chart config info to the cloud for %s", wc->host_guid);
  478. aclk_push_alert_config_event(wc, cmd);
  479. break;
  480. case ACLK_DATABASE_PUSH_ALERT:
  481. debug(D_ACLK_SYNC, "Pushing alert info to the cloud for %s", wc->host_guid);
  482. aclk_push_alert_event(wc, cmd);
  483. break;
  484. case ACLK_DATABASE_ALARM_HEALTH_LOG:
  485. debug(D_ACLK_SYNC, "Pushing alarm health log to the cloud for %s", wc->host_guid);
  486. aclk_push_alarm_health_log(wc, cmd);
  487. break;
  488. case ACLK_DATABASE_PUSH_ALERT_SNAPSHOT:
  489. debug(D_ACLK_SYNC, "Pushing alert snapshot to the cloud for node %s", wc->host_guid);
  490. aclk_push_alert_snapshot_event(wc, cmd);
  491. break;
  492. case ACLK_DATABASE_QUEUE_REMOVED_ALERTS:
  493. debug(D_ACLK_SYNC, "Queueing removed alerts for node %s", wc->host_guid);
  494. sql_process_queue_removed_alerts_to_aclk(wc, cmd);
  495. break;
  496. // NODE OPERATIONS
  497. case ACLK_DATABASE_NODE_INFO:
  498. debug(D_ACLK_SYNC,"Sending node info for %s", wc->uuid_str);
  499. sql_build_node_info(wc, cmd);
  500. break;
  501. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  502. case ACLK_DATABASE_DIM_DELETION:
  503. debug(D_ACLK_SYNC,"Sending dimension deletion information %s", wc->uuid_str);
  504. aclk_process_dimension_deletion(wc, cmd);
  505. break;
  506. case ACLK_DATABASE_UPD_RETENTION:
  507. if (unlikely(wc->retention_running))
  508. break;
  509. if (unlikely(request_retention_run())) {
  510. wc->rotation_after = now_realtime_sec() + ACLK_DATABASE_RETENTION_RETRY;
  511. break;
  512. }
  513. debug(D_ACLK_SYNC,"Sending retention info for %s", wc->uuid_str);
  514. retention_work.data = wc;
  515. wc->retention_running = 1;
  516. if (unlikely(uv_queue_work(loop, &retention_work, send_retention, after_send_retention))) {
  517. wc->retention_running = 0;
  518. stop_retention_run();
  519. }
  520. break;
  521. // NODE_INSTANCE DETECTION
  522. case ACLK_DATABASE_ORPHAN_HOST:
  523. wc->host = NULL;
  524. wc->is_orphan = 1;
  525. aclk_add_worker_thread(wc);
  526. break;
  527. #endif
  528. case ACLK_DATABASE_TIMER:
  529. if (unlikely(localhost && !wc->host && !wc->is_orphan)) {
  530. if (claimed()) {
  531. wc->host = rrdhost_find_by_guid(wc->host_guid, 0);
  532. if (wc->host) {
  533. info("HOST %s (%s) detected as active", wc->host->hostname, wc->host_guid);
  534. snprintfz(threadname, NETDATA_THREAD_NAME_MAX, "AS_%s", wc->host->hostname);
  535. uv_thread_set_name_np(wc->thread, threadname);
  536. wc->host->dbsync_worker = wc;
  537. aclk_del_worker_thread(wc);
  538. wc->node_info_send = 1;
  539. }
  540. }
  541. }
  542. if (wc->node_info_send && wc->host && localhost && claimed() && aclk_connected) {
  543. cmd.opcode = ACLK_DATABASE_NODE_INFO;
  544. cmd.completion = NULL;
  545. wc->node_info_send = aclk_database_enq_cmd_noblock(wc, &cmd);
  546. }
  547. if (localhost == wc->host)
  548. (void) sqlite3_wal_checkpoint(db_meta, NULL);
  549. break;
  550. default:
  551. debug(D_ACLK_SYNC, "%s: default.", __func__);
  552. break;
  553. }
  554. if (cmd.completion)
  555. aclk_complete(cmd.completion);
  556. } while (opcode != ACLK_DATABASE_NOOP);
  557. }
  558. if (!uv_timer_stop(&timer_req))
  559. uv_close((uv_handle_t *)&timer_req, NULL);
  560. /* cleanup operations of the event loop */
  561. //info("Shutting down ACLK sync event loop for %s", wc->host_guid);
  562. /*
  563. * uv_async_send after uv_close does not seem to crash in linux at the moment,
  564. * it is however undocumented behaviour we need to be aware if this becomes
  565. * an issue in the future.
  566. */
  567. uv_close((uv_handle_t *)&wc->async, NULL);
  568. uv_run(loop, UV_RUN_DEFAULT);
  569. info("Shutting down ACLK sync event loop complete for host %s", wc->host_guid);
  570. /* TODO: don't let the API block by waiting to enqueue commands */
  571. uv_cond_destroy(&wc->cmd_cond);
  572. /* uv_mutex_destroy(&wc->cmd_mutex); */
  573. //fatal_assert(0 == uv_loop_close(loop));
  574. int rc;
  575. do {
  576. rc = uv_loop_close(loop);
  577. } while (rc != UV_EBUSY);
  578. freez(loop);
  579. rrd_rdlock();
  580. if (likely(wc->host))
  581. wc->host->dbsync_worker = NULL;
  582. freez(wc);
  583. rrd_unlock();
  584. worker_unregister();
  585. return;
  586. error_after_timer_init:
  587. uv_close((uv_handle_t *)&wc->async, NULL);
  588. error_after_async_init:
  589. fatal_assert(0 == uv_loop_close(loop));
  590. error_after_loop_init:
  591. freez(loop);
  592. worker_unregister();
  593. }
  594. // -------------------------------------------------------------
  595. void sql_create_aclk_table(RRDHOST *host, uuid_t *host_uuid, uuid_t *node_id)
  596. {
  597. #ifdef ENABLE_ACLK
  598. char uuid_str[GUID_LEN + 1];
  599. char host_guid[GUID_LEN + 1];
  600. uuid_unparse_lower_fix(host_uuid, uuid_str);
  601. if (aclk_worker_thread_exists(uuid_str))
  602. return;
  603. uuid_unparse_lower(*host_uuid, host_guid);
  604. BUFFER *sql = buffer_create(ACLK_SYNC_QUERY_SIZE);
  605. buffer_sprintf(sql, TABLE_ACLK_CHART, uuid_str);
  606. db_execute(buffer_tostring(sql));
  607. buffer_flush(sql);
  608. buffer_sprintf(sql, TABLE_ACLK_CHART_PAYLOAD, uuid_str);
  609. db_execute(buffer_tostring(sql));
  610. buffer_flush(sql);
  611. buffer_sprintf(sql, TABLE_ACLK_CHART_LATEST, uuid_str);
  612. db_execute(buffer_tostring(sql));
  613. buffer_flush(sql);
  614. buffer_sprintf(sql, INDEX_ACLK_CHART, uuid_str, uuid_str);
  615. db_execute(buffer_tostring(sql));
  616. buffer_flush(sql);
  617. buffer_sprintf(sql, INDEX_ACLK_CHART_LATEST, uuid_str, uuid_str);
  618. db_execute(buffer_tostring(sql));
  619. buffer_flush(sql);
  620. buffer_sprintf(sql, TRIGGER_ACLK_CHART_PAYLOAD, uuid_str, uuid_str, uuid_str);
  621. db_execute(buffer_tostring(sql));
  622. buffer_flush(sql);
  623. buffer_sprintf(sql, TABLE_ACLK_ALERT, uuid_str);
  624. db_execute(buffer_tostring(sql));
  625. buffer_flush(sql);
  626. buffer_sprintf(sql, INDEX_ACLK_ALERT, uuid_str, uuid_str);
  627. db_execute(buffer_tostring(sql));
  628. buffer_free(sql);
  629. if (likely(host) && unlikely(host->dbsync_worker))
  630. return;
  631. struct aclk_database_worker_config *wc = callocz(1, sizeof(struct aclk_database_worker_config));
  632. if (likely(host))
  633. host->dbsync_worker = (void *) wc;
  634. wc->host = host;
  635. strcpy(wc->uuid_str, uuid_str);
  636. strcpy(wc->host_guid, host_guid);
  637. if (node_id && !uuid_is_null(*node_id))
  638. uuid_unparse_lower(*node_id, wc->node_id);
  639. wc->chart_updates = 0;
  640. wc->alert_updates = 0;
  641. wc->retry_count = 0;
  642. aclk_database_init_cmd_queue(wc);
  643. aclk_add_worker_thread(wc);
  644. fatal_assert(0 == uv_thread_create(&(wc->thread), aclk_database_worker, wc));
  645. #else
  646. UNUSED(host);
  647. UNUSED(host_uuid);
  648. UNUSED(node_id);
  649. #endif
  650. return;
  651. }
  652. void sql_maint_aclk_sync_database(struct aclk_database_worker_config *wc, struct aclk_database_cmd cmd)
  653. {
  654. UNUSED(cmd);
  655. debug(D_ACLK, "Checking database for %s", wc->host_guid);
  656. BUFFER *sql = buffer_create(ACLK_SYNC_QUERY_SIZE);
  657. buffer_sprintf(sql,"DELETE FROM aclk_chart_%s WHERE date_submitted IS NOT NULL AND "
  658. "date_updated < strftime('%%s','now','-%d seconds');", wc->uuid_str, ACLK_DELETE_ACK_INTERNAL);
  659. db_execute(buffer_tostring(sql));
  660. buffer_flush(sql);
  661. buffer_sprintf(sql,"DELETE FROM aclk_chart_payload_%s WHERE unique_id NOT IN "
  662. "(SELECT unique_id FROM aclk_chart_%s) AND unique_id NOT IN (SELECT unique_id FROM aclk_chart_latest_%s);",
  663. wc->uuid_str, wc->uuid_str, wc->uuid_str);
  664. db_execute(buffer_tostring(sql));
  665. buffer_flush(sql);
  666. buffer_sprintf(sql,"DELETE FROM aclk_alert_%s WHERE date_submitted IS NOT NULL AND "
  667. "date_cloud_ack < strftime('%%s','now','-%d seconds');", wc->uuid_str, ACLK_DELETE_ACK_ALERTS_INTERNAL);
  668. db_execute(buffer_tostring(sql));
  669. buffer_free(sql);
  670. return;
  671. }
  672. #define SQL_SELECT_HOST_BY_UUID "SELECT host_id FROM host WHERE host_id = @host_id;"
  673. static int is_host_available(uuid_t *host_id)
  674. {
  675. sqlite3_stmt *res = NULL;
  676. int rc;
  677. if (unlikely(!db_meta)) {
  678. if (default_rrd_memory_mode == RRD_MEMORY_MODE_DBENGINE)
  679. error_report("Database has not been initialized");
  680. return 1;
  681. }
  682. rc = sqlite3_prepare_v2(db_meta, SQL_SELECT_HOST_BY_UUID, -1, &res, 0);
  683. if (unlikely(rc != SQLITE_OK)) {
  684. error_report("Failed to prepare statement to select node instance information for a node");
  685. return 1;
  686. }
  687. rc = sqlite3_bind_blob(res, 1, host_id, sizeof(*host_id), SQLITE_STATIC);
  688. if (unlikely(rc != SQLITE_OK)) {
  689. error_report("Failed to bind host_id parameter to select node instance information");
  690. goto failed;
  691. }
  692. rc = sqlite3_step(res);
  693. failed:
  694. if (unlikely(sqlite3_finalize(res) != SQLITE_OK))
  695. error_report("Failed to finalize the prepared statement when checking host existence");
  696. return (rc == SQLITE_ROW);
  697. }
  698. // OPCODE: ACLK_DATABASE_DELETE_HOST
  699. void sql_delete_aclk_table_list(struct aclk_database_worker_config *wc, struct aclk_database_cmd cmd)
  700. {
  701. UNUSED(wc);
  702. char uuid_str[GUID_LEN + 1];
  703. char host_str[GUID_LEN + 1];
  704. int rc;
  705. uuid_t host_uuid;
  706. char *host_guid = (char *)cmd.data;
  707. if (unlikely(!host_guid))
  708. return;
  709. rc = uuid_parse(host_guid, host_uuid);
  710. freez(host_guid);
  711. if (rc)
  712. return;
  713. uuid_unparse_lower(host_uuid, host_str);
  714. uuid_unparse_lower_fix(&host_uuid, uuid_str);
  715. debug(D_ACLK_SYNC, "Checking if I should delete aclk tables for node %s", host_str);
  716. if (is_host_available(&host_uuid)) {
  717. debug(D_ACLK_SYNC, "Host %s exists, not deleting aclk sync tables", host_str);
  718. return;
  719. }
  720. debug(D_ACLK_SYNC, "Host %s does NOT exist, can delete aclk sync tables", host_str);
  721. sqlite3_stmt *res = NULL;
  722. BUFFER *sql = buffer_create(ACLK_SYNC_QUERY_SIZE);
  723. buffer_sprintf(sql,"SELECT 'drop '||type||' IF EXISTS '||name||';' FROM sqlite_schema " \
  724. "WHERE name LIKE 'aclk_%%_%s' AND type IN ('table', 'trigger', 'index');", uuid_str);
  725. rc = sqlite3_prepare_v2(db_meta, buffer_tostring(sql), -1, &res, 0);
  726. if (rc != SQLITE_OK) {
  727. error_report("Failed to prepare statement to clean up aclk tables");
  728. goto fail;
  729. }
  730. buffer_flush(sql);
  731. while (sqlite3_step(res) == SQLITE_ROW)
  732. buffer_strcat(sql, (char *) sqlite3_column_text(res, 0));
  733. rc = sqlite3_finalize(res);
  734. if (unlikely(rc != SQLITE_OK))
  735. error_report("Failed to finalize statement to clean up aclk tables, rc = %d", rc);
  736. db_execute(buffer_tostring(sql));
  737. fail:
  738. buffer_free(sql);
  739. return;
  740. }
  741. static int sql_check_aclk_table(void *data, int argc, char **argv, char **column)
  742. {
  743. struct aclk_database_worker_config *wc = data;
  744. UNUSED(argc);
  745. UNUSED(column);
  746. debug(D_ACLK_SYNC,"Scheduling aclk sync table check for node %s", (char *) argv[0]);
  747. struct aclk_database_cmd cmd;
  748. memset(&cmd, 0, sizeof(cmd));
  749. cmd.opcode = ACLK_DATABASE_DELETE_HOST;
  750. cmd.data = strdupz((char *) argv[0]);
  751. aclk_database_enq_cmd_noblock(wc, &cmd);
  752. return 0;
  753. }
  754. #define SQL_SELECT_ACLK_ACTIVE_LIST "SELECT REPLACE(SUBSTR(name,19),'_','-') FROM sqlite_schema " \
  755. "WHERE name LIKE 'aclk_chart_latest_%' AND type IN ('table');"
  756. void sql_check_aclk_table_list(struct aclk_database_worker_config *wc)
  757. {
  758. char *err_msg = NULL;
  759. debug(D_ACLK_SYNC,"Cleaning tables for nodes that do not exist");
  760. int rc = sqlite3_exec(db_meta, SQL_SELECT_ACLK_ACTIVE_LIST, sql_check_aclk_table, (void *) wc, &err_msg);
  761. if (rc != SQLITE_OK) {
  762. error_report("Query failed when trying to check for obsolete ACLK sync tables, %s", err_msg);
  763. sqlite3_free(err_msg);
  764. }
  765. db_execute("DELETE FROM dimension_delete WHERE host_id NOT IN (SELECT host_id FROM host) "
  766. " OR strftime('%s') - date_created > 604800;");
  767. return;
  768. }
  769. void aclk_data_rotated(void)
  770. {
  771. #ifdef ENABLE_NEW_CLOUD_PROTOCOL
  772. if (!aclk_use_new_cloud_arch || !aclk_connected)
  773. return;
  774. time_t next_rotation_time = now_realtime_sec()+ACLK_DATABASE_ROTATION_DELAY;
  775. rrd_rdlock();
  776. RRDHOST *this_host = localhost;
  777. while (this_host) {
  778. struct aclk_database_worker_config *wc = this_host->dbsync_worker;
  779. if (wc)
  780. wc->rotation_after = next_rotation_time;
  781. this_host = this_host->next;
  782. }
  783. rrd_unlock();
  784. struct aclk_database_worker_config *tmp = aclk_thread_head;
  785. uv_mutex_lock(&aclk_async_lock);
  786. while (tmp) {
  787. tmp->rotation_after = next_rotation_time;
  788. tmp = tmp->next;
  789. }
  790. uv_mutex_unlock(&aclk_async_lock);
  791. #endif
  792. return;
  793. }