commands.c 22 KB

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