spawn_server.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "spawn.h"
  3. static uv_loop_t *loop;
  4. static uv_pipe_t server_pipe;
  5. static int server_shutdown = 0;
  6. static uv_thread_t thread;
  7. /* spawn outstanding execution structure */
  8. static avl_tree_lock spawn_outstanding_exec_tree;
  9. static char prot_buffer[MAX_COMMAND_LENGTH];
  10. static unsigned prot_buffer_len = 0;
  11. struct spawn_execution_info {
  12. avl_t avl;
  13. void *handle;
  14. int exit_status;
  15. pid_t pid;
  16. struct spawn_execution_info *next;
  17. };
  18. int spawn_exec_compare(void *a, void *b)
  19. {
  20. struct spawn_execution_info *spwna = a, *spwnb = b;
  21. if (spwna->pid < spwnb->pid) return -1;
  22. if (spwna->pid > spwnb->pid) return 1;
  23. return 0;
  24. }
  25. /* wake up waiter thread to reap the spawned processes */
  26. static uv_mutex_t wait_children_mutex;
  27. static uv_cond_t wait_children_cond;
  28. static uint8_t spawned_processes;
  29. static struct spawn_execution_info *child_waited_list;
  30. static uv_async_t child_waited_async;
  31. static inline struct spawn_execution_info *dequeue_child_waited_list(void)
  32. {
  33. struct spawn_execution_info *exec_info;
  34. uv_mutex_lock(&wait_children_mutex);
  35. if (NULL == child_waited_list) {
  36. exec_info = NULL;
  37. } else {
  38. exec_info = child_waited_list;
  39. child_waited_list = exec_info->next;
  40. }
  41. uv_mutex_unlock(&wait_children_mutex);
  42. return exec_info;
  43. }
  44. static inline void enqueue_child_waited_list(struct spawn_execution_info *exec_info)
  45. {
  46. uv_mutex_lock(&wait_children_mutex);
  47. exec_info->next = child_waited_list;
  48. child_waited_list = exec_info;
  49. uv_mutex_unlock(&wait_children_mutex);
  50. }
  51. static void after_pipe_write(uv_write_t *req, int status)
  52. {
  53. (void)status;
  54. #ifdef SPAWN_DEBUG
  55. fprintf(stderr, "SERVER %s called status=%d\n", __func__, status);
  56. #endif
  57. freez(req->data);
  58. }
  59. static void child_waited_async_cb(uv_async_t *async_handle)
  60. {
  61. uv_buf_t writebuf[2];
  62. int ret;
  63. struct spawn_execution_info *exec_info;
  64. struct write_context *write_ctx;
  65. (void)async_handle;
  66. while (NULL != (exec_info = dequeue_child_waited_list())) {
  67. write_ctx = mallocz(sizeof(*write_ctx));
  68. write_ctx->write_req.data = write_ctx;
  69. write_ctx->header.opcode = SPAWN_PROT_CMD_EXIT_STATUS;
  70. write_ctx->header.handle = exec_info->handle;
  71. write_ctx->exit_status.exec_exit_status = exec_info->exit_status;
  72. writebuf[0] = uv_buf_init((char *) &write_ctx->header, sizeof(write_ctx->header));
  73. writebuf[1] = uv_buf_init((char *) &write_ctx->exit_status, sizeof(write_ctx->exit_status));
  74. #ifdef SPAWN_DEBUG
  75. fprintf(stderr, "SERVER %s SPAWN_PROT_CMD_EXIT_STATUS\n", __func__);
  76. #endif
  77. ret = uv_write(&write_ctx->write_req, (uv_stream_t *) &server_pipe, writebuf, 2, after_pipe_write);
  78. fatal_assert(ret == 0);
  79. freez(exec_info);
  80. }
  81. }
  82. static void wait_children(void *arg)
  83. {
  84. siginfo_t i;
  85. struct spawn_execution_info tmp, *exec_info;
  86. avl_t *ret_avl;
  87. (void)arg;
  88. while (!server_shutdown) {
  89. uv_mutex_lock(&wait_children_mutex);
  90. while (!spawned_processes) {
  91. uv_cond_wait(&wait_children_cond, &wait_children_mutex);
  92. }
  93. spawned_processes = 0;
  94. uv_mutex_unlock(&wait_children_mutex);
  95. while (!server_shutdown) {
  96. i.si_pid = 0;
  97. if (waitid(P_ALL, (id_t) 0, &i, WEXITED) == -1) {
  98. if (errno != ECHILD)
  99. fprintf(stderr, "SPAWN: Failed to wait: %s\n", strerror(errno));
  100. break;
  101. }
  102. if (i.si_pid == 0) {
  103. fprintf(stderr, "SPAWN: No child exited.\n");
  104. break;
  105. }
  106. #ifdef SPAWN_DEBUG
  107. fprintf(stderr, "SPAWN: Successfully waited for pid:%d.\n", (int) i.si_pid);
  108. #endif
  109. fatal_assert(CLD_EXITED == i.si_code);
  110. tmp.pid = (pid_t)i.si_pid;
  111. while (NULL == (ret_avl = avl_remove_lock(&spawn_outstanding_exec_tree, (avl_t *)&tmp))) {
  112. fprintf(stderr,
  113. "SPAWN: race condition detected, waiting for child process %d to be indexed.\n",
  114. (int)tmp.pid);
  115. (void)sleep_usec(10000); /* 10 msec */
  116. }
  117. exec_info = (struct spawn_execution_info *)ret_avl;
  118. exec_info->exit_status = i.si_status;
  119. enqueue_child_waited_list(exec_info);
  120. /* wake up event loop */
  121. fatal_assert(0 == uv_async_send(&child_waited_async));
  122. }
  123. }
  124. }
  125. void spawn_protocol_execute_command(void *handle, char *command_to_run, uint16_t command_length)
  126. {
  127. uv_buf_t writebuf[2];
  128. int ret;
  129. avl_t *avl_ret;
  130. struct spawn_execution_info *exec_info;
  131. struct write_context *write_ctx;
  132. write_ctx = mallocz(sizeof(*write_ctx));
  133. write_ctx->write_req.data = write_ctx;
  134. command_to_run[command_length] = '\0';
  135. #ifdef SPAWN_DEBUG
  136. fprintf(stderr, "SPAWN: executing command '%s'\n", command_to_run);
  137. #endif
  138. if (netdata_spawn(command_to_run, &write_ctx->spawn_result.exec_pid)) {
  139. fprintf(stderr, "SPAWN: Cannot spawn(\"%s\", \"r\").\n", command_to_run);
  140. write_ctx->spawn_result.exec_pid = 0;
  141. } else { /* successfully spawned command */
  142. write_ctx->spawn_result.exec_run_timestamp = now_realtime_sec();
  143. /* record it for when the process finishes execution */
  144. exec_info = mallocz(sizeof(*exec_info));
  145. exec_info->handle = handle;
  146. exec_info->pid = write_ctx->spawn_result.exec_pid;
  147. avl_ret = avl_insert_lock(&spawn_outstanding_exec_tree, (avl_t *)exec_info);
  148. fatal_assert(avl_ret == (avl_t *)exec_info);
  149. /* wake up the thread that blocks waiting for processes to exit */
  150. uv_mutex_lock(&wait_children_mutex);
  151. spawned_processes = 1;
  152. uv_cond_signal(&wait_children_cond);
  153. uv_mutex_unlock(&wait_children_mutex);
  154. }
  155. write_ctx->header.opcode = SPAWN_PROT_SPAWN_RESULT;
  156. write_ctx->header.handle = handle;
  157. writebuf[0] = uv_buf_init((char *)&write_ctx->header, sizeof(write_ctx->header));
  158. writebuf[1] = uv_buf_init((char *)&write_ctx->spawn_result, sizeof(write_ctx->spawn_result));
  159. #ifdef SPAWN_DEBUG
  160. fprintf(stderr, "SERVER %s SPAWN_PROT_SPAWN_RESULT\n", __func__);
  161. #endif
  162. ret = uv_write(&write_ctx->write_req, (uv_stream_t *)&server_pipe, writebuf, 2, after_pipe_write);
  163. fatal_assert(ret == 0);
  164. }
  165. static void server_parse_spawn_protocol(unsigned source_len, char *source)
  166. {
  167. unsigned required_len;
  168. struct spawn_prot_header *header;
  169. struct spawn_prot_exec_cmd *payload;
  170. uint16_t command_length;
  171. while (source_len) {
  172. required_len = sizeof(*header);
  173. if (prot_buffer_len < required_len)
  174. copy_to_prot_buffer(prot_buffer, &prot_buffer_len, required_len - prot_buffer_len, &source, &source_len);
  175. if (prot_buffer_len < required_len)
  176. return; /* Source buffer ran out */
  177. header = (struct spawn_prot_header *)prot_buffer;
  178. fatal_assert(SPAWN_PROT_EXEC_CMD == header->opcode);
  179. fatal_assert(NULL != header->handle);
  180. required_len += sizeof(*payload);
  181. if (prot_buffer_len < required_len)
  182. copy_to_prot_buffer(prot_buffer, &prot_buffer_len, required_len - prot_buffer_len, &source, &source_len);
  183. if (prot_buffer_len < required_len)
  184. return; /* Source buffer ran out */
  185. payload = (struct spawn_prot_exec_cmd *)(header + 1);
  186. command_length = payload->command_length;
  187. required_len += command_length;
  188. if (unlikely(required_len > MAX_COMMAND_LENGTH - 1)) {
  189. fprintf(stderr, "SPAWN: Ran out of protocol buffer space.\n");
  190. command_length = (MAX_COMMAND_LENGTH - 1) - (sizeof(*header) + sizeof(*payload));
  191. required_len = MAX_COMMAND_LENGTH - 1;
  192. }
  193. if (prot_buffer_len < required_len)
  194. copy_to_prot_buffer(prot_buffer, &prot_buffer_len, required_len - prot_buffer_len, &source, &source_len);
  195. if (prot_buffer_len < required_len)
  196. return; /* Source buffer ran out */
  197. spawn_protocol_execute_command(header->handle, payload->command_to_run, command_length);
  198. prot_buffer_len = 0;
  199. }
  200. }
  201. static void on_pipe_read(uv_stream_t *pipe, ssize_t nread, const uv_buf_t *buf)
  202. {
  203. if (0 == nread) {
  204. fprintf(stderr, "SERVER %s: Zero bytes read from spawn pipe.\n", __func__);
  205. } else if (UV_EOF == nread) {
  206. fprintf(stderr, "EOF found in spawn pipe.\n");
  207. } else if (nread < 0) {
  208. fprintf(stderr, "%s: %s\n", __func__, uv_strerror(nread));
  209. }
  210. if (nread < 0) { /* stop spawn server due to EOF or error */
  211. int error;
  212. uv_mutex_lock(&wait_children_mutex);
  213. server_shutdown = 1;
  214. spawned_processes = 1;
  215. uv_cond_signal(&wait_children_cond);
  216. uv_mutex_unlock(&wait_children_mutex);
  217. fprintf(stderr, "Shutting down spawn server event loop.\n");
  218. /* cleanup operations of the event loop */
  219. (void)uv_read_stop((uv_stream_t *) pipe);
  220. uv_close((uv_handle_t *)&server_pipe, NULL);
  221. error = uv_thread_join(&thread);
  222. if (error) {
  223. fprintf(stderr, "uv_thread_create(): %s", uv_strerror(error));
  224. }
  225. /* After joining it is safe to destroy child_waited_async */
  226. uv_close((uv_handle_t *)&child_waited_async, NULL);
  227. } else if (nread) {
  228. #ifdef SPAWN_DEBUG
  229. fprintf(stderr, "SERVER %s nread %u\n", __func__, (unsigned)nread);
  230. #endif
  231. server_parse_spawn_protocol(nread, buf->base);
  232. }
  233. if (buf && buf->len) {
  234. freez(buf->base);
  235. }
  236. }
  237. static void on_read_alloc(uv_handle_t *handle,
  238. size_t suggested_size,
  239. uv_buf_t* buf)
  240. {
  241. (void)handle;
  242. buf->base = mallocz(suggested_size);
  243. buf->len = suggested_size;
  244. }
  245. static void ignore_signal_handler(int signo) {
  246. /*
  247. * By having a signal handler we allow spawned processes to reset default signal dispositions. Setting SIG_IGN
  248. * would be inherited by the spawned children which is not desirable.
  249. */
  250. (void)signo;
  251. }
  252. void spawn_server(void)
  253. {
  254. int error;
  255. test_clock_boottime();
  256. test_clock_monotonic_coarse();
  257. // close all open file descriptors, except the standard ones
  258. // the caller may have left open files (lxc-attach has this issue)
  259. int fd;
  260. for(fd = (int)(sysconf(_SC_OPEN_MAX) - 1) ; fd > 2 ; --fd)
  261. if(fd_is_valid(fd))
  262. close(fd);
  263. // Have the libuv IPC pipe be closed when forking child processes
  264. (void) fcntl(0, F_SETFD, FD_CLOEXEC);
  265. fprintf(stderr, "Spawn server is up.\n");
  266. // Define signals we want to ignore
  267. struct sigaction sa;
  268. int signals_to_ignore[] = {SIGPIPE, SIGINT, SIGQUIT, SIGTERM, SIGHUP, SIGUSR1, SIGUSR2, SIGBUS, SIGCHLD};
  269. unsigned ignore_length = sizeof(signals_to_ignore) / sizeof(signals_to_ignore[0]);
  270. unsigned i;
  271. for (i = 0; i < ignore_length ; ++i) {
  272. sa.sa_flags = 0;
  273. sigemptyset(&sa.sa_mask);
  274. sa.sa_handler = ignore_signal_handler;
  275. if(sigaction(signals_to_ignore[i], &sa, NULL) == -1)
  276. fprintf(stderr, "SPAWN: Failed to change signal handler for signal: %d.\n", signals_to_ignore[i]);
  277. }
  278. signals_unblock();
  279. loop = uv_default_loop();
  280. loop->data = NULL;
  281. error = uv_pipe_init(loop, &server_pipe, 1);
  282. if (error) {
  283. fprintf(stderr, "uv_pipe_init(): %s\n", uv_strerror(error));
  284. exit(error);
  285. }
  286. fatal_assert(server_pipe.ipc);
  287. error = uv_pipe_open(&server_pipe, 0 /* UV_STDIN_FD */);
  288. if (error) {
  289. fprintf(stderr, "uv_pipe_open(): %s\n", uv_strerror(error));
  290. exit(error);
  291. }
  292. avl_init_lock(&spawn_outstanding_exec_tree, spawn_exec_compare);
  293. spawned_processes = 0;
  294. fatal_assert(0 == uv_cond_init(&wait_children_cond));
  295. fatal_assert(0 == uv_mutex_init(&wait_children_mutex));
  296. child_waited_list = NULL;
  297. error = uv_async_init(loop, &child_waited_async, child_waited_async_cb);
  298. if (error) {
  299. fprintf(stderr, "uv_async_init(): %s\n", uv_strerror(error));
  300. exit(error);
  301. }
  302. error = uv_thread_create(&thread, wait_children, NULL);
  303. if (error) {
  304. fprintf(stderr, "uv_thread_create(): %s\n", uv_strerror(error));
  305. exit(error);
  306. }
  307. prot_buffer_len = 0;
  308. error = uv_read_start((uv_stream_t *)&server_pipe, on_read_alloc, on_pipe_read);
  309. fatal_assert(error == 0);
  310. while (!server_shutdown) {
  311. uv_run(loop, UV_RUN_DEFAULT);
  312. }
  313. fprintf(stderr, "Shutting down spawn server loop complete.\n");
  314. fatal_assert(0 == uv_loop_close(loop));
  315. exit(0);
  316. }