commands.c 23 KB

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