baseproc-service.cc 16 KB

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