baseproc-service.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. #include <cstring>
  2. #include <cstdlib>
  3. #include <sys/un.h>
  4. #include <sys/socket.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <unistd.h>
  8. #include "dinit.h"
  9. #include "dinit-log.h"
  10. #include "dinit-socket.h"
  11. #include "proc-service.h"
  12. #include "baseproc-sys.h"
  13. /*
  14. * Base process implementation (base_process_service).
  15. *
  16. * See proc-service.h for interface documentation.
  17. */
  18. void base_process_service::do_smooth_recovery() noexcept
  19. {
  20. if (!restart_ps_process()) {
  21. unrecoverable_stop();
  22. services->process_queues();
  23. }
  24. }
  25. bool base_process_service::bring_up() noexcept
  26. {
  27. if (!open_socket()) {
  28. return false;
  29. }
  30. bool start_success;
  31. if (in_auto_restart) {
  32. start_success = restart_ps_process();
  33. }
  34. else {
  35. restart_interval_count = 0;
  36. start_success = start_ps_process(exec_arg_parts,
  37. onstart_flags.starts_on_console || onstart_flags.shares_console);
  38. // start_ps_process updates last_start_time, use it also for restart_interval_time:
  39. restart_interval_time = last_start_time;
  40. // Arm start timer. (For restarts, this is only done once the restart interval expires).
  41. if (start_success) {
  42. if (start_timeout != time_val(0,0)) {
  43. process_timer.arm_timer_rel(event_loop, start_timeout);
  44. waiting_stopstart_timer = true;
  45. }
  46. else if (waiting_stopstart_timer) {
  47. process_timer.stop_timer(event_loop);
  48. waiting_stopstart_timer = false;
  49. }
  50. }
  51. }
  52. return start_success;
  53. }
  54. void base_process_service::handle_unexpected_termination() noexcept
  55. {
  56. // unexpected termination, with possible restart
  57. stop_reason = stopped_reason_t::TERMINATED;
  58. // We want to circumvent the normal process of waiting for dependents to stop before we
  59. // attempt to restart, for two reasons:
  60. // 1) we can restart more quickly
  61. // 2) we can use the restart rate-limiting logic from restart_ps_process rather than
  62. // the usual start_ps_process (the usual bring-up).
  63. // But we need to issue a forced stop and process queues, to discover our eventual target
  64. // state (so we know whether we actually want to restart or not).
  65. // Note we can't call forced_stop() directly here, because we need to set in_auto_restart in
  66. // between do_stop() and processing queues (so that it is set correctly if restart occurs):
  67. force_stop = true;
  68. do_stop();
  69. services->process_queues();
  70. if (get_state() == service_state_t::STOPPING) {
  71. // We must be waiting for dependents;
  72. // If we're going to restart, we can kick that off now:
  73. if (get_target_state() == service_state_t::STARTED && !pinned_stopped) {
  74. initiate_start();
  75. services->process_queues();
  76. }
  77. }
  78. }
  79. bool base_process_service::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
  80. {
  81. // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
  82. // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
  83. // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
  84. // is written to the pipe, and the parent can read it.
  85. event_loop.get_time(last_start_time, clock_type::MONOTONIC);
  86. int pipefd[2];
  87. if (bp_sys::pipe2(pipefd, O_CLOEXEC)) {
  88. log(loglevel_t::ERROR, get_name(), ": can't create status check pipe: ", strerror(errno));
  89. return false;
  90. }
  91. const char * logfile = this->logfile.c_str();
  92. if (this->log_type == log_type_id::LOGFILE || this->log_type == log_type_id::NONE) {
  93. if (*logfile == 0) {
  94. logfile = "/dev/null";
  95. }
  96. }
  97. else /* log_type_id::BUFFER */ {
  98. if (this->log_output_fd == -1) {
  99. int logfd[2];
  100. // Note: we set CLOEXEC on the file descriptors here; when the output file descriptor is dup'd
  101. // to stdout, this will be effectively removed for the output end
  102. if (bp_sys::pipe2(logfd, O_CLOEXEC)) {
  103. log(loglevel_t::ERROR, get_name(), ": can't create output pipe: ", strerror(errno));
  104. goto out_p;
  105. }
  106. this->log_input_fd = logfd[0];
  107. this->log_output_fd = logfd[1];
  108. try {
  109. this->log_output_listener.add_watch(event_loop, logfd[0], dasynq::IN_EVENTS,
  110. false /* not enabled */);
  111. }
  112. catch (...) {
  113. log(loglevel_t::ERROR, get_name(), ": can't add output watch (insufficient resources)");
  114. bp_sys::close(this->log_input_fd);
  115. bp_sys::close(this->log_output_fd);
  116. this->log_input_fd = -1;
  117. this->log_output_fd = -1;
  118. goto out_p;
  119. }
  120. }
  121. // (More is done below, after we have performed additional setup)
  122. }
  123. {
  124. bool child_status_registered = false;
  125. control_conn_t *control_conn = nullptr;
  126. int control_socket[2] = {-1, -1};
  127. int notify_pipe[2] = {-1, -1};
  128. bool have_notify = !notification_var.empty() || force_notification_fd != -1;
  129. ready_notify_watcher * rwatcher = have_notify ? get_ready_watcher() : nullptr;
  130. bool ready_watcher_registered = false;
  131. if (onstart_flags.pass_cs_fd) {
  132. if (dinit_socketpair(AF_UNIX, SOCK_STREAM, /* protocol */ 0, control_socket, SOCK_NONBLOCK)) {
  133. log(loglevel_t::ERROR, get_name(), ": can't create control socket: ", strerror(errno));
  134. goto out_lfd;
  135. }
  136. // Make the server side socket close-on-exec:
  137. int fdflags = bp_sys::fcntl(control_socket[0], F_GETFD);
  138. bp_sys::fcntl(control_socket[0], F_SETFD, fdflags | FD_CLOEXEC);
  139. try {
  140. control_conn = new control_conn_t(event_loop, services, control_socket[0]);
  141. }
  142. catch (std::exception &exc) {
  143. log(loglevel_t::ERROR, get_name(), ": can't launch process; out of memory");
  144. goto out_cs;
  145. }
  146. }
  147. if (have_notify) {
  148. // Create a notification pipe:
  149. if (bp_sys::pipe2(notify_pipe, 0) != 0) {
  150. log(loglevel_t::ERROR, get_name(), ": can't create notification pipe: ", strerror(errno));
  151. goto out_cs_h;
  152. }
  153. // Set the read side as close-on-exec:
  154. int fdflags = bp_sys::fcntl(notify_pipe[0], F_GETFD);
  155. bp_sys::fcntl(notify_pipe[0], F_SETFD, fdflags | FD_CLOEXEC);
  156. // add, but don't yet enable, readiness watcher:
  157. try {
  158. rwatcher->add_watch(event_loop, notify_pipe[0], dasynq::IN_EVENTS, false);
  159. ready_watcher_registered = true;
  160. }
  161. catch (std::exception &exc) {
  162. log(loglevel_t::ERROR, get_name(), ": can't add notification watch: ", exc.what());
  163. goto out_cs_h;
  164. }
  165. }
  166. if (log_type == log_type_id::BUFFER) {
  167. // Set watcher enabled if space in buffer
  168. if (log_buf_size > 0) {
  169. // Append a "restarted" message to buffer contents
  170. const char *restarting_msg = "\n(dinit: note: service restarted)\n";
  171. unsigned restarting_msg_len = strlen(restarting_msg);
  172. bool trailing_nl = log_buffer[log_buf_size - 1] == '\n';
  173. if (trailing_nl) {
  174. ++restarting_msg; // trim leading newline
  175. --restarting_msg_len;
  176. }
  177. if (log_buf_size + restarting_msg_len >= log_buf_max) {
  178. goto skip_enable_log_watch;
  179. }
  180. if (!ensure_log_buffer_backing(log_buf_size + restarting_msg_len)) {
  181. goto skip_enable_log_watch;
  182. }
  183. memcpy(log_buffer.data() + log_buf_size, restarting_msg, restarting_msg_len);
  184. log_buf_size += restarting_msg_len;
  185. }
  186. log_output_listener.set_enabled(event_loop, true);
  187. }
  188. skip_enable_log_watch: ;
  189. // Set up complete, now fork and exec:
  190. pid_t forkpid;
  191. try {
  192. child_status_listener.add_watch(event_loop, pipefd[0], dasynq::IN_EVENTS);
  193. child_status_registered = true;
  194. // We specify a high priority (i.e. low priority value) so that process termination is
  195. // handled early. This means we have always recorded that the process is terminated by the
  196. // time that we handle events that might otherwise cause us to signal the process, so we
  197. // avoid sending a signal to an invalid (and possibly recycled) process ID.
  198. forkpid = child_listener.fork(event_loop, reserved_child_watch, dasynq::DEFAULT_PRIORITY - 10);
  199. reserved_child_watch = true;
  200. }
  201. catch (std::exception &e) {
  202. log(loglevel_t::ERROR, get_name(), ": could not fork: ", e.what());
  203. goto out_cs_h;
  204. }
  205. if (forkpid == 0) {
  206. const char * working_dir_c = nullptr;
  207. if (! working_dir.empty()) working_dir_c = working_dir.c_str();
  208. after_fork(getpid());
  209. run_proc_params run_params{cmd.data(), working_dir_c, logfile, pipefd[1], run_as_uid, run_as_gid, rlimits};
  210. run_params.on_console = on_console;
  211. run_params.in_foreground = !onstart_flags.shares_console;
  212. run_params.csfd = control_socket[1];
  213. run_params.socket_fd = socket_fd;
  214. run_params.notify_fd = notify_pipe[1];
  215. run_params.force_notify_fd = force_notification_fd;
  216. run_params.notify_var = notification_var.c_str();
  217. run_params.env_file = env_file.c_str();
  218. run_params.output_fd = log_output_fd;
  219. #if SUPPORT_CGROUPS
  220. run_params.run_in_cgroup = run_in_cgroup.c_str();
  221. #endif
  222. run_child_proc(run_params);
  223. }
  224. else {
  225. // Parent process
  226. pid = forkpid;
  227. bp_sys::close(pipefd[1]); // close the 'other end' fd
  228. if (control_socket[1] != -1) bp_sys::close(control_socket[1]);
  229. if (notify_pipe[1] != -1) bp_sys::close(notify_pipe[1]);
  230. notification_fd = notify_pipe[0];
  231. waiting_for_execstat = true;
  232. return true;
  233. }
  234. // Failure exit:
  235. out_cs_h:
  236. if (child_status_registered) {
  237. child_status_listener.deregister(event_loop);
  238. }
  239. if (notify_pipe[0] != -1) bp_sys::close(notify_pipe[0]);
  240. if (notify_pipe[1] != -1) bp_sys::close(notify_pipe[1]);
  241. if (ready_watcher_registered) {
  242. rwatcher->deregister(event_loop);
  243. }
  244. if (onstart_flags.pass_cs_fd) {
  245. delete control_conn;
  246. out_cs:
  247. bp_sys::close(control_socket[0]);
  248. bp_sys::close(control_socket[1]);
  249. }
  250. }
  251. out_lfd:
  252. if (log_input_fd != -1) {
  253. log_output_listener.deregister(event_loop);
  254. bp_sys::close(log_input_fd);
  255. bp_sys::close(log_output_fd);
  256. log_input_fd = -1;
  257. log_output_fd = -1;
  258. }
  259. out_p:
  260. bp_sys::close(pipefd[0]);
  261. bp_sys::close(pipefd[1]);
  262. return false;
  263. }
  264. base_process_service::base_process_service(service_set *sset, string name,
  265. service_type_t service_type_p, ha_string &&command,
  266. const std::list<std::pair<unsigned,unsigned>> &command_offsets,
  267. const std::list<prelim_dep> &deplist_p)
  268. : service_record(sset, name, service_type_p, deplist_p), child_listener(this),
  269. child_status_listener(this), process_timer(this), log_output_listener(this)
  270. {
  271. program_name = std::move(command);
  272. exec_arg_parts = separate_args(program_name, command_offsets);
  273. restart_interval_count = 0;
  274. restart_interval_time = {0, 0};
  275. process_timer.service = this;
  276. process_timer.add_timer(event_loop);
  277. // By default, allow a maximum of 3 restarts within 10.0 seconds:
  278. restart_interval.seconds() = 10;
  279. restart_interval.nseconds() = 0;
  280. max_restart_interval_count = 3;
  281. waiting_restart_timer = false;
  282. waiting_stopstart_timer = false;
  283. reserved_child_watch = false;
  284. tracking_child = false;
  285. }
  286. void base_process_service::do_restart() noexcept
  287. {
  288. // Actually perform process restart. We may be in smooth recovery (state = STARTED) or this may
  289. // be a regular restart.
  290. waiting_restart_timer = false;
  291. auto service_state = get_state();
  292. if (!start_ps_process(exec_arg_parts, have_console || onstart_flags.shares_console)) {
  293. if (service_state == service_state_t::STARTING) {
  294. failed_to_start();
  295. }
  296. else {
  297. // smooth recovery failure
  298. unrecoverable_stop();
  299. }
  300. services->process_queues();
  301. }
  302. else {
  303. // started process successfully (at least as far as fork)
  304. if (start_timeout != time_val(0,0)) {
  305. process_timer.arm_timer_rel(event_loop, start_timeout);
  306. waiting_stopstart_timer = true;
  307. }
  308. }
  309. }
  310. bool base_process_service::restart_ps_process() noexcept
  311. {
  312. using time_val = dasynq::time_val;
  313. time_val current_time;
  314. event_loop.get_time(current_time, clock_type::MONOTONIC);
  315. // Check if enough time has lapsed since the previous restart. If not, start a timer:
  316. time_val tdiff = current_time - last_start_time;
  317. if (restart_delay <= tdiff) {
  318. // > restart delay (normally 200ms)
  319. do_restart();
  320. }
  321. else {
  322. time_val timeout = restart_delay - tdiff;
  323. process_timer.arm_timer_rel(event_loop, timeout);
  324. waiting_restart_timer = true;
  325. }
  326. return true;
  327. }
  328. bool base_process_service::interrupt_start() noexcept
  329. {
  330. if (waiting_restart_timer) {
  331. process_timer.stop_timer(event_loop);
  332. waiting_restart_timer = false;
  333. return service_record::interrupt_start();
  334. }
  335. else {
  336. log(loglevel_t::WARN, "Interrupting start of service ", get_name(), " with pid ", pid,
  337. " (with SIGINT).");
  338. kill_pg(SIGINT);
  339. if (stop_timeout != time_val(0,0)) {
  340. process_timer.arm_timer_rel(event_loop, stop_timeout);
  341. waiting_stopstart_timer = true;
  342. }
  343. else if (waiting_stopstart_timer) {
  344. process_timer.stop_timer(event_loop);
  345. waiting_stopstart_timer = false;
  346. }
  347. set_state(service_state_t::STOPPING);
  348. return false;
  349. }
  350. }
  351. void base_process_service::kill_with_fire() noexcept
  352. {
  353. if (pid != -1) {
  354. log(loglevel_t::WARN, "Service ", get_name(), " with pid ", pid,
  355. " exceeded allowed stop time; killing.");
  356. kill_pg(SIGKILL);
  357. }
  358. }
  359. void base_process_service::kill_pg(int signo) noexcept
  360. {
  361. if (onstart_flags.signal_process_only) {
  362. bp_sys::kill(pid, signo);
  363. }
  364. else {
  365. pid_t pgid = bp_sys::getpgid(pid);
  366. if (pgid == -1) {
  367. // On some OSes (eg OpenBSD) we aren't allowed to get the pgid of a process in a different
  368. // session. If the process is in a different session, however, it must be a process group
  369. // leader and the pgid must equal the process id.
  370. pgid = pid;
  371. }
  372. bp_sys::kill(-pgid, signo);
  373. }
  374. }
  375. void base_process_service::timer_expired() noexcept
  376. {
  377. waiting_stopstart_timer = false;
  378. // Timer expires if:
  379. // We are stopping, including after having startup cancelled (stop timeout, state is STOPPING); We are
  380. // starting (start timeout, state is STARTING); We are waiting for restart timer before restarting,
  381. // including smooth recovery (restart timeout, state is STARTING or STARTED).
  382. if (get_state() == service_state_t::STOPPING) {
  383. kill_with_fire();
  384. }
  385. else if (pid != -1) {
  386. // Starting, start timed out.
  387. log(loglevel_t::WARN, "Service ", get_name(), " with pid ", pid,
  388. " exceeded allowed start time; cancelling.");
  389. interrupt_start();
  390. stop_reason = stopped_reason_t::TIMEDOUT;
  391. failed_to_start(false, false);
  392. }
  393. else {
  394. // STARTING / STARTED, and we have no pid: must be restarting (smooth recovery if STARTED)
  395. do_restart();
  396. }
  397. }
  398. void base_process_service::becoming_inactive() noexcept
  399. {
  400. if (socket_fd != -1) {
  401. close(socket_fd);
  402. socket_fd = -1;
  403. }
  404. }
  405. bool base_process_service::open_socket() noexcept
  406. {
  407. if (socket_path.empty() || socket_fd != -1) {
  408. // No socket, or already open
  409. return true;
  410. }
  411. const char * saddrname = socket_path.c_str();
  412. // Check the specified socket path
  413. struct stat stat_buf;
  414. if (stat(saddrname, &stat_buf) == 0) {
  415. if ((stat_buf.st_mode & S_IFSOCK) == 0) {
  416. // Not a socket
  417. log(loglevel_t::ERROR, get_name(), ": activation socket file exists (and is not a socket)");
  418. return false;
  419. }
  420. }
  421. else if (errno != ENOENT) {
  422. // Other error
  423. log(loglevel_t::ERROR, get_name(), ": error checking activation socket: ", strerror(errno));
  424. return false;
  425. }
  426. // Remove stale socket file (if it exists).
  427. // We won't test the return from unlink - if it fails other than due to ENOENT, we should get an
  428. // error when we try to create the socket anyway.
  429. unlink(saddrname);
  430. uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
  431. struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
  432. if (name == nullptr) {
  433. log(loglevel_t::ERROR, get_name(), ": opening activation socket: out of memory");
  434. return false;
  435. }
  436. name->sun_family = AF_UNIX;
  437. strcpy(name->sun_path, saddrname);
  438. int sockfd = dinit_socket(AF_UNIX, SOCK_STREAM, 0, SOCK_NONBLOCK | SOCK_CLOEXEC);
  439. if (sockfd == -1) {
  440. log(loglevel_t::ERROR, get_name(), ": error creating activation socket: ", strerror(errno));
  441. free(name);
  442. return false;
  443. }
  444. if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
  445. log(loglevel_t::ERROR, get_name(), ": error binding activation socket: ", strerror(errno));
  446. close(sockfd);
  447. free(name);
  448. return false;
  449. }
  450. free(name);
  451. // POSIX (1003.1, 2013) says that fchown and fchmod don't necessarily work on sockets. We have to
  452. // use chown and chmod instead.
  453. if (chown(saddrname, socket_uid, socket_gid)) {
  454. log(loglevel_t::ERROR, get_name(), ": error setting activation socket owner/group: ",
  455. strerror(errno));
  456. close(sockfd);
  457. return false;
  458. }
  459. if (chmod(saddrname, socket_perms) == -1) {
  460. log(loglevel_t::ERROR, get_name(), ": Error setting activation socket permissions: ",
  461. strerror(errno));
  462. close(sockfd);
  463. return false;
  464. }
  465. if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
  466. log(loglevel_t::ERROR, ": error listening on activation socket: ", strerror(errno));
  467. close(sockfd);
  468. return false;
  469. }
  470. socket_fd = sockfd;
  471. return true;
  472. }
  473. bool base_process_service::ensure_log_buffer_backing(unsigned new_size) noexcept
  474. {
  475. // Note: we manage capacity manually to avoid it exceeding maximum
  476. if (log_buffer.size() < new_size) {
  477. if (log_buffer.capacity() < new_size) {
  478. try {
  479. unsigned new_capacity = std::max((unsigned)log_buffer.capacity() * 2, new_size);
  480. new_capacity = std::min(new_capacity, log_buf_max);
  481. log_buffer.reserve(new_capacity);
  482. log_buffer.resize(new_capacity);
  483. }
  484. catch (std::bad_alloc &badalloc) {
  485. log(loglevel_t::WARN, get_name(), ": cannot increase log buffer; out-of-memory");
  486. return false;
  487. }
  488. }
  489. else {
  490. log_buffer.resize(new_size);
  491. }
  492. }
  493. return true;
  494. }