commands.c 22 KB

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