commands.c 23 KB

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