baseproc-service.cc 18 KB

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