service.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. #include <cstring>
  2. #include <cerrno>
  3. #include <sstream>
  4. #include <iterator>
  5. #include <memory>
  6. #include <cstddef>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <sys/ioctl.h>
  10. #include <sys/un.h>
  11. #include <sys/socket.h>
  12. #include <fcntl.h>
  13. #include <unistd.h>
  14. #include <termios.h>
  15. #include "service.h"
  16. #include "dinit-log.h"
  17. // from dinit.cc:
  18. void open_control_socket(struct ev_loop *loop) noexcept;
  19. // Find the requested service by name
  20. static ServiceRecord * findService(const std::list<ServiceRecord *> & records,
  21. const char *name) noexcept
  22. {
  23. using std::list;
  24. list<ServiceRecord *>::const_iterator i = records.begin();
  25. for ( ; i != records.end(); i++ ) {
  26. if (strcmp((*i)->getServiceName(), name) == 0) {
  27. return *i;
  28. }
  29. }
  30. return (ServiceRecord *)0;
  31. }
  32. ServiceRecord * ServiceSet::findService(const std::string &name) noexcept
  33. {
  34. return ::findService(records, name.c_str());
  35. }
  36. void ServiceSet::startService(const char *name)
  37. {
  38. using namespace std;
  39. ServiceRecord *record = loadServiceRecord(name);
  40. record->start();
  41. }
  42. void ServiceSet::stopService(const std::string & name) noexcept
  43. {
  44. ServiceRecord *record = findService(name);
  45. if (record != nullptr) {
  46. record->stop();
  47. }
  48. }
  49. // Called when a service has actually stopped.
  50. void ServiceRecord::stopped() noexcept
  51. {
  52. if (service_type != ServiceType::SCRIPTED && service_type != ServiceType::BGPROCESS && onstart_flags.runs_on_console) {
  53. tcsetpgrp(0, getpgrp());
  54. releaseConsole();
  55. }
  56. logServiceStopped(service_name);
  57. service_state = ServiceState::STOPPED;
  58. force_stop = false;
  59. // Stop any dependencies whose desired state is STOPPED:
  60. for (sr_iter i = depends_on.begin(); i != depends_on.end(); i++) {
  61. (*i)->dependentStopped();
  62. }
  63. service_set->service_inactive(this);
  64. notifyListeners(ServiceEvent::STOPPED);
  65. if (desired_state == ServiceState::STARTED) {
  66. // Desired state is "started".
  67. start();
  68. }
  69. else if (socket_fd != -1) {
  70. close(socket_fd);
  71. socket_fd = -1;
  72. }
  73. }
  74. void ServiceRecord::process_child_callback(struct ev_loop *loop, ev_child *w, int revents) noexcept
  75. {
  76. ServiceRecord *sr = (ServiceRecord *) w->data;
  77. sr->pid = -1;
  78. sr->exit_status = w->rstatus;
  79. ev_child_stop(loop, w);
  80. // Ok, for a process service, any process death which we didn't rig
  81. // ourselves is a bit... unexpected. Probably, the child died because
  82. // we asked it to (sr->service_state == STOPPING). But even if
  83. // we didn't, there's not much we can do.
  84. if (sr->waiting_for_execstat) {
  85. // We still don't have an exec() status from the forked child, wait for that
  86. // before doing any further processing.
  87. return;
  88. }
  89. sr->handle_exit_status();
  90. }
  91. void ServiceRecord::handle_exit_status() noexcept
  92. {
  93. if (exit_status != 0 && service_state != ServiceState::STOPPING) {
  94. log(LogLevel::ERROR, "Service ", service_name, " process terminated with exit code ", exit_status);
  95. }
  96. if (doing_recovery) {
  97. // (BGPROCESS only)
  98. doing_recovery = false;
  99. bool do_stop = false;
  100. if (exit_status != 0) {
  101. do_stop = true;
  102. }
  103. else {
  104. // We need to re-read the PID, since it has now changed.
  105. if (service_type == ServiceType::BGPROCESS && pid_file.length() != 0) {
  106. if (! read_pid_file()) {
  107. do_stop = true;
  108. }
  109. }
  110. }
  111. if (do_stop) {
  112. stop();
  113. if (auto_restart && service_set->get_auto_restart()) {
  114. start();
  115. }
  116. }
  117. return;
  118. }
  119. if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS) {
  120. if (service_state == ServiceState::STARTING) {
  121. // (only applies to BGPROCESS)
  122. if (exit_status == 0) {
  123. started();
  124. }
  125. else {
  126. failed_to_start();
  127. }
  128. }
  129. else if (service_state == ServiceState::STOPPING) {
  130. // TODO log non-zero rstatus?
  131. stopped();
  132. }
  133. else if (smooth_recovery && service_state == ServiceState::STARTED) {
  134. // TODO ensure a minimum time between restarts
  135. // TODO if we are pinned-started then we should probably check
  136. // that dependencies have started before trying to re-start the
  137. // service process.
  138. doing_recovery = (service_type == ServiceType::BGPROCESS);
  139. start_ps_process();
  140. return;
  141. }
  142. else {
  143. forceStop();
  144. }
  145. if (auto_restart && service_set->get_auto_restart()) {
  146. start();
  147. }
  148. }
  149. else { // SCRIPTED
  150. if (service_state == ServiceState::STOPPING) {
  151. if (exit_status == 0) {
  152. stopped();
  153. }
  154. else {
  155. // ??? failed to stop! Let's log it as info:
  156. log(LogLevel::INFO, "service ", service_name, " stop command failed with exit code ", exit_status);
  157. // Just assume that we stopped, so that any dependencies
  158. // can be stopped:
  159. stopped();
  160. }
  161. }
  162. else { // STARTING
  163. if (exit_status == 0) {
  164. started();
  165. }
  166. else {
  167. // failed to start
  168. log(LogLevel::ERROR, "service ", service_name, " command failed with exit code ", exit_status);
  169. failed_to_start();
  170. }
  171. }
  172. }
  173. }
  174. void ServiceRecord::process_child_status(struct ev_loop *loop, ev_io * stat_io, int revents) noexcept
  175. {
  176. ServiceRecord *sr = (ServiceRecord *) stat_io->data;
  177. sr->waiting_for_execstat = false;
  178. int exec_status;
  179. int r = read(stat_io->fd, &exec_status, sizeof(int));
  180. close(stat_io->fd);
  181. ev_io_stop(loop, stat_io);
  182. if (r != 0) {
  183. // We read an errno code; exec() failed, and the service startup failed.
  184. sr->pid = -1;
  185. log(LogLevel::ERROR, sr->service_name, ": execution failed: ", strerror(exec_status));
  186. if (sr->service_state == ServiceState::STARTING) {
  187. sr->failed_to_start();
  188. }
  189. else if (sr->service_state == ServiceState::STOPPING) {
  190. // Must be a scripted servce. We've logged the failure, but it's probably better
  191. // not to leave the service in STARTED state:
  192. sr->stopped();
  193. }
  194. }
  195. else {
  196. // exec() succeeded.
  197. if (sr->service_type == ServiceType::PROCESS) {
  198. if (sr->service_state != ServiceState::STARTED) {
  199. sr->started();
  200. }
  201. }
  202. if (sr->pid == -1) {
  203. // Somehow the process managed to complete before we even saw the status.
  204. sr->handle_exit_status();
  205. }
  206. }
  207. }
  208. void ServiceRecord::start() noexcept
  209. {
  210. if ((service_state == ServiceState::STARTING || service_state == ServiceState::STARTED)
  211. && desired_state == ServiceState::STOPPED) {
  212. // This service was starting, or started, but was set to be stopped.
  213. // Cancel the stop (and continue starting/running).
  214. notifyListeners(ServiceEvent::STOPCANCELLED);
  215. }
  216. if (desired_state == ServiceState::STARTED && service_state != ServiceState::STOPPED) return;
  217. desired_state = ServiceState::STARTED;
  218. if (pinned_stopped) return;
  219. if (service_state != ServiceState::STOPPED) {
  220. // We're already starting/started, or we are stopping and need to wait for
  221. // that the complete.
  222. if (service_state != ServiceState::STOPPING || ! can_interrupt_stop()) {
  223. return;
  224. }
  225. // We're STOPPING, and that can be interrupted. Our dependencies might be STOPPING,
  226. // but if so they are waiting (for us), so they too can be instantly returned to
  227. // STARTING state.
  228. }
  229. service_state = ServiceState::STARTING;
  230. service_set->service_active(this);
  231. waiting_for_deps = true;
  232. // Ask dependencies to start, mark them as being waited on.
  233. if (! startCheckDependencies(true)) {
  234. return;
  235. }
  236. // Actually start this service.
  237. allDepsStarted();
  238. }
  239. void ServiceRecord::dependencyStarted() noexcept
  240. {
  241. if (service_state != ServiceState::STARTING || ! waiting_for_deps) {
  242. return;
  243. }
  244. if (startCheckDependencies(false)) {
  245. allDepsStarted();
  246. }
  247. }
  248. bool ServiceRecord::startCheckDependencies(bool start_deps) noexcept
  249. {
  250. bool all_deps_started = true;
  251. for (sr_iter i = depends_on.begin(); i != depends_on.end(); ++i) {
  252. if ((*i)->service_state != ServiceState::STARTED) {
  253. if (start_deps) {
  254. all_deps_started = false;
  255. (*i)->start();
  256. }
  257. else {
  258. return false;
  259. }
  260. }
  261. }
  262. for (auto i = soft_deps.begin(); i != soft_deps.end(); ++i) {
  263. ServiceRecord * to = i->getTo();
  264. if (start_deps) {
  265. if (to->service_state != ServiceState::STARTED) {
  266. to->start();
  267. i->waiting_on = true;
  268. all_deps_started = false;
  269. }
  270. else {
  271. i->waiting_on = false;
  272. }
  273. }
  274. else if (i->waiting_on) {
  275. if (to->service_state != ServiceState::STARTING) {
  276. // Service has either started or is no longer starting
  277. i->waiting_on = false;
  278. }
  279. else {
  280. // We are still waiting on this service
  281. return false;
  282. }
  283. }
  284. }
  285. return all_deps_started;
  286. }
  287. bool ServiceRecord::open_socket() noexcept
  288. {
  289. if (socket_path.empty() || socket_fd != -1) {
  290. // No socket, or already open
  291. return true;
  292. }
  293. const char * saddrname = socket_path.c_str();
  294. uint sockaddr_size = offsetof(struct sockaddr_un, sun_path) + socket_path.length() + 1;
  295. struct sockaddr_un * name = static_cast<sockaddr_un *>(malloc(sockaddr_size));
  296. if (name == nullptr) {
  297. log(LogLevel::ERROR, service_name, ": Opening activation socket: out of memory");
  298. return false;
  299. }
  300. // Un-link any stale socket. TODO: safety check? should at least confirm the path is a socket.
  301. unlink(saddrname);
  302. name->sun_family = AF_UNIX;
  303. strcpy(name->sun_path, saddrname);
  304. int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
  305. if (sockfd == -1) {
  306. log(LogLevel::ERROR, service_name, ": Error creating activation socket: ", strerror(errno));
  307. free(name);
  308. return false;
  309. }
  310. if (bind(sockfd, (struct sockaddr *) name, sockaddr_size) == -1) {
  311. log(LogLevel::ERROR, service_name, ": Error binding activation socket: ", strerror(errno));
  312. close(sockfd);
  313. free(name);
  314. return false;
  315. }
  316. free(name);
  317. // POSIX (1003.1, 2013) says that fchown and fchmod don't necesarily work on sockets. We have to
  318. // use chown and chmod instead.
  319. if (chown(saddrname, socket_uid, socket_gid)) {
  320. log(LogLevel::ERROR, service_name, ": Error setting activation socket owner/group: ", strerror(errno));
  321. close(sockfd);
  322. return false;
  323. }
  324. if (chmod(saddrname, socket_perms) == -1) {
  325. log(LogLevel::ERROR, service_name, ": Error setting activation socket permissions: ", strerror(errno));
  326. close(sockfd);
  327. return false;
  328. }
  329. if (listen(sockfd, 128) == -1) { // 128 "seems reasonable".
  330. log(LogLevel::ERROR, ": Error listening on activation socket: ", strerror(errno));
  331. close(sockfd);
  332. return false;
  333. }
  334. socket_fd = sockfd;
  335. return true;
  336. }
  337. void ServiceRecord::allDepsStarted(bool has_console) noexcept
  338. {
  339. if (onstart_flags.runs_on_console && ! has_console) {
  340. waiting_for_deps = true;
  341. queueForConsole();
  342. return;
  343. }
  344. waiting_for_deps = false;
  345. if (! open_socket()) {
  346. failed_to_start();
  347. }
  348. if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS
  349. || service_type == ServiceType::SCRIPTED) {
  350. bool start_success = start_ps_process();
  351. if (! start_success) {
  352. failed_to_start();
  353. }
  354. }
  355. else {
  356. // "internal" service
  357. started();
  358. }
  359. }
  360. void ServiceRecord::acquiredConsole() noexcept
  361. {
  362. if (service_state != ServiceState::STARTING) {
  363. // We got the console but no longer want it.
  364. releaseConsole();
  365. }
  366. else if (startCheckDependencies(false)) {
  367. log_to_console = false;
  368. allDepsStarted(true);
  369. }
  370. else {
  371. // We got the console but can't use it yet.
  372. releaseConsole();
  373. }
  374. }
  375. bool ServiceRecord::read_pid_file() noexcept
  376. {
  377. const char *pid_file_c = pid_file.c_str();
  378. int fd = open(pid_file_c, O_CLOEXEC);
  379. if (fd != -1) {
  380. char pidbuf[21]; // just enought to hold any 64-bit integer
  381. int r = read(fd, pidbuf, 20);
  382. if (r > 0) {
  383. pidbuf[r] = 0; // store nul terminator
  384. pid = std::atoi(pidbuf);
  385. if (kill(pid, 0) == 0) {
  386. ev_child_init(&child_listener, process_child_callback, pid, 0);
  387. child_listener.data = this;
  388. ev_child_start(ev_default_loop(EVFLAG_AUTO), &child_listener);
  389. }
  390. else {
  391. log(LogLevel::ERROR, service_name, ": pid read from pidfile (", pid, ") is not valid");
  392. pid = -1;
  393. close(fd);
  394. return false;
  395. }
  396. }
  397. close(fd);
  398. return true;
  399. }
  400. else {
  401. log(LogLevel::ERROR, service_name, ": read pid file: ", strerror(errno));
  402. return false;
  403. }
  404. }
  405. void ServiceRecord::started() noexcept
  406. {
  407. if (onstart_flags.runs_on_console && (service_type == ServiceType::SCRIPTED || service_type == ServiceType::BGPROCESS)) {
  408. tcsetpgrp(0, getpgrp());
  409. releaseConsole();
  410. }
  411. if (service_type == ServiceType::BGPROCESS && pid_file.length() != 0) {
  412. if (! read_pid_file()) {
  413. failed_to_start();
  414. return;
  415. }
  416. }
  417. logServiceStarted(service_name);
  418. service_state = ServiceState::STARTED;
  419. notifyListeners(ServiceEvent::STARTED);
  420. if (onstart_flags.rw_ready) {
  421. open_control_socket(ev_default_loop(EVFLAG_AUTO));
  422. }
  423. if (force_stop || desired_state == ServiceState::STOPPED) {
  424. // We must now stop.
  425. bool do_restart = (desired_state != ServiceState::STOPPED);
  426. stop();
  427. if (do_restart) {
  428. start();
  429. }
  430. return;
  431. }
  432. // Notify any dependents whose desired state is STARTED:
  433. for (auto i = dependents.begin(); i != dependents.end(); i++) {
  434. (*i)->dependencyStarted();
  435. }
  436. for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
  437. (*i)->getFrom()->dependencyStarted();
  438. }
  439. }
  440. void ServiceRecord::failed_to_start()
  441. {
  442. if (onstart_flags.runs_on_console) {
  443. tcsetpgrp(0, getpgrp());
  444. releaseConsole();
  445. }
  446. logServiceFailed(service_name);
  447. service_state = ServiceState::STOPPED;
  448. desired_state = ServiceState::STOPPED;
  449. service_set->service_inactive(this);
  450. notifyListeners(ServiceEvent::FAILEDSTART);
  451. // failure to start
  452. // Cancel start of dependents:
  453. for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
  454. if ((*i)->service_state == ServiceState::STARTING) {
  455. (*i)->failed_dependency();
  456. }
  457. }
  458. for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
  459. // We can send 'start', because this is only a soft dependency.
  460. // Our startup failure means that they don't have to wait for us.
  461. (*i)->getFrom()->dependencyStarted();
  462. }
  463. }
  464. bool ServiceRecord::start_ps_process() noexcept
  465. {
  466. return start_ps_process(exec_arg_parts, onstart_flags.runs_on_console);
  467. }
  468. bool ServiceRecord::start_ps_process(const std::vector<const char *> &cmd, bool on_console) noexcept
  469. {
  470. // In general, you can't tell whether fork/exec is successful. We use a pipe to communicate
  471. // success/failure from the child to the parent. The pipe is set CLOEXEC so a successful
  472. // exec closes the pipe, and the parent sees EOF. If the exec is unsuccessful, the errno
  473. // is written to the pipe, and the parent can read it.
  474. int pipefd[2];
  475. if (pipe2(pipefd, O_CLOEXEC)) {
  476. // TODO log error
  477. return false;
  478. }
  479. // Set up the argument array and other data now (before fork), in case memory allocation fails.
  480. auto args = cmd.data();
  481. const char * logfile = this->logfile.c_str();
  482. if (*logfile == 0) {
  483. logfile = "/dev/null";
  484. }
  485. // TODO make sure pipefd's are not 0/1/2 (STDIN/OUT/ERR) - if they are, dup them
  486. // until they are not.
  487. pid_t forkpid = fork();
  488. if (forkpid == -1) {
  489. // TODO log error
  490. close(pipefd[0]);
  491. close(pipefd[1]);
  492. return false;
  493. }
  494. // If the console already has a session leader, presumably it is us. On the other hand
  495. // if it has no session leader, and we don't create one, then control inputs such as
  496. // ^C will have no effect.
  497. bool do_set_ctty = (tcgetsid(0) == -1);
  498. if (forkpid == 0) {
  499. // Child process. Must not allocate memory (or otherwise risk throwing any exception)
  500. // from here until exit().
  501. ev_default_destroy(); // won't need that on this side, free up fds.
  502. constexpr int bufsz = ((CHAR_BIT * sizeof(pid_t) - 1) / 3 + 2) + 11;
  503. // "LISTEN_PID=" - 11 characters
  504. char nbuf[bufsz];
  505. if (socket_fd != -1) {
  506. dup2(socket_fd, 3);
  507. if (socket_fd != 3) {
  508. close(socket_fd);
  509. }
  510. if (putenv(const_cast<char *>("LISTEN_FDS=1"))) goto failure_out;
  511. snprintf(nbuf, bufsz, "LISTEN_PID=%jd", static_cast<intmax_t>(getpid()));
  512. if (putenv(nbuf)) goto failure_out;
  513. }
  514. if (! on_console) {
  515. // Re-set stdin, stdout, stderr
  516. close(0); close(1); close(2);
  517. // TODO rethink this logic. If we open it at not-0, shouldn't we just dup it to 0?:
  518. if (open("/dev/null", O_RDONLY) == 0) {
  519. // stdin = 0. That's what we should have; proceed with opening
  520. // stdout and stderr.
  521. open(logfile, O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
  522. dup2(1, 2);
  523. }
  524. }
  525. else {
  526. // "run on console" - run as a foreground job on the terminal/console device
  527. if (do_set_ctty) {
  528. setsid();
  529. ioctl(0, TIOCSCTTY, 0);
  530. }
  531. setpgid(0,0);
  532. tcsetpgrp(0, getpgrp());
  533. // TODO disable suspend (^Z)? (via tcsetattr)
  534. // (should be done before TIOCSCTTY)
  535. }
  536. execvp(exec_arg_parts[0], const_cast<char **>(args));
  537. // If we got here, the exec failed:
  538. failure_out:
  539. int exec_status = errno;
  540. write(pipefd[1], &exec_status, sizeof(int));
  541. exit(0);
  542. }
  543. else {
  544. // Parent process
  545. close(pipefd[1]); // close the 'other end' fd
  546. pid = forkpid;
  547. // Listen for status
  548. ev_io_init(&child_status_listener, process_child_status, pipefd[0], EV_READ);
  549. child_status_listener.data = this;
  550. ev_io_start(ev_default_loop(EVFLAG_AUTO), &child_status_listener);
  551. // Add a process listener so we can detect when the
  552. // service stops
  553. ev_child_init(&child_listener, process_child_callback, pid, 0);
  554. child_listener.data = this;
  555. ev_child_start(ev_default_loop(EVFLAG_AUTO), &child_listener);
  556. waiting_for_execstat = true;
  557. return true;
  558. }
  559. }
  560. // Mark this and all dependent services as force-stopped.
  561. void ServiceRecord::forceStop() noexcept
  562. {
  563. if (service_state != ServiceState::STOPPED) {
  564. force_stop = true;
  565. for (sr_iter i = dependents.begin(); i != dependents.end(); i++) {
  566. (*i)->forceStop();
  567. }
  568. stop();
  569. // We don't want to force stop soft dependencies, however.
  570. }
  571. }
  572. // A dependency of this service failed to start.
  573. // Only called when state == STARTING.
  574. void ServiceRecord::failed_dependency()
  575. {
  576. desired_state = ServiceState::STOPPED;
  577. // Presumably, we were starting. So now we're not.
  578. service_state = ServiceState::STOPPED;
  579. service_set->service_inactive(this);
  580. logServiceFailed(service_name);
  581. // Notify dependents of this service also
  582. for (auto i = dependents.begin(); i != dependents.end(); i++) {
  583. if ((*i)->service_state == ServiceState::STARTING) {
  584. (*i)->failed_dependency();
  585. }
  586. }
  587. for (auto i = soft_dpts.begin(); i != soft_dpts.end(); i++) {
  588. // It's a soft dependency, so send them 'started' rather than
  589. // 'failed dep'.
  590. (*i)->getFrom()->dependencyStarted();
  591. }
  592. }
  593. void ServiceRecord::dependentStopped() noexcept
  594. {
  595. if (service_state == ServiceState::STOPPING) {
  596. // Check the other dependents before we stop.
  597. if (stopCheckDependents()) {
  598. allDepsStopped();
  599. }
  600. }
  601. }
  602. void ServiceRecord::stop() noexcept
  603. {
  604. if ((service_state == ServiceState::STOPPING || service_state == ServiceState::STOPPED)
  605. && desired_state == ServiceState::STARTED) {
  606. // The service *was* stopped/stopping, but it was going to restart.
  607. // Now, we'll cancel the restart.
  608. notifyListeners(ServiceEvent::STARTCANCELLED);
  609. }
  610. if (desired_state == ServiceState::STOPPED && service_state != ServiceState::STARTED) return;
  611. desired_state = ServiceState::STOPPED;
  612. if (pinned_started) return;
  613. if (service_state != ServiceState::STARTED) {
  614. if (service_state == ServiceState::STARTING) {
  615. if (! can_interrupt_start()) {
  616. // Well this is awkward: we're going to have to continue
  617. // starting, but we don't want any dependents to think that
  618. // they are still waiting to start.
  619. // Make sure they remain stopped:
  620. stopDependents();
  621. return;
  622. }
  623. // Reaching this point, we have can_interrupt_start() == true. So,
  624. // we can stop. Dependents might be starting, but they must be
  625. // waiting on us, so they should also be immediately stoppable.
  626. // Fall through to below.
  627. }
  628. else {
  629. // If we're starting we need to wait for that to complete.
  630. // If we're already stopping/stopped there's nothing to do.
  631. return;
  632. }
  633. }
  634. service_state = ServiceState::STOPPING;
  635. waiting_for_deps = true;
  636. // If we get here, we are in STARTED state; stop all dependents.
  637. if (stopDependents()) {
  638. allDepsStopped();
  639. }
  640. }
  641. bool ServiceRecord::stopCheckDependents() noexcept
  642. {
  643. bool all_deps_stopped = true;
  644. for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
  645. if ((*i)->service_state != ServiceState::STOPPED) {
  646. all_deps_stopped = false;
  647. break;
  648. }
  649. }
  650. return all_deps_stopped;
  651. }
  652. bool ServiceRecord::stopDependents() noexcept
  653. {
  654. bool all_deps_stopped = true;
  655. for (sr_iter i = dependents.begin(); i != dependents.end(); ++i) {
  656. if ((*i)->service_state != ServiceState::STOPPED) {
  657. all_deps_stopped = false;
  658. (*i)->stop();
  659. }
  660. }
  661. return all_deps_stopped;
  662. }
  663. // Dependency stopped or is stopping; we must stop too.
  664. void ServiceRecord::allDepsStopped()
  665. {
  666. waiting_for_deps = false;
  667. if (service_type == ServiceType::PROCESS || service_type == ServiceType::BGPROCESS) {
  668. if (pid != -1) {
  669. // The process is still kicking on - must actually kill it.
  670. if (! onstart_flags.no_sigterm) {
  671. kill(pid, SIGTERM);
  672. }
  673. if (term_signal != -1) {
  674. kill(pid, term_signal);
  675. }
  676. // Now we wait; the rest is done in process_child_callback
  677. }
  678. else {
  679. // The process is already dead.
  680. stopped();
  681. }
  682. }
  683. else if (service_type == ServiceType::SCRIPTED) {
  684. // Scripted service.
  685. if (stop_command.length() == 0) {
  686. stopped();
  687. }
  688. else if (! start_ps_process(stop_arg_parts, false)) {
  689. // Couldn't execute stop script, but there's not much we can do:
  690. stopped();
  691. }
  692. }
  693. else {
  694. stopped();
  695. }
  696. }
  697. void ServiceRecord::pinStart() noexcept
  698. {
  699. start();
  700. pinned_started = true;
  701. }
  702. void ServiceRecord::pinStop() noexcept
  703. {
  704. stop();
  705. pinned_stopped = true;
  706. }
  707. void ServiceRecord::unpin() noexcept
  708. {
  709. if (pinned_started) {
  710. pinned_started = false;
  711. if (desired_state == ServiceState::STOPPED) {
  712. stop();
  713. }
  714. }
  715. if (pinned_stopped) {
  716. pinned_stopped = false;
  717. if (desired_state == ServiceState::STARTED) {
  718. start();
  719. }
  720. }
  721. }
  722. void ServiceRecord::queueForConsole() noexcept
  723. {
  724. next_for_console = nullptr;
  725. auto tail = service_set->consoleQueueTail(this);
  726. if (tail == nullptr) {
  727. acquiredConsole();
  728. }
  729. else {
  730. tail->next_for_console = this;
  731. }
  732. }
  733. void ServiceRecord::releaseConsole() noexcept
  734. {
  735. log_to_console = true;
  736. if (next_for_console != nullptr) {
  737. next_for_console->acquiredConsole();
  738. }
  739. else {
  740. service_set->consoleQueueTail(nullptr);
  741. }
  742. }
  743. void ServiceSet::service_active(ServiceRecord *sr) noexcept
  744. {
  745. active_services++;
  746. }
  747. void ServiceSet::service_inactive(ServiceRecord *sr) noexcept
  748. {
  749. active_services--;
  750. }