commands.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "common.h"
  3. #include "../database/engine/rrdenginelib.h"
  4. static uv_thread_t thread;
  5. static uv_loop_t* loop;
  6. static uv_async_t async;
  7. static struct completion completion;
  8. static uv_pipe_t server_pipe;
  9. char cmd_prefix_by_status[] = {
  10. CMD_PREFIX_INFO,
  11. CMD_PREFIX_ERROR,
  12. CMD_PREFIX_ERROR
  13. };
  14. static int command_server_initialized = 0;
  15. static int command_thread_error;
  16. static int command_thread_shutdown;
  17. static unsigned clients = 0;
  18. struct command_context {
  19. /* embedded client pipe structure at address 0 */
  20. uv_pipe_t client;
  21. uv_work_t work;
  22. uv_write_t write_req;
  23. cmd_t idx;
  24. char *args;
  25. char *message;
  26. cmd_status_t status;
  27. char command_string[MAX_COMMAND_LENGTH];
  28. unsigned command_string_size;
  29. };
  30. /* Forward declarations */
  31. static cmd_status_t cmd_help_execute(char *args, char **message);
  32. static cmd_status_t cmd_reload_health_execute(char *args, char **message);
  33. static cmd_status_t cmd_save_database_execute(char *args, char **message);
  34. static cmd_status_t cmd_reopen_logs_execute(char *args, char **message);
  35. static cmd_status_t cmd_exit_execute(char *args, char **message);
  36. static cmd_status_t cmd_fatal_execute(char *args, char **message);
  37. static cmd_status_t cmd_reload_claiming_state_execute(char *args, char **message);
  38. static cmd_status_t cmd_reload_labels_execute(char *args, char **message);
  39. static cmd_status_t cmd_read_config_execute(char *args, char **message);
  40. static cmd_status_t cmd_write_config_execute(char *args, char **message);
  41. static cmd_status_t cmd_ping_execute(char *args, char **message);
  42. static command_info_t command_info_array[] = {
  43. {"help", cmd_help_execute, CMD_TYPE_HIGH_PRIORITY}, // show help menu
  44. {"reload-health", cmd_reload_health_execute, CMD_TYPE_ORTHOGONAL}, // reload health configuration
  45. {"save-database", cmd_save_database_execute, CMD_TYPE_ORTHOGONAL}, // save database for memory mode save
  46. {"reopen-logs", cmd_reopen_logs_execute, CMD_TYPE_ORTHOGONAL}, // Close and reopen log files
  47. {"shutdown-agent", cmd_exit_execute, CMD_TYPE_EXCLUSIVE}, // exit cleanly
  48. {"fatal-agent", cmd_fatal_execute, CMD_TYPE_HIGH_PRIORITY}, // exit with fatal error
  49. {"reload-claiming-state", cmd_reload_claiming_state_execute, CMD_TYPE_ORTHOGONAL}, // reload claiming state
  50. {"reload-labels", cmd_reload_labels_execute, CMD_TYPE_ORTHOGONAL}, // reload the labels
  51. {"read-config", cmd_read_config_execute, CMD_TYPE_CONCURRENT},
  52. {"write-config", cmd_write_config_execute, CMD_TYPE_ORTHOGONAL},
  53. {"ping", cmd_ping_execute, CMD_TYPE_ORTHOGONAL}
  54. };
  55. /* Mutexes for commands of type CMD_TYPE_ORTHOGONAL */
  56. static uv_mutex_t command_lock_array[CMD_TOTAL_COMMANDS];
  57. /* Commands of type CMD_TYPE_EXCLUSIVE are writers */
  58. static uv_rwlock_t exclusive_rwlock;
  59. /*
  60. * Locking order:
  61. * 1. exclusive_rwlock
  62. * 2. command_lock_array[]
  63. */
  64. /* Forward declarations */
  65. static void cmd_lock_exclusive(unsigned index);
  66. static void cmd_lock_orthogonal(unsigned index);
  67. static void cmd_lock_idempotent(unsigned index);
  68. static void cmd_lock_high_priority(unsigned index);
  69. static command_lock_t *cmd_lock_by_type[] = {
  70. cmd_lock_exclusive,
  71. cmd_lock_orthogonal,
  72. cmd_lock_idempotent,
  73. cmd_lock_high_priority
  74. };
  75. /* Forward declarations */
  76. static void cmd_unlock_exclusive(unsigned index);
  77. static void cmd_unlock_orthogonal(unsigned index);
  78. static void cmd_unlock_idempotent(unsigned index);
  79. static void cmd_unlock_high_priority(unsigned index);
  80. static command_lock_t *cmd_unlock_by_type[] = {
  81. cmd_unlock_exclusive,
  82. cmd_unlock_orthogonal,
  83. cmd_unlock_idempotent,
  84. cmd_unlock_high_priority
  85. };
  86. static cmd_status_t cmd_help_execute(char *args, char **message)
  87. {
  88. (void)args;
  89. *message = mallocz(MAX_COMMAND_LENGTH);
  90. strncpyz(*message,
  91. "\nThe commands are (arguments are in brackets):\n"
  92. "help\n"
  93. " Show this help menu.\n"
  94. "reload-health\n"
  95. " Reload health configuration.\n"
  96. "reload-labels\n"
  97. " Reload all labels.\n"
  98. "save-database\n"
  99. " Save internal DB to disk for memory mode save.\n"
  100. "reopen-logs\n"
  101. " Close and reopen log files.\n"
  102. "shutdown-agent\n"
  103. " Cleanup and exit the netdata agent.\n"
  104. "fatal-agent\n"
  105. " Log the state and halt the netdata agent.\n"
  106. "reload-claiming-state\n"
  107. " Reload agent claiming state from disk.\n"
  108. "ping\n"
  109. " Return with 'pong' if agent is alive.\n",
  110. MAX_COMMAND_LENGTH - 1);
  111. return CMD_STATUS_SUCCESS;
  112. }
  113. static cmd_status_t cmd_reload_health_execute(char *args, char **message)
  114. {
  115. (void)args;
  116. (void)message;
  117. error_log_limit_unlimited();
  118. info("COMMAND: Reloading HEALTH configuration.");
  119. health_reload();
  120. error_log_limit_reset();
  121. return CMD_STATUS_SUCCESS;
  122. }
  123. static cmd_status_t cmd_save_database_execute(char *args, char **message)
  124. {
  125. (void)args;
  126. (void)message;
  127. error_log_limit_unlimited();
  128. info("COMMAND: Saving databases.");
  129. rrdhost_save_all();
  130. info("COMMAND: Databases saved.");
  131. error_log_limit_reset();
  132. return CMD_STATUS_SUCCESS;
  133. }
  134. static cmd_status_t cmd_reopen_logs_execute(char *args, char **message)
  135. {
  136. (void)args;
  137. (void)message;
  138. error_log_limit_unlimited();
  139. info("COMMAND: Reopening all log files.");
  140. reopen_all_log_files();
  141. error_log_limit_reset();
  142. return CMD_STATUS_SUCCESS;
  143. }
  144. static cmd_status_t cmd_exit_execute(char *args, char **message)
  145. {
  146. (void)args;
  147. (void)message;
  148. error_log_limit_unlimited();
  149. info("COMMAND: Cleaning up to exit.");
  150. netdata_cleanup_and_exit(0);
  151. exit(0);
  152. return CMD_STATUS_SUCCESS;
  153. }
  154. static cmd_status_t cmd_fatal_execute(char *args, char **message)
  155. {
  156. (void)args;
  157. (void)message;
  158. fatal("COMMAND: netdata now exits.");
  159. return CMD_STATUS_SUCCESS;
  160. }
  161. static cmd_status_t cmd_reload_claiming_state_execute(char *args, char **message)
  162. {
  163. (void)args;
  164. (void)message;
  165. #if defined(DISABLE_CLOUD) || !defined(ENABLE_ACLK)
  166. info("The claiming feature has been explicitly disabled");
  167. *message = strdupz("This agent cannot be claimed, it was built without support for Cloud");
  168. return CMD_STATUS_FAILURE;
  169. #endif
  170. error_log_limit_unlimited();
  171. info("COMMAND: Reloading Agent Claiming configuration.");
  172. load_claiming_state();
  173. registry_update_cloud_base_url();
  174. error_log_limit_reset();
  175. return CMD_STATUS_SUCCESS;
  176. }
  177. static cmd_status_t cmd_reload_labels_execute(char *args, char **message)
  178. {
  179. (void)args;
  180. info("COMMAND: reloading host labels.");
  181. reload_host_labels();
  182. BUFFER *wb = buffer_create(10);
  183. rrdhost_rdlock(localhost);
  184. netdata_rwlock_rdlock(&localhost->labels_rwlock);
  185. struct label *l=localhost->labels;
  186. while (l != NULL) {
  187. buffer_sprintf(wb,"Label [source id=%s]: \"%s\" -> \"%s\"\n", translate_label_source(l->label_source), l->key, l->value);
  188. l = l->next;
  189. }
  190. netdata_rwlock_unlock(&localhost->labels_rwlock);
  191. rrdhost_unlock(localhost);
  192. (*message)=strdupz(buffer_tostring(wb));
  193. buffer_free(wb);
  194. return CMD_STATUS_SUCCESS;
  195. }
  196. static cmd_status_t cmd_read_config_execute(char *args, char **message)
  197. {
  198. size_t n = strlen(args);
  199. char *separator = strchr(args,'|');
  200. if (separator == NULL)
  201. return CMD_STATUS_FAILURE;
  202. char *separator2 = strchr(separator + 1,'|');
  203. if (separator2 == NULL)
  204. return CMD_STATUS_FAILURE;
  205. char *temp = callocz(n + 1, 1);
  206. strcpy(temp, args);
  207. size_t offset = separator - args;
  208. temp[offset] = 0;
  209. size_t offset2 = separator2 - args;
  210. temp[offset2] = 0;
  211. const char *conf_file = temp; /* "cloud" is cloud.conf, otherwise netdata.conf */
  212. struct config *tmp_config = strcmp(conf_file, "cloud") ? &netdata_config : &cloud_config;
  213. char *value = appconfig_get(tmp_config, temp + offset + 1, temp + offset2 + 1, NULL);
  214. if (value == NULL)
  215. {
  216. error("Cannot execute read-config conf_file=%s section=%s / key=%s because no value set", conf_file,
  217. temp + offset + 1, temp + offset2 + 1);
  218. freez(temp);
  219. return CMD_STATUS_FAILURE;
  220. }
  221. else
  222. {
  223. (*message) = strdupz(value);
  224. freez(temp);
  225. return CMD_STATUS_SUCCESS;
  226. }
  227. }
  228. static cmd_status_t cmd_write_config_execute(char *args, char **message)
  229. {
  230. UNUSED(message);
  231. info("write-config %s", args);
  232. size_t n = strlen(args);
  233. char *separator = strchr(args,'|');
  234. if (separator == NULL)
  235. return CMD_STATUS_FAILURE;
  236. char *separator2 = strchr(separator + 1,'|');
  237. if (separator2 == NULL)
  238. return CMD_STATUS_FAILURE;
  239. char *separator3 = strchr(separator2 + 1,'|');
  240. if (separator3 == NULL)
  241. return CMD_STATUS_FAILURE;
  242. char *temp = callocz(n + 1, 1);
  243. strcpy(temp, args);
  244. size_t offset = separator - args;
  245. temp[offset] = 0;
  246. size_t offset2 = separator2 - args;
  247. temp[offset2] = 0;
  248. size_t offset3 = separator3 - args;
  249. temp[offset3] = 0;
  250. const char *conf_file = temp; /* "cloud" is cloud.conf, otherwise netdata.conf */
  251. struct config *tmp_config = strcmp(conf_file, "cloud") ? &netdata_config : &cloud_config;
  252. appconfig_set(tmp_config, temp + offset + 1, temp + offset2 + 1, temp + offset3 + 1);
  253. info("write-config conf_file=%s section=%s key=%s value=%s",conf_file, temp + offset + 1, temp + offset2 + 1,
  254. temp + offset3 + 1);
  255. freez(temp);
  256. return CMD_STATUS_SUCCESS;
  257. }
  258. static cmd_status_t cmd_ping_execute(char *args, char **message)
  259. {
  260. (void)args;
  261. *message = strdupz("pong");
  262. return CMD_STATUS_SUCCESS;
  263. }
  264. static void cmd_lock_exclusive(unsigned index)
  265. {
  266. (void)index;
  267. uv_rwlock_wrlock(&exclusive_rwlock);
  268. }
  269. static void cmd_lock_orthogonal(unsigned index)
  270. {
  271. uv_rwlock_rdlock(&exclusive_rwlock);
  272. uv_mutex_lock(&command_lock_array[index]);
  273. }
  274. static void cmd_lock_idempotent(unsigned index)
  275. {
  276. (void)index;
  277. uv_rwlock_rdlock(&exclusive_rwlock);
  278. }
  279. static void cmd_lock_high_priority(unsigned index)
  280. {
  281. (void)index;
  282. }
  283. static void cmd_unlock_exclusive(unsigned index)
  284. {
  285. (void)index;
  286. uv_rwlock_wrunlock(&exclusive_rwlock);
  287. }
  288. static void cmd_unlock_orthogonal(unsigned index)
  289. {
  290. uv_rwlock_rdunlock(&exclusive_rwlock);
  291. uv_mutex_unlock(&command_lock_array[index]);
  292. }
  293. static void cmd_unlock_idempotent(unsigned index)
  294. {
  295. (void)index;
  296. uv_rwlock_rdunlock(&exclusive_rwlock);
  297. }
  298. static void cmd_unlock_high_priority(unsigned index)
  299. {
  300. (void)index;
  301. }
  302. static void pipe_close_cb(uv_handle_t* handle)
  303. {
  304. /* Also frees command context */
  305. freez(handle);
  306. }
  307. static void pipe_write_cb(uv_write_t* req, int status)
  308. {
  309. (void)status;
  310. uv_pipe_t *client = req->data;
  311. uv_close((uv_handle_t *)client, pipe_close_cb);
  312. --clients;
  313. info("Command Clients = %u\n", clients);
  314. }
  315. static inline void add_char_to_command_reply(char *reply_string, unsigned *reply_string_size, char character)
  316. {
  317. reply_string[(*reply_string_size)++] = character;
  318. }
  319. static inline void add_string_to_command_reply(char *reply_string, unsigned *reply_string_size, char *str)
  320. {
  321. unsigned len;
  322. len = strlen(str);
  323. strncpyz(reply_string + *reply_string_size, str, len);
  324. *reply_string_size += len;
  325. }
  326. static void send_command_reply(struct command_context *cmd_ctx, cmd_status_t status, char *message)
  327. {
  328. int ret;
  329. char reply_string[MAX_COMMAND_LENGTH] = {'\0', };
  330. char exit_status_string[MAX_EXIT_STATUS_LENGTH + 1] = {'\0', };
  331. unsigned reply_string_size = 0;
  332. uv_buf_t write_buf;
  333. uv_stream_t *client = (uv_stream_t *)(uv_pipe_t *)cmd_ctx;
  334. snprintfz(exit_status_string, MAX_EXIT_STATUS_LENGTH, "%u", status);
  335. add_char_to_command_reply(reply_string, &reply_string_size, CMD_PREFIX_EXIT_CODE);
  336. add_string_to_command_reply(reply_string, &reply_string_size, exit_status_string);
  337. add_char_to_command_reply(reply_string, &reply_string_size, '\0');
  338. if (message) {
  339. add_char_to_command_reply(reply_string, &reply_string_size, cmd_prefix_by_status[status]);
  340. add_string_to_command_reply(reply_string, &reply_string_size, message);
  341. }
  342. cmd_ctx->write_req.data = client;
  343. write_buf.base = reply_string;
  344. write_buf.len = reply_string_size;
  345. ret = uv_write(&cmd_ctx->write_req, (uv_stream_t *)client, &write_buf, 1, pipe_write_cb);
  346. if (ret) {
  347. error("uv_write(): %s", uv_strerror(ret));
  348. }
  349. info("COMMAND: Sending reply: \"%s\"", reply_string);
  350. }
  351. cmd_status_t execute_command(cmd_t idx, char *args, char **message)
  352. {
  353. cmd_status_t status;
  354. cmd_type_t type = command_info_array[idx].type;
  355. cmd_lock_by_type[type](idx);
  356. status = command_info_array[idx].func(args, message);
  357. cmd_unlock_by_type[type](idx);
  358. return status;
  359. }
  360. static void after_schedule_command(uv_work_t *req, int status)
  361. {
  362. struct command_context *cmd_ctx = req->data;
  363. (void)status;
  364. send_command_reply(cmd_ctx, cmd_ctx->status, cmd_ctx->message);
  365. if (cmd_ctx->message)
  366. freez(cmd_ctx->message);
  367. }
  368. static void schedule_command(uv_work_t *req)
  369. {
  370. struct command_context *cmd_ctx = req->data;
  371. cmd_ctx->status = execute_command(cmd_ctx->idx, cmd_ctx->args, &cmd_ctx->message);
  372. }
  373. /* This will alter the state of the command_info_array.cmd_str
  374. */
  375. static void parse_commands(struct command_context *cmd_ctx)
  376. {
  377. char *message = NULL, *pos, *lstrip, *rstrip;
  378. cmd_t i;
  379. cmd_status_t status;
  380. status = CMD_STATUS_FAILURE;
  381. /* Skip white-space characters */
  382. for (pos = cmd_ctx->command_string ; isspace(*pos) && ('\0' != *pos) ; ++pos) {;}
  383. for (i = 0 ; i < CMD_TOTAL_COMMANDS ; ++i) {
  384. if (!strncmp(pos, command_info_array[i].cmd_str, strlen(command_info_array[i].cmd_str))) {
  385. if (CMD_EXIT == i) {
  386. /* musl C does not like libuv workqueues calling exit() */
  387. execute_command(CMD_EXIT, NULL, NULL);
  388. }
  389. for (lstrip=pos + strlen(command_info_array[i].cmd_str); isspace(*lstrip) && ('\0' != *lstrip); ++lstrip) {;}
  390. for (rstrip=lstrip+strlen(lstrip)-1; rstrip>lstrip && isspace(*rstrip); *(rstrip--) = 0 );
  391. cmd_ctx->work.data = cmd_ctx;
  392. cmd_ctx->idx = i;
  393. cmd_ctx->args = lstrip;
  394. cmd_ctx->message = NULL;
  395. assert(0 == uv_queue_work(loop, &cmd_ctx->work, schedule_command, after_schedule_command));
  396. break;
  397. }
  398. }
  399. if (CMD_TOTAL_COMMANDS == i) {
  400. /* no command found */
  401. message = strdupz("Illegal command. Please type \"help\" for instructions.");
  402. send_command_reply(cmd_ctx, status, message);
  403. freez(message);
  404. }
  405. }
  406. static void pipe_read_cb(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf)
  407. {
  408. struct command_context *cmd_ctx = (struct command_context *)client;
  409. if (0 == nread) {
  410. info("%s: Zero bytes read by command pipe.", __func__);
  411. } else if (UV_EOF == nread) {
  412. info("EOF found in command pipe.");
  413. parse_commands(cmd_ctx);
  414. } else if (nread < 0) {
  415. error("%s: %s", __func__, uv_strerror(nread));
  416. }
  417. if (nread < 0) { /* stop stream due to EOF or error */
  418. (void)uv_read_stop((uv_stream_t *)client);
  419. } else if (nread) {
  420. size_t to_copy;
  421. to_copy = MIN(nread, MAX_COMMAND_LENGTH - 1 - cmd_ctx->command_string_size);
  422. memcpy(cmd_ctx->command_string + cmd_ctx->command_string_size, buf->base, to_copy);
  423. cmd_ctx->command_string_size += to_copy;
  424. cmd_ctx->command_string[cmd_ctx->command_string_size] = '\0';
  425. }
  426. if (buf && buf->len) {
  427. freez(buf->base);
  428. }
  429. if (nread < 0 && UV_EOF != nread) {
  430. uv_close((uv_handle_t *)client, pipe_close_cb);
  431. --clients;
  432. info("Command Clients = %u\n", clients);
  433. }
  434. }
  435. static void alloc_cb(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf)
  436. {
  437. (void)handle;
  438. buf->base = mallocz(suggested_size);
  439. buf->len = suggested_size;
  440. }
  441. static void connection_cb(uv_stream_t *server, int status)
  442. {
  443. int ret;
  444. uv_pipe_t *client;
  445. struct command_context *cmd_ctx;
  446. assert(status == 0);
  447. /* combined allocation of client pipe and command context */
  448. cmd_ctx = mallocz(sizeof(*cmd_ctx));
  449. client = (uv_pipe_t *)cmd_ctx;
  450. ret = uv_pipe_init(server->loop, client, 1);
  451. if (ret) {
  452. error("uv_pipe_init(): %s", uv_strerror(ret));
  453. freez(cmd_ctx);
  454. return;
  455. }
  456. ret = uv_accept(server, (uv_stream_t *)client);
  457. if (ret) {
  458. error("uv_accept(): %s", uv_strerror(ret));
  459. uv_close((uv_handle_t *)client, pipe_close_cb);
  460. return;
  461. }
  462. ++clients;
  463. info("Command Clients = %u\n", clients);
  464. /* Start parsing a new command */
  465. cmd_ctx->command_string_size = 0;
  466. cmd_ctx->command_string[0] = '\0';
  467. ret = uv_read_start((uv_stream_t*)client, alloc_cb, pipe_read_cb);
  468. if (ret) {
  469. error("uv_read_start(): %s", uv_strerror(ret));
  470. uv_close((uv_handle_t *)client, pipe_close_cb);
  471. --clients;
  472. info("Command Clients = %u\n", clients);
  473. return;
  474. }
  475. }
  476. static void async_cb(uv_async_t *handle)
  477. {
  478. uv_stop(handle->loop);
  479. }
  480. static void command_thread(void *arg)
  481. {
  482. int ret;
  483. uv_fs_t req;
  484. (void) arg;
  485. loop = mallocz(sizeof(uv_loop_t));
  486. ret = uv_loop_init(loop);
  487. if (ret) {
  488. error("uv_loop_init(): %s", uv_strerror(ret));
  489. command_thread_error = ret;
  490. goto error_after_loop_init;
  491. }
  492. loop->data = NULL;
  493. ret = uv_async_init(loop, &async, async_cb);
  494. if (ret) {
  495. error("uv_async_init(): %s", uv_strerror(ret));
  496. command_thread_error = ret;
  497. goto error_after_async_init;
  498. }
  499. async.data = NULL;
  500. ret = uv_pipe_init(loop, &server_pipe, 0);
  501. if (ret) {
  502. error("uv_pipe_init(): %s", uv_strerror(ret));
  503. command_thread_error = ret;
  504. goto error_after_pipe_init;
  505. }
  506. (void)uv_fs_unlink(loop, &req, PIPENAME, NULL);
  507. uv_fs_req_cleanup(&req);
  508. ret = uv_pipe_bind(&server_pipe, PIPENAME);
  509. if (ret) {
  510. error("uv_pipe_bind(): %s", uv_strerror(ret));
  511. command_thread_error = ret;
  512. goto error_after_pipe_bind;
  513. }
  514. ret = uv_listen((uv_stream_t *)&server_pipe, SOMAXCONN, connection_cb);
  515. if (ret) {
  516. /* Fallback to backlog of 1 */
  517. info("uv_listen() failed with backlog = %d, falling back to backlog = 1.", SOMAXCONN);
  518. ret = uv_listen((uv_stream_t *)&server_pipe, 1, connection_cb);
  519. }
  520. if (ret) {
  521. error("uv_listen(): %s", uv_strerror(ret));
  522. command_thread_error = ret;
  523. goto error_after_uv_listen;
  524. }
  525. command_thread_error = 0;
  526. command_thread_shutdown = 0;
  527. /* wake up initialization thread */
  528. complete(&completion);
  529. while (command_thread_shutdown == 0) {
  530. uv_run(loop, UV_RUN_DEFAULT);
  531. }
  532. /* cleanup operations of the event loop */
  533. info("Shutting down command event loop.");
  534. uv_close((uv_handle_t *)&async, NULL);
  535. uv_close((uv_handle_t*)&server_pipe, NULL);
  536. uv_run(loop, UV_RUN_DEFAULT); /* flush all libuv handles */
  537. info("Shutting down command loop complete.");
  538. assert(0 == uv_loop_close(loop));
  539. freez(loop);
  540. return;
  541. error_after_uv_listen:
  542. error_after_pipe_bind:
  543. uv_close((uv_handle_t*)&server_pipe, NULL);
  544. error_after_pipe_init:
  545. uv_close((uv_handle_t *)&async, NULL);
  546. error_after_async_init:
  547. uv_run(loop, UV_RUN_DEFAULT); /* flush all libuv handles */
  548. assert(0 == uv_loop_close(loop));
  549. error_after_loop_init:
  550. freez(loop);
  551. /* wake up initialization thread */
  552. complete(&completion);
  553. }
  554. static void sanity_check(void)
  555. {
  556. /* The size of command_info_array must be CMD_TOTAL_COMMANDS elements */
  557. BUILD_BUG_ON(CMD_TOTAL_COMMANDS != sizeof(command_info_array) / sizeof(command_info_array[0]));
  558. }
  559. void commands_init(void)
  560. {
  561. cmd_t i;
  562. int error;
  563. sanity_check();
  564. if (command_server_initialized)
  565. return;
  566. info("Initializing command server.");
  567. for (i = 0 ; i < CMD_TOTAL_COMMANDS ; ++i) {
  568. assert(0 == uv_mutex_init(&command_lock_array[i]));
  569. }
  570. assert(0 == uv_rwlock_init(&exclusive_rwlock));
  571. init_completion(&completion);
  572. error = uv_thread_create(&thread, command_thread, NULL);
  573. if (error) {
  574. error("uv_thread_create(): %s", uv_strerror(error));
  575. goto after_error;
  576. }
  577. /* wait for worker thread to initialize */
  578. wait_for_completion(&completion);
  579. destroy_completion(&completion);
  580. uv_thread_set_name_np(thread, "DAEMON_COMMAND");
  581. if (command_thread_error) {
  582. error = uv_thread_join(&thread);
  583. if (error) {
  584. error("uv_thread_create(): %s", uv_strerror(error));
  585. }
  586. goto after_error;
  587. }
  588. command_server_initialized = 1;
  589. return;
  590. after_error:
  591. error("Failed to initialize command server. The netdata cli tool will be unable to send commands.");
  592. }
  593. void commands_exit(void)
  594. {
  595. cmd_t i;
  596. if (!command_server_initialized)
  597. return;
  598. command_thread_shutdown = 1;
  599. info("Shutting down command server.");
  600. /* wake up event loop */
  601. assert(0 == uv_async_send(&async));
  602. assert(0 == uv_thread_join(&thread));
  603. for (i = 0 ; i < CMD_TOTAL_COMMANDS ; ++i) {
  604. uv_mutex_destroy(&command_lock_array[i]);
  605. }
  606. uv_rwlock_destroy(&exclusive_rwlock);
  607. info("Command server has stopped.");
  608. command_server_initialized = 0;
  609. }