commands.c 22 KB

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