commands.c 23 KB

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