commands.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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. rrdpush_claimed_id(localhost);
  175. error_log_limit_reset();
  176. return CMD_STATUS_SUCCESS;
  177. }
  178. static cmd_status_t cmd_reload_labels_execute(char *args, char **message)
  179. {
  180. (void)args;
  181. info("COMMAND: reloading host labels.");
  182. reload_host_labels();
  183. BUFFER *wb = buffer_create(10);
  184. rrdhost_rdlock(localhost);
  185. netdata_rwlock_rdlock(&localhost->labels.labels_rwlock);
  186. struct label *l = localhost->labels.head;
  187. while (l != NULL) {
  188. buffer_sprintf(wb,"Label [source id=%s]: \"%s\" -> \"%s\"\n", translate_label_source(l->label_source), l->key, l->value);
  189. l = l->next;
  190. }
  191. netdata_rwlock_unlock(&localhost->labels.labels_rwlock);
  192. rrdhost_unlock(localhost);
  193. (*message)=strdupz(buffer_tostring(wb));
  194. buffer_free(wb);
  195. return CMD_STATUS_SUCCESS;
  196. }
  197. static cmd_status_t cmd_read_config_execute(char *args, char **message)
  198. {
  199. size_t n = strlen(args);
  200. char *separator = strchr(args,'|');
  201. if (separator == NULL)
  202. return CMD_STATUS_FAILURE;
  203. char *separator2 = strchr(separator + 1,'|');
  204. if (separator2 == NULL)
  205. return CMD_STATUS_FAILURE;
  206. char *temp = callocz(n + 1, 1);
  207. strcpy(temp, args);
  208. size_t offset = separator - args;
  209. temp[offset] = 0;
  210. size_t offset2 = separator2 - args;
  211. temp[offset2] = 0;
  212. const char *conf_file = temp; /* "cloud" is cloud.conf, otherwise netdata.conf */
  213. struct config *tmp_config = strcmp(conf_file, "cloud") ? &netdata_config : &cloud_config;
  214. char *value = appconfig_get(tmp_config, temp + offset + 1, temp + offset2 + 1, NULL);
  215. if (value == NULL)
  216. {
  217. error("Cannot execute read-config conf_file=%s section=%s / key=%s because no value set", conf_file,
  218. temp + offset + 1, temp + offset2 + 1);
  219. freez(temp);
  220. return CMD_STATUS_FAILURE;
  221. }
  222. else
  223. {
  224. (*message) = strdupz(value);
  225. freez(temp);
  226. return CMD_STATUS_SUCCESS;
  227. }
  228. }
  229. static cmd_status_t cmd_write_config_execute(char *args, char **message)
  230. {
  231. UNUSED(message);
  232. info("write-config %s", args);
  233. size_t n = strlen(args);
  234. char *separator = strchr(args,'|');
  235. if (separator == NULL)
  236. return CMD_STATUS_FAILURE;
  237. char *separator2 = strchr(separator + 1,'|');
  238. if (separator2 == NULL)
  239. return CMD_STATUS_FAILURE;
  240. char *separator3 = strchr(separator2 + 1,'|');
  241. if (separator3 == NULL)
  242. return CMD_STATUS_FAILURE;
  243. char *temp = callocz(n + 1, 1);
  244. strcpy(temp, args);
  245. size_t offset = separator - args;
  246. temp[offset] = 0;
  247. size_t offset2 = separator2 - args;
  248. temp[offset2] = 0;
  249. size_t offset3 = separator3 - args;
  250. temp[offset3] = 0;
  251. const char *conf_file = temp; /* "cloud" is cloud.conf, otherwise netdata.conf */
  252. struct config *tmp_config = strcmp(conf_file, "cloud") ? &netdata_config : &cloud_config;
  253. appconfig_set(tmp_config, temp + offset + 1, temp + offset2 + 1, temp + offset3 + 1);
  254. info("write-config conf_file=%s section=%s key=%s value=%s",conf_file, temp + offset + 1, temp + offset2 + 1,
  255. temp + offset3 + 1);
  256. freez(temp);
  257. return CMD_STATUS_SUCCESS;
  258. }
  259. static cmd_status_t cmd_ping_execute(char *args, char **message)
  260. {
  261. (void)args;
  262. *message = strdupz("pong");
  263. return CMD_STATUS_SUCCESS;
  264. }
  265. static void cmd_lock_exclusive(unsigned index)
  266. {
  267. (void)index;
  268. uv_rwlock_wrlock(&exclusive_rwlock);
  269. }
  270. static void cmd_lock_orthogonal(unsigned index)
  271. {
  272. uv_rwlock_rdlock(&exclusive_rwlock);
  273. uv_mutex_lock(&command_lock_array[index]);
  274. }
  275. static void cmd_lock_idempotent(unsigned index)
  276. {
  277. (void)index;
  278. uv_rwlock_rdlock(&exclusive_rwlock);
  279. }
  280. static void cmd_lock_high_priority(unsigned index)
  281. {
  282. (void)index;
  283. }
  284. static void cmd_unlock_exclusive(unsigned index)
  285. {
  286. (void)index;
  287. uv_rwlock_wrunlock(&exclusive_rwlock);
  288. }
  289. static void cmd_unlock_orthogonal(unsigned index)
  290. {
  291. uv_rwlock_rdunlock(&exclusive_rwlock);
  292. uv_mutex_unlock(&command_lock_array[index]);
  293. }
  294. static void cmd_unlock_idempotent(unsigned index)
  295. {
  296. (void)index;
  297. uv_rwlock_rdunlock(&exclusive_rwlock);
  298. }
  299. static void cmd_unlock_high_priority(unsigned index)
  300. {
  301. (void)index;
  302. }
  303. static void pipe_close_cb(uv_handle_t* handle)
  304. {
  305. /* Also frees command context */
  306. freez(handle);
  307. }
  308. static void pipe_write_cb(uv_write_t* req, int status)
  309. {
  310. (void)status;
  311. uv_pipe_t *client = req->data;
  312. uv_close((uv_handle_t *)client, pipe_close_cb);
  313. --clients;
  314. info("Command Clients = %u\n", clients);
  315. }
  316. static inline void add_char_to_command_reply(char *reply_string, unsigned *reply_string_size, char character)
  317. {
  318. reply_string[(*reply_string_size)++] = character;
  319. }
  320. static inline void add_string_to_command_reply(char *reply_string, unsigned *reply_string_size, char *str)
  321. {
  322. unsigned len;
  323. len = strlen(str);
  324. strncpyz(reply_string + *reply_string_size, str, len);
  325. *reply_string_size += len;
  326. }
  327. static void send_command_reply(struct command_context *cmd_ctx, cmd_status_t status, char *message)
  328. {
  329. int ret;
  330. char reply_string[MAX_COMMAND_LENGTH] = {'\0', };
  331. char exit_status_string[MAX_EXIT_STATUS_LENGTH + 1] = {'\0', };
  332. unsigned reply_string_size = 0;
  333. uv_buf_t write_buf;
  334. uv_stream_t *client = (uv_stream_t *)(uv_pipe_t *)cmd_ctx;
  335. snprintfz(exit_status_string, MAX_EXIT_STATUS_LENGTH, "%u", status);
  336. add_char_to_command_reply(reply_string, &reply_string_size, CMD_PREFIX_EXIT_CODE);
  337. add_string_to_command_reply(reply_string, &reply_string_size, exit_status_string);
  338. add_char_to_command_reply(reply_string, &reply_string_size, '\0');
  339. if (message) {
  340. add_char_to_command_reply(reply_string, &reply_string_size, cmd_prefix_by_status[status]);
  341. add_string_to_command_reply(reply_string, &reply_string_size, message);
  342. }
  343. cmd_ctx->write_req.data = client;
  344. write_buf.base = reply_string;
  345. write_buf.len = reply_string_size;
  346. ret = uv_write(&cmd_ctx->write_req, (uv_stream_t *)client, &write_buf, 1, pipe_write_cb);
  347. if (ret) {
  348. error("uv_write(): %s", uv_strerror(ret));
  349. }
  350. info("COMMAND: Sending reply: \"%s\"", reply_string);
  351. }
  352. cmd_status_t execute_command(cmd_t idx, char *args, char **message)
  353. {
  354. cmd_status_t status;
  355. cmd_type_t type = command_info_array[idx].type;
  356. cmd_lock_by_type[type](idx);
  357. status = command_info_array[idx].func(args, message);
  358. cmd_unlock_by_type[type](idx);
  359. return status;
  360. }
  361. static void after_schedule_command(uv_work_t *req, int status)
  362. {
  363. struct command_context *cmd_ctx = req->data;
  364. (void)status;
  365. send_command_reply(cmd_ctx, cmd_ctx->status, cmd_ctx->message);
  366. if (cmd_ctx->message)
  367. freez(cmd_ctx->message);
  368. }
  369. static void schedule_command(uv_work_t *req)
  370. {
  371. struct command_context *cmd_ctx = req->data;
  372. cmd_ctx->status = execute_command(cmd_ctx->idx, cmd_ctx->args, &cmd_ctx->message);
  373. }
  374. /* This will alter the state of the command_info_array.cmd_str
  375. */
  376. static void parse_commands(struct command_context *cmd_ctx)
  377. {
  378. char *message = NULL, *pos, *lstrip, *rstrip;
  379. cmd_t i;
  380. cmd_status_t status;
  381. status = CMD_STATUS_FAILURE;
  382. /* Skip white-space characters */
  383. for (pos = cmd_ctx->command_string ; isspace(*pos) && ('\0' != *pos) ; ++pos) {;}
  384. for (i = 0 ; i < CMD_TOTAL_COMMANDS ; ++i) {
  385. if (!strncmp(pos, command_info_array[i].cmd_str, strlen(command_info_array[i].cmd_str))) {
  386. if (CMD_EXIT == i) {
  387. /* musl C does not like libuv workqueues calling exit() */
  388. execute_command(CMD_EXIT, NULL, NULL);
  389. }
  390. for (lstrip=pos + strlen(command_info_array[i].cmd_str); isspace(*lstrip) && ('\0' != *lstrip); ++lstrip) {;}
  391. for (rstrip=lstrip+strlen(lstrip)-1; rstrip>lstrip && isspace(*rstrip); *(rstrip--) = 0 );
  392. cmd_ctx->work.data = cmd_ctx;
  393. cmd_ctx->idx = i;
  394. cmd_ctx->args = lstrip;
  395. cmd_ctx->message = NULL;
  396. fatal_assert(0 == uv_queue_work(loop, &cmd_ctx->work, schedule_command, after_schedule_command));
  397. break;
  398. }
  399. }
  400. if (CMD_TOTAL_COMMANDS == i) {
  401. /* no command found */
  402. message = strdupz("Illegal command. Please type \"help\" for instructions.");
  403. send_command_reply(cmd_ctx, status, message);
  404. freez(message);
  405. }
  406. }
  407. static void pipe_read_cb(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf)
  408. {
  409. struct command_context *cmd_ctx = (struct command_context *)client;
  410. if (0 == nread) {
  411. info("%s: Zero bytes read by command pipe.", __func__);
  412. } else if (UV_EOF == nread) {
  413. info("EOF found in command pipe.");
  414. parse_commands(cmd_ctx);
  415. } else if (nread < 0) {
  416. error("%s: %s", __func__, uv_strerror(nread));
  417. }
  418. if (nread < 0) { /* stop stream due to EOF or error */
  419. (void)uv_read_stop((uv_stream_t *)client);
  420. } else if (nread) {
  421. size_t to_copy;
  422. to_copy = MIN(nread, MAX_COMMAND_LENGTH - 1 - cmd_ctx->command_string_size);
  423. memcpy(cmd_ctx->command_string + cmd_ctx->command_string_size, buf->base, to_copy);
  424. cmd_ctx->command_string_size += to_copy;
  425. cmd_ctx->command_string[cmd_ctx->command_string_size] = '\0';
  426. }
  427. if (buf && buf->len) {
  428. freez(buf->base);
  429. }
  430. if (nread < 0 && UV_EOF != nread) {
  431. uv_close((uv_handle_t *)client, pipe_close_cb);
  432. --clients;
  433. info("Command Clients = %u\n", clients);
  434. }
  435. }
  436. static void alloc_cb(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf)
  437. {
  438. (void)handle;
  439. buf->base = mallocz(suggested_size);
  440. buf->len = suggested_size;
  441. }
  442. static void connection_cb(uv_stream_t *server, int status)
  443. {
  444. int ret;
  445. uv_pipe_t *client;
  446. struct command_context *cmd_ctx;
  447. fatal_assert(status == 0);
  448. /* combined allocation of client pipe and command context */
  449. cmd_ctx = mallocz(sizeof(*cmd_ctx));
  450. client = (uv_pipe_t *)cmd_ctx;
  451. ret = uv_pipe_init(server->loop, client, 1);
  452. if (ret) {
  453. error("uv_pipe_init(): %s", uv_strerror(ret));
  454. freez(cmd_ctx);
  455. return;
  456. }
  457. ret = uv_accept(server, (uv_stream_t *)client);
  458. if (ret) {
  459. error("uv_accept(): %s", uv_strerror(ret));
  460. uv_close((uv_handle_t *)client, pipe_close_cb);
  461. return;
  462. }
  463. ++clients;
  464. info("Command Clients = %u\n", clients);
  465. /* Start parsing a new command */
  466. cmd_ctx->command_string_size = 0;
  467. cmd_ctx->command_string[0] = '\0';
  468. ret = uv_read_start((uv_stream_t*)client, alloc_cb, pipe_read_cb);
  469. if (ret) {
  470. error("uv_read_start(): %s", uv_strerror(ret));
  471. uv_close((uv_handle_t *)client, pipe_close_cb);
  472. --clients;
  473. info("Command Clients = %u\n", clients);
  474. return;
  475. }
  476. }
  477. static void async_cb(uv_async_t *handle)
  478. {
  479. uv_stop(handle->loop);
  480. }
  481. static void command_thread(void *arg)
  482. {
  483. int ret;
  484. uv_fs_t req;
  485. (void) arg;
  486. loop = mallocz(sizeof(uv_loop_t));
  487. ret = uv_loop_init(loop);
  488. if (ret) {
  489. error("uv_loop_init(): %s", uv_strerror(ret));
  490. command_thread_error = ret;
  491. goto error_after_loop_init;
  492. }
  493. loop->data = NULL;
  494. ret = uv_async_init(loop, &async, async_cb);
  495. if (ret) {
  496. error("uv_async_init(): %s", uv_strerror(ret));
  497. command_thread_error = ret;
  498. goto error_after_async_init;
  499. }
  500. async.data = NULL;
  501. ret = uv_pipe_init(loop, &server_pipe, 0);
  502. if (ret) {
  503. error("uv_pipe_init(): %s", uv_strerror(ret));
  504. command_thread_error = ret;
  505. goto error_after_pipe_init;
  506. }
  507. (void)uv_fs_unlink(loop, &req, PIPENAME, NULL);
  508. uv_fs_req_cleanup(&req);
  509. ret = uv_pipe_bind(&server_pipe, PIPENAME);
  510. if (ret) {
  511. error("uv_pipe_bind(): %s", uv_strerror(ret));
  512. command_thread_error = ret;
  513. goto error_after_pipe_bind;
  514. }
  515. ret = uv_listen((uv_stream_t *)&server_pipe, SOMAXCONN, connection_cb);
  516. if (ret) {
  517. /* Fallback to backlog of 1 */
  518. info("uv_listen() failed with backlog = %d, falling back to backlog = 1.", SOMAXCONN);
  519. ret = uv_listen((uv_stream_t *)&server_pipe, 1, connection_cb);
  520. }
  521. if (ret) {
  522. error("uv_listen(): %s", uv_strerror(ret));
  523. command_thread_error = ret;
  524. goto error_after_uv_listen;
  525. }
  526. command_thread_error = 0;
  527. command_thread_shutdown = 0;
  528. /* wake up initialization thread */
  529. complete(&completion);
  530. while (command_thread_shutdown == 0) {
  531. uv_run(loop, UV_RUN_DEFAULT);
  532. }
  533. /* cleanup operations of the event loop */
  534. info("Shutting down command event loop.");
  535. uv_close((uv_handle_t *)&async, NULL);
  536. uv_close((uv_handle_t*)&server_pipe, NULL);
  537. uv_run(loop, UV_RUN_DEFAULT); /* flush all libuv handles */
  538. info("Shutting down command loop complete.");
  539. fatal_assert(0 == uv_loop_close(loop));
  540. freez(loop);
  541. return;
  542. error_after_uv_listen:
  543. error_after_pipe_bind:
  544. uv_close((uv_handle_t*)&server_pipe, NULL);
  545. error_after_pipe_init:
  546. uv_close((uv_handle_t *)&async, NULL);
  547. error_after_async_init:
  548. uv_run(loop, UV_RUN_DEFAULT); /* flush all libuv handles */
  549. fatal_assert(0 == uv_loop_close(loop));
  550. error_after_loop_init:
  551. freez(loop);
  552. /* wake up initialization thread */
  553. complete(&completion);
  554. }
  555. static void sanity_check(void)
  556. {
  557. /* The size of command_info_array must be CMD_TOTAL_COMMANDS elements */
  558. BUILD_BUG_ON(CMD_TOTAL_COMMANDS != sizeof(command_info_array) / sizeof(command_info_array[0]));
  559. }
  560. void commands_init(void)
  561. {
  562. cmd_t i;
  563. int error;
  564. sanity_check();
  565. if (command_server_initialized)
  566. return;
  567. info("Initializing command server.");
  568. for (i = 0 ; i < CMD_TOTAL_COMMANDS ; ++i) {
  569. fatal_assert(0 == uv_mutex_init(&command_lock_array[i]));
  570. }
  571. fatal_assert(0 == uv_rwlock_init(&exclusive_rwlock));
  572. init_completion(&completion);
  573. error = uv_thread_create(&thread, command_thread, NULL);
  574. if (error) {
  575. error("uv_thread_create(): %s", uv_strerror(error));
  576. goto after_error;
  577. }
  578. /* wait for worker thread to initialize */
  579. wait_for_completion(&completion);
  580. destroy_completion(&completion);
  581. uv_thread_set_name_np(thread, "DAEMON_COMMAND");
  582. if (command_thread_error) {
  583. error = uv_thread_join(&thread);
  584. if (error) {
  585. error("uv_thread_create(): %s", uv_strerror(error));
  586. }
  587. goto after_error;
  588. }
  589. command_server_initialized = 1;
  590. return;
  591. after_error:
  592. error("Failed to initialize command server. The netdata cli tool will be unable to send commands.");
  593. }
  594. void commands_exit(void)
  595. {
  596. cmd_t i;
  597. if (!command_server_initialized)
  598. return;
  599. command_thread_shutdown = 1;
  600. info("Shutting down command server.");
  601. /* wake up event loop */
  602. fatal_assert(0 == uv_async_send(&async));
  603. fatal_assert(0 == uv_thread_join(&thread));
  604. for (i = 0 ; i < CMD_TOTAL_COMMANDS ; ++i) {
  605. uv_mutex_destroy(&command_lock_array[i]);
  606. }
  607. uv_rwlock_destroy(&exclusive_rwlock);
  608. info("Command server has stopped.");
  609. command_server_initialized = 0;
  610. }